Skip to content

Pinvou/pinvou-agent / pinvou3-app/src-tauri/resources/common/bundle/lark-skills/lark-sheets

lark-sheets

Verified

【何时用:仅当用户明确指向飞书/Lark 电子表格;泛指做表格默认走本地工具】创建/操作飞书电子表格:工作表与行列结构、读写单元格(值/公式/样式/批注/图片)、查找替换、批量更新、区域复制/排序/填充、图表/透视表/条件格式/筛选/筛选视图/下拉列表/迷你图/浮动图片、公式校验与历史回滚、本地 Excel/CSV 导入导出。按名称搜索云空间表格文件改用 lark-drive 的 drive +search。doubao.com 的 /sheets/ URL 也走本 skill。多维表格改用 lark-base。不适用本地 Excel。

scripts/lark_inspect_workbook.py

View on GitHub
#!/usr/bin/env python3
# Copyright (c) 2026 Lark Technologies Pte. Ltd.
# SPDX-License-Identifier: MIT
"""Inspect a Lark spreadsheet and emit a compact workbook profile."""

from __future__ import annotations

import argparse
from typing import Any

from lark_sheet_range import index_to_col
from lark_sheet_read_cli import (
    LarkCliError,
    add_spreadsheet_args,
    emit_error,
    emit_success,
    envelope_data,
    is_grid_sheet,
    resolve_target_sheets,
    run_sheets,
    sheet_identifier,
    sheet_locator,
    sheet_resource_type,
    sheet_title,
    visible_grid_selection,
)

ACTION = "inspect_workbook"
LAYOUT_INCLUDE = "merges,row_heights,col_widths,hidden_rows,hidden_cols,groups,frozen"


def _sheet_summary(sheet: dict[str, Any]) -> dict[str, Any]:
    return {
        "sheet_id": sheet_identifier(sheet),
        "title": sheet_title(sheet),
        "index": sheet.get("index"),
        "resource_type": sheet_resource_type(sheet),
        "row_count": sheet.get("row_count"),
        "column_count": sheet.get("column_count"),
        "is_hidden": sheet.get("is_hidden"),
        "merged_cells_count": sheet.get("merged_cells_count"),
        "chart_count": sheet.get("chart_count"),
        "pivot_table_count": sheet.get("pivot_table_count"),
        "float_image_count": sheet.get("float_image_count"),
    }


def _list_count(value: Any) -> int:
    return len(value) if isinstance(value, list) else 0


def _layout_summary(layout: dict[str, Any]) -> dict[str, Any]:
    """Retain layout signals without serializing unbounded per-cell metadata."""
    merges = layout.get("merged_cells") or layout.get("merges") or []
    groups = layout.get("groups") if isinstance(layout.get("groups"), dict) else {}
    row_groups = layout.get("row_groups") or groups.get("rows", [])
    col_groups = layout.get("column_groups") or groups.get("columns", [])
    return {
        "merge_count": _list_count(merges),
        "row_heights_count": _list_count(layout.get("row_heights")),
        "column_widths_count": _list_count(layout.get("col_widths")),
        "hidden_rows_count": _list_count(layout.get("hidden_rows")),
        "hidden_columns_count": _list_count(
            layout.get("hidden_cols") or layout.get("hidden_columns")
        ),
        "row_groups_count": _list_count(row_groups),
        "column_groups_count": _list_count(col_groups),
        "frozen": layout.get("frozen"),
    }


