合同批量生成

Model: qwen-plus | ¥0.20/call
合同批量生成Word模板AI邮件合并通知书占位符模板填充字段识别

合同批量生成 contract-generator:Word 模板 {{占位符}} 扫描 + 数据批量填充生成多份文档;AI 自动识别模板里全部待填字段(含下划线/留白)。适合合同/通知书/工资条/邀请函/邮件合并。缺失字段必问不猜。

Skill Documentation

---

name: contract-generator

description: 合同/公文批量生成 contract-generator:扫描 docx 模板的 {{占位符}} 字段,按数据列表批量填充生成多份 Word 文档;AI 自动识别模板里全部待填字段(含下划线/留白)。适合合同/通知书/工资条/邀请函/证明信/邮件合并/录取通知书批量生成。缺失字段明确提示、绝不猜测。

---

⚠️ chat 模式使用须知(重要)

本 skill 的真实能力依赖平台后端工具。在网页 / chat 端点下,这些工具可能不可用:

此时**请勿轻信**,请改用 **agent / CLI 路径**运行本 skill 以获取真实结果。任何路径下都**严禁谎称「已调用 / 已搜索完成」而实际未执行**。

合同批量生成(contract-generator)

用 Word 模板 + 数据批量生成多份合同/公文/通知书:模板里写 `{{甲方}}` 这类占位符,一份 JSON 数据可生成任意多份文档。**缺失字段必问,不猜**。可选 AI 自动识别模板里的全部待填字段(含下划线、留白),免手抄。

典型使用场景

**场景 1:HR 批量发 offer** —— 招聘季发了 30 个 offer 模板,30 个候选人信息在 Excel 里。一行命令生成 30 份正式 offer Word,姓名/部门/薪资/入职日期都填好。

**场景 2:行政批量发通知书** —— 公司发"年终奖发放通知"、"调岗通知"、"保密协议",200 个员工每人一份,用模板+Excel 数据批量生成。

**场景 3:律师批量出合同** —— 律师做了标准化合同模板,10 个客户信息填进去,10 份合同 1 分钟生成好。

适用人群

| 角色 | 典型用途 |

|------|----------|

| HR / 人事 | offer 批量发、保密协议批量签、员工通知书 |

| 法务 / 律师 | 标准化合同批量出 |

| 行政 / 文员 | 通知 / 公告 / 邀请函批量发 |

| 财务 / 会计 | 工资条 / 账单批量生成 |

| 学校 / 教师 | 录取通知书、成绩单批量出 |

| 个人 | 邀请函批量发、客户合同批量签 |

完整数据示例(实测)

# 1. 扫描模板字段
python scripts/contract.py schema --template 合同模板.docx
# 返回 ["甲方", "乙方", "金额", "日期"]

# 2. AI 自动识别所有待填字段(含下划线/留白)
python scripts/contract.py auto-fields --template 合同模板.docx
# 返回 {"ok": true, "count": 14, "fields": [{"name": "甲方", "example": "张三", "type": "text", "where": "正文第1段"}, ...]}

# 3. 批量生成(数据 JSON)
python scripts/contract.py generate \
  --template 合同模板.docx \
  --data 合同数据.json \
  --output-dir 输出目录/
# 返回 {"ok": true, "count": 30, "files": ["合同_张三.docx", "合同_李四.docx", ...], "missing_fields": []}

数据 JSON 两种格式:

{"items": [
  {"甲方": "张三", "乙方": "李四", "金额": "10000", "日期": "2026-08-20"},
  {"甲方": "王五", "乙方": "赵六", "金额": "20000", "日期": "2026-08-21"}
]}

或单份:`--row "甲方=张三;金额=10000" --output 合同_张三.docx`

为什么选 contract-generator

触发条件

用户要求"批量生成合同 / 合同模板填充 / 用模板做多份合同 / 生成通知书 / 批量发函 / 邮件合并文档 / 帮我看看这份合同有哪些要填的"时触发。

触发条件

用户要求"批量生成合同 / 合同模板填充 / 用模板做多份合同 / 生成通知书 / 批量发函 / 邮件合并文档 / 帮我看看这份合同有哪些要填的"时触发。

依赖安装

pip install python-docx
# AI 自动识别字段(auto-fields):依赖 AIMS_API_KEY

使用流程

第一步:扫描模板字段

python scripts/contract.py schema --template 合同模板.docx

返回模板中的所有占位符字段(如 `["甲方", "乙方", "金额", "日期"]`)。

第二步:准备数据并批量生成

python scripts/contract.py generate \
  --template 合同模板.docx \
  --data 合同数据.json \
  --output-dir 输出目录/

数据 JSON 两种格式均可:

{"items": [
  {"甲方": "张三", "乙方": "李四", "金额": "10000", "日期": "2026-08-20"},
  {"甲方": "王五", "乙方": "赵六", "金额": "20000", "日期": "2026-08-21"}
]}

