* docs(base): document Base attachment download via docs +media-download
Base attachment files must be downloaded via 'lark-cli docs +media-download',
not 'lark-cli drive +download' (which returns HTTP 403). The existing
lark-doc reference already documents the command thoroughly, so this PR
just adds entries to the lark-base skill that reference it.
- SKILL.md: add download row to field classification, routing, and record
commands tables, referencing lark-doc-media-download.md
- references/lark-base-record.md: add download entry to the command
navigation table and notes, referencing lark-doc-media-download.md
* docs: add output flag to base attachment download examples
---------
Co-authored-by: kongenpei <kongenpei@users.noreply.github.com>
- Add `+dashboard-arrange` command that triggers server-side smart layout optimization via POST /open-apis/base/v3/bases/{token}/dashboards/{id}/arrange
- Add `text` block type support for dashboard blocks with Markdown syntax (headers, bold, italic, strikethrough, lists)
- Update `validateBlockDataConfig()` to handle text-specific validation rules
- Update documentation (SKILL.md, lark-base-dashboard.md, dashboard-block-data-config.md, lark-base-dashboard-arrange.md)
- Add comprehensive unit tests for new commands and block type
- [x] Unit tests pass (`go test ./shortcuts/base/...`)
- [x] All dashboard-related tests pass including new `TestBaseDashboardExecuteArrange`
- [x] Text block type validation tests pass
- None
* feat(cmdutil): add shared file upload helpers
Add ParseFileFlag, ValidateFileFlag, and BuildFormdata to support
multipart file upload via --file flag across raw API and meta API commands.
Change-Id: Ib724cf8b055b0b314af11d8d830f38559dac60eb
* feat(api): add --file flag for multipart/form-data file uploads
Add --file flag to `lark-cli api` command enabling file upload via
multipart/form-data. The flag accepts [field=]path format and supports
stdin (-). Includes mutual exclusion validation with --output,
--page-all, and GET method. Dry-run mode shows file metadata instead
of building actual formdata.
Change-Id: Icf34aba5da3a558219a97a583e8f6aa951ded199
* feat(service): add --file flag with auto-detection from metadata
Add file upload support to meta API service method commands. The --file
flag is conditionally registered only for methods whose metadata declares
file-type fields (POST/PUT/PATCH/DELETE). The default field name is
auto-detected from metadata when exactly one file field exists.
Change-Id: Ibbf04eb42341ba11bb1fd9750e63bc1d0eacd08d
* feat(schema): show file upload indicators in method detail display
Add hasFileFields helper to detect file-type fields in requestBody
metadata. Modify printMethodDetail to display [file upload] tag on
--data line, --file flag description with default field name, and
--file <path> in CLI example for methods that accept file uploads.
Change-Id: Iae3bc14fe07e16a8b5f6a50a2b3592d6d8490ed9
* fix: address code review findings for file upload feature
- ParseFileFlag: change idx >= 0 to idx > 0 to prevent empty field name
when input like "=photo.jpg" is passed
- BuildFormdata: read file into bytes.Reader with defer Close to prevent
file handle leak on later errors
- BuildFormdata: remove unused ctx parameter from signature and callers
- Eliminate duplicated dry-run logic by having buildAPIRequest and
buildServiceRequest return FileUploadMeta when in dry-run mode,
removing ~60 lines of copy-pasted URL building and validation code
Change-Id: I27b9534fd0eaefce40390f6e723dd0c04a2cdf80
* fix: address PR review findings
- Remove opts.File=="" guard on dual-stdin check so --file photo.jpg
--params - --data - correctly reports an error instead of silently
dropping --data content (P1 bug in both api.go and service.go)
- Extract shared DetectFileFields into cmdutil, deduplicate
detectFileFields (service.go) and hasFileFields (schema.go)
- Show "<stdin>" instead of empty path in dry-run output for --file -
Change-Id: Iccc5d879165ea6a3d04f0425ec6a5018a10e72e1
* fix: reject non-object --data with --file and improve multi-file schema
- --data with --file now requires a JSON object; arrays/strings/numbers
are rejected with a clear error instead of being silently dropped
- Schema display for multi-file methods shows explicit field=path syntax
and lists valid field names instead of advertising a false default
Change-Id: I0facdb3ad86f68cb125c7ea109a33714fd91dba0
* feat(base): add record batch add/set shortcuts
* docs: clarify record batch add/set input guidance
* docs: mark base shortcut references as required before calling
* fix(base): remove stale token stub calls in batch record tests
* feat(base): rename record batch add/set to create/update
* refactor(base): remove noop record json validators
* test(base): align record validate test with nil hooks
* fix: align base record batch shortcuts with openapi routes
* fix(base): pass parse context for record batch JSON parsing
* docs: move base record batch JSON guidance to tips
* refactor: remove noop record validate
* docs: remove has_more from batch update guide
---------
Co-authored-by: kongenpei <kongenpei@users.noreply.github.com>
* feat(base): add +record-search json passthrough shortcut
* docs(base): refine record-search wording and field constraints
* docs(base): prefer record-list unless keyword is explicit
* refactor(base): inline record-search parsing and align tests
* refactor(base): remove noop record validate hook
* docs(base): unify record example token placeholders
* fix: align record search JSON parsing with parse context
* feat: add help tips for base record search
* docs: refine base record search reference
---------
Co-authored-by: kongenpei <kongenpei@users.noreply.github.com>
* feat(base): add record field filters
* fix(base): align record field filter flags with OpenAPI params
* fix: scope record dry-run field filters and align docs
* docs(base): clarify record-list field_scope priority
* refactor(base): remove field-id from record-get
---------
Co-authored-by: zgz2048 <zhonggangzhi.tim@bytedance.com>
Co-authored-by: kongenpei <kongenpei@users.noreply.github.com>
* fix(keychain): improve error hint for keychain initialization
Clarify the error message for uninitialized keychain by combining both possible scenarios (sandbox/CI environment and normal usage) into a single hint to avoid confusion.
* docs(keychain): improve error message hints for sandbox environments
Add suggestion to try running outside sandbox when keychain access fails. Also update hint for uninitialized keychain case to include same suggestion.
* docs(keychain): fix grammar in error message hints
* docs(keychain): fix typo in error message hint
- Add `+dashboard-arrange` command that triggers server-side smart layout optimization via POST /open-apis/base/v3/bases/{token}/dashboards/{id}/arrange
- Add `text` block type support for dashboard blocks with Markdown syntax (headers, bold, italic, strikethrough, lists)
- Update `validateBlockDataConfig()` to handle text-specific validation rules
- Update documentation (SKILL.md, lark-base-dashboard.md, dashboard-block-data-config.md, lark-base-dashboard-arrange.md)
- Add comprehensive unit tests for new commands and block type
- [x] Unit tests pass (`go test ./shortcuts/base/...`)
- [x] All dashboard-related tests pass including new `TestBaseDashboardExecuteArrange`
- [x] Text block type validation tests pass
- None
Add cmd/diagnose_scope_test.go that exports a JSON snapshot of all API
methods and shortcuts with their minimum-privilege scopes, identity
support, auto-approve status, and scope_priorities coverage. Consumed
by scripts/scope_audit.py for diff and reporting.
* fix(mail): replace os.Exit with graceful shutdown in mail watch
The signal handler in mail +watch called os.Exit(0), which bypassed all
deferred cleanup functions, made the code path untestable, and did not
follow Go's idiomatic context cancellation pattern.
Key changes:
- Remove os.Exit(0) and use context.WithCancel to propagate shutdown
- Run cli.Start in a separate goroutine so the main goroutine can return
immediately on signal receipt (the Lark WebSocket SDK does not return
promptly after context cancellation)
- Extract handleMailWatchSignal as a testable standalone function
- Use sync.Once + defer for idempotent cleanup on all exit paths
- Fix eventCount data race with atomic.Int64
- Add signal.Reset to support forced termination via a second Ctrl+C
Closes#268
* docs: add docstrings to handleMailWatchSignal test functions
* fix(mail): cancel watch context on signal handler panic
If handleMailWatchSignal panics, the recover block now calls
cancelWatch() to unblock the main select. Without this, a panic
would leave shutdownBySignal unclosed and watchCtx uncancelled,
causing the process to hang.
* fix(mail): use triggerShutdown to unblock main select on signal handler panic
The previous panic recovery only called cancelWatch(), but since the
WebSocket SDK does not return promptly after context cancellation,
the main select could still hang waiting on startErrCh.
Introduce triggerShutdown() that closes shutdownBySignal (via
sync.Once) and cancels the watch context, used by both the normal
signal path and the panic recovery path. This ensures the main
select unblocks immediately regardless of how the signal goroutine
exits.
Add regression test that forces a panic and asserts shutdownBySignal
is closed promptly.
* feat(mail): add --page-token and --page-size pagination support to mail +triage
Support external pagination for mail +triage with two new flags:
- --page-token: resume from a previous response's page token
- --page-size: alias for --max
Token carries a "search:" or "list:" prefix to identify the API path,
with strict validation: conflicting parameters (e.g. list: token with
--query) fail fast, and bare tokens without prefix are rejected.
JSON/data output now returns an object with messages, total, has_more,
and page_token fields. Table output shows next-page hint on stderr.
* fix(mail): address PR review — keep data format as array, fix whitespace query edge case
- --format data preserves backward-compatible flat array output
- --format json returns the new envelope object with pagination fields
- Align search: prefix guard with TrimSpace(query) to match usesTriageSearchPath
* fix(mail): simplify page-token format and fix page-size change data loss
- Remove page_size encoding from token (search:abc → not search:5:abc)
The search API token is a session cursor; page_size only controls how
many items to return, not the cursor position. Encoding page_size
caused data loss when users changed --page-size between requests.
- Token format is now simply "search:<raw>" / "list:<raw>"
- Add parseTriagePageToken/encodeTriagePageToken helpers for clean
token handling with proper validation
- next page hint in table output now includes --query and --filter
for easy copy-paste continuation
* docs(mail): update triage skill doc for json/data format split and search pagination note
- Separate --format json (object with pagination) and --format data (array) examples
- Update table next-page hint example to show --query/--filter inclusion
- Add search pagination caveat about cross-session result ordering
* fix(mail): make --format data include pagination fields same as json
* fix(mail): address remaining PR review comments
- Reject empty prefixed tokens (search: / list:) in parseTriagePageToken
- Shell-escape query/filter in next-page hint to handle single quotes
- Fix doc caption mismatch (data → json/data) and add language tag to code block
- Fix test comment for TestResolveTriagePageSizeDefaultMax
* fix(mail): rename total to count in triage pagination output
total was misleading — it represented the current page count, not the
global total. Renamed to count to match len(messages) semantics.
* fix(mail): improve dry-run desc when using --page-token
* fix(base): improve --json help examples and group guide
* fix(base): unify --json help tips format
* docs(base): fix view-set-group schema with group_config
* fix(base): remove array wording from view-set-group json help
---------
Co-authored-by: kongenpei <kongenpei@users.noreply.github.com>
* fix(api): add stdin and single-quote support for --params/--data on Windows (#64)
Windows PowerShell 5.x mangles JSON double-quotes when passing arguments
to native executables, causing --params and --data to fail with
"invalid JSON format". This commit adds two mitigations at the framework
level:
- stdin piping: `echo '{"k":"v"}' | lark-cli --params -` bypasses
shell argument parsing entirely and works on all platforms/shells.
- single-quote stripping: cmd.exe passes literal single quotes which
are now transparently removed before JSON parsing.
Implementation:
- New `cmdutil.ResolveInput(raw, stdin)` handles `-` (stdin), strip
surrounding `'...'`, and plain passthrough.
- `ParseJSONMap` and `ParseOptionalBody` now accept an `io.Reader` and
delegate to `ResolveInput` before JSON unmarshalling.
- `cmd/api` and `cmd/service` pass `IOStreams.In` and guard against
simultaneous stdin usage by --params and --data.
- Empty stdin is rejected with a clear error message.
Closes#64
Change-Id: If21e735d0aed5c6a2d6674c1e6c898186fca3aba
* test: add stdin e2e regression coverage
Change-Id: I4e00bf1c6b6f3259f503e3414cae10fa4b34ba75
New capabilities:
1. Alias (send_as) sending for all compose shortcuts (+send, +reply, +reply-all,
+forward, +draft-create, +draft-edit):
- New --mailbox flag separates mailbox routing from sender identity, enabling
alias sending where --mailbox specifies the owning mailbox and --from
specifies the alias address in the From header.
- Example: --mailbox me --from alias@example.com --to bob@example.com
- --mailbox priority: --mailbox > --from > "me"
- --from priority: --from > --mailbox > profile("me")
2. Discovery APIs for available mailboxes and sender addresses:
- accessible_mailboxes: lists all mailboxes the user can access (primary + shared)
- send_as: lists available sender addresses for a mailbox (primary, aliases, mailing lists)
3. Mail rules API:
- user_mailbox.rules resource: create, delete, list, reorder, update
4. Reply-all self-exclusion improvement:
fetchSelfEmailSet now also excludes the --from alias address, preventing the
sender from appearing in the recipient list when replying via an alias.
No breaking changes — omitting --mailbox preserves existing behavior.
When config.json is hand-edited, the appId field can become out of sync
with the appSecret keychain reference (e.g. appId changed but
appSecret.id still points to the old app). This causes silent auth
failures at API call time. Add a pre-flight check in
ResolveConfigFromMulti that compares the two before any keychain lookup
or OAPI request, failing fast with actionable guidance.
Change-Id: I74b9ab640642dde3df1ad70890b93b91ee422022
- Add depguard linter to block shortcuts/ from importing internal/vfs
directly (must use runtime.FileIO() instead)
- Add forbidigo rules for os.* filesystem ops, IO streams, os.Exit,
and filepath.* functions that bypass vfs
- Split os.Remove / os.RemoveAll into separate patterns with accurate
guidance (RemoveAll not yet in vfs)
- Use compact regex groups for maintainability, no duplicate or
shadowed patterns
Change-Id: I9e45ab07ca58a61b86bdcea9f1f2cc6181c974bc
* feat(auth): improve scope handling and output in login flow
- Add scope validation to check for missing requested scopes
- Implement detailed scope breakdown in login success output
- Add new message strings for scope-related output
- Refactor login success output to handle both JSON and text formats
- Add tests for scope validation and output scenarios
* feat(auth): add requested scope caching for device code login
Implement caching of requested scopes during device code login flow to ensure proper scope validation after authorization. The cache is stored in JSON files under config directory and automatically cleaned up after successful or failed authorization.
Add tests for scope caching functionality and verify proper integration with existing login flow.
* docs(auth): add function comments for login scope handling
Add detailed doc comments to all functions in login scope cache and result handling files to improve code documentation and maintainability.
* refactor(auth): remove pending scopes and improve json output stability
- Remove PendingScopes field and related logic as it's no longer needed
- Add emptyIfNil helper to ensure nil slices are normalized to empty slices in JSON output
- Update tests to verify JSON output stability and fix expected text outputs
* refactor(auth): extract device token polling function for testability
Move device token polling to a package-level variable to enable mocking in tests
Add test case for scope cleanup when token is nil
* fix(auth): return JSON write errors instead of ignoring them
Previously, JSON write errors were only logged to stderr but not returned, causing tests to pass when they should fail. Now properly propagate these errors to callers and update tests to verify error handling.
* refactor(auth): simplify scope handling and improve user messaging
remove redundant scope display and consolidate hint messages to focus on actionable guidance
* refactor(auth): improve scope handling and messaging in login flow
remove ShortHint field and simplify scope hint messages
always display missing scopes section with consistent formatting
add StatusHint for successful login with no missing scopes
update tests to reflect new message structure and content