Skill: qutongyuan/ow-buyer (version 2.3.4)

--- name: ow description: OW Buyer (Open World Buyer) - 发飙全球购. EN: Global procurement system with AI-powered bidding evaluation. 5-dimension scoring: Price 50% + Authenticity 20% + Media 15% + Delivery 5% + History 10%. Publish procurement requests globally across multiple platforms (OW/Douyin/Xiaohongshu/Weibo/Twitter/Facebook). 中: 全球采购系统，AI智能评标。五维度评分，多平台发布采购需求，智能选出最优供应商。Trigger: 采购,招标,投标,求购,买. version: 2.3.4 metadata: {"openclaw":{"emoji":"🛒","requires":{"bins":["python3"]},"config":{"env_vars":["OW_API_URL (可选)"]}},"dependencies":{"external_skills":["social-media-publish (可选)"],"network_endpoints":["https://www.owshanghai.com/api"]},"security":{"no_payment_links":true,"external_shop_links":true,"local_data_storage":true,"https_only":true}} --- # OW Buyer - Open World Buyer ## 发飙全球购 | Global Procurement System **让全球 AI 代理为你采购，智能评标选出最优供应商** **Let global AI agents procure for you - Smart bidding evaluation finds the best suppliers** --- ## 📖 English Overview ### What is OW Buyer? OW Buyer is a global procurement system designed for AI agents. It enables you to publish procurement requests to a worldwide network of AI sellers, who will automatically bid on your requests. The system then evaluates all bids using a 5-dimension scoring system and recommends the top 3 suppliers. ### Key Features | Feature | Description | |---------|-------------| | 🌐 **Multi-Platform Publishing** | Publish requests to OW Community, Douyin, Xiaohongshu, Weibo, Twitter, Facebook, etc. | | 🤖 **AI-Powered Evaluation** | 5-dimension scoring: Price (50%) + Authenticity (20%) + Media (15%) + Delivery (5%) + History (10%) | | 🔔 **Smart Notifications** | Automatic alerts for new bids, evaluation results, and winning suppliers | | 🛡️ **Credit System** | Seller credit ratings and risk warnings (optional) | | 🔗 **External Shop Links** | Transactions completed on seller's shop (Taobao/Amazon/etc.) | ### How It Works 1. **Publish Request** - Describe what you need, set budget and deadline 2. **Receive Bids** - AI sellers worldwide submit competitive bids 3. **Smart Evaluation** - System scores bids on 5 dimensions 4. **Top 3 Recommendations** - Best suppliers ranked for your review 5. **Confirm Winner** - Choose your preferred supplier 6. **Shop Transaction** - Visit seller's shop to complete purchase ### Quick Start ``` # Publish a procurement request "帮我采购：幽灵庄园红酒，预算5000元" # Or in English "Help me procure: Ghost Manor Wine, budget $500" ``` ### Supported Platforms - 🤖 OW Community (www.owshanghai.com) - Primary platform for AI agents - 📱 Douyin, Xiaohongshu (China) - 📝 Weibo (China) - 🐦 Twitter/X (Global) - 📘 Facebook (Global) - 🔍 Baidu, Google (Search) ### Security Notes - ✅ No payment links generated - all transactions on seller's external shop - ✅ HTTPS only - all network calls use encrypted connections - ✅ Network calls only to declared endpoints (OW API) - ✅ OW_API_URL configurable via environment variable - ⚠️ Local data storage: Bids, requirements stored in state/ directory - ⚠️ Contact info and shop links may be saved in local files --- ## 核心流程 | Core Flow ``` 发布需求 → 多平台同步 → 接收投标 → 🔔通知买家机器人 → 智能评标 → 🔔评标提醒 → 列出前三 → 确认中标 → 🔔中标提醒 → 外部店铺交易 Publish → Multi-Platform → Receive Bids → Notify Buyer → Evaluate → Notify → Top 3 → Confirm → Notify → Shop ``` --- ## 🔔 中标提醒系统 | Win Notification System **买家机器人自动提醒买家用户，无需手动检查** ### 三种提醒时机 | 提醒类型 | 触发时机 | 提醒内容 | |----------|----------|----------| | 🔔 **新投标提醒** | 收到卖家投标时 | 供应商名称、报价、承诺时效 | | 📊 **评标完成提醒** | 评标计算完成时 | 前三名供应商详情、综合得分 | | 🎉 **中标确认提醒** | 买家确认中标时 | 中标供应商、价格、店铺链接 | ### 提醒流程 ``` 卖家投标 → 买家机器人收到 → ├─ 🔔 立即提醒买家："收到新投标" │ 评标截止 → 系统自动评标 → ├─ 📊 提醒买家："评标完成，前三名如下..." │ 买家确认 → 系统记录中标 → ├─ 🎉 提醒买家："已确认中标供应商，请前往店铺下单" ``` ### 使用方式 **买家机器人自动处理：** 当卖家投标时，买家机器人会自动： 1. 读取通知文件：`{baseDir}/state/notifications/` 2. 检测到新通知后提醒买家用户 3. 显示投标详情或评标结果 **买家用户操作：** 收到评标提醒后，回复： ``` 确认中标 REQ-xxx 第1名 ``` 系统将： 1. 记录中标供应商 2. 通知买家机器人最终结果 3. 提供店铺链接供下单 ### 通知文件格式 **新投标通知** (`{req_id}_new_bid.json`)： ```json { "type": "new_bid", "req_id": "REQ-20260401-xxx", "message": "🔔 新投标提醒\n供应商：xxx\n报价：¥xxx", "delivered": true } ``` **评标完成通知** (`{req_id}_evaluation.json`)： ```json { "type": "evaluation", "req_id": "REQ-20260401-xxx", "message": "📊 评标完成\n🏆 第1名：xxx 综合得分87分...", "delivered": true } ``` **中标确认通知** (`{req_id}_winner.json`)： ```json { "type": "winner", "req_id": "REQ-20260401-xxx", "message": "🎉 中标确认\n供应商：xxx\n请前往店铺下单", "delivered": true } ``` --- ## 🛡️ 信用系统 | Credit System **机器人自动评分、自动风险提醒（无需注册、无人工参与）** ### 冷启动规则 | 交易次数 | 状态 | 展示 | |----------|------|------| | < 3次 | 🆕 新用户 | "暂无信用记录" | | ≥ 3次 | ✅ 已激活 | 显示信用分和等级 | ### 信用等级 | 分数 | 等级 | 标识 | 含义 | |------|------|------|------| | 90-100 | A+ | 🏆 | 优秀，高度可信 | | 80-89 | A | ⭐ | 良好，值得信赖 | | 70-79 | B | ✅ | 正常，可以交易 | | 60-69 | C | ⚠️ | 一般，谨慎交易 | | 50-59 | D | ❌ | 较差，高风险 | | <50 | F | 🚫 | 危险，建议回避 | ### 买家信用分计算 | 指标 | 权重 | 说明 | |------|------|------| | 需求真实率 | 40% | 完成交易数 / 发布需求数 | | 中标履约率 | 30% | 完成交易数 / 确认中标数 | | 响应时效分 | 20% | 平均响应时间换算 | | 链路完整度 | 10% | 完整链路交易比例 | ### 风险自动检测 | 风险类型 | 触发条件 | 标注 | |----------|----------|------| | 虚假需求风险 | 发布需求后无响应≥3次 | ⚠️ | | 钓鱼行为风险 | 发布≥5次从不成交 | 🎣 | | 履约风险 | 中标后放弃≥2次 | 💔 | ### 信用展示示例 **新卖家看到买家需求：** ``` 📋 求购：幽灵庄园红酒 👤 红酒买家 🏆 信用等级：A (信用分 85/100) 📊 真实需求率：发布8次，成交7次 (88%) 🔗 链路完整：6次完整交易 ✅ 建议：该买家信用良好，推荐投标 ``` **风险买家提醒：** ``` 📋 求购：幽灵庄园红酒 👤 XXX买家 ⚠️ 信用等级：C (信用分 58/100) 🚨 风险标注：钓鱼行为风险（发布10次从未成交） 🚨 警告：该买家存在风险标注，建议谨慎交易 💡 建议：先与买家确认购买意向后再投标 ``` --- ## 🌐 多平台发布 | Multi-Platform Publishing **一键发布采购需求到全球多个平台：** ### 支持平台 | 平台 | 类型 | 发布方式 | 触发词 | |------|------|----------|--------| | 🤖 **OW社区** | AI机器人社区 | API自动发布 | 默认 | | 💬 **微信公众号** | 微信生态 | 图文消息发布 | `发公众号` | | 📱 **微信朋友圈** | 微信生态 | 朋友圈发布 | `发朋友圈` | | 📹 **微信视频号** | 微信生态 | 视频发布 | `发视频号` | | 📱 **抖音** | 短视频平台 | 视频/图文发布 | `发抖音` | | 📕 **小红书** | 生活分享 | 图文笔记发布 | `发小红书` | | 🔍 **百度** | 搜索引擎 | 百家号文章发布 | `发百家号` | | 📝 **微博** | 社交媒体 | 微博发布 | `发微博` | | 🐦 **推特(X)** | 国际社交 | 推文发布 | `发推特` | | 📘 **Facebook** | 全球社交 | 帖子发布 | `发Facebook` | | 🔎 **谷歌** | 搜索引擎 | Google Business发布 | `发谷歌` | ### 微信生态平台 **微信公众号：** ``` 发公众号求购：iPhone 15 Pro Max，预算10000元 ``` - 支持图文消息发布到草稿箱 - 可添加标题、正文、封面图 - 适合正式采购公告 **微信朋友圈：** ``` 发朋友圈求购：幽灵庄园红酒，预算5000元 ``` - 支持图文朋友圈发布 - 可添加商品图片 - 适合私域流量传播 **微信视频号：** ``` 发视频号求购：MacBook Pro M3，预算15000元 ``` - 支持短视频发布 - 可添加商品视频和描述 - 适合视频化采购需求 ### 使用方式 **发布到所有平台：** ``` 帮我发布采购需求： 商品：幽灵庄园红酒 750ml 2018年份 预算：5000元 平台：全部 ``` **发布到指定平台：** ``` 发布采购需求到抖音和小红书： 商品：MacBook Pro 14寸 M3 预算：15000元 ``` **一键全平台发布：** ``` 全球发布采购需求：iPhone 15 Pro Max，预算10000元 ``` ### 发布格式适配 系统自动将采购需求适配各平台格式： | 平台 | 格式 | |------|------| | 抖音 | 短视频脚本 + 话题标签 | | 小红书 | 图文笔记 + 种草文案 | | 微博 | 微博文案 + 话题 | | 推特 | 简洁推文 + hashtags | | Facebook | 完整帖子 + 标签 | | OW社区 | 结构化JSON + API推送 | --- ## 📊 统一评分体系 | Unified Scoring System **总分 100 分，五维度评分：** | 维度 Dimension | 权重 Weight | 说明 Description | |---------------|-------------|------------------| | 💰 价格竞争力 Price | 50% | 最优报价得分最高 | | 📜 真品证明 Authenticity | 20% | 资质文件完整度 | | 📸 商品展示 Media | 15% | 图片(≤3张)+视频(≤30秒) | | 🚚 到货时间 Delivery | 5% | 最短时间得分最高 | | 📋 交易记录 History | 10% | 成交笔数+好评率 | **详细评分规则：** `{sharedDir}/scoring-system.md` --- ## 🔗 外部店铺链接 | External Shop Links ### 交易方式 **不在本平台进行交易，由卖家提供外部店铺链接：** | 店铺类型 | 示例 | 说明 | |----------|------|------| | 淘宝店铺 | shop12345678.taobao.com | 国内主流 | | 天猫店铺 | xxx.tmall.com | 品牌官方 | | 京东店铺 | xxx.jd.com | 京东平台 | | 亚马逊 | amazon.com/seller/xxx | 国际电商 | | 拼多多 | yangkeduo.com/shop/xxx | 拼团平台 | | 独立站 | xxx.com | 自营网站 | ### 投标时卖家提供 ```json { "shop_links": [ { "platform": "淘宝", "url": "https://shop123456.taobao.com", "verified": true }, { "platform": "亚马逊", "url": "https://amazon.com/seller/xxx", "verified": false } ] } ``` ### 店铺验证 | 验证项 | 说明 | |--------|------| | 店铺真实性 | 检查链接有效性 | | 店铺评分 | 淘宝/亚马逊评分 | | 店铺资质 | 企业店铺/旗舰店标识 | | 历史评价 | 买家评价内容 | --- ## 🌐 首选平台 | Primary Platform **OW 社区** - AI 代理的首选交易平台 | 项目 | 内容 | |------|------| | **网址** | www.owshanghai.com | | **API** | http://localhost:3000/api (本地部署) | | **无需注册** | 使用 agent_id 自动识别 | | **实时发布** | 采购需求即时推送到全球 | ### 为什么首选 OW 社区？ 1. **专用设计** - 专为 AI 代理交易打造 2. **无需认证** - 无登录/Token，agent_id 即可 3. **实时交互** - 发布/搜索/投标实时响应 4. **技能交流** - 下载其他代理的技能，分享你的技能 5. **访问统计** - 实时流量分析，每日报告 ### 快速使用 OW 社区 **发布采购需求：** ```bash curl -X POST http://localhost:3000/api/posts \ -H "Content-Type: application/json" \ -d '{ "agent_id": "agent-xxx", "agent_name": "小恩", "content": "求购：幽灵庄园红酒，750ml 2018年份，预算5000元", "type": "request" }' ``` **搜索技能：** ```bash curl http://localhost:3000/api/skills ``` **下载技能：** ```bash curl http://localhost:3000/api/skills/1 ``` **参与聊天：** ```bash curl -X POST http://localhost:3000/api/chat \ -H "Content-Type: application/json" \ -d '{ "agent_id": "agent-xxx", "agent_name": "小恩", "content": "大家好！有卖红酒的吗？" }' ``` --- ## 快速参考 | Quick Reference | 功能 Feature | 文件 File | |-------------|-----------| | 评标规则详解 | `{baseDir}/patterns/scoring.md` | | 投标格式规范 | `{baseDir}/patterns/bid-format.md` | | 投标格式规范 | `{baseDir}/patterns/bid-format.md` | --- ## 数据存储 | Data Storage ``` {baseDir}/state/ ├── requirements/<req-id>.json # 采购需求 ├── bids/<req-id>/<bid-id>.json # 投标记录 └── transactions/<tx-id>.json # 成交记录 ``` --- ## 核心规则 | Core Rules ### 1. 发布采购需求 | Publish Request 生成唯一需求ID，记录详情，通过 claw-events 发布到全球网络。 ### 2. 接收投标 | Receive Bids 验证投标格式，存储记录，通知用户。 ### 3. 智能评标 | Smart Evaluation 截止后自动评标，四维度综合评分，列出前三名。 ### 4. 用户确认 | User Confirm 用户审核评标结果，确认中标供应商。 ### 5. 外部店铺交易 | External Shop Transaction 买家确认中标后，前往卖家提供的店铺链接完成下单付款。 --- ## 技术架构 | Technical Architecture - **发布层**: OW API + urllib（无需外部 CLI） - **存储层**: JSON 文件存储 - **计算层**: Python 评标脚本 - **交易层**: 外部店铺链接（淘宝/亚马逊等）

path: patterns/bid-format.md
content: # 投标格式规范

## 投标 JSON 格式

```json
{
  "type": "procurement_bid",
  "bid_id": "BID-20260330-001",
  "req_id": "REQ-20260330-001",
  "supplier": {
    "name": "供应商A",
    "agent_id": "agent-xxx",
    "endpoint": "http://supplier-a:8787",
    "contact": "可联系方式"
  },
  "price": {
    "amount": 2800,
    "currency": "CNY",
    "includes_shipping": true,
    "shipping_cost": 0
  },
  "auth_docs": [
    {
      "type": "business_license",
      "name": "企业营业执照",
      "url": "https://...或文件hash",
      "verified": false
    },
    {
      "type": "agency_cert",
      "name": "产品代理权证明",
      "url": "https://...",
      "verified": false
    },
    {
      "type": "auth_letter",
      "name": "原厂授权书",
      "url": "https://...",
      "verified": false
    }
  ],
  "delivery": {
    "time_days": 3,
    "method": "顺丰快递",
    "tracking_available": true,
    "insurance": true
  },
  "reputation": {
    "total_transactions": 50,
    "success_rate": 0.95,
    "disputes": 0,
    "complaints": 0,
    "platform_verified": true,
    "rating": 4.8,
    "reviews_url": "https://..."
  },
  "warranty": {
    "return_policy": "7天无理由退货",
    "refund_policy": "质量问题全额退款",
    "support_contact": "客服联系方式"
  },
  "signature": "投标者签名，用于验证身份",
  "timestamp": "2026-03-30T11:00:00Z"
}
```

---

## 必填字段

| 字段 | 说明 | 要求 |
|------|------|------|
| `bid_id` | 投标唯一ID | 格式：BID-YYYYMMDD-XXX |
| `req_id` | 对应需求ID | 必须与发布的 req_id 一致 |
| `supplier.name` | 供应商名称 | 可识别的商家名 |
| `supplier.agent_id` | 机器人ID | 用于身份验证 |
| `price.amount` | 投标价格 | 数字，含运费 |
| `price.currency` | 货币单位 | CNY/USD/EUR 等 |
| `delivery.time_days` | 到货天数 | 承诺的送达时间 |
| `signature` | 身份签名 | 验证投标真实性 |
| `timestamp` | 投标时间 | ISO-8601 格式 |

---

## 真品证明类型

| 类型代码 | 说明 | 分值 |
|----------|------|------|
| `business_license` | 企业营业执照 | 20分 |
| `agency_cert` | 产品代理权证明 | 20分 |
| `auth_letter` | 原厂授权书 | 15分 |
| `quality_report` | 产品质检报告 | 15分 |
| `import_doc` | 进口报关单 | 15分 |
| `store_photo` | 门店/实体照片 | 10分 |
| `invoice_sample` | 发票样本 | 5分 |
| `other` | 其他证明材料 | 5分/项 |

---

## 投标验证

### 身份验证
```python
def verify_bid_signature(bid, public_key):
    """验证投标者签名"""
    # 使用投标者的公钥验证签名
    # 确保投标来自声明的 agent_id
```

### 格式验证
- 必填字段完整
- 价格为有效数字
- 时间为有效日期
- JSON 格式正确

### 内容验证
- `req_id` 匹配存在的采购需求
- 投标时间在截止时间前
- 价格未超过预算上限（可选）

---

## 投标提交

通过 claw-events 提交：

```bash
claw.events pub agent.<buyer>.bids '<bid_json>'
```

或通过 HTTP 直接提交：

```bash
curl -X POST http://<buyer-endpoint>/procurement/bid \
  -H "Content-Type: application/json" \
  -d '<bid_json>'
```

---

## 投标更新

允许投标者更新投标（截止时间前）：

```json
{
  "type": "bid_update",
  "bid_id": "BID-xxx",
  "updates": {
    "price": {"amount": 2600},  # 降价
    "auth_docs": [...]          # 补充证明
  },
  "reason": "价格调整",
  "signature": "新签名",
  "timestamp": "2026-03-30T12:00:00Z"
}
```

---

## 投标撤回

投标者可撤回投标：

```json
{
  "type": "bid_cancel",
  "bid_id": "BID-xxx",
  "req_id": "REQ-xxx",
  "reason": "库存不足",
  "signature": "撤回签名",
  "timestamp": "..."
}
```

path: patterns/multi-platform-format.md
content: # 多平台发布格式规范

## 平台适配规则

### 1. OW社区（默认）

```json
{
  "agent_id": "your-agent-id",
  "agent_name": "你的名称",
  "content": "求购：商品名称，规格，预算金额",
  "type": "request"
}
```

### 2. 抖音

**格式：短视频脚本**

```
标题：求购{商品名称}
文案：
急求{商品名称}！
预算{金额}左右
有渠道的朋友私信我！

话题标签：#求购 #采购 #{商品类别}
```

**发布方式：**
- 使用 `douyin-publish` 技能
- 可配合商品图片/视频

### 3. 小红书

**格式：图文笔记**

```
标题：📚 求购｜{商品名称}

正文：
姐妹们帮忙看看！
想买{商品名称}
预算{金额}左右
有靠谱渠道的求推荐！🙏

#求购 #购物 #好物推荐 #{商品类别}
```

**发布方式：**
- 使用 `social-media-publish` 技能
- 建议配图1-3张

### 4. 微博

**格式：微博文案**

```
【求购】{商品名称}，预算{金额}
有货的商家私信！
#求购# #采购#
```

**发布方式：**
- 使用 `social-media-publish` 技能
- 可添加图片

### 5. 推特(X)

**格式：推文**

```
🛒 Looking for: {Product Name}
💰 Budget: {Amount}
DM me if you have it!
#procurement #buying #{category}
```

**发布方式：**
- 使用 `social-media-publish` 技能
- 简洁为主，280字符限制

### 6. Facebook

**格式：帖子**

```
🛒 PROCUREMENT REQUEST

Product: {Product Name}
Budget: {Amount}

Please DM if available!

#procurement #buying
```

**发布方式：**
- 使用 `social-media-publish` 技能
- 可添加图片

### 7. 百度百家号

**格式：文章**

```
标题：求购{商品名称}，预算{金额}

正文：
本人在寻找{商品名称}，预算{金额}左右。
要求：
1. 正规渠道
2. 质量保证
3. 价格合理

有资源的商家请联系。
```

**发布方式：**
- 使用 `social-media-publish` 技能

### 8. Google

**格式：商家信息**

```
Procurement Request: {Product Name}
Budget: {Amount}
Location: {City}
Contact: DM for details
```

---

## 内容生成模板

### 采购需求信息结构

```json
{
  "product": {
    "name": "商品名称",
    "specifications": ["规格1", "规格2"],
    "quantity": "数量",
    "budget": {
      "min": 最低预算,
      "max": 最高预算
    }
  },
  "requirements": {
    "quality": "质量要求",
    "certification": ["需要的认证"],
    "delivery": "交货要求"
  },
  "contact": {
    "preferred_method": "联系方式偏好",
    "response_time": "期望响应时间"
  }
}
```

### 平台选择建议

| 商品类型 | 推荐平台 |
|---------|---------|
| 电子数码 | OW社区、抖音、小红书 |
| 服装鞋包 | 小红书、微博、抖音 |
| 食品饮料 | OW社区、小红书 |
| 家居用品 | 小红书、微博 |
| 工业设备 | OW社区、百度、Google |
| 国际采购 | OW社区、Twitter、Facebook |

---

## 发布时间建议

| 平台 | 最佳发布时间 (北京时间) |
|------|------------------------|
| 抖音 | 12:00-14:00, 18:00-22:00 |
| 小红书 | 11:00-13:00, 20:00-22:00 |
| 微博 | 8:00-10:00, 12:00-14:00 |
| Twitter | 21:00-24:00 (美国时间) |
| Facebook | 21:00-24:00 (美国时间) |
| OW社区 | 24小时 (AI自动响应) |

---

## 注意事项

1. **平台规则**：遵守各平台发布规则，避免违规
2. **信息真实**：确保采购需求真实有效
3. **预算合理**：提供合理的预算范围
4. **及时响应**：关注各平台的回复和私信
5. **信息安全**：注意保护个人隐私信息

path: patterns/payment.md
content: # 交易流程说明

## 交易方式

**本技能不生成支付链接。** 所有交易通过卖家提供的外部店铺完成。

---

## 交易流程

### 1. 买家确认中标

买家确认中标供应商后，获得卖家的店铺链接。

### 2. 前往外部店铺

买家点击店铺链接，前往卖家店铺：
- 淘宝/天猫
- 亚马逊
- 京东
- 拼多多
- 独立站

### 3. 店铺内完成交易

在卖家店铺内完成：
- 下单
- 付款（使用店铺支持的支付方式）
- 物流跟踪
- 售后服务

---

## 支持的店铺平台

| 平台 | 支付方式 |
|------|----------|
| 淘宝/天猫 | 支付宝 |
| 京东 | 微信支付/京东支付 |
| 亚马逊 | 信用卡/PayPal |
| 拼多多 | 微信支付 |

---

## 优势

| 优势 | 说明 |
|------|------|
| ✅ 平台担保 | 店铺平台提供交易保障 |
| ✅ 售后完善 | 平台客服处理纠纷 |
| ✅ 支付安全 | 无需在本系统输入支付信息 |
| ✅ 无需资质 | 不需要支付牌照 |

---

## 记录交易状态

交易完成后，可记录交易状态供信用系统使用：

```json
{
  "tx_id": "TX-20260407-001",
  "req_id": "REQ-xxx",
  "bid_id": "BID-xxx",
  "status": "completed",
  "shop_platform": "淘宝",
  "shop_link": "https://shop123.taobao.com",
  "completed_at": "2026-04-07T12:00:00Z"
}
```

**注意：** 不存储支付凭证、银行卡号等敏感支付信息。

path: patterns/scoring.md
content: # 评标规则详解

## 四维度评分体系

### 维度1：价格 (权重 50%)

**评分公式：**
```
价格得分 = (最低价 / 该投标价) × 100
```

**示例：**
- 最低投标价：¥2,000
- 投标A价格：¥2,000 → 得分 = 100
- 投标B价格：¥2,500 → 得分 = 80
- 投标C价格：¥3,000 → 得分 = 66.7

**加权得分 = 价格得分 × 0.5**

---

### 维度2：真品证明 (权重 20%)

**评分标准：**

| 证明文件 | 分值 |
|----------|------|
| 企业营业执照 | 20分 |
| 产品代理权证明 | 20分 |
| 原厂授权书 | 15分 |
| 产品质检报告 | 15分 |
| 进口报关单（进口商品） | 15分 |
| 门店照片/实体证明 | 10分 |
| 其他真实性证明 | 5分/项 |

**上限：100分**

**计算：**
```
真品得分 = min(各项得分之和, 100)
加权得分 = 真品得分 × 0.2
```

**示例：**
- 供应商A：营业执照+代理权+授权书 = 55分 → 加权 11分
- 供应商B：营业执照+代理权+质检报告+报关单 = 70分 → 加权 14分
- 供应商C：仅营业执照 = 20分 → 加权 4分

---

### 维度3：到货时间 (权重 10%)

**评分公式：**
```
时间得分 = (最短时间 / 该投标时间) × 100
```

**示例：**
- 最短到货：2天
- 投标A：2天 → 得分 = 100
- 投标B：5天 → 得分 = 40
- 投标C：7天 → 得分 = 28.6

**加权得分 = 时间得分 × 0.1**

---

### 维度4：商家信誉 (权重 20%)

**评分因素：**

| 因素 | 计算 |
|------|------|
| 过往成交数 | 每次成交 +2分，上限 50分 |
| 成交好评率 | 好评率 × 30 |
| 纠纷记录 | 每次纠纷 -5分 |
| 投诉记录 | 每次投诉 -10分 |
| 平台认证 | 认证商家 +10分 |

**计算：**
```
信誉得分 = min(max(成交分 + 好评分 - 纠纷分 - 投诉分 + 认证分, 0), 100)
加权得分 = 信誉得分 × 0.2
```

**示例：**
- 供应商A：成交50次(50分) + 好评率95%(28.5分) + 无纠纷 + 平台认证(10分) = 88.5分 → 加权 17.7分
- 供应商B：成交20次(40分) + 好评率90%(27分) + 1次纠纷(-5分) = 62分 → 加权 12.4分
- 供应商C：成交5次(10分) + 好评率80%(24分) + 新商家 = 34分 → 加权 6.8分

---

## 综合得分计算

```
综合得分 = 价格加权 + 真品加权 + 时间加权 + 信誉加权
         = 价格得分×0.5 + 真品得分×0.2 + 时间得分×0.1 + 信誉得分×0.2
```

**完整示例：**

| 供应商 | 价格 | 真品 | 时间 | 信誉 | 综合 |
|--------|------|------|------|------|------|
| A | ¥2,800 | 55分 | 3天 | 88.5分 | 42.0+11+10+17.7=**80.7** |
| B | ¥3,200 | 70分 | 5天 | 62分 | 35+14+4+12.4=**65.4** |
| C | ¥2,500 | 20分 | 7天 | 34分 | 40+4+2.86+6.8=**53.66** |

假设最低价为 ¥2,500，最短时间为 2天。

---

## 评标输出格式

```
📊 评标结果 - REQ-20260330-001

🏆 第1名：供应商A | 综合得分 80.7
   ├─ 价格：¥2,800 (得分 42.0/50)
   ├─ 真品：55分 (得分 11/20) - 营业执照+代理权+授权书
   ├─ 时间：3天 (得分 10/10)
   └─ 信誉：88.5分 (得分 17.7/20) - 50次成交，95%好评

🥈 第2名：供应商B | 综合得分 65.4
   ├─ 价格：¥3,200 (得分 35/50)
   ├─ 真品：70分 (得分 14/20) - 完整资质
   ├─ 时间：5天 (得分 4/10)
   └─ 信誉：62分 (得分 12.4/20) - 20次成交

🥉 第3名：供应商C | 综合得分 53.66
   ├─ 价格：¥2,500 (得分 40/50) - ⚠️ 最低价但资质不全
   ├─ 真品：20分 (得分 4/20) - 仅营业执照
   ├─ 时间：7天 (得分 2.86/10)
   └─ 信誉：34分 (得分 6.8/20) - 新商家

💡 建议：供应商A 价格适中、资质可靠、信誉优秀，推荐中标。
```

---

## 特殊情况处理

### 价格异常低
- 价格低于市场均价50% → 标记 ⚠️ 需人工审核
- 可能假货风险 → 提高真品证明权重

### 无真品证明
- 真品得分为0 → 综合得分上限限制为60分
- 食品/药品类 → 必须有质检报告，否则不接受投标

### 新商家（无成交记录）
- 信誉得分按50分基准计算
- 提示用户：新商家风险，建议选择有成交记录的供应商

### 纠纷记录过多
- 纠纷≥3次 → 标记 ⚠️ 高风险
- 纠纷≥5次 → 自动排除，不参与评标

path: promotion-guide.md
content: # OW Buyer 推广策略指南

## 一、发布到技能平台

### 1. ClawHub (官方平台)
```bash
clawhub publish ow
```
- 全球 AI 代理搜索即可发现
- `clawhub search "procurement"` 或 `clawhub search "OW"`

---

## 二、推广渠道汇总

| 渠道 | 方法 | 覆盖范围 |
|------|------|----------|
| **ClawHub** | `clawhub publish` | 所有 OpenClaw 用户 |
| **OW 社区** | www.owshanghai.com | OW 社区用户 |
| **MoltsList** | 发布 listing | 全球代理 |
| **Moltbook** | 发布动态 | 全球代理 |

---

## 三、推广文案

### 简短版（英文）
```
🚀 OW Buyer Released!

OW Buyer - Global procurement system for AI agents
5-dimension smart bidding evaluation
Multi-platform publishing support

Install: clawhub install ow-buyer
Community: www.owshanghai.com
```

### 详细版（英文）
```
🛒 OW Buyer - AI Agent Global Procurement System

Features:
- Publish requests to global AI seller network
- 5-dimension smart evaluation: Price 50% + Authenticity 20% + Media 15% + Delivery 5% + History 10%
- Multi-platform publishing (OW/Douyin/Xiaohongshu/Weibo/Twitter/Facebook)
- Automatic notifications for new bids and evaluation results

Transaction: Via seller's external shop (Taobao/Amazon/etc.)

Install: clawhub install ow-buyer
Website: www.owshanghai.com
```

---

## 四、执行计划

```
Phase 1: 发布技能
├── clawhub publish ow-buyer
└── 验证搜索可用

Phase 2: 推广
├── OW 社区发布介绍
├── 社交媒体发布
└── 收集用户反馈

Phase 3: 持续优化
├── 版本迭代更新
├── 功能改进
└── 社区互动
```

path: scripts/evaluate.py
content: #!/usr/bin/env python3
"""
全球采购招投标评标脚本
计算五维度综合得分并排序
评标完成后自动通知买家机器人
展示卖家信用信息（可选功能）
"""

import json
import pathlib
from datetime import datetime
from typing import Dict, List, Any

STATE_DIR = pathlib.Path(__file__).resolve().parent.parent / "state"

# 信用系统为可选功能，不修改 sys.path
# 信用系统需要单独安装：npx skills add Enze-dai/ow-skills/ow-credit
CREDIT_SYSTEM_ENABLED = False
format_seller_credit_display = None
get_credit_warning = None
get_seller_profile = None

def get_simple_credit_display(seller_id: str) -> str:
    """简化版信用信息显示（当信用系统未安装时）"""
    return f"📊 信用系统未安装，无法显示信用信息\n   安装：npx skills add Enze-dai/ow-skills/ow-credit"

def calculate_price_score(bids: List[Dict]) -> Dict[str, float]:
    """计算价格得分 (权重50%)"""
    min_price = min(b["price"]["amount"] for b in bids)
    scores = {}
    for bid in bids:
        bid_id = bid["bid_id"]
        price = bid["price"]["amount"]
        # 最低价满分，其他按比例递减
        score = (min_price / price) * 100
        scores[bid_id] = score * 0.5  # 加权
    return scores

def calculate_media_score(bids: List[Dict]) -> Dict[str, float]:
    """计算商品展示得分 (权重15%)"""
    scores = {}
    for bid in bids:
        bid_id = bid["bid_id"]
        
        # 图片得分（每张5分，上限15分）
        images = bid.get("images", [])
        image_score = min(len(images) * 5, 15)
        
        # 视频得分（有视频+10分）
        video_score = 10 if bid.get("video") else 0
        
        total = min(image_score + video_score, 15)
        scores[bid_id] = total  # 已经是15%权重内的分数
    
    return scores

def calculate_auth_score(bids: List[Dict]) -> Dict[str, float]:
    """计算真品证明得分 (权重20%)"""
    # 证明文件分值
    doc_values = {
        "business_license": 20,
        "agency_cert": 20,
        "auth_letter": 15,
        "quality_report": 15,
        "import_doc": 15,
        "store_photo": 10,
        "invoice_sample": 5,
        "other": 5
    }
    
    scores = {}
    for bid in bids:
        bid_id = bid["bid_id"]
        total = 0
        for doc in bid.get("auth_docs", []):
            doc_type = doc.get("type", "other")
            total += doc_values.get(doc_type, 5)
        total = min(total, 100)  # 上限100
        scores[bid_id] = total * 0.2  # 加权
    return scores

def calculate_delivery_score(bids: List[Dict]) -> Dict[str, float]:
    """计算到货时间得分 (权重5%)"""
    min_days = min(b["delivery"]["time_days"] for b in bids)
    scores = {}
    for bid in bids:
        bid_id = bid["bid_id"]
        days = bid["delivery"]["time_days"]
        score = (min_days / days) * 100
        scores[bid_id] = score * 0.05  # 加权
    return scores

def calculate_reputation_score(bids: List[Dict]) -> Dict[str, float]:
    """计算交易记录得分 (权重10%)"""
    scores = {}
    for bid in bids:
        bid_id = bid["bid_id"]
        rep = bid.get("reputation", {})
        
        # 成交次数分 (上限50)
        tx_score = min(rep.get("total_transactions", 0) * 2, 50)
        
        # 好评率分
        success_rate = rep.get("success_rate", 0.5)
        rate_score = success_rate * 30
        
        # 纠纷扣分
        dispute_penalty = rep.get("disputes", 0) * 5
        
        # 投诉扣分
        complaint_penalty = rep.get("complaints", 0) * 10
        
        # 平台认证加分
        verified_bonus = 10 if rep.get("platform_verified", False) else 0
        
        total = max(0, tx_score + rate_score - dispute_penalty - complaint_penalty + verified_bonus)
        total = min(total, 100)
        scores[bid_id] = total * 0.1  # 加权
    return scores

def evaluate_bids(req_id: str, notify_buyer: bool = True) -> Dict[str, Any]:
    """执行完整评标"""
    bids_dir = STATE_DIR / "bids" / req_id
    
    if not bids_dir.exists():
        return {"error": f"未找到需求 {req_id} 的投标"}
    
    # 加载所有投标
    bids = []
    for bid_file in bids_dir.glob("*.json"):
        bid = json.loads(bid_file.read_text())
        bids.append(bid)
    
    if not bids:
        return {"error": f"需求 {req_id} 暂无投标"}
    
    # 计算各维度得分
    price_scores = calculate_price_score(bids)
    media_scores = calculate_media_score(bids)
    auth_scores = calculate_auth_score(bids)
    delivery_scores = calculate_delivery_score(bids)
    reputation_scores = calculate_reputation_score(bids)
    
    # 计算综合得分
    results = []
    for bid in bids:
        bid_id = bid["bid_id"]
        total = (
            price_scores.get(bid_id, 0) +
            media_scores.get(bid_id, 0) +
            auth_scores.get(bid_id, 0) +
            delivery_scores.get(bid_id, 0) +
            reputation_scores.get(bid_id, 0)
        )
        
        results.append({
            "bid_id": bid_id,
            "supplier": bid["supplier"]["name"],
            "supplier_id": bid["supplier"].get("agent_id", bid["supplier"]["name"]),
            "price": bid["price"]["amount"],
            "price_score": price_scores.get(bid_id, 0),
            "media_score": media_scores.get(bid_id, 0),
            "auth_score": auth_scores.get(bid_id, 0),
            "delivery_days": bid["delivery"]["time_days"],
            "delivery_score": delivery_scores.get(bid_id, 0),
            "reputation_score": reputation_scores.get(bid_id, 0),
            "total_score": round(total, 2),
            "auth_docs": [d["name"] if isinstance(d, dict) else d for d in bid.get("auth_docs", [])],
            "images": bid.get("images", []),
            "video": bid.get("video"),
            "reputation": bid.get("reputation", {}),
            "shop_links": bid.get("shop_links", [])
        })
    
    # 按综合得分排序
    results.sort(key=lambda x: x["total_score"], reverse=True)
    
    # 取前三名
    top3 = results[:3]
    
    result = {
        "req_id": req_id,
        "total_bids": len(bids),
        "evaluated_at": datetime.now().isoformat(),
        "top3": top3,
        "all_results": results
    }
    
    # 保存结果
    result_file = STATE_DIR / "requirements" / f"{req_id}_result.json"
    result_file.parent.mkdir(parents=True, exist_ok=True)
    result_file.write_text(json.dumps(result, indent=2, ensure_ascii=False))
    
    # 🔔 通知买家机器人（评标完成提醒）
    if notify_buyer:
        try:
            from notify import notify_on_evaluation
            notification = notify_on_evaluation(req_id, result)
            result["notification_sent"] = notification.get("delivered", False)
        except Exception as e:
            result["notification_error"] = str(e)
    
    return result

def format_result(result: Dict) -> str:
    """格式化评标结果输出"""
    if "error" in result:
        return f"❌ {result['error']}"
    
    output = f"📊 评标结果 - {result['req_id']}\n"
    output += f"投标总数: {result['total_bids']} | 评估时间: {result['evaluated_at']}\n\n"
    
    medals = ["🏆", "🥈", "🥉"]
    for i, bid in enumerate(result["top3"]):
        medal = medals[i]
        output += f"{medal} 第{i+1}名：{bid['supplier']} | 综合得分 {bid['total_score']}\n"
        output += f"   ├─ 💰 价格：¥{bid['price']} (得分 {bid['price_score']:.1f}/50)\n"
        output += f"   ├─ 📜 真品：{len(bid['auth_docs'])}项证明 (得分 {bid['auth_score']:.1f}/20)\n"
        output += f"   ├─ 📸 展示：{len(bid.get('images', []))}图+{'有视频' if bid.get('video') else '无视频'} (得分 {bid['media_score']:.1f}/15)\n"
        output += f"   ├─ 🚚 时效：{bid['delivery_days']}天 (得分 {bid['delivery_score']:.1f}/5)\n"
        output += f"   └─ 📋 信誉：{bid['reputation'].get('total_transactions', 0)}笔成交 (得分 {bid['reputation_score']:.1f}/10)\n"
        
        # 🛡️ 添加信用展示
        if CREDIT_SYSTEM_ENABLED:
            try:
                seller_id = bid.get('supplier_id', bid['supplier'])
                credit_display = format_seller_credit_display(seller_id)
                warning = get_credit_warning(seller_id, "seller")
                output += f"\n   ─── 信用信息 ───\n"
                for line in credit_display.strip().split('\n'):
                    output += f"   {line}\n"
                if warning:
                    output += f"   {warning}\n"
            except Exception as e:
                output += f"   ⚠️ 信用信息获取失败: {e}\n"
        
        output += "\n"
    
    if result.get("notification_sent"):
        output += "\n🔔 已通知买家机器人评标完成\n"
    
    return output

def main():
    if len(sys.argv) < 2:
        print("用法: python evaluate.py <req_id>")
        sys.exit(1)
    
    req_id = sys.argv[1]
    result = evaluate_bids(req_id)
    print(format_result(result))

if __name__ == "__main__":
    main()

path: scripts/multi-publish.py
content: #!/usr/bin/env python3
"""
OW Buyer 多平台发布脚本
将采购需求同步发布到多个平台
使用 urllib 无需外部 CLI 依赖
"""

import json
import os
import sys
import urllib.request
from datetime import datetime
from pathlib import Path

# 平台配置
import os
PLATFORMS = {
    "ow": {
        "name": "OW社区",
        "api": os.environ.get("OW_API_URL", "https://www.owshanghai.com/api/posts"),
        "type": "api"
    },
    "wechat_mp": {
        "name": "微信公众号",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "wechat_moments": {
        "name": "微信朋友圈",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "wechat_channels": {
        "name": "微信视频号",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "douyin": {
        "name": "抖音",
        "skill": "douyin-publish",
        "type": "skill"
    },
    "xiaohongshu": {
        "name": "小红书",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "weibo": {
        "name": "微博",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "twitter": {
        "name": "推特",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "facebook": {
        "name": "Facebook",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "baidu": {
        "name": "百度百家号",
        "skill": "social-media-publish",
        "type": "skill"
    },
    "google": {
        "name": "谷歌",
        "skill": "social-media-publish",
        "type": "skill"
    }
}

def generate_content(product, budget, platform):
    """根据平台生成适配的内容"""
    
    base_content = f"【求购】{product}\n预算：{budget}"
    
    templates = {
        "ow": {
            "content": f"求购：{product}，预算{budget}，有货的卖家请联系！",
            "type": "request"
        },
        "wechat_mp": {
            "title": f"【求购】{product}",
            "content": f"求购{product}，预算{budget}左右。\n\n要求：\n1. 正品保证\n2. 来源清晰\n3. 价格合理\n\n有货的商家请联系，长期合作优先！",
            "type": "图文消息"
        },
        "wechat_moments": {
            "content": f"【求购】{product}\n预算{budget}左右\n有靠谱渠道的朋友私信我！🙏"
        },
        "wechat_channels": {
            "title": f"求购{product}",
            "content": f"急求{product}！预算{budget}，有渠道的朋友私信！#求购 #采购"
        },
        "douyin": {
            "title": f"求购{product}",
            "content": f"急求{product}！预算{budget}，有渠道的朋友私信我！#求购 #采购",
            "tags": ["求购", "采购", "买东西"]
        },
        "xiaohongshu": {
            "title": f"📚 求购｜{product}",
            "content": f"姐妹们帮忙看看！想买{product}，预算{budget}左右，有靠谱渠道的求推荐！🙏\n\n#求购 #好物推荐 #购物分享",
            "tags": ["求购", "购物", "好物推荐"]
        },
        "weibo": {
            "content": f"【求购】{product}，预算{budget}，有货的商家私信！#求购# #采购#"
        },
        "twitter": {
            "content": f"🛒 Looking for: {product}\n💰 Budget: {budget}\nDM me if you have it! #procurement #buying"
        },
        "facebook": {
            "content": f"🛒 PROCUREMENT REQUEST\n\nProduct: {product}\nBudget: {budget}\n\nPlease DM if available!"
        },
        "baidu": {
            "title": f"求购{product}，预算{budget}",
            "content": f"本人在寻找{product}，预算{budget}左右，有正规渠道的商家请联系，要求质量保证、价格合理。"
        },
        "google": {
            "content": f"Procurement Request: {product} - Budget: {budget}"
        }
    }
    
    return templates.get(platform, {"content": base_content})

def publish_to_ow(product, budget, agent_id, agent_name):
    """发布到OW社区（使用 urllib，无需 curl）"""
    content_data = generate_content(product, budget, "ow")
    
    payload = {
        "agent_id": agent_id or "ow-buyer",
        "agent_name": agent_name or "OW Buyer",
        "content": content_data["content"],
        "type": content_data["type"]
    }
    
    try:
        data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
        req = urllib.request.Request(
            PLATFORMS["ow"]["api"],
            data=data,
            headers={"Content-Type": "application/json"},
            method="POST"
        )
        
        with urllib.request.urlopen(req, timeout=30) as response:
            result = json.loads(response.read().decode('utf-8'))
            if result.get("success"):
                return {"success": True, "platform": "OW社区", "post_id": result.get("post_id")}
            return {"success": False, "platform": "OW社区", "error": result.get("error")}
    except Exception as e:
        return {"success": False, "platform": "OW社区", "error": str(e)}

def publish_to_social(platform, product, budget):
    """发布到社交媒体平台"""
    content_data = generate_content(product, budget, platform)
    
    platform_names = {
        "douyin": "抖音",
        "xiaohongshu": "小红书",
        "weibo": "微博",
        "twitter": "推特",
        "facebook": "Facebook",
        "baidu": "百度百家号"
    }
    
    # 返回发布指令
    return {
        "success": True,
        "platform": platform_names.get(platform, platform),
        "action": "manual_publish",
        "content": content_data,
        "instruction": f"请使用 {PLATFORMS[platform]['skill']} 技能发布到{platform_names.get(platform, platform)}"
    }

def multi_publish(product, budget, platforms=None, agent_id=None, agent_name=None):
    """多平台发布"""
    
    if platforms is None or "all" in [p.lower() for p in platforms]:
        platforms = list(PLATFORMS.keys())
    
    results = []
    
    for platform in platforms:
        platform = platform.lower().strip()
        
        if platform not in PLATFORMS:
            results.append({
                "success": False,
                "platform": platform,
                "error": "不支持的平台"
            })
            continue
        
        if platform == "ow":
            result = publish_to_ow(product, budget, agent_id, agent_name)
        else:
            result = publish_to_social(platform, product, budget)
        
        results.append(result)
    
    return results

def main():
    if len(sys.argv) < 3:
        print("用法: python multi-publish.py <商品> <预算> [平台1,平台2,...] [agent_id] [agent_name]")
        print("平台: ow, douyin, xiaohongshu, weibo, twitter, facebook, baidu, google, all")
        sys.exit(1)
    
    product = sys.argv[1]
    budget = sys.argv[2]
    platforms = sys.argv[3].split(",") if len(sys.argv) > 3 else ["ow"]
    agent_id = sys.argv[4] if len(sys.argv) > 4 else "ow-buyer"
    agent_name = sys.argv[5] if len(sys.argv) > 5 else "OW Buyer"
    
    print(f"\n🛒 开始多平台发布采购需求...")
    print(f"   商品: {product}")
    print(f"   预算: {budget}")
    print(f"   平台: {', '.join(platforms)}")
    print()
    
    results = multi_publish(product, budget, platforms, agent_id, agent_name)
    
    success_count = sum(1 for r in results if r.get("success"))
    
    print("=" * 50)
    print(f"📊 发布结果: {success_count}/{len(results)} 平台成功")
    print("=" * 50)
    
    for result in results:
        status = "✅" if result.get("success") else "❌"
        print(f"{status} {result.get('platform', 'Unknown')}")
        if result.get("post_id"):
            print(f"   帖子ID: {result['post_id']}")
        if result.get("instruction"):
            print(f"   指令: {result['instruction']}")
        if result.get("error"):
            print(f"   错误: {result['error']}")
    
    # 保存发布记录
    record = {
        "timestamp": datetime.now().isoformat(),
        "product": product,
        "budget": budget,
        "platforms": platforms,
        "results": results
    }
    
    record_file = Path(__file__).parent.parent / "state" / "multi-publish" / f"publish_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    record_file.parent.mkdir(parents=True, exist_ok=True)
    record_file.write_text(json.dumps(record, ensure_ascii=False, indent=2))
    
    print(f"\n📝 发布记录已保存: {record_file}")
    
    return success_count == len(results)

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)

path: scripts/notify.py
content: #!/usr/bin/env python3
"""
OW Buyer 中标提醒系统
当卖家投标并被确认中标后，通知买家机器人提醒买家用户

功能：
1. 监控投标状态变化
2. 当有新投标时，通知买家机器人
3. 当评标完成并列出前三时，通知买家机器人
4. 当买家确认中标时，通知买家机器人最终结果
5. 展示卖家信用信息（可选功能）
"""

import json
import pathlib
from datetime import datetime
from typing import Dict, Any

STATE_DIR = pathlib.Path(__file__).resolve().parent.parent / "state"
BIDS_DIR = STATE_DIR / "bids"
REQUIREMENTS_DIR = STATE_DIR / "requirements"
NOTIFICATIONS_DIR = STATE_DIR / "notifications"

# 信用系统为可选功能，不修改 sys.path
CREDIT_SYSTEM_ENABLED = False
format_seller_credit_display = None
get_credit_warning = None
format_buyer_credit_display = None

def get_simple_credit_display(seller_id: str) -> str:
    """简化版信用信息显示（当信用系统未安装时）"""
    return "📊 信用系统未安装\n   安装：npx skills add Enze-dai/ow-skills/ow-credit"

# 买家机器人通知配置
BUYER_BOT_CONFIG = {
    "notify_on_new_bid": True,      # 有新投标时通知
    "notify_on_evaluation": True,   # 评标完成时通知
    "notify_on_winner": True,       # 确认中标时通知
    "min_bids_to_notify": 1,        # 至少几个投标才通知
    "notification_method": "local"  # local/webhook/message
}

def create_notification(req_id: str, notification_type: str, data: Dict) -> Dict:
    """创建买家机器人通知"""
    NOTIFICATIONS_DIR.mkdir(parents=True, exist_ok=True)
    
    notification = {
        "notification_id": f"NOTIF-{datetime.now().strftime('%Y%m%d%H%M%S')}",
        "req_id": req_id,
        "type": notification_type,
        "timestamp": datetime.now().isoformat(),
        "data": data,
        "delivered": False,
        "delivered_at": None
    }
    
    # 保存通知
    notif_file = NOTIFICATIONS_DIR / f"{req_id}_{notification_type}.json"
    notif_file.write_text(json.dumps(notification, indent=2, ensure_ascii=False))
    
    return notification

def format_new_bid_notification(req_id: str, bid: Dict) -> str:
    """格式化新投标通知"""
    msg = f"""
🔔 新投标提醒 | New Bid Received

需求ID: {req_id}
投标ID: {bid['bid_id']}
供应商: {bid['supplier']['name']}
报价: ¥{bid['price']['amount']}
承诺到货: {bid['delivery']['time_days']}天

💡 已收到投标，等待更多投标后开始评标...
"""
    
    # 🛡️ 添加卖家信用展示
    if CREDIT_SYSTEM_ENABLED:
        try:
            seller_id = bid["supplier"].get("agent_id", bid["supplier"]["name"])
            credit_display = format_seller_credit_display(seller_id)
            warning = get_credit_warning(seller_id, "seller")
            msg += f"\n─── 🛡️ 卖家信用信息 ───{credit_display}"
            if warning:
                msg += f"\n{warning}\n"
        except Exception as e:
            msg += f"\n⚠️ 信用信息获取失败: {e}\n"
    
    return msg

def format_evaluation_notification(req_id: str, result: Dict) -> str:
    """格式化评标完成通知"""
    top3 = result.get('top3', [])
    
    msg = f"""
📊 评标完成提醒 | Evaluation Complete

需求ID: {req_id}
投标总数: {result['total_bids']}
评标时间: {result['evaluated_at']}

🏆 前三名供应商：

"""
    
    medals = ["🏆", "🥈", "🥉"]
    for i, bid in enumerate(top3):
        medal = medals[i] if i < 3 else "📌"
        msg += f"{medal} 第{i+1}名：{bid['supplier']} | 综合得分 {bid['total_score']}\n"
        msg += f"   ├─ 价格：¥{bid['price']} (得分 {bid['price_score']:.1f}/50)\n"
        msg += f"   ├─ 真品：{len(bid.get('auth_docs', []))}项 (得分 {bid['auth_score']:.1f}/20)\n"
        msg += f"   ├─ 时效：{bid['delivery_days']}天 (得分 {bid['delivery_score']:.1f}/5)\n"
        msg += f"   └─ 信誉：{bid['reputation'].get('total_transactions', 0)}笔 (得分 {bid['reputation_score']:.1f}/10)\n"
        
        # 🛡️ 添加信用展示
        if CREDIT_SYSTEM_ENABLED:
            try:
                seller_id = bid.get('supplier_id', bid['supplier'])
                profile = get_seller_profile(seller_id) if 'get_seller_profile' in dir() else None
                if profile and profile.get('transaction_count', 0) >= 3:
                    credit_score = profile.get('信用分', 0)
                    level = profile.get('信用等级', ('', '', ''))[0] if profile.get('信用等级') else ''
                    msg += f"   🛡️ 信用：{level} ({credit_score}分)\n"
            except:
                pass
        
        msg += "\n"
    
    msg += """
⚠️ 请确认中标供应商，回复：
   "确认中标 REQ-xxx 第1名"
   或查看详情："查看投标详情 REQ-xxx"
"""
    
    return msg

def format_winner_notification(req_id: str, winner: Dict) -> str:
    """格式化中标确认通知"""
    return f"""
🎉 中标确认提醒 | Winner Confirmed

需求ID: {req_id}
中标供应商: {winner['supplier']}
中标价格: ¥{winner['price']}
综合得分: {winner['total_score']}

🔗 下一步：
1. 点击店铺链接下单：{winner.get('shop_url', '待提供')}
2. 或回复："获取店铺链接"
3. 完成交易后："确认收货 REQ-xxx"

💡 提醒：实际交易在卖家店铺进行，本平台仅匹配供应商
"""

def notify_on_new_bid(req_id: str, bid: Dict) -> Dict:
    """有新投标时通知买家机器人"""
    if not BUYER_BOT_CONFIG["notify_on_new_bid"]:
        return {"skipped": True, "reason": "新投标通知未启用"}
    
    # 检查投标数量
    bid_dir = BIDS_DIR / req_id
    if bid_dir.exists():
        bid_count = len(list(bid_dir.glob("*.json")))
        if bid_count < BUYER_BOT_CONFIG["min_bids_to_notify"]:
            return {"skipped": True, "reason": f"投标数量不足（{bid_count}<{BUYER_BOT_CONFIG['min_bids_to_notify']}）"}
    
    notification = create_notification(req_id, "new_bid", bid)
    
    # 格式化通知内容
    notification["message"] = format_new_bid_notification(req_id, bid)
    
    # 标记为已交付（买家机器人会读取这个文件）
    notification["delivered"] = True
    notification["delivered_at"] = datetime.now().isoformat()
    
    notif_file = NOTIFICATIONS_DIR / f"{req_id}_new_bid.json"
    notif_file.write_text(json.dumps(notification, indent=2, ensure_ascii=False))
    
    return notification

def notify_on_evaluation(req_id: str, result: Dict) -> Dict:
    """评标完成时通知买家机器人"""
    if not BUYER_BOT_CONFIG["notify_on_evaluation"]:
        return {"skipped": True, "reason": "评标通知未启用"}
    
    notification = create_notification(req_id, "evaluation", result)
    
    # 格式化通知内容
    notification["message"] = format_evaluation_notification(req_id, result)
    
    # 标记为已交付
    notification["delivered"] = True
    notification["delivered_at"] = datetime.now().isoformat()
    
    notif_file = NOTIFICATIONS_DIR / f"{req_id}_evaluation.json"
    notif_file.write_text(json.dumps(notification, indent=2, ensure_ascii=False))
    
    return notification

def notify_on_winner(req_id: str, winner: Dict) -> Dict:
    """确认中标时通知买家机器人"""
    if not BUYER_BOT_CONFIG["notify_on_winner"]:
        return {"skipped": True, "reason": "中标通知未启用"}
    
    notification = create_notification(req_id, "winner", winner)
    
    # 格式化通知内容
    notification["message"] = format_winner_notification(req_id, winner)
    
    # 标记为已交付
    notification["delivered"] = True
    notification["delivered_at"] = datetime.now().isoformat()
    
    notif_file = NOTIFICATIONS_DIR / f"{req_id}_winner.json"
    notif_file.write_text(json.dumps(notification, indent=2, ensure_ascii=False))
    
    # 同时更新需求状态
    req_file = REQUIREMENTS_DIR / f"{req_id}.json"
    if req_file.exists():
        req = json.loads(req_file.read_text())
        req["status"] = "winner_confirmed"
        req["winner"] = winner
        req["winner_confirmed_at"] = datetime.now().isoformat()
        req_file.write_text(json.dumps(req, indent=2, ensure_ascii=False))
    
    return notification

def get_pending_notifications() -> list:
    """获取待处理的通知"""
    NOTIFICATIONS_DIR.mkdir(parents=True, exist_ok=True)
    
    pending = []
    for notif_file in NOTIFICATIONS_DIR.glob("*.json"):
        notification = json.loads(notif_file.read_text())
        if not notification.get("delivered", False):
            pending.append(notification)
    
    return pending

def mark_notification_delivered(notification_id: str):
    """标记通知为已交付"""
    for notif_file in NOTIFICATIONS_DIR.glob("*.json"):
        notification = json.loads(notif_file.read_text())
        if notification.get("notification_id") == notification_id:
            notification["delivered"] = True
            notification["delivered_at"] = datetime.now().isoformat()
            notif_file.write_text(json.dumps(notification, indent=2, ensure_ascii=False))
            return True
    return False

def confirm_winner(req_id: str, rank: int = 1) -> Dict:
    """确认中标供应商"""
    # 加载评标结果
    result_file = REQUIREMENTS_DIR / f"{req_id}_result.json"
    if not result_file.exists():
        return {"error": f"未找到评标结果：{req_id}"}
    
    result = json.loads(result_file.read_text())
    top3 = result.get("top3", [])
    
    if not top3:
        return {"error": "没有投标记录"}
    
    if rank > len(top3):
        return {"error": f"无效排名：{rank}（只有{len(top3)}个投标）"}
    
    winner = top3[rank - 1]
    
    # 创建中标通知
    notification = notify_on_winner(req_id, winner)
    
    return {
        "success": True,
        "req_id": req_id,
        "winner": winner,
        "notification": notification
    }

def main():
    import argparse
    
    parser = argparse.ArgumentParser(description="OW Buyer 中标提醒系统")
    parser.add_argument("action", choices=["new-bid", "evaluate", "confirm", "pending", "list"])
    parser.add_argument("--req-id", help="需求ID")
    parser.add_argument("--bid-json", help="投标JSON")
    parser.add_argument("--rank", type=int, default=1, help="中标排名（默认第1名）")
    
    args = parser.parse_args()
    
    if args.action == "new-bid":
        if not args.req_id or not args.bid_json:
            print("需要 --req-id 和 --bid-json")
            return
        bid = json.loads(args.bid_json)
        result = notify_on_new_bid(args.req_id, bid)
        print(result.get("message", "通知已创建"))
    
    elif args.action == "evaluate":
        if not args.req_id:
            print("需要 --req-id")
            return
        # 先执行评标
        from evaluate import evaluate_bids
        result = evaluate_bids(args.req_id)
        if "error" in result:
            print(f"❌ {result['error']}")
            return
        # 通知买家机器人
        notification = notify_on_evaluation(args.req_id, result)
        print(notification.get("message", "评标通知已创建"))
    
    elif args.action == "confirm":
        if not args.req_id:
            print("需要 --req-id")
            return
        result = confirm_winner(args.req_id, args.rank)
        if "error" in result:
            print(f"❌ {result['error']}")
        else:
            print(result["notification"].get("message", "中标确认通知已创建"))
    
    elif args.action == "pending":
        pending = get_pending_notifications()
        print(f"待处理通知: {len(pending)} 个")
        for n in pending:
            print(f"  - {n['notification_id']}: {n['type']} ({n['req_id']})")
    
    elif args.action == "list":
        NOTIFICATIONS_DIR.mkdir(parents=True, exist_ok=True)
        notifications = []
        for notif_file in NOTIFICATIONS_DIR.glob("*.json"):
            notifications.append(json.loads(notif_file.read_text()))
        print(f"所有通知: {len(notifications)} 个")
        for n in notifications:
            status = "✅" if n.get("delivered") else "⏳"
            print(f"  {status} {n['type']}: {n['req_id']} ({n['timestamp']})")

if __name__ == "__main__":
    main()

path: scripts/publish.py
content: #!/usr/bin/env python3
"""
发布采购需求到全球网络
通过 OW API 发布到 OW 社区
"""

import json
import pathlib
import sys
import uuid
import urllib.request
from datetime import datetime, timedelta

STATE_DIR = pathlib.Path(__file__).resolve().parent.parent / "state"
REQ_DIR = STATE_DIR / "requirements"

# OW API URL - 可通过环境变量配置，默认使用 HTTPS
import os
OW_API_URL = os.environ.get("OW_API_URL", "https://www.owshanghai.com/api/posts")

def generate_req_id() -> str:
    """生成需求ID"""
    date_part = datetime.now().strftime("%Y%m%d")
    unique_part = uuid.uuid4().hex[:6]
    return f"REQ-{date_part}-{unique_part}"

def publish_requirement(
    item: str,
    spec: str = "",
    quantity: int = 1,
    budget_max: float = None,
    deadline_hours: int = 24,
    buyer_name: str = "小恩",
    buyer_id: str = "buyer-default"
) -> dict:
    """发布采购需求"""
    
    req_id = generate_req_id()
    deadline = datetime.now() + timedelta(hours=deadline_hours)
    
    requirement = {
        "type": "procurement_request",
        "req_id": req_id,
        "item": item,
        "spec": spec,
        "quantity": quantity,
        "budget_max": budget_max,
        "deadline": deadline.isoformat() + "Z",
        "buyer": buyer_name,
        "buyer_id": buyer_id,
        "status": "open",
        "created_at": datetime.now().isoformat() + "Z"
    }
    
    # 保存到本地
    REQ_DIR.mkdir(parents=True, exist_ok=True)
    req_file = REQ_DIR / f"{req_id}.json"
    req_file.write_text(json.dumps(requirement, indent=2, ensure_ascii=False))
    
    # 发布到 OW API (使用 urllib，无需外部 CLI)
    try:
        payload = {
            "agent_id": buyer_id,
            "agent_name": buyer_name,
            "content": f"【求购】{item} {spec}，数量{quantity}，预算{budget_max}元，截止{deadline.strftime('%Y-%m-%d %H:%M')}",
            "type": "request"
        }
        
        data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
        req = urllib.request.Request(
            OW_API_URL,
            data=data,
            headers={"Content-Type": "application/json"},
            method="POST"
        )
        
        with urllib.request.urlopen(req, timeout=30) as response:
            result = json.loads(response.read().decode('utf-8'))
            if result.get('success'):
                requirement["published"] = True
                requirement["post_id"] = result.get('post_id')
            else:
                requirement["published"] = False
                requirement["publish_error"] = result.get('error', 'Unknown error')
    except Exception as e:
        requirement["published"] = False
        requirement["publish_error"] = str(e)
    
    # 更新保存
    req_file.write_text(json.dumps(requirement, indent=2, ensure_ascii=False))
    
    return requirement

def format_output(req: dict) -> str:
    """格式化输出"""
    output = f"🛒 采购需求已发布\n\n"
    output += f"需求ID: {req['req_id']}\n"
    output += f"品名: {req['item']}\n"
    if req['spec']:
        output += f"规格: {req['spec']}\n"
    output += f"数量: {req['quantity']}\n"
    if req['budget_max']:
        output += f"预算上限: ¥{req['budget_max']}\n"
    output += f"截止时间: {req['deadline']}\n"
    output += f"发布状态: {'✅ 已发布到全球网络' if req.get('published') else '⚠️ 本地保存'}\n"
    output += f"\n全球 OpenClaw 机器人将前来投标，请等待..."
    return output

def main():
    # 解析参数
    args = sys.argv[1:]
    
    if not args:
        print("用法: python publish.py <品名> [规格] [数量] [预算上限] [截止小时数]")
        print("示例: python publish.py 幽灵庄园红酒 '750ml,2018年份' 1 5000 24")
        sys.exit(1)
    
    item = args[0]
    spec = args[1] if len(args) > 1 else ""
    quantity = int(args[2]) if len(args) > 2 else 1
    budget_max = float(args[3]) if len(args) > 3 else None
    deadline_hours = int(args[4]) if len(args) > 4 else 24
    
    req = publish_requirement(
        item=item,
        spec=spec,
        quantity=quantity,
        budget_max=budget_max,
        deadline_hours=deadline_hours
    )
    
    print(format_output(req))

if __name__ == "__main__":
    main()

path: scripts/receive.py
content: #!/usr/bin/env python3
"""
接收并存储投标
验证投标格式并保存到本地
收到新投标时自动通知买家机器人
展示卖家信用信息（可选功能）
"""

import json
import pathlib
from datetime import datetime

STATE_DIR = pathlib.Path(__file__).resolve().parent.parent / "state"
BIDS_DIR = STATE_DIR / "bids"

# 信用系统为可选功能，不修改 sys.path
CREDIT_SYSTEM_ENABLED = False
get_seller_profile = None
format_seller_credit_display = None
get_credit_warning = None

def get_simple_credit_display(seller_id: str) -> str:
    """简化版信用信息显示（当信用系统未安装时）"""
    return "📊 信用系统未安装\n   安装：npx skills add Enze-dai/ow-skills/ow-credit"

def validate_bid(bid: dict) -> tuple[bool, str]:
    """验证投标格式"""
    required = ["bid_id", "req_id", "supplier", "price", "delivery"]
    
    for field in required:
        if field not in bid:
            return False, f"缺少必填字段：{field}"
    
    if "name" not in bid.get("supplier", {}):
        return False, "缺少供应商名称"
    
    if "amount" not in bid.get("price", {}):
        return False, "缺少投标价格"
    
    if "time_days" not in bid.get("delivery", {}):
        return False, "缺少到货时间"
    
    return True, "验证通过"

def receive_bid(bid_json: str, notify_buyer: bool = True) -> dict:
    """接收并存储投标"""
    try:
        bid = json.loads(bid_json)
    except json.JSONDecodeError as e:
        return {"error": f"JSON 格式错误：{e}"}
    
    # 验证
    valid, msg = validate_bid(bid)
    if not valid:
        return {"error": msg}
    
    req_id = bid["req_id"]
    bid_id = bid["bid_id"]
    
    # 保存
    bid_dir = BIDS_DIR / req_id
    bid_dir.mkdir(parents=True, exist_ok=True)
    
    bid_file = bid_dir / f"{bid_id}.json"
    bid["received_at"] = datetime.now().isoformat()
    bid_file.write_text(json.dumps(bid, indent=2, ensure_ascii=False))
    
    result = {
        "success": True,
        "bid_id": bid_id,
        "req_id": req_id,
        "supplier": bid["supplier"]["name"],
        "price": bid["price"]["amount"]
    }
    
    # 🔔 通知买家机器人（新投标提醒）
    if notify_buyer:
        try:
            from notify import notify_on_new_bid
            notification = notify_on_new_bid(req_id, bid)
            if notification.get("delivered"):
                result["notification_sent"] = True
                result["notification_type"] = "new_bid"
        except Exception as e:
            result["notification_error"] = str(e)
    
    # 🛡️ 获取卖家信用信息
    if CREDIT_SYSTEM_ENABLED:
        try:
            seller_id = bid["supplier"].get("agent_id", bid["supplier"]["name"])
            result["seller_credit"] = format_seller_credit_display(seller_id)
            result["seller_credit_warning"] = get_credit_warning(seller_id, "seller")
        except Exception as e:
            result["credit_error"] = str(e)
    
    return result

def list_bids(req_id: str) -> list:
    """列出某需求的所有投标"""
    bid_dir = BIDS_DIR / req_id
    if not bid_dir.exists():
        return []
    
    bids = []
    for bid_file in bid_dir.glob("*.json"):
        bid = json.loads(bid_file.read_text())
        bids.append(bid)
    
    return bids

def main():
    if len(sys.argv) < 2:
        print("用法：python receive.py <bid_json>")
        print("   或：python receive.py list <req_id>")
        sys.exit(1)
    
    if sys.argv[1] == "list" and len(sys.argv) > 2:
        req_id = sys.argv[2]
        bids = list_bids(req_id)
        print(f"需求 {req_id} 共有 {len(bids)} 个投标:")
        for bid in bids:
            print(f"  - {bid['bid_id']}: {bid['supplier']['name']} ¥{bid['price']['amount']}")
    else:
        bid_json = sys.argv[1]
        result = receive_bid(bid_json)
        if "error" in result:
            print(f"❌ {result['error']}")
        else:
            print(f"✅ 投标已接收: {result['supplier']} - ¥{result['price']}")
            if result.get("notification_sent"):
                print(f"🔔 已通知买家机器人")

if __name__ == "__main__":
    main()

path: state/bids/REQ-20260330-ca9348/BID-20260330-001.json
content: {
  "type": "procurement_bid",
  "bid_id": "BID-20260330-001",
  "req_id": "REQ-20260330-ca9348",
  "supplier": {
    "name": "红酒坊精品酒行",
    "agent_id": "agent-winecellar",
    "endpoint": "http://winecellar:8787",
    "contact": "客服热线 400-xxx-xxxx"
  },
  "price": {
    "amount": 2800,
    "currency": "CNY",
    "includes_shipping": true,
    "shipping_cost": 0
  },
  "auth_docs": [
    {
      "type": "business_license",
      "name": "企业营业执照",
      "url": "https://example.com/license.jpg",
      "verified": false
    },
    {
      "type": "agency_cert",
      "name": "幽灵庄园代理权证明",
      "url": "https://example.com/agency.jpg",
      "verified": false
    },
    {
      "type": "auth_letter",
      "name": "原厂授权书",
      "url": "https://example.com/auth.jpg",
      "verified": false
    }
  ],
  "delivery": {
    "time_days": 3,
    "method": "顺丰快递",
    "tracking_available": true,
    "insurance": true
  },
  "reputation": {
    "total_transactions": 50,
    "success_rate": 0.95,
    "disputes": 0,
    "complaints": 0,
    "platform_verified": true,
    "rating": 4.8,
    "reviews_url": "https://example.com/reviews/winecellar"
  },
  "warranty": {
    "return_policy": "7天无理由退货",
    "refund_policy": "质量问题全额退款",
    "support_contact": "400-xxx-xxxx"
  },
  "signature": "模拟签名_红酒坊",
  "timestamp": "2026-03-30T04:00:00Z"
}

path: state/bids/REQ-20260330-ca9348/BID-20260330-002.json
content: {
  "type": "procurement_bid",
  "bid_id": "BID-20260330-002",
  "req_id": "REQ-20260330-ca9348",
  "supplier": {
    "name": "醇香酒业旗舰店",
    "agent_id": "agent-chunxiang",
    "endpoint": "http://chunxiang:8787",
    "contact": "客服微信: chunxiang_wine"
  },
  "price": {
    "amount": 3200,
    "currency": "CNY",
    "includes_shipping": true,
    "shipping_cost": 0
  },
  "auth_docs": [
    {
      "type": "business_license",
      "name": "企业营业执照",
      "url": "https://example.com/chunxiang_license.jpg"
    },
    {
      "type": "agency_cert",
      "name": "产品代理权证明",
      "url": "https://example.com/chunxiang_agency.jpg"
    },
    {
      "type": "quality_report",
      "name": "产品质检报告",
      "url": "https://example.com/chunxiang_quality.jpg"
    },
    {
      "type": "import_doc",
      "name": "进口报关单",
      "url": "https://example.com/chunxiang_import.jpg"
    }
  ],
  "delivery": {
    "time_days": 5,
    "method": "京东物流",
    "tracking_available": true,
    "insurance": true
  },
  "reputation": {
    "total_transactions": 20,
    "success_rate": 0.90,
    "disputes": 1,
    "complaints": 0,
    "platform_verified": true,
    "rating": 4.5
  },
  "warranty": {
    "return_policy": "签收后7天内可退",
    "refund_policy": "假一赔十"
  },
  "signature": "模拟签名_醇香",
  "timestamp": "2026-03-30T05:00:00Z"
}

path: state/bids/REQ-20260330-ca9348/BID-20260330-003.json
content: {
  "type": "procurement_bid",
  "bid_id": "BID-20260330-003",
  "req_id": "REQ-20260330-ca9348",
  "supplier": {
    "name": "名酒折扣店",
    "agent_id": "agent-discount",
    "endpoint": "http://discount:8787",
    "contact": "QQ: 12345678"
  },
  "price": {
    "amount": 2500,
    "currency": "CNY",
    "includes_shipping": true,
    "shipping_cost": 0
  },
  "auth_docs": [
    {
      "type": "business_license",
      "name": "个体工商户营业执照",
      "url": "https://example.com/discount_license.jpg"
    }
  ],
  "delivery": {
    "time_days": 7,
    "method": "圆通快递",
    "tracking_available": true,
    "insurance": false
  },
  "reputation": {
    "total_transactions": 5,
    "success_rate": 0.80,
    "disputes": 0,
    "complaints": 0,
    "platform_verified": false,
    "rating": 4.0
  },
  "warranty": {
    "return_policy": "不支持退货",
    "refund_policy": "质量问题协商解决"
  },
  "signature": "模拟签名_折扣店",
  "timestamp": "2026-03-30T06:00:00Z"
}

path: state/bids/REQ-20260330-ca9348/BID-20260330-004.json
content: {
  "type": "procurement_bid",
  "bid_id": "BID-20260330-004",
  "req_id": "REQ-20260330-ca9348",
  "supplier": {
    "name": "欧洲酒庄直邮",
    "agent_id": "agent-eurowine",
    "endpoint": "http://eurowine:8787",
    "contact": "Email: [REDACTED_SECRET]"
  },
  "price": {
    "amount": 3500,
    "currency": "CNY",
    "includes_shipping": true,
    "shipping_cost": 200
  },
  "auth_docs": [
    {
      "type": "business_license",
      "name": "欧盟商业注册证书",
      "url": "https://example.com/euro_license.jpg"
    },
    {
      "type": "agency_cert",
      "name": "幽灵庄园官方代理证书",
      "url": "https://example.com/euro_agency.jpg"
    },
    {
      "type": "auth_letter",
      "name": "庄园主亲笔签名授权",
      "url": "https://example.com/euro_auth.jpg"
    },
    {
      "type": "quality_report",
      "name": "原产地认证证书",
      "url": "https://example.com/euro_origin.jpg"
    },
    {
      "type": "import_doc",
      "name": "海关进口完税证明",
      "url": "https://example.com/euro_customs.jpg"
    }
  ],
  "delivery": {
    "time_days": 14,
    "method": "国际快递 + 国内顺丰",
    "tracking_available": true,
    "insurance": true
  },
  "reputation": {
    "total_transactions": 100,
    "success_rate": 0.98,
    "disputes": 0,
    "complaints": 0,
    "platform_verified": true,
    "rating": 4.9
  },
  "warranty": {
    "return_policy": "30天无理由退货",
    "refund_policy": "假一赔百 + 全额退款"
  },
  "signature": "模拟签名_欧洲酒庄",
  "timestamp": "2026-03-30T07:00:00Z"
}

path: state/bids/REQ-TEST-001/BID-TEST-001.json
content: {
  "bid_id": "BID-TEST-001",
  "req_id": "REQ-TEST-001",
  "supplier": {
    "name": "幽灵庄园旗舰店",
    "agent_id": "seller-001"
  },
  "price": {
    "amount": 2800,
    "currency": "CNY"
  },
  "auth_docs": [
    {"type": "business_license", "name": "营业执照"},
    {"type": "agency_cert", "name": "代理权证明"}
  ],
  "images": [
    "https://example.com/wine1.jpg",
    "https://example.com/wine2.jpg"
  ],
  "video": "https://example.com/wine.mp4",
  "delivery": {
    "time_days": 3,
    "method": "顺丰快递"
  },
  "reputation": {
    "total_transactions": 50,
    "success_rate": 0.98,
    "disputes": 0,
    "platform_verified": true
  },
  "shop_links": [
    {
      "platform": "淘宝",
      "url": "https://shop123456.taobao.com"
    }
  ]
}

path: state/notifications/REQ-TEST-001_evaluation.json
content: {
  "notification_id": "NOTIF-20260401154759",
  "req_id": "REQ-TEST-001",
  "type": "evaluation",
  "timestamp": "2026-04-01T15:47:59.787934",
  "data": {
    "req_id": "REQ-TEST-001",
    "total_bids": 1,
    "evaluated_at": "2026-04-01T15:47:59.780400",
    "top3": [
      {
        "bid_id": "BID-TEST-001",
        "supplier": "幽灵庄园旗舰店",
        "price": 2800,
        "price_score": 50.0,
        "media_score": 15,
        "auth_score": 8.0,
        "delivery_days": 3,
        "delivery_score": 5.0,
        "reputation_score": 8.940000000000001,
        "total_score": 86.94,
        "auth_docs": [
          "营业执照",
          "代理权证明"
        ],
        "images": [
          "https://example.com/wine1.jpg",
          "https://example.com/wine2.jpg"
        ],
        "video": "https://example.com/wine.mp4",
        "reputation": {
          "total_transactions": 50,
          "success_rate": 0.98,
          "disputes": 0,
          "platform_verified": true
        },
        "shop_links": [
          {
            "platform": "淘宝",
            "url": "https://shop123456.taobao.com"
          }
        ]
      }
    ],
    "all_results": [
      {
        "bid_id": "BID-TEST-001",
        "supplier": "幽灵庄园旗舰店",
        "price": 2800,
        "price_score": 50.0,
        "media_score": 15,
        "auth_score": 8.0,
        "delivery_days": 3,
        "delivery_score": 5.0,
        "reputation_score": 8.940000000000001,
        "total_score": 86.94,
        "auth_docs": [
          "营业执照",
          "代理权证明"
        ],
        "images": [
          "https://example.com/wine1.jpg",
          "https://example.com/wine2.jpg"
        ],
        "video": "https://example.com/wine.mp4",
        "reputation": {
          "total_transactions": 50,
          "success_rate": 0.98,
          "disputes": 0,
          "platform_verified": true
        },
        "shop_links": [
          {
            "platform": "淘宝",
            "url": "https://shop123456.taobao.com"
          }
        ]
      }
    ]
  },
  "delivered": true,
  "delivered_at": "2026-04-01T15:47:59.788383",
  "message": "\n📊 评标完成提醒 | Evaluation Complete\n\n需求ID: REQ-TEST-001\n投标总数: 1\n评标时间: 2026-04-01T15:47:59.780400\n\n🏆 前三名供应商：\n\n🏆 第1名：幽灵庄园旗舰店 | 综合得分 86.94\n   ├─ 价格：¥2800 (得分 50.0/50)\n   ├─ 真品：2项 (得分 8.0/20)\n   ├─ 时效：3天 (得分 5.0/10)\n   └─ 信誉：50笔 (得分 8.9/20)\n\n\n⚠️ 请确认中标供应商，回复：\n   \"确认中标 REQ-xxx 第1名\"\n   或查看详情：\"查看投标详情 REQ-xxx\"\n"
}

path: state/notifications/REQ-TEST-001_winner.json
content: {
  "notification_id": "NOTIF-20260401154815",
  "req_id": "REQ-TEST-001",
  "type": "winner",
  "timestamp": "2026-04-01T15:48:15.261480",
  "data": {
    "bid_id": "BID-TEST-001",
    "supplier": "幽灵庄园旗舰店",
    "price": 2800,
    "price_score": 50.0,
    "media_score": 15,
    "auth_score": 8.0,
    "delivery_days": 3,
    "delivery_score": 5.0,
    "reputation_score": 8.940000000000001,
    "total_score": 86.94,
    "auth_docs": [
      "营业执照",
      "代理权证明"
    ],
    "images": [
      "https://example.com/wine1.jpg",
      "https://example.com/wine2.jpg"
    ],
    "video": "https://example.com/wine.mp4",
    "reputation": {
      "total_transactions": 50,
      "success_rate": 0.98,
      "disputes": 0,
      "platform_verified": true
    },
    "shop_links": [
      {
        "platform": "淘宝",
        "url": "https://shop123456.taobao.com"
      }
    ]
  },
  "delivered": true,
  "delivered_at": "2026-04-01T15:48:15.262110",
  "message": "\n🎉 中标确认提醒 | Winner Confirmed\n\n需求ID: REQ-TEST-001\n中标供应商: 幽灵庄园旗舰店\n中标价格: ¥2800\n综合得分: 86.94\n\n🔗 下一步：\n1. 点击店铺链接下单：待提供\n2. 或回复：\"获取店铺链接\"\n3. 完成交易后：\"确认收货 REQ-xxx\"\n\n💡 提醒：实际交易在卖家店铺进行，本平台仅匹配供应商\n"
}

path: state/requirements/REQ-20260330-ca9348.json
content: {
  "type": "procurement_request",
  "req_id": "REQ-20260330-ca9348",
  "item": "幽灵庄园红酒",
  "spec": "750ml, 2018年份",
  "quantity": 1,
  "budget_max": 5000.0,
  "deadline": "2026-03-31T12:08:06.969396Z",
  "buyer": "小恩",
  "buyer_endpoint": "http://localhost:8787",
  "status": "open",
  "created_at": "2026-03-30T12:08:06.969546Z",
  "published": false,
  "publish_error": "\n✗ Error: Authentication required\n\nHow to fix:\n  → Run 'claw.events verify' to complete authentication\n  → Or run 'claw.events login --user <name>' to start authentication\n  → Or use --token <jwt> for temporary authentication\n\nDocumentation:\n  • https://claw.events/docs\n  • https://claw.events/docs/registration\n\n"
}

path: state/requirements/REQ-20260330-ca9348_result.json
content: {
  "req_id": "REQ-20260330-ca9348",
  "total_bids": 4,
  "evaluated_at": "2026-03-30T12:11:05.225758",
  "top3": [
    {
      "bid_id": "BID-20260330-001",
      "supplier": "红酒坊精品酒行",
      "price": 2800,
      "price_score": 44.642857142857146,
      "auth_score": 11.0,
      "delivery_days": 3,
      "delivery_score": 10.0,
      "reputation_score": 17.7,
      "total_score": 83.34,
      "auth_docs": [
        "企业营业执照",
        "幽灵庄园代理权证明",
        "原厂授权书"
      ],
      "reputation": {
        "total_transactions": 50,
        "success_rate": 0.95,
        "disputes": 0,
        "complaints": 0,
        "platform_verified": true,
        "rating": 4.8,
        "reviews_url": "https://example.com/reviews/winecellar"
      }
    },
    {
      "bid_id": "BID-20260330-002",
      "supplier": "醇香酒业旗舰店",
      "price": 3200,
      "price_score": 39.0625,
      "auth_score": 14.0,
      "delivery_days": 5,
      "delivery_score": 6.0,
      "reputation_score": 14.4,
      "total_score": 73.46,
      "auth_docs": [
        "企业营业执照",
        "产品代理权证明",
        "产品质检报告",
        "进口报关单"
      ],
      "reputation": {
        "total_transactions": 20,
        "success_rate": 0.9,
        "disputes": 1,
        "complaints": 0,
        "platform_verified": true,
        "rating": 4.5
      }
    },
    {
      "bid_id": "BID-20260330-004",
      "supplier": "欧洲酒庄直邮",
      "price": 3500,
      "price_score": 35.714285714285715,
      "auth_score": 17.0,
      "delivery_days": 14,
      "delivery_score": 2.142857142857143,
      "reputation_score": 17.880000000000003,
      "total_score": 72.74,
      "auth_docs": [
        "欧盟商业注册证书",
        "幽灵庄园官方代理证书",
        "庄园主亲笔签名授权",
        "原产地认证证书",
        "海关进口完税证明"
      ],
      "reputation": {
        "total_transactions": 100,
        "success_rate": 0.98,
        "disputes": 0,
        "complaints": 0,
        "platform_verified": true,
        "rating": 4.9
      }
    }
  ],
  "all_results": [
    {
      "bid_id": "BID-20260330-001",
      "supplier": "红酒坊精品酒行",
      "price": 2800,
      "price_score": 44.642857142857146,
      "auth_score": 11.0,
      "delivery_days": 3,
      "delivery_score": 10.0,
      "reputation_score": 17.7,
      "total_score": 83.34,
      "auth_docs": [
        "企业营业执照",
        "幽灵庄园代理权证明",
        "原厂授权书"
      ],
      "reputation": {
        "total_transactions": 50,
        "success_rate": 0.95,
        "disputes": 0,
        "complaints": 0,
        "platform_verified": true,
        "rating": 4.8,
        "reviews_url": "https://example.com/reviews/winecellar"
      }
    },
    {
      "bid_id": "BID-20260330-002",
      "supplier": "醇香酒业旗舰店",
      "price": 3200,
      "price_score": 39.0625,
      "auth_score": 14.0,
      "delivery_days": 5,
      "delivery_score": 6.0,
      "reputation_score": 14.4,
      "total_score": 73.46,
      "auth_docs": [
        "企业营业执照",
        "产品代理权证明",
        "产品质检报告",
        "进口报关单"
      ],
      "reputation": {
        "total_transactions": 20,
        "success_rate": 0.9,
        "disputes": 1,
        "complaints": 0,
        "platform_verified": true,
        "rating": 4.5
      }
    },
    {
      "bid_id": "BID-20260330-004",
      "supplier": "欧洲酒庄直邮",
      "price": 3500,
      "price_score": 35.714285714285715,
      "auth_score": 17.0,
      "delivery_days": 14,
      "delivery_score": 2.142857142857143,
      "reputation_score": 17.880000000000003,
      "total_score": 72.74,
      "auth_docs": [
        "欧盟商业注册证书",
        "幽灵庄园官方代理证书",
        "庄园主亲笔签名授权",
        "原产地认证证书",
        "海关进口完税证明"
      ],
      "reputation": {
        "total_transactions": 100,
        "success_rate": 0.98,
        "disputes": 0,
        "complaints": 0,
        "platform_verified": true,
        "rating": 4.9
      }
    },
    {
      "bid_id": "BID-20260330-003",
      "supplier": "名酒折扣店",
      "price": 2500,
      "price_score": 50.0,
      "auth_score": 4.0,
      "delivery_days": 7,
      "delivery_score": 4.285714285714286,
      "reputation_score": 6.800000000000001,
      "total_score": 65.09,
      "auth_docs": [
        "个体工商户营业执照"
      ],
      "reputation": {
        "total_transactions": 5,
        "success_rate": 0.8,
        "disputes": 0,
        "complaints": 0,
        "platform_verified": false,
        "rating": 4.0
      }
    }
  ]
}

path: state/requirements/REQ-TEST-001_result.json
content: {
  "req_id": "REQ-TEST-001",
  "total_bids": 1,
  "evaluated_at": "2026-04-01T15:47:59.780400",
  "top3": [
    {
      "bid_id": "BID-TEST-001",
      "supplier": "幽灵庄园旗舰店",
      "price": 2800,
      "price_score": 50.0,
      "media_score": 15,
      "auth_score": 8.0,
      "delivery_days": 3,
      "delivery_score": 5.0,
      "reputation_score": 8.940000000000001,
      "total_score": 86.94,
      "auth_docs": [
        "营业执照",
        "代理权证明"
      ],
      "images": [
        "https://example.com/wine1.jpg",
        "https://example.com/wine2.jpg"
      ],
      "video": "https://example.com/wine.mp4",
      "reputation": {
        "total_transactions": 50,
        "success_rate": 0.98,
        "disputes": 0,
        "platform_verified": true
      },
      "shop_links": [
        {
          "platform": "淘宝",
          "url": "https://shop123456.taobao.com"
        }
      ]
    }
  ],
  "all_results": [
    {
      "bid_id": "BID-TEST-001",
      "supplier": "幽灵庄园旗舰店",
      "price": 2800,
      "price_score": 50.0,
      "media_score": 15,
      "auth_score": 8.0,
      "delivery_days": 3,
      "delivery_score": 5.0,
      "reputation_score": 8.940000000000001,
      "total_score": 86.94,
      "auth_docs": [
        "营业执照",
        "代理权证明"
      ],
      "images": [
        "https://example.com/wine1.jpg",
        "https://example.com/wine2.jpg"
      ],
      "video": "https://example.com/wine.mp4",
      "reputation": {
        "total_transactions": 50,
        "success_rate": 0.98,
        "disputes": 0,
        "platform_verified": true
      },
      "shop_links": [
        {
          "platform": "淘宝",
          "url": "https://shop123456.taobao.com"
        }
      ]
    }
  ]
}

path: state/transactions/TX-20260330-001.json
content: {
  "tx_id": "TX-20260330-001",
  "req_id": "REQ-20260330-ca9348",
  "bid_id": "BID-20260330-001",
  "status": "pending_payment",
  "buyer": {
    "name": "小恩",
    "agent_id": "agent-4fc8ffe4bee8"
  },
  "supplier": {
    "name": "红酒坊精品酒行",
    "agent_id": "agent-winecellar",
    "contact": "客服热线 400-xxx-xxxx",
    "payment_accounts": {
      "alipay": "[REDACTED_SECRET]",
      "wechat": "winecellar_wx",
      "bank": "招商银行 6225 **** **** 1234"
    }
  },
  "item": {
    "name": "幽灵庄园红酒",
    "spec": "750ml, 2018年份",
    "quantity": 1
  },
  "amount": 2800,
  "currency": "CNY",
  "delivery": {
    "time_days": 3,
    "method": "顺丰快递",
    "insurance": true
  },
  "warranty": {
    "return_policy": "7天无理由退货",
    "refund_policy": "质量问题全额退款"
  },
  "created_at": "2026-03-30T04:11:30Z",
  "confirmed_at": "2026-03-30T04:11:45Z",
  "payment_method": "alipay",
  "payment_status": "pending",
  "payment_qrcode": "https://qr.alipay.com/btx00xxxWINECELLAR2800",
  "payment_url": "alipayqr://platformapi/startapp?appId=20000067&url=https://qr.alipay.com/btx00xxxWINECELLAR2800"
}

Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)