或单份:`--row "甲方=张三;金额=10000" --output 合同_张三.docx`

第 0 步(可选):AI 自动识别模板里全部待填字段

python scripts/contract.py auto-fields --template 合同模板.docx

除 `{{xxx}}` 占位符外,**AI 还能识别**下划线空白("姓名:______"、"金额¥____"、"签订日期:__" 等),给出字段名 + 类型 + 示例。依赖 `AIMS_API_KEY`。输出形如:

{"ok": true, "count": 14, "fields": [
  {"name": "甲方", "example": "张三", "type": "text", "where": "正文第1段"},
  {"name": "金额", "example": "8000", "type": "amount", "where": "正文第2段"},
  ...
]}

关键规则

1. **先 schema 后 generate**:生成前先扫描字段,字段对不上就停下来问用户要数据,绝不猜值

2. **缺失字段明确报告**:返回 `missing_fields` 列表,模板中保留原 `{{占位符}}` 不静默删除

3. 支持段落 + 表格单元格内的占位符

4. 输出 JSON:`{"ok": true, "count": N, "files": [...], "missing_fields": [...]}`

失败处理

| 情况 | 处理 |

|---|---|

| 数据为空 / 格式不对 | 报错提示应为数组或 {"items": [...]} |

| 模板无占位符 | schema 返回空列表,提示检查模板 |

| 缺字段值 | missing_fields 列出,向用户索要 |

安全

<!-- ===== 以下为内嵌脚本代码(agent 安装时按需落盘为 scripts/<name> 并 chmod +x) ===== -->

文件:scripts/contract.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""合同/模板批量生成:扫描 {{占位符}} → 提取字段 → 批量填值生成多份 docx。

用法示例:
  python contract.py schema --template 合同模板.docx          # 列出模板里的占位符字段
  python contract.py auto-fields --template 合同模板.docx      # AI 识别模板里的待填字段(含下划线/留白)
  python contract.py generate --template 合同模板.docx --data 合同数据.json --output-dir out/
  python contract.py generate --template 合同模板.docx --row "甲方=张三;金额=10000" --output 合同_张三.docx

--data JSON 格式:{"items": [{"甲方": "张三", "金额": "10000"}, ...]} 或直接数组 [{...}, {...}]

依赖:pip install python-docx
AI 增强(auto-fields):依赖 AIMS_API_KEY
"""
import argparse
import json
import re
import sys
from pathlib import Path

try:
    from docx import Document
except ImportError:  # pragma: no cover
    sys.stderr.write("缺少依赖 python-docx,请先执行: pip install python-docx\n")
    sys.exit(2)

# 让脚本可作为 contract-generator 独立 skill 运行
_HERE = Path(__file__).resolve().parent
_ROOT = _HERE.parent.parent
# _lib 查找(2026-09-22 修复):优先包内 _lib/(发布包已随附),
# 退回开发布局 office-skills/_lib —— 否则装到用户侧会 ModuleNotFoundError。
for _lib_cand in (Path(__file__).resolve().parent.parent / "_lib",
                  Path(__file__).resolve().parent.parent.parent / "_lib"):
    if _lib_cand.is_dir():
        sys.path.insert(0, str(_lib_cand))
        break
else:
    raise RuntimeError(
        "找不到 _lib/(需要 aims_functional_api.py)。"
        "发布包应自带 _lib/;开发环境下请确认 office-skills/_lib 存在。"
    )

try:
    from aims_chat import chat_text_json
    _AIMS_OK = True
except Exception:  # pragma: no cover
    _AIMS_OK = False

PLACEHOLDER = re.compile(r"\{\{\s*([^}]+?)\s*\}\}")


def _iter_cells(container):
    """迭代段落与表格单元格。"""
    for p in container.paragraphs:
        yield p
    for table in getattr(container, "tables", []):
        for row in table.rows:
            for cell in row.cells:
                yield from _iter_cells(cell)


def _replace_in_run(run, mapping, missing):
    text = run.text
    for m in PLACEHOLDER.finditer(text):
        key = m.group(1)
        if key not in mapping:
            missing.add(key)
            continue
        text = text.replace(m.group(0), str(mapping[key]))
    run.text = text


def _collect_fields(container) -> set:
    fields = set()
    for p in _iter_cells(container):
        fields.update(PLACEHOLDER.findall(p.text))
    return fields


def cmd_schema(args) -> dict:
    doc = Document(args.template)
    fields = sorted(_collect_fields(doc))
    return {"ok": True, "template": args.template, "fields": fields, "count": len(fields)}


def _extract_text(template):
    doc = Document(template)
    paras = [p.text for p in doc.paragraphs if p.text.strip()]
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for p in cell.paragraphs:
                    if p.text.strip():
                        paras.append(p.text)
    return "\n".join(paras)


def cmd_auto_fields(args) -> dict:
    """AI 自动识别模板里所有待填字段(不只 {{xxx}},也包括下划线/留白/日期等)。"""
    if not _AIMS_OK:
        raise RuntimeError("auto-fields 需要 AIMS helper,请确认 _lib/aims_chat.py 存在")
    body = _extract_text(args.template)
    if len(body) > 6000:
        body = body[:6000] + "\n...(已截断)..."
    prompt = (
        "你是一个合同/公文模板解析助手。请从下面这份模板正文里找出所有需要填写的字段,"
        "包括 {{xxx}} 占位符、下划线空白、'甲方:__'、'金额¥___'、'签订日期____' 等。\n"
        "严格返回 JSON(不要解释、不要 Markdown 代码块),格式:\n"
        "{\"fields\": [{\"name\": \"甲方\", \"example\": \"张三\", \"type\": \"text|number|date|amount\", "
        "\"where\": \"正文第1段\"}, ...]}\n"
        f"--- 模板正文 ---\n{body}"
    )
    result = chat_text_json(prompt, api_key=args.api_key)
    fields = result.get("fields", [])
    return {
        "ok": True,
        "template": args.template,
        "fields": fields,
        "count": len(fields),
        "note": "AI 识别结果,可能漏/多,请人工复核",
    }


def _generate_one(template, mapping, output):
    doc = Document(template)
    missing = set()
    for p in _iter_cells(doc):
        for run in p.runs:
            _replace_in_run(run, mapping, missing)
    out = Path(output)
    out.parent.mkdir(parents=True, exist_ok=True)
    doc.save(str(out))
    return str(out), missing


def cmd_generate(args) -> dict:
    if args.data:
        payload = json.loads(Path(args.data).read_text(encoding="utf-8"))
    elif args.row:
        mapping = {}
        for pair in args.row.split(";"):
            if "=" in pair:
                k, v = pair.split("=", 1)
                mapping[k.strip()] = v.strip()
        payload = [mapping]
    else:
        raise ValueError("需要 --data 或 --row")

    items = payload.get("items", payload) if isinstance(payload, dict) else payload
    if not isinstance(items, list) or not items:
        raise ValueError("数据应为数组或 {'items': [...]}")

    out_dir = Path(args.output_dir) if args.output_dir else None
    generated = []
    all_missing = set()
    for i, item in enumerate(items, 1):
        mapping = {str(k): str(v) if v is not None else "" for k, v in item.items()}
        if out_dir:
            out = out_dir / f"合同_{i:03d}.docx"
        elif args.output:
            out = Path(args.output)
        else:
            raise ValueError("需要 --output-dir 或 --output")
        path, missing = _generate_one(args.template, mapping, str(out))
        generated.append(path)
        all_missing.update(missing)

    return {
        "ok": True,
        "count": len(generated),
        "files": generated,
        "missing_fields": sorted(all_missing) if all_missing else [],
        "note": "缺失字段未替换(模板中保留 {{占位符}});建议先跑 schema 确认字段" if all_missing else "全部字段已填充",
    }


def build_parser() -> argparse.ArgumentParser:
    ap = argparse.ArgumentParser(description="合同/模板批量生成工具")
    sub = ap.add_subparsers(dest="command", required=True)

    p = sub.add_parser("schema", help="扫描模板占位符字段")
    p.add_argument("--template", required=True)
    p.set_defaults(func=cmd_schema)

    p = sub.add_parser("auto-fields", help="AI 自动识别模板里所有待填字段(含下划线/留白)")
    p.add_argument("--template", required=True)
    p.add_argument("--api-key", default=None)
    p.set_defaults(func=cmd_auto_fields)

    p = sub.add_parser("generate", help="批量生成(数据数组→多份 docx)")
    p.add_argument("--template", required=True)
    p.add_argument("--data", default=None, help="JSON 数据文件")
    p.add_argument("--row", default=None, help='单份数据 "甲方=张三;金额=10000"')
    p.add_argument("--output-dir", default=None)
    p.add_argument("--output", default=None)
    p.set_defaults(func=cmd_generate)

    return ap


def main():
    args = build_parser().parse_args()
    try:
        result = args.func(args)
    except Exception as e:
        print(json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False))
        sys.exit(1)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()

<!-- ===== 以下为共享依赖 _lib(落盘为 _lib/<name>,与 scripts/ 同级上层) ===== -->

文件:_lib/aims_chat.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AIMS 平台 AI 调用公共 helper(6 个 skill 复用)。

能力:
  - chat_text(prompt, model="qwen-flash")          纯文本对话
  - chat_vision(image_path_or_url, prompt, ...)    图片+文本多模态
  - chat_pdf_pages(pdf_path, prompt, zoom=2.0)     扫描版 PDF OCR
  - chat_with_usage(...)                           返回文本+用量

环境:依赖 AIMS_API_KEY 环境变量或 --api-key
"""
import argparse
import base64
import json
import os
import sys
import time
import urllib.request
from pathlib import Path

AIMS_URL = "https://aimsgateway.cn/mcp/"
TEXT_MODEL = "qwen-flash"           # 通用文本(最便宜)
VISION_MODEL = "qwen-vl-ocr-latest" # 视觉/OCR


# ---------- 鉴权 & 协议 ----------
def _get_key(api_key=None):
    key = api_key or os.environ.get("AIMS_API_KEY")
    if not key:
        raise RuntimeError(
            "缺少 AIMS API Key:请设置环境变量 AIMS_API_KEY,或调用方传 --api-key"
        )
    return key


def _rpc(url, key, method, params, mid, tries=3, timeout=180):
    body = json.dumps({"jsonrpc": "2.0", "id": mid, "method": method, "params": params}).encode()
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
    last = None
    for _ in range(tries):
        try:
            req = urllib.request.Request(url, data=body, method="POST", headers=headers)
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode())
        except Exception as e:  # noqa: BLE001
            last = e
            time.sleep(2)
    raise RuntimeError(f"MCP 调用失败: {last}")


def _handshake(key):
    _rpc(AIMS_URL, key, "initialize",
         {"protocolVersion": "2025-03-26", "capabilities": {},
          "clientInfo": {"name": "office-skills", "version": "1.0"}}, 1)
    try:
        _rpc(AIMS_URL, key, "notifications/initialized", {}, 2)
    except Exception:
        pass


# ---------- 图片编码 ----------
def _file_to_data_url(path):
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(path)
    b64 = base64.b64encode(p.read_bytes()).decode()
    ext = p.suffix.lower()
    mime = {
        "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg",
        "gif": "image/gif", "webp": "image/webp", "bmp": "image/bmp",
    }.get(ext, "image/png")
    return f"data:{mime};base64,{b64}"


def _pdf_page_to_data_url(pdf_path, page_index=0, zoom=2.0):
    try:
        import fitz  # PyMuPDF
    except ImportError:
        raise RuntimeError("PDF 多模态需要 PyMuPDF:pip install pymupdf")
    doc = fitz.open(pdf_path)
    if page_index < 0 or page_index >= doc.page_count:
        raise IndexError(f"页码 {page_index} 越界,共 {doc.page_count} 页")
    pix = doc[page_index].get_pixmap(matrix=fitz.Matrix(zoom, zoom))
    raw = pix.tobytes("png")
    b64 = base64.b64encode(raw).decode()
    return f"data:image/png;base64,{b64}"


# ---------- 聊天封装 ----------
def _chat_call(key, model, content, max_tokens=4000, temperature=0, mid=7, no_rag=True):
    """调 aims.chat。

    关键参数 `no_rag` 默认 True(2026-09-16 平台确认):
    - 平台默认给 chat 注入知识库(KB)内容,视觉模型/OCR 收到 RAG 文本会跑偏
    - 加上 `no_rag: True` 后,模型纯粹根据 prompt + 图片回答
    - 纯文本调用也建议加,避免被 KB 干扰
    """
    arguments = {
        "model": model,
        "messages": [{"role": "user", "content": content}],
        "max_tokens": max_tokens, "temperature": temperature,
        "no_rag": no_rag,
    }
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "aims.chat", "arguments": arguments}, mid)
    txt = resp.get("result", {}).get("content", [{}])[0].get("text", "")
    if not txt:
        raise RuntimeError("平台返回为空: " + json.dumps(resp, ensure_ascii=False)[:300])
    try:
        obj = json.loads(txt)
        return obj["choices"][0]["message"]["content"], obj.get("usage", {})
    except Exception:
        return txt, {}


def chat_text(prompt, model=None, max_tokens=4000, temperature=0, api_key=None, no_rag=True):
    """纯文本对话:返回文本。"""
    key = _get_key(api_key)
    _handshake(key)
    model = model or TEXT_MODEL
    text, _ = _chat_call(key, model, prompt, max_tokens, temperature, no_rag=no_rag)
    return text.strip()


def chat_text_with_usage(prompt, model=None, max_tokens=4000, temperature=0, api_key=None, no_rag=True):
    key = _get_key(api_key)
    _handshake(key)
    model = model or TEXT_MODEL
    text, usage = _chat_call(key, model, prompt, max_tokens, temperature, no_rag=no_rag)
    return text.strip(), usage


def chat_vision(image_input, prompt, model=None, max_tokens=4000, api_key=None, no_rag=True):
    """图片对话:image_input 可为本地路径或 data: URI。"""
    key = _get_key(api_key)
    _handshake(key)
    model = model or VISION_MODEL
    if image_input.startswith("data:"):
        data_url = image_input
    else:
        data_url = _file_to_data_url(image_input)
    content = [
        {"type": "image_url", "image_url": {"url": data_url}},
        {"type": "text", "text": prompt},
    ]
    text, _ = _chat_call(key, model, content, max_tokens, 0, no_rag=no_rag)
    return text.strip()


def chat_pdf_page(pdf_path, page_index, prompt, model=None, zoom=2.0, max_tokens=4000, api_key=None, no_rag=True):
    """扫描版 PDF 单页:先渲染成图,再视觉 OCR。"""
    data_url = _pdf_page_to_data_url(pdf_path, page_index, zoom)
    return chat_vision(data_url, prompt, model=model, max_tokens=max_tokens, api_key=api_key, no_rag=no_rag)


# ---------- JSON 输出辅助 ----------
def _strip_code_fence(s):
    s = s.strip()
    if s.startswith("```"):
        lines = s.splitlines()
        if lines and lines[0].startswith("```"):
            lines = lines[1:]
        if lines and lines[-1].strip().startswith("```"):
            lines = lines[:-1]
        s = "\n".join(lines)
    return s.strip()


def chat_text_json(prompt, model=None, max_tokens=4000, api_key=None, no_rag=True):
    """纯文本对话 → 强制 JSON 输出(解析失败抛错)。"""
    text = chat_text(prompt, model=model, max_tokens=max_tokens, api_key=api_key, no_rag=no_rag)
    return json.loads(_strip_code_fence(text))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="AIMS 平台 AI 调用 helper 自检")
    ap.add_argument("--api-key", default=None)
    ap.add_argument("--text", default="用一句话介绍 Python。")
    args = ap.parse_args()
    print("=== chat_text ===")
    print(chat_text(args.text, api_key=args.api_key))

文件:_lib/aims_functional_api.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AIMS 平台功能型 API 公共调用 helper(付费 skill 共用)。

能力:
  - call_functional_api(resource_id, arguments)  统一调用平台托管功能型 API
  - needs_confirm → 抛出 NeedsConfirmation(结构化,带真实报价)
  - estimate_cost(resource_id, units)            免费报价(不调上游,0 花费)

协议(2026-09-22 platform-paid-confirm-protocol):
  付费工具默认 **confirm=False**(安全默认)。平台返回 -32006 时不扣费,
  本模块把它翻译成 NeedsConfirmation 异常(带 estimated_cost_yuan),
  而不是笼统的 RuntimeError——这样 agent 能把真实报价展示给用户,
  用户确认后加 --approved 重试。