def inspect_workbook(args) -> tuple[dict[str, Any], list[str]]:
    warnings: list[str] = []
    workbook = envelope_data(
        run_sheets(
            "+workbook-info",
            url=args.url,
            spreadsheet_token=args.spreadsheet_token,
            timeout=args.timeout,
        )
    )
    # An explicit selector must resolve: without require_one a typo'd
    # --sheet-id/--sheet-name silently yields sheet_count 0, which reads as
    # "empty workbook" instead of a locator error.
    selection = visible_grid_selection(workbook, sheet_id=args.sheet_id, sheet_name=args.sheet_name)
    all_sheets = resolve_target_sheets(workbook)
    target_sheets = resolve_target_sheets(
        workbook,
        sheet_id=args.sheet_id,
        sheet_name=args.sheet_name,
        require_one=bool(args.sheet_id or args.sheet_name),
    )
    preview_targets = target_sheets
    if not args.sheet_id and not args.sheet_name:
        # is_hidden 缺失不等于隐藏:预览只是只读预检,除显式 is_hidden=true 外一律纳入,
        # 否则旧 payload 会静默退化成「只有 summary、零预览」。写入侧的保守可见性判定
        # 仍由 selection 负责(visibility_unknown 在那里照样排除)。
        preview_targets = [sheet for sheet in all_sheets if is_grid_sheet(sheet) and sheet.get("is_hidden") is not True]
    if args.max_sheets < 1:
        raise LarkCliError("--max-sheets must be at least 1")
    inspect_count = min(len(preview_targets), args.max_sheets)
    if inspect_count < len(preview_targets):
        warnings.append(
            f"layout and preview skipped for {len(preview_targets) - inspect_count} visible grid sheets; "
            "pass --sheet-id or --sheet-name to inspect one"
        )
    if not preview_targets and all_sheets:
        if any(is_grid_sheet(sheet) for sheet in all_sheets):
            warnings.append(
                "no previewable grid sheet: every grid sheet is explicitly hidden; "
                "pass --sheet-id or --sheet-name to inspect one anyway"
            )
        else:
            # 非网格子表在 visible_grid_selection 里会被显式拒绝,别提示「带 selector 重跑」
            # ——照做必然拿到 "is not a grid sheet",恢复动作等于死路。
            warnings.append(
                "no grid sheet in this workbook: every sheet is non-grid; "
                "read it through the matching product API instead of the grid read/write path"
            )
    # 按对象身份而非 sheet_id 圈定预览集合:payload 缺 sheet_id 时 sheet_identifier 全为
    # 空串,用 id 集合会把所有子表折叠成同一个 key,--max-sheets 直接失效(照样逐表发
    # +sheet-info / +csv-get)。all_sheets 与 preview_targets 取自同一份 workbook,元素是
    # 同一批 dict 实例,id() 比较安全。
    preview_marks = {id(sheet) for sheet in preview_targets[:inspect_count]}

    profiles = []
    for sheet in all_sheets:
        sid = sheet_identifier(sheet)
        title = sheet_title(sheet)
        profile = _sheet_summary(sheet)
        if id(sheet) not in preview_marks:
            profiles.append(profile)
            continue
        locator = sheet_locator(sheet)
        col_count = int(sheet.get("column_count") or args.max_preview_cols)
        preview_cols = min(col_count, args.max_preview_cols)
        if col_count > args.max_preview_cols:
            warnings.append(
                f"{title or sid}: preview clipped to first {args.max_preview_cols} columns"
            )
        end_col = index_to_col(max(1, preview_cols))
        preview_range = f"A1:{end_col}{args.preview_rows}"

        # Per-sheet, not fail-the-run: this is the first-step pre-flight, and
        # one unreadable sheet (odd type, transient error, a locator that does
        # not resolve) must not throw away the summaries already collected for
        # every other sheet. The basic summary comes from +workbook-info and is
        # already in hand, so a failure here degrades detail, not correctness —
        # same call the sibling profile_table downgrades to a warning.
        try:
            layout = envelope_data(
                run_sheets(
                    "+sheet-info",
                    url=args.url,
                    spreadsheet_token=args.spreadsheet_token,
                    **locator,
                    flags={"include": LAYOUT_INCLUDE},
                    timeout=args.timeout,
                )
            )
            preview = envelope_data(
                run_sheets(
                    "+csv-get",
                    url=args.url,
                    spreadsheet_token=args.spreadsheet_token,
                    **locator,
                    flags={"range": preview_range, "max_chars": args.max_chars},
                    timeout=args.timeout,
                )
            )
        except LarkCliError as exc:
            warnings.append(
                f"{title or sid}: layout/preview unavailable ({exc}); "
                "re-read this sheet on its own with --sheet-name, or use +sheet-info / +csv-get directly"
            )
            profiles.append(profile)
            continue
        if preview.get("has_more"):
            warnings.append(f"{title or sid}: preview range {preview_range} was truncated")

        profiles.append(
            {
                **profile,
                "layout": _layout_summary(layout),
                "preview": {
                    "range": preview_range,
                    "current_region": preview.get("current_region"),
                    "row_indices": preview.get("row_indices"),
                    "col_indices": preview.get("col_indices"),
                    "annotated_csv": preview.get("annotated_csv"),
                    "has_more": preview.get("has_more"),
                },
            }
        )

    return {"sheet_count": len(all_sheets), "sheets": profiles, "selection": selection}, warnings


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_spreadsheet_args(parser, require_sheet=False, allow_sheet=True)
    parser.add_argument("--preview-rows", type=int, default=15)
    parser.add_argument("--max-preview-cols", type=int, default=100)
    parser.add_argument("--max-chars", type=int, default=8000)
    parser.add_argument("--max-sheets", type=int, default=3)
    parser.add_argument("--timeout", type=int, default=60)
    args = parser.parse_args()
    try:
        data, warnings = inspect_workbook(args)
    except (LarkCliError, ValueError, TypeError) as exc:
        emit_error(ACTION, str(exc))
    emit_success(ACTION, data, warnings)


if __name__ == "__main__":
    main()
deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall