mirror of
https://github.com/larksuite/cli.git
synced 2026-07-08 18:13:01 +08:00
Compare commits
11 Commits
feat/sessi
...
feat/slide
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
386e35e237 | ||
|
|
a962bec276 | ||
|
|
7f4631e195 | ||
|
|
a6ce6f8db2 | ||
|
|
5dd6d75977 | ||
|
|
ba20f354ed | ||
|
|
0db6fe4b4d | ||
|
|
bca66cb620 | ||
|
|
ef9f397423 | ||
|
|
869a259d4e | ||
|
|
ee46e22abd |
18
README.md
18
README.md
@@ -233,6 +233,24 @@ lark-cli api POST /open-apis/im/v1/messages --params '{"receive_id_type":"chat_i
|
||||
--format csv # Comma-separated values
|
||||
```
|
||||
|
||||
### JSON Output Contract
|
||||
|
||||
With `--format json` (the default), success and error envelopes are distinct.
|
||||
|
||||
Success goes to **stdout**, exit code `0`:
|
||||
|
||||
```json
|
||||
{ "ok": true, "identity": "user", "data": { "guid": "..." }, "meta": { "count": 1 } }
|
||||
```
|
||||
|
||||
Errors go to **stderr**, non-zero exit code:
|
||||
|
||||
```json
|
||||
{ "ok": false, "identity": "user", "error": { "type": "api", "subtype": "...", "code": 99991679, "message": "...", "hint": "..." } }
|
||||
```
|
||||
|
||||
To check whether a command succeeded, test `ok == true` (or the exit code) — **not** `code == 0`. Unlike raw OpenAPI responses (`{"code": 0, "msg": "ok", ...}`), the success envelope carries no `code` or `msg` field; `code` appears only inside `error` as the upstream OpenAPI code. See [errs/ERROR_CONTRACT.md](errs/ERROR_CONTRACT.md) for the full error taxonomy.
|
||||
|
||||
### Pagination
|
||||
|
||||
```bash
|
||||
|
||||
18
README.zh.md
18
README.zh.md
@@ -234,6 +234,24 @@ lark-cli api POST /open-apis/im/v1/messages --params '{"receive_id_type":"chat_i
|
||||
--format csv # 逗号分隔值
|
||||
```
|
||||
|
||||
### JSON 输出契约
|
||||
|
||||
`--format json`(默认)下,成功与错误的信封结构不同。
|
||||
|
||||
成功信封写入 **stdout**,退出码 0:
|
||||
|
||||
```json
|
||||
{ "ok": true, "identity": "user", "data": { "guid": "..." }, "meta": { "count": 1 } }
|
||||
```
|
||||
|
||||
错误信封写入 **stderr**,退出码非 0:
|
||||
|
||||
```json
|
||||
{ "ok": false, "identity": "user", "error": { "type": "api", "subtype": "...", "code": 99991679, "message": "...", "hint": "..." } }
|
||||
```
|
||||
|
||||
判断命令是否成功,请检查 `ok == true`(或进程退出码),**不要用 `code == 0`**。与原始 OpenAPI 响应(`{"code": 0, "msg": "ok", ...}`)不同,成功信封没有 `code` 和 `msg` 字段;`code` 只出现在错误信封的 `error` 内,含义是上游 OpenAPI 的 numeric code。完整错误分类见 [errs/ERROR_CONTRACT.md](errs/ERROR_CONTRACT.md)。
|
||||
|
||||
### 分页
|
||||
|
||||
```bash
|
||||
|
||||
@@ -27,9 +27,6 @@ func NewCmdAuthStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobr
|
||||
cmd := &cobra.Command{
|
||||
Use: "status",
|
||||
Short: "View current auth status",
|
||||
Long: `Show OAuth user login, token validity, and granted scopes.
|
||||
For token-validity checks, run lark-cli auth status --json --verify.
|
||||
This is not profile/app selection diagnostics; use lark-cli whoami for the effective app/profile identity used by an invocation.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if runF != nil {
|
||||
return runF(opts)
|
||||
|
||||
@@ -6,7 +6,6 @@ package auth
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
@@ -14,20 +13,6 @@ import (
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
func TestAuthStatusHelpDistinguishesFromWhoami(t *testing.T) {
|
||||
cmd := NewCmdAuthStatus(nil, nil)
|
||||
for _, want := range []string{
|
||||
"OAuth user login",
|
||||
"auth status --json --verify",
|
||||
"not profile/app selection diagnostics",
|
||||
"lark-cli whoami",
|
||||
} {
|
||||
if !strings.Contains(cmd.Long, want) {
|
||||
t.Errorf("auth status --help Long missing %q; got:\n%s", want, cmd.Long)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthStatusRun_SplitsBotAndUserIdentity(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "secret", Brand: core.BrandFeishu,
|
||||
|
||||
@@ -6,10 +6,8 @@ package cmd
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/envvars"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
@@ -28,13 +26,5 @@ func BootstrapInvocationContext(args []string) (cmdutil.InvocationContext, error
|
||||
if err := fs.Parse(args); err != nil && !errors.Is(err, pflag.ErrHelp) {
|
||||
return cmdutil.InvocationContext{}, err
|
||||
}
|
||||
|
||||
profileFromFlag := globals.Profile != ""
|
||||
if !profileFromFlag {
|
||||
globals.Profile = os.Getenv(envvars.CliProfile)
|
||||
}
|
||||
return cmdutil.InvocationContext{
|
||||
Profile: globals.Profile,
|
||||
ProfileFromFlag: profileFromFlag,
|
||||
}, nil
|
||||
return cmdutil.InvocationContext{Profile: globals.Profile}, nil
|
||||
}
|
||||
|
||||
@@ -3,11 +3,7 @@
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/envvars"
|
||||
)
|
||||
import "testing"
|
||||
|
||||
func TestBootstrapInvocationContext_ProfileFlag(t *testing.T) {
|
||||
inv, err := BootstrapInvocationContext([]string{"--profile", "target", "auth", "status"})
|
||||
@@ -74,45 +70,3 @@ func TestBootstrapInvocationContext_HelpWithProfile(t *testing.T) {
|
||||
t.Fatalf("profile = %q, want %q", inv.Profile, "target")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapProfileEnvFallback(t *testing.T) {
|
||||
t.Run("flag wins over env", func(t *testing.T) {
|
||||
t.Setenv(envvars.CliProfile, "tenant_env")
|
||||
inv, err := BootstrapInvocationContext([]string{"--profile", "tenant_flag", "whoami"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if inv.Profile != "tenant_flag" {
|
||||
t.Errorf("got %q, want tenant_flag", inv.Profile)
|
||||
}
|
||||
if !inv.ProfileFromFlag {
|
||||
t.Errorf("ProfileFromFlag = false, want true")
|
||||
}
|
||||
})
|
||||
t.Run("env used when flag absent", func(t *testing.T) {
|
||||
t.Setenv(envvars.CliProfile, "tenant_env")
|
||||
inv, err := BootstrapInvocationContext([]string{"whoami"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if inv.Profile != "tenant_env" {
|
||||
t.Errorf("got %q, want tenant_env", inv.Profile)
|
||||
}
|
||||
if inv.ProfileFromFlag {
|
||||
t.Errorf("ProfileFromFlag = true, want false")
|
||||
}
|
||||
})
|
||||
t.Run("empty when neither set", func(t *testing.T) {
|
||||
t.Setenv(envvars.CliProfile, "")
|
||||
inv, err := BootstrapInvocationContext([]string{"whoami"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if inv.Profile != "" {
|
||||
t.Errorf("got %q, want empty", inv.Profile)
|
||||
}
|
||||
if inv.ProfileFromFlag {
|
||||
t.Errorf("ProfileFromFlag = true, want false")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -84,16 +84,6 @@ func TestConfigShowCmd_FlagParsing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigShowHelpClarifiesSavedConfig(t *testing.T) {
|
||||
cmd := NewCmdConfigShow(nil, nil)
|
||||
if !strings.Contains(cmd.Short, "saved config") {
|
||||
t.Errorf("config show short = %q, want saved config", cmd.Short)
|
||||
}
|
||||
if !strings.Contains(cmd.Long, "lark-cli whoami --json") {
|
||||
t.Errorf("config show help missing whoami route")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigShowRun_NotConfiguredReturnsStructuredError(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
|
||||
|
||||
@@ -27,8 +27,7 @@ func NewCmdConfigShow(f *cmdutil.Factory, runF func(*ConfigShowOptions) error) *
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "show",
|
||||
Short: "Show saved config",
|
||||
Long: "Shows saved config. To see the app/profile lark-cli is using now, run `lark-cli whoami --json`.",
|
||||
Short: "Show current configuration",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if runF != nil {
|
||||
return runF(opts)
|
||||
|
||||
@@ -21,7 +21,7 @@ type profileListItem struct {
|
||||
Name string `json:"name"`
|
||||
AppID string `json:"appId"`
|
||||
Brand core.LarkBrand `json:"brand"`
|
||||
Default bool `json:"default"`
|
||||
Active bool `json:"active"`
|
||||
User string `json:"user,omitempty"`
|
||||
TokenStatus string `json:"tokenStatus,omitempty"`
|
||||
}
|
||||
@@ -30,8 +30,7 @@ type profileListItem struct {
|
||||
func NewCmdProfileList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List saved profiles",
|
||||
Long: "Lists saved profiles. To see the app/profile lark-cli is using now, run `lark-cli whoami --json`.",
|
||||
Short: "List all profiles",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return profileListRun(f)
|
||||
},
|
||||
@@ -54,7 +53,7 @@ func profileListRun(f *cmdutil.Factory) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Intentionally uses "" to show the saved default profile, not the ephemeral --profile override.
|
||||
// Intentionally uses "" to show the persistent active profile, not the ephemeral --profile override.
|
||||
currentApp := multi.CurrentAppConfig("")
|
||||
currentName := ""
|
||||
if currentApp != nil {
|
||||
@@ -67,10 +66,10 @@ func profileListRun(f *cmdutil.Factory) error {
|
||||
name := app.ProfileName()
|
||||
|
||||
item := profileListItem{
|
||||
Name: name,
|
||||
AppID: app.AppId,
|
||||
Brand: app.Brand,
|
||||
Default: name == currentName,
|
||||
Name: name,
|
||||
AppID: app.AppId,
|
||||
Brand: app.Brand,
|
||||
Active: name == currentName,
|
||||
}
|
||||
|
||||
if len(app.Users) > 0 {
|
||||
|
||||
@@ -14,15 +14,6 @@ func NewCmdProfile(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "profile",
|
||||
Short: "Manage configuration profiles",
|
||||
Long: `Profiles are named app identities managed by lark-cli.
|
||||
|
||||
Profile selection:
|
||||
lark-cli whoami --json Show the app/profile lark-cli is using now.
|
||||
lark-cli auth status --json Verify OAuth login and token state.
|
||||
--profile <name> Use a profile for this command only.
|
||||
LARKSUITE_CLI_PROFILE Use a profile for the current shell / agent session.
|
||||
config show / profile list Inspect saved config, not current usage.
|
||||
unset LARKSUITE_CLI_PROFILE Clear the session profile and fall back to direct app env or configured default.`,
|
||||
}
|
||||
cmdutil.DisableAuthCheck(cmd)
|
||||
cmdutil.SetTips(cmd, []string{
|
||||
|
||||
@@ -306,21 +306,14 @@ func TestProfileListRun_OutputsProfiles(t *testing.T) {
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("Unmarshal() error = %v; output=%s", err, stdout.String())
|
||||
}
|
||||
raw := stdout.String()
|
||||
if strings.Contains(raw, `"active"`) {
|
||||
t.Fatalf("profile list output contains legacy active field: %s", raw)
|
||||
}
|
||||
if !strings.Contains(raw, `"default"`) {
|
||||
t.Fatalf("profile list output missing default field: %s", raw)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("len(got) = %d, want 2", len(got))
|
||||
}
|
||||
if got[0].Name != "default" || !got[0].Default {
|
||||
t.Fatalf("got[0] = %#v, want configured default profile", got[0])
|
||||
if got[0].Name != "default" || !got[0].Active {
|
||||
t.Fatalf("got[0] = %#v, want active default profile", got[0])
|
||||
}
|
||||
if got[1].Name != "target" || got[1].Default {
|
||||
t.Fatalf("got[1] = %#v, want non-default target profile", got[1])
|
||||
if got[1].Name != "target" || got[1].Active {
|
||||
t.Fatalf("got[1] = %#v, want inactive target profile", got[1])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -634,35 +627,6 @@ func TestProfileRemoveRun_ValidationErrors(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestProfileHelpHasSelectionSection asserts `profile --help` documents the
|
||||
// per-invocation flag and session-scoped env var for selecting a profile, so
|
||||
// users and AI agents can find LARKSUITE_CLI_PROFILE without reading source.
|
||||
func TestProfileHelpHasSelectionSection(t *testing.T) {
|
||||
cmd := NewCmdProfile(nil)
|
||||
if !strings.Contains(cmd.Long, "Profile selection:") {
|
||||
t.Errorf("profile --help missing Profile selection section")
|
||||
}
|
||||
if !strings.Contains(cmd.Long, "LARKSUITE_CLI_PROFILE") {
|
||||
t.Errorf("profile --help missing LARKSUITE_CLI_PROFILE")
|
||||
}
|
||||
if !strings.Contains(cmd.Long, "lark-cli whoami --json") {
|
||||
t.Errorf("profile --help missing whoami identity route")
|
||||
}
|
||||
if !strings.Contains(cmd.Long, "config show / profile list") {
|
||||
t.Errorf("profile --help missing saved-config boundary")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileListHelpClarifiesSavedProfiles(t *testing.T) {
|
||||
cmd := NewCmdProfileList(nil)
|
||||
if !strings.Contains(cmd.Short, "saved profiles") {
|
||||
t.Errorf("profile list short = %q, want saved profiles", cmd.Short)
|
||||
}
|
||||
if !strings.Contains(cmd.Long, "lark-cli whoami --json") {
|
||||
t.Errorf("profile list help missing whoami route")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileListRun_InvalidConfigReturnsValidationError(t *testing.T) {
|
||||
dir := setupProfileConfigDir(t)
|
||||
if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte("{invalid json"), 0600); err != nil {
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/credential"
|
||||
"github.com/larksuite/cli/internal/identitydiag"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
)
|
||||
@@ -34,15 +33,6 @@ type whoamiResult struct {
|
||||
TokenStatus string `json:"tokenStatus"`
|
||||
OnBehalfOf *delegatedUser `json:"onBehalfOf,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
|
||||
// CredentialSource, Explicit, and DirectCredentialEnv surface the cached
|
||||
// credential.IdentitySelection computed during resolution (not re-inferred
|
||||
// here). CredentialSource can be empty ("") on the non-env
|
||||
// extension-provider path (e.g. sidecar mode), where no selection kind
|
||||
// applies; this is a documented, valid state, not an error.
|
||||
CredentialSource string `json:"credentialSource"`
|
||||
Explicit bool `json:"explicit"`
|
||||
DirectCredentialEnv credential.DirectCredentialEnv `json:"directCredentialEnv"`
|
||||
}
|
||||
|
||||
// delegatedUser is the user a user-identity acts on behalf of.
|
||||
@@ -68,10 +58,6 @@ func NewCmdWhoami(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "whoami",
|
||||
Short: "Show the current effective identity, app, profile, and token status (JSON)",
|
||||
Long: `Show the effective app identity used by this invocation. This is not OAuth login status;
|
||||
use ` + "`lark-cli auth status --json`" + ` for OAuth user/token state.
|
||||
The JSON output includes credentialSource, appId, brand, and whether direct app credential
|
||||
env is present and matches the selected profile.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return whoamiRun(cmd, opts)
|
||||
},
|
||||
@@ -111,17 +97,7 @@ func whoamiRun(cmd *cobra.Command, opts *Options) error {
|
||||
f.ResolveStrictMode(ctx).ForcedIdentity(),
|
||||
)
|
||||
diag := identitydiag.Diagnose(ctx, f, cfg, false)
|
||||
// Read the cached selection computed during resolution; never re-infer it
|
||||
// here. A resolution failure (e.g. under a non-env extension provider that
|
||||
// doesn't populate a selection) degrades to the zero value rather than
|
||||
// regressing whoami's own error/diagnostic path above.
|
||||
var selection credential.IdentitySelection
|
||||
if f.Credential != nil {
|
||||
if sel, err := f.Credential.Selection(ctx); err == nil {
|
||||
selection = sel
|
||||
}
|
||||
}
|
||||
res := buildResult(cfg, as, source, diag, selection)
|
||||
res := buildResult(cfg, as, source, diag)
|
||||
output.PrintJson(f.IOStreams.Out, res)
|
||||
return nil
|
||||
}
|
||||
@@ -146,23 +122,18 @@ func resolveSource(changedAs bool, flagAs core.Identity, autoDetected bool, stri
|
||||
|
||||
// buildResult maps the resolved identity and local diagnostics into the output.
|
||||
// ResolveAs only ever returns user or bot, so the default branch handles user.
|
||||
// selection is the cached credential.IdentitySelection from resolution; it is
|
||||
// read as-is, never recomputed.
|
||||
func buildResult(cfg *core.CliConfig, as core.Identity, source string, diag identitydiag.Result, selection credential.IdentitySelection) *whoamiResult {
|
||||
func buildResult(cfg *core.CliConfig, as core.Identity, source string, diag identitydiag.Result) *whoamiResult {
|
||||
defaultAs := cfg.DefaultAs
|
||||
if defaultAs == "" {
|
||||
defaultAs = core.AsAuto
|
||||
}
|
||||
res := &whoamiResult{
|
||||
Profile: cfg.ProfileName,
|
||||
AppID: cfg.AppID,
|
||||
Brand: cfg.Brand,
|
||||
DefaultAs: string(defaultAs),
|
||||
Identity: string(as),
|
||||
IdentitySource: source,
|
||||
CredentialSource: string(selection.Source),
|
||||
Explicit: selection.Explicit(),
|
||||
DirectCredentialEnv: selection.DirectCredentialEnv,
|
||||
Profile: cfg.ProfileName,
|
||||
AppID: cfg.AppID,
|
||||
Brand: cfg.Brand,
|
||||
DefaultAs: string(defaultAs),
|
||||
Identity: string(as),
|
||||
IdentitySource: source,
|
||||
}
|
||||
// Use the diagnosed hint as-is: it is tailored to the credential source, so
|
||||
// it never says "auth login" when that is blocked under an external provider.
|
||||
|
||||
@@ -15,13 +15,10 @@ import (
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
extcred "github.com/larksuite/cli/extension/credential"
|
||||
envprovider "github.com/larksuite/cli/extension/credential/env"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/credential"
|
||||
"github.com/larksuite/cli/internal/envvars"
|
||||
"github.com/larksuite/cli/internal/identitydiag"
|
||||
"github.com/larksuite/cli/internal/keychain"
|
||||
)
|
||||
|
||||
func TestResolveSource(t *testing.T) {
|
||||
@@ -55,7 +52,7 @@ func TestBuildResult_UserValid(t *testing.T) {
|
||||
diag := identitydiag.Result{
|
||||
User: identitydiag.Identity{Available: true, Status: "ready", TokenStatus: "valid", OpenID: "ou_x", UserName: "Alice"},
|
||||
}
|
||||
r := buildResult(cfg, core.AsUser, "auto_detect", diag, credential.IdentitySelection{})
|
||||
r := buildResult(cfg, core.AsUser, "auto_detect", diag)
|
||||
|
||||
if r.Identity != "user" || r.IdentitySource != "auto_detect" {
|
||||
t.Fatalf("identity/source = %q/%q", r.Identity, r.IdentitySource)
|
||||
@@ -80,7 +77,7 @@ func TestBuildResult_UserMissingToken(t *testing.T) {
|
||||
diag := identitydiag.Result{
|
||||
User: identitydiag.Identity{Available: false, Status: "missing", Hint: "run: lark-cli auth login --help"}, // never logged in
|
||||
}
|
||||
r := buildResult(cfg, core.AsUser, "auto_detect", diag, credential.IdentitySelection{})
|
||||
r := buildResult(cfg, core.AsUser, "auto_detect", diag)
|
||||
|
||||
if r.Available {
|
||||
t.Fatalf("available = true, want false")
|
||||
@@ -103,7 +100,7 @@ func TestBuildResult_BotReady(t *testing.T) {
|
||||
diag := identitydiag.Result{
|
||||
Bot: identitydiag.Identity{Available: true, Status: "ready"},
|
||||
}
|
||||
r := buildResult(cfg, core.AsBot, "default_as", diag, credential.IdentitySelection{})
|
||||
r := buildResult(cfg, core.AsBot, "default_as", diag)
|
||||
|
||||
if r.Identity != "bot" || r.IdentitySource != "default_as" {
|
||||
t.Fatalf("identity/source = %q/%q", r.Identity, r.IdentitySource)
|
||||
@@ -124,7 +121,7 @@ func TestBuildResult_BotNotConfigured(t *testing.T) {
|
||||
diag := identitydiag.Result{
|
||||
Bot: identitydiag.Identity{Available: false, Status: "not_configured", Hint: "run: lark-cli config --help"},
|
||||
}
|
||||
r := buildResult(cfg, core.AsBot, "auto_detect", diag, credential.IdentitySelection{})
|
||||
r := buildResult(cfg, core.AsBot, "auto_detect", diag)
|
||||
|
||||
if r.Available {
|
||||
t.Fatalf("available = true, want false")
|
||||
@@ -321,94 +318,3 @@ func TestWhoami_ExternalProvider_UserHintNotKeychain(t *testing.T) {
|
||||
t.Fatalf("hint should explain external management: %q", got.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// noopWhoamiKeychain is a no-op KeychainAccess; the profile below uses a
|
||||
// plaintext secret, so no keychain lookup is actually required.
|
||||
type noopWhoamiKeychain struct{}
|
||||
|
||||
func (noopWhoamiKeychain) Get(service, account string) (string, error) { return "", nil }
|
||||
func (noopWhoamiKeychain) Set(service, account, value string) error { return nil }
|
||||
func (noopWhoamiKeychain) Remove(service, account string) error { return nil }
|
||||
|
||||
// credentialSourceSecret is the profile secret written to config for
|
||||
// TestWhoamiIncludesCredentialSource. It must never leak into whoami's output
|
||||
// (security §5.1).
|
||||
const credentialSourceSecret = "test-secret"
|
||||
|
||||
// profileSelectionFactory builds a Factory whose CredentialProvider resolves
|
||||
// an explicit profile ("tenant_a") supplied via the LARKSUITE_CLI_PROFILE env
|
||||
// fallback (not --profile), so Selection().Source resolves to
|
||||
// env:LARKSUITE_CLI_PROFILE and Explicit() is true, with no direct
|
||||
// app-credential env vars present.
|
||||
func profileSelectionFactory(t *testing.T) (*cmdutil.Factory, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
|
||||
multi := &core.MultiAppConfig{
|
||||
CurrentApp: "tenant_a",
|
||||
Apps: []core.AppConfig{{
|
||||
Name: "tenant_a",
|
||||
AppId: "cli_a",
|
||||
AppSecret: core.PlainSecret(credentialSourceSecret),
|
||||
Brand: core.BrandFeishu,
|
||||
}},
|
||||
}
|
||||
if err := core.SaveMultiAppConfig(multi); err != nil {
|
||||
t.Fatalf("SaveMultiAppConfig: %v", err)
|
||||
}
|
||||
|
||||
defaultAcct := credential.NewDefaultAccountProvider(func() keychain.KeychainAccess { return noopWhoamiKeychain{} }, "tenant_a")
|
||||
cred := credential.NewCredentialProvider([]extcred.Provider{&envprovider.Provider{}}, defaultAcct, nil, nil)
|
||||
cred.WithProfile("tenant_a", false) // fromFlag=false -> env:LARKSUITE_CLI_PROFILE
|
||||
|
||||
cfg := &core.CliConfig{ProfileName: "tenant_a", AppID: "cli_a", AppSecret: credentialSourceSecret, Brand: core.BrandFeishu}
|
||||
out := &bytes.Buffer{}
|
||||
f := &cmdutil.Factory{
|
||||
Config: func() (*core.CliConfig, error) { return cfg, nil },
|
||||
Credential: cred,
|
||||
IOStreams: &cmdutil.IOStreams{Out: out, ErrOut: &bytes.Buffer{}},
|
||||
}
|
||||
return f, out
|
||||
}
|
||||
|
||||
// TestWhoamiIncludesCredentialSource locks in the diagnostic fields surfaced
|
||||
// from the cached credential.IdentitySelection (Task 6): credentialSource,
|
||||
// explicit, and directCredentialEnv. whoami must read the cached selection
|
||||
// as-is, not re-infer it.
|
||||
func TestWhoamiIncludesCredentialSource(t *testing.T) {
|
||||
f, out := profileSelectionFactory(t)
|
||||
|
||||
cmd := NewCmdWhoami(f)
|
||||
cmd.SetArgs([]string{})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
|
||||
raw := out.String()
|
||||
if strings.Contains(raw, credentialSourceSecret) {
|
||||
t.Fatalf("whoami output leaked the profile secret: %s", raw)
|
||||
}
|
||||
|
||||
var got whoamiResult
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json.Unmarshal() error = %v\n%s", err, raw)
|
||||
}
|
||||
if got.CredentialSource != string(credential.SourceEnvProfile) {
|
||||
t.Fatalf("credentialSource = %q, want %q", got.CredentialSource, credential.SourceEnvProfile)
|
||||
}
|
||||
if !got.Explicit {
|
||||
t.Fatalf("explicit = false, want true")
|
||||
}
|
||||
if got.DirectCredentialEnv.Present {
|
||||
t.Fatalf("directCredentialEnv.present = true, want false: %#v", got.DirectCredentialEnv)
|
||||
}
|
||||
if !strings.Contains(raw, `"credentialSource": "env:LARKSUITE_CLI_PROFILE"`) {
|
||||
t.Fatalf("raw JSON missing credentialSource literal: %s", raw)
|
||||
}
|
||||
if got.DirectCredentialEnv.Present || len(got.DirectCredentialEnv.Keys) != 0 ||
|
||||
got.DirectCredentialEnv.AppID != "" || got.DirectCredentialEnv.Matched || got.DirectCredentialEnv.ConflictsWithProfile {
|
||||
t.Fatalf("directCredentialEnv = %#v, want only present:false set", got.DirectCredentialEnv)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,28 @@ other category. `error.type` is `"policy"`, `error.subtype` is one of
|
||||
`challenge_required` / `access_denied`, and process exit is `6` via
|
||||
`CategoryPolicy`.
|
||||
|
||||
### Success envelope (stdout)
|
||||
|
||||
For contrast: success responses render to **stdout** as an
|
||||
`output.Envelope` (`internal/output/envelope.go`), exit code `0`:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"identity": "user",
|
||||
"data": { "guid": "e297d3d0-..." },
|
||||
"meta": { "count": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
Consumers must branch on `ok` (or the process exit code). The success
|
||||
envelope has **no top-level `code` or `msg` field** — `code` exists only
|
||||
inside `error`, where it is the upstream numeric code (invariant 4).
|
||||
Wrappers that follow the raw OpenAPI convention and test `code == 0`
|
||||
will misclassify every successful call as a failure, which is
|
||||
especially dangerous around write commands (e.g. retrying a create that
|
||||
already succeeded).
|
||||
|
||||
## Categories
|
||||
|
||||
| Category | When | Exit | Typed struct |
|
||||
|
||||
@@ -136,77 +136,6 @@ func TestConfigError_MarshalJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigError_ProfileFieldsMarshalJSON(t *testing.T) {
|
||||
ce := NewConfigError(SubtypeAppCredentialIncomplete, "incomplete").
|
||||
WithMissingKeys("LARKSUITE_CLI_APP_ID", "LARKSUITE_CLI_APP_SECRET").
|
||||
WithProfile("work").
|
||||
WithAppID("cli_abc").
|
||||
WithCredentialSource("flag:--profile")
|
||||
b, err := json.Marshal(ce)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := string(b)
|
||||
for _, want := range []string{
|
||||
`"type":"config"`,
|
||||
`"subtype":"app_credential_incomplete"`,
|
||||
`"missing_keys":["LARKSUITE_CLI_APP_ID","LARKSUITE_CLI_APP_SECRET"]`,
|
||||
`"profile":"work"`,
|
||||
`"app_id":"cli_abc"`,
|
||||
`"credential_source":"flag:--profile"`,
|
||||
} {
|
||||
if !strings.Contains(s, want) {
|
||||
t.Errorf("missing %q in %s", want, s)
|
||||
}
|
||||
}
|
||||
|
||||
// omitempty: unset fields must not appear on the wire.
|
||||
empty := NewConfigError(SubtypeProfileNotFound, "x")
|
||||
b2, err := json.Marshal(empty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2 := string(b2)
|
||||
for _, notWant := range []string{`"missing_keys"`, `"profile"`, `"app_id"`, `"credential_source"`} {
|
||||
if strings.Contains(s2, notWant) {
|
||||
t.Errorf("%q should be omitted when empty; got %s", notWant, s2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationError_ProfileConflictMarshalJSON(t *testing.T) {
|
||||
ve := NewValidationError(SubtypeProfileAppCredentialConflict, "conflict").
|
||||
WithProfileAppConflict("cli_profile", "cli_env")
|
||||
b, err := json.Marshal(ve)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := string(b)
|
||||
for _, want := range []string{
|
||||
`"type":"validation"`,
|
||||
`"subtype":"profile_app_credential_conflict"`,
|
||||
`"profile_app_id":"cli_profile"`,
|
||||
`"env_app_id":"cli_env"`,
|
||||
} {
|
||||
if !strings.Contains(s, want) {
|
||||
t.Errorf("missing %q in %s", want, s)
|
||||
}
|
||||
}
|
||||
|
||||
// omitempty: unset conflict fields must not appear on the wire.
|
||||
empty := NewValidationError(SubtypeInvalidArgument, "x")
|
||||
b2, err := json.Marshal(empty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2 := string(b2)
|
||||
for _, notWant := range []string{`"profile_app_id"`, `"env_app_id"`} {
|
||||
if strings.Contains(s2, notWant) {
|
||||
t.Errorf("%q should be omitted when empty; got %s", notWant, s2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkError_MarshalJSON(t *testing.T) {
|
||||
ne := &NetworkError{
|
||||
Problem: Problem{Category: CategoryNetwork, Subtype: SubtypeNetworkTimeout, Message: "dial timeout"},
|
||||
|
||||
@@ -12,9 +12,8 @@ const (
|
||||
|
||||
// CategoryValidation subtypes
|
||||
const (
|
||||
SubtypeInvalidArgument Subtype = "invalid_argument" // user-supplied flag / arg failed validation (gRPC INVALID_ARGUMENT alignment)
|
||||
SubtypeFailedPrecondition Subtype = "failed_precondition" // request is valid but the system/resource state is not in the state required to execute; caller must change state (not retry) — e.g. ambiguous remote mapping (gRPC FAILED_PRECONDITION alignment)
|
||||
SubtypeProfileAppCredentialConflict Subtype = "profile_app_credential_conflict" // profile and direct app env both set but app_id differs
|
||||
SubtypeInvalidArgument Subtype = "invalid_argument" // user-supplied flag / arg failed validation (gRPC INVALID_ARGUMENT alignment)
|
||||
SubtypeFailedPrecondition Subtype = "failed_precondition" // request is valid but the system/resource state is not in the state required to execute; caller must change state (not retry) — e.g. ambiguous remote mapping (gRPC FAILED_PRECONDITION alignment)
|
||||
)
|
||||
|
||||
// CategoryAuthentication subtypes
|
||||
@@ -42,13 +41,9 @@ const (
|
||||
|
||||
// CategoryConfig subtypes
|
||||
const (
|
||||
SubtypeInvalidClient Subtype = "invalid_client" // app_id / app_secret incorrect (RFC 6749 §5.2 alignment)
|
||||
SubtypeNotConfigured Subtype = "not_configured" // local config file absent (user has not run `config init`)
|
||||
SubtypeInvalidConfig Subtype = "invalid_config" // local config file present but malformed
|
||||
SubtypeProfileNotFound Subtype = "profile_not_found" // --profile / LARKSUITE_CLI_PROFILE points to a nonexistent profile
|
||||
SubtypeNoActiveProfile Subtype = "no_active_profile" // no active identity input and no usable default profile
|
||||
SubtypeAppCredentialIncomplete Subtype = "app_credential_incomplete" // direct app env missing app_id or app_secret
|
||||
SubtypeProfileSecretInvalid Subtype = "profile_secret_invalid" // profile exists but its secret cannot be resolved locally
|
||||
SubtypeInvalidClient Subtype = "invalid_client" // app_id / app_secret incorrect (RFC 6749 §5.2 alignment)
|
||||
SubtypeNotConfigured Subtype = "not_configured" // local config file absent (user has not run `config init`)
|
||||
SubtypeInvalidConfig Subtype = "invalid_config" // local config file present but malformed
|
||||
)
|
||||
|
||||
// CategoryNetwork subtypes
|
||||
|
||||
@@ -61,11 +61,9 @@ type TypedError interface {
|
||||
// it is intentionally not serialized.
|
||||
type ValidationError struct {
|
||||
Problem
|
||||
Param string `json:"param,omitempty"`
|
||||
Params []InvalidParam `json:"params,omitempty"`
|
||||
ProfileAppID string `json:"profile_app_id,omitempty"`
|
||||
EnvAppID string `json:"env_app_id,omitempty"`
|
||||
Cause error `json:"-"`
|
||||
Param string `json:"param,omitempty"`
|
||||
Params []InvalidParam `json:"params,omitempty"`
|
||||
Cause error `json:"-"`
|
||||
}
|
||||
|
||||
// InvalidParam is one structured validation diagnostic: the parameter that
|
||||
@@ -152,12 +150,6 @@ func (e *ValidationError) WithCause(cause error) *ValidationError {
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *ValidationError) WithProfileAppConflict(profileAppID, envAppID string) *ValidationError {
|
||||
e.ProfileAppID = profileAppID
|
||||
e.EnvAppID = envAppID
|
||||
return e
|
||||
}
|
||||
|
||||
// =========================== AuthenticationError =============================
|
||||
|
||||
// AuthenticationError is the typed error for CategoryAuthentication.
|
||||
@@ -323,17 +315,8 @@ func (e *PermissionError) WithCause(cause error) *PermissionError {
|
||||
// intentionally not serialized.
|
||||
type ConfigError struct {
|
||||
Problem
|
||||
Field string `json:"field,omitempty"`
|
||||
MissingKeys []string `json:"missing_keys,omitempty"`
|
||||
Profile string `json:"profile,omitempty"`
|
||||
AppID string `json:"app_id,omitempty"`
|
||||
// CredentialSource is the machine-readable App/credential selection source
|
||||
// that produced this config error (e.g. "flag:--profile",
|
||||
// "env:LARKSUITE_CLI_PROFILE", "config"). It is required on
|
||||
// profile_not_found and no_active_profile (spec §5) so an agent can branch
|
||||
// on how the identity was (or was not) chosen. It is never a secret.
|
||||
CredentialSource string `json:"credential_source,omitempty"`
|
||||
Cause error `json:"-"`
|
||||
Field string `json:"field,omitempty"`
|
||||
Cause error `json:"-"`
|
||||
}
|
||||
|
||||
// Unwrap is nil-receiver safe; see ValidationError.Unwrap.
|
||||
@@ -387,29 +370,6 @@ func (e *ConfigError) WithField(field string) *ConfigError {
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *ConfigError) WithMissingKeys(keys ...string) *ConfigError {
|
||||
e.MissingKeys = slices.Clone(keys)
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *ConfigError) WithProfile(name string) *ConfigError {
|
||||
e.Profile = name
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *ConfigError) WithAppID(appID string) *ConfigError {
|
||||
e.AppID = appID
|
||||
return e
|
||||
}
|
||||
|
||||
// WithCredentialSource records the machine-readable credential-selection source
|
||||
// on the wire (snake_case credential_source). The value is an enum string
|
||||
// (e.g. "flag:--profile", "config"), never a secret.
|
||||
func (e *ConfigError) WithCredentialSource(source string) *ConfigError {
|
||||
e.CredentialSource = source
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *ConfigError) WithCause(cause error) *ConfigError {
|
||||
e.Cause = cause
|
||||
return e
|
||||
|
||||
@@ -643,29 +643,3 @@ func TestBuilderSetter_DefensiveCopy(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ======================= Profile selection error subtypes =======================
|
||||
|
||||
func TestConfigErrorProfileFields(t *testing.T) {
|
||||
e := errs.NewConfigError(errs.SubtypeAppCredentialIncomplete, "incomplete").
|
||||
WithMissingKeys("LARKSUITE_CLI_APP_ID").
|
||||
WithCredentialSource("env:LARKSUITE_CLI_PROFILE")
|
||||
p, ok := errs.ProblemOf(e)
|
||||
if !ok || p.Subtype != errs.SubtypeAppCredentialIncomplete {
|
||||
t.Fatalf("subtype mismatch: %+v", p)
|
||||
}
|
||||
if len(e.MissingKeys) != 1 || e.MissingKeys[0] != "LARKSUITE_CLI_APP_ID" {
|
||||
t.Errorf("missing_keys not set: %v", e.MissingKeys)
|
||||
}
|
||||
if e.CredentialSource != "env:LARKSUITE_CLI_PROFILE" {
|
||||
t.Errorf("credential_source not set: %q", e.CredentialSource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationErrorProfileConflict(t *testing.T) {
|
||||
e := errs.NewValidationError(errs.SubtypeProfileAppCredentialConflict, "conflict").
|
||||
WithProfileAppConflict("cli_profile", "cli_env")
|
||||
if e.ProfileAppID != "cli_profile" || e.EnvAppID != "cli_env" {
|
||||
t.Errorf("conflict fields not set: %q %q", e.ProfileAppID, e.EnvAppID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,11 +27,6 @@ import (
|
||||
// In tests, replace any field to stub out external dependencies.
|
||||
type InvocationContext struct {
|
||||
Profile string
|
||||
// ProfileFromFlag is true when Profile was set via the --profile flag,
|
||||
// and false when it came from the LARKSUITE_CLI_PROFILE env fallback
|
||||
// (or neither was set). Downstream credential resolution uses this to
|
||||
// report the correct profile source.
|
||||
ProfileFromFlag bool
|
||||
}
|
||||
|
||||
type Factory struct {
|
||||
|
||||
@@ -61,11 +61,10 @@ func NewDefault(streams *IOStreams, inv InvocationContext) *Factory {
|
||||
// Phase 2: Credential (sole data source)
|
||||
// Keychain is read via closure so callers can replace f.Keychain after construction.
|
||||
f.Credential = buildCredentialProvider(credentialDeps{
|
||||
Keychain: func() keychain.KeychainAccess { return f.Keychain },
|
||||
Profile: inv.Profile,
|
||||
ProfileFromFlag: inv.ProfileFromFlag,
|
||||
HttpClient: f.HttpClient,
|
||||
ErrOut: f.IOStreams.ErrOut,
|
||||
Keychain: func() keychain.KeychainAccess { return f.Keychain },
|
||||
Profile: inv.Profile,
|
||||
HttpClient: f.HttpClient,
|
||||
ErrOut: f.IOStreams.ErrOut,
|
||||
})
|
||||
|
||||
// Phase 3: Config derived from Credential via an explicit conversion boundary.
|
||||
@@ -163,11 +162,10 @@ func buildSDKTransport() http.RoundTripper {
|
||||
}
|
||||
|
||||
type credentialDeps struct {
|
||||
Keychain func() keychain.KeychainAccess
|
||||
Profile string
|
||||
ProfileFromFlag bool
|
||||
HttpClient func() (*http.Client, error)
|
||||
ErrOut io.Writer
|
||||
Keychain func() keychain.KeychainAccess
|
||||
Profile string
|
||||
HttpClient func() (*http.Client, error)
|
||||
ErrOut io.Writer
|
||||
}
|
||||
|
||||
func buildCredentialProvider(deps credentialDeps) *credential.CredentialProvider {
|
||||
@@ -180,6 +178,5 @@ func buildCredentialProvider(deps credentialDeps) *credential.CredentialProvider
|
||||
// depend on. enrichUserInfo failures are already non-fatal (the
|
||||
// provider clears unverified identity fields), so silencing the
|
||||
// warning is safe.
|
||||
return credential.NewCredentialProvider(providers, defaultAcct, defaultToken, deps.HttpClient).
|
||||
WithProfile(deps.Profile, deps.ProfileFromFlag)
|
||||
return credential.NewCredentialProvider(providers, defaultAcct, defaultToken, deps.HttpClient)
|
||||
}
|
||||
|
||||
@@ -9,21 +9,13 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
extcred "github.com/larksuite/cli/extension/credential"
|
||||
"github.com/larksuite/cli/internal/auth"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/envvars"
|
||||
)
|
||||
|
||||
// directCredentialProviderName is the Name() of the env provider, the source
|
||||
// of direct app credentials (LARKSUITE_CLI_APP_ID / _APP_SECRET). Only its
|
||||
// incomplete blocks map to app_credential_incomplete (spec §3 step 1).
|
||||
const directCredentialProviderName = "env"
|
||||
|
||||
// DefaultAccountResolver is implemented by the default account provider.
|
||||
type DefaultAccountResolver interface {
|
||||
ResolveAccount(ctx context.Context) (*Account, error)
|
||||
@@ -144,18 +136,10 @@ type CredentialProvider struct {
|
||||
httpClient func() (*http.Client, error)
|
||||
warnOut io.Writer
|
||||
|
||||
// profile is the active profile (from --profile or LARKSUITE_CLI_PROFILE).
|
||||
// profileFromFlag discriminates the source for the reported selection.
|
||||
profile string
|
||||
profileFromFlag bool
|
||||
|
||||
accountOnce sync.Once
|
||||
account *Account
|
||||
accountErr error
|
||||
selectedSource credentialSource
|
||||
// selection is the explainable credential-selection result, populated by
|
||||
// doResolveAccount under accountOnce. It never carries a secret (§5.1).
|
||||
selection IdentitySelection
|
||||
|
||||
hintOnce sync.Once
|
||||
hint *IdentityHint
|
||||
@@ -177,15 +161,6 @@ func (p *CredentialProvider) SetWarnOut(warnOut io.Writer) *CredentialProvider {
|
||||
return p
|
||||
}
|
||||
|
||||
// WithProfile records the active profile and whether it came from the
|
||||
// --profile flag (as opposed to the LARKSUITE_CLI_PROFILE env fallback).
|
||||
// It governs credential arbitration and the reported selection source.
|
||||
func (p *CredentialProvider) WithProfile(profile string, fromFlag bool) *CredentialProvider {
|
||||
p.profile = profile
|
||||
p.profileFromFlag = fromFlag
|
||||
return p
|
||||
}
|
||||
|
||||
// ResolveAccount resolves app credentials. Result is cached after first call.
|
||||
// NOTE: Uses sync.Once — only the context from the first call is used for resolution.
|
||||
// Subsequent calls return the cached result regardless of their context.
|
||||
@@ -197,273 +172,40 @@ func (p *CredentialProvider) ResolveAccount(ctx context.Context) (*Account, erro
|
||||
return p.account, p.accountErr
|
||||
}
|
||||
|
||||
// doResolveAccount arbitrates the credential/App selection per the spec
|
||||
// resolution order (§3): env-partial → profile → env-complete → config default.
|
||||
// It populates p.selection (no secret; §5.1) and p.selectedSource on every
|
||||
// success path.
|
||||
func (p *CredentialProvider) doResolveAccount(ctx context.Context) (*Account, error) {
|
||||
// Step 1 (spec §3): consult the extension providers. The env provider is
|
||||
// the "direct app credential" source. An incomplete direct credential
|
||||
// (only APP_ID or only APP_SECRET set) short-circuits to
|
||||
// app_credential_incomplete regardless of the active profile.
|
||||
var envAcct *Account
|
||||
var envSource extensionTokenSource
|
||||
for _, prov := range p.providers {
|
||||
acct, err := prov.ResolveAccount(ctx)
|
||||
if err != nil {
|
||||
var blockErr *extcred.BlockError
|
||||
// Only the env (direct-credential) provider maps an incomplete
|
||||
// block to app_credential_incomplete. Other providers' blocks
|
||||
// propagate unchanged so they still stop the chain (§3 step 1
|
||||
// is specifically about direct app credential env vars).
|
||||
if errors.As(err, &blockErr) && prov.Name() == directCredentialProviderName {
|
||||
if missing := missingDirectCredentialKeys(); len(missing) > 0 {
|
||||
return nil, errs.NewConfigError(errs.SubtypeAppCredentialIncomplete,
|
||||
"direct app credential is incomplete").
|
||||
WithMissingKeys(missing...).
|
||||
WithHint("set both %s and %s, or unset both and use --profile / a config default.",
|
||||
envvars.CliAppID, envvars.CliAppSecret)
|
||||
}
|
||||
// Block for a reason other than incompleteness (e.g. an
|
||||
// invalid identity/strict-mode value); preserve prior behavior.
|
||||
return nil, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if acct != nil {
|
||||
// Only the env (direct-credential) provider feeds profile
|
||||
// arbitration / conflict detection / DirectCredentialEnv reporting.
|
||||
// This mirrors the block-path guard above. A non-env extension
|
||||
// provider (e.g. sidecar) is NOT a direct-credential env account:
|
||||
// it wins outright here, returning its account + token source
|
||||
// unchanged (pre-diff behavior), without being misreported as a
|
||||
// direct env credential (§4.2: Present = direct env vars actually
|
||||
// set) or triggering a spurious profile_app_credential_conflict.
|
||||
if prov.Name() != directCredentialProviderName {
|
||||
internal := convertAccount(acct)
|
||||
source := extensionTokenSource{provider: prov}
|
||||
if err := p.enrichUserInfo(ctx, internal, source); err != nil {
|
||||
if p.warnOut != nil {
|
||||
_, _ = fmt.Fprintf(p.warnOut, "warning: unable to verify user identity from credential source %q: %v\n", source.Name(), err)
|
||||
}
|
||||
// enrichUserInfo failure is non-fatal: SupportedIdentities
|
||||
// (used for strict mode) is already set by the provider.
|
||||
// Clear unverified user identity for safety.
|
||||
internal.UserOpenId = ""
|
||||
internal.UserName = ""
|
||||
internal := convertAccount(acct)
|
||||
source := extensionTokenSource{provider: prov}
|
||||
if err := p.enrichUserInfo(ctx, internal, source); err != nil {
|
||||
if p.warnOut != nil {
|
||||
_, _ = fmt.Fprintf(p.warnOut, "warning: unable to verify user identity from credential source %q: %v\n", source.Name(), err)
|
||||
}
|
||||
p.selectedSource = source
|
||||
return internal, nil
|
||||
// enrichUserInfo failure is non-fatal: SupportedIdentities
|
||||
// (used for strict mode) is already set by the provider.
|
||||
// Clear unverified user identity for safety.
|
||||
internal.UserOpenId = ""
|
||||
internal.UserName = ""
|
||||
}
|
||||
envAcct = convertAccount(acct)
|
||||
envSource = extensionTokenSource{provider: prov}
|
||||
break
|
||||
p.selectedSource = source
|
||||
return internal, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2 (spec §3): an explicit profile was requested.
|
||||
if p.profile != "" {
|
||||
multi, loadErr := core.LoadMultiAppConfig()
|
||||
if errors.Is(loadErr, core.ErrMalformedConfig) {
|
||||
// A malformed config must not be masked as profile_not_found (which
|
||||
// would tell the user to run `profile list` and hide a real config
|
||||
// problem). Pass the underlying error through unchanged so
|
||||
// errors.Is / errors.Unwrap keep working. An absent config is not
|
||||
// malformed and still falls through to the friendly
|
||||
// profile_not_found below, since the requested profile cannot exist.
|
||||
return nil, loadErr
|
||||
}
|
||||
var app *core.AppConfig
|
||||
if loadErr == nil && multi != nil {
|
||||
app = multi.FindApp(p.profile)
|
||||
}
|
||||
if app == nil {
|
||||
return nil, errs.NewConfigError(errs.SubtypeProfileNotFound,
|
||||
"profile %q not found", p.profile).
|
||||
WithProfile(p.profile).
|
||||
WithCredentialSource(string(p.profileSource())).
|
||||
WithHint("run `lark-cli profile list` to see available profiles.")
|
||||
}
|
||||
if envAcct != nil {
|
||||
// E == complete: the direct env app_id must match the profile.
|
||||
if app.AppId != envAcct.AppID {
|
||||
return nil, errs.NewValidationError(errs.SubtypeProfileAppCredentialConflict,
|
||||
"profile %q app_id does not match %s", p.profile, envvars.CliAppID).
|
||||
WithProfileAppConflict(app.AppId, envAcct.AppID).
|
||||
WithHint("unset %s/%s, or select a profile whose app_id matches the environment.",
|
||||
envvars.CliAppID, envvars.CliAppSecret)
|
||||
}
|
||||
p.selection = IdentitySelection{
|
||||
Source: p.profileSource(),
|
||||
DirectCredentialEnv: DirectCredentialEnv{
|
||||
Present: true,
|
||||
Keys: presentDirectCredentialKeys(),
|
||||
AppID: envAcct.AppID,
|
||||
Matched: true,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
p.selection = IdentitySelection{
|
||||
Source: p.profileSource(),
|
||||
DirectCredentialEnv: DirectCredentialEnv{Present: false},
|
||||
}
|
||||
}
|
||||
// Resolve the profile's own (keychain-backed) credential locally.
|
||||
acct, err := p.defaultAcct.ResolveAccount(ctx)
|
||||
if err != nil {
|
||||
// SECURITY (§5.1): generic message — never embed the underlying
|
||||
// error or any secret material.
|
||||
p.selection = IdentitySelection{}
|
||||
return nil, errs.NewConfigError(errs.SubtypeProfileSecretInvalid,
|
||||
"profile %q credential could not be resolved locally", p.profile).
|
||||
WithProfile(p.profile).
|
||||
WithAppID(app.AppId).
|
||||
WithHint("verify the profile's app secret or re-add the profile with `lark-cli config`.")
|
||||
}
|
||||
p.selectedSource = defaultTokenSource{resolver: p.defaultToken}
|
||||
return acct, nil
|
||||
}
|
||||
|
||||
// Step 3 (spec §3): no explicit profile — direct env credential wins.
|
||||
if envAcct != nil {
|
||||
if err := p.enrichUserInfo(ctx, envAcct, envSource); err != nil {
|
||||
if p.warnOut != nil {
|
||||
_, _ = fmt.Fprintf(p.warnOut, "warning: unable to verify user identity from credential source %q: %v\n", envSource.Name(), err)
|
||||
}
|
||||
// enrichUserInfo failure is non-fatal: SupportedIdentities
|
||||
// (used for strict mode) is already set by the provider.
|
||||
// Clear unverified user identity for safety.
|
||||
envAcct.UserOpenId = ""
|
||||
envAcct.UserName = ""
|
||||
}
|
||||
p.selectedSource = envSource
|
||||
p.selection = IdentitySelection{
|
||||
Source: SourceEnvAppID,
|
||||
DirectCredentialEnv: DirectCredentialEnv{
|
||||
Present: true,
|
||||
Keys: presentDirectCredentialKeys(),
|
||||
AppID: envAcct.AppID,
|
||||
},
|
||||
}
|
||||
return envAcct, nil
|
||||
}
|
||||
|
||||
// No direct env credential and no profile → the config default.
|
||||
if p.defaultAcct != nil {
|
||||
acct, err := p.defaultAcct.ResolveAccount(ctx)
|
||||
if err != nil {
|
||||
// The config default failed to resolve. Distinguish (spec §3 step
|
||||
// 3.2): a default profile that EXISTS (has an app_id) but whose
|
||||
// secret cannot be resolved locally is a profile_secret_invalid —
|
||||
// "identity is configured, its secret is broken" is more actionable
|
||||
// than "no active profile". Only when there is genuinely no usable
|
||||
// default profile do we report no_active_profile. Other typed
|
||||
// failures (e.g. a specific config error) pass through unchanged.
|
||||
if prob, ok := errs.ProblemOf(err); ok && prob.Subtype == errs.SubtypeNotConfigured {
|
||||
if name, appID, ok := defaultProfileIdentity(); ok {
|
||||
// SECURITY (§5.1): generic message — never embed the
|
||||
// underlying error or any secret material. app_id is
|
||||
// plaintext and safe to echo.
|
||||
return nil, errs.NewConfigError(errs.SubtypeProfileSecretInvalid,
|
||||
"profile %q credential could not be resolved locally", name).
|
||||
WithProfile(name).
|
||||
WithAppID(appID).
|
||||
WithHint("verify the profile's app secret or re-add the profile with `lark-cli config`.")
|
||||
}
|
||||
return nil, errs.NewConfigError(errs.SubtypeNoActiveProfile, "no active profile").
|
||||
WithCredentialSource(noActiveProfileCredentialSource).
|
||||
WithHint("run `lark-cli config init` / `lark-cli profile add`, or set %s.", envvars.CliProfile)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
multi, _ := core.LoadMultiAppConfig()
|
||||
p.selectedSource = defaultTokenSource{resolver: p.defaultToken}
|
||||
p.selection = IdentitySelection{Source: selectionSourceForDefault(multi)}
|
||||
return acct, nil
|
||||
}
|
||||
return nil, core.NotConfiguredError()
|
||||
}
|
||||
|
||||
// profileSource reports the credential source kind for a profile-backed
|
||||
// selection, discriminating the --profile flag from the env fallback.
|
||||
func (p *CredentialProvider) profileSource() CredentialSourceKind {
|
||||
if p.profileFromFlag {
|
||||
return SourceFlagProfile
|
||||
}
|
||||
return SourceEnvProfile
|
||||
}
|
||||
|
||||
// noActiveProfileCredentialSource is the credential_source reported on the
|
||||
// no_active_profile error. Spec §5 fixes this to the literal "config": there is
|
||||
// no resolved default profile at all, so the more specific config:currentApp /
|
||||
// config:firstApp source values (used on successful config-default selections)
|
||||
// would be misleading. It is an enum string, never a secret.
|
||||
const noActiveProfileCredentialSource = "config"
|
||||
|
||||
// defaultProfileIdentity reports the config default profile's display name and
|
||||
// app_id when a usable default profile actually EXISTS (currentApp > firstApp
|
||||
// resolves to an app with a non-empty app_id). It never touches the keychain or
|
||||
// any secret, so it can distinguish "default profile exists but its secret is
|
||||
// broken" (→ profile_secret_invalid) from "no usable default profile at all"
|
||||
// (→ no_active_profile), without risking a secret leak (§5.1).
|
||||
func defaultProfileIdentity() (name, appID string, ok bool) {
|
||||
multi, err := core.LoadMultiAppConfig()
|
||||
if err != nil || multi == nil {
|
||||
return "", "", false
|
||||
}
|
||||
app := multi.CurrentAppConfig("")
|
||||
if app == nil || app.AppId == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return app.ProfileName(), app.AppId, true
|
||||
}
|
||||
|
||||
// selectionSourceForDefault reports whether the config default resolved to the
|
||||
// explicit currentApp or fell back to the first app (spec §3 step 3.2).
|
||||
func selectionSourceForDefault(multi *core.MultiAppConfig) CredentialSourceKind {
|
||||
if multi != nil && multi.CurrentApp != "" {
|
||||
return SourceConfigCurrentApp
|
||||
}
|
||||
return SourceConfigFirstApp
|
||||
}
|
||||
|
||||
// missingDirectCredentialKeys returns the NAMES (never values) of the direct
|
||||
// app credential env vars that are absent. Used only when the env provider
|
||||
// blocks, to map an incomplete direct credential to app_credential_incomplete.
|
||||
func missingDirectCredentialKeys() []string {
|
||||
var missing []string
|
||||
if os.Getenv(envvars.CliAppID) == "" {
|
||||
missing = append(missing, envvars.CliAppID)
|
||||
}
|
||||
if os.Getenv(envvars.CliAppSecret) == "" {
|
||||
missing = append(missing, envvars.CliAppSecret)
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
||||
// presentDirectCredentialKeys returns the NAMES (never values) of the direct
|
||||
// app credential env vars that are set. Used to annotate DirectCredentialEnv.
|
||||
func presentDirectCredentialKeys() []string {
|
||||
var keys []string
|
||||
if os.Getenv(envvars.CliAppID) != "" {
|
||||
keys = append(keys, envvars.CliAppID)
|
||||
}
|
||||
if os.Getenv(envvars.CliAppSecret) != "" {
|
||||
keys = append(keys, envvars.CliAppSecret)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// Selection resolves the account (once) and returns the cached, secret-free
|
||||
// explanation of how the credential/App was selected. It mirrors
|
||||
// selectedCredentialSource: resolve-then-return.
|
||||
func (p *CredentialProvider) Selection(ctx context.Context) (IdentitySelection, error) {
|
||||
if _, err := p.ResolveAccount(ctx); err != nil {
|
||||
return IdentitySelection{}, err
|
||||
}
|
||||
return p.selection, nil
|
||||
}
|
||||
|
||||
// enrichUserInfo resolves user identity when extension provides a UAT.
|
||||
// If UAT is available, user_info API call is mandatory (security: verify token validity).
|
||||
// If no UAT from extension, falls back to provider-supplied OpenID.
|
||||
|
||||
@@ -1,554 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
extcred "github.com/larksuite/cli/extension/credential"
|
||||
envprovider "github.com/larksuite/cli/extension/credential/env"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/credential"
|
||||
"github.com/larksuite/cli/internal/envvars"
|
||||
"github.com/larksuite/cli/internal/keychain"
|
||||
)
|
||||
|
||||
func asConfigError(t *testing.T, err error) *errs.ConfigError {
|
||||
t.Helper()
|
||||
var ce *errs.ConfigError
|
||||
if !errors.As(err, &ce) {
|
||||
t.Fatalf("expected *errs.ConfigError, got %T: %v", err, err)
|
||||
}
|
||||
return ce
|
||||
}
|
||||
|
||||
func asValidationError(t *testing.T, err error) *errs.ValidationError {
|
||||
t.Helper()
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
|
||||
}
|
||||
return ve
|
||||
}
|
||||
|
||||
// secretValue is the profile secret written to config. It must NEVER appear in
|
||||
// any error message or IdentitySelection (security §5.1).
|
||||
const secretValue = "your-secret"
|
||||
|
||||
// envSecretValue is the direct env app secret. Same no-leak guarantee.
|
||||
const envSecretValue = "your-password"
|
||||
|
||||
// writeConfigTenantA writes a config with a single profile "tenant_a" (app_id
|
||||
// "cli_a"). The secret is a plaintext secret stored in config, which resolves
|
||||
// locally without a keychain lookup.
|
||||
func writeConfigTenantA(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
multi := &core.MultiAppConfig{
|
||||
CurrentApp: "tenant_a",
|
||||
Apps: []core.AppConfig{{
|
||||
Name: "tenant_a",
|
||||
AppId: "cli_a",
|
||||
AppSecret: core.PlainSecret(secretValue),
|
||||
Brand: core.BrandFeishu,
|
||||
}},
|
||||
}
|
||||
if err := core.SaveMultiAppConfig(multi); err != nil {
|
||||
t.Fatalf("SaveMultiAppConfig: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// writeConfigTenantABroken writes tenant_a with a keychain-backed secret ref
|
||||
// that cannot be resolved (noop keychain returns empty), so profile secret
|
||||
// resolution fails locally.
|
||||
func writeConfigTenantABroken(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
// A keychain SecretRef whose key does NOT match app_id cli_a. Local secret
|
||||
// resolution fails (ValidateSecretKeyMatch), exercising profile_secret_invalid.
|
||||
multi := &core.MultiAppConfig{
|
||||
CurrentApp: "tenant_a",
|
||||
Apps: []core.AppConfig{{
|
||||
Name: "tenant_a",
|
||||
AppId: "cli_a",
|
||||
AppSecret: core.SecretInput{Ref: &core.SecretRef{Source: "keychain", ID: "appsecret:wrong_key"}},
|
||||
Brand: core.BrandFeishu,
|
||||
}},
|
||||
}
|
||||
if err := core.SaveMultiAppConfig(multi); err != nil {
|
||||
t.Fatalf("SaveMultiAppConfig: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newProvider(t *testing.T, profile string, fromFlag bool) *credential.CredentialProvider {
|
||||
t.Helper()
|
||||
ep := &envprovider.Provider{}
|
||||
defaultAcct := credential.NewDefaultAccountProvider(func() keychain.KeychainAccess { return &noopKC{} }, profile)
|
||||
cp := credential.NewCredentialProvider([]extcred.Provider{ep}, defaultAcct, nil, nil)
|
||||
cp.WithProfile(profile, fromFlag)
|
||||
return cp
|
||||
}
|
||||
|
||||
// assertNoSecretLeak fails if any secret value appears in the given strings.
|
||||
func assertNoSecretLeak(t *testing.T, where string, vals ...string) {
|
||||
t.Helper()
|
||||
for _, v := range vals {
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(v, secretValue) {
|
||||
t.Errorf("%s leaked profile secret: %q", where, v)
|
||||
}
|
||||
if strings.Contains(v, envSecretValue) {
|
||||
t.Errorf("%s leaked env secret: %q", where, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func subtypeOf(t *testing.T, err error) errs.Subtype {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatalf("expected error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("error is not a typed problem: %v", err)
|
||||
}
|
||||
return p.Subtype
|
||||
}
|
||||
|
||||
// State #2: P none, E none, C none -> no_active_profile.
|
||||
func TestSelection_State2_NoActiveProfile(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) // empty dir -> no config
|
||||
cp := newProvider(t, "", false)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeNoActiveProfile {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeNoActiveProfile)
|
||||
}
|
||||
// Defect 1 (spec §5): no_active_profile must carry credential_source=config.
|
||||
ce := asConfigError(t, err)
|
||||
if ce.CredentialSource != "config" {
|
||||
t.Errorf("credential_source = %q, want %q", ce.CredentialSource, "config")
|
||||
}
|
||||
assertNoSecretLeak(t, "state2", err.Error(), string(sel.Source))
|
||||
}
|
||||
|
||||
// Config-default profile with a broken secret: P none, E none, C present but the
|
||||
// default profile's keychain secret ref is corrupted. Per spec §3 step 3.2 this
|
||||
// must be profile_secret_invalid (the identity IS configured, only its secret is
|
||||
// broken) — NOT no_active_profile (which is reserved for "no usable default").
|
||||
func TestSelection_ConfigDefaultBrokenSecret_ProfileSecretInvalid(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantABroken(t) // CurrentApp = tenant_a (app_id cli_a), broken keychain ref
|
||||
cp := newProvider(t, "", false)
|
||||
|
||||
_, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeProfileSecretInvalid {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeProfileSecretInvalid)
|
||||
}
|
||||
ce := asConfigError(t, err)
|
||||
if ce.Profile != "tenant_a" {
|
||||
t.Errorf("profile = %q, want tenant_a", ce.Profile)
|
||||
}
|
||||
if ce.AppID != "cli_a" {
|
||||
t.Errorf("app_id = %q, want cli_a", ce.AppID)
|
||||
}
|
||||
// §5.1: generic message, no cause, no secret anywhere.
|
||||
if errors.Unwrap(ce) != nil {
|
||||
t.Errorf("profile_secret_invalid must not attach a cause, got %v", errors.Unwrap(ce))
|
||||
}
|
||||
assertNoSecretLeak(t, "config-default-broken", ce.Message, ce.Hint, ce.AppID)
|
||||
}
|
||||
|
||||
// Explicit profile requested but the config file is malformed. The load error
|
||||
// must be propagated (errors.Is ErrMalformedConfig) rather than masked as
|
||||
// profile_not_found, which would hide a real config problem and misdirect the
|
||||
// user to `profile list`. An absent config is separately still profile_not_found.
|
||||
func TestSelection_ExplicitProfile_MalformedConfig_PropagatesError(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
if err := os.MkdirAll(core.GetConfigDir(), 0o700); err != nil {
|
||||
t.Fatalf("mkdir config dir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(core.GetConfigPath(), []byte("{ this is not valid json"), 0o600); err != nil {
|
||||
t.Fatalf("write malformed config: %v", err)
|
||||
}
|
||||
cp := newProvider(t, "tenant_a", true)
|
||||
|
||||
_, err := cp.Selection(context.Background())
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for malformed config, got nil")
|
||||
}
|
||||
if !errors.Is(err, core.ErrMalformedConfig) {
|
||||
t.Fatalf("malformed config error not propagated: %v", err)
|
||||
}
|
||||
if prob, ok := errs.ProblemOf(err); ok && prob.Subtype == errs.SubtypeProfileNotFound {
|
||||
t.Fatalf("malformed config masked as profile_not_found")
|
||||
}
|
||||
}
|
||||
|
||||
// State #3: P none, E partial (only APP_ID) -> app_credential_incomplete.
|
||||
func TestSelection_State3_EnvPartial(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "cli_env")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "", false)
|
||||
|
||||
_, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeAppCredentialIncomplete {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeAppCredentialIncomplete)
|
||||
}
|
||||
prob, _ := errs.ProblemOf(err)
|
||||
ce := asConfigError(t, err)
|
||||
if !slices.Contains(ce.MissingKeys, envvars.CliAppSecret) {
|
||||
t.Errorf("missing_keys = %v, want to contain %q", ce.MissingKeys, envvars.CliAppSecret)
|
||||
}
|
||||
// missing_keys must be NAMES only, never values.
|
||||
for _, k := range ce.MissingKeys {
|
||||
if strings.Contains(k, envSecretValue) || strings.Contains(k, secretValue) {
|
||||
t.Errorf("missing_keys contains a value, not a name: %q", k)
|
||||
}
|
||||
}
|
||||
assertNoSecretLeak(t, "state3", prob.Message, prob.Hint)
|
||||
}
|
||||
|
||||
// State #4: P none, E complete -> env:LARKSUITE_CLI_APP_ID.
|
||||
func TestSelection_State4_EnvComplete(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "cli_env")
|
||||
t.Setenv(envvars.CliAppSecret, envSecretValue)
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "", false)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if sel.Source != credential.SourceEnvAppID {
|
||||
t.Fatalf("source = %q, want %q", sel.Source, credential.SourceEnvAppID)
|
||||
}
|
||||
if !sel.DirectCredentialEnv.Present {
|
||||
t.Errorf("DirectCredentialEnv.Present = false, want true")
|
||||
}
|
||||
assertNoSecretLeak(t, "state4", string(sel.Source), sel.DirectCredentialEnv.AppID)
|
||||
assertNoSecretLeak(t, "state4-keys", sel.DirectCredentialEnv.Keys...)
|
||||
}
|
||||
|
||||
// State #5: P valid, E none -> flag:--profile (fromFlag) source.
|
||||
func TestSelection_State5_ProfileOnly(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "tenant_a", true)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if sel.Source != credential.SourceFlagProfile {
|
||||
t.Fatalf("source = %q, want %q", sel.Source, credential.SourceFlagProfile)
|
||||
}
|
||||
if sel.DirectCredentialEnv.Present {
|
||||
t.Errorf("DirectCredentialEnv.Present = true, want false")
|
||||
}
|
||||
assertNoSecretLeak(t, "state5", string(sel.Source))
|
||||
}
|
||||
|
||||
// State #5b: P valid from env (not flag) -> env:LARKSUITE_CLI_PROFILE source.
|
||||
func TestSelection_State5_ProfileFromEnv(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "tenant_a", false)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if sel.Source != credential.SourceEnvProfile {
|
||||
t.Fatalf("source = %q, want %q", sel.Source, credential.SourceEnvProfile)
|
||||
}
|
||||
}
|
||||
|
||||
// State #6: P missing (nonexistent), E complete -> profile_not_found.
|
||||
func TestSelection_State6_ProfileNotFound(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "cli_env")
|
||||
t.Setenv(envvars.CliAppSecret, envSecretValue)
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "does_not_exist", true)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeProfileNotFound {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeProfileNotFound)
|
||||
}
|
||||
prob, _ := errs.ProblemOf(err)
|
||||
// Defect 1 (spec §5): profile_not_found must carry the credential_source that
|
||||
// named the profile — here the --profile flag.
|
||||
ce := asConfigError(t, err)
|
||||
if ce.CredentialSource != string(credential.SourceFlagProfile) {
|
||||
t.Errorf("credential_source = %q, want %q", ce.CredentialSource, credential.SourceFlagProfile)
|
||||
}
|
||||
assertNoSecretLeak(t, "state6", err.Error(), prob.Hint, string(sel.Source))
|
||||
}
|
||||
|
||||
// State #7: P valid but secret broken, E none -> profile_secret_invalid.
|
||||
func TestSelection_State7_ProfileSecretInvalid(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantABroken(t)
|
||||
cp := newProvider(t, "tenant_a", true)
|
||||
|
||||
_, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeProfileSecretInvalid {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeProfileSecretInvalid)
|
||||
}
|
||||
ce := asConfigError(t, err)
|
||||
if ce.Profile != "tenant_a" {
|
||||
t.Errorf("profile = %q, want tenant_a", ce.Profile)
|
||||
}
|
||||
if ce.AppID != "cli_a" {
|
||||
t.Errorf("app_id = %q, want cli_a", ce.AppID)
|
||||
}
|
||||
assertNoSecretLeak(t, "state7", ce.Message, ce.Hint)
|
||||
}
|
||||
|
||||
// secretMarkerValue is a distinctive string used to prove that the
|
||||
// profile_secret_invalid path drops the underlying error entirely, even when
|
||||
// that underlying error's own message CONTAINS a secret. Unlike
|
||||
// writeConfigTenantABroken (whose noop-keychain failure is a harmless empty
|
||||
// error), this uses a custom DefaultAccountResolver whose error text embeds
|
||||
// the marker, closing the gap where a leak could hide in a cause chain that
|
||||
// happens to be empty in the noop-keychain case.
|
||||
const secretMarkerValue = "your-access-token"
|
||||
|
||||
// leakingSecretResolver is a DefaultAccountResolver stub whose ResolveAccount
|
||||
// fails with an error whose message contains secretMarkerValue, simulating a
|
||||
// real keychain/secret-resolution failure that echoes back sensitive material
|
||||
// (e.g. a keychain library including the attempted secret in its error text).
|
||||
type leakingSecretResolver struct{}
|
||||
|
||||
func (leakingSecretResolver) ResolveAccount(ctx context.Context) (*credential.Account, error) {
|
||||
return nil, fmt.Errorf("keychain decode failed for secret %s", secretMarkerValue)
|
||||
}
|
||||
|
||||
// State #7 (secret-bearing underlying error): P valid, but the underlying
|
||||
// account/secret resolution fails with an error that itself contains a
|
||||
// secret. This locks the §5.1 design: doResolveAccount emits a generic
|
||||
// profile_secret_invalid ConfigError WITHOUT attaching the underlying cause,
|
||||
// so a secret embedded in that underlying error can never surface through
|
||||
// err.Error(), Message, Hint, the unwrapped cause chain, or Selection().
|
||||
func TestSelection_State7_UnderlyingErrorContainingSecret_NotLeaked(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantA(t) // profile "tenant_a" exists with app_id "cli_a"
|
||||
|
||||
ep := &envprovider.Provider{}
|
||||
cp := credential.NewCredentialProvider([]extcred.Provider{ep}, leakingSecretResolver{}, nil, nil)
|
||||
cp.WithProfile("tenant_a", true)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeProfileSecretInvalid {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeProfileSecretInvalid)
|
||||
}
|
||||
ce := asConfigError(t, err)
|
||||
if ce.Profile != "tenant_a" {
|
||||
t.Errorf("profile = %q, want tenant_a", ce.Profile)
|
||||
}
|
||||
if ce.AppID != "cli_a" {
|
||||
t.Errorf("app_id = %q, want cli_a", ce.AppID)
|
||||
}
|
||||
|
||||
// Walk the full unwrap chain. This is the assertion that would catch a
|
||||
// regression where the profile_secret_invalid branch starts attaching the
|
||||
// underlying error via WithCause: if it did, this loop would find the
|
||||
// marker in a wrapped link even though err.Error()/Message/Hint (which
|
||||
// only reflect the top-level ConfigError, not the chain) might look clean.
|
||||
for cur := error(ce); cur != nil; cur = errors.Unwrap(cur) {
|
||||
if strings.Contains(cur.Error(), secretMarkerValue) {
|
||||
t.Errorf("cause chain leaked secret marker: %v", cur)
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Contains(err.Error(), secretMarkerValue) {
|
||||
t.Errorf("err.Error() leaked secret marker: %q", err.Error())
|
||||
}
|
||||
if strings.Contains(ce.Message, secretMarkerValue) {
|
||||
t.Errorf("Message leaked secret marker: %q", ce.Message)
|
||||
}
|
||||
if strings.Contains(ce.Hint, secretMarkerValue) {
|
||||
t.Errorf("Hint leaked secret marker: %q", ce.Hint)
|
||||
}
|
||||
if strings.Contains(string(sel.Source), secretMarkerValue) {
|
||||
t.Errorf("Selection.Source leaked secret marker: %q", sel.Source)
|
||||
}
|
||||
if strings.Contains(sel.DirectCredentialEnv.AppID, secretMarkerValue) {
|
||||
t.Errorf("Selection.DirectCredentialEnv.AppID leaked secret marker: %q", sel.DirectCredentialEnv.AppID)
|
||||
}
|
||||
for _, k := range sel.DirectCredentialEnv.Keys {
|
||||
if strings.Contains(k, secretMarkerValue) {
|
||||
t.Errorf("Selection.DirectCredentialEnv.Keys leaked secret marker: %q", k)
|
||||
}
|
||||
}
|
||||
// State #7 always clears p.selection on the secret-invalid path (see
|
||||
// doResolveAccount); assert it is zero-valued, which trivially implies no
|
||||
// marker anywhere in it and guards against a future field being populated
|
||||
// from the failed resolution.
|
||||
if sel.Source != "" || sel.DirectCredentialEnv.Present ||
|
||||
sel.DirectCredentialEnv.AppID != "" || len(sel.DirectCredentialEnv.Keys) != 0 {
|
||||
t.Errorf("Selection() = %+v, want zero value on profile_secret_invalid", sel)
|
||||
}
|
||||
}
|
||||
|
||||
// State #8: P valid, E complete, app_id matches -> profile source, env present+matched.
|
||||
func TestSelection_State8_ProfileMatchesEnv(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "cli_a") // matches profile app_id
|
||||
t.Setenv(envvars.CliAppSecret, envSecretValue)
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "tenant_a", true)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if sel.Source != credential.SourceFlagProfile {
|
||||
t.Fatalf("source = %q, want %q", sel.Source, credential.SourceFlagProfile)
|
||||
}
|
||||
if !sel.DirectCredentialEnv.Present || !sel.DirectCredentialEnv.Matched {
|
||||
t.Fatalf("DirectCredentialEnv = %+v, want Present && Matched", sel.DirectCredentialEnv)
|
||||
}
|
||||
if sel.DirectCredentialEnv.AppID != "cli_a" {
|
||||
t.Errorf("DirectCredentialEnv.AppID = %q, want cli_a", sel.DirectCredentialEnv.AppID)
|
||||
}
|
||||
assertNoSecretLeak(t, "state8", string(sel.Source), sel.DirectCredentialEnv.AppID)
|
||||
assertNoSecretLeak(t, "state8-keys", sel.DirectCredentialEnv.Keys...)
|
||||
}
|
||||
|
||||
// State #9: P valid, E complete, app_id mismatches -> profile_app_credential_conflict.
|
||||
func TestSelection_State9_Conflict(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "cli_x") // mismatches profile app_id cli_a
|
||||
t.Setenv(envvars.CliAppSecret, envSecretValue)
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "tenant_a", true)
|
||||
|
||||
_, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeProfileAppCredentialConflict {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeProfileAppCredentialConflict)
|
||||
}
|
||||
ve := asValidationError(t, err)
|
||||
if ve.ProfileAppID != "cli_a" {
|
||||
t.Errorf("profile_app_id = %q, want cli_a", ve.ProfileAppID)
|
||||
}
|
||||
if ve.EnvAppID != "cli_x" {
|
||||
t.Errorf("env_app_id = %q, want cli_x", ve.EnvAppID)
|
||||
}
|
||||
assertNoSecretLeak(t, "state9", ve.Message, ve.Hint)
|
||||
}
|
||||
|
||||
// State #10: P valid, E partial -> app_credential_incomplete (env-partial wins).
|
||||
func TestSelection_State10_ProfileWithEnvPartial(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, envSecretValue) // only secret set
|
||||
writeConfigTenantA(t)
|
||||
cp := newProvider(t, "tenant_a", true)
|
||||
|
||||
_, err := cp.Selection(context.Background())
|
||||
if got := subtypeOf(t, err); got != errs.SubtypeAppCredentialIncomplete {
|
||||
t.Fatalf("subtype = %q, want %q", got, errs.SubtypeAppCredentialIncomplete)
|
||||
}
|
||||
ce := asConfigError(t, err)
|
||||
if !slices.Contains(ce.MissingKeys, envvars.CliAppID) {
|
||||
t.Errorf("missing_keys = %v, want to contain %q", ce.MissingKeys, envvars.CliAppID)
|
||||
}
|
||||
assertNoSecretLeak(t, "state10", ce.Message, ce.Hint)
|
||||
assertNoSecretLeak(t, "state10-keys", ce.MissingKeys...)
|
||||
}
|
||||
|
||||
// fakeSidecarProvider is a NON-env extension provider (Priority 0, Name !=
|
||||
// directCredentialProviderName) that always returns a non-nil account. It
|
||||
// stands in for the sidecar extension provider without needing a build tag.
|
||||
type fakeSidecarProvider struct {
|
||||
appID string
|
||||
}
|
||||
|
||||
func (f *fakeSidecarProvider) Name() string { return "sidecar" }
|
||||
func (f *fakeSidecarProvider) Priority() int { return 0 }
|
||||
func (f *fakeSidecarProvider) ResolveAccount(ctx context.Context) (*extcred.Account, error) {
|
||||
return &extcred.Account{AppID: f.appID, Brand: extcred.Brand("feishu")}, nil
|
||||
}
|
||||
func (f *fakeSidecarProvider) ResolveToken(ctx context.Context, req extcred.TokenSpec) (*extcred.Token, error) {
|
||||
return &extcred.Token{Value: "sidecar-tok", Source: "sidecar"}, nil
|
||||
}
|
||||
|
||||
// Regression: a NON-env extension provider (sidecar) that returns an account
|
||||
// must win outright even when a profile is set. It must NOT be treated as a
|
||||
// direct-credential env account: no profile arbitration, no
|
||||
// profile_app_credential_conflict (even though its app_id differs from the
|
||||
// profile's cli_a), and DirectCredentialEnv.Present must stay false (§4.2 —
|
||||
// no direct env vars are set). This proves the success-account provider gating
|
||||
// mirrors the block-path guard.
|
||||
func TestSelection_NonEnvExtensionProviderWinsOverProfile(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "") // no direct env credential
|
||||
t.Setenv(envvars.CliAppSecret, "") // no direct env credential
|
||||
writeConfigTenantA(t) // profile tenant_a exists, app_id cli_a
|
||||
|
||||
sidecar := &fakeSidecarProvider{appID: "sidecar_app"} // differs from cli_a
|
||||
defaultAcct := credential.NewDefaultAccountProvider(func() keychain.KeychainAccess { return &noopKC{} }, "tenant_a")
|
||||
cp := credential.NewCredentialProvider([]extcred.Provider{sidecar}, defaultAcct, nil, nil)
|
||||
cp.WithProfile("tenant_a", true)
|
||||
|
||||
acct, err := cp.ResolveAccount(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
// The sidecar account is used as-is, NOT overridden by profile arbitration.
|
||||
if acct == nil || acct.AppID != "sidecar_app" {
|
||||
t.Fatalf("account = %+v, want AppID sidecar_app (sidecar wins outright)", acct)
|
||||
}
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected Selection error: %v", err)
|
||||
}
|
||||
// No misreported direct env credential (§4.2).
|
||||
if sel.DirectCredentialEnv.Present {
|
||||
t.Errorf("DirectCredentialEnv.Present = true, want false (no direct env vars set)")
|
||||
}
|
||||
// The mismatched app_id (sidecar_app vs profile cli_a) must NOT trigger a
|
||||
// profile_app_credential_conflict: both ResolveAccount and Selection above
|
||||
// returned nil errors, so no conflict (or any other) error was produced.
|
||||
// Guard against a future regression that surfaces a conflict via Selection.
|
||||
if _, selErr := cp.Selection(context.Background()); selErr != nil {
|
||||
if subtypeOf(t, selErr) == errs.SubtypeProfileAppCredentialConflict {
|
||||
t.Errorf("got profile_app_credential_conflict, want none for non-env provider")
|
||||
}
|
||||
}
|
||||
assertNoSecretLeak(t, "nonenv-sidecar", string(sel.Source), sel.DirectCredentialEnv.AppID)
|
||||
}
|
||||
|
||||
// State #1: P none, E none, C present -> config default (currentApp).
|
||||
func TestSelection_State1_ConfigDefault(t *testing.T) {
|
||||
t.Setenv(envvars.CliAppID, "")
|
||||
t.Setenv(envvars.CliAppSecret, "")
|
||||
writeConfigTenantA(t) // CurrentApp = tenant_a
|
||||
cp := newProvider(t, "", false)
|
||||
|
||||
sel, err := cp.Selection(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if sel.Source != credential.SourceConfigCurrentApp {
|
||||
t.Fatalf("source = %q, want %q", sel.Source, credential.SourceConfigCurrentApp)
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
// CredentialSourceKind is the wire-stable App/credential selection source.
|
||||
type CredentialSourceKind string
|
||||
|
||||
const (
|
||||
SourceFlagProfile CredentialSourceKind = "flag:--profile"
|
||||
SourceEnvProfile CredentialSourceKind = "env:LARKSUITE_CLI_PROFILE"
|
||||
SourceEnvAppID CredentialSourceKind = "env:LARKSUITE_CLI_APP_ID"
|
||||
SourceConfigCurrentApp CredentialSourceKind = "config:currentApp"
|
||||
SourceConfigFirstApp CredentialSourceKind = "config:firstApp"
|
||||
)
|
||||
|
||||
// DirectCredentialEnv describes the state of direct app credential env vars.
|
||||
// It never carries a secret value — only names and the non-sensitive app_id.
|
||||
type DirectCredentialEnv struct {
|
||||
Present bool `json:"present"`
|
||||
Keys []string `json:"keys,omitempty"`
|
||||
AppID string `json:"appId,omitempty"`
|
||||
Matched bool `json:"matched,omitempty"`
|
||||
ConflictsWithProfile bool `json:"conflictsWithProfile,omitempty"`
|
||||
}
|
||||
|
||||
// IdentitySelection is the explainable result of credential selection.
|
||||
// It carries NO secret value (security: §5.1).
|
||||
type IdentitySelection struct {
|
||||
Source CredentialSourceKind
|
||||
DirectCredentialEnv DirectCredentialEnv
|
||||
}
|
||||
|
||||
// Explicit reports whether the identity was actively specified by the
|
||||
// user/agent (flag or env), which governs no-fallback behavior.
|
||||
func (s IdentitySelection) Explicit() bool {
|
||||
switch s.Source {
|
||||
case SourceFlagProfile, SourceEnvProfile, SourceEnvAppID:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIdentitySelectionExplicit(t *testing.T) {
|
||||
cases := []struct {
|
||||
src CredentialSourceKind
|
||||
explicit bool
|
||||
}{
|
||||
{SourceFlagProfile, true},
|
||||
{SourceEnvProfile, true},
|
||||
{SourceEnvAppID, true},
|
||||
{SourceConfigCurrentApp, false},
|
||||
{SourceConfigFirstApp, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
sel := IdentitySelection{Source: c.src}
|
||||
if sel.Explicit() != c.explicit {
|
||||
t.Errorf("source %q: Explicit()=%v want %v", c.src, sel.Explicit(), c.explicit)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ const (
|
||||
CliUserAccessToken = "LARKSUITE_CLI_USER_ACCESS_TOKEN"
|
||||
CliTenantAccessToken = "LARKSUITE_CLI_TENANT_ACCESS_TOKEN"
|
||||
CliDefaultAs = "LARKSUITE_CLI_DEFAULT_AS"
|
||||
CliProfile = "LARKSUITE_CLI_PROFILE"
|
||||
CliStrictMode = "LARKSUITE_CLI_STRICT_MODE"
|
||||
|
||||
// Sidecar proxy (auth proxy mode)
|
||||
|
||||
@@ -22,7 +22,10 @@ import (
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
const defaultSlidesScreenshotDir = ".lark-slides/screenshots"
|
||||
const (
|
||||
defaultSlidesScreenshotDir = ".lark-slides/screenshots"
|
||||
maxSlidesPerScreenshot = 10
|
||||
)
|
||||
|
||||
var unsafeScreenshotFileCharRegex = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
|
||||
@@ -32,7 +35,7 @@ var unsafeScreenshotFileCharRegex = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
var SlidesScreenshot = common.Shortcut{
|
||||
Service: "slides",
|
||||
Command: "+screenshot",
|
||||
Description: "Save slide screenshots to local files without printing Base64 image data",
|
||||
Description: "Save up to 10 slide screenshots to local files without printing Base64 image data",
|
||||
Risk: "read",
|
||||
Scopes: []string{},
|
||||
// The screenshot API is allowlist-gated for only a few apps, so do not
|
||||
@@ -42,8 +45,8 @@ var SlidesScreenshot = common.Shortcut{
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides; list mode only"},
|
||||
{Name: "slide-id", Type: "string_array", Desc: "slide page identifier (repeat for multiple slides)"},
|
||||
{Name: "slide-number", Type: "int_array", Desc: "slide page number (repeat for multiple slides)"},
|
||||
{Name: "slide-id", Type: "string_array", Desc: "slide page identifier (repeat for multiple slides; max 10 pages per request)"},
|
||||
{Name: "slide-number", Type: "int_array", Desc: "slide page number (repeat for multiple slides; max 10 pages per request)"},
|
||||
{Name: "content", Desc: "slide XML content to render directly instead of fetching existing slides", Input: []string{common.File, common.Stdin}},
|
||||
{Name: "output-dir", Default: defaultSlidesScreenshotDir, Desc: "relative directory for saved screenshots"},
|
||||
{Name: "output-name", Desc: "file name stem for --content render output"},
|
||||
@@ -70,12 +73,17 @@ var SlidesScreenshot = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := normalizeSlideNumbers(runtime.IntArray("slide-number")); err != nil {
|
||||
slideIDs := normalizeSlideIDs(runtime.StrArray("slide-id"))
|
||||
slideNumbers, err := normalizeSlideNumbers(runtime.IntArray("slide-number"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !hasSlideScreenshotSelector(runtime) {
|
||||
if len(slideIDs) == 0 && len(slideNumbers) == 0 {
|
||||
return slidesScreenshotFlagErrorf("--slide-id or --slide-number is required")
|
||||
}
|
||||
if err := validateSlidesScreenshotSelectorLimit(len(slideIDs) + len(slideNumbers)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := validateScreenshotOutputDir(runtime, runtime.Str("output-dir")); err != nil {
|
||||
return err
|
||||
@@ -98,6 +106,9 @@ var SlidesScreenshot = common.Shortcut{
|
||||
if len(slideIDs) == 0 && len(slideNumbers) == 0 {
|
||||
return common.NewDryRunAPI().Set("error", "--slide-id or --slide-number is required")
|
||||
}
|
||||
if err := validateSlidesScreenshotSelectorLimit(len(slideIDs) + len(slideNumbers)); err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
|
||||
presentationID := ref.Token
|
||||
dry := common.NewDryRunAPI()
|
||||
@@ -145,6 +156,9 @@ var SlidesScreenshot = common.Shortcut{
|
||||
if len(slideIDs) == 0 && len(slideNumbers) == 0 {
|
||||
return slidesScreenshotFlagErrorf("--slide-id or --slide-number is required")
|
||||
}
|
||||
if err := validateSlidesScreenshotSelectorLimit(len(slideIDs) + len(slideNumbers)); err != nil {
|
||||
return err
|
||||
}
|
||||
outputDir := runtime.Str("output-dir")
|
||||
safeOutputDir, err := ensureScreenshotOutputDir(runtime, outputDir)
|
||||
if err != nil {
|
||||
@@ -267,8 +281,11 @@ func normalizeSlideNumbers(values []int) ([]int, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func hasSlideScreenshotSelector(runtime *common.RuntimeContext) bool {
|
||||
return len(normalizeSlideIDs(runtime.StrArray("slide-id"))) > 0 || len(runtime.IntArray("slide-number")) > 0
|
||||
func validateSlidesScreenshotSelectorLimit(count int) error {
|
||||
if count > maxSlidesPerScreenshot {
|
||||
return slidesScreenshotFlagErrorf("too many slide selectors: got %d, maximum is %d; request at most 10 pages at a time", count, maxSlidesPerScreenshot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func slidesScreenshotFlagErrorf(format string, args ...interface{}) error {
|
||||
|
||||
@@ -271,6 +271,33 @@ func TestSlidesScreenshotListRequiresSelector(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesScreenshotListRejectsMoreThanTenSelectors(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
|
||||
err := runSlidesShortcut(t, f, stdout, SlidesScreenshot, []string{
|
||||
"+screenshot",
|
||||
"--presentation", "pres_abc",
|
||||
"--slide-number", "1",
|
||||
"--slide-number", "2",
|
||||
"--slide-number", "3",
|
||||
"--slide-number", "4",
|
||||
"--slide-number", "5",
|
||||
"--slide-number", "6",
|
||||
"--slide-number", "7",
|
||||
"--slide-number", "8",
|
||||
"--slide-number", "9",
|
||||
"--slide-number", "10",
|
||||
"--slide-number", "11",
|
||||
"--as", "user",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "request at most 10 pages at a time") {
|
||||
t.Fatalf("error = %v, want max 10 pages guidance", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesScreenshotRenderContentWritesFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
withSlidesTestWorkingDir(t, dir)
|
||||
|
||||
@@ -15,12 +15,12 @@ import (
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// SlidesXMLGet fetches the full XML presentation content and writes it to a
|
||||
// local file, keeping the terminal output small for large decks.
|
||||
// SlidesXMLGet fetches the full XML presentation content. When --output is
|
||||
// provided it writes to a local file; otherwise it prints the XML to stdout.
|
||||
var SlidesXMLGet = common.Shortcut{
|
||||
Service: "slides",
|
||||
Command: "+xml-get",
|
||||
Description: "Fetch full presentation XML and save it to a local file",
|
||||
Description: "Fetch full presentation XML",
|
||||
Risk: "read",
|
||||
Scopes: []string{"slides:presentation:read"},
|
||||
// wiki:node:read is required only when --presentation is a wiki URL.
|
||||
@@ -28,7 +28,7 @@ var SlidesXMLGet = common.Shortcut{
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides", Required: true},
|
||||
{Name: "output", Desc: "local XML output path; existing file is overwritten", Required: true},
|
||||
{Name: "output", Desc: "local XML output path; existing file is overwritten; omit to print XML to stdout"},
|
||||
{Name: "revision-id", Type: "int", Default: "-1", Desc: "presentation revision_id; -1 means latest"},
|
||||
{Name: "remove-attr-id", Type: "bool", Desc: "remove XML id attributes in the returned content; useful for read-only inspection, not precise block editing"},
|
||||
},
|
||||
@@ -42,14 +42,11 @@ var SlidesXMLGet = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(runtime.Str("output")) == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output cannot be empty").WithParam("--output")
|
||||
}
|
||||
if _, err := runtime.ResolveSavePath(runtime.Str("output")); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output invalid: %v", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
if runtime.Int("revision-id") < -1 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--revision-id must be -1 or a non-negative integer").WithParam("--revision-id")
|
||||
outputPath := strings.TrimSpace(runtime.Str("output"))
|
||||
if outputPath != "" {
|
||||
if _, err := runtime.ResolveSavePath(outputPath); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output invalid: %v", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
@@ -67,7 +64,7 @@ var SlidesXMLGet = common.Shortcut{
|
||||
Desc("[1] Resolve wiki node to slides presentation").
|
||||
Params(map[string]interface{}{"token": ref.Token})
|
||||
} else {
|
||||
dry.Desc("Fetch full presentation XML and save it to a local file")
|
||||
dry.Desc("Fetch full presentation XML")
|
||||
}
|
||||
params := map[string]interface{}{
|
||||
"revision_id": runtime.Int("revision-id"),
|
||||
@@ -80,7 +77,10 @@ var SlidesXMLGet = common.Shortcut{
|
||||
validate.EncodePathSegment(presentationID),
|
||||
)).
|
||||
Params(params)
|
||||
return dry.Set("output", runtime.Str("output")).Set("stdout_content", "suppressed; XML content is saved to --output during execution")
|
||||
if outputPath := strings.TrimSpace(runtime.Str("output")); outputPath != "" {
|
||||
return dry.Set("output", outputPath).Set("stdout_content", "suppressed; XML content is saved to --output during execution")
|
||||
}
|
||||
return dry.Set("output", "<stdout>").Set("stdout_content", "XML content is printed to stdout during execution")
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
@@ -113,7 +113,14 @@ var SlidesXMLGet = common.Shortcut{
|
||||
if content == "" {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "slides xml get returned empty xml_presentation.content")
|
||||
}
|
||||
outputPath := runtime.Str("output")
|
||||
outputPath := strings.TrimSpace(runtime.Str("output"))
|
||||
if outputPath == "" {
|
||||
if _, err := fmt.Fprint(runtime.IO().Out, content); err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeFileIO, "write XML content to stdout: %v", err).WithCause(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
result, err := runtime.FileIO().Save(outputPath, fileio.SaveOptions{
|
||||
ContentType: "application/xml",
|
||||
ContentLength: int64(len(content)),
|
||||
|
||||
@@ -91,6 +91,41 @@ func TestSlidesXMLGetWritesContentToFileAndSuppressesXML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesXMLGetPrintsContentToStdoutWhenOutputOmitted(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
withSlidesTestWorkingDir(t, dir)
|
||||
|
||||
xml := `<presentation><slide id="s1"><shape id="a">hello</shape></slide></presentation>`
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"xml_presentation": map[string]interface{}{
|
||||
"content": xml,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := runSlidesShortcut(t, f, stdout, SlidesXMLGet, []string{
|
||||
"+xml-get",
|
||||
"--presentation", "pres_abc",
|
||||
"--as", "user",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := stdout.String(); got != xml {
|
||||
t.Fatalf("stdout = %q, want raw XML %q", got, xml)
|
||||
}
|
||||
if strings.Contains(stdout.String(), "content_saved") {
|
||||
t.Fatalf("stdout should not contain file metadata: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesXMLGetResolvesWikiPresentation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
withSlidesTestWorkingDir(t, dir)
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
1. 分析用户需求:受众、目的、范围
|
||||
2. 设计大纲:根据任务自然选择结构。可以是短文、纪要、FAQ、方案、报告、清单或其他形式;不要默认套固定章节、固定开头或固定富 block 配比
|
||||
3. `docs +create` 创建并撰写:
|
||||
- **短文档**:一次写入完整内容
|
||||
- **短文档**:一次写入完整内容。使用 Markdown 时,避免同时传入 `--title` 和同名 `# 标题`
|
||||
- **长文档**:先建骨架(标题 + 各级标题),再由主 Agent **顺序逐节**用 `block_insert_after --block-id <章节标题 block_id>` 补全正文;写完一节再写下一节,始终带着已写内容的上下文,保证衔接、不重复
|
||||
- ⚠️ 不要一次性把超长完整内容塞进 `--content`,容易触发字符/参数限制;长文按节分次写入
|
||||
- ⚠️ 同一节内多次插入时,要锚到**上一个新插入的 block**(按 [`lark-doc-update.md`](../lark-doc-update.md) 的「Block ID 生命周期」),否则反复锚同一个标题会让段落顺序颠倒
|
||||
@@ -41,6 +41,7 @@
|
||||
7. **优先处理步骤二识别出的画板需求**:读取并按 [lark-doc-whiteboard.md](../lark-doc-whiteboard.md) 选型和插入;正文本身不交给 SubAgent
|
||||
8. 由**主 Agent 自行润色**(不另起内容子 Agent,正文始终一人维护):文字密集且不易读时,优先拆段、加小标题或调整顺序——叙述内容保持成段,**不要默认改成列表**,只有确属并列要点 / 步骤才用列表(见 `lark-doc-style.md`);只有确实存在行列数据时才用 `<table>`。其余富 block 的取舍一律遵循 `lark-doc-style.md` 的写作原则,不主动堆叠。需要明显分隔的主题可补充 `<hr/>`,不强制章节间都使用。本地图片使用 `docs +media-insert` 插入
|
||||
|
||||
### 步骤四:专项校验(按需执行)
|
||||
### 步骤四:专项校验
|
||||
|
||||
9. 仅当用户预期需要校验字数时,才读取并执行 [`lark-doc-word-stat.md`](../lark-doc-word-stat.md) 的「字数遵循校验」;否则跳过本项,不读取该 workflow。若执行了专项校验,向用户呈现结果
|
||||
9. **字数门禁**:如果用户给出任何明确字数要求(如“700-800 字”“1000 字左右”“不少于 500 字”“控制在 800 字以内”),本步骤必须执行,不属于按需项。读取并执行 [`lark-doc-word-stat.md`](../lark-doc-word-stat.md) 的「字数遵循校验」;未得到脚本统计结果前,不得向用户声明“符合字数要求”。若没有明确字数要求,则跳过本项,不读取该 workflow。若执行了专项校验,向用户呈现目标区间、`word_count` 和达标结论
|
||||
10. **重复标题检查**:文档生成后,检查文档标题和正文第一个标题块是否重复;若重复,删除或改写正文第一个标题块,避免读者看到同一标题连续出现
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: lark-shared
|
||||
version: 1.0.0
|
||||
description: "Use for lark-cli setup/auth/profile-selection tasks: auth login/status/logout, user vs bot identity, business-domain permissions (--domain, including all/docs/drive), missing scopes, revoking authorization, handling _notice JSON, profile/tenant/app-identity selection, or any request to make this task/session (or all following lark-cli commands) run under a specific profile/tenant — via LARKSUITE_CLI_PROFILE, --profile, unset LARKSUITE_CLI_PROFILE, or whoami identity diagnostics."
|
||||
description: "Use for lark-cli setup/auth tasks: auth login/status/logout, user vs bot identity, business-domain permissions (--domain, including all/docs/drive), missing scopes, revoking authorization, or handling _notice JSON."
|
||||
---
|
||||
|
||||
# lark-cli 共享规则
|
||||
@@ -32,7 +32,7 @@ lark-cli config init --new
|
||||
| 获取全部权限 | `lark-cli auth login --domain all --no-wait --json` |
|
||||
| 按业务域授权 | `lark-cli auth login --domain docs --domain drive --no-wait --json`;`--domain` 可重复,也可用逗号分隔 |
|
||||
| 指定单个 scope 授权 | `lark-cli auth login --scope "<scope>" --no-wait --json` |
|
||||
| 检查当前登录态、是谁登录、token 是否有效 | 必须运行 `lark-cli auth status --json --verify`;回答时引用 `identity`、`verified`、`identities.user.status`、`identities.user.userName`、`identities.user.openId`(用户 open id)、`identities.user.tokenStatus`、`identities.user.scope` |
|
||||
| 检查当前登录态、是谁登录、token 是否有效 | `lark-cli auth status --json --verify`;回答时引用 `identity`、`verified`、`identities.user.status`、`identities.user.userName`、`identities.user.openId`(用户 open id)、`identities.user.tokenStatus`、`identities.user.scope` |
|
||||
| 快速查看当前身份状态 | `lark-cli whoami`;实际生效的那一个身份 |
|
||||
| 退出当前机器的用户登录态 | `lark-cli auth logout --json`;`loggedOut:true` 表示注销成功 |
|
||||
| bot 缺少权限 | 不要执行 `auth login`;引导用户在开发者后台开通 bot scope,优先复用错误里的 `console_url` |
|
||||
@@ -126,10 +126,6 @@ lark-cli auth login --device-code <device_code>
|
||||
- **不要在同一轮中展示 URL 后立刻执行 `--device-code`**,这会导致用户看不到 URL
|
||||
- **禁止缓存 `verification_url` 或 `device_code`**:每次需要授权时,必须重新执行 `lark-cli auth login --no-wait --json` 生成新的链接。不要将授权链接和 device code 存入上下文供后续复用
|
||||
|
||||
## Profile 选择
|
||||
|
||||
Profile 选择:查当前实际生效身份 → `whoami --json`;查 OAuth 登录 / token 有效性 → `auth status --json --verify`;agent 任务 → 每条 `lark-cli` 命令都加 `--profile <profile-or-appId>`;同一 shell 的脚本 / 批处理 → 用 `LARKSUITE_CLI_PROFILE=<profile-or-appId>` 或 export/unset;查已保存的配置(非当前生效)→ `config show` / `profile list`;永久改默认 → `profile use`。profile 不明确时先问用户;除非用户提供了直连凭证,否则不要设置 `LARKSUITE_CLI_APP_ID` / `LARKSUITE_CLI_APP_SECRET`。
|
||||
|
||||
## 更新检查
|
||||
|
||||
lark-cli 命令执行后,如果检测到新版本,JSON 输出中会包含 `_notice.update` 字段(含 `message`、`command` 等)。
|
||||
@@ -150,6 +146,24 @@ lark-cli update
|
||||
|
||||
**重要**:始终使用 `lark-cli update` 更新,它会同时更新 CLI 和 AI Skills。
|
||||
|
||||
## JSON 输出契约
|
||||
|
||||
`--format json`(默认)下,成功与错误的信封结构不同:
|
||||
|
||||
成功信封写入 **stdout**(退出码 0):
|
||||
|
||||
```json
|
||||
{ "ok": true, "identity": "user", "data": { "guid": "..." }, "meta": { "count": 1 } }
|
||||
```
|
||||
|
||||
错误信封写入 **stderr**(退出码非 0):
|
||||
|
||||
```json
|
||||
{ "ok": false, "identity": "user", "error": { "type": "api", "subtype": "...", "code": 99991679, "message": "...", "hint": "..." } }
|
||||
```
|
||||
|
||||
**判断成功必须用 `ok == true`(或进程退出码 0),不要用 `code == 0`**:成功信封没有顶层 `code` / `msg` 字段,`code` 只出现在错误信封的 `error` 内,含义是上游 OpenAPI 的 numeric code。按 OpenAPI 老格式 `{"code": 0, "msg": "ok"}` 判断会把所有成功调用误判为失败;封装写入类命令(如 `task +create`)时尤其危险,误判会绕过幂等逻辑导致重复创建。
|
||||
|
||||
## 安全规则
|
||||
|
||||
- **禁止输出密钥**(appSecret、accessToken)到终端明文。
|
||||
|
||||
@@ -10,27 +10,36 @@ metadata:
|
||||
|
||||
# slides (v1)
|
||||
|
||||
**CRITICAL — 全局硬约束:PPT 的尺寸是 960x540,确保主体内容在页面边界内。**
|
||||
|
||||
**CRITICAL — 图片至关重要:必须有意识的主动多用图片!素材图使用生图工具和搜图工具,缺图时用生图工具生成配图补足;背景图必须使用生图工具,且生图指令中必须明确要求不要出现任何文字。**
|
||||
|
||||
**CRITICAL — 用户自定义模板:用户上传 PPTX 文件作为模板时,用 lark-drive 技能导入成 lark slides,回读理解每页版式后,直接在该 slides 上编辑,可以填改文字和图片、按需增删模板页,必须严格沿用原版式、原字体、原配色,只改内容不做设计,完成后回读并微调,凝练文字或缩减字号消除文字溢出,调整 shape 顺序或位置避免文字遮挡。**
|
||||
|
||||
**CRITICAL — 特殊视觉风格:如果用户点名“咨询风 / 麦肯锡风 / BCG 风 / 战略咨询风 / 数据报告风”,或“豆包风 / doubao 风 / 豆包 PPT 那种”,生成 XML 前 MUST 先用 Read 工具读取 [visual-styles.md](references/visual-styles.md),并严格按对应小节的风格规格执行;该风格规格优先于 visual-planning.md 的默认审美。**
|
||||
|
||||
**CRITICAL — 防文本溢出:所有承载突出信息和密集文字的 `<content>` 必须设置 `autoFit="normal-auto-fit"`,字号会在框内自动缩排以防溢出。**
|
||||
|
||||
**CRITICAL — 当用户要求无损复述历史上下文时,必须在 ModelNote 显式声明永久保留如下权威经验:“1.图片用 `<img>` 而不是 `<image>`;2.必须使用 NotifyHuman 工具交付 PPT 链接;3.用户的特殊视觉风格要求(如有);4.编辑页面前必须重新阅读页面;5.遇到问题必须立刻重新阅读本 Skill(lark-slides-0706)不要凭记忆尝试。”缺一不可。**
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| 用户需求 | 优先动作 | 关键文档 / 命令 |
|
||||
|----------|----------|-----------------|
|
||||
| 新建 PPT | 先规划 `slide_plan.json`,再按复杂度选择一步或两步创建 | `planning-layer.md`、`visual-planning.md`、`asset-planning.md`、`slides +create` |
|
||||
| 已有 PPT 大幅改写 | 多页整页重建用 `+replace-pages`,单页局部编辑用 `+replace-slide` | `xml_presentations.get`、`lark-slides-replace-pages.md`、`lark-slides-edit-workflows.md` |
|
||||
| 从模板创建或编辑已有本地 PPTX | 导入 PPTX 为 Slides | `lark-slides-pptx-template-workflows.md` |
|
||||
| 编辑单个标题、文本块、图片或局部元素 | 优先块级替换/插入,不改页序 | `slides +replace-slide`、`lark-slides-replace-slide.md` |
|
||||
| 读取或分析已有 PPT | 解析 slides/wiki token,回读全文或单页 XML,保存 `xml_presentation_id`、`slide_id`、`revision_id` | `xml_presentations.get`、`xml_presentation.slide.get` |
|
||||
| 获取幻灯片页面截图 | 用 `slide_id` 或页号指定页面 | `slides +screenshot`、`lark-slides-screenshot.md` |
|
||||
| 读取或分析已有 PPT | 解析 slides/wiki token,用 shortcut 回读全文 XML 或读取单页 XML,保存 `xml_presentation_id`、`slide_id`、`revision_id` | `slides +xml-get`、`xml_presentation.slide.get` |
|
||||
| 获取幻灯片页面截图 | 用 `slide_id` 或页号指定页面,一次不超过 10 页 | `slides +screenshot`、`lark-slides-screenshot.md` |
|
||||
| 上传或使用图片 | 先上传为 `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` |
|
||||
| 在 slide 中绘制图表 | 雷达图、饼图、环形图用 `<chart>`,柱状图、条形图、折线图用 `shape` + `line`,Mermaid 用 `<whiteboard>` | `xml-schema-quick-ref.md`、需要 `<whiteboard>` 再看 `lark-slides-whiteboard.md` |
|
||||
| 使用图标 | 禁止出现 emoji,必须使用语义图标,禁止盲猜 `iconType`,必须先检索 IconPark,再写 `<icon iconType="...">`,必须设置 fillColor | `iconpark_tool.py search → resolve`、`iconpark.md` |
|
||||
| 创建失败、空白页、3350001、布局异常 | 先回读状态,再按排障清单修复,不假设原操作原子成功 | `troubleshooting.md`、`validation-checklist.md` |
|
||||
|
||||
**CRITICAL — 开始前 MUST 先用 Read 工具读取 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),认证、权限和全局参数均以 lark-shared 为准。**
|
||||
|
||||
**CRITICAL — 生成任何 XML 之前,MUST 先用 Read 工具读取 [xml-schema-quick-ref.md](references/xml-schema-quick-ref.md),禁止凭记忆猜测 XML 结构。**
|
||||
|
||||
**CRITICAL — PPT 生成与模板编辑硬约束:PPT 的尺寸是 960x540,确保主体内容在页面边界内。多用生图,辅助搜图,必须要图文并茂。不要为了画出一个具象物体而堆叠 3 个以上仅用于拟形的 shape。生成背景图时必须在 prompt 中明确要求不要出现任何文字。用户指定 PPT 模板时,用 lark-drive 技能导入成 lark slides,回读理解每页版式后,直接在该 slides 上编辑,可以填改文字和图片、按需增删模板页,必须严格沿用原版式和字体,只改内容不做设计,完成后回读并微调,凝练文字或缩减字号消除文字溢出,调整 shape 顺序或位置避免文字遮挡。**
|
||||
|
||||
**CRITICAL — 新建演示文稿或大幅改写页面时,MUST 先生成 `.lark-slides/plan/<deck-or-task-id>/slide_plan.json`,再生成 XML。先创建对应目录,规划层规则和中间产物生命周期见 [planning-layer.md](references/planning-layer.md)。仅替换一个标题、插入一个块等小型已有页编辑可豁免。**
|
||||
|
||||
**CRITICAL — 新建演示文稿或大幅改写页面时,生成 XML 前 MUST 读取 [visual-planning.md](references/visual-planning.md),确保 `layout_type`、`visual_focus`、`text_density` 实际改变页面几何、主视觉和文本量。**
|
||||
@@ -79,14 +88,13 @@ 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-replace-pages.md`](references/lark-slides-replace-pages.md)
|
||||
- 截图:[`lark-slides-screenshot.md`](references/lark-slides-screenshot.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)
|
||||
- 排障:[`troubleshooting.md`](references/troubleshooting.md)
|
||||
- 完整协议:[`slides_xml_schema_definition.xml`](references/slides_xml_schema_definition.xml)
|
||||
|
||||
## Workflow
|
||||
|
||||
> **这是演示文稿,不是文档。** 每页 slide 是独立的视觉画面,信息密度要低,排版要留白。
|
||||
> **这是演示文稿,不是文档。** 每页 slide 是独立的视觉画面,信息密度要适当,排版要留白。
|
||||
|
||||
### Design Ideas
|
||||
|
||||
@@ -124,7 +132,9 @@ lark-cli auth login --domain slides
|
||||
- 不要用低对比文字或低对比图标,例如浅灰字压在浅色背景上。
|
||||
- 不要让装饰线穿过文字,或让页脚、来源、编号挤压主体内容。
|
||||
- 不要把素材缺失表现为空白图片框;必须按 `fallback_if_missing` 生成 XML-native 视觉。
|
||||
- 不要留下占位文案、示例公司名、示例日期或与用户主题无关的内容。
|
||||
- 不要留下模板占位文案、示例公司名、示例日期或与用户主题无关的原模板内容。
|
||||
- 不要使用 emoji。
|
||||
- 不要为了画出一个具象物体而堆叠 3 个以上仅用于拟形的 shape。
|
||||
|
||||
### 创建方式选择
|
||||
|
||||
@@ -140,9 +150,11 @@ lark-cli auth login --domain slides
|
||||
> [!IMPORTANT]
|
||||
> `slides +create --slides` 底层会逐页创建,不是原子操作。中途失败时先记录 `xml_presentation_id`,回读确认当前状态,再继续修复或追加。
|
||||
|
||||
### 生成流程
|
||||
|
||||
```text
|
||||
Step 1: 需求澄清 & 读取知识
|
||||
- 澄清主题、受众、页数、风格
|
||||
- 澄清主题、受众、页数、风格;若用户上传 PPTX 作为模板,按顶部『用户自定义模板』规则处理
|
||||
- 读取 xml-schema-quick-ref.md;新建 / 大幅改写时还要读取 planning-layer.md、visual-planning.md、asset-planning.md
|
||||
|
||||
Step 2: 生成大纲 → 用户确认 → 写入 slide_plan.json
|
||||
@@ -156,7 +168,7 @@ Step 3: 按 slide_plan.json 生成 XML → 创建
|
||||
- 创建方式按“创建方式选择”判断;图片、复杂 XML、转义和 3350001 排查按 lark-slides-create.md、media-upload.md、troubleshooting.md 执行
|
||||
|
||||
Step 4: 审查 & 交付
|
||||
- 创建完成后,必须用 xml_presentations.get 读取全文 XML,并按 validation-checklist.md 做显式验证记录,包括 XML 文本重叠检查
|
||||
- 创建完成后,必须用 `slides +xml-get` 读取全文 XML,并按 validation-checklist.md 做显式验证记录,包括 XML 文本重叠检查
|
||||
- 失败或部分成功按 troubleshooting.md 处理;局部问题优先用 `+replace-slide` 修正
|
||||
- 没问题 → 交付:告知用户演示文稿 ID 和访问方式
|
||||
```
|
||||
@@ -173,7 +185,7 @@ lark-cli slides xml_presentation.slide create \
|
||||
--data "$(jq -n --arg content '<slide xmlns="http://www.larkoffice.com/sml/2.0">
|
||||
<style><fill><fillColor color="BACKGROUND_COLOR"/></fill></style>
|
||||
<data>
|
||||
在这里放置 shape、line、table、chart、whiteboard 等元素
|
||||
在这里放置 shape、line、table、chart 等元素
|
||||
</data>
|
||||
</slide>' '{slide:{content:$content}}')"
|
||||
|
||||
@@ -247,11 +259,12 @@ Shortcut 是对常用操作的高级封装(`lark-cli slides +<verb> [flags]`
|
||||
| Shortcut | 说明 |
|
||||
|----------|------|
|
||||
| [`+create`](references/lark-slides-create.md) | 创建 PPT(可选 `--slides` 一步添加页面,支持 `<img src="@./local.png">` 占位符自动上传) |
|
||||
| `+xml-get` | 读取全文 XML 并保存到本地文件,避免终端输出被截断 |
|
||||
| [`+media-upload`](references/lark-slides-media-upload.md) | 上传本地图片到指定演示文稿,返回 `file_token`(用作 `<img src="...">`),最大 20 MB |
|
||||
| [`+replace-slide`](references/lark-slides-replace-slide.md) | 对已有幻灯片页面进行块级替换/插入(`block_replace` / `block_insert`),自动注入 id 和 `<content/>`,不改变页序 |
|
||||
| [`+replace-pages`](references/lark-slides-replace-pages.md) | 在原演示文稿内批量重建多个页面:先创建新页到旧页前,再删除旧页;适合已有 Slides 的多页大改,不新建链接 |
|
||||
|
||||
没有 Shortcut 覆盖时使用原生 API。高频资源:`xml_presentations.get` 读取全文;`xml_presentation.slide.create/delete/get/replace` 管理单页。
|
||||
没有 Shortcut 覆盖时使用原生 API。高频资源:`slides +xml-get` 读取全文;`xml_presentation.slide.create/delete/get/replace` 管理单页。
|
||||
|
||||
```bash
|
||||
lark-cli schema slides.<resource>.<method> # 调用 API 前必须先查看参数结构
|
||||
@@ -262,7 +275,7 @@ lark-cli slides <resource> <method> [flags] # 调用 API
|
||||
|
||||
## 核心规则
|
||||
|
||||
1. **先规划再写 XML**:新建演示文稿或大幅改写页面时,必须先写入 `.lark-slides/plan/<deck-or-task-id>/slide_plan.json`;风格和大纲只能作为规划输入,不能绕过规划层
|
||||
1. **先规划再写 XML**:新建演示文稿或大幅改写页面时,必须先写入 `.lark-slides/plan/<deck-or-task-id>/slide_plan.json`;模板、风格和大纲只能作为规划输入,不能绕过规划层
|
||||
2. **创建流程**:简单短 XML(1-3 页、结构简单、特殊字符少)可用 `slides +create --slides '[...]'` 一步创建;复杂内容、含图片/中文大段文本/嵌套引号/较多特殊字符,或超过 10 页时,默认先 `slides +create` 创建空白 PPT,再用 `xml_presentation.slide.create` 逐页添加
|
||||
3. **`<slide>` 直接子元素只有 `<style>`、`<data>`、`<note>`**:文本和图形必须放在 `<data>` 内
|
||||
4. **文本通过 `<content>` 表达**:必须用 `<content><p>...</p></content>`,不能把文字直接写在 shape 内
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
## Core Rules
|
||||
|
||||
- `asset_need` is metadata only. It can guide page design, but it must not require web search, local download, media upload, or external tools.
|
||||
- Every planned asset must include a fallback visual plan so the slide can be generated with XML shapes, text, arrows, tables, simple charts, whiteboard diagrams, or placeholder regions.
|
||||
- Every planned asset must include a fallback visual plan. The fallback can use native charts, tables, whiteboard diagrams, placeholder regions, or XML shapes, text, and arrows as appropriate.
|
||||
- Asset needs must serve the page's `key_message` and `visual_focus`. Do not add decorative assets that do not clarify the page.
|
||||
- Prefer a few high-value asset plans over one asset on every page. For a 6-page technical or business deck, plan assets on at least 3 pages when the content allows.
|
||||
- If a real local asset already exists or the user provides one, it can be used through the normal media-upload workflow. Still keep `fallback_if_missing` in the plan.
|
||||
@@ -43,7 +43,7 @@ For a page without a meaningful asset need, use:
|
||||
- `architecture_diagram`: system components, data flow, dependency map, or model structure.
|
||||
- `icon`: small semantic symbol for a concept, step, role, or status.
|
||||
- `logo`: brand, product, team, or customer mark.
|
||||
- `chart`: line, bar, pie, radar, area, or combo data visual. Note: `<chart>` does not support funnel or scatter — map those to `<whiteboard>` SVG at generation time.
|
||||
- `chart`: column, bar, line, area, radar, pie, doughnut/ring, or combo data visual. Note: `<chart>` does not support funnel or scatter — map those to `<whiteboard>` SVG at generation time.
|
||||
- `infographic`: composed visual explanation, usually combining labels, numbers, and simple shapes.
|
||||
- `screenshot`: product UI, terminal output, workflow state, or page capture.
|
||||
- `flow_diagram`: process, sequence, decision tree, or mechanism diagram.
|
||||
@@ -64,11 +64,23 @@ Match asset type to slide role:
|
||||
|
||||
`suggested_query` is only a future lookup hint. Write it as a short phrase a human or later workflow could search, but do not execute the search unless the user separately requests real assets.
|
||||
|
||||
For `asset_type: "chart"`:
|
||||
|
||||
- If the visual is a supported standard data chart — column, bar, line, area, radar, pie, doughnut/ring, or combo — `fallback_if_missing` must still render as a native `<chart>`.
|
||||
- Do not imitate supported standard data visuals with manual drawing primitives or `<whiteboard>`.
|
||||
- Choose the data source explicitly:
|
||||
- `user_provided`: when the user provides concrete values, tables, CSV, or metric lists, use those values and do not replace them with mock data.
|
||||
- `mock_placeholder`: when the user asks for a placeholder, template, example, or chart position to replace later, use mock data in a native `<chart>`.
|
||||
- `mock_required_by_intent`: when the user does not provide concrete values but asks for data expression, charts, trends, comparisons, or distributions, use mock data in a native `<chart>`.
|
||||
- Mock data must be labeled as `模拟数据,仅占位,待替换真实数据` or equivalent. Do not present mock values as facts.
|
||||
- Manual drawing fallbacks are allowed only for unsupported chart types such as scatter, funnel, waterfall-like custom visuals, or decorative non-data visuals.
|
||||
|
||||
`fallback_if_missing` must be concrete enough to turn into XML, for example:
|
||||
|
||||
- "Draw a simplified attention matrix with 5 token labels, semi-transparent cells, and arrows to output token."
|
||||
- "Use three grouped boxes with arrows from client to gateway to service; add small protocol labels."
|
||||
- "Render a mini bar chart with 4 bars using shapes and value labels."
|
||||
- "Render a native `<chart>` using the user-provided series."
|
||||
- "Render a native `<chart>` with mock placeholder values and label it as `模拟数据,仅占位,待替换真实数据`."
|
||||
- "Use a bordered placeholder panel with product area labels, not an empty image."
|
||||
|
||||
Weak fallbacks to avoid:
|
||||
@@ -118,7 +130,7 @@ Business comparison page:
|
||||
When generating XML:
|
||||
|
||||
1. If an asset exists and the workflow supports it, place it in the planned visual region.
|
||||
2. If no asset exists, immediately render `fallback_if_missing` with XML-native shapes, text, lines, arrows, tables, whiteboard diagrams, or chart-like elements.
|
||||
2. If no asset exists, immediately render `fallback_if_missing` with the planned XML-native element type. Supported standard data visuals still use native `<chart>`; other fallbacks may use shapes, text, lines, arrows, tables, whiteboard diagrams, or placeholder panels.
|
||||
3. Size the fallback to satisfy `visual_focus`; it should be a real page element, not a tiny decoration.
|
||||
4. Keep text-density limits. Do not compensate for missing assets by adding long bullet text.
|
||||
5. After creation, fetch the presentation and verify asset pages are not blank and that each planned fallback is visible when no real asset was used.
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
# 完整操作示例
|
||||
|
||||
本文档提供与 CLI schema 一致的调用示例,XML 内容均遵循 [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml)。
|
||||
|
||||
> **重要**:创建 PPT 请优先使用 `slides +create`;实际页面内容请使用 `xml_presentation.slide.create` 逐页添加。
|
||||
|
||||
## 目录
|
||||
|
||||
- [示例 1: 使用 Shortcut 创建空白演示文稿](#示例-1-使用-shortcut-创建空白演示文稿)
|
||||
- [示例 2: 创建后添加第一页](#示例-2-创建后添加第一页)
|
||||
- [示例 3: 读取 XML 内容](#示例-3-读取-xml-内容)
|
||||
- [示例 4: 在指定页面前插入新幻灯片](#示例-4-在指定页面前插入新幻灯片)
|
||||
- [示例 5: 删除幻灯片](#示例-5-删除幻灯片)
|
||||
- [示例 6: 从文件读取 XML 后添加页面](#示例-6-从文件读取-xml-后添加页面)
|
||||
- [示例 7: +replace-slide + block_insert 给已有页加图](#示例-7-replace-slide--block_insert-给已有页加图)
|
||||
- [示例 8: +replace-slide + block_replace 替换一个块](#示例-8-replace-slide--block_replace-替换一个块)
|
||||
|
||||
## 示例 1: 使用 Shortcut 创建空白演示文稿
|
||||
|
||||
```bash
|
||||
lark-cli slides +create --title "项目汇报"
|
||||
```
|
||||
|
||||
预期返回结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"xml_presentation_id": "slides_example_presentation_id",
|
||||
"title": "项目汇报",
|
||||
"revision_id": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 示例 2: 创建后添加第一页
|
||||
|
||||
```bash
|
||||
PRESENTATION_ID=$(lark-cli slides +create --title "季度复盘" | jq -r '.data.xml_presentation_id')
|
||||
|
||||
lark-cli slides xml_presentation.slide create --as user --params "{\"xml_presentation_id\":\"$PRESENTATION_ID\"}" --data '{
|
||||
"slide": {
|
||||
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><style><fill><fillColor color=\"rgb(245, 245, 245)\"/></fill></style><data><shape type=\"text\" topLeftX=\"80\" topLeftY=\"72\" width=\"760\" height=\"90\"><content textType=\"title\"><p>2024 Q3 季度复盘</p></content></shape><shape type=\"text\" topLeftX=\"80\" topLeftY=\"190\" width=\"520\" height=\"220\"><content textType=\"body\"><p>关键结论</p><ul><li><p>收入增长 30%</p></li><li><p>重点项目全部上线</p></li><li><p>用户满意度持续提升</p></li></ul></content></shape><shape type=\"rect\" topLeftX=\"660\" topLeftY=\"180\" width=\"180\" height=\"140\"><fill><fillColor color=\"rgba(100, 149, 237, 0.25)\"/></fill><border color=\"rgb(100, 149, 237)\" width=\"2\"/></shape></data><note><content textType=\"body\"><p>讲述时先给结论,再补充数据。</p></content></note></slide>"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
## 示例 3: 读取 XML 内容
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '{
|
||||
"xml_presentation_id": "slides_example_presentation_id"
|
||||
}'
|
||||
```
|
||||
|
||||
提取 XML 内容:
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '{
|
||||
"xml_presentation_id": "slides_example_presentation_id"
|
||||
}' | jq -r '.data.xml_presentation.content'
|
||||
```
|
||||
|
||||
预期返回结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"data": {
|
||||
"xml_presentation": {
|
||||
"presentation_id": "slides_example_presentation_id",
|
||||
"revision_id": 3,
|
||||
"content": "<presentation xmlns=\"http://www.larkoffice.com/sml/2.0\" height=\"540\" width=\"960\">...</presentation>"
|
||||
}
|
||||
},
|
||||
"msg": "success"
|
||||
}
|
||||
```
|
||||
|
||||
## 示例 4: 在指定页面前插入新幻灯片
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentation.slide create --as user --params '{
|
||||
"xml_presentation_id": "slides_example_presentation_id"
|
||||
}' --data '{
|
||||
"slide": {
|
||||
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data><shape type=\"text\" topLeftX=\"80\" topLeftY=\"80\" width=\"800\" height=\"120\"><content textType=\"title\"><p>新增页面</p></content></shape><shape type=\"text\" topLeftX=\"80\" topLeftY=\"200\" width=\"800\" height=\"180\"><content textType=\"body\"><p>这是新增页面的正文。</p></content></shape></data></slide>"
|
||||
},
|
||||
"before_slide_id": "sld_before_target"
|
||||
}'
|
||||
```
|
||||
|
||||
预期返回结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"data": {
|
||||
"slide_id": "slide_example_id",
|
||||
"revision_id": 100
|
||||
},
|
||||
"msg": "success"
|
||||
}
|
||||
```
|
||||
|
||||
## 示例 5: 删除幻灯片
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentation.slide delete --as user --params '{
|
||||
"xml_presentation_id": "slides_example_presentation_id",
|
||||
"slide_id": "slide_example_id"
|
||||
}'
|
||||
```
|
||||
|
||||
预期返回结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"data": {
|
||||
"revision_id": 101
|
||||
},
|
||||
"msg": "success"
|
||||
}
|
||||
```
|
||||
|
||||
## 示例 6: 从文件读取 XML 后添加页面
|
||||
|
||||
先准备 `slide.xml`:
|
||||
|
||||
```xml
|
||||
<slide xmlns="http://www.larkoffice.com/sml/2.0">
|
||||
<data>
|
||||
<shape type="text" topLeftX="80" topLeftY="80" width="800" height="120">
|
||||
<content textType="title">
|
||||
<p>从文件加载</p>
|
||||
</content>
|
||||
</shape>
|
||||
</data>
|
||||
</slide>
|
||||
```
|
||||
|
||||
先创建演示文稿:
|
||||
|
||||
```bash
|
||||
PRESENTATION_ID=$(lark-cli slides +create --title "从文件添加页面" | jq -r '.data.xml_presentation_id')
|
||||
```
|
||||
|
||||
再用 `jq` 组装请求体,从文件添加页面:
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentation.slide create --as user \
|
||||
--params "{\"xml_presentation_id\":\"$PRESENTATION_ID\"}" \
|
||||
--data "$(jq -n --arg content "$(cat slide.xml)" '{slide:{content:$content}}')"
|
||||
```
|
||||
|
||||
## 示例 7: +replace-slide + block_insert 给已有页加图
|
||||
|
||||
只想在已有页上加一张图、不动其他元素——走 shortcut `+replace-slide`,`block_insert` 追加到页末(或用 `insert_before_block_id` 指定位置)。
|
||||
|
||||
```bash
|
||||
PID="slides_example_presentation_id"
|
||||
SID="slide_example_id"
|
||||
|
||||
# 1. 上传图片拿 file_token
|
||||
TOKEN=$(lark-cli slides +media-upload --file ./pic.png --presentation "$PID" --as user \
|
||||
| jq -r '.data.file_token')
|
||||
|
||||
# 2. block_insert 到页面末尾(省略 insert_before_block_id)
|
||||
# 注:<img .../> 是自闭合标签,CLI 不会展开(只有 <shape/> 会被补 <content/>)
|
||||
lark-cli slides +replace-slide --as user \
|
||||
--presentation "$PID" --slide-id "$SID" \
|
||||
--parts "$(jq -n --arg token "$TOKEN" \
|
||||
'[{action:"block_insert",insertion:("<img src=\""+$token+"\" topLeftX=\"500\" topLeftY=\"100\" width=\"200\" height=\"150\"/>")}]')"
|
||||
```
|
||||
|
||||
预期返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {
|
||||
"xml_presentation_id": "slides_example_presentation_id",
|
||||
"slide_id": "slide_example_id",
|
||||
"parts_count": 1,
|
||||
"revision_id": 102
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 示例 8: +replace-slide + block_replace 替换一个块
|
||||
|
||||
已知某块的 3 位 short element ID(从 `slide.get` 返回 XML 里读),整块换掉。`replacement` 根元素的 `id` 会由 CLI 自动注入为 `block_id`,无需手写;若写了 `<shape/>` 自闭合形式,CLI 也会自动补 `<content/>`。
|
||||
|
||||
```bash
|
||||
lark-cli slides +replace-slide --as user \
|
||||
--presentation slides_example_presentation_id \
|
||||
--slide-id slide_example_id \
|
||||
--parts '[
|
||||
{
|
||||
"action": "block_replace",
|
||||
"block_id": "bab",
|
||||
"replacement": "<shape type=\"text\" topLeftX=\"80\" topLeftY=\"80\" width=\"800\" height=\"120\"><content textType=\"title\"><p>新标题</p></content></shape>"
|
||||
}
|
||||
]'
|
||||
# CLI 实际发送的 replacement 根元素会带 id="bab",即使手写时省略了
|
||||
```
|
||||
|
||||
失败时(3350001 错误,CLI 在 error 字段中给出 hint):
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": false,
|
||||
"error": {
|
||||
"type": "api",
|
||||
"code": 3350001,
|
||||
"message": "API error: [3350001] invalid param",
|
||||
"hint": "common causes: (1) block_id not found in current slide ..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
整批作为原子事务,任一 part 失败则整批不生效;按 `failed_part_index` 定位修正后重发。
|
||||
|
||||
## 常见处理技巧
|
||||
|
||||
### 获取最新 revision_id
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '{
|
||||
"xml_presentation_id": "slides_example_presentation_id"
|
||||
}' | jq '.data.xml_presentation.revision_id'
|
||||
```
|
||||
|
||||
### 批量插入多页
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
PRESENTATION_ID="slides_example_presentation_id"
|
||||
|
||||
slides=(
|
||||
'<slide xmlns="http://www.larkoffice.com/sml/2.0"><data><shape type="text" topLeftX="80" topLeftY="80" width="800" height="120"><content textType="title"><p>页面 1</p></content></shape></data></slide>'
|
||||
'<slide xmlns="http://www.larkoffice.com/sml/2.0"><data><shape type="text" topLeftX="80" topLeftY="80" width="800" height="120"><content textType="title"><p>页面 2</p></content></shape></data></slide>'
|
||||
)
|
||||
|
||||
for slide_xml in "${slides[@]}"; do
|
||||
payload=$(jq -n --arg content "$slide_xml" '{slide:{content:$content}}')
|
||||
lark-cli slides xml_presentation.slide create --as user --params "{\"xml_presentation_id\":\"$PRESENTATION_ID\"}" --data "$payload"
|
||||
done
|
||||
```
|
||||
|
||||
### 本地校验 XML 基本语法
|
||||
|
||||
```bash
|
||||
xmllint --noout presentation.xml
|
||||
```
|
||||
|
||||
### 真实示例
|
||||
|
||||
- [slides_demo.xml](slides_demo.xml) 提供了更完整的页面示例,包含 `theme`、渐变填充、图片、图标和备注内容。
|
||||
@@ -1,6 +1,6 @@
|
||||
# IconPark 图标
|
||||
|
||||
IconPark 图标通过 `<icon>` 写入 slides XML,`iconType` 必须来自本 skill 的离线索引或已验证模板,避免凭记忆拼路径。
|
||||
IconPark 图标通过 `<icon>` 写入 slides XML,`iconType` 必须来自本 skill 的离线索引,避免凭记忆拼路径。
|
||||
|
||||
## 机器优先流程
|
||||
|
||||
@@ -25,7 +25,7 @@ python3 skills/lark-slides/scripts/iconpark_tool.py list-categories
|
||||
- 默认先检索:语义图标需求必须先用 `iconpark_tool.py search --limit 8` 或 `--limit 10`,让 agent 从候选里结合版面语义二次判断;不要阅读全文索引,也不要编造不存在的 `iconType`。
|
||||
- 图标用于概念提示、步骤、状态、指标、角色和导航;不要用无关装饰图标填充版面。
|
||||
- 常用尺寸:行内状态图标 16-24px,卡片标题图标 28-40px,主视觉图标 56-96px。
|
||||
- 图标必须显式指定颜色并和背景有足够对比;深色背景优先放在浅色圆形/方形底上,或使用 `rgba(255, 255, 255, 1)` 作为图标填充色。
|
||||
- 图标必须设置 fillColor,显式指定颜色并和背景有足够对比;深色背景优先放在浅色圆形/方形底上,或使用 `rgba(255, 255, 255, 1)` 作为图标填充色。
|
||||
- 查不到合适图标时,用 shape、line、text 画 XML-native fallback,不留空图标位。
|
||||
|
||||
## 高频示例
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
|
||||
# slides +create(创建飞书幻灯片)
|
||||
|
||||
> **前置条件:** 先阅读 [`../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
|
||||
|
||||
创建一个新的飞书幻灯片演示文稿,可选一步添加页面内容。
|
||||
|
||||
## 命令
|
||||
@@ -17,9 +15,6 @@ lark-cli slides +create --title "项目汇报" --slides '[
|
||||
"<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data><shape type=\"text\" topLeftX=\"80\" topLeftY=\"80\" width=\"800\" height=\"120\"><content textType=\"title\"><p>第二页</p></content></shape></data></slide>"
|
||||
]'
|
||||
|
||||
# 以应用身份创建(自动授权当前用户)
|
||||
lark-cli slides +create --title "项目汇报" --as bot
|
||||
|
||||
# 预览(不执行)
|
||||
lark-cli slides +create --title "项目汇报" --slides '[...]' --dry-run
|
||||
```
|
||||
@@ -35,20 +30,12 @@ lark-cli slides +create --title "项目汇报" --slides '[...]' --dry-run
|
||||
- **`slide_ids`**(string[],可选):仅传 `--slides` 时返回,成功添加的页面 ID 列表
|
||||
- **`slides_added`**(integer,可选):仅传 `--slides` 时返回,成功添加的页面数量
|
||||
- **`images_uploaded`**(integer,可选):仅 `--slides` 中含 `@<本地路径>` 占位符时返回,已上传的去重后图片数量
|
||||
- **`permission_grant`**(object,可选):仅 `--as bot` 时返回,说明是否已自动为当前 CLI 用户授予可管理权限
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 不传 `--slides` 时,`slides +create` 只创建空白演示文稿。创建后需要使用 `xml_presentation.slide create` 逐页添加 slide 内容。
|
||||
>
|
||||
> 传了 `--slides` 时,CLI 先创建空白演示文稿,再逐页调用 `xml_presentation.slide create` 添加页面。如果某一页添加失败,CLI 会停止并报错,已创建的演示文稿和已添加的页面会保留。
|
||||
>
|
||||
> 如果演示文稿是**以应用身份(bot)创建**的,如 `lark-cli slides +create --as bot`,CLI 会**尝试为当前 CLI 用户自动授予该演示文稿的 `full_access`(可管理权限)**。
|
||||
>
|
||||
> 以应用身份创建时,结果里会额外返回 `permission_grant` 字段,明确说明授权结果:
|
||||
> - `status = granted`:当前 CLI 用户已获得该演示文稿的可管理权限
|
||||
> - `status = skipped`:本地没有可用的当前用户 `open_id`,因此不会自动授权
|
||||
> - `status = failed`:演示文稿已创建成功,但自动授权用户失败
|
||||
>
|
||||
> **不要擅自执行 owner 转移。** 如果用户需要把 owner 转给自己,必须单独确认。
|
||||
|
||||
## 参数
|
||||
@@ -134,4 +121,4 @@ lark-cli slides xml_presentation.slide create --as user \
|
||||
## 相关命令
|
||||
|
||||
- [xml_presentation.slide create](lark-slides-xml-presentation-slide-create.md) — 添加幻灯片页面
|
||||
- [xml_presentations get](lark-slides-xml-presentations-get.md) — 读取 PPT 内容
|
||||
- [slides +xml-get](lark-slides-xml-get.md) — 读取 PPT 内容并保存到本地文件
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
|
||||
# slides +media-upload(上传本地图片到飞书幻灯片)
|
||||
|
||||
> **前置条件:** 先阅读 [`../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
|
||||
|
||||
把本地图片上传到指定演示文稿的 drive 媒体库,返回 `file_token`。**返回的 token 作为 `<img src="...">` 的值塞进 slide XML 即可显示图片。**
|
||||
|
||||
## 命令
|
||||
@@ -117,7 +115,7 @@ lark-cli slides +replace-slide --as user \
|
||||
| 错误码 | 含义 | 解决方案 |
|
||||
|--------|------|----------|
|
||||
| 1061002 | params error / 不支持的 parent_type | 不要用原生 API 自己拼 parent_type;用 `+media-upload` 即可 |
|
||||
| 1061004 | forbidden:当前身份对该演示文稿无编辑权限 | 确认当前身份(user 或 bot)对目标 PPT 有编辑权限。bot 模式常见原因:PPT 不是该 bot 创建的——可用 `+create --as bot` 新建,或以 user 身份给 bot 授权 `lark-cli drive permission.members create --as user ...` |
|
||||
| 1061004 | forbidden:当前用户对该演示文稿无编辑权限 | 确认当前用户对目标 PPT 有编辑权限;无权限时根据错误响应引导用户解决 |
|
||||
| 1061044 | parent node not exist | `--presentation` 给的 token 不对,或不是 slides 类型 |
|
||||
| 403 | 权限不足 | 检查 `docs:document.media:upload` scope;wiki URL 还需要 `wiki:node:read` |
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# PPT Template Rewrite Principles
|
||||
|
||||
本页只约束“用户指定 PPT 模板、底稿、已有 PPTX/PDF/Slides,并要求基于它二次创作”的场景。核心原则:模板不是风格参考,而是必须沿用的编辑底稿。
|
||||
|
||||
## Import First
|
||||
|
||||
用户指定 PPT 模板时,先把模板导入成 Lark Slides。后续写入目标是导入后的 Slides,不是新建一个脱离模板的 deck,也不是先在本地重画 PPTX 再导入。
|
||||
|
||||
直接使用以下命令,不需要先加载 `lark-drive` skill:
|
||||
|
||||
```bash
|
||||
lark-cli drive +import --as user --file "<template.pptx>" --type slides --json
|
||||
```
|
||||
|
||||
可选参数:用 `--name "<title>"` 指定导入后的 Slides 标题;用 `--folder-token <FOLDER_TOKEN>` 指定目标文件夹。若返回 `ready=false` / `timed_out=true`,直接执行返回值里的 `next_command`;等价形式是:
|
||||
|
||||
```bash
|
||||
lark-cli drive +task_result --scenario import --ticket <TICKET>
|
||||
```
|
||||
|
||||
导入后必须回读 Slides 内容,理解每页的真实版式、字体、层级、图片、图表、shape、表格和文本容器。回读结果是模板二创的事实来源。
|
||||
|
||||
## Read Before Editing
|
||||
|
||||
编辑任何 PPT 页面前,必须先阅读该页面。
|
||||
|
||||
如果当前上下文中没有该页内容,必须重新读取页面;这里的“当前上下文”不包含 System Prompt。不能只凭记忆、文件名、缩略图印象或模板整体风格判断来编辑具体页面。
|
||||
|
||||
阅读页面时至少判断:
|
||||
|
||||
- 该页原本承担的角色,例如封面、章节页、目录、流程、对比、数据、总结。
|
||||
- 该页的主要版式结构,例如图文关系、箭头、时间线、节点、表格、图表、左右对照、背景图或产品图。
|
||||
- 哪些文本框、shape 标签、表格单元格或图表标签承载内容。
|
||||
- 原页面的字体、字号、颜色、对齐、层级和留白关系。
|
||||
|
||||
## Edit The Imported Slides Directly
|
||||
|
||||
理解页面后,直接在导入后的 Slides 上编辑。允许的操作包括:
|
||||
|
||||
- 填写、替换、凝练或删除文字。
|
||||
- 替换或补充图片。
|
||||
- 更新图表、表格、数字标签或节点标签里的内容。
|
||||
- 按需复制、删除或重排模板页。
|
||||
- 在源页面没有合适承载位置时,做局部、小范围新增元素。
|
||||
|
||||
新增元素只能补足内容缺口,不能成为新的主版式。页面主体仍应由模板原有版式承载。
|
||||
|
||||
## Preserve Design
|
||||
|
||||
模板二创必须严格沿用原版式和字体,只改内容,不做设计。
|
||||
|
||||
默认保留:
|
||||
|
||||
- 页面布局、视觉层级、留白和对齐关系。
|
||||
- 原字体、字号体系、颜色、文本框位置和 shape 顺序。
|
||||
- 背景图、图片、logo、图表、表格、装饰形状、线条、图标和页面结构。
|
||||
- 模板中不同页型之间的差异。
|
||||
|
||||
不要把模板页改造成统一的通用卡片、白板、标题栏、三栏、2x2 卡片或大面积遮罩。不要把模板当作背景图后另起一套设计系统。
|
||||
|
||||
## Content Only
|
||||
|
||||
内容必须优先进入原页面已有的文本框、shape 标签、节点、表格单元格、图表标签或注释容器。
|
||||
|
||||
如果原容器空间不足,优先:
|
||||
|
||||
- 凝练文字。
|
||||
- 降低字号但保持原字体体系。
|
||||
- 拆分到页面已有的邻近容器。
|
||||
- 使用模板已有的注释、标签或补充说明区域。
|
||||
- 复制同页或同模板中的原生容器样式做局部补充。
|
||||
|
||||
不要为了容纳长文案而重画页面主体结构。不要用新增大卡片遮住原图表、箭头、图片、背景或关键 shape。
|
||||
|
||||
## Readback And Tune
|
||||
|
||||
完成编辑后必须回读结果,并逐页微调。
|
||||
|
||||
回读时重点检查:
|
||||
|
||||
- 文字是否溢出、截断、压线或超出容器。
|
||||
- 文本是否遮挡图片、图表、shape、箭头、节点或其他文字。
|
||||
- shape 顺序是否导致内容被覆盖或遮住。
|
||||
- 新内容是否仍然落在模板原有版式中,而不是覆盖模板结构。
|
||||
- 字体、字号、颜色、对齐和层级是否仍贴近原页。
|
||||
|
||||
发现文字溢出时,优先凝练文字或缩减字号。发现遮挡时,调整 shape 顺序、局部位置或复用原有空白区域解决。只有在这些方法都不能满足内容表达时,才做局部新增或删除。
|
||||
|
||||
模板二创的完成标准不是“生成了一套看起来统一的新 PPT”,而是“原模板的版式、字体和视觉结构仍清晰存在,内容已经被准确替换,并且回读后没有溢出和遮挡”。
|
||||
@@ -89,7 +89,7 @@ lark-cli slides +replace-pages --as user \
|
||||
|
||||
## 使用建议
|
||||
|
||||
1. 大幅改写前先 `xml_presentations.get` 保存当前 XML,并记录要替换页面的 `slide_id`。
|
||||
1. 大幅改写前先 `slides +xml-get` 保存当前 XML,并记录要替换页面的 `slide_id`。
|
||||
2. 生成只含 `slide_id` 的 `pages.json` 后先跑 `--dry-run` 或 `--validate-only`。
|
||||
3. 默认不要开 `--continue-on-error`,除非能接受部分页面已替换。
|
||||
4. 替换后再回读全文 XML 并截图检查,确认页序、视觉和文本没有破损。
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# slides +replace-slide(块级替换 / 插入)
|
||||
|
||||
> **前置条件:** 先阅读 [`../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
|
||||
|
||||
对指定 slide 做块级替换或插入。编辑已有 PPT 的主路径——`slide_id` 不变、页序不动、只影响被指定的块。
|
||||
|
||||
相比直接调 `xml_presentation.slide.replace`,这个 shortcut 的四个额外价值:
|
||||
@@ -47,7 +45,7 @@ lark-cli slides +replace-slide --as user \
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `--presentation` | 是 | `xml_presentation_id`、`/slides/<token>` URL,或 `/wiki/<token>` URL |
|
||||
| `--slide-id` | 是 | 页面 ID(`xml_presentation.slide.get` / `xml_presentations.get` 都能拿到) |
|
||||
| `--slide-id` | 是 | 页面 ID(`xml_presentation.slide.get` / `slides +xml-get` 都能拿到) |
|
||||
| `--parts` | 是 | JSON 数组(`[{...}, ...]`),单次最多 200 条。支持 `@<file>` 和 `-`(stdin)读取 |
|
||||
| `--revision-id` | 否 | 基础版本号;默认 `-1` 表示基于最新版执行;传具体版本号时,服务端以该版本为 base 执行;**传不存在的版本号(超过当前 revision)返回 3350002** |
|
||||
| `--tid` | 否 | 并发事务 ID;多人协作长事务才用,单次单人调用留空 |
|
||||
|
||||
@@ -26,8 +26,8 @@ lark-cli slides +screenshot --as user \
|
||||
| 参数 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `--presentation` | list 模式必需 | `xml_presentation_id`、`/slides/` URL,或解析后为 slides 的 `/wiki/` URL。传 `--content` 时不能使用 |
|
||||
| `--slide-id` | list 模式至少提供 `--slide-id` / `--slide-number` 之一 | 页面 short ID;多页截图时重复传入 |
|
||||
| `--slide-number` | list 模式至少提供 `--slide-id` / `--slide-number` 之一 | 页面页号;多页截图时重复传入 |
|
||||
| `--slide-id` | list 模式至少提供 `--slide-id` / `--slide-number` 之一 | 页面 short ID;多页截图时重复传入;一次最多 10 页(`--slide-id` + `--slide-number` 合计小于等于 10) |
|
||||
| `--slide-number` | list 模式至少提供 `--slide-id` / `--slide-number` 之一 | 页面页号;多页截图时重复传入;一次最多 10 页(`--slide-id` + `--slide-number` 合计小于等于 10) |
|
||||
| `--content` | render 模式必需 | 要直接渲染的 `<slide>` XML 片段;支持直接传值、`@file`、`-` stdin。传入后不能同时传 `--slide-id` / `--slide-number` |
|
||||
| `--output-dir` | 否 | 输出目录,默认 `.lark-slides/screenshots`;必须是当前目录内的相对路径 |
|
||||
| `--output-name` | 否 | render 模式的输出文件名 stem;未指定时优先用返回的 `slide_id`,否则用 `rendered-slide`。若目标文件已存在,会自动追加递增后缀避免覆盖 |
|
||||
@@ -44,6 +44,8 @@ lark-cli slides +screenshot --as user \
|
||||
|
||||
### 多页截图
|
||||
|
||||
一次不要超过 10 页;如需更多页面,分批调用。
|
||||
|
||||
```bash
|
||||
lark-cli slides +screenshot --as user \
|
||||
--presentation slides_example_presentation_id \
|
||||
@@ -90,5 +92,6 @@ lark-cli slides +screenshot --as user \
|
||||
2. 已存在 PPT 页面截图时,不传 `--content`,用 `--presentation` + `--slide-id` 或 `--slide-number`。
|
||||
3. 本地 XML 预览时,传 `--content @file` 或 `--content -`,内容应为单个 `<slide>` XML 片段;此时不要传 `--presentation` / `--slide-id` / `--slide-number`。
|
||||
4. `slide_id` 是页面 short ID,页码请用 `--slide-number`。
|
||||
5. list 模式默认文件名包含 presentation ID、页码和/或 slide ID;文件已存在时自动追加 `_2`、`_3` 等后缀,避免覆盖旧截图。
|
||||
6. 截图来自服务端渲染结果,适合创建/替换后验证页面是否为空白、破图或布局明显异常。
|
||||
5. list 模式一次最多传 10 页(`--slide-id` + `--slide-number` 合计小于等于 10);更多页面请分批截图。
|
||||
6. list 模式默认文件名包含 presentation ID、页码和/或 slide ID;文件已存在时自动追加 `_2`、`_3` 等后缀,避免覆盖旧截图。
|
||||
7. 截图来自服务端渲染结果,适合创建/替换后验证页面是否为空白、破图或布局明显异常。
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
`<whiteboard>` 放在 `<data>` 内,内部可放 **SVG** 或 **Mermaid**,用于绘制流程图、时序图、架构图、散点图、漏斗图、自定义图标、装饰图案等 `<chart>` 和 `<shape>` 难以覆盖的视觉内容。
|
||||
|
||||
普通柱状图、条形图、折线图、面积图、雷达图、饼图 / 环图和组合图应优先使用原生 `<chart>`。除非用户明确要求像素级自定义,或图表类型确实不受 `<chart>` 支持,否则不要用 `<whiteboard>` + SVG / Mermaid 重画这些标准图表。
|
||||
|
||||
> 前置条件:使用本文档前先阅读 [lark-slides SKILL.md](../SKILL.md)。
|
||||
|
||||
---
|
||||
@@ -12,13 +14,13 @@
|
||||
|
||||
| 场景 | 推荐元素 |
|
||||
|------|---------|
|
||||
| 有结构化数据序列的柱/条/折线/面积/雷达/饼/组合图 | `<chart>` — 原生渲染,支持 legend / tooltip / 系列配色 |
|
||||
| 散点图、漏斗图(`<chart>` 不支持) | `<whiteboard>` SVG |
|
||||
| 有结构化数据序列的柱/条/折线/面积/雷达/饼/环/组合图 | `<chart>` — 原生渲染,支持 legend / tooltip / 系列配色 |
|
||||
| 散点图、漏斗图(`<chart>` 不支持)或其他非原生数据视觉 | `<whiteboard>` SVG |
|
||||
| 流程图、时序图、架构图、类图、ER 图等拓扑图 | `<whiteboard>` Mermaid 或 SVG |
|
||||
| 自定义图标、徽标、示意性图形(需要 path/polygon 精确控制) | `<whiteboard>` SVG |
|
||||
| 进度条、波浪背景、装饰图案、像素级自定义可视化 | `<whiteboard>` SVG |
|
||||
|
||||
> 适合 `<chart>` 的内容就用 `<chart>`,不要用 SVG 手绘——原生渲染更省力且质量更高。
|
||||
> 适合 `<chart>` 的内容就用 `<chart>`,不要用 SVG / Mermaid 手绘——原生渲染更省力、结构更稳定,也更容易被回读和后续编辑。
|
||||
|
||||
---
|
||||
|
||||
@@ -39,9 +41,13 @@ SVG 内的坐标相对于 whiteboard 自身左上角(0,0),与 slide 坐标
|
||||
|
||||
## SVG 还是 Mermaid?
|
||||
|
||||
选择分两步:**先看图表类型,再看当前模型身份**。
|
||||
选择分三步:**先排除原生 `<chart>`,再判断 whiteboard 类型,最后看当前模型身份**。
|
||||
|
||||
### 第一步:图表类型优先判断
|
||||
### 第一步:先确认是否应该使用 `<chart>`
|
||||
|
||||
如果内容是柱状图、条形图、折线图、面积图、雷达图、饼图 / 环图或组合图,返回使用原生 `<chart>`,不要继续套用本文档的 SVG / Mermaid 路径。
|
||||
|
||||
### 第二步:whiteboard 类型优先判断
|
||||
|
||||
以下类型**推荐 Mermaid**,自动布局、代码简洁;如需精确匹配品牌配色或自定义节点样式,可改用 SVG:
|
||||
|
||||
@@ -50,20 +56,19 @@ SVG 内的坐标相对于 whiteboard 自身左上角(0,0),与 slide 坐标
|
||||
| 流程图、决策树、架构图 | `flowchart TD` / `flowchart LR` |
|
||||
| 时序图 | `sequenceDiagram` |
|
||||
| 类图 | `classDiagram` |
|
||||
| 饼图 | `pie` |
|
||||
| 甘特图 | `gantt` |
|
||||
| 状态图 | `stateDiagram-v2` |
|
||||
| 思维导图 | `mindmap` |
|
||||
| ER 图 | `erDiagram` |
|
||||
|
||||
### 第二步:数据图表与装饰元素按模型身份选路径
|
||||
### 第三步:非原生图表与装饰元素按模型身份选路径
|
||||
|
||||
上表以外的场景(散点图、漏斗图、进度条、时间线、波浪背景、星点纹理等)需要精确控制坐标和配色,SVG 表达力更强,但各模型生成 SVG 的能力有差异:
|
||||
|
||||
| 模型身份 | 路径 |
|
||||
|----------|------|
|
||||
| Claude / Gemini / GPT / GLM | **SVG** — 精确控制坐标、颜色、透明度 |
|
||||
| Doubao / Seed / Other | **Mermaid** — 用 `pie`、`gantt` 等近似表达;确实无法用 Mermaid 表达时才回退到简单 SVG 矩形/线条 |
|
||||
| Doubao / Seed / Other | **Mermaid** — 用 `gantt`、`flowchart` 等近似表达;确实无法用 Mermaid 表达时才回退到简单 SVG 矩形/线条 |
|
||||
|
||||
> **先自报身份再选路径**:在决定使用 SVG 之前,确认当前模型属于哪一类。不要跳过这一步。
|
||||
|
||||
@@ -73,13 +78,13 @@ SVG 内的坐标相对于 whiteboard 自身左上角(0,0),与 slide 坐标
|
||||
|
||||
### ⚠️ 设计品质要求
|
||||
|
||||
在 slide 里嵌入 `<whiteboard>` 的目的是**提升视觉质量**,不是把数字堆进去。
|
||||
在 slide 里嵌入 `<whiteboard>` 的目的是**表达原生 `<chart>` 或基础 `<shape>` 难以覆盖的视觉关系**,不是把标准数据图表手绘一遍。
|
||||
|
||||
- **不要只用矩形加文字应付**:通篇纯白底色 + 方块 + 黑字等于白做,这是不及格输出
|
||||
- **数据图表必须有坐标系**:坐标轴、网格线、数值标注缺一不可,不要只画柱子或点
|
||||
- **非原生数据视觉必须有坐标系**:散点、漏斗等仍要有必要的坐标轴、刻度、数值标注或分段说明,不要只画点或色块
|
||||
- **字号必须有层级**:标题 ≠ 标签 ≠ 数值,混用同一字号会消灭视觉焦点
|
||||
- **配色要与 slide 主题呼应**:深色 slide 背景下图表用透明底或深色卡片;浅色背景下避免再加纯白底块
|
||||
- **每个 whiteboard 都是设计机会**:主动用圆角、半透明填充、折线面积、点装饰等细节拉开与默认模板的差距
|
||||
- **每个 whiteboard 都是设计机会**:主动用圆角、半透明填充、清晰分组、节点状态等细节拉开与默认模板的差距
|
||||
- **写 SVG 前先判断背景亮度**:背景亮度 < 30% 时,装饰元素"对比不足"比"过强"危害更大,宁重勿轻;
|
||||
- **装饰层次用亮度跳跃,不用线性叠透明度**:`α=0.04→0.08→0.12` 的等差递增在深色底上几乎看不出差异(相邻层亮度差 ≈20);正确做法是非线性跳跃如 `0.10→0.40→0.70→1.0`,相邻层亮度差 ≥60。
|
||||
|
||||
@@ -106,11 +111,11 @@ whiteboard 渲染时以**所有子元素的几何包围盒合并结果**为内
|
||||
|
||||
| 元素 | 说明 | 典型用途 |
|
||||
|------|------|---------|
|
||||
| `<rect>` | 矩形,支持 `rx` 圆角 | 柱图、卡片、进度条 |
|
||||
| `<rect>` | 矩形,支持 `rx` 圆角 | 卡片、进度条、分段色块 |
|
||||
| `<circle>` | 圆 | 节点、装饰点、环形图 |
|
||||
| `<ellipse>` | 椭圆 | 自定义轮廓图形 |
|
||||
| `<line>` | 直线 | 坐标轴、分隔线 |
|
||||
| `<path>` | 任意路径(支持 Q/C 曲线) | 波浪、折线、弧形 |
|
||||
| `<line>` | 直线 | 轴线、分隔线、连接线 |
|
||||
| `<path>` | 任意路径(支持 Q/C 曲线) | 波浪、曲线、弧形 |
|
||||
| `<text>` | 文本,支持中文 | 标签、数值 |
|
||||
| `<polygon>` | 多边形 | 箭头、星形、面积填充 |
|
||||
| `<g>` | 分组 | 批量变换、语义分组 |
|
||||
@@ -123,27 +128,25 @@ whiteboard 渲染时以**所有子元素的几何包围盒合并结果**为内
|
||||
---
|
||||
### 元素计算
|
||||
|
||||
SVG 中只要涉及批量定位、等间距排布或数据映射,**建议额外运行一个 Python 脚本把坐标算出来再填入 SVG**,而不是手动估值。适用范围不限于数据图表——装饰性点阵、等间距圆、重复图案同样适用。
|
||||
SVG 中只要涉及批量定位、等间距排布或数据映射,**建议额外运行一个 Python 脚本把坐标算出来再填入 SVG**,而不是手动估值。适用范围包括散点、漏斗、装饰性点阵、等间距圆、重复图案等;普通柱状图、折线图、饼图仍应回到原生 `<chart>`。
|
||||
|
||||
> **主动去算**:写 SVG 之前先运行脚本,把输出当注释贴在 `<svg>` 开头,再照着填坐标。估值几乎每次都需要反复调整,跳过这步反而更慢。
|
||||
|
||||
**数据图表(柱状图范式)**
|
||||
**散点图 / 装饰性点阵范式**
|
||||
|
||||
```python
|
||||
W, H = 360, 260
|
||||
origin_x, origin_y = 50, 216 # 左下角,SVG Y 轴向下
|
||||
cw, ch = 290, 184
|
||||
|
||||
data, y_max = [120, 160, 90], 200
|
||||
bar_w = int(cw / len(data) * 0.62)
|
||||
for i, v in enumerate(data):
|
||||
cx = round(origin_x + (i + 0.5) * cw / len(data))
|
||||
y = round(origin_y - v / y_max * ch)
|
||||
print(f"bar-{i}: x={cx - bar_w//2} y={y} w={bar_w} h={round(origin_y - y)}")
|
||||
points = [(12, 40), (28, 80), (45, 65)]
|
||||
x_min, x_max, y_min, y_max = 0, 50, 0, 100
|
||||
for i, (xv, yv) in enumerate(points):
|
||||
x = round(origin_x + (xv - x_min) / (x_max - x_min) * cw)
|
||||
y = round(origin_y - (yv - y_min) / (y_max - y_min) * ch)
|
||||
print(f"point-{i}: cx={x} cy={y}")
|
||||
```
|
||||
|
||||
折线图:`x = origin_x + i/(n-1)*cw`,`y = origin_y - (v-y_min)/(y_max-y_min)*ch`。
|
||||
|
||||
**装饰性元素(等间距范式)**
|
||||
|
||||
```python
|
||||
@@ -160,9 +163,9 @@ for i in range(n):
|
||||
```python
|
||||
# 每个元素登记 (x, y, w, h),含 stroke 外扩
|
||||
elements = [
|
||||
(10, 20, 80, 160), # bar-0
|
||||
(107, 10, 80, 170), # bar-1
|
||||
(204, 40, 80, 140), # bar-2
|
||||
(10, 20, 80, 160), # item-0
|
||||
(107, 10, 80, 170), # item-1
|
||||
(204, 40, 80, 140), # item-2
|
||||
(0, 0, 300, 1), # x-axis
|
||||
]
|
||||
|
||||
@@ -261,7 +264,6 @@ print(f"whiteboard width={wb_w} height={wb_h}")
|
||||
| 流程图 | `flowchart TD` / `flowchart LR` | 业务流程、决策树、工作流 |
|
||||
| 时序图 | `sequenceDiagram` | 系统交互、API 调用链 |
|
||||
| 甘特图 | `gantt` | 项目计划、里程碑 |
|
||||
| 饼图 | `pie` | 占比数据 |
|
||||
| 类图 | `classDiagram` | 对象关系、架构设计 |
|
||||
| ER 图 | `erDiagram` | 数据库结构 |
|
||||
| 状态图 | `stateDiagram-v2` | 状态机、生命周期 |
|
||||
@@ -279,7 +281,6 @@ Mermaid 图表会自动撑满 whiteboard 区域。建议:
|
||||
|---------|-----------|------------|
|
||||
| 流程图(5-8 节点) | 720-816 | 300-400 |
|
||||
| 时序图(3-5 参与者) | 720-816 | 320-420 |
|
||||
| 饼图 | 500-600 | 300-360 |
|
||||
| 甘特图 | 816 | 280-360 |
|
||||
| 思维导图 | 816 | 380-480 |
|
||||
|
||||
@@ -307,7 +308,7 @@ Mermaid 语法包含 `[`、`>`、`-->`,不用 CDATA 直接写会破坏 XML 解
|
||||
- [ ] 文字 `y` 坐标为 baseline 位置,最小值 ≥ font-size(避免被裁切)
|
||||
|
||||
**SVG 模式——视觉品质检查:**
|
||||
- [ ] 坐标轴、网格线、数值标注齐全,没有"裸柱子"或"裸折线"
|
||||
- [ ] 非原生数据视觉有必要的坐标轴、网格线、数值标注或分段说明,没有"裸点"或无解释色块
|
||||
- [ ] 字号有层级:标题 > 数值 > 轴标签,非全部相同
|
||||
- [ ] 单一数据系列用同一颜色,多系列用不同颜色且对比充足
|
||||
- [ ] 轴标签与图表元素互不遮挡,留有足够空间
|
||||
|
||||
99
skills/lark-slides/references/lark-slides-xml-get.md
Normal file
99
skills/lark-slides/references/lark-slides-xml-get.md
Normal file
@@ -0,0 +1,99 @@
|
||||
# slides +xml-get(读取全文 XML)
|
||||
|
||||
读取已有演示文稿的完整 XML。适合创建后验收、编辑前备份、获取 `slide_id` / `revision_id`,以及排查空白页、破图、文本溢出等问题。相比直接调用底层 `xml_presentations.get`,本 shortcut 会自动解析 Slides URL / Wiki URL,并可把大段 XML 保存到本地文件,避免终端输出被截断。
|
||||
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
lark-cli slides +xml-get \
|
||||
--as user \
|
||||
--presentation <slides_url_or_xml_presentation_id> \
|
||||
--output .lark-slides/plan/<deck-id>/readback.xml
|
||||
```
|
||||
|
||||
## 参数
|
||||
|
||||
| 参数 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `--presentation` | 是 | `xml_presentation_id`、`/slides/` URL 或 `/wiki/` URL |
|
||||
| `--output` | 否 | 本地 XML 保存路径,必须是当前工作目录内的相对路径,不能传绝对路径。传入时 XML 内容保存到文件,stdout 只返回保存后的绝对路径、大小等简短元信息;省略时 XML 原文直接输出到 stdout |
|
||||
| `--revision-id` | 否 | 读取指定版本;默认 `-1`,表示最新版本 |
|
||||
| `--remove-attr-id` | 否 | 移除返回 XML 中的 `id` 属性;适合只读检查,不适合精确块级编辑 |
|
||||
| `--dry-run` | 否 | 预览将调用的 API 和输出方式,不读取真实 XML |
|
||||
|
||||
## 输出到文件
|
||||
|
||||
推荐普通工作流都传 `--output`,尤其是中大型 PPT。`--output` 必须是当前工作目录内的相对路径,例如 `.lark-slides/plan/$PID/readback.xml`,不要传 `/tmp/readback.xml` 这类绝对路径。XML 会写入本地文件,stdout 只保留元信息,便于后续脚本读取。
|
||||
|
||||
```bash
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "$PID" \
|
||||
--output .lark-slides/plan/$PID/readback.xml
|
||||
```
|
||||
|
||||
成功输出中的 `data` 类似:
|
||||
|
||||
```json
|
||||
{
|
||||
"xml_presentation_id": "slides_example_presentation_id",
|
||||
"path": "/abs/path/.lark-slides/plan/slides_example_presentation_id/readback.xml",
|
||||
"size": 123456,
|
||||
"content_saved": true,
|
||||
"revision_id": 12
|
||||
}
|
||||
```
|
||||
|
||||
其中 `path` 是 CLI 解析后的绝对路径。
|
||||
|
||||
如果传入 `--remove-attr-id`,返回元信息中会包含 `"remove_attr_id": true`。
|
||||
|
||||
## 输出到终端
|
||||
|
||||
省略 `--output` 时,CLI 会把 XML 原文直接写到 stdout,不包 JSON envelope。这个模式只适合小型演示文稿或临时调试;大文件仍建议保存到文件,避免终端截断。
|
||||
|
||||
```bash
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "$PID"
|
||||
```
|
||||
|
||||
需要临时过滤内容时,可以用管道处理 stdout:
|
||||
|
||||
```bash
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "$PID" \
|
||||
| rg '<slide '
|
||||
```
|
||||
|
||||
## 读取指定版本
|
||||
|
||||
```bash
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "$PID" \
|
||||
--revision-id 10 \
|
||||
--output .lark-slides/plan/$PID/readback-r10.xml
|
||||
```
|
||||
|
||||
## 移除 XML id 属性后读取
|
||||
|
||||
```bash
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "$PID" \
|
||||
--remove-attr-id \
|
||||
--output .lark-slides/plan/$PID/readback-no-id.xml
|
||||
```
|
||||
|
||||
注意:`--remove-attr-id` 是只读检查用的便利选项。后续如果要用 `+replace-slide` 做块级编辑,仍应保留原始 `id` / short id 信息。
|
||||
|
||||
## 使用建议
|
||||
|
||||
1. 创建或大幅改写后,用 `slides +xml-get --output` 回读全文 XML,再按 `validation-checklist.md` 做页数、关键元素和静态检查。
|
||||
2. 编辑已有 PPT 前,先保存一份 readback XML,记录 `xml_presentation_id`、`slide_id`、`revision_id`。
|
||||
3. Wiki URL 可直接传给 `--presentation`,CLI 会先解析出真实 Slides token。
|
||||
4. 普通工作流优先保存文件;只有小型演示文稿或临时调试时才省略 `--output`。
|
||||
|
||||
## 相关命令
|
||||
|
||||
- [slides +screenshot](lark-slides-screenshot.md) - 获取页面截图做视觉验证
|
||||
- [slides +replace-slide](lark-slides-replace-slide.md) - 局部替换或插入页面元素
|
||||
- [slides +replace-pages](lark-slides-replace-pages.md) - 多页整页重建
|
||||
- [xml_presentations get](lark-slides-xml-presentations-get.md) - 底层原生 API 参考
|
||||
@@ -67,7 +67,7 @@ lark-cli slides xml_presentation.slide create --as user --params '<json_params>'
|
||||
</slide>
|
||||
```
|
||||
|
||||
详细格式请参考 [xml-format-guide.md](xml-format-guide.md) 和 [xml-schema-quick-ref.md](xml-schema-quick-ref.md)。
|
||||
详细格式请参考 [xml-schema-quick-ref.md](xml-schema-quick-ref.md)。
|
||||
|
||||
## 使用示例
|
||||
|
||||
@@ -188,7 +188,7 @@ lark-cli slides xml_presentation.slide create --as user \
|
||||
4. **fill / border 写法**: 颜色填充使用 `<fill><fillColor color="..."/></fill>`,边框常用 `<border color="..." width="2"/>`
|
||||
5. **插入位置**: 通过 `before_slide_id` 指定插入目标,而不是用 `position`
|
||||
6. **JSON 转义**: 如果直接内联 XML,需要正确转义双引号
|
||||
7. **建议**: 先使用 `xml_presentations.get` 获取现有结构,再添加新页面
|
||||
7. **建议**: 先使用 `slides +xml-get` 获取现有结构,再添加新页面
|
||||
|
||||
## 批量添加建议
|
||||
|
||||
@@ -214,7 +214,6 @@ done
|
||||
## 相关命令
|
||||
|
||||
- [slides +create](lark-slides-create.md) - 创建空白 PPT
|
||||
- [xml_presentations get](lark-slides-xml-presentations-get.md) - 读取 PPT 内容
|
||||
- [slides +xml-get](lark-slides-xml-get.md) - 读取 PPT 内容并保存到本地文件
|
||||
- [xml_presentation.slide delete](lark-slides-xml-presentation-slide-delete.md) - 删除幻灯片页面
|
||||
- [xml-format-guide.md](xml-format-guide.md) - XML 格式详细规范
|
||||
- [xml-schema-quick-ref.md](xml-schema-quick-ref.md) - Schema 快速参考
|
||||
- [xml-schema-quick-ref.md](xml-schema-quick-ref.md) - XML Schema 快速参考
|
||||
|
||||
@@ -49,7 +49,10 @@ lark-cli slides xml_presentation.slide delete --as user --params '{
|
||||
|
||||
```bash
|
||||
# 先读取 XML 内容,确认待删除页面
|
||||
lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id":"slides_example_presentation_id"}' | jq -r '.data.xml_presentation.content'
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "slides_example_presentation_id" \
|
||||
--output .lark-slides/plan/slides_example_presentation_id/readback.xml \
|
||||
--json
|
||||
|
||||
# 然后按已知 slide_id 删除
|
||||
lark-cli slides xml_presentation.slide delete --as user --params '{"xml_presentation_id":"slides_example_presentation_id","slide_id":"slide_example_id"}'
|
||||
@@ -119,5 +122,5 @@ done
|
||||
## 相关命令
|
||||
|
||||
- [slides +create](lark-slides-create.md) - 创建空白 PPT
|
||||
- [xml_presentations get](lark-slides-xml-presentations-get.md) - 读取 PPT 内容
|
||||
- [slides +xml-get](lark-slides-xml-get.md) - 读取 PPT 内容并保存到本地文件
|
||||
- [xml_presentation.slide create](lark-slides-xml-presentation-slide-create.md) - 添加幻灯片页面
|
||||
|
||||
@@ -106,5 +106,5 @@ lark-cli slides xml_presentation.slide get --as user --params '{
|
||||
|
||||
- [slides +replace-slide](lark-slides-replace-slide.md) — 块级替换 shortcut(推荐)
|
||||
- [xml_presentation.slide replace](lark-slides-xml-presentation-slide-replace.md) — 底层 replace API 参考
|
||||
- [xml_presentations get](lark-slides-xml-presentations-get.md) — 读整个 PPT
|
||||
- [slides +xml-get](lark-slides-xml-get.md) — 读整个 PPT 并保存到本地文件
|
||||
- [lark-slides-edit-workflows.md](lark-slides-edit-workflows.md) — 读-改-写闭环
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
读取飞书幻灯片(PPT)演示文稿的完整 XML 内容信息。
|
||||
|
||||
## 命令
|
||||
## 底层原生命令形态
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '<json_params>'
|
||||
@@ -35,19 +35,22 @@ lark-cli slides xml_presentations get --as user --params '<json_params>'
|
||||
### 基础示例
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id":"slides_example_presentation_id"}'
|
||||
lark-cli slides xml_presentations get --as user \
|
||||
--params '{"xml_presentation_id":"slides_example_presentation_id","revision_id":-1}'
|
||||
```
|
||||
|
||||
### 结合 jq 格式化输出
|
||||
### 指定版本读取
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id":"slides_example_presentation_id"}' | jq -r '.data.xml_presentation.content'
|
||||
lark-cli slides xml_presentations get --as user \
|
||||
--params '{"xml_presentation_id":"slides_example_presentation_id","revision_id":10}'
|
||||
```
|
||||
|
||||
### 保存到文件
|
||||
### 移除 XML id 属性后读取
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id":"slides_example_presentation_id"}' > presentation_data.json
|
||||
lark-cli slides xml_presentations get --as user \
|
||||
--params '{"xml_presentation_id":"slides_example_presentation_id","revision_id":-1,"remove_attr_id":true}'
|
||||
```
|
||||
|
||||
## 返回值
|
||||
@@ -86,10 +89,9 @@ lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id"
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **执行前必做**: 使用 `lark-cli schema slides.xml_presentations.get` 查看最新的参数结构
|
||||
1. 直接调用底层 API 前,使用 `lark-cli schema slides.xml_presentations.get` 查看最新的参数结构
|
||||
2. 返回的 XML 在 `data.xml_presentation.content` 字段中
|
||||
3. 如果只需要部分信息,可以使用 `jq` 等工具过滤返回结果
|
||||
4. 建议将获取的 XML 保存为文件,便于后续编辑或备份
|
||||
|
||||
## 相关命令
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
4. 写入 `.lark-slides/plan/<deck-or-task-id>/slide_plan.json`。
|
||||
5. 读取 `xml-schema-quick-ref.md`、`visual-planning.md` 和 `asset-planning.md`。
|
||||
6. 按 plan、visual planning 和 asset planning 规则逐页生成 XML,把 `layout_type`、`visual_focus`、`text_density` 转成具体页面几何和文本量约束,并把缺失素材转成可执行兜底视觉。
|
||||
7. 创建 PPT 后用 `xml_presentations.get` 回读,核对页面数量、关键元素和 plan 到 XML 的对应关系。
|
||||
7. 创建 PPT 后用 `slides +xml-get` 回读,核对页面数量、关键元素和 plan 到 XML 的对应关系。
|
||||
|
||||
## Plan Path
|
||||
|
||||
@@ -119,6 +119,34 @@ Each slide must include:
|
||||
- `text_density`: `low`, `medium`, or `high`.
|
||||
- `speaker_intent`: why the speaker needs this page and how it advances the story.
|
||||
|
||||
Optional slide fields:
|
||||
|
||||
- `chart_contract`: required when the page plan includes a standard data chart that `<chart>` supports. Use this shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"chart_contract": {
|
||||
"required": true,
|
||||
"render_as": "native_chart",
|
||||
"chart_type": "line",
|
||||
"data_source": "mock_placeholder",
|
||||
"data_series_required": true,
|
||||
"placeholder_label_required": true,
|
||||
"manual_shape_fallback_allowed": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When `chart_contract.required == true`, XML generation must produce a `<chart>` element on that slide. A shape, line, polyline, or whiteboard approximation does not satisfy the plan.
|
||||
|
||||
`data_source` must be one of:
|
||||
|
||||
- `user_provided`: the user supplied concrete values, tables, CSV, or metric lists; use them and do not replace them with mock data.
|
||||
- `mock_placeholder`: the user asked for a placeholder, template, example, or later-replaceable chart position; use mock data in native `<chart>`.
|
||||
- `mock_required_by_intent`: the user did not provide concrete values but asked for data expression, charts, trends, comparisons, or distributions; use mock data in native `<chart>`.
|
||||
|
||||
`data_series_required` means the generated XML must include `<chartData>`. It does not require user-provided real-world values. When real values are unavailable but chart expression is part of the user's intent, write mock or placeholder values into native `<chart>` and label them clearly instead of switching to manual drawing primitives or metric blocks.
|
||||
|
||||
## Layout Vocabulary
|
||||
|
||||
Use one of these `layout_type` values unless the user explicitly needs a custom structure:
|
||||
@@ -183,6 +211,7 @@ Use an object for one planned asset, an array for multiple real needs, or `asset
|
||||
- `purpose`: why this asset helps the page's key message.
|
||||
- `suggested_query`: short future lookup hint only; do not execute it unless separately requested.
|
||||
- `fallback_if_missing`: concrete XML-native visual plan using shapes, labels, tables, whiteboard diagrams, or placeholder panels.
|
||||
- `chart_contract`: when `asset_type` is `chart` and the visual is a supported standard data chart, set this optional slide-level field so generation is locked to native `<chart>`.
|
||||
|
||||
For detailed rules and examples, read `asset-planning.md`.
|
||||
|
||||
@@ -190,7 +219,7 @@ Good examples:
|
||||
|
||||
- `{"asset_type":"architecture_diagram","purpose":"Explain component relationships.","suggested_query":"service architecture diagram","fallback_if_missing":"Draw a component diagram with grouped boxes, connector arrows, and short labels."}`
|
||||
- `{"asset_type":"logo","purpose":"Identify the customer context.","suggested_query":"customer logo","fallback_if_missing":"Use a text label in a small badge."}`
|
||||
- `{"asset_type":"chart","purpose":"Show adoption trend.","suggested_query":"monthly adoption trend chart","fallback_if_missing":"Draw a simple trend line chart with axis labels and data points."}`
|
||||
- `{"asset_type":"chart","purpose":"Show adoption trend.","suggested_query":"monthly adoption trend chart","fallback_if_missing":"Render a native `<chart>` using the provided series when available; otherwise render a native `<chart>` with mock placeholder values and label it as 模拟数据,仅占位,待替换真实数据."}`
|
||||
|
||||
## XML Generation Contract
|
||||
|
||||
@@ -201,6 +230,7 @@ Before writing each slide XML, map the plan fields to concrete decisions:
|
||||
- `visual_focus` determines the largest visual region or emphasized object.
|
||||
- `text_density` caps visible text volume.
|
||||
- `asset_need` informs placeholder diagrams, icons, charts, screenshots, or shape-based fallback visuals only. Missing real assets must use `fallback_if_missing`, not blank regions.
|
||||
- `chart_contract` locks supported standard data charts to native `<chart>` output. Manual approximations are allowed only when the planned chart type is unsupported by `<chart>` or when the visual is explicitly non-data/decorative.
|
||||
|
||||
After creating the PPT, fetch the presentation and verify:
|
||||
|
||||
|
||||
1
skills/lark-slides/references/slides_chart_demo.xml
Normal file
1
skills/lark-slides/references/slides_chart_demo.xml
Normal file
File diff suppressed because one or more lines are too long
@@ -1,226 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<presentation xmlns="http://www.larkoffice.com/sml/2.0" height="540" width="960">
|
||||
<title>制造端智能升级</title>
|
||||
<theme>
|
||||
<textStyles>
|
||||
<headline fontColor="rgb(255,255,255)" fontFamily="思源黑体" fontSize="36"/>
|
||||
<sub-headline fontColor="rgb(229,231,235)" fontFamily="思源黑体" fontSize="20"/>
|
||||
<body fontColor="rgb(229,231,235)" fontFamily="思源黑体" fontSize="16"/>
|
||||
</textStyles>
|
||||
</theme>
|
||||
<slide>
|
||||
<style>
|
||||
<fill>
|
||||
<fillColor color="linear-gradient(180deg, rgb(47, 79, 79) 0%, rgb(26, 26, 26) 100%)"/>
|
||||
</fill>
|
||||
</style>
|
||||
<data>
|
||||
<shape height="36" rotation="0" topLeftX="48" topLeftY="40" type="text" width="300">
|
||||
<content>
|
||||
<p>
|
||||
<strong>
|
||||
<span color="rgb(255, 215, 0)" fontFamily="黑体" fontSize="28">时代背景</span>
|
||||
</strong>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="200" rotation="0" topLeftX="48" topLeftY="85" type="rect" width="864">
|
||||
<fill>
|
||||
<fillColor color="rgba(0,0,0,0.2)"/>
|
||||
</fill>
|
||||
</shape>
|
||||
<img alpha="0.4" alt="十月革命场景" height="180" rotation="0" src="https://example.com/images/scene-1.png" topLeftX="48" topLeftY="95" width="288">
|
||||
<crop type="rect"/>
|
||||
</img>
|
||||
<img alpha="0.4" alt="列宁演讲油画" height="180" rotation="0" src="https://example.com/images/scene-2.png" topLeftX="336" topLeftY="95" width="288">
|
||||
<crop type="rect"/>
|
||||
</img>
|
||||
<img alpha="0.4" alt="十月革命战斗场面" height="180" rotation="0" src="https://example.com/images/scene-3.png" topLeftX="624" topLeftY="95" width="288">
|
||||
<crop type="rect"/>
|
||||
</img>
|
||||
<shape height="2" rotation="0" topLeftX="90" topLeftY="180" type="rect" width="780">
|
||||
<fill>
|
||||
<fillColor color="rgba(255, 215, 0, 0.3)"/>
|
||||
</fill>
|
||||
</shape>
|
||||
<shape height="10" rotation="0" topLeftX="120" topLeftY="176" type="ellipse" width="10">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
<border color="rgb(255, 215, 0)" width="1"/>
|
||||
</shape>
|
||||
<shape height="24" rotation="0" topLeftX="60" topLeftY="140" type="text" width="200">
|
||||
<content>
|
||||
<p textAlign="center">
|
||||
<strong>
|
||||
<span color="rgb(255, 215, 0)" fontFamily="黑体" fontSize="20">1917</span>
|
||||
</strong>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="22" rotation="0" topLeftX="60" topLeftY="200" type="text" width="200">
|
||||
<content>
|
||||
<p textAlign="center">
|
||||
<span color="rgb(230, 230, 230)" fontFamily="宋体" fontSize="16">十月革命</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="40" rotation="0" topLeftX="60" topLeftY="225" type="text" width="200">
|
||||
<content verticalAlign="top">
|
||||
<p textAlign="center">
|
||||
<span color="rgb(156, 163, 175)" fontSize="12">沙皇专制终结,苏维埃政权建立</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="10" rotation="0" topLeftX="475" topLeftY="176" type="ellipse" width="10">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
<border color="rgb(255, 215, 0)" width="1"/>
|
||||
</shape>
|
||||
<shape height="24" rotation="0" topLeftX="380" topLeftY="140" type="text" width="200">
|
||||
<content>
|
||||
<p textAlign="center">
|
||||
<strong>
|
||||
<span color="rgb(255, 215, 0)" fontFamily="黑体" fontSize="20">1920s</span>
|
||||
</strong>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="22" rotation="0" topLeftX="380" topLeftY="200" type="text" width="200">
|
||||
<content>
|
||||
<p textAlign="center">
|
||||
<span color="rgb(230, 230, 230)" fontFamily="宋体" fontSize="16">国内战争</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="40" rotation="0" topLeftX="380" topLeftY="225" type="text" width="200">
|
||||
<content verticalAlign="top">
|
||||
<p textAlign="center">
|
||||
<span color="rgb(156, 163, 175)" fontSize="12">革命与反革命的残酷斗争</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="10" rotation="0" topLeftX="830" topLeftY="176" type="ellipse" width="10">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
<border color="rgb(255, 215, 0)" width="1"/>
|
||||
</shape>
|
||||
<shape height="24" rotation="0" topLeftX="740" topLeftY="140" type="text" width="200">
|
||||
<content>
|
||||
<p textAlign="center">
|
||||
<strong>
|
||||
<span color="rgb(255, 215, 0)" fontFamily="黑体" fontSize="20">1930s</span>
|
||||
</strong>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="22" rotation="0" topLeftX="740" topLeftY="200" type="text" width="200">
|
||||
<content>
|
||||
<p textAlign="center">
|
||||
<span color="rgb(230, 230, 230)" fontFamily="宋体" fontSize="16">社会主义建设</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="40" rotation="0" topLeftX="740" topLeftY="225" type="text" width="200">
|
||||
<content verticalAlign="top">
|
||||
<p textAlign="center">
|
||||
<span color="rgb(156, 163, 175)" fontSize="12">新经济政策与工业化探索</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="1" rotation="0" topLeftX="48" topLeftY="300" type="rect" width="864">
|
||||
<fill>
|
||||
<fillColor color="rgba(255, 215, 0, 0.2)"/>
|
||||
</fill>
|
||||
</shape>
|
||||
<shape height="24" rotation="0" topLeftX="48" topLeftY="320" type="text" width="280">
|
||||
<content>
|
||||
<p>
|
||||
<span color="rgb(230, 230, 230)" fontFamily="宋体" fontSize="18">作者:奥斯特洛夫斯基</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<icon height="16" iconType="iconpark/Peoples/user.svg" topLeftX="52" topLeftY="360" width="16">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
</icon>
|
||||
<shape height="20" topLeftX="76" topLeftY="358" type="text" width="260">
|
||||
<content verticalAlign="middle">
|
||||
<p>
|
||||
<span color="rgb(209, 213, 219)" fontSize="13">工人家庭出身,投身革命浪潮</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<icon height="16" iconType="iconpark/Sports/torch.svg" topLeftX="52" topLeftY="390" width="16">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
</icon>
|
||||
<shape height="20" topLeftX="76" topLeftY="388" type="text" width="260">
|
||||
<content verticalAlign="middle">
|
||||
<p>
|
||||
<span color="rgb(209, 213, 219)" fontSize="13">战场负伤致残,生命陷入黑暗</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<icon height="16" iconType="iconpark/Health/first-aid-kit.svg" topLeftX="52" topLeftY="420" width="16">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
</icon>
|
||||
<shape height="20" topLeftX="76" topLeftY="418" type="text" width="260">
|
||||
<content verticalAlign="middle">
|
||||
<p>
|
||||
<span color="rgb(209, 213, 219)" fontSize="13">全身瘫痪、双目失明</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<icon height="16" iconType="iconpark/Edit/edit.svg" topLeftX="52" topLeftY="450" width="16">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
</icon>
|
||||
<shape height="20" topLeftX="76" topLeftY="448" type="text" width="260">
|
||||
<content verticalAlign="middle">
|
||||
<p>
|
||||
<span color="rgb(209, 213, 219)" fontSize="13">以文学为武器,口述完成创作</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<img alt="奥斯特洛夫斯基青年时期" height="213" rotation="0" src="https://example.com/images/ostrovsky.png" topLeftX="360" topLeftY="320" width="160">
|
||||
<border color="rgba(255, 215, 0, 0.5)" width="2"/>
|
||||
<crop type="rect"/>
|
||||
</img>
|
||||
<shape height="24" rotation="0" topLeftX="552" topLeftY="320" type="text" width="360">
|
||||
<content>
|
||||
<p>
|
||||
<span color="rgb(230, 230, 230)" fontFamily="宋体" fontSize="18">创作动机</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape height="16" rotation="0" topLeftX="552" topLeftY="350" type="rect" width="2">
|
||||
<fill>
|
||||
<fillColor color="rgb(196, 30, 58)"/>
|
||||
</fill>
|
||||
</shape>
|
||||
<shape height="120" rotation="0" topLeftX="562" topLeftY="350" type="text" width="350">
|
||||
<content lineSpacing="multiple:1.6" verticalAlign="top">
|
||||
<p>
|
||||
<span color="rgb(209, 213, 219)" fontSize="13">在双目失明、全身瘫痪的逆境中,奥斯特洛夫斯基以自身经历为蓝本,用顽强的意志口述完成了这部不朽巨著。他将文学创作视为生命的延续和战斗的武器,旨在通过保尔·柯察金的形象,向青年一代传递坚不可摧的革命信念和超越个人痛苦的崇高人生价值观。</span>
|
||||
</p>
|
||||
</content>
|
||||
</shape>
|
||||
</data>
|
||||
<note>
|
||||
<content>
|
||||
<p>各位好,这一页将我们带回《钢铁是怎样炼成的》这部巨著诞生的波澜壮阔的时代。</p>
|
||||
<p>上半部分展示了从1917年十月革命到1930年代苏联社会主义建设的宏大历史画卷。这是一个充满剧烈社会变革和残酷斗争的年代,也是英雄主义和理想主义精神熊熊燃烧的年代。正是这样的背景,孕育了小说的灵魂。</p>
|
||||
<p>下半部分,我们聚焦于作者奥斯特洛夫斯基的个人经历。他的一生,本身就是一部比小说更震撼人心的传奇。从投身革命的青年,到因伤致残的战士,再到与命运抗争的文学巨匠。他的创作动机源于自身不屈的战斗精神,他希望用保尔的故事激励后人,在任何困境中都不要放弃理想,要将有限的生命投入到无限的为人类解放而斗争的事业中去。</p>
|
||||
<p>通过了解这段历史和作者的生平,我们能更深刻地理解《钢铁是怎样炼成的》这部作品的伟大之处。</p>
|
||||
</content>
|
||||
</note>
|
||||
</slide>
|
||||
</presentation>
|
||||
@@ -3018,7 +3018,7 @@
|
||||
|
||||
子元素(mermaid 与 svg 二选一):
|
||||
- mermaid: Mermaid 源码文本, 可使用 CDATA 包裹
|
||||
适用场景: 流程图、时序图、思维导图、类图、甘特图、饼图等结构化图表
|
||||
适用场景: 流程图、时序图、思维导图、类图、甘特图、ER 图、用户旅程等结构图
|
||||
特点: 用简短的文本声明描述图表逻辑, 由渲染引擎自动布局, 无需手动计算坐标
|
||||
示例: <mermaid><![CDATA[flowchart TD\n A[开始] --> B[结束]]]></mermaid>
|
||||
- svg: SVG 内容
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
遇到 `invalid param`、某一页创建失败、页面空白或布局错乱时,按顺序处理:
|
||||
|
||||
1. 记录 `xml_presentation_id`,不要假设失败代表什么都没创建。
|
||||
2. 用 `xml_presentations.get` 回读,确认是否已有部分页面写入。
|
||||
2. 用 `slides +xml-get` 回读,确认是否已有部分页面写入。
|
||||
3. 检查失败页是否含未转义字符:`Q&A -> Q&A`,文本 `<` / `>` 写成 `<` / `>`,属性 URL `a=1&b=2 -> a=1&b=2`。
|
||||
4. 检查标签闭合、属性引号、`<content>` 结构,以及 `<slide>` 直接子元素。
|
||||
5. 页面空白、溢出、重叠或越界时,按 [validation-checklist.md](validation-checklist.md) 运行 XML 文本重叠检查,并人工核对越界、截断、图文压盖等视觉风险;工具当前只会报告 `xml_not_well_formed` / `bbox_overlap`。
|
||||
@@ -46,14 +46,14 @@
|
||||
| 400 XML 格式错误 | XML 语法错误 | 检查标签闭合、属性引号、特殊字符转义 |
|
||||
| 400 请求包装错误 | `--data` 未按 schema 包装 | 检查是否传入 `xml_presentation.content` 或 `slide.content` |
|
||||
| 创建成功但页面空白 / 内容缺失 / 布局错乱 | 常见于 `--slides '[...]'` 的 shell 转义或长参数传递问题 | 改用两步创建,并在创建后立即读取 XML 验证 |
|
||||
| 403 权限不足 | 身份或 scope 不匹配 | 先检查是否误用了 bot 身份,再确认 scope 和文档权限 |
|
||||
| 403 权限不足 | scope 或文档权限不匹配 | 确认 scope 和文档权限;无权限时根据错误响应引导用户解决 |
|
||||
| 404 演示文稿不存在 | `xml_presentation_id` 不正确或无权限 | 检查 token;wiki URL 需先解析真实 `obj_token` |
|
||||
| 404 幻灯片不存在 | `slide_id` 不正确 | 重新读取 presentation 或 slide,确认最新 ID |
|
||||
| 400 无法删除唯一幻灯片 | 演示文稿至少保留一页 | 先创建新页,再删除旧页 |
|
||||
| 1061002 媒体上传 params error | slides 媒体上传参数不符合约定 | 用 `slides +media-upload`,不要手拼原生 `medias/upload_all`;slides 唯一可用 `parent_type` 是 `slide_file` |
|
||||
| 1061004 forbidden | 当前身份对演示文稿无编辑权限 | 确认 user/bot 对目标 PPT 有编辑权限;bot 常见于 PPT 非该 bot 创建 |
|
||||
| 1061004 forbidden | 当前用户对演示文稿无编辑权限 | 确认当前用户对目标 PPT 有编辑权限 |
|
||||
| 3350001 | XML 非 well-formed、XML 结构不符合服务端要求,或 replace 片段问题 | 优先检查未转义字符;replace 场景再看 `block_id` 和 `<content/>` |
|
||||
| 3350002 | `revision_id` 大于当前版本 | 用 `-1` 取当前版本,或重新读 `xml_presentations.get` 取最新 `revision_id` |
|
||||
| 3350002 | `revision_id` 大于当前版本 | 用 `-1` 取当前版本,或重新用 `slides +xml-get` 取最新 `revision_id` |
|
||||
| validation: unsafe file path | `--file` 给了绝对路径或上层路径 | `--file` 必须是 CWD 内相对路径;先 `cd` 到素材目录再执行 |
|
||||
|
||||
## Command-Specific References
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
## Required Flow
|
||||
|
||||
1. 记录创建或编辑返回的 `xml_presentation_id`,以及已知的 `slide_id` / `revision_id`。
|
||||
2. 用 `xml_presentations.get` 回读全文 XML。
|
||||
2. 用 `slides +xml-get` 回读全文 XML 到本地文件。
|
||||
3. 检查实际页数是否符合计划或用户要求。
|
||||
4. 检查每页 `<data>` 内是否有预期主要元素。
|
||||
5. 检查没有明显空白页、破损页、缺失标题或缺失主视觉。
|
||||
@@ -19,13 +19,15 @@
|
||||
回读命令:
|
||||
|
||||
```bash
|
||||
lark-cli slides xml_presentations get --as user \
|
||||
--params '{"xml_presentation_id":"YOUR_ID"}'
|
||||
lark-cli slides +xml-get --as user \
|
||||
--presentation "YOUR_ID" \
|
||||
--output .lark-slides/plan/<deck-or-task-id>/readback.xml \
|
||||
--json
|
||||
```
|
||||
|
||||
## Automated XML Text Overlap Lint
|
||||
|
||||
回读 XML 保存到本地文件后,优先运行 XML 语法和文本重叠静态检查:
|
||||
`slides +xml-get` 保存 XML 到本地文件后,优先运行 XML 语法和文本重叠静态检查:
|
||||
|
||||
```bash
|
||||
python3 skills/lark-slides/scripts/xml_text_overlap_lint.py --input <presentation.xml>
|
||||
@@ -101,7 +103,7 @@ python3 skills/lark-slides/scripts/xml_text_overlap_lint.py --input <presentatio
|
||||
|
||||
```text
|
||||
验证记录:
|
||||
- 回读:已执行 xml_presentations.get,实际页数 N / 预期 N。
|
||||
- 回读:已执行 slides +xml-get,实际页数 N / 预期 N。
|
||||
- 关键页:架构解释 / Self-Attention / 对比或演进 / 总结页均存在。
|
||||
- 结构:检查了主要 shape/img/table/chart 元素,无明显空白页或破损页。
|
||||
- 布局:检查了标题层级、主视觉、重叠/越界/文本溢出风险。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
新建演示文稿或大幅改写页面时,在 `slide_plan.json` 完成后、生成 XML 前读取本文件。目标是让 `layout_type`、`visual_focus`、`text_density` 变成实际页面几何,而不是只写在 plan 里。
|
||||
|
||||
默认画布按 `960 x 540` 规划。已有页面回读 XML 可以影响具体坐标,但不能覆盖这些原则:页面要有主视觉区域、文本要受密度约束、不同 `layout_type` 必须产生明显不同的坐标结构。
|
||||
默认画布按 `960 x 540` 规划。模板 XML 可以覆盖具体坐标,但不能覆盖这些原则:页面要有主视觉区域、文本要受密度约束、不同 `layout_type` 必须产生明显不同的坐标结构。
|
||||
|
||||
## Core Rules
|
||||
|
||||
@@ -131,6 +131,7 @@ Purpose: make one metric or fact memorable.
|
||||
|
||||
Geometry:
|
||||
- Reserve the largest object for the metric: font size often `64-110`, region at least `300 x 120`.
|
||||
- Set `autoFit="normal-auto-fit"` on the metric's `<content>` so an oversized number shrinks to fit its box instead of overflowing.
|
||||
- Pair the number with one explanation and optional 2-3 small supporting labels.
|
||||
- Do not bury the number in a bullet list or small card.
|
||||
|
||||
@@ -168,7 +169,7 @@ Text:
|
||||
|
||||
Purpose: explain components, dependencies, or system flow.
|
||||
|
||||
Implementation: prefer `<whiteboard>` (see `lark-slides-whiteboard.md`); use `<shape>` + `<line>` only as fallback.
|
||||
Implementation: prefer Mermaid `<whiteboard>` (see `lark-slides-whiteboard.md`); use `<shape>` + `<line>` as fallback.
|
||||
|
||||
Geometry:
|
||||
- Main visual area should be a diagram, not prose.
|
||||
@@ -184,7 +185,7 @@ Text:
|
||||
|
||||
Purpose: show operational steps, workflow, or cause-effect path.
|
||||
|
||||
Implementation: prefer `<whiteboard>` (see `lark-slides-whiteboard.md`); use `<shape>` + `<line>` only as fallback.
|
||||
Implementation: prefer Mermaid `<whiteboard>` (see `lark-slides-whiteboard.md`); use `<shape>` + `<line>` as fallback.
|
||||
|
||||
Geometry:
|
||||
- Use numbered steps connected by arrows or lines.
|
||||
|
||||
46
skills/lark-slides/references/visual-styles.md
Normal file
46
skills/lark-slides/references/visual-styles.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# 特殊视觉风格
|
||||
|
||||
当用户明确点名以下某种风格时,本文对应小节的规格**优先于** `visual-planning.md` 的默认审美设定;仍需遵守画布 960×540、留白、文字不溢出等硬约束。颜色一律用 `rgba(R,G,B,A)`,深浅背景都友好。
|
||||
|
||||
适用触发:用户说“咨询风 / 麦肯锡风 / BCG 风 / 战略咨询风 / 数据报告风”,或“豆包风 / doubao 风 / 豆包 PPT 那种”,或直接贴出属于这两类风格的参考图/链接。
|
||||
|
||||
---
|
||||
|
||||
## 咨询风(McKinsey / BCG 战略咨询)
|
||||
|
||||
要求:一张专业、高密度的咨询演示幻灯片,设计风格需融合顶尖战略咨询公司(麦肯锡/BCG)的风格与高端出版物的美学。
|
||||
|
||||
核心内容与布局:
|
||||
- 丰富的数据可视化:幻灯片需填充复杂、精确的图表(堆叠柱状图、瀑布图或折线图)以及包含行和列的详细数据表。
|
||||
- 结构化框架:包含战略图表或由细致、简洁线条构成的 2x2 矩阵。
|
||||
- 高信息密度:布局精致且采用多栏设计,模仿真实的商业分析文稿,而非仅仅是一个空白的封面页。
|
||||
|
||||
视觉风格:
|
||||
- 美学:科技极简主义,但信息承载量大。风格干净、锐利且具权威感。
|
||||
- 字体:主标题使用衬线体(如 Times New Roman),以营造高级财务报告的质感;图表标签和数据数字使用简洁的无衬线体。
|
||||
- 配色:纯白背景。文字为清晰的黑色。图表和图形装饰使用深皇家蓝(Deep Royal Blue)和不同深浅的灰色来体现数据层级。
|
||||
- 图形:表格使用极细的边框线,图表使用精确的矢量线条。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 豆包风(豆包数据卡片)
|
||||
|
||||
要求:一张信息密度巨高的图文卡片化布局幻灯片,追求充实饱满、图文丰富、可逐行细读的版面。
|
||||
|
||||
核心内容与布局:
|
||||
- **信息密度巨高(至关重要):除封面和分节页外,每个内容页都塞满多张图文卡片,宁可密而满,不要空而疏,不要留白。**
|
||||
- 卡片化布局:方角卡片按多行网格铺满版面(网格数、图文比例按内容变化,避免每页雷同);每个卡片不是短标签,而是“标题 + 完整说明”,像浓缩的分析文稿。
|
||||
- 卡片版式:卡片用窄条点缀(贴任意一边或不加),采用“锚点(语义图标或编号)+ 标题 + 细分隔线(可选)+ 正文”的结构。
|
||||
- 文字卡片:内容页正文量级必须达到 400-600 中文字,分布在 4-12 个卡片,每个文字卡片都塞满文字内容,宁可密而满,不要空而疏。
|
||||
- 图片卡片:内容页必须包含图片卡片,多数内容页目标 1-3 张,图片卡片与文字卡片组成网格,缺少图片卡片时必须用生图工具生成配图补足。
|
||||
- 图标密集镶嵌:文字卡片、列表项和指标旁大量内嵌语义图标(部分放在圆形 / 方形底里)作为视觉锚点,让高密度文字也有图形节奏,而不是成片纯文字块。
|
||||
- 数据驱动:数据页密集使用原生图表(饼图、环形图、柱状、折线、组合),图表常与卡片网格并排成半栏布局(如左图右卡或上表下卡)。
|
||||
- 关键指标突出:KPI 用比正文稍大的数字呈现,不要过大,下方配小字标签与简短解读。
|
||||
- 防文本溢出:所有承载突出信息和密集文字的 `<content>` 必须设置 `autoFit="normal-auto-fit"`,字号会在框内自动缩排以防溢出。
|
||||
|
||||
视觉风格:
|
||||
- 美学:干净、明亮、清爽但信息饱满;纯平无渐变,靠卡片、分隔线和对齐网格在高密度下维持秩序感。
|
||||
- 字体:全篇以无衬线体(思源黑体)为主,封面或关键强调可少量使用衬线体。
|
||||
- 字号:使用偏小的正文字号以容纳更多文字,提高信息密度。
|
||||
- 配色:控制配色数量,避免色彩泛滥导致画面杂乱,1 个主色,1-2 个辅助色,1 个强调色。
|
||||
@@ -1,369 +0,0 @@
|
||||
# XML 格式指南
|
||||
|
||||
本文档基于 [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml) 整理,说明飞书 Slides XML Schema(SML 2.0)的核心结构和常用写法。
|
||||
|
||||
## 基本结构
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<presentation xmlns="http://www.larkoffice.com/sml/2.0" width="960" height="540">
|
||||
<title>演示文稿标题</title>
|
||||
<slide>
|
||||
<style>
|
||||
<fill>
|
||||
<fillColor color="rgb(245, 245, 245)"/>
|
||||
</fill>
|
||||
</style>
|
||||
<data>
|
||||
<shape type="text" topLeftX="80" topLeftY="80" width="800" height="120">
|
||||
<content textType="title">
|
||||
<p>主标题</p>
|
||||
</content>
|
||||
</shape>
|
||||
</data>
|
||||
<note>
|
||||
<content textType="body">
|
||||
<p>这是演讲者备注。</p>
|
||||
</content>
|
||||
</note>
|
||||
</slide>
|
||||
</presentation>
|
||||
```
|
||||
|
||||
## 根元素
|
||||
|
||||
### `<presentation>`
|
||||
|
||||
协议标准写法应带命名空间 `http://www.larkoffice.com/sml/2.0`;当前服务端实现可能兼容不带 `xmlns` 的输入,但不作为协议保证。
|
||||
|
||||
**属性:**
|
||||
|
||||
| 属性 | 类型 | 必需 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `width` | positiveInteger | 是 | 演示文稿宽度,如 `960` |
|
||||
| `height` | positiveInteger | 是 | 演示文稿高度,如 `540` |
|
||||
| `id` | string | 否 | 演示文稿标识 |
|
||||
|
||||
**子元素:**
|
||||
|
||||
| 元素 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `<title>` | 否 | 演示文稿标题 |
|
||||
| `<theme>` | 否 | 全局主题 |
|
||||
| `<slide>` | 是 | 幻灯片页面,至少 1 页,最多 100 页 |
|
||||
|
||||
## 主题
|
||||
|
||||
### `<theme>`
|
||||
|
||||
`<theme>` 当前包含两部分:
|
||||
|
||||
- `<background>`:演示文稿级背景填充
|
||||
- `<textStyles>`:主题文本样式集合
|
||||
|
||||
`<textStyles>` 下可选子元素:
|
||||
|
||||
- `<title>`
|
||||
- `<headline>`
|
||||
- `<sub-headline>`
|
||||
- `<body>`
|
||||
- `<caption>`
|
||||
|
||||
这些元素定义的是主题默认样式,不是页面结构。常用属性:
|
||||
|
||||
| 属性 | 说明 |
|
||||
|------|------|
|
||||
| `fontFamily` | 字体 |
|
||||
| `fontSize` | 字号 |
|
||||
| `fontColor` | 字体颜色 |
|
||||
|
||||
## 幻灯片元素
|
||||
|
||||
### `<slide>`
|
||||
|
||||
单张幻灯片的结构比较严格。
|
||||
|
||||
**属性:**
|
||||
|
||||
| 属性 | 类型 | 必需 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `id` | string | 否 | 幻灯片标识 |
|
||||
|
||||
**直接子元素只有:**
|
||||
|
||||
| 元素 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `<style>` | 否 | 页面样式 |
|
||||
| `<data>` | 否 | 页面元素容器 |
|
||||
| `<note>` | 否 | 演讲者备注 |
|
||||
|
||||
这意味着 `<title>`、`<headline>`、`<body>`、`<caption>` 不能直接放在 `<slide>` 下。
|
||||
|
||||
## 文本内容模型
|
||||
|
||||
### `<content>`
|
||||
|
||||
实际页面文本通常通过 `<content>` 表达,常见位置有:
|
||||
|
||||
- `shape` 内部
|
||||
- `table/td` 内部
|
||||
- `note` 内部
|
||||
|
||||
**常用属性:**
|
||||
|
||||
| 属性 | 说明 |
|
||||
|------|------|
|
||||
| `textType` | `title` / `headline` / `sub-headline` / `body` / `caption` |
|
||||
| `verticalAlign` | 垂直对齐 |
|
||||
| `textAlign` | 水平对齐 |
|
||||
| `lineSpacing` | 行间距 |
|
||||
| `fontSize` | 字号 |
|
||||
| `fontFamily` | 字体 |
|
||||
| `color` | 字体颜色 |
|
||||
| `bold` / `italic` / `underline` / `strikethrough` | 内容级样式 |
|
||||
| `wrap` | 是否自动换行 |
|
||||
|
||||
**可包含的子元素:**
|
||||
|
||||
- `<p>`
|
||||
- `<ul>`
|
||||
- `<ol>`
|
||||
|
||||
### `<p>`
|
||||
|
||||
`<p>` 是段落元素,可混排纯文本和内联标签:
|
||||
|
||||
- `<br/>`
|
||||
- `<strong>`
|
||||
- `<em>`
|
||||
- `<u>`
|
||||
- `<span>`
|
||||
- `<del>`
|
||||
- `<a>`
|
||||
- `<shadow>`
|
||||
- `<outline>`
|
||||
|
||||
示例:
|
||||
|
||||
```xml
|
||||
<content textType="body" textAlign="left">
|
||||
<p>普通文本 <strong>加粗</strong> <em>斜体</em> <a href="https://example.com">链接</a></p>
|
||||
<ul>
|
||||
<li><p>列表项 1</p></li>
|
||||
<li><p>列表项 2</p></li>
|
||||
</ul>
|
||||
</content>
|
||||
```
|
||||
|
||||
## 常用页面元素
|
||||
|
||||
所有页面元素都放在 `<data>` 中。
|
||||
|
||||
### `<shape>`
|
||||
|
||||
`shape` 可表示普通形状,也可表示文本框。文本框推荐使用 `type="text"`。
|
||||
|
||||
```xml
|
||||
<shape type="text" topLeftX="80" topLeftY="80" width="800" height="120">
|
||||
<content textType="title">
|
||||
<p>主标题</p>
|
||||
</content>
|
||||
</shape>
|
||||
```
|
||||
|
||||
```xml
|
||||
<shape type="rect" topLeftX="700" topLeftY="120" width="180" height="120">
|
||||
<fill>
|
||||
<fillColor color="rgba(100, 149, 237, 0.25)"/>
|
||||
</fill>
|
||||
<border color="rgb(100, 149, 237)" width="2"/>
|
||||
</shape>
|
||||
```
|
||||
|
||||
**属性:**
|
||||
|
||||
| 属性 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `type` | 是 | 形状类型,`text` 表示文本框 |
|
||||
| `topLeftX` | 是 | 左上角 X 坐标 |
|
||||
| `topLeftY` | 是 | 左上角 Y 坐标 |
|
||||
| `width` | 是 | 宽度 |
|
||||
| `height` | 是 | 高度 |
|
||||
| `rotation` | 否 | 旋转角度 |
|
||||
| `flipX` / `flipY` | 否 | 翻转 |
|
||||
| `alpha` | 否 | 透明度 |
|
||||
|
||||
**可选子元素:**
|
||||
|
||||
- `<fill>`
|
||||
- `<border>`
|
||||
- `<reflection>`
|
||||
- `<shadow>`
|
||||
- `<content>`
|
||||
|
||||
### `<line>`
|
||||
|
||||
```xml
|
||||
<line startX="100" startY="200" endX="420" endY="200">
|
||||
<border color="rgb(43, 47, 54)" width="2"/>
|
||||
</line>
|
||||
```
|
||||
|
||||
`line` 使用的是 `startX` / `startY` / `endX` / `endY`,不是 `x1` / `y1` / `x2` / `y2`。
|
||||
|
||||
### `<img>`
|
||||
|
||||
```xml
|
||||
<img src="file_token_or_url" topLeftX="100" topLeftY="220" width="320" height="180"/>
|
||||
```
|
||||
|
||||
`img` 使用 `topLeftX` / `topLeftY`,不是 `x` / `y`。
|
||||
|
||||
`src` 只接受两种值:
|
||||
|
||||
| `src` 形式 | 说明 |
|
||||
|---|---|
|
||||
| `file_token`(如 `boxcnXXXXXXXXXXXXXXXXXXXXXX`) | 通过 `slides +media-upload` 上传后返回的 token |
|
||||
| `@<本地路径>`(如 `@./assets/chart.png`) | **仅在 `slides +create --slides` 中可用**:CLI 会自动上传该文件并替换为 file_token |
|
||||
|
||||
> **禁止使用 http(s) 外链 URL**:飞书 slides 渲染端不会代理外链图片,`src="https://..."` 在 PPT 里通常显示破图。要用网图必须先 `curl`/下载到 CWD 内,再走上传流程拿 `file_token`。
|
||||
|
||||
本地图片的两种姿势:
|
||||
|
||||
- **新建带图 PPT**:`+create --slides` 里直接写 `src="@./pic.png"`,CLI 在创空白 PPT 后、加 slides 前自动上传并替换 token
|
||||
- **给已有 PPT 加带图新页**:先 `slides +media-upload --file ./pic.png --presentation $PID` 拿 token,再用 token 写进 `xml_presentation.slide create` 的 XML
|
||||
|
||||
### `<icon>`
|
||||
|
||||
```xml
|
||||
<icon iconType="iconpark/Base/setting.svg" topLeftX="440" topLeftY="220" width="32" height="32"/>
|
||||
```
|
||||
|
||||
### `<table>`
|
||||
|
||||
表格结构为:
|
||||
|
||||
- `<table>`
|
||||
- `<colgroup>` / `<tr>`
|
||||
- `<tr>` 内为 `<td>`
|
||||
- `<td>` 内可放 `<content>`
|
||||
|
||||
### `<chart>`
|
||||
|
||||
图表元素必须至少包含:
|
||||
|
||||
- `<chartPlotArea>`
|
||||
- `<chartData>`
|
||||
|
||||
同时还可以包含:
|
||||
|
||||
- `<chartTitle>`
|
||||
- `<chartSubTitle>`
|
||||
- `<chartStyle>`
|
||||
- `<chartLegend>`
|
||||
- `<chartTooltip>`
|
||||
|
||||
如果要写图表 XML,建议直接以 XSD 为准,不要自行发明更简化的 chart DSL。
|
||||
|
||||
## 样式元素
|
||||
|
||||
### `<fill>`
|
||||
|
||||
```xml
|
||||
<fill>
|
||||
<fillColor color="rgb(100, 149, 237)"/>
|
||||
</fill>
|
||||
```
|
||||
|
||||
### `<border>`
|
||||
|
||||
```xml
|
||||
<border color="rgb(0, 0, 0)" width="2" dashArray="solid"/>
|
||||
```
|
||||
|
||||
### 颜色格式
|
||||
|
||||
```xml
|
||||
<fillColor color="rgb(255, 0, 0)"/>
|
||||
<fillColor color="rgba(255, 0, 0, 0.5)"/>
|
||||
<fillColor color="linear-gradient(90deg, rgb(255,0,0) 0%, rgb(0,0,255) 100%)"/>
|
||||
<fillColor color="radial-gradient(circle at 50% 50%, rgb(255,0,0) 0%, rgb(0,0,255) 100%)"/>
|
||||
```
|
||||
|
||||
## 演讲者备注
|
||||
|
||||
### `<note>`
|
||||
|
||||
```xml
|
||||
<note>
|
||||
<content textType="body">
|
||||
<p>这是演讲者备注内容。</p>
|
||||
</content>
|
||||
</note>
|
||||
```
|
||||
|
||||
## 完整示例
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<presentation xmlns="http://www.larkoffice.com/sml/2.0" width="960" height="540">
|
||||
<title>季度报告</title>
|
||||
<theme>
|
||||
<textStyles>
|
||||
<title fontFamily="思源黑体" fontSize="54" fontColor="rgba(0, 0, 0, 1)"/>
|
||||
<body fontFamily="思源黑体" fontSize="18" fontColor="rgba(43, 47, 54, 1)"/>
|
||||
</textStyles>
|
||||
</theme>
|
||||
<slide>
|
||||
<style>
|
||||
<fill>
|
||||
<fillColor color="rgb(245, 245, 245)"/>
|
||||
</fill>
|
||||
</style>
|
||||
<data>
|
||||
<shape type="text" topLeftX="80" topLeftY="72" width="760" height="100">
|
||||
<content textType="title">
|
||||
<p>2024 年第一季度报告</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape type="text" topLeftX="80" topLeftY="200" width="520" height="180">
|
||||
<content textType="body">
|
||||
<p>核心指标</p>
|
||||
<ul>
|
||||
<li><p>用户增长:+25%</p></li>
|
||||
<li><p>收入增长:+30%</p></li>
|
||||
<li><p>市场份额:15%</p></li>
|
||||
</ul>
|
||||
</content>
|
||||
</shape>
|
||||
<shape type="rect" topLeftX="660" topLeftY="180" width="180" height="140">
|
||||
<fill>
|
||||
<fillColor color="rgba(100, 149, 237, 0.25)"/>
|
||||
</fill>
|
||||
<border color="rgb(100, 149, 237)" width="2"/>
|
||||
</shape>
|
||||
</data>
|
||||
<note>
|
||||
<content textType="body">
|
||||
<p>讲到增长率时补充样本范围。</p>
|
||||
</content>
|
||||
</note>
|
||||
</slide>
|
||||
</presentation>
|
||||
```
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. 始终带上命名空间 `xmlns="http://www.larkoffice.com/sml/2.0"`
|
||||
2. 用 `shape type="text"` + `content` 表达页面文本
|
||||
3. 用 `topLeftX` / `topLeftY`、`startX` / `startY` 等 schema 中定义的属性名
|
||||
4. 优先使用 `rgb` / `rgba` 颜色格式
|
||||
5. 特殊字符按 XML 规则转义
|
||||
6. 标准 16:9 页面建议使用 `width="960"` 和 `height="540"`
|
||||
|
||||
## 参考文档
|
||||
|
||||
- [xml-schema-quick-ref.md](xml-schema-quick-ref.md)
|
||||
- [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml)
|
||||
- [examples.md](examples.md)
|
||||
- [slides_demo.xml](slides_demo.xml)
|
||||
@@ -1,6 +1,6 @@
|
||||
# XML Schema 快速参考
|
||||
|
||||
本文档是 [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml) 的精简版摘要;如果两者不一致,以 XSD 原文为准。
|
||||
本文档是 [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml) 的精简版摘要,并合并了常用 XML 格式写法;如果两者不一致,以 XSD 原文为准。
|
||||
|
||||
## 最重要的规则
|
||||
|
||||
@@ -30,25 +30,31 @@
|
||||
|
||||
| 属性 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `width` | 是 | 演示文稿宽度,正整数 |
|
||||
| `height` | 是 | 演示文稿高度,正整数 |
|
||||
| `width` | 是 | 演示文稿宽度,正整数,标准 16:9 页面建议使用 `960` |
|
||||
| `height` | 是 | 演示文稿高度,正整数,标准 16:9 页面建议使用 `540` |
|
||||
| `id` | 否 | 演示文稿标识 |
|
||||
|
||||
**子元素:** `<title>?`, `<theme>?`, `<slide>+`
|
||||
|
||||
## slide 元素
|
||||
|
||||
| 属性 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `id` | 否 | 幻灯片标识 |
|
||||
|
||||
**子元素:**
|
||||
- `<style>?` - 页面样式,目前可放 `<fill>`
|
||||
- `<data>?` - 页面元素容器,可放 `shape`、`line`、`polyline`、`img`、`table`、`icon`、`chart`、`whiteboard`、`undefined`
|
||||
- `<note>?` - 演讲者备注,内部可放 `<content>`
|
||||
`<slide>` 至少 1 页,最多 100 页。
|
||||
|
||||
## theme 与文本类型
|
||||
|
||||
`<theme>` 当前包含两部分:
|
||||
|
||||
- `<background>`:演示文稿级背景填充
|
||||
- `<textStyles>`:主题文本样式集合
|
||||
|
||||
`<textStyles>` 下可选子元素包括 `<title>`、`<headline>`、`<sub-headline>`、`<body>`、`<caption>`。这些元素定义的是主题默认样式,不是页面结构。
|
||||
|
||||
常用属性:
|
||||
|
||||
| 属性 | 说明 |
|
||||
|------|------|
|
||||
| `fontFamily` | 字体 |
|
||||
| `fontSize` | 字号 |
|
||||
| `fontColor` | 字体颜色 |
|
||||
|
||||
XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出现在:
|
||||
|
||||
- `<theme><textStyles>...</textStyles></theme>` 中,作为主题文本样式
|
||||
@@ -64,6 +70,20 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
| `body` | 16 |
|
||||
| `caption` | 12 |
|
||||
|
||||
## slide 元素
|
||||
|
||||
| 属性 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `id` | 否 | 幻灯片标识 |
|
||||
|
||||
**子元素:**
|
||||
|
||||
- `<style>?` - 页面样式,目前可放 `<fill>`
|
||||
- `<data>?` - 页面元素容器,可放 `shape`、`line`、`polyline`、`img`、`table`、`icon`、`chart`、`whiteboard`、`undefined`
|
||||
- `<note>?` - 演讲者备注,内部可放 `<content>`
|
||||
|
||||
这意味着 `<title>`、`<headline>`、`<body>`、`<caption>` 不能直接放在 `<slide>` 下。
|
||||
|
||||
## content 内容模型
|
||||
|
||||
`<content>` 可出现在 `shape`、`table/td`、`note` 中,常用属性包括:
|
||||
@@ -71,12 +91,14 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
| 属性 | 说明 |
|
||||
|------|------|
|
||||
| `textType` | `title` / `headline` / `sub-headline` / `body` / `caption` |
|
||||
| `verticalAlign` | 垂直对齐 |
|
||||
| `textAlign` | 文本对齐方式 |
|
||||
| `lineSpacing` | 行间距,schema 默认 `multiple:1.5` |
|
||||
| `fontSize` | 字号 |
|
||||
| `fontFamily` | 字体 |
|
||||
| `color` | 字体颜色 |
|
||||
| `bold` / `italic` / `underline` / `strikethrough` | 文本样式 |
|
||||
| `bold` / `italic` / `underline` / `strikethrough` | 内容级样式 |
|
||||
| `wrap` | 是否自动换行 |
|
||||
|
||||
`<content>` 的子元素只能是:
|
||||
|
||||
@@ -84,7 +106,21 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
- `<ul>`
|
||||
- `<ol>`
|
||||
|
||||
### content 示例
|
||||
### p 段落与内联标签
|
||||
|
||||
`<p>` 是段落元素,可混排纯文本和内联标签:
|
||||
|
||||
- `<br/>`
|
||||
- `<strong>`
|
||||
- `<em>`
|
||||
- `<u>`
|
||||
- `<span>`
|
||||
- `<del>`
|
||||
- `<a>`
|
||||
- `<shadow>`
|
||||
- `<outline>`
|
||||
|
||||
示例:
|
||||
|
||||
```xml
|
||||
<content textType="body" textAlign="left">
|
||||
@@ -98,8 +134,20 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
|
||||
## data 常用元素
|
||||
|
||||
所有页面元素都放在 `<data>` 中。
|
||||
|
||||
### shape
|
||||
|
||||
`shape` 可表示普通形状,也可表示文本框。文本框推荐使用 `type="text"`。
|
||||
|
||||
```xml
|
||||
<shape type="text" topLeftX="80" topLeftY="80" width="800" height="120">
|
||||
<content textType="title">
|
||||
<p>主标题</p>
|
||||
</content>
|
||||
</shape>
|
||||
```
|
||||
|
||||
```xml
|
||||
<shape type="rect" topLeftX="120" topLeftY="120" width="240" height="120">
|
||||
<fill>
|
||||
@@ -117,6 +165,16 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
| `width` | 是 | 宽度 |
|
||||
| `height` | 是 | 高度 |
|
||||
| `rotation` | 否 | 旋转角度 |
|
||||
| `flipX` / `flipY` | 否 | 翻转 |
|
||||
| `alpha` | 否 | 透明度 |
|
||||
|
||||
可选子元素:
|
||||
|
||||
- `<fill>`
|
||||
- `<border>`
|
||||
- `<reflection>`
|
||||
- `<shadow>`
|
||||
- `<content>`
|
||||
|
||||
### line
|
||||
|
||||
@@ -126,14 +184,23 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
</line>
|
||||
```
|
||||
|
||||
`line` 使用的是 `startX` / `startY` / `endX` / `endY`,不是 `x1` / `y1` / `x2` / `y2`。
|
||||
|
||||
### img
|
||||
|
||||
```xml
|
||||
<img src="file_token_or_url" topLeftX="80" topLeftY="120" width="320" height="180"/>
|
||||
```
|
||||
|
||||
`img` 使用 `topLeftX` / `topLeftY`,不是 `x` / `y`。
|
||||
|
||||
`src` 只支持:`slides +media-upload` 返回的 `file_token`,或 `@<本地路径>` 占位符(仅 `+create --slides` 自动上传并替换)。**禁止使用 http(s) 外链 URL**——飞书 slides 渲染端不会代理外链图,外链 src 在 PPT 里通常不显示。本地图片详见 [lark-slides-create.md](lark-slides-create.md#本地图片path-占位符) / [lark-slides-media-upload.md](lark-slides-media-upload.md)。
|
||||
|
||||
本地图片的两种姿势:
|
||||
|
||||
- 新建带图 PPT:`+create --slides` 里直接写 `src="@./pic.png"`,CLI 在创空白 PPT 后、加 slides 前自动上传并替换 token
|
||||
- 给已有 PPT 加带图新页:先 `slides +media-upload --file ./pic.png --presentation $PID` 拿 token,再用 token 写进 `xml_presentation.slide create` 的 XML
|
||||
|
||||
> **注意**:`width`/`height` 是**裁剪后**的显示尺寸。比例和原图不一致时会自动裁剪(无法靠属性关闭),想避免裁剪就让 `width:height` 对齐原图比例。
|
||||
|
||||
### icon
|
||||
@@ -144,10 +211,85 @@ XSD 中的 `title`、`headline`、`sub-headline`、`body`、`caption` 主要出
|
||||
|
||||
`iconType` 必须来自已验证的 IconPark 路径。需要语义图标时,先运行 `scripts/iconpark_tool.py search --query "<语义>"`,不要凭记忆拼路径。更多规则见 [iconpark.md](iconpark.md)。
|
||||
|
||||
### table
|
||||
|
||||
表格结构为:
|
||||
|
||||
- `<table>`
|
||||
- `<colgroup>` / `<tr>`
|
||||
- `<tr>` 内为 `<td>`
|
||||
- `<td>` 内可放 `<content>`
|
||||
|
||||
### chart
|
||||
|
||||
图表元素必须至少包含:
|
||||
|
||||
- `<chartPlotArea>`
|
||||
- `<chartData>`
|
||||
|
||||
同时还可以包含:
|
||||
|
||||
- `<chartTitle>`
|
||||
- `<chartSubTitle>`
|
||||
- `<chartStyle>`
|
||||
- `<chartLegend>`
|
||||
- `<chartTooltip>`
|
||||
|
||||
完整图表类型覆盖示例见 [slides_chart_demo.xml](slides_chart_demo.xml),其中包含柱状、条形、折线、面积、饼 / 环、雷达等原生 `<chart>` 示例,以及散点、气泡、漏斗、帕累托、瀑布等 `<whiteboard>` SVG 图表示例。
|
||||
|
||||
组合图示例:
|
||||
|
||||
```xml
|
||||
<chart width="556" height="350" topLeftX="42" topLeftY="132">
|
||||
<chartPlotArea>
|
||||
<chartPlot type="combo">
|
||||
<chartExtra/>
|
||||
<chartSeriesList>
|
||||
<chartSeries index="1" comboType="column"/>
|
||||
<chartSeries index="2" comboType="line" yAxisPosition="right">
|
||||
<chartTooltip format="0%"/>
|
||||
</chartSeries>
|
||||
</chartSeriesList>
|
||||
</chartPlot>
|
||||
<chartAxes>
|
||||
<chartAxis type="x">
|
||||
<chartLabel fontSize="10"/>
|
||||
</chartAxis>
|
||||
<chartAxis type="y" position="left">
|
||||
<chartGridLine color="rgb(226, 232, 240)"/>
|
||||
<chartLabel fontSize="10"/>
|
||||
</chartAxis>
|
||||
<chartAxis type="y" position="right">
|
||||
<chartLabel fontSize="10" format="0%"/>
|
||||
</chartAxis>
|
||||
</chartAxes>
|
||||
</chartPlotArea>
|
||||
<chartLegend position="bottom" fontSize="11"/>
|
||||
<chartData>
|
||||
<dim1>
|
||||
<chartField name="季度">24Q1,24Q2,24Q3,24Q4,25Q1,25Q2,25Q3,25Q4</chartField>
|
||||
</dim1>
|
||||
<dim2>
|
||||
<chartField name="营收">180,195,210,245,220,238,258,296</chartField>
|
||||
<chartField name="增速">0.08,0.12,0.15,0.18,0.22,0.22,0.23,0.21</chartField>
|
||||
</dim2>
|
||||
</chartData>
|
||||
<chartTitle fontSize="12" color="rgba(15, 30, 58, 1)" bold="true">营收(亿美元, 左轴) · 同比增速(%, 右轴)</chartTitle>
|
||||
<chartStyle>
|
||||
<chartBackground color="rgba(0, 0, 0, 0)"/>
|
||||
<chartBorder color="rgb(222, 224, 227)" width="0"/>
|
||||
<chartColorTheme>
|
||||
<color value="rgb(28, 71, 120)"/>
|
||||
<color value="rgb(240, 129, 54)"/>
|
||||
</chartColorTheme>
|
||||
</chartStyle>
|
||||
</chart>
|
||||
```
|
||||
|
||||
### whiteboard
|
||||
|
||||
```xml
|
||||
<!-- SVG 模式:数据图表、装饰元素 -->
|
||||
<!-- SVG 模式:<chart> 不支持的图表或自定义视觉、装饰元素 -->
|
||||
<whiteboard topLeftX="580" topLeftY="120" width="340" height="280">
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="60" y="80" width="40" height="140" rx="3" fill="rgba(59,130,246,0.85)"/>
|
||||
@@ -231,12 +373,69 @@ Mermaid 模式:内容用 `<![CDATA[...]]>` 包裹,避免 `[`、`>`、`-->`
|
||||
</note>
|
||||
```
|
||||
|
||||
## 完整示例
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<presentation xmlns="http://www.larkoffice.com/sml/2.0" width="960" height="540">
|
||||
<title>季度报告</title>
|
||||
<theme>
|
||||
<textStyles>
|
||||
<title fontFamily="思源黑体" fontSize="54" fontColor="rgba(0, 0, 0, 1)"/>
|
||||
<body fontFamily="思源黑体" fontSize="18" fontColor="rgba(43, 47, 54, 1)"/>
|
||||
</textStyles>
|
||||
</theme>
|
||||
<slide>
|
||||
<style>
|
||||
<fill>
|
||||
<fillColor color="rgb(245, 245, 245)"/>
|
||||
</fill>
|
||||
</style>
|
||||
<data>
|
||||
<shape type="text" topLeftX="80" topLeftY="72" width="760" height="100">
|
||||
<content textType="title">
|
||||
<p>2024 年第一季度报告</p>
|
||||
</content>
|
||||
</shape>
|
||||
<shape type="text" topLeftX="80" topLeftY="200" width="520" height="180">
|
||||
<content textType="body">
|
||||
<p>核心指标</p>
|
||||
<ul>
|
||||
<li><p>用户增长:+25%</p></li>
|
||||
<li><p>收入增长:+30%</p></li>
|
||||
<li><p>市场份额:15%</p></li>
|
||||
</ul>
|
||||
</content>
|
||||
</shape>
|
||||
<shape type="rect" topLeftX="660" topLeftY="180" width="180" height="140">
|
||||
<fill>
|
||||
<fillColor color="rgba(100, 149, 237, 0.25)"/>
|
||||
</fill>
|
||||
<border color="rgb(100, 149, 237)" width="2"/>
|
||||
</shape>
|
||||
</data>
|
||||
<note>
|
||||
<content textType="body">
|
||||
<p>讲到增长率时补充样本范围。</p>
|
||||
</content>
|
||||
</note>
|
||||
</slide>
|
||||
</presentation>
|
||||
```
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. 始终带上命名空间 `xmlns="http://www.larkoffice.com/sml/2.0"`
|
||||
2. 用 `shape type="text"` + `content` 表达页面文本
|
||||
3. 用 `topLeftX` / `topLeftY`、`startX` / `startY` 等 schema 中定义的属性名
|
||||
4. 优先使用 `rgb` / `rgba` 颜色格式;渐变必须使用 `rgba()` 且带百分比停靠点
|
||||
5. 特殊字符按 XML 规则转义
|
||||
6. 标准 16:9 页面建议使用 `width="960"` 和 `height="540"`
|
||||
|
||||
## 详细参考
|
||||
|
||||
- [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml)
|
||||
- [xml-format-guide.md](xml-format-guide.md)
|
||||
- [examples.md](examples.md)
|
||||
- [slides_demo.xml](slides_demo.xml)
|
||||
- [slides_chart_demo.xml](slides_chart_demo.xml)
|
||||
|
||||
## Schema 版本信息
|
||||
|
||||
|
||||
@@ -3,12 +3,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import xml_text_overlap_lint
|
||||
|
||||
|
||||
TEMPLATES_DIR = Path(__file__).resolve().parents[1] / "assets" / "templates"
|
||||
|
||||
|
||||
class XmlTextOverlapLintTest(unittest.TestCase):
|
||||
def assertNoXmlTextOverlapLintIssues(self, result: dict, sample_name: str) -> None:
|
||||
def assertNoXmlTextOverlapLintIssues(self, result: dict, template_path: Path) -> None:
|
||||
issue_summaries = []
|
||||
for slide in result.get("slides", []):
|
||||
for issue in slide.get("issues", []):
|
||||
@@ -21,64 +25,24 @@ class XmlTextOverlapLintTest(unittest.TestCase):
|
||||
self.assertEqual(
|
||||
result["summary"]["error_count"],
|
||||
0,
|
||||
f"{sample_name} has XML text overlap lint errors:\n" + "\n".join(issue_summaries),
|
||||
f"{template_path.name} has XML text overlap lint errors:\n" + "\n".join(issue_summaries),
|
||||
)
|
||||
self.assertEqual(
|
||||
result["summary"]["warning_count"],
|
||||
0,
|
||||
f"{sample_name} has XML text overlap lint warnings:\n" + "\n".join(issue_summaries),
|
||||
f"{template_path.name} has XML text overlap lint warnings:\n" + "\n".join(issue_summaries),
|
||||
)
|
||||
|
||||
def test_xml_text_overlap_lint_accepts_inline_fixture_xml_samples(self) -> None:
|
||||
samples = {
|
||||
"image-led-cover": """
|
||||
<presentation xmlns="http://www.larkoffice.com/sml/2.0" width="960" height="540">
|
||||
<slide xmlns="http://www.larkoffice.com/sml/2.0">
|
||||
<style><fill><fillColor color="rgb(15,23,42)"/></fill></style>
|
||||
<data>
|
||||
<img src="tok" topLeftX="560" topLeftY="0" width="400" height="540"/>
|
||||
<shape type="text" topLeftX="64" topLeftY="150" width="420" height="70">
|
||||
<content textType="title"><p><span fontSize="42">Quarterly Review</span></p></content>
|
||||
</shape>
|
||||
<shape type="text" topLeftX="64" topLeftY="235" width="420" height="36">
|
||||
<content textType="sub-headline"><p><span fontSize="20">Focus, progress, and next steps</span></p></content>
|
||||
</shape>
|
||||
</data>
|
||||
</slide>
|
||||
</presentation>
|
||||
""",
|
||||
"content-grid": """
|
||||
<presentation xmlns="http://www.larkoffice.com/sml/2.0" width="960" height="540">
|
||||
<slide xmlns="http://www.larkoffice.com/sml/2.0">
|
||||
<data>
|
||||
<shape type="text" topLeftX="60" topLeftY="44" width="620" height="46">
|
||||
<content textType="title"><p><span fontSize="30">Execution Snapshot</span></p></content>
|
||||
</shape>
|
||||
<shape type="rect" topLeftX="60" topLeftY="126" width="250" height="150"/>
|
||||
<shape type="text" topLeftX="84" topLeftY="152" width="200" height="36">
|
||||
<content textType="headline"><p><span fontSize="22">Plan</span></p></content>
|
||||
</shape>
|
||||
<shape type="rect" topLeftX="355" topLeftY="126" width="250" height="150"/>
|
||||
<shape type="text" topLeftX="379" topLeftY="152" width="200" height="36">
|
||||
<content textType="headline"><p><span fontSize="22">Build</span></p></content>
|
||||
</shape>
|
||||
<shape type="rect" topLeftX="650" topLeftY="126" width="250" height="150"/>
|
||||
<shape type="text" topLeftX="674" topLeftY="152" width="200" height="36">
|
||||
<content textType="headline"><p><span fontSize="22">Launch</span></p></content>
|
||||
</shape>
|
||||
</data>
|
||||
</slide>
|
||||
</presentation>
|
||||
""",
|
||||
}
|
||||
self.assertTrue(samples)
|
||||
for sample_name, sample_xml in samples.items():
|
||||
with self.subTest(sample=sample_name):
|
||||
def test_xml_text_overlap_lint_accepts_all_template_xml_files(self) -> None:
|
||||
template_paths = sorted(TEMPLATES_DIR.glob("*.xml"))
|
||||
self.assertTrue(template_paths)
|
||||
for template_path in template_paths:
|
||||
with self.subTest(template=template_path.name):
|
||||
result = xml_text_overlap_lint.lint_xml(
|
||||
sample_xml,
|
||||
sample_name,
|
||||
template_path.read_text(encoding="utf-8"),
|
||||
str(template_path),
|
||||
)
|
||||
self.assertNoXmlTextOverlapLintIssues(result, sample_name)
|
||||
self.assertNoXmlTextOverlapLintIssues(result, template_path)
|
||||
|
||||
def test_lint_xml_reports_unescaped_ampersand_in_text(self) -> None:
|
||||
result = xml_text_overlap_lint.lint_xml(
|
||||
|
||||
@@ -46,7 +46,20 @@ lark-cli task +create --summary "Test Task" --dry-run
|
||||
1. Confirm with the user: task summary, due date, assignee, and tasklist if necessary.
|
||||
- **Crucial Rule for Assignee**: If the user explicitly or implicitly says "create a task for me" (给我创建一个任务), or "help me create a task" (帮我新建/创建一个任务), you MUST assign the task to the current logged-in user. You can get the current user's `open_id` by executing `lark-cli auth status` (it already outputs JSON by default, so do not add `--json`) or `lark-cli contact +get-user` first, extracting `.identities.user.openId` (from `auth status`) or `.data.user.open_id` (from `contact +get-user`), and then passing it to the `--assignee` parameter.
|
||||
2. Execute `lark-cli task +create --summary "..." ...`
|
||||
3. Report the result: task ID and summary.
|
||||
3. Judge success by `ok == true` in the stdout JSON (the success envelope has no `code` field — do not test `code == 0`), then report the result: task ID (`data.guid`) and summary.
|
||||
|
||||
Example success response:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"identity": "user",
|
||||
"data": {
|
||||
"guid": "e297d3d0-4b60-4a5f-a4d4-xxxxxxxxxxxx",
|
||||
"url": "https://applink.larkoffice.com/client/todo/detail?guid=e297d3d0-4b60-4a5f-a4d4-xxxxxxxxxxxx"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> This is a **Write Operation** -- You must confirm the user's intent before executing.
|
||||
|
||||
Reference in New Issue
Block a user