mirror of
https://github.com/larksuite/cli.git
synced 2026-07-07 17:20:00 +08:00
Compare commits
7 Commits
fix/im-ci
...
fix/skills
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77ad271fce | ||
|
|
9d845442ce | ||
|
|
c07a14aa2b | ||
|
|
8b39f7243c | ||
|
|
e40ef66912 | ||
|
|
e1bb9db552 | ||
|
|
7c50b3d9e3 |
16
cmd/build.go
16
cmd/build.go
@@ -6,6 +6,7 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
|
||||
"github.com/larksuite/cli/cmd/api"
|
||||
"github.com/larksuite/cli/cmd/auth"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"github.com/larksuite/cli/cmd/profile"
|
||||
"github.com/larksuite/cli/cmd/schema"
|
||||
"github.com/larksuite/cli/cmd/service"
|
||||
"github.com/larksuite/cli/cmd/skill"
|
||||
cmdupdate "github.com/larksuite/cli/cmd/update"
|
||||
_ "github.com/larksuite/cli/events"
|
||||
"github.com/larksuite/cli/internal/build"
|
||||
@@ -51,6 +53,18 @@ func WithKeychain(kc keychain.KeychainAccess) BuildOption {
|
||||
}
|
||||
}
|
||||
|
||||
// embeddedSkillContent is the skill tree wired into cmdutil.Factory.SkillContent
|
||||
// at build time. It is registered by the repo-root package main's init via
|
||||
// SetEmbeddedSkillContent — it cannot be threaded through main.go without
|
||||
// breaking the single-file preview build (see skills_embed.go). nil in builds
|
||||
// that embed no skills; the `skills` commands then return a typed internal error.
|
||||
var embeddedSkillContent fs.FS
|
||||
|
||||
// SetEmbeddedSkillContent registers the embedded skill tree. Called from the
|
||||
// repo-root package main's init; a wrapper main can call it before Execute to
|
||||
// supply its own skill content.
|
||||
func SetEmbeddedSkillContent(fsys fs.FS) { embeddedSkillContent = fsys }
|
||||
|
||||
// HideProfile sets the visibility policy for the root-level --profile flag.
|
||||
// When hide is true the flag stays registered (so existing invocations still
|
||||
// parse) but is omitted from help and shell completion. Typically called as
|
||||
@@ -103,6 +117,7 @@ func buildInternal(ctx context.Context, inv cmdutil.InvocationContext, opts ...B
|
||||
if cfg.keychain != nil {
|
||||
f.Keychain = cfg.keychain
|
||||
}
|
||||
f.SkillContent = embeddedSkillContent
|
||||
rootCmd := &cobra.Command{
|
||||
Use: "lark-cli",
|
||||
Short: "Lark/Feishu CLI — OAuth authorization, UAT management, API calls",
|
||||
@@ -140,6 +155,7 @@ func buildInternal(ctx context.Context, inv cmdutil.InvocationContext, opts ...B
|
||||
rootCmd.AddCommand(completion.NewCmdCompletion(f))
|
||||
rootCmd.AddCommand(cmdupdate.NewCmdUpdate(f))
|
||||
rootCmd.AddCommand(cmdevent.NewCmdEvents(f))
|
||||
rootCmd.AddCommand(skill.NewCmdSkill(f))
|
||||
service.RegisterServiceCommandsWithContext(ctx, rootCmd, f)
|
||||
shortcuts.RegisterShortcutsWithContext(ctx, rootCmd, f)
|
||||
|
||||
|
||||
183
cmd/skill/skill.go
Normal file
183
cmd/skill/skill.go
Normal file
@@ -0,0 +1,183 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package skill implements the `lark-cli skills` command group, which serves
|
||||
// binary-embedded skill content to AI agents. The package is "skill"; the
|
||||
// user-facing verb is "skills".
|
||||
package skill
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/skillcontent"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newReader(f *cmdutil.Factory) (*skillcontent.Reader, error) {
|
||||
if f.SkillContent == nil {
|
||||
return nil, errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"skill content not embedded in this build")
|
||||
}
|
||||
return skillcontent.New(f.SkillContent), nil
|
||||
}
|
||||
|
||||
type readEnvelope struct {
|
||||
Skill string `json:"skill"`
|
||||
Path string `json:"path"`
|
||||
Content string `json:"content"`
|
||||
Guidance string `json:"guidance,omitempty"`
|
||||
}
|
||||
|
||||
type listEnvelope struct {
|
||||
OK bool `json:"ok"`
|
||||
Skills []skillcontent.SkillInfo `json:"skills"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type listPathEnvelope struct {
|
||||
OK bool `json:"ok"`
|
||||
Path string `json:"path"`
|
||||
Entries []skillcontent.DirEntry `json:"entries"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func NewCmdSkill(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "skills",
|
||||
Short: "Read embedded skill content (list / read)",
|
||||
Long: "Read agent-readable skill content (SKILL.md and reference files) embedded in " +
|
||||
"the CLI binary at build time, so it stays in sync with the CLI version. " +
|
||||
"Machine resources such as assets/ and scripts/ are not embedded.",
|
||||
}
|
||||
// Risk is set on each leaf (GetRisk does not walk parents); the group has none.
|
||||
cmdutil.DisableAuthCheck(cmd)
|
||||
cmd.AddCommand(newListCmd(f), newReadCmd(f))
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newListCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list [name[/path]]",
|
||||
Short: "List skills, or list one layer under a skill path (like ls)",
|
||||
Example: ` lark-cli skills list # all skills: name, description, version
|
||||
lark-cli skills list lark-doc # one layer under a skill (like ls)
|
||||
lark-cli skills list lark-doc/references # one layer under a subdirectory`,
|
||||
Args: cobra.ArbitraryArgs,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) > 1 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"list takes at most 1 argument: [name[/path]]").
|
||||
WithHint("run 'lark-cli skills list --help'")
|
||||
}
|
||||
r, err := newReader(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(args) == 0 {
|
||||
skills, err := r.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
output.PrintJson(f.IOStreams.Out, listEnvelope{OK: true, Skills: skills, Count: len(skills)})
|
||||
return nil
|
||||
}
|
||||
entries, listed, err := r.ListPath(args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
output.PrintJson(f.IOStreams.Out, listPathEnvelope{OK: true, Path: listed, Entries: entries, Count: len(entries)})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
// --json is a no-op (list is always JSON), accepted only to stay symmetric with read.
|
||||
cmd.Flags().Bool("json", false, "no-op (list output is always JSON)")
|
||||
cmdutil.SetRisk(cmd, "read")
|
||||
cmdutil.DisableAuthCheck(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newReadCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
var asJSON bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "read <name>[/<path>] [path]",
|
||||
Short: "Print a skill's SKILL.md, or a file under the skill (raw markdown by default)",
|
||||
Example: ` lark-cli skills read lark-doc # the skill's SKILL.md
|
||||
lark-cli skills read lark-doc references/lark-doc-fetch.md # a file under the skill
|
||||
lark-cli skills read lark-doc/references/lark-doc-fetch.md # same, slash form
|
||||
lark-cli skills read lark-doc --json # JSON envelope`,
|
||||
Args: cobra.ArbitraryArgs,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
name, relpath, err := parseReadTarget(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r, err := newReader(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var content []byte
|
||||
var pathOut string
|
||||
if relpath == "" {
|
||||
content, err = r.ReadSkill(name)
|
||||
pathOut = "SKILL.md"
|
||||
} else {
|
||||
content, pathOut, err = r.ReadReference(name, relpath)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
isMain := pathOut == "SKILL.md"
|
||||
if asJSON {
|
||||
env := readEnvelope{Skill: name, Path: pathOut, Content: string(content)}
|
||||
if isMain {
|
||||
env.Guidance = readGuidance(name)
|
||||
}
|
||||
output.PrintJson(f.IOStreams.Out, env)
|
||||
return nil
|
||||
}
|
||||
// Raw stdout stays byte-identical to the file; guidance goes to stderr.
|
||||
if _, err := f.IOStreams.Out.Write(content); err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeFileIO, "failed to write output: %v", err)
|
||||
}
|
||||
if isMain {
|
||||
fmt.Fprintln(f.IOStreams.ErrOut, readGuidance(name))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&asJSON, "json", false, "output as a JSON envelope instead of raw markdown")
|
||||
cmdutil.SetRisk(cmd, "read")
|
||||
cmdutil.DisableAuthCheck(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// parseReadTarget maps 1-or-2 positional args to (name, relpath); a lone
|
||||
// "<a>/<b>" splits on the first '/', and relpath "" reads the main SKILL.md.
|
||||
func parseReadTarget(args []string) (name, relpath string, err error) {
|
||||
switch len(args) {
|
||||
case 1:
|
||||
name, relpath = skillcontent.SplitArg(args[0])
|
||||
return name, relpath, nil
|
||||
case 2:
|
||||
return args[0], args[1], nil
|
||||
default:
|
||||
return "", "", errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"read requires 1 or 2 arguments: <name>[/<path>] [path]").
|
||||
WithHint("run 'lark-cli skills read --help'")
|
||||
}
|
||||
}
|
||||
|
||||
// readGuidance routes cross-skill "../lark-foo/..." references back through
|
||||
// `skills read lark-foo/...`: the path guard rejects a literal "../", so the
|
||||
// relative form must be rewritten.
|
||||
func readGuidance(name string) string {
|
||||
return fmt.Sprintf("> Tip: read this skill's own files (e.g. `references/...`) with "+
|
||||
"`lark-cli skills read %s <relative-path>` to keep them in sync with this CLI version. "+
|
||||
"A reference to another skill (`../lark-foo/...`) uses the same command with the "+
|
||||
"leading `../` removed: `lark-cli skills read lark-foo/...`.", name)
|
||||
}
|
||||
306
cmd/skill/skill_test.go
Normal file
306
cmd/skill/skill_test.go
Normal file
@@ -0,0 +1,306 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package skill
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/fs"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// calFS is the default single-skill content tree for these tests. The embedded
|
||||
// FS is now injected through the Factory (no package global), so tests pass it
|
||||
// explicitly to run() — nothing is shared, so they are safe under -parallel.
|
||||
func calFS() fstest.MapFS {
|
||||
return fstest.MapFS{
|
||||
"lark-calendar/SKILL.md": {Data: []byte("---\nname: lark-calendar\nversion: 1.0.0\ndescription: \"Cal\"\nmetadata:\n cliHelp: \"lark-cli calendar --help\"\n---\nbody")},
|
||||
"lark-calendar/references/agenda.md": {Data: []byte("# Agenda")},
|
||||
}
|
||||
}
|
||||
|
||||
// run executes the skills command tree against the given content FS (may be nil
|
||||
// to exercise the not-embedded path) and returns stdout/stderr/err.
|
||||
func run(t *testing.T, fsys fs.FS, args ...string) (stdout, stderr string, err error) {
|
||||
t.Helper()
|
||||
// Isolate CLI config state so tests never read/write the real config dir
|
||||
// (repo convention).
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, out, errOut, _ := cmdutil.TestFactory(t, nil)
|
||||
f.SkillContent = fsys
|
||||
cmd := NewCmdSkill(f)
|
||||
cmd.SetOut(io.Discard)
|
||||
cmd.SetErr(io.Discard)
|
||||
cmd.SetArgs(args)
|
||||
err = cmd.Execute()
|
||||
return out.String(), errOut.String(), err
|
||||
}
|
||||
|
||||
func TestSkillList(t *testing.T) {
|
||||
stdout, _, err := run(t, calFS(), "list")
|
||||
if err != nil {
|
||||
t.Fatalf("list error: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
OK bool `json:"ok"`
|
||||
Skills []map[string]any `json:"skills"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
if e := json.Unmarshal([]byte(stdout), &got); e != nil {
|
||||
t.Fatalf("invalid JSON: %v\n%s", e, stdout)
|
||||
}
|
||||
// "ok" is an explicit success marker (the list envelope is a typed struct;
|
||||
// no automatic _notice attaches).
|
||||
if !got.OK {
|
||||
t.Error("expected ok=true in list envelope")
|
||||
}
|
||||
if got.Count != 1 || len(got.Skills) != 1 {
|
||||
t.Fatalf("count: got %d", got.Count)
|
||||
}
|
||||
if got.Skills[0]["name"] != "lark-calendar" {
|
||||
t.Errorf("name: got %v", got.Skills[0]["name"])
|
||||
}
|
||||
// Top-level list carries version + metadata, not a references list.
|
||||
if _, ok := got.Skills[0]["references"]; ok {
|
||||
t.Error("top-level list must not include references")
|
||||
}
|
||||
if got.Skills[0]["version"] != "1.0.0" {
|
||||
t.Errorf("version: got %v, want 1.0.0", got.Skills[0]["version"])
|
||||
}
|
||||
if _, ok := got.Skills[0]["metadata"]; !ok {
|
||||
t.Error("expected metadata in list entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillListJSONFlagAccepted(t *testing.T) {
|
||||
// `list --json` must be accepted (no-op), not rejected as an unknown flag,
|
||||
// so it stays symmetric with read --json.
|
||||
stdout, _, err := run(t, calFS(), "list", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("list --json error: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
OK bool `json:"ok"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
if e := json.Unmarshal([]byte(stdout), &got); e != nil {
|
||||
t.Fatalf("invalid JSON: %v\n%s", e, stdout)
|
||||
}
|
||||
if !got.OK || got.Count != 1 {
|
||||
t.Errorf("envelope: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillListPath(t *testing.T) {
|
||||
stdout, _, err := run(t, calFS(), "list", "lark-calendar")
|
||||
if err != nil {
|
||||
t.Fatalf("list <name> error: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
OK bool `json:"ok"`
|
||||
Path string `json:"path"`
|
||||
Entries []struct {
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
} `json:"entries"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
if e := json.Unmarshal([]byte(stdout), &got); e != nil {
|
||||
t.Fatalf("invalid JSON: %v\n%s", e, stdout)
|
||||
}
|
||||
if !got.OK || got.Path != "lark-calendar" {
|
||||
t.Errorf("envelope: %+v", got)
|
||||
}
|
||||
// One layer under the skill root: SKILL.md (file) + references (dir).
|
||||
if got.Count != 2 || len(got.Entries) != 2 {
|
||||
t.Fatalf("entries: got %+v", got.Entries)
|
||||
}
|
||||
if got.Entries[0].Path != "lark-calendar/SKILL.md" || got.Entries[0].IsDir {
|
||||
t.Errorf("entry[0]: got %+v", got.Entries[0])
|
||||
}
|
||||
if got.Entries[1].Path != "lark-calendar/references" || !got.Entries[1].IsDir {
|
||||
t.Errorf("entry[1]: got %+v", got.Entries[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillListPathUnknown(t *testing.T) {
|
||||
_, _, err := run(t, calFS(), "list", "no-such-skill")
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown skill") {
|
||||
t.Fatalf("expected 'unknown skill' error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillListPathTraversal(t *testing.T) {
|
||||
stdout, _, err := run(t, calFS(), "list", "lark-calendar/../../etc")
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid path") {
|
||||
t.Fatalf("expected 'invalid path' error, got %v", err)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Errorf("stdout must be empty on rejection, got %q", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillListTooManyArgs(t *testing.T) {
|
||||
_, _, err := run(t, calFS(), "list", "a", "b")
|
||||
if err == nil || !strings.Contains(err.Error(), "at most 1 argument") {
|
||||
t.Fatalf("expected 'at most 1 argument' error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSkillListSkipsDirWithoutSKILLmd proves a top-level dir lacking SKILL.md is
|
||||
// omitted from the catalog (no blank entry).
|
||||
func TestSkillListSkipsDirWithoutSKILLmd(t *testing.T) {
|
||||
fsys := fstest.MapFS{
|
||||
"lark-calendar/SKILL.md": {Data: []byte("---\nname: lark-calendar\ndescription: \"Cal\"\n---\nb")},
|
||||
"not-a-skill/readme.txt": {Data: []byte("junk")}, // dir without SKILL.md
|
||||
}
|
||||
stdout, _, err := run(t, fsys, "list")
|
||||
if err != nil {
|
||||
t.Fatalf("list error: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Skills []map[string]any `json:"skills"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
if e := json.Unmarshal([]byte(stdout), &got); e != nil {
|
||||
t.Fatalf("invalid JSON: %v\n%s", e, stdout)
|
||||
}
|
||||
if got.Count != 1 || got.Skills[0]["name"] != "lark-calendar" {
|
||||
t.Fatalf("expected only lark-calendar, got %+v", got.Skills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadRaw(t *testing.T) {
|
||||
stdout, stderr, err := run(t, calFS(), "read", "lark-calendar")
|
||||
if err != nil {
|
||||
t.Fatalf("read error: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(stdout, "---\nname: lark-calendar") {
|
||||
t.Errorf("raw output: got %q", stdout)
|
||||
}
|
||||
// Raw stdout is byte-pure SKILL.md — the guidance tip must NOT be appended.
|
||||
if strings.Contains(stdout, "Tip:") {
|
||||
t.Errorf("raw stdout must not carry the guidance tip: got %q", stdout)
|
||||
}
|
||||
// Guidance goes to stderr: own files via `skills read <name> ...`, and
|
||||
// cross-skill refs routed to `skills read <other-skill> ...` (version-
|
||||
// consistent), not "read directly".
|
||||
if !strings.Contains(stderr, "lark-cli skills read lark-calendar <relative-path>") {
|
||||
t.Errorf("expected own-files guidance on stderr: got %q", stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, "lark-cli skills read lark-foo/...") {
|
||||
t.Errorf("expected cross-skill refs routed to skills read: got %q", stderr)
|
||||
}
|
||||
if strings.Contains(stderr, "instead of opening them directly") ||
|
||||
strings.Contains(stderr, "read those directly") {
|
||||
t.Errorf("guidance must not steer cross-skill refs to direct reads: got %q", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadJSON(t *testing.T) {
|
||||
stdout, _, err := run(t, calFS(), "read", "lark-calendar", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("read --json error: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Skill, Path, Content, Guidance string
|
||||
}
|
||||
if e := json.Unmarshal([]byte(stdout), &got); e != nil {
|
||||
t.Fatalf("invalid JSON: %v", e)
|
||||
}
|
||||
if got.Skill != "lark-calendar" || got.Path != "SKILL.md" || got.Content == "" {
|
||||
t.Errorf("envelope: %+v", got)
|
||||
}
|
||||
// Guidance is a separate field, not merged into content.
|
||||
if got.Guidance == "" {
|
||||
t.Error("expected guidance field for main SKILL.md")
|
||||
}
|
||||
if strings.Contains(got.Content, "Tip:") {
|
||||
t.Error("guidance must not be merged into content")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadFile(t *testing.T) {
|
||||
// Both the 2-arg and slash forms read the same file, with no guidance tip.
|
||||
for _, args := range [][]string{
|
||||
{"read", "lark-calendar", "references/agenda.md"},
|
||||
{"read", "lark-calendar/references/agenda.md"},
|
||||
} {
|
||||
stdout, stderr, err := run(t, calFS(), args...)
|
||||
if err != nil {
|
||||
t.Fatalf("read %v error: %v", args, err)
|
||||
}
|
||||
if stdout != "# Agenda" {
|
||||
t.Errorf("read %v output: got %q", args, stdout)
|
||||
}
|
||||
// Reference reads carry no guidance on either stream.
|
||||
if strings.Contains(stderr, "Tip:") {
|
||||
t.Errorf("read %v must not emit guidance on stderr: got %q", args, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadFileJSON(t *testing.T) {
|
||||
stdout, _, err := run(t, calFS(), "read", "lark-calendar", "references/agenda.md", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("read file --json error: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Skill, Path, Content, Guidance string
|
||||
}
|
||||
if e := json.Unmarshal([]byte(stdout), &got); e != nil {
|
||||
t.Fatalf("invalid JSON: %v\n%s", e, stdout)
|
||||
}
|
||||
if got.Skill != "lark-calendar" || got.Path != "references/agenda.md" || got.Content != "# Agenda" {
|
||||
t.Errorf("envelope: %+v", got)
|
||||
}
|
||||
// Reference reads do not carry the guidance tip.
|
||||
if got.Guidance != "" {
|
||||
t.Errorf("reference read must not include guidance, got %q", got.Guidance)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadUnknown(t *testing.T) {
|
||||
_, _, err := run(t, calFS(), "read", "no-such")
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown skill") {
|
||||
t.Errorf("err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadMissingArg(t *testing.T) {
|
||||
_, _, err := run(t, calFS(), "read")
|
||||
if err == nil || !strings.Contains(err.Error(), "requires 1 or 2 arguments") {
|
||||
t.Fatalf("expected arg error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillReadTraversal(t *testing.T) {
|
||||
stdout, _, err := run(t, calFS(), "read", "lark-calendar", "../../etc/passwd")
|
||||
if err == nil {
|
||||
t.Fatal("expected rejection")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "invalid path") {
|
||||
t.Errorf("err: %v", err)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Errorf("stdout must be empty on rejection, got %q", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillNilContentFS(t *testing.T) {
|
||||
_, _, err := run(t, nil, "list")
|
||||
if err == nil {
|
||||
t.Fatal("expected error when SkillContent is nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "not embedded") {
|
||||
t.Errorf("err: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -49,12 +49,21 @@ func mockDetectAndNpm(t *testing.T, result selfupdate.DetectResult, npmFn func(s
|
||||
u.DetectOverride = func() selfupdate.DetectResult { return result }
|
||||
u.NpmInstallOverride = npmFn
|
||||
u.VerifyOverride = func(string) error { return nil }
|
||||
u.SkillsIndexFetchOverride = successfulSkillsIndexFetch()
|
||||
u.SkillsCommandOverride = successfulSkillsCommand()
|
||||
return u
|
||||
}
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
}
|
||||
|
||||
func successfulSkillsIndexFetch() func() *selfupdate.NpmResult {
|
||||
return func() *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stdout.WriteString(`{"skills":[{"name":"lark-calendar"},{"name":"lark-mail"}]}`)
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
func successfulSkillsCommand() func(args ...string) *selfupdate.NpmResult {
|
||||
return func(args ...string) *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
@@ -478,6 +487,10 @@ func TestUpdateNpmVerifyFail_JSON_NoRestoreHintWhenBackupUnavailable(t *testing.
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} }
|
||||
u.VerifyOverride = func(string) error { return errors.New("bad binary") }
|
||||
u.RestoreAvailableOverride = func() bool { return false }
|
||||
u.SkillsIndexFetchOverride = func() *selfupdate.NpmResult {
|
||||
t.Fatal("skills sync should not run when binary verification fails")
|
||||
return nil
|
||||
}
|
||||
u.SkillsCommandOverride = func(args ...string) *selfupdate.NpmResult {
|
||||
t.Fatal("skills sync should not run when binary verification fails")
|
||||
return nil
|
||||
@@ -810,6 +823,11 @@ func TestUpdateNpm_SkillsFail_JSON(t *testing.T) {
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} }
|
||||
u.VerifyOverride = func(string) error { return nil }
|
||||
u.SkillsIndexFetchOverride = func() *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Err = fmt.Errorf("index unavailable")
|
||||
return r
|
||||
}
|
||||
u.SkillsCommandOverride = func(args ...string) *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stderr.WriteString("npx: command not found")
|
||||
@@ -862,6 +880,11 @@ func TestUpdateNpm_SkillsFail_Human(t *testing.T) {
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} }
|
||||
u.VerifyOverride = func(string) error { return nil }
|
||||
u.SkillsIndexFetchOverride = func() *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Err = fmt.Errorf("index unavailable")
|
||||
return r
|
||||
}
|
||||
u.SkillsCommandOverride = func(args ...string) *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stderr.WriteString("npx: command not found")
|
||||
@@ -1006,6 +1029,7 @@ func TestUpdateRun_AlreadyLatest_RunsSkillsSync(t *testing.T) {
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
return &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: successfulSkillsIndexFetch(),
|
||||
SkillsCommandOverride: func(args ...string) *selfupdate.NpmResult {
|
||||
skillsCalled = true
|
||||
return successfulSkillsCommand()(args...)
|
||||
@@ -1044,6 +1068,7 @@ func TestUpdateRun_Manual_RunsSkillsSync(t *testing.T) {
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
return &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: successfulSkillsIndexFetch(),
|
||||
DetectOverride: func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{
|
||||
Method: selfupdate.InstallManual,
|
||||
@@ -1088,6 +1113,7 @@ func TestUpdateRun_Npm_RunsSkillsSync_WritesLatestState(t *testing.T) {
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
return &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: successfulSkillsIndexFetch(),
|
||||
DetectOverride: func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{
|
||||
Method: selfupdate.InstallNpm, NpmAvailable: true,
|
||||
@@ -1147,6 +1173,10 @@ func TestUpdateRun_CheckIncludesSkillsStatus(t *testing.T) {
|
||||
DetectOverride: func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{Method: selfupdate.InstallNpm, NpmAvailable: true}
|
||||
},
|
||||
SkillsIndexFetchOverride: func() *selfupdate.NpmResult {
|
||||
skillsCalled = true
|
||||
return successfulSkillsIndexFetch()()
|
||||
},
|
||||
SkillsCommandOverride: func(args ...string) *selfupdate.NpmResult {
|
||||
skillsCalled = true
|
||||
return successfulSkillsCommand()(args...)
|
||||
@@ -1196,6 +1226,10 @@ func TestUpdateRun_CheckAlreadyLatest_NoSideEffect(t *testing.T) {
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
return &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: func() *selfupdate.NpmResult {
|
||||
skillsCalled = true
|
||||
return successfulSkillsIndexFetch()()
|
||||
},
|
||||
SkillsCommandOverride: func(args ...string) *selfupdate.NpmResult {
|
||||
skillsCalled = true
|
||||
return successfulSkillsCommand()(args...)
|
||||
|
||||
@@ -6,6 +6,7 @@ package cmdutil
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -43,6 +44,8 @@ type Factory struct {
|
||||
Credential *credential.CredentialProvider
|
||||
|
||||
FileIOProvider fileio.Provider // file transfer provider (default: local filesystem)
|
||||
|
||||
SkillContent fs.FS // embedded skill tree (rooted at the skill list); nil when the build embeds no skills
|
||||
}
|
||||
|
||||
// ResolveFileIO resolves a FileIO instance using the current execution context.
|
||||
|
||||
@@ -10,10 +10,13 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/transport"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
@@ -37,9 +40,15 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
npmInstallTimeout = 10 * time.Minute
|
||||
skillsUpdateTimeout = 2 * time.Minute
|
||||
verifyTimeout = 10 * time.Second
|
||||
npmInstallTimeout = 10 * time.Minute
|
||||
skillsUpdateTimeout = 2 * time.Minute
|
||||
skillsIndexMaxBodySize = 1 << 20
|
||||
verifyTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
skillsIndexFetchTimeout = 10 * time.Second
|
||||
officialSkillsIndexURL = "https://open.feishu.cn/.well-known/skills/index.json"
|
||||
)
|
||||
|
||||
// DetectResult holds installation detection results.
|
||||
@@ -83,6 +92,7 @@ func (r *NpmResult) CombinedOutput() string {
|
||||
type Updater struct {
|
||||
DetectOverride func() DetectResult
|
||||
NpmInstallOverride func(version string) *NpmResult
|
||||
SkillsIndexFetchOverride func() *NpmResult
|
||||
SkillsCommandOverride func(args ...string) *NpmResult
|
||||
VerifyOverride func(expectedVersion string) error
|
||||
RestoreAvailableOverride func() bool
|
||||
@@ -153,6 +163,53 @@ func (u *Updater) RunNpmInstall(version string) *NpmResult {
|
||||
return r
|
||||
}
|
||||
|
||||
func (u *Updater) ListOfficialSkillsIndex() *NpmResult {
|
||||
if u.SkillsIndexFetchOverride != nil {
|
||||
return u.SkillsIndexFetchOverride()
|
||||
}
|
||||
|
||||
r := &NpmResult{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), skillsIndexFetchTimeout)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, officialSkillsIndexURL, nil)
|
||||
if err != nil {
|
||||
r.Err = err
|
||||
return r
|
||||
}
|
||||
|
||||
client := transport.NewHTTPClient(0)
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("official skills index redirected to non-HTTPS URL: %s", req.URL.Redacted())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
r.Err = err
|
||||
return r
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
r.Err = fmt.Errorf("official skills index returned HTTP %d", resp.StatusCode)
|
||||
return r
|
||||
}
|
||||
|
||||
limited := io.LimitReader(resp.Body, skillsIndexMaxBodySize+1)
|
||||
if _, err := io.Copy(&r.Stdout, limited); err != nil {
|
||||
r.Err = err
|
||||
return r
|
||||
}
|
||||
if r.Stdout.Len() > skillsIndexMaxBodySize {
|
||||
r.Stdout.Reset()
|
||||
r.Err = fmt.Errorf("official skills index exceeds %d bytes", skillsIndexMaxBodySize)
|
||||
return r
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (u *Updater) ListOfficialSkills() *NpmResult {
|
||||
r := u.runSkillsListOfficial("https://open.feishu.cn")
|
||||
if r.Err != nil {
|
||||
|
||||
@@ -4,12 +4,18 @@
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
@@ -232,6 +238,113 @@ func TestSkillsCommandsUseExpectedArgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsIndexSuccess(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"skills":[{"name":"lark-calendar"}]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := officialSkillsIndexURL
|
||||
officialSkillsIndexURL = server.URL
|
||||
t.Cleanup(func() { officialSkillsIndexURL = oldURL })
|
||||
|
||||
result := New().ListOfficialSkillsIndex()
|
||||
if result.Err != nil {
|
||||
t.Fatalf("ListOfficialSkillsIndex() err = %v, want nil", result.Err)
|
||||
}
|
||||
if got := result.Stdout.String(); !strings.Contains(got, "lark-calendar") {
|
||||
t.Fatalf("ListOfficialSkillsIndex() stdout = %q, want skill JSON", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsIndexHTTPError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := officialSkillsIndexURL
|
||||
officialSkillsIndexURL = server.URL
|
||||
t.Cleanup(func() { officialSkillsIndexURL = oldURL })
|
||||
|
||||
result := New().ListOfficialSkillsIndex()
|
||||
if result.Err == nil || !strings.Contains(result.Err.Error(), "HTTP 404") {
|
||||
t.Fatalf("ListOfficialSkillsIndex() err = %v, want HTTP 404", result.Err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsIndexBodyTooLarge(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, strings.Repeat("x", skillsIndexMaxBodySize+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := officialSkillsIndexURL
|
||||
officialSkillsIndexURL = server.URL
|
||||
t.Cleanup(func() { officialSkillsIndexURL = oldURL })
|
||||
|
||||
result := New().ListOfficialSkillsIndex()
|
||||
if result.Err == nil || !strings.Contains(result.Err.Error(), "exceeds") {
|
||||
t.Fatalf("ListOfficialSkillsIndex() err = %v, want exceeds", result.Err)
|
||||
}
|
||||
if result.Stdout.Len() != 0 {
|
||||
t.Fatalf("ListOfficialSkillsIndex() stdout len = %d, want 0", result.Stdout.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsIndexTimeout(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
fmt.Fprint(w, `{"skills":[{"name":"lark-calendar"}]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := officialSkillsIndexURL
|
||||
oldTimeout := skillsIndexFetchTimeout
|
||||
officialSkillsIndexURL = server.URL
|
||||
skillsIndexFetchTimeout = 50 * time.Millisecond
|
||||
t.Cleanup(func() {
|
||||
officialSkillsIndexURL = oldURL
|
||||
skillsIndexFetchTimeout = oldTimeout
|
||||
})
|
||||
|
||||
result := New().ListOfficialSkillsIndex()
|
||||
var netErr net.Error
|
||||
if result.Err == nil || (!errors.Is(result.Err, context.DeadlineExceeded) && !(errors.As(result.Err, &netErr) && netErr.Timeout())) {
|
||||
t.Fatalf("ListOfficialSkillsIndex() err = %v, want timeout error", result.Err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsIndexRejectsNonHTTPSRedirect(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://example.com/skills.json", http.StatusFound)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := officialSkillsIndexURL
|
||||
officialSkillsIndexURL = server.URL
|
||||
t.Cleanup(func() { officialSkillsIndexURL = oldURL })
|
||||
|
||||
result := New().ListOfficialSkillsIndex()
|
||||
if result.Err == nil || !strings.Contains(result.Err.Error(), "non-HTTPS") {
|
||||
t.Fatalf("ListOfficialSkillsIndex() err = %v, want non-HTTPS redirect", result.Err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsIndexUsesOverride(t *testing.T) {
|
||||
result := (&Updater{SkillsIndexFetchOverride: func() *NpmResult {
|
||||
r := &NpmResult{}
|
||||
r.Stdout.WriteString(`{"skills":[{"name":"override-skill"}]}`)
|
||||
return r
|
||||
}}).ListOfficialSkillsIndex()
|
||||
if result.Err != nil {
|
||||
t.Fatalf("ListOfficialSkillsIndex() err = %v, want nil", result.Err)
|
||||
}
|
||||
if !strings.Contains(result.Stdout.String(), "override-skill") {
|
||||
t.Fatalf("ListOfficialSkillsIndex() stdout = %q, want override result", result.Stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOfficialSkillsFallsBack(t *testing.T) {
|
||||
called := []string{}
|
||||
updater := &Updater{
|
||||
|
||||
209
internal/skillcontent/reader.go
Normal file
209
internal/skillcontent/reader.go
Normal file
@@ -0,0 +1,209 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package skillcontent reads embedded skill content from an injected fs.FS
|
||||
// rooted at the skill list (entries like "lark-calendar/SKILL.md").
|
||||
package skillcontent
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Reader struct {
|
||||
fsys fs.FS
|
||||
}
|
||||
|
||||
func New(fsys fs.FS) *Reader { return &Reader{fsys: fsys} }
|
||||
|
||||
type SkillInfo struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// DirEntry.Path is skill-prefixed (e.g. "lark-doc/references/x.md") so it can be
|
||||
// fed straight back into `read`.
|
||||
type DirEntry struct {
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
}
|
||||
|
||||
func (r *Reader) List() ([]SkillInfo, error) {
|
||||
entries, err := fs.ReadDir(r.fsys, ".")
|
||||
if err != nil {
|
||||
return nil, errs.NewInternalError(errs.SubtypeFileIO, "failed to read embedded skills: %v", err)
|
||||
}
|
||||
out := make([]SkillInfo, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
// Skip dirs that aren't real skills (no SKILL.md).
|
||||
if info, ok := r.skillInfo(e.Name()); ok {
|
||||
out = append(out, info)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *Reader) skillInfo(name string) (SkillInfo, bool) {
|
||||
data, err := fs.ReadFile(r.fsys, name+"/SKILL.md")
|
||||
if err != nil {
|
||||
return SkillInfo{}, false
|
||||
}
|
||||
desc, version, metadata := parseFrontmatter(data)
|
||||
return SkillInfo{Name: name, Description: desc, Version: version, Metadata: metadata}, true
|
||||
}
|
||||
|
||||
// ListPath lists one directory layer (no recursion) under "<name>" or
|
||||
// "<name>/<sub>", returning the entries and the cleaned path listed.
|
||||
func (r *Reader) ListPath(arg string) ([]DirEntry, string, error) {
|
||||
name, sub := SplitArg(arg)
|
||||
if err := r.ensureSkill(name); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
dir := name
|
||||
if sub != "" {
|
||||
cleaned, err := cleanSubPath(sub)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
dir = name + "/" + cleaned
|
||||
info, err := fs.Stat(r.fsys, dir)
|
||||
if err != nil {
|
||||
return nil, "", errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"path %q not found in skill %q", sub, name).
|
||||
WithHint("run 'lark-cli skills list " + name + "' to see files in this skill")
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil, "", errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"path %q is a file, not a directory; use 'lark-cli skills read %s/%s' to read it", sub, name, cleaned)
|
||||
}
|
||||
}
|
||||
entries, err := fs.ReadDir(r.fsys, dir)
|
||||
if err != nil {
|
||||
return nil, "", errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"failed to read embedded skill content: %v", err)
|
||||
}
|
||||
out := make([]DirEntry, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
out = append(out, DirEntry{Path: dir + "/" + e.Name(), IsDir: e.IsDir()})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
|
||||
return out, dir, nil
|
||||
}
|
||||
|
||||
// SplitArg splits "<name>/<rest>" at the first separator; an argument with no
|
||||
// separator is a bare skill name (rest "").
|
||||
func SplitArg(arg string) (name, rest string) {
|
||||
name, rest, _ = strings.Cut(arg, "/")
|
||||
return name, rest
|
||||
}
|
||||
|
||||
// parseFrontmatter best-effort-extracts the frontmatter fields; missing or
|
||||
// unparseable frontmatter yields ("", "", nil), never an error.
|
||||
func parseFrontmatter(skillMD []byte) (description, version string, metadata map[string]any) {
|
||||
lines := strings.Split(string(skillMD), "\n")
|
||||
if strings.TrimRight(lines[0], "\r") != "---" {
|
||||
return "", "", nil
|
||||
}
|
||||
block := make([]string, 0, len(lines))
|
||||
closed := false
|
||||
for _, ln := range lines[1:] {
|
||||
if strings.TrimRight(ln, "\r") == "---" {
|
||||
closed = true
|
||||
break
|
||||
}
|
||||
block = append(block, ln)
|
||||
}
|
||||
if !closed {
|
||||
return "", "", nil
|
||||
}
|
||||
var fm struct {
|
||||
Description string `yaml:"description"`
|
||||
Version string `yaml:"version"`
|
||||
Metadata map[string]any `yaml:"metadata"`
|
||||
}
|
||||
if err := yaml.Unmarshal([]byte(strings.Join(block, "\n")), &fm); err != nil {
|
||||
return "", "", nil
|
||||
}
|
||||
return fm.Description, fm.Version, fm.Metadata
|
||||
}
|
||||
|
||||
func (r *Reader) ReadSkill(name string) ([]byte, error) {
|
||||
if err := r.ensureSkill(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := fs.ReadFile(r.fsys, name+"/SKILL.md")
|
||||
if err != nil {
|
||||
return nil, errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"failed to read embedded skill content: %v", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (r *Reader) ensureSkill(name string) error {
|
||||
if name == "" || strings.ContainsAny(name, `/\`) || name == "." || name == ".." {
|
||||
return unknownSkill(name)
|
||||
}
|
||||
info, err := fs.Stat(r.fsys, name)
|
||||
if err != nil || !info.IsDir() {
|
||||
return unknownSkill(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unknownSkill(name string) error {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unknown skill %q", name).
|
||||
WithHint("run 'lark-cli skills list' to see available skills")
|
||||
}
|
||||
|
||||
// cleanSubPath returns the cleaned form of relpath, rejecting absolute paths and
|
||||
// ".." escapes. relpath must be non-empty (callers handle the skill-root case).
|
||||
func cleanSubPath(relpath string) (string, error) {
|
||||
cleaned := path.Clean(relpath)
|
||||
// path.Clean only treats '/' as a separator, so a Windows-style "..\" prefix
|
||||
// survives; reject it explicitly alongside "../".
|
||||
if relpath == "" || path.IsAbs(relpath) || cleaned == "." ||
|
||||
cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, `..\`) {
|
||||
return "", errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"invalid path %q: must be a relative path without '..'", relpath)
|
||||
}
|
||||
return cleaned, nil
|
||||
}
|
||||
|
||||
// ReadReference returns the bytes of <name>/<relpath> and the cleaned path.
|
||||
func (r *Reader) ReadReference(name, relpath string) ([]byte, string, error) {
|
||||
if err := r.ensureSkill(name); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cleaned, err := cleanSubPath(relpath)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
full := name + "/" + cleaned
|
||||
info, err := fs.Stat(r.fsys, full)
|
||||
if err != nil {
|
||||
return nil, "", errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"reference %q not found in skill %q", relpath, name).
|
||||
WithHint("run 'lark-cli skills list " + name + "' to see files in this skill")
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil, "", errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"reference %q is a directory, not a file", relpath)
|
||||
}
|
||||
data, err := fs.ReadFile(r.fsys, full)
|
||||
if err != nil {
|
||||
return nil, "", errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"failed to read embedded skill content: %v", err)
|
||||
}
|
||||
return data, cleaned, nil
|
||||
}
|
||||
290
internal/skillcontent/reader_test.go
Normal file
290
internal/skillcontent/reader_test.go
Normal file
@@ -0,0 +1,290 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package skillcontent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
)
|
||||
|
||||
func testFS() fstest.MapFS {
|
||||
return fstest.MapFS{
|
||||
"lark-calendar/SKILL.md": {Data: []byte("---\nname: lark-calendar\nversion: 1.0.0\ndescription: \"Calendar skill\"\nmetadata:\n requires:\n bins: [\"lark-cli\"]\n cliHelp: \"lark-cli calendar --help\"\n---\nbody\n")},
|
||||
"lark-calendar/references/agenda.md": {Data: []byte("# Agenda")},
|
||||
"lark-calendar/references/create.md": {Data: []byte("# Create")},
|
||||
"lark-calendar/assets/tpl.html": {Data: []byte("<html></html>")},
|
||||
"lark-im/SKILL.md": {Data: []byte("no frontmatter here\n")},
|
||||
"lark-im/references/send.md": {Data: []byte("# Send")},
|
||||
}
|
||||
}
|
||||
|
||||
func TestList(t *testing.T) {
|
||||
r := New(testFS())
|
||||
skills, err := r.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List() error: %v", err)
|
||||
}
|
||||
if len(skills) != 2 {
|
||||
t.Fatalf("got %d skills, want 2", len(skills))
|
||||
}
|
||||
if skills[0].Name != "lark-calendar" || skills[1].Name != "lark-im" {
|
||||
t.Fatalf("skills not sorted by name: %v", skills)
|
||||
}
|
||||
if skills[0].Description != "Calendar skill" {
|
||||
t.Errorf("description: got %q, want %q", skills[0].Description, "Calendar skill")
|
||||
}
|
||||
// version is the frontmatter `version:` field, passed through for drift checks.
|
||||
if skills[0].Version != "1.0.0" {
|
||||
t.Errorf("version: got %q, want %q", skills[0].Version, "1.0.0")
|
||||
}
|
||||
// metadata is the frontmatter `metadata:` block, passed through verbatim.
|
||||
if skills[0].Metadata == nil {
|
||||
t.Fatal("expected metadata for lark-calendar")
|
||||
}
|
||||
if skills[0].Metadata["cliHelp"] != "lark-cli calendar --help" {
|
||||
t.Errorf("metadata.cliHelp: got %v", skills[0].Metadata["cliHelp"])
|
||||
}
|
||||
// No frontmatter → empty description and nil metadata (omitted from JSON).
|
||||
if skills[1].Description != "" {
|
||||
t.Errorf("lark-im description: got %q, want empty", skills[1].Description)
|
||||
}
|
||||
if skills[1].Metadata != nil {
|
||||
t.Errorf("lark-im metadata: got %v, want nil", skills[1].Metadata)
|
||||
}
|
||||
if skills[1].Version != "" {
|
||||
t.Errorf("lark-im version: got %q, want empty", skills[1].Version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPath(t *testing.T) {
|
||||
r := New(testFS())
|
||||
|
||||
// Skill root: direct children only (one layer), each path skill-prefixed.
|
||||
entries, listed, err := r.ListPath("lark-calendar")
|
||||
if err != nil {
|
||||
t.Fatalf("ListPath root error: %v", err)
|
||||
}
|
||||
if listed != "lark-calendar" {
|
||||
t.Errorf("listed path: got %q", listed)
|
||||
}
|
||||
want := map[string]bool{ // path → isDir
|
||||
"lark-calendar/SKILL.md": false,
|
||||
"lark-calendar/references": true,
|
||||
"lark-calendar/assets": true,
|
||||
}
|
||||
if len(entries) != len(want) {
|
||||
t.Fatalf("root entries: got %v, want %d entries", entries, len(want))
|
||||
}
|
||||
for _, e := range entries {
|
||||
isDir, ok := want[e.Path]
|
||||
if !ok {
|
||||
t.Errorf("unexpected entry %q", e.Path)
|
||||
continue
|
||||
}
|
||||
if e.IsDir != isDir {
|
||||
t.Errorf("%q is_dir: got %v, want %v", e.Path, e.IsDir, isDir)
|
||||
}
|
||||
}
|
||||
// Entries are sorted by path.
|
||||
if entries[0].Path != "lark-calendar/SKILL.md" {
|
||||
t.Errorf("entries not sorted: %v", entries)
|
||||
}
|
||||
|
||||
// Subdirectory: one layer under <name>/<subpath>.
|
||||
subEntries, subListed, err := r.ListPath("lark-calendar/references")
|
||||
if err != nil {
|
||||
t.Fatalf("ListPath subdir error: %v", err)
|
||||
}
|
||||
if subListed != "lark-calendar/references" {
|
||||
t.Errorf("listed subpath: got %q", subListed)
|
||||
}
|
||||
if len(subEntries) != 2 ||
|
||||
subEntries[0].Path != "lark-calendar/references/agenda.md" ||
|
||||
subEntries[1].Path != "lark-calendar/references/create.md" {
|
||||
t.Errorf("subdir entries: got %v", subEntries)
|
||||
}
|
||||
|
||||
// Unknown skill → typed validation error.
|
||||
if _, _, err := r.ListPath("no-such-skill"); err == nil {
|
||||
t.Error("expected error for unknown skill")
|
||||
} else {
|
||||
var verr *errs.ValidationError
|
||||
if !errors.As(err, &verr) {
|
||||
t.Errorf("expected *errs.ValidationError, got %T", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Path that points at a file (not a dir) → validation error.
|
||||
if _, _, err := r.ListPath("lark-calendar/SKILL.md"); err == nil {
|
||||
t.Error("expected error listing a file")
|
||||
} else if !strings.Contains(err.Error(), "is a file") {
|
||||
t.Errorf("message: got %q", err.Error())
|
||||
}
|
||||
|
||||
// Nonexistent subpath → validation error.
|
||||
if _, _, err := r.ListPath("lark-calendar/nope"); err == nil {
|
||||
t.Error("expected not-found error")
|
||||
} else if !strings.Contains(err.Error(), "not found") {
|
||||
t.Errorf("message: got %q", err.Error())
|
||||
}
|
||||
|
||||
// Traversal in the subpath is rejected, no listing leaked.
|
||||
for _, bad := range []string{"lark-calendar/../lark-im", "lark-calendar/../../etc", `lark-calendar/..\x`} {
|
||||
entries, _, err := r.ListPath(bad)
|
||||
if err == nil {
|
||||
t.Errorf("expected rejection for %q", bad)
|
||||
}
|
||||
if entries != nil {
|
||||
t.Errorf("entries leaked for %q: %v", bad, entries)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadSkill(t *testing.T) {
|
||||
r := New(testFS())
|
||||
|
||||
data, err := r.ReadSkill("lark-calendar")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadSkill error: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(string(data), "---\nname: lark-calendar") {
|
||||
t.Errorf("unexpected content: %q", string(data))
|
||||
}
|
||||
|
||||
_, err = r.ReadSkill("no-such-skill")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unknown skill")
|
||||
}
|
||||
var verr *errs.ValidationError
|
||||
if !errors.As(err, &verr) {
|
||||
t.Fatalf("expected *errs.ValidationError, got %T", err)
|
||||
}
|
||||
if !strings.Contains(verr.Message, `unknown skill "no-such-skill"`) {
|
||||
t.Errorf("message: got %q", verr.Message)
|
||||
}
|
||||
|
||||
if _, err := r.ReadSkill("../etc"); err == nil {
|
||||
t.Error("expected error for name with separator")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadReference(t *testing.T) {
|
||||
r := New(testFS())
|
||||
|
||||
data, cleaned, err := r.ReadReference("lark-calendar", "references/agenda.md")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadReference error: %v", err)
|
||||
}
|
||||
if string(data) != "# Agenda" {
|
||||
t.Errorf("content: got %q", string(data))
|
||||
}
|
||||
if cleaned != "references/agenda.md" {
|
||||
t.Errorf("cleaned path: got %q", cleaned)
|
||||
}
|
||||
|
||||
if _, _, err := r.ReadReference("lark-calendar", "references/nope.md"); err == nil {
|
||||
t.Error("expected not-found error")
|
||||
} else if !strings.Contains(err.Error(), "not found") {
|
||||
t.Errorf("message: got %q", err.Error())
|
||||
}
|
||||
|
||||
if _, _, err := r.ReadReference("lark-calendar", "references"); err == nil {
|
||||
t.Error("expected directory error")
|
||||
} else if !strings.Contains(err.Error(), "is a directory") {
|
||||
t.Errorf("message: got %q", err.Error())
|
||||
}
|
||||
|
||||
for _, bad := range []string{"../../etc/passwd", "/etc/passwd", "..", "", "references/../../im/SKILL.md", `..\..\x`} {
|
||||
data, _, err := r.ReadReference("lark-calendar", bad)
|
||||
if err == nil {
|
||||
t.Errorf("expected rejection for %q", bad)
|
||||
}
|
||||
if data != nil {
|
||||
t.Errorf("content leaked for %q: %q", bad, string(data))
|
||||
}
|
||||
var verr *errs.ValidationError
|
||||
if !errors.As(err, &verr) {
|
||||
t.Errorf("expected validation error for %q, got %T", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFrontmatter(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
wantDesc string
|
||||
wantVer string
|
||||
wantHasMeta bool
|
||||
}{
|
||||
{
|
||||
name: "description, version and metadata",
|
||||
input: "---\ndescription: My skill\nversion: 2.1.0\nmetadata:\n cliHelp: \"x\"\n---\nbody\n",
|
||||
wantDesc: "My skill",
|
||||
wantVer: "2.1.0",
|
||||
wantHasMeta: true,
|
||||
},
|
||||
{
|
||||
name: "description only, no metadata",
|
||||
input: "---\ndescription: Plain\n---\nbody\n",
|
||||
wantDesc: "Plain",
|
||||
},
|
||||
{
|
||||
name: "no frontmatter",
|
||||
input: "no frontmatter here\n",
|
||||
},
|
||||
{
|
||||
name: "unclosed frontmatter",
|
||||
input: "---\ndescription: Never closed\n",
|
||||
},
|
||||
{
|
||||
name: "malformed YAML inside frontmatter",
|
||||
input: "---\n: bad: yaml: [\n---\nbody\n",
|
||||
},
|
||||
{
|
||||
name: "CRLF line endings",
|
||||
input: "---\r\ndescription: CRLF skill\r\nmetadata:\r\n cliHelp: \"y\"\r\n---\r\nbody\r\n",
|
||||
wantDesc: "CRLF skill",
|
||||
wantHasMeta: true,
|
||||
},
|
||||
{
|
||||
name: "empty input",
|
||||
input: "",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
desc, ver, meta := parseFrontmatter([]byte(tc.input))
|
||||
if desc != tc.wantDesc {
|
||||
t.Errorf("description = %q, want %q", desc, tc.wantDesc)
|
||||
}
|
||||
if ver != tc.wantVer {
|
||||
t.Errorf("version = %q, want %q", ver, tc.wantVer)
|
||||
}
|
||||
if (meta != nil) != tc.wantHasMeta {
|
||||
t.Errorf("metadata = %v, wantHasMeta %v", meta, tc.wantHasMeta)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadSkillMissingFile(t *testing.T) {
|
||||
// Use a separate MapFS so testFS() (and TestList) are unaffected.
|
||||
emptyFS := fstest.MapFS{
|
||||
"lark-empty/references/x.md": {Data: []byte("# X")},
|
||||
}
|
||||
r := New(emptyFS)
|
||||
_, err := r.ReadSkill("lark-empty")
|
||||
if err == nil {
|
||||
t.Fatal("expected error when SKILL.md is absent")
|
||||
}
|
||||
var ierr *errs.InternalError
|
||||
if !errors.As(err, &ierr) {
|
||||
t.Fatalf("expected *errs.InternalError, got %T: %v", err, err)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"github.com/larksuite/cli/internal/selfupdate"
|
||||
)
|
||||
|
||||
const skillsStateUpdatedAtLayout = "2006-01-02T15:04:05"
|
||||
|
||||
var (
|
||||
skillNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_:-]*(@[^\s]+)?$`)
|
||||
ansiPattern = regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]`)
|
||||
@@ -80,6 +82,30 @@ func ParseGlobalSkillsJSON(text string) []string {
|
||||
return sortedKeys(seen)
|
||||
}
|
||||
|
||||
func ParseOfficialSkillsIndexJSON(text string) ([]string, error) {
|
||||
type officialSkill struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
type officialIndex struct {
|
||||
Skills []officialSkill `json:"skills"`
|
||||
}
|
||||
|
||||
var index officialIndex
|
||||
if err := json.Unmarshal([]byte(text), &index); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, skill := range index.Skills {
|
||||
candidate := strings.TrimSpace(skill.Name)
|
||||
if skillNamePattern.MatchString(candidate) {
|
||||
seen[candidate] = true
|
||||
}
|
||||
}
|
||||
|
||||
return sortedKeys(seen), nil
|
||||
}
|
||||
|
||||
// parseGlobalSkillsList parses the output of "npx -y skills ls -g"
|
||||
func parseGlobalSkillsList(lines []string) []string {
|
||||
seen := map[string]bool{}
|
||||
@@ -160,8 +186,7 @@ func parseOfficialSkillsList(lines []string) []string {
|
||||
|
||||
if len(parts) > 0 {
|
||||
candidate := parts[0]
|
||||
// Check if it's a valid official skill name
|
||||
if strings.HasPrefix(candidate, "lark-") && skillNamePattern.MatchString(candidate) {
|
||||
if skillNamePattern.MatchString(candidate) {
|
||||
seen[candidate] = true
|
||||
}
|
||||
}
|
||||
@@ -223,6 +248,7 @@ func PlanSync(input SyncInput) SyncPlan {
|
||||
}
|
||||
|
||||
type SkillsRunner interface {
|
||||
ListOfficialSkillsIndex() *selfupdate.NpmResult
|
||||
ListOfficialSkills() *selfupdate.NpmResult
|
||||
ListGlobalSkillsJSON() *selfupdate.NpmResult
|
||||
ListGlobalSkills() *selfupdate.NpmResult
|
||||
@@ -258,14 +284,9 @@ func SyncSkills(opts SyncOptions) *SyncResult {
|
||||
}
|
||||
|
||||
// --- Step 1: List official skills ---
|
||||
officialResult := opts.Runner.ListOfficialSkills()
|
||||
if officialResult == nil || officialResult.Err != nil {
|
||||
return fallbackFullInstall(opts, resultDetail(officialResult), nil)
|
||||
}
|
||||
official := ParseSkillsList(officialResult.Stdout.String())
|
||||
|
||||
if len(official) == 0 && strings.TrimSpace(officialResult.Stdout.String()) != "" {
|
||||
return fallbackFullInstall(opts, "official skills list parsed as empty despite non-empty stdout", nil)
|
||||
official, reason, ok := listOfficialSkills(opts.Runner)
|
||||
if !ok {
|
||||
return fallbackFullInstall(opts, reason, nil)
|
||||
}
|
||||
|
||||
// --- Step 2: List local (installed) skills ---
|
||||
@@ -316,7 +337,7 @@ func SyncSkills(opts SyncOptions) *SyncResult {
|
||||
UpdatedSkills: plan.ToUpdate,
|
||||
AddedOfficialSkills: plan.Added,
|
||||
SkippedDeletedSkills: plan.SkippedDeleted,
|
||||
UpdatedAt: opts.Now().UTC().Format(time.RFC3339),
|
||||
UpdatedAt: opts.Now().Format(skillsStateUpdatedAtLayout),
|
||||
}
|
||||
if err := WriteState(state); err != nil {
|
||||
result.Action = "failed"
|
||||
@@ -327,6 +348,40 @@ func SyncSkills(opts SyncOptions) *SyncResult {
|
||||
return result
|
||||
}
|
||||
|
||||
func listOfficialSkills(runner SkillsRunner) ([]string, string, bool) {
|
||||
reasons := []string{}
|
||||
|
||||
indexResult := runner.ListOfficialSkillsIndex()
|
||||
if indexResult == nil || indexResult.Err != nil {
|
||||
reasons = append(reasons, "official skills index failed: "+resultDetail(indexResult))
|
||||
} else {
|
||||
official, err := ParseOfficialSkillsIndexJSON(indexResult.Stdout.String())
|
||||
if err != nil {
|
||||
reasons = append(reasons, "official skills index JSON invalid: "+err.Error())
|
||||
} else if len(official) > 0 {
|
||||
return official, "", true
|
||||
} else {
|
||||
reasons = append(reasons, "official skills index contains no skills")
|
||||
}
|
||||
}
|
||||
|
||||
officialResult := runner.ListOfficialSkills()
|
||||
if officialResult == nil || officialResult.Err != nil {
|
||||
reasons = append(reasons, "official skills list failed: "+resultDetail(officialResult))
|
||||
return nil, strings.Join(reasons, "; "), false
|
||||
}
|
||||
official := ParseSkillsList(officialResult.Stdout.String())
|
||||
if len(official) > 0 {
|
||||
return official, "", true
|
||||
}
|
||||
if strings.TrimSpace(officialResult.Stdout.String()) != "" {
|
||||
reasons = append(reasons, "official skills list parsed as empty despite non-empty stdout")
|
||||
} else {
|
||||
reasons = append(reasons, "official skills list returned no skills")
|
||||
}
|
||||
return nil, strings.Join(reasons, "; "), false
|
||||
}
|
||||
|
||||
func listLocalSkills(runner SkillsRunner) ([]string, bool) {
|
||||
jsonResult := runner.ListGlobalSkillsJSON()
|
||||
if jsonResult != nil && jsonResult.Err == nil {
|
||||
@@ -375,7 +430,7 @@ func fallbackFullInstall(opts SyncOptions, reason string, official []string) *Sy
|
||||
UpdatedSkills: official,
|
||||
AddedOfficialSkills: official,
|
||||
SkippedDeletedSkills: []string{},
|
||||
UpdatedAt: opts.Now().UTC().Format(time.RFC3339),
|
||||
UpdatedAt: opts.Now().Format(skillsStateUpdatedAtLayout),
|
||||
}
|
||||
if writeErr := WriteState(state); writeErr != nil {
|
||||
return &SyncResult{
|
||||
|
||||
@@ -30,6 +30,19 @@ lark-cli-harness:dev@0.1.0
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOfficialSkillsListAcceptsNonLarkOfficialNames(t *testing.T) {
|
||||
input := `Available Skills
|
||||
│ lark-calendar
|
||||
│ official-shared
|
||||
│ bad/name
|
||||
`
|
||||
got := ParseSkillsList(input)
|
||||
want := []string{"lark-calendar", "official-shared"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ParseSkillsList() (Available Skills) = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGlobalSkillsList(t *testing.T) {
|
||||
input := `Global Skills
|
||||
|
||||
@@ -110,6 +123,43 @@ func TestParseGlobalSkillsJSONInvalidOrUnsupported(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOfficialSkillsIndexJSON(t *testing.T) {
|
||||
input := `{
|
||||
"skills": [
|
||||
{"name":"lark-calendar","description":"Calendar","files":["SKILL.md"]},
|
||||
{"name":"lark-mail","description":"Mail","files":["SKILL.md","references/lark-mail-search.md"]},
|
||||
{"name":" lark-base ","description":"Base","files":[]},
|
||||
{"name":"lark-calendar","description":"duplicate","files":["SKILL.md"]},
|
||||
{"name":"custom-skill","description":"not official","files":["SKILL.md"]},
|
||||
{"name":"bad skill","description":"invalid","files":["SKILL.md"]},
|
||||
{"name":"","description":"empty","files":["SKILL.md"]}
|
||||
]
|
||||
}`
|
||||
got, err := ParseOfficialSkillsIndexJSON(input)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseOfficialSkillsIndexJSON() err = %v, want nil", err)
|
||||
}
|
||||
want := []string{"custom-skill", "lark-base", "lark-calendar", "lark-mail"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ParseOfficialSkillsIndexJSON() = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOfficialSkillsIndexJSONInvalidOrUnsupported(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
`not json`,
|
||||
`[{"name":"lark-calendar"}]`,
|
||||
`{"name":"lark-calendar"}`,
|
||||
`{"skills":[]}`,
|
||||
`{"skills":[{"name":"bad skill"}]}`,
|
||||
} {
|
||||
got, err := ParseOfficialSkillsIndexJSON(input)
|
||||
if err == nil && len(got) != 0 {
|
||||
t.Fatalf("ParseOfficialSkillsIndexJSON(%q) = %#v, want empty", input, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanNormal_WithReadableStatePreservesDeletedAndAddsNew(t *testing.T) {
|
||||
previous := &SkillsState{OfficialSkills: []string{"lark-calendar", "lark-mail"}}
|
||||
got := PlanSync(SyncInput{
|
||||
@@ -156,9 +206,11 @@ func TestPlanForceRestoresAllOfficial(t *testing.T) {
|
||||
}
|
||||
|
||||
type fakeSkillsRunner struct {
|
||||
officialIndexOut string
|
||||
officialOut string
|
||||
globalJSONOut string
|
||||
globalOut string
|
||||
officialIndexErr error
|
||||
officialErr error
|
||||
globalJSONErr error
|
||||
globalErr error
|
||||
@@ -166,6 +218,8 @@ type fakeSkillsRunner struct {
|
||||
installAllErr error
|
||||
installed [][]string
|
||||
installedAll int
|
||||
listedIndex int
|
||||
listedOfficial int
|
||||
listedGlobalJSON int
|
||||
listedGlobalText int
|
||||
}
|
||||
@@ -181,6 +235,19 @@ func officialSkillsOutput(names ...string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func officialSkillsIndexOutput(names ...string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"skills":[`)
|
||||
for i, name := range names {
|
||||
if i > 0 {
|
||||
b.WriteString(",")
|
||||
}
|
||||
fmt.Fprintf(&b, `{"name":%q,"description":"test skill","files":["SKILL.md"]}`, name)
|
||||
}
|
||||
b.WriteString(`]}`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func globalSkillsOutput(names ...string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("Global Skills\n\n")
|
||||
@@ -206,7 +273,16 @@ func globalSkillsJSONOutput(names ...string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (f *fakeSkillsRunner) ListOfficialSkillsIndex() *selfupdate.NpmResult {
|
||||
f.listedIndex++
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stdout.WriteString(f.officialIndexOut)
|
||||
r.Err = f.officialIndexErr
|
||||
return r
|
||||
}
|
||||
|
||||
func (f *fakeSkillsRunner) ListOfficialSkills() *selfupdate.NpmResult {
|
||||
f.listedOfficial++
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stdout.WriteString(f.officialOut)
|
||||
r.Err = f.officialErr
|
||||
@@ -255,14 +331,17 @@ func TestSyncSkills_WritesStateAndDoesNotWriteStamp(t *testing.T) {
|
||||
}
|
||||
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail", "lark-new"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-custom"),
|
||||
globalOut: globalSkillsOutput("lark-mail"),
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail", "lark-new"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail", "lark-new"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-custom"),
|
||||
globalOut: globalSkillsOutput("lark-mail"),
|
||||
}
|
||||
result := SyncSkills(SyncOptions{
|
||||
Version: "1.0.33",
|
||||
Runner: runner,
|
||||
Now: func() time.Time { return time.Date(2026, 5, 18, 12, 0, 0, 0, time.UTC) },
|
||||
Now: func() time.Time {
|
||||
return time.Date(2026, 5, 18, 12, 0, 0, 0, time.FixedZone("UTC+8", 8*60*60))
|
||||
},
|
||||
})
|
||||
|
||||
if result.Err != nil {
|
||||
@@ -284,17 +363,127 @@ func TestSyncSkills_WritesStateAndDoesNotWriteStamp(t *testing.T) {
|
||||
assertStrings(t, state.UpdatedSkills, []string{"lark-calendar", "lark-new"})
|
||||
assertStrings(t, state.AddedOfficialSkills, []string{"lark-new"})
|
||||
assertStrings(t, state.SkippedDeletedSkills, []string{"lark-mail"})
|
||||
if state.UpdatedAt != "2026-05-18T12:00:00" {
|
||||
t.Errorf("state.UpdatedAt = %q, want local wall-clock timestamp without timezone", state.UpdatedAt)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "skills.stamp")); !os.IsNotExist(err) {
|
||||
t.Fatalf("skills.stamp exists or stat failed with unexpected err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_OfficialIndexSuccessSkipsOfficialListCommand(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail", "lark-new"),
|
||||
officialOut: officialSkillsOutput("lark-should-not-be-used"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar"),
|
||||
globalOut: globalSkillsOutput("lark-mail"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
if result.Err != nil {
|
||||
t.Fatalf("SyncSkills() err = %v, want nil", result.Err)
|
||||
}
|
||||
assertStrings(t, result.Official, []string{"lark-calendar", "lark-mail", "lark-new"})
|
||||
assertStrings(t, runner.installed[0], []string{"lark-calendar", "lark-mail", "lark-new"})
|
||||
if runner.listedIndex != 1 {
|
||||
t.Fatalf("listedIndex = %d, want 1", runner.listedIndex)
|
||||
}
|
||||
if runner.listedOfficial != 0 {
|
||||
t.Fatalf("listedOfficial = %d, want 0 when index succeeds", runner.listedOfficial)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_OfficialIndexFailureFallsBackToOfficialList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
if result.Err != nil {
|
||||
t.Fatalf("SyncSkills() err = %v, want nil", result.Err)
|
||||
}
|
||||
assertStrings(t, result.Official, []string{"lark-calendar", "lark-mail"})
|
||||
if runner.listedIndex != 1 || runner.listedOfficial != 1 {
|
||||
t.Fatalf("listed index/official = %d/%d, want 1/1", runner.listedIndex, runner.listedOfficial)
|
||||
}
|
||||
if runner.installedAll != 0 {
|
||||
t.Fatalf("installedAll = %d, want 0", runner.installedAll)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_OfficialIndexEmptyFallsBackToOfficialList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialIndexOut: `{"skills":[]}`,
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
if result.Err != nil {
|
||||
t.Fatalf("SyncSkills() err = %v, want nil", result.Err)
|
||||
}
|
||||
assertStrings(t, result.Official, []string{"lark-calendar", "lark-mail"})
|
||||
if runner.listedIndex != 1 || runner.listedOfficial != 1 {
|
||||
t.Fatalf("listed index/official = %d/%d, want 1/1", runner.listedIndex, runner.listedOfficial)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_OfficialDiscoveryFailuresFallBackToFullInstallWithReasons(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
if result.Action != "fallback_synced" {
|
||||
t.Fatalf("SyncSkills() action = %q, want fallback_synced", result.Action)
|
||||
}
|
||||
if runner.installedAll != 1 {
|
||||
t.Fatalf("installedAll = %d, want 1", runner.installedAll)
|
||||
}
|
||||
if !strings.Contains(result.Detail, "official skills index failed") || !strings.Contains(result.Detail, "official skills list failed") {
|
||||
t.Fatalf("SyncSkills() detail = %q, want both discovery failure reasons", result.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_OfficialDiscoveryEmptyFallsBackToFullInstallWithReasons(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialIndexOut: `{"skills":[]}`,
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
if result.Action != "fallback_synced" {
|
||||
t.Fatalf("SyncSkills() action = %q, want fallback_synced", result.Action)
|
||||
}
|
||||
if runner.installedAll != 1 {
|
||||
t.Fatalf("installedAll = %d, want 1", runner.installedAll)
|
||||
}
|
||||
if !strings.Contains(result.Detail, "official skills index contains no skills") || !strings.Contains(result.Detail, "official skills list returned no skills") {
|
||||
t.Fatalf("SyncSkills() detail = %q, want both empty discovery reasons", result.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_ListOfficialFailureFallsBackToFullInstall(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: nil,
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -322,8 +511,9 @@ func TestSyncSkills_ListOfficialFailureAndFullInstallFails(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: fmt.Errorf("full install failed"),
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: fmt.Errorf("full install failed"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -342,9 +532,10 @@ func TestSyncSkills_GlobalJSONFailureFallsBackToTextList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONErr: fmt.Errorf("json list failed"),
|
||||
globalOut: globalSkillsOutput("lark-calendar"),
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONErr: fmt.Errorf("json list failed"),
|
||||
globalOut: globalSkillsOutput("lark-calendar"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -367,9 +558,10 @@ func TestSyncSkills_LocalListsFailureFallsBackToFullInstall(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONErr: fmt.Errorf("json list failed with /Users/example/.agents/skills/lark-calendar agents Codex"),
|
||||
globalErr: fmt.Errorf("text list failed with /Users/example/.agents/skills/lark-mail agents Codex"),
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONErr: fmt.Errorf("json list failed with /Users/example/.agents/skills/lark-calendar agents Codex"),
|
||||
globalErr: fmt.Errorf("text list failed with /Users/example/.agents/skills/lark-mail agents Codex"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -391,12 +583,19 @@ func TestSyncSkills_ParseEmptyLocalListsFallBackToFullInstall(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: `[]`,
|
||||
globalOut: "Some unrecognized output format\n",
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: `[]`,
|
||||
globalOut: "Some unrecognized output format\n",
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
result := SyncSkills(SyncOptions{
|
||||
Version: "1.0.33",
|
||||
Runner: runner,
|
||||
Now: func() time.Time {
|
||||
return time.Date(2026, 5, 18, 12, 0, 0, 0, time.FixedZone("UTC-7", -7*60*60))
|
||||
},
|
||||
})
|
||||
if result.Action != "fallback_synced" {
|
||||
t.Fatalf("SyncSkills() action = %q, want fallback_synced", result.Action)
|
||||
}
|
||||
@@ -406,6 +605,13 @@ func TestSyncSkills_ParseEmptyLocalListsFallBackToFullInstall(t *testing.T) {
|
||||
if runner.installedAll != 1 {
|
||||
t.Fatalf("installedAll = %d, want 1", runner.installedAll)
|
||||
}
|
||||
state, readable, err := ReadState()
|
||||
if err != nil || !readable {
|
||||
t.Fatalf("ReadState() = (_, %v, %v), want readable", readable, err)
|
||||
}
|
||||
if state.UpdatedAt != "2026-05-18T12:00:00" {
|
||||
t.Errorf("state.UpdatedAt = %q, want local wall-clock timestamp without timezone", state.UpdatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSkills_EmptyToUpdateFallsBackToFullInstall(t *testing.T) {
|
||||
@@ -420,9 +626,10 @@ func TestSyncSkills_EmptyToUpdateFallsBackToFullInstall(t *testing.T) {
|
||||
}
|
||||
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput(),
|
||||
installAllErr: nil,
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput(),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -445,11 +652,12 @@ func TestSyncSkills_InstallFailureFallsBackToFullInstall(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: nil,
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -477,11 +685,12 @@ func TestSyncSkills_InstallFailureAndFullInstallFails(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: fmt.Errorf("full install boom"),
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: fmt.Errorf("full install boom"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -510,8 +719,9 @@ func TestSyncSkills_ParseEmptyWithNonEmptyStdoutFallsBack(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: "Some unrecognized output format\n",
|
||||
installAllErr: nil,
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialOut: "Some unrecognized output format\n",
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -527,8 +737,9 @@ func TestSyncSkills_ParseEmptyWithNonEmptyStdoutAndFullInstallFails(t *testing.T
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: "Some unrecognized output format\n",
|
||||
installAllErr: fmt.Errorf("full install failed"),
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialOut: "Some unrecognized output format\n",
|
||||
installAllErr: fmt.Errorf("full install failed"),
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -551,8 +762,9 @@ func TestSyncSkills_FallbackWithUnknownOfficialWritesMinimalState(t *testing.T)
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: "Some unrecognized output format\n",
|
||||
installAllErr: nil,
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialOut: "Some unrecognized output format\n",
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -576,11 +788,12 @@ func TestSyncSkills_FallbackWithKnownOfficialWritesFullState(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: nil,
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -601,11 +814,12 @@ func TestSyncSkills_FallbackResultContainsMetadata(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: nil,
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
installErr: fmt.Errorf("incremental boom"),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -625,8 +839,9 @@ func TestSyncSkills_FallbackBreaksDegradationLoop(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
runner := &fakeSkillsRunner{
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: nil,
|
||||
officialIndexErr: fmt.Errorf("index unavailable"),
|
||||
officialErr: fmt.Errorf("list failed"),
|
||||
installAllErr: nil,
|
||||
}
|
||||
|
||||
result1 := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner, Now: time.Now})
|
||||
@@ -643,9 +858,10 @@ func TestSyncSkills_FallbackBreaksDegradationLoop(t *testing.T) {
|
||||
}
|
||||
|
||||
runner2 := &fakeSkillsRunner{
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
officialIndexOut: officialSkillsIndexOutput("lark-calendar", "lark-mail"),
|
||||
officialOut: officialSkillsOutput("lark-calendar", "lark-mail"),
|
||||
globalJSONOut: globalSkillsJSONOutput("lark-calendar", "lark-mail"),
|
||||
globalOut: globalSkillsOutput("lark-calendar", "lark-mail"),
|
||||
}
|
||||
result2 := SyncSkills(SyncOptions{Version: "1.0.33", Runner: runner2, Now: time.Now})
|
||||
if result2.Action != "synced" {
|
||||
|
||||
@@ -424,6 +424,8 @@ func TestFeedGroupValidationErrors(t *testing.T) {
|
||||
{"list missing feed-group-id", ImFeedGroupListItem, map[string]string{}, "--feed-group-id is required"},
|
||||
{"list bad page-size", ImFeedGroupListItem, map[string]string{"feed-group-id": "ofg_x", "page-size": "0"}, "--page-size must be an integer between 1 and 50"},
|
||||
{"list bad page-limit", ImFeedGroupListItem, map[string]string{"feed-group-id": "ofg_x", "page-limit": "2000"}, "--page-limit must be an integer between 1 and 1000"},
|
||||
{"list bad start-time", ImFeedGroupListItem, map[string]string{"feed-group-id": "ofg_x", "start-time": "notnum"}, "--start-time must be Unix milliseconds"},
|
||||
{"list bad end-time", ImFeedGroupListItem, map[string]string{"feed-group-id": "ofg_x", "end-time": "notnum"}, "--end-time must be Unix milliseconds"},
|
||||
{"query missing feed-group-id", ImFeedGroupQueryItem, map[string]string{"feed-id": "oc_a"}, "--feed-group-id is required"},
|
||||
{"query missing feed-id", ImFeedGroupQueryItem, map[string]string{"feed-group-id": "ofg_x"}, "--feed-id is required (comma-separated chat IDs)"},
|
||||
{"query blank feed-id tokens", ImFeedGroupQueryItem, map[string]string{"feed-group-id": "ofg_x", "feed-id": ", ,"}, "--feed-id is required (comma-separated chat IDs)"},
|
||||
@@ -446,7 +448,7 @@ func TestFeedGroupValidationErrors(t *testing.T) {
|
||||
|
||||
func TestFeedGroupListItemDryRun(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupListItem, map[string]string{
|
||||
"feed-group-id": "ofg_x", "page-size": "10", "start-time": "100",
|
||||
"feed-group-id": "ofg_x", "page-size": "10", "page-token": "TKN", "start-time": "100", "end-time": "200",
|
||||
}, nil, nil)
|
||||
d := ImFeedGroupListItem.DryRun(context.Background(), runtime)
|
||||
calls := dryRunCalls(t, d)
|
||||
@@ -460,11 +462,12 @@ func TestFeedGroupListItemDryRun(t *testing.T) {
|
||||
t.Errorf("url = %s", url)
|
||||
}
|
||||
params, _ := calls[0]["params"].(map[string]interface{})
|
||||
if params["page_size"] != "10" {
|
||||
t.Errorf("params page_size = %v, want 10", params["page_size"])
|
||||
}
|
||||
if params["start_time"] != "100" {
|
||||
t.Errorf("params start_time = %v, want 100", params["start_time"])
|
||||
for key, want := range map[string]string{
|
||||
"page_size": "10", "page_token": "TKN", "start_time": "100", "end_time": "200",
|
||||
} {
|
||||
if params[key] != want {
|
||||
t.Errorf("params %s = %v, want %s", key, params[key], want)
|
||||
}
|
||||
}
|
||||
if desc, _ := calls[0]["desc"].(string); !strings.Contains(desc, "im:chat:read") {
|
||||
t.Errorf("desc = %q, want chat_name enrichment note", desc)
|
||||
@@ -514,3 +517,197 @@ func TestFeedGroupQueryItemDryRunValidationError(t *testing.T) {
|
||||
t.Fatalf("expected error in dry-run output, got %#v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// ── list-item: time-window flags reach the query ──
|
||||
|
||||
func TestFeedGroupListItemTimeWindowQueryParams(t *testing.T) {
|
||||
var reqs []recordedFGRequest
|
||||
runtime := newFGRuntime(t, ImFeedGroupListItem, map[string]string{
|
||||
"feed-group-id": "ofg_x", "start-time": "100", "end-time": "200",
|
||||
}, &reqs, func(path string, _ int) (int, interface{}) {
|
||||
if strings.HasSuffix(path, "/list_item") {
|
||||
return 200, wrapData(map[string]interface{}{
|
||||
"items": []interface{}{}, "deleted_items": []interface{}{},
|
||||
"page_token": "", "has_more": false,
|
||||
})
|
||||
}
|
||||
return 200, wrapData(map[string]interface{}{})
|
||||
})
|
||||
if err := ImFeedGroupListItem.Execute(context.Background(), runtime); err != nil {
|
||||
t.Fatalf("Execute error: %v", err)
|
||||
}
|
||||
req := findFGRequest(reqs, "/list_item")
|
||||
if req == nil {
|
||||
t.Fatal("expected list_item request")
|
||||
}
|
||||
if got := firstQueryValue(req.query, "start_time"); got != "100" {
|
||||
t.Errorf("start_time query = %q, want 100", got)
|
||||
}
|
||||
if got := firstQueryValue(req.query, "end_time"); got != "200" {
|
||||
t.Errorf("end_time query = %q, want 200", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ── list-item: infinite-loop guard + defensive page-limit clamping ──
|
||||
|
||||
func TestFeedGroupListItemPageAllStopsOnRepeatedToken(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
pageLimit string
|
||||
}{
|
||||
{"limit clamped up from 0", "0"},
|
||||
{"limit clamped down from 1001", "1001"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var reqs []recordedFGRequest
|
||||
runtime := newFGRuntime(t, ImFeedGroupListItem, map[string]string{
|
||||
"feed-group-id": "ofg_x", "page-all": "true", "page-limit": tc.pageLimit,
|
||||
"start-time": "100", "end-time": "200",
|
||||
}, &reqs, func(path string, _ int) (int, interface{}) {
|
||||
if strings.HasSuffix(path, "/list_item") {
|
||||
return 200, wrapData(map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"feed_id": "oc_a", "feed_type": "chat", "update_time": "1"}},
|
||||
"deleted_items": []interface{}{},
|
||||
"page_token": "SAME", "has_more": true,
|
||||
})
|
||||
}
|
||||
return 200, wrapData(map[string]interface{}{})
|
||||
})
|
||||
runtime.Format = "pretty" // exercise the page-all table-render path too
|
||||
if err := ImFeedGroupListItem.Execute(context.Background(), runtime); err != nil {
|
||||
t.Fatalf("Execute error: %v", err)
|
||||
}
|
||||
if got := countFGRequests(reqs, "/list_item"); got != 2 {
|
||||
t.Errorf("expected 2 list_item requests (stop on repeated token), got %d", got)
|
||||
}
|
||||
errOut, _ := runtime.Factory.IOStreams.ErrOut.(*bytes.Buffer)
|
||||
if !strings.Contains(errOut.String(), "page_token did not change") {
|
||||
t.Errorf("stderr missing loop warning; got:\n%s", errOut.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── list-item: API errors surface from both Execute paths ──
|
||||
|
||||
func TestFeedGroupListItemAPIError(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
}{
|
||||
{"single page", map[string]string{"feed-group-id": "ofg_x"}},
|
||||
{"page-all", map[string]string{"feed-group-id": "ofg_x", "page-all": "true"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupListItem, tc.flags, nil,
|
||||
func(_ string, _ int) (int, interface{}) {
|
||||
return 200, map[string]interface{}{"code": 99999, "msg": "boom"}
|
||||
})
|
||||
if err := ImFeedGroupListItem.Execute(context.Background(), runtime); err == nil {
|
||||
t.Fatal("expected API error, got nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── enrichment: total resolution failure warns on stderr, nil data is a no-op ──
|
||||
|
||||
func TestEnrichFeedGroupItemsWarnsWhenResolutionFails(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupQueryItem, map[string]string{}, nil,
|
||||
func(path string, _ int) (int, interface{}) {
|
||||
if strings.HasSuffix(path, "/chats/batch_query") {
|
||||
return 200, map[string]interface{}{"code": 99999, "msg": "boom"}
|
||||
}
|
||||
return 200, wrapData(map[string]interface{}{})
|
||||
})
|
||||
|
||||
// nil data must not panic.
|
||||
enrichFeedGroupItemsChatName(runtime, nil)
|
||||
|
||||
data := map[string]any{
|
||||
"items": []any{map[string]any{"feed_id": "oc_a", "feed_type": "chat"}},
|
||||
"deleted_items": []any{},
|
||||
}
|
||||
enrichFeedGroupItemsChatName(runtime, data)
|
||||
|
||||
item := data["items"].([]any)[0].(map[string]any)
|
||||
if _, present := item["chat_name"]; present {
|
||||
t.Errorf("chat_name should be absent when resolution fails, got %v", item["chat_name"])
|
||||
}
|
||||
errOut, _ := runtime.Factory.IOStreams.ErrOut.(*bytes.Buffer)
|
||||
if !strings.Contains(errOut.String(), "could not resolve chat names") {
|
||||
t.Errorf("stderr missing resolution warning; got:\n%s", errOut.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ── query-item: Execute error paths ──
|
||||
|
||||
func TestFeedGroupQueryItemExecuteErrors(t *testing.T) {
|
||||
t.Run("invalid flags", func(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupQueryItem, map[string]string{"feed-group-id": "ofg_x"}, nil, nil)
|
||||
if err := ImFeedGroupQueryItem.Execute(context.Background(), runtime); err == nil {
|
||||
t.Fatal("expected validation error from Execute, got nil")
|
||||
}
|
||||
})
|
||||
t.Run("api error", func(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupQueryItem, map[string]string{
|
||||
"feed-group-id": "ofg_x", "feed-id": "oc_a",
|
||||
}, nil, func(_ string, _ int) (int, interface{}) {
|
||||
return 200, map[string]interface{}{"code": 99999, "msg": "boom"}
|
||||
})
|
||||
if err := ImFeedGroupQueryItem.Execute(context.Background(), runtime); err == nil {
|
||||
t.Fatal("expected API error, got nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── formatFeedGroupUpdateTime: empty / non-numeric inputs pass through ──
|
||||
|
||||
func TestFormatFeedGroupUpdateTime(t *testing.T) {
|
||||
if got := formatFeedGroupUpdateTime(""); got != "" {
|
||||
t.Errorf("empty input = %q, want empty passthrough", got)
|
||||
}
|
||||
if got := formatFeedGroupUpdateTime("not-millis"); got != "not-millis" {
|
||||
t.Errorf("non-numeric input = %q, want raw passthrough", got)
|
||||
}
|
||||
want := time.UnixMilli(1767196800000).Local().Format(time.RFC3339)
|
||||
if got := formatFeedGroupUpdateTime("1767196800000"); got != want {
|
||||
t.Errorf("millis input = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// ── query-item: pretty table output renders enriched items ──
|
||||
|
||||
func TestFeedGroupQueryItemTableOutput(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupQueryItem, map[string]string{
|
||||
"feed-group-id": "ofg_x", "feed-id": "oc_a",
|
||||
}, nil, func(path string, _ int) (int, interface{}) {
|
||||
switch {
|
||||
case strings.HasSuffix(path, "/batch_query_item"):
|
||||
return 200, wrapData(map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"feed_id": "oc_a", "feed_type": "chat", "update_time": "1767196800000"}},
|
||||
"deleted_items": []interface{}{},
|
||||
})
|
||||
case strings.HasSuffix(path, "/chats/batch_query"):
|
||||
return 200, wrapData(map[string]interface{}{"items": []interface{}{
|
||||
map[string]interface{}{"chat_id": "oc_a", "name": "Team A"},
|
||||
}})
|
||||
}
|
||||
return 200, wrapData(map[string]interface{}{})
|
||||
})
|
||||
runtime.Format = "pretty"
|
||||
|
||||
if err := ImFeedGroupQueryItem.Execute(context.Background(), runtime); err != nil {
|
||||
t.Fatalf("Execute error: %v", err)
|
||||
}
|
||||
out, _ := runtime.Factory.IOStreams.Out.(*bytes.Buffer)
|
||||
if out == nil {
|
||||
t.Fatal("stdout buffer missing")
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"oc_a", "Team A", "1 item(s)"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("table output missing %q; got:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"strconv"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
@@ -57,7 +58,7 @@ var ImFeedGroupList = common.Shortcut{
|
||||
return executeFeedGroupListGroupsAllPages(runtime)
|
||||
}
|
||||
|
||||
data, err := runtime.DoAPIJSON("GET", feedGroupListPath, feedGroupListGroupsQuery(runtime), nil)
|
||||
data, err := runtime.DoAPIJSONTyped("GET", feedGroupListPath, feedGroupListGroupsQuery(runtime), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -72,19 +73,19 @@ var ImFeedGroupList = common.Shortcut{
|
||||
|
||||
func validateFeedGroupListPageOptions(rt *common.RuntimeContext) error {
|
||||
if n := rt.Int("page-size"); n < 1 || n > 50 {
|
||||
return output.ErrValidation("--page-size must be an integer between 1 and 50")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--page-size must be an integer between 1 and 50").WithParam("--page-size")
|
||||
}
|
||||
if n := rt.Int("page-limit"); n < 1 || n > 1000 {
|
||||
return output.ErrValidation("--page-limit must be an integer between 1 and 1000")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--page-limit must be an integer between 1 and 1000").WithParam("--page-limit")
|
||||
}
|
||||
if v := rt.Str("start-time"); v != "" {
|
||||
if _, err := strconv.ParseInt(v, 10, 64); err != nil {
|
||||
return output.ErrValidation("--start-time must be Unix milliseconds (a decimal integer string)")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--start-time must be Unix milliseconds (a decimal integer string)").WithParam("--start-time")
|
||||
}
|
||||
}
|
||||
if v := rt.Str("end-time"); v != "" {
|
||||
if _, err := strconv.ParseInt(v, 10, 64); err != nil {
|
||||
return output.ErrValidation("--end-time must be Unix milliseconds (a decimal integer string)")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--end-time must be Unix milliseconds (a decimal integer string)").WithParam("--end-time")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -158,7 +159,7 @@ func executeFeedGroupListGroupsAllPages(rt *common.RuntimeContext) error {
|
||||
params["end_time"] = []string{end}
|
||||
}
|
||||
|
||||
data, err := rt.DoAPIJSON("GET", feedGroupListPath, params, nil)
|
||||
data, err := rt.DoAPIJSONTyped("GET", feedGroupListPath, params, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"io"
|
||||
"strconv"
|
||||
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
@@ -54,7 +54,7 @@ var ImFeedGroupListItem = common.Shortcut{
|
||||
return executeFeedGroupListAllPages(runtime)
|
||||
}
|
||||
|
||||
data, err := runtime.DoAPIJSON("GET", feedGroupListItemPath(runtime), feedGroupListQuery(runtime), nil)
|
||||
data, err := runtime.DoAPIJSONTyped("GET", feedGroupListItemPath(runtime), feedGroupListQuery(runtime), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -70,22 +70,22 @@ var ImFeedGroupListItem = common.Shortcut{
|
||||
|
||||
func validateFeedGroupListOptions(rt *common.RuntimeContext) error {
|
||||
if rt.Str("feed-group-id") == "" {
|
||||
return output.ErrValidation("--feed-group-id is required")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--feed-group-id is required").WithParam("--feed-group-id")
|
||||
}
|
||||
if n := rt.Int("page-size"); n < 1 || n > 50 {
|
||||
return output.ErrValidation("--page-size must be an integer between 1 and 50")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--page-size must be an integer between 1 and 50").WithParam("--page-size")
|
||||
}
|
||||
if n := rt.Int("page-limit"); n < 1 || n > 1000 {
|
||||
return output.ErrValidation("--page-limit must be an integer between 1 and 1000")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--page-limit must be an integer between 1 and 1000").WithParam("--page-limit")
|
||||
}
|
||||
if v := rt.Str("start-time"); v != "" {
|
||||
if _, err := strconv.ParseInt(v, 10, 64); err != nil {
|
||||
return output.ErrValidation("--start-time must be Unix milliseconds (a decimal integer string)")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--start-time must be Unix milliseconds (a decimal integer string)").WithParam("--start-time")
|
||||
}
|
||||
}
|
||||
if v := rt.Str("end-time"); v != "" {
|
||||
if _, err := strconv.ParseInt(v, 10, 64); err != nil {
|
||||
return output.ErrValidation("--end-time must be Unix milliseconds (a decimal integer string)")
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--end-time must be Unix milliseconds (a decimal integer string)").WithParam("--end-time")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -163,7 +163,7 @@ func executeFeedGroupListAllPages(rt *common.RuntimeContext) error {
|
||||
params["end_time"] = []string{end}
|
||||
}
|
||||
|
||||
data, err := rt.DoAPIJSON("GET", feedGroupListItemPath(rt), params, nil)
|
||||
data, err := rt.DoAPIJSONTyped("GET", feedGroupListItemPath(rt), params, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -102,6 +103,7 @@ func TestFeedGroupListValidation(t *testing.T) {
|
||||
{"page-size too large", map[string]string{"page-size": "51"}, "--page-size"},
|
||||
{"page-limit too large", map[string]string{"page-limit": "1001"}, "--page-limit"},
|
||||
{"bad start-time", map[string]string{"start-time": "notnum"}, "--start-time"},
|
||||
{"bad end-time", map[string]string{"end-time": "notnum"}, "--end-time"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -116,3 +118,140 @@ func TestFeedGroupListValidation(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFeedGroupListSinglePageTableOutput covers the non-page-all Execute path:
|
||||
// time-window params must reach the query, and the pretty table must render
|
||||
// group_id / name / type with the summary, pagination hint and deleted count.
|
||||
func TestFeedGroupListSinglePageTableOutput(t *testing.T) {
|
||||
var reqs []recordedFGRequest
|
||||
runtime := newFGRuntime(t, ImFeedGroupList, map[string]string{
|
||||
"start-time": "100", "end-time": "200",
|
||||
}, &reqs, func(_ string, _ int) (int, interface{}) {
|
||||
return 200, wrapData(map[string]interface{}{
|
||||
"groups": []interface{}{fgGroup("g1"), fgGroup("g2")},
|
||||
"deleted_groups": []interface{}{fgGroup("d1")},
|
||||
"page_token": "TKN", "has_more": true,
|
||||
})
|
||||
})
|
||||
runtime.Format = "pretty"
|
||||
|
||||
if err := ImFeedGroupList.Execute(context.Background(), runtime); err != nil {
|
||||
t.Fatalf("Execute: %v", err)
|
||||
}
|
||||
if got := countFGRequests(reqs, "/groups"); got != 1 {
|
||||
t.Fatalf("expected 1 groups request, got %d", got)
|
||||
}
|
||||
if got := firstQueryValue(reqs[0].query, "start_time"); got != "100" {
|
||||
t.Errorf("start_time query = %q, want 100", got)
|
||||
}
|
||||
if got := firstQueryValue(reqs[0].query, "end_time"); got != "200" {
|
||||
t.Errorf("end_time query = %q, want 200", got)
|
||||
}
|
||||
|
||||
out, _ := runtime.Factory.IOStreams.Out.(*bytes.Buffer)
|
||||
if out == nil {
|
||||
t.Fatal("stdout buffer missing")
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"group_id", "g1", "g2", "2 group(s)", "more available", "(1 deleted)"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("table output missing %q; got:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFeedGroupListDryRun locks the dry-run shape: GET /groups with page_size,
|
||||
// page_token (always present) and the optional time-window params.
|
||||
func TestFeedGroupListDryRun(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupList, map[string]string{
|
||||
"page-size": "10", "page-token": "TKN", "start-time": "100", "end-time": "200",
|
||||
}, nil, nil)
|
||||
d := ImFeedGroupList.DryRun(context.Background(), runtime)
|
||||
calls := dryRunCalls(t, d)
|
||||
if len(calls) != 1 {
|
||||
t.Fatalf("expected 1 call, got %d", len(calls))
|
||||
}
|
||||
if calls[0]["method"] != "GET" {
|
||||
t.Errorf("method = %v, want GET", calls[0]["method"])
|
||||
}
|
||||
if url, _ := calls[0]["url"].(string); !strings.HasSuffix(url, "/open-apis/im/v1/groups") {
|
||||
t.Errorf("url = %s", url)
|
||||
}
|
||||
params, _ := calls[0]["params"].(map[string]interface{})
|
||||
for key, want := range map[string]string{
|
||||
"page_size": "10", "page_token": "TKN", "start_time": "100", "end_time": "200",
|
||||
} {
|
||||
if params[key] != want {
|
||||
t.Errorf("params %s = %v, want %s", key, params[key], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedGroupListDryRunValidationError(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupList, map[string]string{"page-size": "0"}, nil, nil)
|
||||
d := ImFeedGroupList.DryRun(context.Background(), runtime)
|
||||
m := dryRunJSON(t, d)
|
||||
errMsg, _ := m["error"].(string)
|
||||
if !strings.Contains(errMsg, "--page-size") {
|
||||
t.Errorf("dry-run error = %q, want --page-size validation message", errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFeedGroupListPageAllStopsOnRepeatedToken locks the infinite-loop guard:
|
||||
// when the server keeps returning the same page_token with has_more=true,
|
||||
// pagination must stop after the repeat and warn on stderr. Also exercises the
|
||||
// defensive page-limit clamping (Execute is called directly, bypassing Validate).
|
||||
func TestFeedGroupListPageAllStopsOnRepeatedToken(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
pageLimit string
|
||||
}{
|
||||
{"limit clamped up from 0", "0"},
|
||||
{"limit clamped down from 1001", "1001"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var reqs []recordedFGRequest
|
||||
runtime := newFGRuntime(t, ImFeedGroupList, map[string]string{
|
||||
"page-all": "true", "page-limit": tc.pageLimit, "start-time": "100", "end-time": "200",
|
||||
}, &reqs, func(_ string, _ int) (int, interface{}) {
|
||||
return 200, wrapData(map[string]interface{}{
|
||||
"groups": []interface{}{fgGroup("g1")},
|
||||
"deleted_groups": []interface{}{},
|
||||
"page_token": "SAME", "has_more": true,
|
||||
})
|
||||
})
|
||||
runtime.Format = "pretty" // exercise the page-all table-render path too
|
||||
if err := ImFeedGroupList.Execute(context.Background(), runtime); err != nil {
|
||||
t.Fatalf("Execute: %v", err)
|
||||
}
|
||||
if got := countFGRequests(reqs, "/groups"); got != 2 {
|
||||
t.Errorf("expected 2 requests (stop on repeated token), got %d", got)
|
||||
}
|
||||
errOut, _ := runtime.Factory.IOStreams.ErrOut.(*bytes.Buffer)
|
||||
if !strings.Contains(errOut.String(), "page_token did not change") {
|
||||
t.Errorf("stderr missing loop warning; got:\n%s", errOut.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFeedGroupListAPIError checks both Execute paths surface API errors.
|
||||
func TestFeedGroupListAPIError(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
}{
|
||||
{"single page", map[string]string{}},
|
||||
{"page-all", map[string]string{"page-all": "true"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
runtime := newFGRuntime(t, ImFeedGroupList, tc.flags, nil,
|
||||
func(_ string, _ int) (int, interface{}) {
|
||||
return 200, map[string]interface{}{"code": 99999, "msg": "boom"}
|
||||
})
|
||||
if err := ImFeedGroupList.Execute(context.Background(), runtime); err == nil {
|
||||
t.Fatal("expected API error, got nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
@@ -47,7 +47,7 @@ var ImFeedGroupQueryItem = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := runtime.DoAPIJSON("POST", feedGroupQueryItemPath(runtime), nil, body)
|
||||
data, err := runtime.DoAPIJSONTyped("POST", feedGroupQueryItemPath(runtime), nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -70,7 +70,7 @@ func feedGroupQueryItemPath(rt *common.RuntimeContext) string {
|
||||
// {"items":[{"feed_id":"<tok>","feed_type":"chat"}, ...]}.
|
||||
func buildFeedGroupQueryItemBody(rt *common.RuntimeContext) (map[string]any, error) {
|
||||
if rt.Str("feed-group-id") == "" {
|
||||
return nil, output.ErrValidation("--feed-group-id is required")
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--feed-group-id is required").WithParam("--feed-group-id")
|
||||
}
|
||||
tokens := common.SplitCSV(rt.Str("feed-id"))
|
||||
items := make([]any, 0, len(tokens))
|
||||
@@ -84,7 +84,7 @@ func buildFeedGroupQueryItemBody(rt *common.RuntimeContext) (map[string]any, err
|
||||
})
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil, output.ErrValidation("--feed-id is required (comma-separated chat IDs)")
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--feed-id is required (comma-separated chat IDs)").WithParam("--feed-id")
|
||||
}
|
||||
return map[string]any{"items": items}, nil
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
## 快速决策
|
||||
|
||||
- 用户要**整理 / 盘点 / 归类 / 重构知识库、个人文档库、文档库目录或 Wiki 节点结构**,或要生成整理方案、目标目录树、移动计划时,不要只使用 Wiki 节点 API。必须先阅读 [`../lark-drive/references/lark-drive-workflow-knowledge-organize.md`](../lark-drive/references/lark-drive-workflow-knowledge-organize.md),该 workflow 负责 Drive / Wiki / 个人文档库的统一入口解析、资源盘点、分类计划、写前确认和结果验证。
|
||||
- 用户给的是知识库 URL(`.../wiki/<token>`),且后续要查成员/加成员/删成员:先调用 `lark-cli wiki spaces get_node --params '{"token":"<wiki_token>"}'` 获取 `space_id`,后续成员接口统一使用 `space_id`。
|
||||
- 用户要**删除**知识空间(`wiki +delete-space`)但只给了名称或 URL:**不能**把名称 / URL 原样传给 `--space-id`,必须先解析出真实 `space_id`。解析方式:
|
||||
- URL(`.../wiki/<token>`):`lark-cli wiki spaces get_node --params '{"token":"<wiki_token>"}' --format json`,读 `data.node.space_id`。
|
||||
@@ -13,6 +14,7 @@
|
||||
- **关键安全约束**:无论精确还是模糊,**无论命中 1 条还是多条,发起删除前都必须把候选(`name` + `space_id` + `description` + `space_type`)列给用户,由用户明确选定一个 `space_id` 再执行**。不要因为"只命中一条"就自动执行删除。
|
||||
- 命中 0 条:停下来问用户是名称拼错了还是调用方无权限;**不要**自行改名字重试。
|
||||
- 用户明确选定后再执行 `lark-cli wiki +delete-space --space-id <ID> --yes`(高风险写操作,必须显式 `--yes`)。
|
||||
- 反例:不要把 wiki URL / 名称直接当 `--space-id`(如 `--space-id "https://.../wiki/<wiki_token>"`);务必先用 `wiki spaces get_node` 解析出 `data.node.space_id` 再传。
|
||||
- 用户要在知识库中创建新节点,优先使用 `lark-cli wiki +node-create`。
|
||||
- 用户说“给知识库添加成员/管理员”:先把目标解析成“用户 / 群 / 部门 / 应用”四类之一,再决定 `--member-type`,不要先调 `wiki +member-add` 再根据报错反推类型。
|
||||
- 用户说“部门 + bot”:这是已知不支持路径。不要继续尝试 `wiki +member-add --as bot`;直接提示必须改成 `--as user`,或明确告知当前要求无法完成。
|
||||
|
||||
@@ -59,7 +59,7 @@ JSON keeps the raw envelope and adds `chat_name` to each resolvable item:
|
||||
}
|
||||
```
|
||||
|
||||
A feed card whose chat cannot be resolved (soft-deleted or no permission) simply omits `chat_name` — the command still exits 0.
|
||||
A feed card whose chat cannot be resolved (soft-deleted or no permission) simply omits `chat_name` — the command still exits 0. p2p (direct) chats also omit `chat_name`: the server returns an empty `name` for them (the client UI shows the partner's display name instead); if a label is needed, fetch the chat via `chats/batch_query`, read `p2p_target_id`, and resolve it with a contact lookup.
|
||||
|
||||
## See also
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ lark-cli im +feed-group-query-item --as user \
|
||||
|
||||
The command sends `{"items":[{"feed_id":"oc_a","feed_type":"chat"},{"feed_id":"oc_b","feed_type":"chat"}]}`, then enriches the response (`items[]` and `deleted_items[]`) with `chat_name` exactly as `+feed-group-list-item` does. There is no pagination for this method.
|
||||
|
||||
A feed card whose chat cannot be resolved (soft-deleted or no permission) simply omits `chat_name` — the command still exits 0.
|
||||
A feed card whose chat cannot be resolved (soft-deleted or no permission) simply omits `chat_name` — the command still exits 0. p2p (direct) chats also omit `chat_name`: the server returns an empty `name` for them (the client UI shows the partner's display name instead); if a label is needed, fetch the chat via `chats/batch_query`, read `p2p_target_id`, and resolve it with a contact lookup.
|
||||
|
||||
## See also
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ The two `*-item` shortcuts resolve `chat_name` via a follow-up `chats/batch_quer
|
||||
|
||||
## Common Notes
|
||||
|
||||
- `feed_group_id` is the feed-group identifier returned by `create`, typically formatted as `ofg_xxx`. In meta examples it appears as a string; on the wire it is the group's stable ID.
|
||||
- `feed_group_id` is the feed-group identifier returned by `create`, typically formatted as `ofg_xxx`. It is an opaque string — the group's stable ID.
|
||||
- `feed_id` is the identifier of one feed card inside a group. In v1 only the `chat` feed card type is supported (see `feed_card_type` below), so `feed_id` is currently a chat ID such as `oc_xxx`.
|
||||
- All `feed.groups.*` methods require `user_access_token`. Run with `--as user`; bot/tenant tokens are rejected.
|
||||
- Read APIs (`batch_query`, `list`, `batch_query_item`, `list_item`) return **two parallel lists**: a live list (`groups[]` or `items[]`) and a soft-deleted list (`deleted_groups[]` or `deleted_items[]`). Consumers tracking incremental sync should consume both.
|
||||
@@ -268,7 +268,7 @@ lark-cli im feed.groups batch_add_item --as user \
|
||||
| `--data` | `items[].feed_id` | No | The chat ID to add (e.g. `oc_xxx`) |
|
||||
| `--data` | `items[].feed_type` | Yes (`"chat"` only) | Wire-typed as an open string. v1 OAPI service accepts only `chat`; anything else is rejected at runtime. See the Enums section. |
|
||||
|
||||
> Note: `items[].feed_id` is marked `Required: No` in the meta but every element of `items` must set it — a missing field yields an unusable entry. Always pass `{"feed_id": "oc_xxx", "feed_type": "chat"}` per item.
|
||||
> Note: `items[].feed_id` is not marked as required in the API schema, but every element of `items` must set it — a missing field yields an unusable entry. Always pass `{"feed_id": "oc_xxx", "feed_type": "chat"}` per item.
|
||||
|
||||
### Response
|
||||
|
||||
@@ -314,7 +314,7 @@ lark-cli im feed.groups batch_remove_item --as user \
|
||||
| `--data` | `items[].feed_id` | No | The chat ID to remove |
|
||||
| `--data` | `items[].feed_type` | Yes (`"chat"` only) | Wire-typed as an open string. v1 OAPI service accepts only `chat`; anything else is rejected at runtime. See the Enums section. |
|
||||
|
||||
> Note: same caveat as `batch_add_item` — `items[].feed_id` is `Required: No` per the meta but must be present in practice.
|
||||
> Note: same caveat as `batch_add_item` — `items[].feed_id` is optional per the API schema but must be present in practice.
|
||||
|
||||
### Response
|
||||
|
||||
@@ -330,7 +330,7 @@ Shortcut-only: [`+feed-group-list-item`](lark-im-feed-group-list-item.md). Lists
|
||||
|
||||
## Enums
|
||||
|
||||
The enums below are sourced from the internal datasync IDL (`lark.im.datasync.open.thrift`). All values listed here are exhaustive.
|
||||
All enum values listed here are exhaustive.
|
||||
|
||||
### `feed_group_type`
|
||||
|
||||
@@ -341,7 +341,7 @@ Used in `feed_group_creator.type` and the response `groups[].type`.
|
||||
|
||||
### `feed_card_type`
|
||||
|
||||
Used in `items[].feed_type` everywhere a feed card appears. Wire type is the open string alias `FeedCardTypeV1`.
|
||||
Used in `items[].feed_type` everywhere a feed card appears. Wire type is an open string.
|
||||
|
||||
- `chat` — the only value the v1 OAPI service accepts. `feed_id` is therefore a chat ID such as `oc_xxx`.
|
||||
|
||||
@@ -399,7 +399,7 @@ Used inside `feed_group_updater.update_fields`. Multiple values may be listed.
|
||||
- `1` — update name only.
|
||||
- `2` — update rules only.
|
||||
|
||||
Wire form: integers from the `FeedGroupUpdateField` enum (`1` = name, `2` = rules). The server rejects the lowercase string forms (`"name"`, `"rules"`) with `9499 Invalid parameter value`. Omit the array (or pass an empty array) to make no field updates.
|
||||
Wire form: integers (`1` = name, `2` = rules). The server rejects the lowercase string forms (`"name"`, `"rules"`) with `9499 Invalid parameter value`. Omit the array (or pass an empty array) to make no field updates.
|
||||
|
||||
## feed_group_rules
|
||||
|
||||
@@ -450,5 +450,3 @@ If a required scope is missing, the CLI surfaces a hint such as `lark-cli auth l
|
||||
|
||||
- [lark-im](../SKILL.md) — all IM commands
|
||||
- [lark-shared](../../lark-shared/SKILL.md) — authentication and global parameters
|
||||
- Design wiki: `https://bytedance.larkoffice.com/wiki/LIdSwrCzaitg3MkH8oScLhBCnFQ`
|
||||
- IDL source (internal): `lark.im.datasync.open.thrift`
|
||||
|
||||
@@ -10,7 +10,7 @@ A message can have flags on both layers simultaneously:
|
||||
- Message layer: `(default, message)`
|
||||
- Feed layer: `(thread, feed)` or `(msg_thread, feed)` depending on chat type
|
||||
|
||||
**When no `--flag-type` is specified, the shortcut performs double-cancel**: removes both message layer and feed layer flags. The server handles cancel requests for non-existent flags idempotently, so this is safe.
|
||||
**When no `--flag-type` is specified, the shortcut performs best-effort double-cancel**: the message-layer flag is always removed; the feed-layer flag is also removed when the chat type can be determined (otherwise a warning is printed on stderr and the feed layer is skipped). The server handles cancel requests for non-existent flags idempotently, so this is safe.
|
||||
|
||||
**Feed layer item_type is determined by chat_mode**:
|
||||
- Topic-style chat (`chat_mode=topic`) → `item_type=thread`
|
||||
@@ -37,7 +37,7 @@ lark-cli im +flag-cancel --as user --message-id om_xxx --dry-run
|
||||
| Parameter | Required | Description |
|
||||
|------|------|------|
|
||||
| `--message-id <om_xxx>` | Required | Message ID |
|
||||
| `--flag-type <name>` | No | `message` or `feed`; **when omitted, double-cancels both layers** |
|
||||
| `--flag-type <name>` | No | `message` or `feed`; **when omitted, best-effort double-cancel of both layers** |
|
||||
| `--item-type <name>` | No | `default\|thread\|msg_thread`; required when `--flag-type feed` |
|
||||
| `--as user` | Required | Currently only supports user identity |
|
||||
|
||||
|
||||
@@ -126,6 +126,7 @@ lark-cli 命令执行后,如果检测到新版本,JSON 输出中会包含 `_
|
||||
- **禁止输出密钥**(appSecret、accessToken)到终端明文。
|
||||
- **写入/删除操作前必须确认用户意图**。
|
||||
- 用 `--dry-run` 预览危险请求。
|
||||
- **文件路径只接受相对路径**:`--file`、`--output`、`--output-dir`、`@file` 等路径参数只接受 cwd 下的相对路径,传绝对路径会报 `unsafe file path`。数据输入(`@file`、大 JSON)优先用 stdin 传入,避免路径和转义问题。
|
||||
|
||||
## 高风险操作的审批协议(exit 10)
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ metadata:
|
||||
| 上传或使用图片 | 先上传为 `file_token`,禁止直接写 http(s) 外链 | `slides +media-upload`,或 `+create --slides` 的 `@./path` 占位符 |
|
||||
| 在 slide 中绘制柱/条/折线/面积/雷达/饼等有数据序列的图表 | 使用原生 `<chart>` 元素 | `xml-schema-quick-ref.md` |
|
||||
| 在 slide 中绘制流程图、时序图、架构图、散点图、漏斗图或装饰图案 | 必须先用 Read 工具读取参考文档,再生成 `<whiteboard>` 元素 | [`lark-slides-whiteboard.md`](references/lark-slides-whiteboard.md) |
|
||||
| 使用语义图标 | 先检索 IconPark,再写 `<icon iconType="...">` | `iconpark_tool.py search → resolve`、`iconpark.md` |
|
||||
| 用户提到模板、主题、版式 | 先检索模板,再摘要,必要时裁切骨架 | `template_tool.py search → summarize → extract` |
|
||||
| 创建失败、空白页、3350001、布局异常 | 先回读状态,再按排障清单修复,不假设原操作原子成功 | `troubleshooting.md`、`validation-checklist.md` |
|
||||
|
||||
@@ -83,6 +84,7 @@ lark-cli auth login --domain slides
|
||||
- 编辑:[`lark-slides-edit-workflows.md`](references/lark-slides-edit-workflows.md)、[`lark-slides-replace-slide.md`](references/lark-slides-replace-slide.md)
|
||||
- 图片:[`lark-slides-media-upload.md`](references/lark-slides-media-upload.md)
|
||||
- 流程图 / 时序图 / 架构图 / 装饰图案:[`lark-slides-whiteboard.md`](references/lark-slides-whiteboard.md)
|
||||
- 图标:[`iconpark.md`](references/iconpark.md)、[`scripts/iconpark_tool.py`](scripts/iconpark_tool.py)
|
||||
- 模板:[`template-catalog.md`](references/template-catalog.md)、[`scripts/template_tool.py`](scripts/template_tool.py)
|
||||
- 排障:[`troubleshooting.md`](references/troubleshooting.md)
|
||||
- 完整协议:[`slides_xml_schema_definition.xml`](references/slides_xml_schema_definition.xml)
|
||||
|
||||
41901
skills/lark-slides/references/iconpark-index.json
Normal file
41901
skills/lark-slides/references/iconpark-index.json
Normal file
File diff suppressed because it is too large
Load Diff
46
skills/lark-slides/references/iconpark.md
Normal file
46
skills/lark-slides/references/iconpark.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# IconPark 图标
|
||||
|
||||
IconPark 图标通过 `<icon>` 写入 slides XML,`iconType` 必须来自本 skill 的离线索引或已验证模板,避免凭记忆拼路径。
|
||||
|
||||
## 机器优先流程
|
||||
|
||||
```bash
|
||||
python3 skills/lark-slides/scripts/iconpark_tool.py search --query "增长趋势" --limit 8
|
||||
python3 skills/lark-slides/scripts/iconpark_tool.py resolve --name chart-line
|
||||
python3 skills/lark-slides/scripts/iconpark_tool.py list-categories
|
||||
```
|
||||
|
||||
`search` 返回 JSON 数组,每项包含 `iconType`、`category`、`name`、`tags`、`score`。直接把选中的 `iconType` 写入 XML,并为图标指定可见颜色:
|
||||
|
||||
```xml
|
||||
<icon iconType="iconpark/Charts/chart-line.svg" topLeftX="80" topLeftY="120" width="32" height="32">
|
||||
<fill>
|
||||
<fillColor color="rgba(37, 99, 235, 1)"/>
|
||||
</fill>
|
||||
</icon>
|
||||
```
|
||||
|
||||
## 使用规则
|
||||
|
||||
- 默认先检索:语义图标需求必须先用 `iconpark_tool.py search --limit 8` 或 `--limit 10`,让 agent 从候选里结合版面语义二次判断;不要阅读全文索引,也不要编造不存在的 `iconType`。
|
||||
- 图标用于概念提示、步骤、状态、指标、角色和导航;不要用无关装饰图标填充版面。
|
||||
- 常用尺寸:行内状态图标 16-24px,卡片标题图标 28-40px,主视觉图标 56-96px。
|
||||
- 图标必须显式指定颜色并和背景有足够对比;深色背景优先放在浅色圆形/方形底上,或使用 `rgba(255, 255, 255, 1)` 作为图标填充色。
|
||||
- 查不到合适图标时,用 shape、line、text 画 XML-native fallback,不留空图标位。
|
||||
|
||||
## 高频示例
|
||||
|
||||
| 语义 | iconType |
|
||||
|---|---|
|
||||
| 设置/配置 | `iconpark/Base/setting.svg` |
|
||||
| 目标 | `iconpark/Base/aiming.svg` |
|
||||
| 增长趋势 | `iconpark/Charts/positive-dynamics.svg` |
|
||||
| 折线趋势 | `iconpark/Charts/chart-line.svg` |
|
||||
| 占比 | `iconpark/Charts/chart-proportion.svg` |
|
||||
| 数据看板 | `iconpark/Charts/data-screen.svg` |
|
||||
| 成功 | `iconpark/Character/check-one.svg` |
|
||||
| 失败/风险 | `iconpark/Character/close-one.svg` |
|
||||
| 团队/用户 | `iconpark/Peoples/peoples.svg` |
|
||||
| 安全防护 | `iconpark/Safe/protect.svg` |
|
||||
| 全球/市场 | `iconpark/Travel/world.svg` |
|
||||
| 邮件/联系 | `iconpark/Office/envelope-one.svg` |
|
||||
@@ -84,7 +84,7 @@ lark-cli slides +replace-slide --as user \
|
||||
| `<line>` | 直线 | 需 `startX/startY/endX/endY` |
|
||||
| `<polyline>` | 折线 | `points` 读回时被服务端规整丢弃(几何已入库) |
|
||||
| `<img>` | 图片 | `src` 必须是 [`+media-upload`](lark-slides-media-upload.md) 返回的 `file_token`,不能是 URL |
|
||||
| `<icon>` | 图标 | `iconType` 取自 iconpark 资源 |
|
||||
| `<icon>` | 图标 | `iconType` 取自 iconpark 资源;语义图标先用 `scripts/iconpark_tool.py search` 检索 |
|
||||
| `<table>` | 表格 | 整表替换会**重建内部 td id**,旧 td block_id 立即失效 |
|
||||
| `<td>` | 单元格局部替换 | 只能 `block_replace`,不能 `block_insert`;`block_id` 必须是最新 `slide.get` 拿到的 td id |
|
||||
| `<chart>` | 图表(line/bar/column/pie/area/radar/combo) | 必须嵌 `<chartPlotArea>` + `<chartData>` + `<dim1>/<dim2>/<chartField>` |
|
||||
|
||||
@@ -142,6 +142,8 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
<icon iconType="iconpark/Base/setting.svg" topLeftX="80" topLeftY="120" width="32" height="32"/>
|
||||
```
|
||||
|
||||
`iconType` 必须来自已验证的 IconPark 路径。需要语义图标时,先运行 `scripts/iconpark_tool.py search --query "<语义>"`,不要凭记忆拼路径。更多规则见 [iconpark.md](iconpark.md)。
|
||||
|
||||
### whiteboard
|
||||
|
||||
```xml
|
||||
|
||||
362
skills/lark-slides/scripts/iconpark_tool.py
Normal file
362
skills/lark-slides/scripts/iconpark_tool.py
Normal file
@@ -0,0 +1,362 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
||||
REFERENCES_DIR = SKILL_ROOT / "references"
|
||||
DEFAULT_INDEX_PATH = REFERENCES_DIR / "iconpark-index.json"
|
||||
DEFAULT_LIMIT = 8
|
||||
CURATED_ICON_BOOSTS = {
|
||||
"设置": {"iconpark/Base/setting.svg"},
|
||||
"配置": {"iconpark/Base/setting.svg", "iconpark/Base/config.svg"},
|
||||
"目标": {"iconpark/Base/aiming.svg", "iconpark/Sports/target-one.svg"},
|
||||
"增长": {"iconpark/Charts/positive-dynamics.svg"},
|
||||
"趋势": {"iconpark/Charts/chart-line.svg", "iconpark/Charts/positive-dynamics.svg"},
|
||||
"占比": {"iconpark/Charts/chart-proportion.svg"},
|
||||
"数据": {"iconpark/Charts/data-screen.svg"},
|
||||
"看板": {"iconpark/Charts/data-screen.svg"},
|
||||
"成功": {"iconpark/Character/check-one.svg"},
|
||||
"完成": {"iconpark/Character/check-one.svg"},
|
||||
"失败": {"iconpark/Character/close-one.svg"},
|
||||
"风险": {"iconpark/Character/close-one.svg"},
|
||||
"团队": {"iconpark/Peoples/peoples.svg"},
|
||||
"用户": {"iconpark/Peoples/peoples.svg", "iconpark/Peoples/user.svg"},
|
||||
"安全": {"iconpark/Safe/protect.svg"},
|
||||
"防护": {"iconpark/Safe/protect.svg"},
|
||||
"全球": {"iconpark/Travel/world.svg"},
|
||||
"市场": {"iconpark/Travel/world.svg"},
|
||||
"邮件": {"iconpark/Office/envelope-one.svg"},
|
||||
"联系": {"iconpark/Office/envelope-one.svg"},
|
||||
"会议": {"iconpark/Office/schedule.svg"},
|
||||
"日程": {"iconpark/Office/schedule.svg"},
|
||||
"飞书": {"iconpark/Brand/bydesign.svg"},
|
||||
}
|
||||
CURATED_BOOST_SCORE = 40
|
||||
|
||||
|
||||
class IconParkToolError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise IconParkToolError(message)
|
||||
|
||||
|
||||
def normalize_whitespace(value: str) -> str:
|
||||
return re.sub(r"\s+", " ", value).strip()
|
||||
|
||||
|
||||
def normalize_token(value: str) -> str:
|
||||
return normalize_whitespace(value.lower().replace("_", "-"))
|
||||
|
||||
|
||||
def append_unique(target: list[str], token: str) -> None:
|
||||
normalized = normalize_token(token)
|
||||
if normalized and normalized not in target:
|
||||
target.append(normalized)
|
||||
|
||||
|
||||
def tokenize_query(value: str) -> list[str]:
|
||||
normalized = normalize_token(value)
|
||||
if not normalized:
|
||||
return []
|
||||
|
||||
tokens: list[str] = []
|
||||
for item in re.split(r"[\s,/|,。;;::()()【】\[\]《》<>]+", normalized):
|
||||
append_unique(tokens, item)
|
||||
|
||||
for phrase in re.findall(r"[\u3400-\u9fff]+", normalized):
|
||||
if len(phrase) < 2:
|
||||
continue
|
||||
max_size = min(6, len(phrase))
|
||||
for size in range(max_size, 1, -1):
|
||||
for start in range(0, len(phrase) - size + 1):
|
||||
append_unique(tokens, phrase[start : start + size])
|
||||
|
||||
synonym_tokens = {
|
||||
"目标": ["aim", "target", "goal"],
|
||||
"聚焦": ["focus", "target"],
|
||||
"增长": ["growth", "trend", "positive"],
|
||||
"趋势": ["trend", "chart", "line"],
|
||||
"数据": ["data", "analytics", "chart"],
|
||||
"指标": ["metric", "data"],
|
||||
"看板": ["dashboard", "screen", "data"],
|
||||
"成功": ["success", "check", "done"],
|
||||
"完成": ["done", "success", "check"],
|
||||
"失败": ["fail", "close", "risk"],
|
||||
"风险": ["risk", "fail", "protect"],
|
||||
"安全": ["safe", "security", "protect"],
|
||||
"配置": ["config", "setting", "system"],
|
||||
"设置": ["setting", "config"],
|
||||
"团队": ["team", "people", "users"],
|
||||
"用户": ["user", "people"],
|
||||
"全球": ["global", "world", "earth"],
|
||||
"市场": ["market", "world", "business"],
|
||||
"邮件": ["mail", "message"],
|
||||
"mail": ["message", "envelope", "envelope-one"],
|
||||
"计划": ["plan", "schedule"],
|
||||
"时间": ["time", "schedule"],
|
||||
"学习": ["learning", "education", "book"],
|
||||
"培训": ["training", "education"],
|
||||
"自动化": ["automation", "ai"],
|
||||
"ai": ["ai", "automation", "magic"],
|
||||
}
|
||||
for token in list(tokens):
|
||||
for keyword, aliases in synonym_tokens.items():
|
||||
if is_ascii_token(keyword):
|
||||
matches = token == keyword
|
||||
else:
|
||||
matches = keyword in token
|
||||
if matches:
|
||||
for alias in aliases:
|
||||
append_unique(tokens, alias)
|
||||
|
||||
return tokens
|
||||
|
||||
|
||||
def is_ascii_token(value: str) -> bool:
|
||||
return bool(re.fullmatch(r"[a-z0-9-]+", value))
|
||||
|
||||
|
||||
def allows_substring_match(value: str) -> bool:
|
||||
return not is_ascii_token(value) or len(value) >= 3
|
||||
|
||||
|
||||
def field_tokens(*values: str) -> set[str]:
|
||||
tokens: set[str] = set()
|
||||
for value in values:
|
||||
normalized = normalize_token(value)
|
||||
if not normalized:
|
||||
continue
|
||||
tokens.add(normalized)
|
||||
for part in re.split(r"[-\s]+", normalized):
|
||||
if part:
|
||||
tokens.add(part)
|
||||
return tokens
|
||||
|
||||
|
||||
def load_index(path: str | Path = DEFAULT_INDEX_PATH) -> dict[str, Any]:
|
||||
index_path = Path(path)
|
||||
if not index_path.exists():
|
||||
fail(f"iconpark index not found: {index_path}")
|
||||
try:
|
||||
index_data = json.loads(index_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as error:
|
||||
fail(f"invalid iconpark index JSON: {error}")
|
||||
if not isinstance(index_data.get("icons"), list):
|
||||
fail("iconpark index must contain an icons array")
|
||||
return index_data
|
||||
|
||||
|
||||
def icon_search_text(entry: dict[str, Any]) -> str:
|
||||
parts = [
|
||||
entry.get("iconType", ""),
|
||||
entry.get("category", ""),
|
||||
entry.get("name", ""),
|
||||
" ".join(entry.get("tags") or []),
|
||||
]
|
||||
return normalize_token(" ".join(parts))
|
||||
|
||||
|
||||
def score_icon(entry: dict[str, Any], query: str, tokens: list[str]) -> int:
|
||||
raw_icon_type = entry.get("iconType", "")
|
||||
icon_type = normalize_token(raw_icon_type)
|
||||
category = normalize_token(entry.get("category", ""))
|
||||
name = normalize_token(entry.get("name", ""))
|
||||
tags = [normalize_token(tag) for tag in entry.get("tags") or []]
|
||||
name_tokens = field_tokens(name)
|
||||
category_tokens = field_tokens(category)
|
||||
tag_tokens = field_tokens(*tags)
|
||||
icon_type_tokens = field_tokens(icon_type)
|
||||
search_text = icon_search_text(entry)
|
||||
normalized_query = normalize_token(query)
|
||||
|
||||
score = 0
|
||||
boosted_keywords: set[str] = set()
|
||||
if normalized_query:
|
||||
if normalized_query == icon_type or normalized_query == name:
|
||||
score += 200
|
||||
elif normalized_query in tag_tokens:
|
||||
score += 120
|
||||
elif normalized_query in icon_type_tokens:
|
||||
score += 60
|
||||
elif allows_substring_match(normalized_query) and normalized_query in search_text:
|
||||
score += 30
|
||||
|
||||
for token in tokens:
|
||||
for keyword, boosted_icon_types in CURATED_ICON_BOOSTS.items():
|
||||
if keyword in boosted_keywords:
|
||||
continue
|
||||
if keyword in token and raw_icon_type in boosted_icon_types:
|
||||
score += CURATED_BOOST_SCORE
|
||||
boosted_keywords.add(keyword)
|
||||
if token == name:
|
||||
score += 80
|
||||
elif token in name_tokens:
|
||||
score += 55
|
||||
elif allows_substring_match(token) and token in name:
|
||||
score += 45
|
||||
if token == category:
|
||||
score += 35
|
||||
elif token in category_tokens:
|
||||
score += 25
|
||||
elif allows_substring_match(token) and token in category:
|
||||
score += 15
|
||||
for tag in tags:
|
||||
if token == tag:
|
||||
score += 60
|
||||
elif token in field_tokens(tag):
|
||||
score += 45
|
||||
elif allows_substring_match(token) and token in tag:
|
||||
score += 20
|
||||
if token in icon_type_tokens:
|
||||
score += 20
|
||||
elif allows_substring_match(token) and token in icon_type:
|
||||
score += 15
|
||||
|
||||
return score
|
||||
|
||||
|
||||
def parse_limit(value: Any) -> int:
|
||||
if value is None or value is False:
|
||||
return DEFAULT_LIMIT
|
||||
if value is True:
|
||||
fail("limit requires an integer value")
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
fail(f"limit must be an integer: {value}")
|
||||
|
||||
|
||||
def public_icon(entry: dict[str, Any], score: int | None = None) -> dict[str, Any]:
|
||||
result = {
|
||||
"iconType": entry["iconType"],
|
||||
"category": entry["category"],
|
||||
"name": entry["name"],
|
||||
"tags": entry.get("tags") or [],
|
||||
}
|
||||
if score is not None:
|
||||
result["score"] = score
|
||||
return result
|
||||
|
||||
|
||||
def search_icons(index_data: dict[str, Any], options: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
query = str(options.get("query") or "")
|
||||
if not normalize_whitespace(query):
|
||||
fail("query is required")
|
||||
limit = parse_limit(options.get("limit"))
|
||||
category_filter = normalize_token(str(options.get("category") or ""))
|
||||
tokens = tokenize_query(query)
|
||||
|
||||
ranked: list[dict[str, Any]] = []
|
||||
for entry in index_data["icons"]:
|
||||
if category_filter and normalize_token(entry.get("category", "")) != category_filter:
|
||||
continue
|
||||
score = score_icon(entry, query, tokens)
|
||||
if query and score == 0:
|
||||
continue
|
||||
ranked.append(public_icon(entry, score))
|
||||
|
||||
ranked.sort(key=lambda item: (-int(item["score"]), item["category"], item["name"]))
|
||||
return ranked[: max(limit, 0)]
|
||||
|
||||
|
||||
def resolve_icon(index_data: dict[str, Any], name_or_type: str | None) -> dict[str, Any]:
|
||||
if not name_or_type:
|
||||
fail("name is required")
|
||||
target = normalize_token(name_or_type)
|
||||
matches = []
|
||||
for entry in index_data["icons"]:
|
||||
candidates = {
|
||||
normalize_token(entry["iconType"]),
|
||||
normalize_token(entry["name"]),
|
||||
normalize_token(f'{entry["category"]}/{entry["name"]}.svg'),
|
||||
}
|
||||
if target in candidates:
|
||||
matches.append(entry)
|
||||
if not matches:
|
||||
fail(f"icon not found: {name_or_type}")
|
||||
if len(matches) > 1:
|
||||
names = ", ".join(entry["iconType"] for entry in matches)
|
||||
fail(f"ambiguous icon name: {name_or_type}; matches: {names}")
|
||||
return public_icon(matches[0])
|
||||
|
||||
|
||||
def list_categories(index_data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
counts: dict[str, int] = {}
|
||||
for entry in index_data["icons"]:
|
||||
counts[entry["category"]] = counts.get(entry["category"], 0) + 1
|
||||
return [{"category": category, "count": counts[category]} for category in sorted(counts)]
|
||||
|
||||
|
||||
def parse_cli_args(argv: list[str]) -> tuple[str | None, dict[str, Any]]:
|
||||
if not argv:
|
||||
return None, {}
|
||||
command, *rest = argv
|
||||
options: dict[str, Any] = {}
|
||||
index = 0
|
||||
while index < len(rest):
|
||||
token = rest[index]
|
||||
if not token.startswith("--"):
|
||||
fail(f"unexpected argument: {token}")
|
||||
key = token[2:]
|
||||
next_token = rest[index + 1] if index + 1 < len(rest) else None
|
||||
if next_token is None or next_token.startswith("--"):
|
||||
options[key] = True
|
||||
index += 1
|
||||
continue
|
||||
options[key] = next_token
|
||||
index += 2
|
||||
return command, options
|
||||
|
||||
|
||||
def print_usage() -> None:
|
||||
usage = [
|
||||
"Usage:",
|
||||
" python3 iconpark_tool.py search --query <text> [--category <Category>] [--limit 8]",
|
||||
" python3 iconpark_tool.py resolve --name <name|iconType>",
|
||||
" python3 iconpark_tool.py list-categories",
|
||||
]
|
||||
print("\n".join(usage), file=sys.stderr)
|
||||
|
||||
|
||||
def write_json(value: Any) -> None:
|
||||
print(json.dumps(value, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def run_cli(argv: list[str] | None = None) -> None:
|
||||
command, options = parse_cli_args(argv or sys.argv[1:])
|
||||
if not command or command in {"--help", "help"}:
|
||||
print_usage()
|
||||
raise SystemExit(0)
|
||||
|
||||
index_data = load_index()
|
||||
if command == "search":
|
||||
write_json(search_icons(index_data, options))
|
||||
return
|
||||
if command == "resolve":
|
||||
write_json(resolve_icon(index_data, options.get("name")))
|
||||
return
|
||||
if command == "list-categories":
|
||||
write_json(list_categories(index_data))
|
||||
return
|
||||
|
||||
print_usage()
|
||||
fail(f"unknown command: {command}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
run_cli()
|
||||
except IconParkToolError as error:
|
||||
print(f"iconpark-tool error: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from error
|
||||
177
skills/lark-slides/scripts/iconpark_tool_test.py
Normal file
177
skills/lark-slides/scripts/iconpark_tool_test.py
Normal file
@@ -0,0 +1,177 @@
|
||||
# Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
# SPDX-License-Identifier: MIT
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import iconpark_tool
|
||||
|
||||
|
||||
SCRIPT_PATH = Path(__file__).resolve().with_name("iconpark_tool.py")
|
||||
|
||||
|
||||
class IconParkToolTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.index_data = iconpark_tool.load_index()
|
||||
|
||||
def test_search_icons_finds_growth_trend(self) -> None:
|
||||
results = iconpark_tool.search_icons(self.index_data, {"query": "增长趋势", "limit": 5})
|
||||
self.assertTrue(results)
|
||||
self.assertTrue(
|
||||
any(entry["iconType"] == "iconpark/Charts/positive-dynamics.svg" for entry in results)
|
||||
)
|
||||
|
||||
def test_search_icons_supports_english_query(self) -> None:
|
||||
results = iconpark_tool.search_icons(self.index_data, {"query": "security protect", "limit": 3})
|
||||
self.assertTrue(results)
|
||||
self.assertEqual(results[0]["iconType"], "iconpark/Safe/protect.svg")
|
||||
|
||||
def test_search_icons_supports_category_filter(self) -> None:
|
||||
results = iconpark_tool.search_icons(
|
||||
self.index_data,
|
||||
{"query": "data", "category": "Charts", "limit": 10},
|
||||
)
|
||||
self.assertTrue(results)
|
||||
self.assertTrue(all(entry["category"] == "Charts" for entry in results))
|
||||
|
||||
def test_search_icons_does_not_expand_ai_inside_words(self) -> None:
|
||||
mail_results = iconpark_tool.search_icons(self.index_data, {"query": "mail", "limit": 5})
|
||||
self.assertEqual(mail_results[0]["iconType"], "iconpark/Office/envelope-one.svg")
|
||||
self.assertNotEqual(mail_results[0]["iconType"], "iconpark/Others/magic.svg")
|
||||
|
||||
fail_results = iconpark_tool.search_icons(self.index_data, {"query": "fail", "limit": 5})
|
||||
self.assertNotEqual(fail_results[0]["iconType"], "iconpark/Others/magic.svg")
|
||||
|
||||
def test_search_icons_supports_template_icon_queries(self) -> None:
|
||||
cases = [
|
||||
("arrow", "iconpark/Arrows/arrow-right.svg"),
|
||||
("right", "iconpark/Arrows/right.svg"),
|
||||
("PPT", "iconpark/Music/ppt.svg"),
|
||||
("table", "iconpark/Office/table.svg"),
|
||||
("会议", "iconpark/Office/schedule.svg"),
|
||||
("飞书", "iconpark/Brand/bydesign.svg"),
|
||||
]
|
||||
for query, icon_type in cases:
|
||||
with self.subTest(query=query):
|
||||
results = iconpark_tool.search_icons(self.index_data, {"query": query, "limit": 10})
|
||||
self.assertTrue(
|
||||
any(entry["iconType"] == icon_type for entry in results),
|
||||
f"{icon_type} not found in {results}",
|
||||
)
|
||||
|
||||
def test_search_icons_defaults_to_wider_candidate_set(self) -> None:
|
||||
results = iconpark_tool.search_icons(self.index_data, {"query": "data"})
|
||||
self.assertEqual(len(results), 8)
|
||||
|
||||
def test_search_icons_boosts_common_slide_terms(self) -> None:
|
||||
results = iconpark_tool.search_icons(self.index_data, {"query": "会议", "limit": 3})
|
||||
self.assertTrue(
|
||||
any(entry["iconType"] == "iconpark/Office/schedule.svg" for entry in results),
|
||||
f"iconpark/Office/schedule.svg not found in {results}",
|
||||
)
|
||||
|
||||
def test_search_icons_keeps_high_value_top_results(self) -> None:
|
||||
cases = [
|
||||
("安全", "iconpark/Safe/protect.svg"),
|
||||
("邮件", "iconpark/Office/mail-open.svg"),
|
||||
("会议", "iconpark/Office/schedule.svg"),
|
||||
("增长趋势", "iconpark/Charts/chart-line.svg"),
|
||||
("飞书", "iconpark/Brand/bydesign.svg"),
|
||||
]
|
||||
for query, icon_type in cases:
|
||||
with self.subTest(query=query):
|
||||
results = iconpark_tool.search_icons(self.index_data, {"query": query, "limit": 3})
|
||||
self.assertTrue(results)
|
||||
self.assertEqual(results[0]["iconType"], icon_type)
|
||||
|
||||
def test_search_icons_requires_query(self) -> None:
|
||||
with self.assertRaises(iconpark_tool.IconParkToolError):
|
||||
iconpark_tool.search_icons(self.index_data, {"limit": 5})
|
||||
|
||||
def test_search_icons_rejects_invalid_limit(self) -> None:
|
||||
with self.assertRaises(iconpark_tool.IconParkToolError):
|
||||
iconpark_tool.search_icons(self.index_data, {"query": "data", "limit": "abc"})
|
||||
|
||||
def test_resolve_icon_accepts_name_and_icon_type(self) -> None:
|
||||
by_name = iconpark_tool.resolve_icon(self.index_data, "chart-line")
|
||||
by_type = iconpark_tool.resolve_icon(self.index_data, "iconpark/Charts/chart-line.svg")
|
||||
self.assertEqual(by_name["iconType"], "iconpark/Charts/chart-line.svg")
|
||||
self.assertEqual(by_name, by_type)
|
||||
|
||||
def test_resolve_icon_accepts_template_icon_type(self) -> None:
|
||||
result = iconpark_tool.resolve_icon(self.index_data, "iconpark/Arrows/arrow-right.svg")
|
||||
self.assertEqual(result["iconType"], "iconpark/Arrows/arrow-right.svg")
|
||||
|
||||
def test_resolve_icon_rejects_unknown_name(self) -> None:
|
||||
with self.assertRaises(iconpark_tool.IconParkToolError):
|
||||
iconpark_tool.resolve_icon(self.index_data, "not-a-real-icon")
|
||||
|
||||
def test_list_categories_counts_index(self) -> None:
|
||||
categories = iconpark_tool.list_categories(self.index_data)
|
||||
self.assertTrue(any(entry["category"] == "Charts" and entry["count"] > 0 for entry in categories))
|
||||
|
||||
|
||||
class IconParkToolCLITest(unittest.TestCase):
|
||||
def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SCRIPT_PATH), *args],
|
||||
capture_output=True,
|
||||
check=False,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def test_cli_search_writes_json_to_stdout(self) -> None:
|
||||
result = self.run_tool("search", "--query", "增长趋势", "--limit", "5")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
output = json.loads(result.stdout)
|
||||
self.assertTrue(output)
|
||||
self.assertTrue(
|
||||
any(entry["iconType"] == "iconpark/Charts/positive-dynamics.svg" for entry in output)
|
||||
)
|
||||
|
||||
def test_cli_resolve_writes_json_to_stdout(self) -> None:
|
||||
result = self.run_tool("resolve", "--name", "chart-line")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
output = json.loads(result.stdout)
|
||||
self.assertEqual(output["iconType"], "iconpark/Charts/chart-line.svg")
|
||||
|
||||
def test_cli_list_categories_writes_json_to_stdout(self) -> None:
|
||||
result = self.run_tool("list-categories")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
output = json.loads(result.stdout)
|
||||
self.assertTrue(any(entry["category"] == "Charts" and entry["count"] > 0 for entry in output))
|
||||
|
||||
def test_cli_help_writes_usage_to_stderr(self) -> None:
|
||||
result = self.run_tool("--help")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "")
|
||||
self.assertIn("Usage:", result.stderr)
|
||||
self.assertIn("python3 iconpark_tool.py search", result.stderr)
|
||||
|
||||
def test_cli_invalid_argument_writes_error_to_stderr(self) -> None:
|
||||
result = self.run_tool("search", "增长趋势")
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(result.stdout, "")
|
||||
self.assertIn("iconpark-tool error: unexpected argument: 增长趋势", result.stderr)
|
||||
|
||||
def test_cli_unknown_command_writes_usage_and_error_to_stderr(self) -> None:
|
||||
result = self.run_tool("unknown")
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(result.stdout, "")
|
||||
self.assertIn("Usage:", result.stderr)
|
||||
self.assertIn("iconpark-tool error: unknown command: unknown", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: lark-wiki
|
||||
version: 1.0.0
|
||||
description: "飞书知识库:管理知识空间、空间成员和文档节点。创建和查询知识空间、查看和管理空间成员、管理节点层级结构、在知识库中组织文档和快捷方式。当用户需要在知识库中查找或创建文档、浏览知识空间结构、查看或管理空间成员、移动或复制节点时使用。当用户给出 doubao.com 的 /wiki/ URL/token 时,也应直接使用本 skill,不要因为域名不是飞书而回退到 WebFetch;路由依据是 URL 路径模式和 token,而不是域名。"
|
||||
version: 1.0.1
|
||||
description: "飞书知识库:管理知识空间、空间成员和文档节点。创建和查询知识空间、查看和管理空间成员、管理节点层级结构、在知识库中组织文档和快捷方式。当用户需要在知识库中查找或创建文档、浏览知识空间结构、查看或管理空间成员、移动或复制节点时使用。当用户给出 doubao.com 的 /wiki/ URL/token 时,也应直接使用本 skill,不要因为域名不是飞书而回退到 WebFetch;路由依据是 URL 路径模式和 token,而不是域名。不负责:上传文件到知识库节点下(走 lark-drive)、编辑文档/表格/Base 内容(走 lark-doc / lark-sheets / lark-base)。"
|
||||
metadata:
|
||||
requires:
|
||||
bins: ["lark-cli"]
|
||||
@@ -32,6 +32,7 @@ metadata:
|
||||
- **关键安全约束**:无论精确还是模糊,**无论命中 1 条还是多条,发起删除前都必须把候选(`name` + `space_id` + `description` + `space_type`)列给用户,由用户明确选定一个 `space_id` 再执行**。不要因为"只命中一条"就自动执行删除。
|
||||
- 命中 0 条:停下来问用户是名称拼错了还是调用方无权限;**不要**自行改名字重试。
|
||||
- 用户明确选定后再执行 `lark-cli wiki +delete-space --space-id <ID> --yes`(高风险写操作,必须显式 `--yes`)。
|
||||
- 反例:不要把 wiki URL / 名称直接当 `--space-id`(如 `--space-id "https://.../wiki/<wiki_token>"`);务必先用 `wiki spaces get_node` 解析出 `data.node.space_id` 再传。
|
||||
- 用户要在知识库中创建新节点,优先使用 `lark-cli wiki +node-create`。
|
||||
- 用户说“给知识库添加成员/管理员”:先把目标解析成“用户 / 群 / 部门 / 应用”四类之一,再决定 `--member-type`,不要先调 `wiki +member-add` 再根据报错反推类型。
|
||||
- 用户说“部门 + bot”:这是已知不支持路径。不要继续尝试 `wiki +member-add --as bot`;直接提示必须改成 `--as user`,或明确告知当前要求无法完成。
|
||||
@@ -39,23 +40,6 @@ metadata:
|
||||
- 用户说“查看 / 列出空间成员”:用 `wiki +member-list`;该 shortcut 默认只取一页,多成员场景显式加 `--page-all`。
|
||||
- 用户说“移除 / 删除空间成员”:用 `wiki +member-remove`,必须传齐原始授予时的 `--member-type` 和 `--member-role`(不知道就先 `wiki +member-list` 查一下)。
|
||||
|
||||
## 成员添加流程
|
||||
|
||||
- 调用 `lark-cli wiki +member-add` 前,先把自然语言里的“人 / 群 / 部门 / 应用”解析成正确的 `--member-id`,不要猜格式。
|
||||
- 用户场景默认优先 `--member-type=openid`:用 `lark-cli contact +search-user --query "<姓名/邮箱/手机号>" --format json` 获取 `open_id`。
|
||||
- 群组场景使用 `--member-type=openchat`:用 `lark-cli im +chat-search --query "<群名关键词>" --format json` 获取 `chat_id`。
|
||||
- 应用场景使用 `--member-type=appid`:`--member-id` 传应用 ID,格式通常为 `cli_xxx`。
|
||||
- `userid` / `unionid` 只在下游明确要求时才使用;先拿到 `open_id`,再调用 `lark-cli api GET /open-apis/contact/v3/users/<open_id> --params '{"user_id_type":"open_id"}' --format json` 读取 `user_id` / `union_id`。
|
||||
- 部门场景使用 `--member-type=opendepartmentid`:当前 CLI 没有 shortcut,需调用 `lark-cli api POST /open-apis/contact/v3/departments/search --as user --params '{"department_id_type":"open_department_id"}' --data '{"query":"<部门名>"}'` 获取 `open_department_id`。
|
||||
- 只有在目标类型和身份都已确认可行后,才调用 `lark-cli wiki +member-add`。对于部门场景,这意味着必须是 `--as user`。
|
||||
|
||||
## 目标语义约束
|
||||
|
||||
- `我的文档库` / `My Document Library` / `我的知识库` / `个人知识库` / `my_library` 都应视为 **Wiki personal library**,不是 Drive 根目录
|
||||
- 处理这类目标时,先解析 `my_library` 对应的真实 `space_id`,再执行 `wiki +move`、`wiki +node-create` 或其他 Wiki 写操作
|
||||
- 不要因为缺少显式 `space_id` 就退化成 `drive +move`
|
||||
- 如果用户明确说的是 Drive 文件夹、云空间(云盘/云存储)根目录、`我的空间`,才进入 Drive 域处理
|
||||
|
||||
## Shortcuts(推荐优先使用)
|
||||
|
||||
Shortcut 是对常用操作的高级封装(`lark-cli wiki +<verb> [flags]`)。有 Shortcut 的操作优先使用。
|
||||
@@ -75,15 +59,30 @@ Shortcut 是对常用操作的高级封装(`lark-cli wiki +<verb> [flags]`)
|
||||
| [`+member-remove`](references/lark-wiki-member-remove.md) | Remove a member from a wiki space |
|
||||
| [`+member-list`](references/lark-wiki-member-list.md) | List members of a wiki space (supports pagination) |
|
||||
|
||||
## 成员添加流程
|
||||
|
||||
- 调用 `lark-cli wiki +member-add` 前,先把自然语言里的“人 / 群 / 部门 / 应用”解析成正确的 `--member-id`,不要猜格式。
|
||||
- 用户场景默认优先 `--member-type=openid`:用 `lark-cli contact +search-user --query "<姓名/邮箱/手机号>" --format json` 获取 `open_id`。
|
||||
- 群组场景使用 `--member-type=openchat`:用 `lark-cli im +chat-search --query "<群名关键词>" --format json` 获取 `chat_id`。
|
||||
- 应用场景使用 `--member-type=appid`:`--member-id` 传应用 ID,格式通常为 `cli_xxx`。
|
||||
- `userid` / `unionid` 只在下游明确要求时才使用;先拿到 `open_id`,再调用 `lark-cli api GET /open-apis/contact/v3/users/<open_id> --params '{"user_id_type":"open_id"}' --format json` 读取 `user_id` / `union_id`。
|
||||
- 部门场景使用 `--member-type=opendepartmentid`:当前 CLI 没有 shortcut,需调用 `lark-cli api POST /open-apis/contact/v3/departments/search --as user --params '{"department_id_type":"open_department_id"}' --data '{"query":"<部门名>"}'` 获取 `open_department_id`。
|
||||
- 只有在目标类型和身份都已确认可行后,才调用 `lark-cli wiki +member-add`。对于部门场景,这意味着必须是 `--as user`。
|
||||
|
||||
## 目标语义约束
|
||||
|
||||
- `我的文档库` / `My Document Library` / `我的知识库` / `个人知识库` / `my_library` 都应视为 **Wiki personal library**,不是 Drive 根目录
|
||||
- 处理这类目标时,先解析 `my_library` 对应的真实 `space_id`,再执行 `wiki +move`、`wiki +node-create` 或其他 Wiki 写操作
|
||||
- 不要因为缺少显式 `space_id` 就退化成 `drive +move`
|
||||
- 如果用户明确说的是 Drive 文件夹、云空间(云盘/云存储)根目录、`我的空间`,才进入 Drive 域处理
|
||||
|
||||
## API Resources
|
||||
|
||||
```bash
|
||||
lark-cli schema wiki.<resource>.<method> # 调用 API 前必须先查看参数结构
|
||||
lark-cli wiki <resource> <method> [flags] # 调用 API
|
||||
lark-cli schema wiki.<resource>.<method> # 调用原生 API 前必须先查看 --data / --params 参数结构,不要猜测字段格式
|
||||
lark-cli wiki <resource> <method> [flags] # 调用 API
|
||||
```
|
||||
|
||||
> **重要**:使用原生 API 时,必须先运行 `schema` 查看 `--data` / `--params` 参数结构,不要猜测字段格式。
|
||||
|
||||
### spaces
|
||||
|
||||
- `create` — 创建知识空间
|
||||
@@ -103,18 +102,9 @@ lark-cli wiki <resource> <method> [flags] # 调用 API
|
||||
- `create` — 创建知识空间节点
|
||||
- `list` — 获取知识空间子节点列表
|
||||
|
||||
## 权限表
|
||||
## 不在本 skill 范围
|
||||
|
||||
| 方法 | 所需 scope |
|
||||
|------|-----------|
|
||||
| `spaces.create` | `wiki:space:write_only` |
|
||||
| `spaces.get` | `wiki:space:read` |
|
||||
| `spaces.get_node` | `wiki:node:read` |
|
||||
| `spaces.list` | `wiki:space:retrieve` |
|
||||
| `members.create` | `wiki:member:create` |
|
||||
| `members.delete` | `wiki:member:update` |
|
||||
| `members.list` | `wiki:member:retrieve` |
|
||||
| `nodes.copy` | `wiki:node:copy` |
|
||||
| `nodes.move` | `wiki:node:move` |
|
||||
| `nodes.create` | `wiki:node:create` |
|
||||
| `nodes.list` | `wiki:node:retrieve` |
|
||||
- 上传 / 下载文件到知识库节点下 → [`lark-drive`](../lark-drive/SKILL.md)(`drive +upload --wiki-token`)
|
||||
- 编辑文档正文内容 → [`lark-doc`](../lark-doc/SKILL.md)
|
||||
- 表格 / 多维表格数据操作 → [`lark-sheets`](../lark-sheets/SKILL.md) / [`lark-base`](../lark-base/SKILL.md)
|
||||
- 按名称搜索文档 / Wiki / 表格文件、评论与权限管理 → [`lark-drive`](../lark-drive/SKILL.md)
|
||||
|
||||
35
skills_embed.go
Normal file
35
skills_embed.go
Normal file
@@ -0,0 +1,35 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
|
||||
"github.com/larksuite/cli/cmd"
|
||||
)
|
||||
|
||||
// skillsEmbedFS embeds each skill's agent-readable content (SKILL.md +
|
||||
// references/, plus lark-whiteboard's routes/ and scenes/) so the CLI serves
|
||||
// content matching the binary version; machine-resource dirs (assets/, scripts/)
|
||||
// are excluded, saving ~3.3 MB. It's a whitelist — a new subdirectory type is
|
||||
// silently omitted until added here.
|
||||
//
|
||||
//go:embed skills/*/SKILL.md skills/*/references skills/*/routes skills/*/scenes
|
||||
var skillsEmbedFS embed.FS
|
||||
|
||||
// init wires the embedded tree in as the default skill content. It compiles into
|
||||
// `go build .` but not the single-file preview build (`go build ./main.go`), so
|
||||
// main.go stays self-contained and that build still compiles (shipping no
|
||||
// embedded skills). Assembly failure warns on stderr rather than panicking.
|
||||
func init() {
|
||||
sub, err := fs.Sub(skillsEmbedFS, "skills")
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "warning: skills embed assembly failed, skills commands disabled:", err)
|
||||
return
|
||||
}
|
||||
cmd.SetEmbeddedSkillContent(sub)
|
||||
}
|
||||
Reference in New Issue
Block a user