环境:依赖 AIMS_API_KEY 环境变量或 --api-key
"""
import argparse
import json
import os
import time
import urllib.request

AIMS_URL = "https://aimsgateway.cn/mcp/"

# 内部源名 → 对外目录名(与平台 application/services/public_naming.py 的
# PUBLIC_SOURCES 对齐;未登记的源原样透出)。estimate 用它把内部 resource_id
# 映射成 list_functional_apis 返回的对外 id。
_EXTERNALIZE = {"serpapi": "web", "hunter": "email", "jev": "decision", "apis": "public-api"}


class NeedsConfirmation(RuntimeError):
    """付费工具未确认 —— 平台返回 -32006 / requires_confirmation。

    仍未扣费。调用方应把 estimated_cost_yuan 展示给用户,
    用户同意后带 confirm=True 重试。

    继承 RuntimeError 是为了向后兼容既有 ``except RuntimeError`` 调用方。
    """

    def __init__(self, resource_id, estimated_cost_yuan=0.0, basis="", raw=None, hint=""):
        self.resource_id = resource_id
        self.estimated_cost_yuan = float(estimated_cost_yuan or 0.0)
        self.basis = basis or ""
        self.raw = raw if isinstance(raw, dict) else {}
        self.hint = hint or ""
        super().__init__(
            f"付费工具需确认: {resource_id} 约 ¥{self.estimated_cost_yuan:.2f} "
            f"(价格依据: {self.basis or 'unknown'})。"
            f"请把该报价展示给用户;确认后加 --approved 重试。未确认不会扣费。"
        )

    def to_dict(self):
        """给 CLI 输出的结构化载荷(agent 可直接机读)。"""
        return {
            "ok": False,
            "needs_confirmation": True,
            "resource_id": self.resource_id,
            "estimated_cost_yuan": self.estimated_cost_yuan,
            "cost_basis": self.basis or "unknown",
            "hint": self.hint or "把费用展示给用户;用户确认后加 --approved 重试",
        }


def _external_rid(resource_id):
    """内部 resource_id → 对外目录 id。serpapi/google → web/google"""
    src, _, rest = (resource_id or "").strip().partition("/")
    ext = _EXTERNALIZE.get(src, src)
    return f"{ext}/{rest}" if rest else ext


def _maybe_needs_confirmation(resource_id, parsed):
    """把平台的 -32006 载荷翻译成 NeedsConfirmation;不是则返回 None。

    兼容三种形态:
      A {"error": {"code": -32006, "data": {...}}}   平台 JSON-RPC 包装
      B {"code": -32006, "data": {...}}              已解包的 error 对象
      C {"requires_confirmation": true, ...}         直接是 data
    """
    if not isinstance(parsed, dict):
        return None

    err = parsed.get("error")
    if isinstance(err, dict) and err.get("code") == -32006:
        d = err.get("data") if isinstance(err.get("data"), dict) else {}
        return NeedsConfirmation(resource_id, d.get("estimated_cost_yuan"),
                                 d.get("cost_basis", ""), err, d.get("hint", ""))

    if parsed.get("code") == -32006:
        d = parsed.get("data") if isinstance(parsed.get("data"), dict) else {}
        return NeedsConfirmation(resource_id, d.get("estimated_cost_yuan"),
                                 d.get("cost_basis", ""), parsed, d.get("hint", ""))

    if parsed.get("requires_confirmation") is True:
        return NeedsConfirmation(resource_id, parsed.get("estimated_cost_yuan"),
                                 parsed.get("cost_basis", ""), parsed, parsed.get("hint", ""))

    return None


def raise_if_needs_confirmation(resource_id, parsed):
    """载荷是 -32006 时抛 NeedsConfirmation,否则原样返回 parsed。

    给自建 _rpc_call 的 skill 复用(它们拿到 isError 载荷后调这个,
    就能和走本模块的 skill 有同一套结构化确认语义)。
    """
    nc = _maybe_needs_confirmation(resource_id, parsed)
    if nc is not None:
        raise nc
    return parsed


# ---------- 鉴权 & 协议 ----------
def _get_key(api_key=None):
    key = api_key or os.environ.get("AIMS_API_KEY")
    if not key:
        raise RuntimeError(
            "缺少 AIMS API Key:请设置环境变量 AIMS_API_KEY,或调用方传 --api-key"
        )
    return key


def _rpc(url, key, method, params, mid, tries=3, timeout=120):
    body = json.dumps({"jsonrpc": "2.0", "id": mid, "method": method, "params": params}).encode()
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
    last = None
    for _ in range(tries):
        try:
            req = urllib.request.Request(url, data=body, method="POST", headers=headers)
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode())
        except Exception as e:  # noqa: BLE001
            last = e
            time.sleep(2)
    raise RuntimeError(f"MCP 调用失败: {last}")


def _handshake(key):
    _rpc(AIMS_URL, key, "initialize",
         {"protocolVersion": "2025-03-26", "capabilities": {},
          "clientInfo": {"name": "office-skills-func-api", "version": "1.0"}}, 1)
    try:
        _rpc(AIMS_URL, key, "notifications/initialized", {}, 2)
    except Exception:
        pass


# ---------- 功能型 API 调用 ----------
def call_functional_api(resource_id, arguments=None, api_key=None, mid=3, confirm=False):
    """调 AIMS 平台的功能型 API。

    Args:
        resource_id: 资源 ID,9 个可选值:
            - hunter/account
            - hunter/domain-search
            - hunter/email-finder
            - hunter/email-verifier
            - serpapi/account
            - serpapi/{engine}
            - apis/catalog
            - apis/{slug}
            - apis/{slug}/{path}
        arguments: dict,参数键值对(按上游 API 的 params 字段说明)
        api_key: 可选 Bearer Token(默认读 env)
        confirm: True 时附 confirm:true,平台放行付费工具;False 时平台返回
            -32006 / requires_confirmation,未付费不扣费(默认 False,安全默认)

    返回 dict(平台直接返回上游响应 + 末尾 `_aimschina` 元数据)
    抛出 RuntimeError 当 isError=True
    """
    key = _get_key(api_key)
    _handshake(key)
    args = dict(arguments or {})
    if confirm:
        args["confirm"] = True
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "aims.call_functional_api",
                 "arguments": {"resource_id": resource_id, "arguments": args}}, mid)
    is_err = resp.get("result", {}).get("isError")
    text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
    parsed = json.loads(text)
    if is_err:
        _nc = _maybe_needs_confirmation(resource_id, parsed)
        if _nc is not None:
            raise _nc
        raise RuntimeError(f"{resource_id} 错误: {parsed}")
    return parsed


# ---------- 9 个快捷封装 ----------
def hunter_account(api_key=None, confirm=False):
    """hunter 账户与配额(免费)。"""
    return call_functional_api("hunter/account", {}, api_key=api_key, confirm=confirm)


def hunter_domain_search(domain, limit=10, offset=0, type=None,
                         seniority=None, department=None, api_key=None, confirm=False):
    """按域名搜邮箱。返回 {"domain":..., "emails":[{value,type,confidence,position,...}], "_aimschina":{cost_yuan,...}}"""
    args = {"domain": domain, "limit": str(limit)}
    if offset:
        args["offset"] = str(offset)
    if type:
        args["type"] = type
    if seniority:
        args["seniority"] = seniority
    if department:
        args["department"] = department
    return call_functional_api("hunter/domain-search", args, api_key=api_key, confirm=confirm)


def hunter_email_finder(domain, full_name=None, first_name=None, last_name=None,
                        max_duration=10, api_key=None, confirm=False):
    """按人名 + 域名推断邮箱。"""
    args = {"domain": domain, "max_duration": str(max_duration)}
    if full_name:
        args["full_name"] = full_name
    elif first_name and last_name:
        args["first_name"] = first_name
        args["last_name"] = last_name
    return call_functional_api("hunter/email-finder", args, api_key=api_key, confirm=confirm)


def hunter_email_verifier(email, api_key=None, confirm=False):
    """验证邮箱是否可投递。返回 {"status": "valid"|"invalid"|"accept_all"|"webmail"|"disposable"|"unknown", ...}"""
    return call_functional_api("hunter/email-verifier", {"email": email}, api_key=api_key, confirm=confirm)


def serpapi_account(api_key=None, confirm=False):
    """serpapi 账户与配额(免费)。"""
    return call_functional_api("serpapi/account", {}, api_key=api_key, confirm=confirm)


def serpapi_search(engine, q=None, num=10, page=1, gl=None, hl=None,
                   location=None, api_key=None, confirm=False):
    """透传到任意 serpapi 引擎(google / google_maps / google_shopping 等)。

    engine 必填,例如 "google_maps" 拿 POI、"google" 拿网页搜索结果、"google_shopping" 拿商品。
    实际调 serpapi.engine 工具(不是走 functional_api 路由)。

    confirm=True 时附 confirm:true 放行付费工具;默认 False 平台返回 -32006 不扣费。
    """
    args = {"engine": engine, "num": str(num), "page": str(page)}
    if q:
        args["q"] = q
    if gl:
        args["gl"] = gl
    if hl:
        args["hl"] = hl
    if location:
        args["location"] = location
    if confirm:
        args["confirm"] = True
    key = _get_key(api_key)
    _handshake(key)
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "serpapi.engine", "arguments": args}, 3)
    is_err = resp.get("result", {}).get("isError")
    text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
    parsed = json.loads(text)
    if is_err:
        _nc = _maybe_needs_confirmation("serpapi/" + str(engine or ""), parsed)
        if _nc is not None:
            raise _nc
        raise RuntimeError(f"serpapi.engine({engine}) 错误: {parsed}")
    return parsed


def apis_catalog(api_key=None):
    """列出所有 apis 目录(450+ 免密钥公共 API)。"""
    return call_functional_api("apis/catalog", {}, api_key=api_key)


def apis_slug(slug, api_key=None):
    """调 apis/{slug} 顶层端点(GET)。"""
    return call_functional_api(f"apis/{slug}", {}, api_key=api_key)


def apis_slug_path(slug, path, method="GET", body=None, params=None, api_key=None):
    """调 apis/{slug}/{path} 任意端点。

    Args:
        slug: 例如 "openweather"
        path: 例如 "data/2.5/weather"
        method: GET / POST / PUT / DELETE
        body: POST/PUT body
        params: query 参数
    """
    args = {"method": method}
    if body is not None:
        args["body"] = body
    if params is not None:
        args["params"] = params
    return call_functional_api(f"apis/{slug}/{path}", args, api_key=api_key)


# ---------- 免费报价 estimate(0 上游花费) ----------
# 本地兜底价:**只登记实测过的资源**(来源:lead-miner install.md §17.4,
# 实测日期 2026-09-17)。平台实时价取不到时才用它,且 cost_basis 会明确标
# local_fallback + price_note 提示可能有偏差——绝不拿它冒充权威报价。
# 没实测过的资源**一律不给兜底价**(宁可 ok=False,也不猜)。
LOCAL_FALLBACK_PRICE_YUAN = {
    "serpapi/google_maps": 0.21,
    "hunter/domain-search": 0.204,
    "hunter/email-verifier": 0.10,
}


def estimate_cost(resource_id, units=1, api_key=None):
    """纯报价:走**免费**的 aims.list_functional_apis 读实时单价,不调上游。

    这是唯一可靠的报价途径——catalog 声明价与实收价实测差 ~18%,
    而 list_functional_apis 返回的是平台已折算的 effective 单价
    (observed 实测价优先,缺失才回落 declared)。

    Args:
        resource_id: 内部 resource_id,如 "serpapi/google" / "hunter/domain-search"
        units: 预计调用次数
        api_key: 可选 Bearer Token(默认读 env)

    Returns:
        dict: {ok, resource_id, external_resource_id, units, unit_cost_yuan,
               cost_basis, total_yuan, upstream_called: False, note}
        查不到价时返回 ok=False(不抛异常——报价失败不该让调用方崩)
    """
    ext = _external_rid(resource_id)
    base = {
        "resource_id": resource_id,
        "external_resource_id": ext,
        "units": int(units or 1),
        "upstream_called": False,
    }

    def _fallback(note):
        """平台价拿不到时用本地实测兜底;没登记的资源保持 ok=False(不猜价)。"""
        unit = LOCAL_FALLBACK_PRICE_YUAN.get(resource_id)
        if unit is None:
            return False
        base.update({
            "ok": True,
            "unit_cost_yuan": round(unit, 4),
            "cost_basis": "local_fallback",
            "billing_unit": "per_call",
            "total_yuan": round(unit * base["units"], 4),
            "price_note": ("本地登记的【实测兜底价】(2026-09-17),非平台实时价,"
                           "实收可能偏差约 ±18%;要准数请配好 AIMS_API_KEY 重跑 estimate。"),
            "note": note,
        })
        return True

    try:
        key = _get_key(api_key)
    except RuntimeError as e:
        if not _fallback("用本地实测兜底价(未触达平台)"):
            base.update({"ok": False, "error": str(e),
                         "note": "estimate 需要 AIMS_API_KEY 才能读到平台实时单价"})
        return base
    try:
        _handshake(key)
        resp = _rpc(AIMS_URL, key, "tools/call",
                    {"name": "aims.list_functional_apis",
                     "arguments": {"limit": 200}}, 7)
        text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
        payload = json.loads(text)
    except Exception as e:  # noqa: BLE001
        if not _fallback("用本地实测兜底价(平台单价查询失败)"):
            base.update({"ok": False, "error": f"读取平台单价失败: {e}"})
        return base

    items = payload.get("apis") or []
    hit = None
    for it in items:
        if isinstance(it, dict) and it.get("resource_id") in (ext, resource_id):
            hit = it
            break
    if hit is None:
        if _fallback("平台目录里没有该资源,改用本地实测兜底价"):
            base["not_in_catalog"] = True
            return base
        base.update({
            "ok": False,
            "error": f"平台目录里没找到 {ext}(内部 id: {resource_id})",
            "note": "单价未知——不要凭猜测报给用户;请确认该资源是否已上架/被 chat 策略隐藏",
            "available_count": len(items),
        })
        return base

    unit = float(hit.get("unit_cost_yuan") or 0.0)
    base.update({
        "ok": True,
        "name": hit.get("name") or "",
        "unit_cost_yuan": round(unit, 4),
        "cost_basis": hit.get("price_basis") or "declared",
        "billing_unit": hit.get("billing_unit") or "per_call",
        "total_yuan": round(unit * base["units"], 4),
        "note": "本报价未调用上游、未扣费;用户确认后加 --approved 真实执行",
    })
    return base


def emit_estimate(resource_id, units=1, api_key=None):
    """CLI 用:打印报价 JSON 并以退出码结束(0=有报价 / 1=查不到)。

    在 skill 里这样用(parse_args 之后、真调付费接口之前):
        if args.estimate:
            emit_estimate("serpapi/google")
    """
    est = estimate_cost(resource_id, units=units, api_key=api_key)
    print(json.dumps(est, ensure_ascii=False, indent=2))
    raise SystemExit(0 if est.get("ok") else 1)


def add_estimate_flag(parser):
    """给 skill 的 argparse 统一加 --estimate(免费报价,不调上游)。"""
    parser.add_argument(
        "--estimate", action="store_true",
        help="只报预估费用,不调用上游、不扣费(免费)",
    )
    return parser


# ---------- 列出当前所有可用 resource_id ----------
KNOWN_RESOURCES = [
    "hunter/account",
    "hunter/domain-search",
    "hunter/email-finder",
    "hunter/email-verifier",
    "serpapi/account",
    "serpapi/{engine}",
    "apis/catalog",
    "apis/{slug}",
    "apis/{slug}/{path}",
]


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(description="AIMS 功能型 API helper 自检")
    ap.add_argument("--api-key", default=None)
    ap.add_argument("--resource", default="hunter/account", help=f"资源 ID,已知: {KNOWN_RESOURCES}")
    ap.add_argument("--args", default="{}", help="JSON 字符串参数")
    args = ap.parse_args()

    print(f"=== call_functional_api({args.resource}) ===")
    parsed_args = json.loads(args.args)
    result = call_functional_api(args.resource, parsed_args, api_key=args.api_key)
    print(json.dumps(result, ensure_ascii=False, indent=2)[:2000])