Compare commits

...
18 Commits
Author SHA1 Message Date
修雨 86ff7e2f50 docs(changelog): add 1.0.32 release notes (#354) 2026-05-25 19:54:47 +08:00
Ari 45cb237f74 fix(drive): unblock OSS upload + improve AI-agent discoverability (#347)
* fix(drive): drop client-side Content-Type fallback on presigned OSS PUT

The drive helper used to set req.Header["Content-Type"] = fallbackMIME
whenever the prepare_upload response returned an empty headers map.
DingTalk drive uses OSS presigned URLs whose StringToSign is computed
against an empty Content-Type at signing time, so any client-side
Content-Type makes the signature OSS recomputes at PUT time differ
from the server's presignature → HTTP 403 SignatureDoesNotMatch.

This broke every `dws drive upload` for any file whose mime detects
to a non-empty value (image/png, application/pdf, etc.), which is
basically everything in practice.

Reproduction (against DingTalk drive):
  dws drive upload --file any.png
  → [1/3] 获取上传凭证 any.png (X 字节, image/png)...
  → [2/3] 上传文件到 OSS...
  → OSS 上传失败 HTTP 403: SignatureDoesNotMatch

Fix: trust the server's headers map as authoritative. Empty map means
"no client-side headers needed" — do not infer and add Content-Type.
Removes the hasContentType / fallbackMIME path entirely; httpPutDriveFile
signature loses the fallbackMIME parameter.

Manual verification:
  curl -X PUT -H "Content-Type:" --data-binary @file <same-presigned-url>
  → HTTP 200 (proves the only difference was the client-side Content-Type)

Note: aitable.go's upload-file helper deliberately keeps its
Set("Content-Type", mimeType) call because its OSS endpoint uses a
different signing mode (server includes the client-declared mime in
its signature computation, verified by running aitable upload-file
across 12 file types — all succeed). The two helpers must not be
unified without re-validating both endpoints.

Tests:
  - TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty: guards
    that an empty server headers map results in no Content-Type on PUT.
  - TestHttpPutDriveFile_PassthroughServerHeaders: guards that server
    headers (Content-Type, x-oss-*) are forwarded verbatim.

* feat(aitable): unhide attachment upload-file + clarify prepare-only command

AI agents that discover commands only via --help (e.g. Lobster, generic
LLM agents) currently hit a dead end when trying to upload an attachment
to an AITable:

  - `dws aitable attachment` exposes only `upload` (prepare-only),
    which returns uploadUrl + fileToken but does not actually upload.
  - The real one-shot command `attachment upload-file` (which performs
    prepare + HTTP PUT + return fileToken automatically) is marked
    Hidden:true, so it is invisible in --help output.

Agents that don't read skills/references/products/aitable.md therefore
get stuck after step 1 — they call `upload`, receive an uploadUrl they
have no idea how to consume, attempt various wrong things (e.g. write
the uploadUrl into the record's attachment field as if it were a token),
fail, and fall back to "please use the UI to upload" messages, which
makes dws look broken even though the capability is fully implemented.

This is the same UX gap that lark-cli avoids with its highly visible
`base +record-upload-attachment` command — discoverability via --help
is the difference between "works for any agent" and "only works if the
agent reads our skill docs".

Changes:

  - newAITableUploadFileCommand: remove Hidden:true so the command
    appears in `dws aitable attachment --help`. Tighten Short to
    explicitly mention the 3 steps it bundles. Long now also calls
    out the prepare-only sibling and recommends this command as the
    default for AI agents.

  - newAITableAttachmentUploadCommand (prepare-only): add a Long
    description that explicitly states this command is only step 1
    of a 3-step flow, lists what an agent must do after (HTTP PUT,
    then write fileToken into record attachment field with the exact
    [{"fileToken":"ft_xxx"}] shape), and points to upload-file as
    the recommended one-shot alternative. Updated Short to flag that
    no file is uploaded by this command.

  - aitable_upload_file_test: add TestAITableUploadFileCommandIsDiscoverable
    to guard against re-introducing Hidden:true. The test includes a
    rationale comment explaining the agent-discoverability gap.

The drive Content-Type fix in the preceding commit and this aitable
discoverability fix together restore end-to-end attachment upload
functionality for both human operators and AI agents that only read
--help.

* feat(root): show 'dws upgrade' guidance in dws --help when commands are missing

AI agents (and users) reading `dws --help` see only the discovered MCP
service list and utility command list, with no hint about what to do if
none of the listed commands fit their task. The natural failure mode is
to give up or hack around — but in many cases the right action is just
`dws upgrade`, because new capabilities and bugfixes ship continuously
and a missing command is usually a stale binary issue.

Two changes restore visibility of the root command's Long description so
this guidance can be surfaced:

  - internal/app/root.go: set root.Long to a one-paragraph hint —
    "if you hit a missing command, an error, or cannot complete the
    task, try `dws upgrade` first; both the DingTalk OpenAPI surface
    and dws CLI evolve continuously."

  - internal/app/root_help.go: the custom SetHelpFunc that renders the
    root help (renderRootHelp) replaces cobra's default template, which
    had been silently dropping root.Long from --help output. Restore
    rendering by appending root.Long (when non-empty) after the command
    list, separated by a blank line. This matches cobra's default
    behavior for the Long field while preserving the custom services /
    utilities sections renderRootHelp introduced.

  - internal/app/visibility_test.go: new TestRenderRootHelpIncludesLong
    guards against re-introducing the regression. Uses a sentinel Long
    string and asserts renderRootHelp output contains it verbatim. If a
    future change rewrites the help renderer without preserving Long
    rendering, this test fails immediately and reminds the author the
    upgrade hint must stay visible.

Verified locally:
  $ ./dws --help | tail -3
  Use "dws <service> --help" for more information about a discovered MCP
  service or "dws <command> --help" for utility commands.

  提示: 如果遇到能力缺失、命令报错、新功能未注册、或无法完成任务,
  请先用 'dws upgrade' 升级到最新版本后再试. 钉钉 OpenAPI 和 dws CLI
  持续迭代, 新能力和 bugfix 会先在新版本上线.
2026-05-24 15:55:08 +08:00
修雨 bd711108f9 fix(upgrade): ad-hoc sign darwin binaries to fix amfid SIGKILL on Apple Silicon (#339)
GoReleaser cross-compiles darwin/arm64 binaries on ubuntu-latest with no
codesign step. macOS 11+ on Apple Silicon requires at least an ad-hoc
signature; unsigned arm64 binaries are SIGKILL'd by amfid on first exec,
which surfaces as `signal: killed` and aborts `dws upgrade` at the
"解压并验证" step.

Two layers of fix:

1. Release-side: post-goreleaser.sh now unpacks each dws-darwin-*.tar.gz,
   applies an ad-hoc signature (codesign locally, rcodesign in CI),
   deterministically repacks, and rewrites the matching line in
   checksums.txt. release.yml installs rcodesign 0.27.0 before
   GoReleaser runs.

2. Client-side self-heal: validateNewBinary detects `signal: killed` on
   darwin and retries once after running `codesign --force --sign -` and
   clearing com.apple.quarantine. Future releases stay functional even
   if the signing step is ever skipped.

Verified end-to-end: stripped a real dws binary → exec exits 137 →
validateNewBinary recovers → final binary shows Signature=adhoc and runs.
2026-05-21 22:45:22 +08:00
修雨 6b4d808d39 docs(changelog): add 1.0.31 release notes (#338) 2026-05-21 20:22:57 +08:00
修雨andClaude Opus 4.7 c7d8ddf98d feat: align drive with wukong — helper (upload) + skill docs (doc/sheet dingpan URL) (#335)
* feat(helpers): drive upload 三步合成胶水(list-spaces / delete 由 envelope 接管)

业务背景:开源版 dws drive 仅有来自服务发现 envelope 的 6 个工具,悟空版多
3 个能力 — list-spaces / upload / delete。这 3 个里只有 upload 是真正的客户端
胶水(PUT 文件二进制到 OSS 的中间 HTTP 步),其它两个完全可以通过 envelope
toolOverrides 表达,无需 Go 代码。

按 envelope 优先原则拆分:

1. envelope/pre-discovery.pre.json (单独提供 / 不在本 commit)
   - drive.toolOverrides.list_spaces  →  cliName: list-spaces
   - drive.toolOverrides.delete_document → cliName: delete, serverOverride: doc,
                                             isSensitive: true
2. internal/helpers/drive.go (本 commit)
   - 仅注册 upload 一个 leaf
   - 原因:envelope.PipelineStep 只支持 type:"call"/"download",没有
     type:"upload"。客户端流式 PUT 本地文件到 OSS 签名 URL(含 per-URL
     headers)当前 envelope schema 表达不了,故保留为 helper。

internal/helpers/drive.go (新增 ~290 行)

  - upload — 三步合成:
    1) drive get_upload_info → resourceUrl + uploadId + headers
    2) HTTP PUT 文件二进制 → OSS(沿用 aitable upload-file 模式,
       10min timeout,跟随 per-URL headers)
    3) drive commit_upload → 提交入库
    --dry-run 输出三步 invocation 预览不实际请求。
    parseDriveUploadInfo 兼容 content/result 包裹层与 resourceUrls 数组
    及 flat resourceUrl/uploadUrl fallback,与悟空侧 parseDriveUploadInfo
    等价。
    validateDriveParentID 拒纯数字 dentryId(防混淆 chat 链路 dentryId 与
    drive 链路 dentryUuid)。

注入路径:helpers.RegisterPublic → pickCommands.MergeHardcodedLeaves(dynamic,
helper)(dynamic 赢冲突、helper 填空白)。本 helper root.Use="drive" 不覆盖
dynamic 的 6 个 leaf,仅追加 upload。

dry-run 实测:

  $ dws drive upload --file /etc/hosts --dry-run --format json
  → step_1_get_upload_info + step_2_http_put_oss + step_3_commit_upload 三步预览

测试结果:
  ok  internal/helpers (含全部既有 TestSendByBot* / TestAtomicWrite* /
                       TestValidate* 等 23 个测试)
  ok  test/integration/extensions
  test/cli_compat pre-existing failures 与本改动无关(在干净 origin/main HEAD
  同样 fail,fixture 缺失等)。

未来工作 (follow-up):
  - 等 envelope 文件 commit 到主线后,list-spaces / delete 自动从 envelope
    生成 cobra command,无需此 helper 操心
  - 如果 envelope schema 加入 type:"upload" pipeline 步类型,本 helper 整个
    可以删除,由 envelope pipeline 表达完整三步

关联:
  - 悟空源头实现:dws-wukong/wukong/products/drive.go
    (runDriveUpload / parseDriveUploadInfo / httpPutFile + delete 路由)
  - 配套 skill 文档 PR:#333 (doc 端钉盘 URL 识别)
  - envelope 改动: drive.toolOverrides 增加 list_spaces + delete_document,
    见对应的 envelope PR / commit

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(skill): doc --node 接受钉盘 document/edit|preview?dentryKey URL + 新增 url-patterns 分流

业务背景:hho 业务侧用户在悟空版上已用钉盘 URL(alidocs.dingtalk.com/document/edit?dentryKey=...)
直接喂给 Agent,但开源版 skill 文档未覆盖这种格式,Agent 不知道整段 URL 应原样传给 --node,
经常误把 dentryKey 当成裸 nodeId 调用导致失败。

本 PR 把悟空 dws-wukong PR #82157526 的 skill 文档增量移植到开源主线,保持 doc/sheet
两端入口的 URL 识别策略对齐悟空:

skills/SKILL.md
- 核心流程新增 Step 0「URL 预检」:含 alidocs URL 必须先读 url-patterns.md 分流,再选择产品
- 详细参考目录加入 url-patterns.md 引用

skills/references/products/doc.md
- dws doc info/read 的 Example 各 +2 行钉盘 URL 示例
- 「URL 识别与 DOC_ID 提取」支持的 URL 格式表新增 document/edit|preview?dentryKey={key} 一行
- 提取规则拆成 3 条,禁止 Agent 自行提取 dentryKey 当裸 nodeId
- 「nodeId 双格式说明」升级为「nodeId 多格式说明」,给出 4 种 --node 输入等价示例

skills/references/url-patterns.md (新建)
- 沉淀 alidocs URL 5 类分流决策:/i/p/ 短链 / /i/nodes/ 节点 / /spreadsheetv2/ 直链 /
  /document/edit|preview?dentryKey 链接 / 其他
- 含 i/nodes/ 类型探测流程(doc info 探 contentType/extension/nodeType 后再选产品)
- 含分享短链 read_url 兜底处理 + 动态渲染失败时的标准答复

skill 命名形态兼容:
- 当前 main 上 skills/ 是扁平结构,改动直接落在 skills/* 路径
- 单点(mono)/ 多点(multi)拆分形态在 feature/skill-setup 分支,待该分支合主线时
  按相同语义同步到 skills/mono/* 和 skills/multi/dingtalk-{doc,sheet}/* 两套

不涉及 Go 代码变更,纯 skill 文档;钉盘 URL 解析逻辑由 MCP 服务端承担。

关联悟空 PR:dws-wukong commit 565c63f8 / 712da968(#82157526)
对应 wukong skill 包:dingtalk-workspace/{SKILL.md,references/products/doc.md,references/url-patterns.md}

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 17:38:00 +08:00
修雨 754b0df056 docs(changelog): add 1.0.30 release notes (#322)
* docs(changelog): add 1.0.30 release notes

Notes for the wukong-IM-envelope alignment + schema-pipeline / transform /
market enhancements that landed via #317. Also extends the README "Pipe &
File Input" section with the `@<text>` ASCII-prefix rule that lets literal
Chinese mentions like `@所有人` / `@张三` pass through unchanged.

Validated against `dws-wukong/auto-test/cli_to_mcp` with `--edition open`,
account wukong01, on this main:
- chat: 107 passed / 0 failed / 0 errored → 100.0% PASS
- report: auto-test/cli_to_mcp/open_report/test_report_20260519_155449.md

* docs(changelog,readme): drop internal validation note; refresh chat row

- CHANGELOG: remove the validation paragraph from the 1.0.30 entry — it
  cited an internal repo path, a test account, and a local-only report
  file, none of which belong in public release notes.
- README / README_zh: bump the Chat / IM row in the Key Services table
  from 23 → 57 leaves and expand the subcommand list to match the
  current chat tree (group-mute / group-mute-member / mute / set-top /
  list-categories / list-conversations, plus message reply, search /
  search-advanced, forward, emoji & text-emotion reactions, cards,
  group member-role CRUD, transfer-owner, set-admin, quit, ...). Count
  matches `dws chat --help` enumeration on this main.
2026-05-19 17:29:35 +08:00
修雨 6be124777f feat: align CLI to wukong IM envelope + schema pipeline / transform / market enhancements (#317)
把 test/pre-mcp-discovery 上累积的稳定改动整理成一个 commit 合入 main,剔除
test-only 的预发环境硬编码与 merge/revert 噪音。

- internal/helpers: 重写 chat.go 对齐 wukong IM envelope,拆分共享的 chat
  命令,删减历史测试桩
- internal/compat: 新增 Pipeline tool override + executor、CLIAliases
  override、json_parse_strict 与 file_read transform;envelope leaf cmd
  Args 从 NoArgs 放宽到 ArbitraryArgs
- internal/cli: stdin 处理增强,覆盖更多 --content / --content-file 路径
- internal/app: direct_runtime / runner 适配嫁接硬编码 helper 到动态命令树
- internal/market: registry 强化 + 单元测试

最终 diff: 12 个文件,+369 / -387。
2026-05-19 15:25:39 +08:00
修雨 355a1460d9 docs(changelog): add 1.0.29 release notes (#309)
CHANGELOG: write up 1.0.29 — summary paragraph, then Added (3 new
envelope products: aiapp / live / aisearch with their flag aliases /
subcommand aliases / short flags rationale), Fixed (#306 leaf cmd
ArbitraryArgs), and the existing Security entry (#300 app.json
edition partitioning) preserved.

README.md / README_zh.md: lift aiapp / aisearch / live out of "Coming
soon" into the Key Services table; rename "Coming soon" to keep only
conference; bump totals 16 → 19 products / 204 → 209 commands.
2026-05-17 17:59:28 +08:00
c6edc84e40 fix(auth): partition app.json filename by edition to isolate credentials (#300)
* fix(auth): partition app.json filename by edition to isolate credentials

Two dws binaries sharing the same config directory (typically ~/.dws or
DWS_CONFIG_DIR) previously read and wrote a single app.json. Editions
that pin AuthClientID via hooks still go through the open-core
post-login persistence path, which records a bare ClientID without a
paired ClientSecret. The sibling edition reading the same path would
then adopt that foreign clientID via ResolveAppCredentials.

Mirror the strategy already used by the cache loader
(pkg/config.EditionPartition): GetAppConfigPath returns a filename
suffixed with the active edition name. Open-source keeps "app.json" for
backwards compatibility; sibling editions land on "app-<edition>.json".
LoadAppConfig / SaveAppConfig / HasAppConfig / DeleteAppConfig all
route through GetAppConfigPath, so this single change physically
isolates credential files end-to-end without any read-time heuristics.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(auth): address app config partition review

* fix(auth): clean legacy sibling app config

* test(auth): cover legacy app config cleanup guards

* fix(auth): close app config review follow-ups

---------

Co-authored-by: shangguanxuan.sgx <shangguanxuan.sgx@alibaba-inc.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 17:43:20 +08:00
修雨 f497047fff fix(compat): relax envelope leaf cmd Args from NoArgs to ArbitraryArgs (#306)
NewDirectCommand was hard-coding cobra.NoArgs for envelope-generated
leaf commands that have no positional bindings (totalMax == 0). This
is stricter than cobra's own default — legacyArgs (args.go:30-32)
returns nil for any command without subcommands.

The strict behavior surfaced as "unknown command \"<word>\" for
\"dws aisearch person\"" whenever an AI agent passed trailing
positional words after a leaf, e.g.

  dws aisearch person search --keyword "张"
  dws aisearch person user search --keyword "张"

Switching to cobra.ArbitraryArgs restores cobra's natural leaf
behavior: trailing positional args are silently ignored. Existing
positional-binding paths (MinimumNArgs / RangeArgs / MaximumNArgs)
are unchanged.

Verified against dws-wukong/auto-test/cli_to_mcp/testcases on
aiapp / live / aisearch: 50/50 pass (was 48/50; the 2 remaining
failures were the F-class extra-positional-args tolerance cases
this commit fixes).
2026-05-17 17:23:17 +08:00
修雨 a9de7d3ca4 chore(readme): refresh community DingTalk group QR (#296)
* chore(readme): refresh community DingTalk group QR

Replace the external alicdn-hosted QR image with a repo-tracked one
(.github/assets/community-qr.png), so the README is self-contained and
not dependent on third-party CDN availability.

QR encodes an external (cross-org) DingTalk group "dws开源沟通群",
valid until 2027-05-14. Scan with DingTalk mobile to join.

* chore(readme): use alicdn-hosted QR image (no repo binary)

Drop the repo-tracked .github/assets/community-qr.png and reference the
new community group QR via the alicdn CDN URL instead, matching the
original README convention (external image, no binary asset in tree).

QR points to "dws 开源沟通群" (external/cross-org DingTalk group),
valid until 2027-05-14. Mobile scan to join.

* chore(readme): match prior QR image width (150px)
2026-05-15 13:56:54 +08:00
FuShu-Yang 1c200d883f fix(app): prevent command field from overwriting existing endpoint (#297)
* fix(app): prevent command field from overwriting existing endpoint

In AppendDynamicServer, when a plugin declares command != id, the command
endpoint is written unconditionally, overwriting any previously registered entry.

Fix: use first-writer-wins - only write if the key is not yet present.

id registration and dynamicProducts remain unconditional (unaffected).

* test(app): add regression test for command endpoint first-writer-wins guard
2026-05-15 11:29:07 +08:00
修雨 d268524084 docs(changelog): add 1.0.28 release notes (#295) 2026-05-14 21:34:28 +08:00
修雨 ed4673e7d2 fix(chat): require --title for group messages, completing #250's symmetric fix (#294)
`send_message_as_user`'s schema also marks `title` as required, but
`buildChatMessageSendInvocation` only pre-validated it for direct
messages. Sending `dws chat message send --group <cid> --text "1"`
without `--title` therefore reached the API and returned the same
misleading `发群服务窗会话消息失败` business error that #250 fixed for
direct messages, just on the other branch.

Pre-validation now covers both branches: group sends without title
return `--title is required for group messages (--group)`, direct sends
keep the existing `--title is required for direct messages (...)`
message. `Long` help, the `--title` flag description, the first
`Example` line, and `skills/references/products/chat.md` (including the
deeper "drive → chat" workflow example) are realigned to
"群聊与单聊都必填". `internal/helpers/chat_test.go` gains a
`group-without-title` case, and the existing `group` / `positional-text`
success cases are updated to pass `--title`. No API request shape change.
2026-05-14 21:13:28 +08:00
修雨 de723914a5 docs(changelog): add 1.0.27 release notes (#293)
* docs(changelog): add 1.0.27 release notes

Covers what landed on main since 1.0.26:

- #291: file_read transform + CLIFlagOverride.MapsTo field, and the
  envelope-side rollout that turns it into `dws doc update --content`
  / `--content-file` (literal vs file/stdin → markdown).
- envelope: `dws sheet find --query` hidden alias via the existing
  CLIFlagOverride.Aliases — keeps wukong-doc copy-paste working on
  open-source. Needs `dws cache refresh` once.
- #285: suppress noisy WARN on stdio client shutdown.

* docs(changelog): translate 1.0.27 entry to English
2026-05-14 15:50:45 +08:00
FuShu-Yang 649801e479 fix(transport): suppress noisy WARN on stdio client shutdown (#285)
* fix(transport): suppress noisy WARN on stdio client shutdown

When Stop() kills the subprocess, cmd.Wait() always returns a non-zero
exit code which is expected behavior. Previously this propagated as an
error, causing "failed to stop stdio client ... exit status 1" warnings
on every normal CLI exit for stdio-based plugins.

Now Stop() returns nil when the process was explicitly killed, keeping
the error path only for cases where the process exits on its own with
a non-zero code (e.g. stdin close without kill).

🤖 Generated with [Qoder][https://qoder.com]

* fix(transport): address review feedback — simplify Stop(), fix test assertion

- Remove redundant `killed` flag; inline Kill+Wait+return nil
- Update integration test to positively assert Stop() returns nil after kill

🤖 Generated with [Qoder][https://qoder.com]
2026-05-14 14:45:23 +08:00
修雨 49c5bea4f3 feat(schema): file_read transform + CLIFlagOverride.MapsTo for --content/--content-file (#277 #278 #282 #288) (#291)
* feat(transform): add file_read transform for UTF-8 file / stdin content (#277)

Introduces a new ApplyTransform case "file_read":
- Input: a string flag value treated as a UTF-8 file path
- Special case: the path "-" reads from stdin
- Output: the file contents as a string
- Errors surface as validation errors (exit 2) — non-UTF-8, missing
  file, empty path, and non-string input all reject cleanly

This is a foundational primitive intended to compose with envelope
schema features so a CLI flag like --content-file can carry a path
that ultimately feeds a string-typed MCP parameter with the file's
contents.

## Scope note — MapsTo intentionally NOT included

The original proposal in #277 paired this transform with a new
CLIFlagOverride.MapsTo field that retargets a flag's value to a
different MCP parameter (e.g. --content / --content-file both feed
the upstream `markdown` param). Pre-production end-to-end validation
(see #282) showed that the MCP registry server-side schema does not
currently recognise `mapsTo` and strips it on serialisation. Every
other new envelope field (hidden / required / transform /
mutuallyExclusive / requireOneOf) survives — only mapsTo is dropped.

Shipping MapsTo without server-side support would land dead client
code. The MapsTo field + sourceFlag transform guard were therefore
removed from this PR; they will return in a follow-up PR once #282
(server-side schema acknowledgement of mapsTo) is resolved. The
file_read transform stays here because it composes with multiple
mechanisms beyond MapsTo and is independently testable.

## Tests

Six new cases in internal/compat/transform_test.go cover the
contract: literal file, stdin via "-", missing file, non-UTF-8
input, empty path, non-string input. All pass under both `go test`
and `go test -coverprofile`.

Refs #277, blocked-by #282

* feat(schema): add CLIFlagOverride.MapsTo for sibling-flag routing (#277 #282)

Adds the `MapsTo` field on `CLIFlagOverride` and wires the dispatch loop
in `compat.buildOverrideBindings` so a flag's final value (post-transform
or literal) is routed into a different MCP parameter slot than its own
property name. This lets two sibling CLI flags feed a single upstream
parameter — the canonical case being `--content` (literal) + `--content-file`
(transform: file_read) both mapping to `markdown`.

Tool-level `CLIToolOverride.MutuallyExclusive` (cobra MarkFlagsMutuallyExclusive)
is the right partner for guarding "set one, not both" at parse time; no
new exclusion machinery is added.

Closes the client-side gap previously misattributed to a server-side
mapsTo strip in #282. Once a doc envelope with mapsTo lands in pre-prod,
end-to-end `--content-file` becomes shippable, finishing #277 Step 1b.

Test coverage (internal/compat/dynamic_commands_test.go):
  - MapsTo without transform: literal --content → params[markdown]
  - MapsTo with file_read transform: --content-file path → params[markdown]
  - Sibling flags both mapsTo same target, only one set: clean routing
  - Sibling flags both set: rejected by tool-level MutuallyExclusive (regression)

Backward-compat: empty MapsTo preserves existing params[propertyName] write
semantics for every existing envelope.
2026-05-14 14:44:00 +08:00
6707e56f9c feat(cli): schema-aware sticky flag splitting and structured unknown-flag recovery (#272)
* chore: update coverage badge [skip ci]

* chore: update coverage badge [skip ci]

* chore: update coverage badge [skip ci]

* chore: update coverage badge [skip ci]

* chore: update coverage badge [skip ci]

* 1.0.19 changelog

* stick opt

* fix(cli): utf-8 safe sticky suffix guard + changelog (#272)

SuffixLooksLikeValue used to read suffix[0] (a single byte) for both the
uuid format branch and the fallback "is the first rune a letter?" check.
For multi-byte UTF-8 leading runes — common in dws because value text is
often Chinese — this picked up only the first byte (0xE0..0xF4 lead),
which is not a letter and not a hex digit, so the function silently
returned true and let glued tokens like --name<CJK> get split into
--name <CJK>... This switches both branches to utf8.DecodeRuneInString
and adds a utf8.RuneError guard so invalid UTF-8 input is rejected too.

Also locks down the new behaviour in CHANGELOG ## [Unreleased]:
- Changed: schema-aware sticky flag splitting
- Added: available_flags field on unknown-flag errors

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 10:56:02 +08:00
53 changed files with 3274 additions and 549 deletions
+11
View File
@@ -28,6 +28,17 @@ jobs:
- name: Install archive tooling
run: sudo apt-get update && sudo apt-get install -y zip unzip
- name: Install rcodesign (ad-hoc sign darwin binaries from Linux)
run: |
set -eu
RCS_VERSION="0.27.0"
curl -fsSL -o /tmp/rcodesign.tar.gz \
"https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F${RCS_VERSION}/apple-codesign-${RCS_VERSION}-x86_64-unknown-linux-musl.tar.gz"
mkdir -p /tmp/rcodesign
tar -xzf /tmp/rcodesign.tar.gz -C /tmp/rcodesign --strip-components=1
sudo install -m 0755 /tmp/rcodesign/rcodesign /usr/local/bin/rcodesign
rcodesign --version
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
+110
View File
@@ -4,6 +4,108 @@ All notable changes to this project will be documented in this file.
The format is inspired by [Keep a Changelog](https://keepachangelog.com/) and this project follows [Semantic Versioning](https://semver.org/).
## [1.0.32] - 2026-05-25
Two user-visible regressions resolved plus two AI-agent discoverability fixes. `dws drive upload` was returning `HTTP 403 SignatureDoesNotMatch` for any file whose MIME detects to a non-empty value — basically every real file — because the helper added a client-side `Content-Type` fallback whenever `drive.get_upload_info` returned an empty headers map. DingTalk drive's OSS presigned PUT URLs are signed against an empty `Content-Type` at signing time, so any client-supplied header makes the signature OSS recomputes diverge from the server-signed one, and the PUT is rejected (#347). On Apple Silicon, `dws upgrade` was aborting at the "解压并验证" step with `signal: killed` because GoReleaser cross-compiles `darwin/arm64` binaries on `ubuntu-latest` with no codesign step, and macOS 11+ `amfid` SIGKILLs unsigned arm64 binaries on first exec (#339) — the release pipeline now ad-hoc signs every darwin tarball, and the upgrade client self-heals if it ever encounters an unsigned binary again. On the AI-agent discoverability side, `dws aitable attachment upload-file` (the one-shot prepare + PUT + commit composite) is no longer hidden from `--help` — agents that only browse the command tree were getting stuck at the prepare-only `attachment upload` step, which returns an upload URL + fileToken but doesn't actually upload. And `dws --help` itself now surfaces the missing-command upgrade hint that the custom `renderRootHelp` had been silently dropping from cobra's `root.Long`.
### Added
- **`dws aitable attachment upload-file` is now visible in `dws aitable attachment --help`** (#347, `internal/helpers/aitable.go`) — the hardcoded one-shot composite (prepare + HTTP PUT + commit, returns `fileToken` directly) was previously marked `Hidden:true` and only reachable by agents that read `skills/references/products/aitable.md`. Agents that only discover commands via `--help` were getting stuck at the sibling envelope-generated `attachment upload` (prepare-only): they'd receive `uploadUrl` + `fileToken`, have no idea how to consume the URL, and either write the URL into the attachment field as if it were a token (wrong shape — the field expects `[{"fileToken":"ft_xxx"}]`) or fall back to "please use the UI" messages, which made `dws` look broken even though the capability was fully implemented. Unhiding mirrors the discoverability pattern `lark-cli base +record-upload-attachment` already follows. `Short` is tightened to explicitly mention the 3 steps it bundles; `Long` calls out the prepare-only sibling and recommends `upload-file` as the default for AI agents. The sibling `attachment upload` (prepare-only) keeps its envelope-generated registration but gets a new `Long` that states it is only step 1 of a 3-step flow, lists what an agent must do after (HTTP PUT to `uploadUrl`, then write `[{"fileToken":"ft_xxx"}]` into the attachment field), and points to `upload-file` as the recommended one-shot alternative. `TestAITableUploadFileCommandIsDiscoverable` in `internal/helpers/aitable_upload_file_test.go` guards against re-introducing `Hidden:true`.
- **`dws --help` root output now surfaces the `dws upgrade` hint when no listed command fits** (#347, `internal/app/root.go` + `internal/app/root_help.go`) — `root.Long` is set to `"提示: 如果遇到能力缺失、命令报错、新功能未注册、或无法完成任务, 请先用 'dws upgrade' 升级到最新版本后再试. 钉钉 OpenAPI 和 dws CLI 持续迭代, 新能力和 bugfix 会先在新版本上线."`. The custom `renderRootHelp` (which replaces cobra's default template to render the services / utilities sections) had been silently dropping `root.Long`; restoring it costs one `Fprintln` after the command list, separated by a blank line. The natural failure mode for both agents and users staring at `dws --help` is to give up or hack around when none of the listed commands fit — but in many cases the right action is simply `dws upgrade`, because new capabilities and bugfixes ship continuously and a missing command is usually a stale-binary issue. `TestRenderRootHelpIncludesLong` in `internal/app/visibility_test.go` uses a sentinel `Long` string and asserts the rendered output contains it verbatim, so any future rewrite of the help renderer that drops `Long` fails this test immediately.
### Fixed
- **`dws drive upload` no longer fails with `HTTP 403 SignatureDoesNotMatch` on any non-empty MIME type** (#347, `internal/helpers/drive.go`) — `httpPutDriveFile` was setting `req.Header["Content-Type"] = fallbackMIME` whenever the prepare_upload response returned an empty headers map. DingTalk drive's OSS presigned URLs sign `StringToSign` against an empty `Content-Type` at signing time, so any client-side header makes the signature OSS recomputes at PUT time differ from the server's presignature, and the upload is rejected with `403 SignatureDoesNotMatch`. This broke every `dws drive upload` for any file whose MIME detects to a non-empty value (`image/png`, `application/pdf`, every common binary) — i.e. essentially every real upload. Fix: drop the `hasContentType` / `fallbackMIME` path entirely, trust the server's headers map as authoritative; empty map means "no client-side headers needed", do not infer. `httpPutDriveFile`'s signature loses the `fallbackMIME` parameter. Manual verification: `curl -X PUT -H "Content-Type:" --data-binary @file <same-presigned-url>` returns `HTTP 200`, proving the only difference was the client-side `Content-Type`. `TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty` guards the empty-map path; `TestHttpPutDriveFile_PassthroughServerHeaders` guards that server-provided `Content-Type` / `x-oss-*` headers are forwarded verbatim. Important: `internal/helpers/aitable.go`'s `upload-file` helper deliberately keeps its `Set("Content-Type", mimeType)` call — its OSS endpoint uses a different signing mode (server includes the client-declared MIME in the signature, verified across 12 file types — all succeed). The two helpers must not be unified without re-validating both endpoints.
- **`dws upgrade` no longer dies with `signal: killed` on Apple Silicon after fetching the new binary** (#339) — GoReleaser cross-compiles `darwin/arm64` binaries on `ubuntu-latest` with no codesign step, and macOS 11+ on Apple Silicon requires at least an ad-hoc signature on every arm64 binary; `amfid` SIGKILLs unsigned arm64 binaries on first exec, which the upgrade client surfaces as `signal: killed` and aborts at the "解压并验证" step. Two layers of fix:
- **Release-side ad-hoc signing** (`scripts/release/post-goreleaser.sh` + `.github/workflows/release.yml`) — after GoReleaser produces the per-platform tarballs, `post-goreleaser.sh` unpacks each `dws-darwin-*.tar.gz`, applies an ad-hoc signature (`codesign --force --sign -` locally, `rcodesign` in CI), deterministically repacks the tarball, and rewrites the matching line in `checksums.txt` so the checksum stays consistent with the resigned tarball. `release.yml` installs `rcodesign 0.27.0` before GoReleaser runs. Every 1.0.32+ tarball ships signed; the install regression is fixed at the source.
- **Client-side self-heal in `validateNewBinary`** (`internal/app/upgrade.go`) — when running the freshly-extracted binary returns `signal: killed` on darwin, the validator retries once after running `codesign --force --sign -` on the binary and clearing the `com.apple.quarantine` xattr. This keeps `dws upgrade` working even if a future release ever skips the signing step again, and covers users upgrading from older unsigned binaries. `internal/app/upgrade_test.go` (+80 lines) covers the retry path end-to-end: a stripped binary exits 137 on first exec, `validateNewBinary` recovers via ad-hoc sign + xattr clear, the final binary shows `Signature=adhoc` and runs.
## [1.0.31] - 2026-05-21
Closes the last drive-surface gap with the Wukong edition: `dws drive upload` lands as a single-shot composite (`drive.get_upload_info` → HTTP PUT to OSS → `drive.commit_upload`) so a local file reaches DingTalk drive in one CLI invocation, no manual three-step orchestration. Two more drive commands — `dws drive list-spaces` (list visible drive spaces) and `dws drive delete` (delete a drive file, routed via `serverOverride` to the doc MCP server) — ship via the portal envelope; `dws cache refresh` once to pick them up. Companion skill docs teach the agent to recognise dingpan URLs of the form `alidocs.dingtalk.com/document/edit?dentryKey=…` / `…/document/preview?dentryKey=…` and pass the whole URL through to `--node` instead of trying to extract `dentryKey` by hand (the server interprets `dentryKey` and a bare `nodeId` differently — manual extraction was failing).
### Added
- **`dws drive upload --file <path> [--folder <dentryUuid>] [--space-id <id>] [--file-name <name>] [--mime-type <type>]`** (#335, see `internal/helpers/drive.go`) — composite leaf that runs the full three-step upload internally:
1. `drive.get_upload_info` — fetch the OSS-signed `resourceUrl` + `uploadId` + per-URL headers.
2. HTTP `PUT` the file binary to OSS (10-minute timeout, attaches every header returned by step 1).
3. `drive.commit_upload` — register the new file under the target space / folder.
`--dry-run` prints the three step invocations as a single JSON payload without making any network calls. `--file -` is rejected on purpose: this is a local-path upload, not stdin streaming. `--folder` only accepts a `dentryUuid`; pure-numeric values are rejected up front (`validateDriveParentID`) so callers don't accidentally pass a chat-link `dentryId` (a different ID namespace) where the drive API expects a `dentryUuid`. Response normalisation handles all the wrapper shapes the upstream returns — `content` / `result` envelopes, `resourceUrls[]` arrays, and the flat `resourceUrl` / `uploadUrl` fallbacks — so the composite produces a stable JSON shape regardless of which path the upstream takes. The helper only registers `upload`; the existing six envelope-generated leaves (`list` / `info` / `download` / `mkdir` / `upload-info` / `commit`) keep flowing through dynamic discovery unchanged. `pickCommands.MergeHardcodedLeaves` guarantees dynamic leaves win on collision, so this helper only fills the upload gap.
- **`dws drive list-spaces` and `dws drive delete` (envelope rollout)** (#335, ships via portal envelope) — `list_spaces` registers as a plain `cliName` alias on the existing drive MCP server; `delete_document` registers with `serverOverride: doc` so the call routes to the doc MCP server (which owns the delete API), surfacing under the drive command tree for ergonomics. **Existing users must run `dws cache refresh` once** to pick up these two new leaves; no binary upgrade is required for them, but they pair naturally with the v1.0.31 client that ships `upload`.
- **`skills/references/url-patterns.md`** (#335) — single authority for dispatching `alidocs.dingtalk.com` URLs across doc / sheet / wiki. Five-way split: `/i/p/<token>` short links → expand via `doc info`; `/i/nodes/<id>` node URLs → probe with `doc info` and route by `contentType` / `extension` / `nodeType`; `/spreadsheetv2/...` → `sheet`; `/document/edit|preview?dentryKey=<key>` (dingpan format) → pass the whole URL to `--node`, do not strip `dentryKey` by hand; `/i/share/...` (read-only share) → use the `read_url` fallback. The "URL precheck" Step 0 in `skills/SKILL.md` now redirects every URL-bearing prompt through this dispatcher before the agent picks a product.
### Changed
- **`skills/references/products/doc.md` — `--node` accepts dingpan URLs end-to-end** (#335) — `dws doc info` / `dws doc read` examples gain two extra rows showing `--node "https://alidocs.dingtalk.com/document/edit?dentryKey=<KEY>"` and `…/preview?dentryKey=<KEY>` as first-class `--node` inputs. The "URL recognition & DOC_ID extraction" table adds the `document/edit|preview?dentryKey=<key>` row, and the extraction rules are split into three explicit clauses so the agent stops manually pulling `dentryKey` out of the URL and feeding it as a bare `nodeId` (which the server rejects). The "nodeId dual-format note" upgrades to "nodeId multi-format note" with four equivalent `--node` input shapes side by side.
## [1.0.30] - 2026-05-19
Aligns the open-source CLI with the IM envelope and schema-pipeline plumbing the Wukong edition has been running in pre-prod, plus three user-visible quality-of-life fixes. The most visible one: chat-bot webhook payloads carrying literal Chinese mentions (`@所有人 周报来了` / `@张三 看一下`) no longer fail with `file not found` — `@` is only treated as the `@<filename>` file-injection prefix when followed by an ASCII path-shaped character. The `chat` command tree is refactored to lean on the service-discovery envelope: thin wrappers (`chat search`, `chat group rename`, `chat group members list/add/remove/add-bot`, `chat bot search`) move out of the hardcoded helper and become envelope-generated dynamic commands; the helper keeps only the chat commands with real business logic (intelligent routing, current-user resolution, response normalization, stdin/@file input). A new `dws chat message reply` joins the existing `send` / `send-by-bot` / `recall-by-bot` / `send-by-webhook` family. Underneath: `transform: invert_bool` lets envelopes flip boolean semantics between CLI surface and MCP body (e.g. `--off` ↔ `mute=true`); the pipeline executor fail-fast on upstream `content.errorCode` instead of polling forever; service-discovery dedup keeps two envelope entries that share an MCP endpoint but declare different `cli.id` as separate descriptors (so the `bot-root` / `bot-message` / `bot-group` trio fronting one MCP server stays as three distinct CLI command roots); and `dws chat` no longer nests as `dws chat chat` when two envelope servers both declare the same top-level command name.
### Added
- **`transform: invert_bool` for envelope flag overrides** (#317, see `internal/compat/transform.go`) — flips a boolean at send time. Strings `true`/`1`/`yes`/`on` → `false`; `false`/`0`/`no`/`off`/`""` → `true`. Used when the CLI surface and the MCP body have opposite semantics — e.g. envelope declares `--off` on the CLI but the MCP parameter is `mute=true` for "muted". The framework flips at send time so the envelope keeps the natural CLI verb without forcing every caller to remember the inverted mapping. Coverage in `internal/compat/transform_test.go`.
- **`dws chat message reply`** (#317, see `internal/helpers/chat.go`) — reply to a chat message. Sits alongside `send` / `send-by-bot` / `recall-by-bot` / `send-by-webhook` under `dws chat message`.
### Changed
- **`chat` command tree refactored to lean on the service-discovery envelope** (#317, commit `6be1247`) — `internal/helpers/chat.go` now only carries the chat commands that need real business logic on top of the raw MCP call: `chat message send` (current-user resolution + symmetric direct/group title validation), `chat message send-by-bot` / `recall-by-bot` / `send-by-webhook` (bot routing + stdin/@file input), and `chat group create` (response normalization). The thin wrappers — `chat search`, `chat group rename`, `chat group members list/add/remove/add-bot`, `chat bot search` — are now produced by the envelope as dynamic commands. Net diff in the helper: `+358 / -71` overall (re-aligning to envelope-owned chat structure), and `chat_test.go` drops 71 lines of test-stubs the dynamic path covers natively. Every previously documented chat command keeps the same flag set and the same MCP tool routing — the surface is just sourced differently.
- **Pipeline executor fail-fast on `content.errorCode`** (#317, see `internal/compat/pipeline.go`) — when an upstream tool returns a non-empty `content.errorCode`, `executePipelineCall` raises a validation error immediately with the upstream `errorMessage` instead of proceeding into the poll/download phase. Pre-execution cobra validation (`MarkFlagRequired`) only checks that a flag was set, not that its value was non-empty — so a `--required-flag ""` reaches the upstream tool and the upstream rejects with `errorCode`. Without the short-circuit the pipeline kept polling for a task ID that would never exist, either spinning to `PollTimeout` or burning through retries with no actionable error. Exit code 2 (validation), same as any other CLI-layer pre-flight rejection.
- **Service-discovery dedup keys now include `cli.id`** (#317, see `internal/market/registry.go`) — `NormalizeServers` used to dedup envelope entries by endpoint alone (and by `displayName` in the second pass), which collapsed envelope entries that intentionally split one MCP endpoint into multiple CLI command trees. The `bot-root` / `bot-message` / `bot-group` trio all front the same `.../server/4717...` MCP endpoint and share the displayName `机器人消息`, but each declares a distinct `cli.id` and a distinct CLI command root; the old dedup kept only the last-write and dropped two of them. The dedup key now appends `#<cli.id>` when present, falling back to endpoint / name when absent so historical envelopes without `cli.id` keep their existing behaviour. Coverage in `internal/market/registry_test.go`.
### Fixed
- **`@<text>` injection no longer eats Chinese mentions like `@所有人` / `@张三`** (#317, see `internal/cli/stdin.go`) — `ReadFileArg` and `ResolveInputSource` used to treat *any* value starting with `@` as the `@<filename>` injection syntax. Chat-bot webhook payloads commonly contain literal mentions, so `dws chat message send-by-bot --text "@所有人 周报"` was failing with `file not found: 所有人 周报` before the message reached the API. The new `looksLikeFilePath` heuristic accepts `@` followed by an ASCII path-prefix character (`A-Z` / `a-z` / `0-9` / `.` / `/` / `~` / `_` / `-`), or `@-` for stdin, and passes the value through unchanged otherwise. `@A 但接下来都是中文@测试` *does* still attempt a file lookup because the rune right after `@` is ASCII — this matches the documented `@<path>` prefix shape. The historical "bare `@` is an error" behaviour is preserved. Coverage in `internal/cli/stdin_test.go::TestReadFileArgChineseAtMention`.
- **`dws chat` no longer nests as `dws chat chat` when two envelope servers contribute the same top-level command** (#317, see `internal/compat/dynamic_commands.go`) — `BuildDynamicCommands` used to overwrite `topLevel[name]` on the second contribution and rely on `attachOrMerge` later, which then attached the *whole* incoming command (named `chat`) under the existing root, producing `dws chat chat <leaf>`. The new `mergeSubcommandsInto` moves the second contribution's *children* under the first root and drops the duplicate wrapper, so e.g. `group-chat` + `im` envelopes that both declare `cli.command: chat` produce a single flat `dws chat` subtree.
- **Multi-server tool-name authority correction in the runtime runner** (#317, see `internal/app/runner.go` + `internal/app/direct_runtime.go`) — when two envelope servers share the same `cli.command`, the per-product endpoint map `endpoints[cmd]` in `registerDynamicServer` is second-writer-wins, and `catalog.FindProduct` may return the wrong server's endpoint for a tool whose real owner is the *other* server. `runtimeRunner.Run` now cross-checks the canonical tool→endpoint map exposed by the new `directRuntimeToolEndpoint`: when the per-tool endpoint exists and differs from the per-product endpoint the catalog returned, the tool-owner endpoint wins. Pairs with the registry dedup change above so the routing matches the dedup result.
## [1.0.29] - 2026-05-17
Three discovery-envelope products land on the open-source surface — `aiapp` (AI applications), `live` (DingTalk live streaming), and `aisearch` (enterprise people search) — closing the gap with the Wukong edition's product list. The `aisearch` envelope ships rich model-tolerance affordances (short flags, flag aliases, subcommand aliases) so AI agents that hallucinate keyword synonyms (`--query` / `--name` / `--q` / `--text` / `--find`) or alias subcommands (`search` / `find` / `query` / `user` / `people` / ...) still route to the canonical `person` tool instead of erroring out. To support that final fragment of agent tolerance, `internal/compat/registry.go` relaxes the envelope-generated leaf command's `Args` validator from `cobra.NoArgs` to `cobra.ArbitraryArgs` — restoring cobra's own default (`legacyArgs` returns nil for leaves) so trailing positional words are silently ignored. Plus the previously-shipped credential-isolation fix.
### Added
- **`dws aiapp` / `dws live` / `dws aisearch` — three new products discovered via envelope** (no public issue; pre-Diamond rollout) — open-source `dws` now exposes:
- **`dws aiapp`** — AI application lifecycle: `create --prompt <p> [--attachments <json>] [--skills <csv>]` / `query --task-id <id>` / `modify --prompt <p> --thread-id <id> [--skills <csv>]`. Backed by upstream `create_ai_app` / `query_ai_app` / `modify_ai_app` MCP tools.
- **`dws live stream list`** — list my DingTalk live streams. Backed by upstream `get_my_lives`.
- **`dws aisearch person`** — enterprise people search by keyword + multi-dimension filter. Dimensions: `all` (default) / `name` / `department` / `position` / `duty` / `supervisor` / `subordinate` / `phone` / `jobNumber` — multiple comma-separated (`--dimension name,department`). Backed by upstream `enterprise_person_search`.
- The `aisearch` envelope additionally registers `-w` / `-d` short flags (keyword / dimension); hidden flag aliases `--query` / `--name` / `--q` / `--text` / `--find` all routing to `keyword`; and cobra subcommand aliases `search` / `find` / `query` / `user` / `people` / `search-person` / `search-user` / `user-search` / `lookup` / `ask` / `contact` all routing to `person`. This closes the F-class model-tolerance regression cases in `dws-wukong/auto-test/cli_to_mcp/testcases/aisearch/test_90_aisearch_param_regression.py` (50/50 pass for aiapp + live + aisearch on the pre-mcp build).
- **Users must run `dws cache refresh` once** to pick up the new envelopes; no binary upgrade is required, but pairs naturally with the v1.0.29 client (see Fixed below for the envelope-leaf-Args change).
### Fixed
- **Envelope-generated leaf commands now tolerate trailing positional args** (#306, no public issue) — `NewDirectCommand` in `internal/compat/registry.go` was hard-coding `cobra.NoArgs` for leaves without positional bindings (`totalMax == 0`). This is stricter than cobra's own `legacyArgs` (cobra `args.go:30-32` returns `nil` for any command without subcommands), and surfaced as `unknown command "<word>" for "<leaf>"` whenever an AI agent passed trailing positional words after a leaf — e.g. `dws aisearch person search --keyword "张"` or `dws aisearch person user search --keyword "张"`. Switching the `totalMax == 0` branch (and the initial value) from `cobra.NoArgs` to `cobra.ArbitraryArgs` restores cobra's natural leaf behavior: trailing positional args are silently ignored. Existing positional-binding paths (`MinimumNArgs` / `RangeArgs` / `MaximumNArgs`) are unchanged. Verified against `dws-wukong/auto-test/cli_to_mcp/testcases` — aiapp (9/9) + live (3/3) + aisearch (38/38) = **50/50** pass, vs 48/50 before this patch.
### Security
- **App credential files are partitioned by edition to prevent cross-edition credential leakage** (#300, no public issue; found during internal review) — different `dws` editions sharing the same config directory previously read and wrote the same `app.json`. A sibling edition that pinned its OAuth client ID could persist that ID through the shared post-login path, and the open-source build could later adopt it from the same file. Open-source/empty edition keeps the legacy `app.json` path for compatibility; sibling editions now use `app-<edition>.json`, matching the existing cache partitioning strategy. This prevents new cross-edition app credential writes and reads from colliding. After a sibling edition saves its new partitioned file, it also best-effort removes a legacy `~/.dws/app.json` only when that file's `clientId` matches the sibling edition being saved; a different, unparsable, or otherwise unowned `app.json` is left untouched to avoid deleting open-source credentials. If you previously ran multiple editions in one shared `~/.dws`, remove any confirmed-stale orphan manually with `rm ~/.dws/app.json` after verifying it is not the open-source credential file you still need.
## [1.0.28] - 2026-05-14
A single symmetric follow-up to 1.0.26's #250: `dws chat message send --group <cid>` now refuses an empty `--title` at the CLI layer instead of letting the call fall through to the API and surface a misleading `发群服务窗会话消息失败` error. No other behaviour changes.
### Fixed
- **`dws chat message send` rejects missing `--title` on group messages** (#294, completes #250) — `send_message_as_user`'s schema marks `title` as required (just like `send_direct_message_as_user`), but `buildChatMessageSendInvocation` only had the pre-validation on the direct-message branches. Group sends without a title were falling through to the API and returning the same misleading `发群服务窗会话消息失败` that #250 already fixed for direct messages. The check now covers both branches: missing `--title` on `--group` returns `--title is required for group messages (--group)` with exit code 2; missing on `--user` / `--open-dingtalk-id` keeps the original `--title is required for direct messages (--user / --open-dingtalk-id)`. The `Long` help, `--title` flag description, the first `Example`, and `skills/references/products/chat.md` (including the drive→chat workflow example) are realigned to "title is required for both direct and group messages" — the docs previously contradicted themselves (the prose said 群聊可选 while the flag listing said 必填). `internal/helpers/chat_test.go` adds a `group-without-title` rejection case; the existing `group` / `positional-text` success cases now pass `--title` to stay aligned with the new validation. No API request shape change — the server has always required `title`; the CLI now matches.
## [1.0.27] - 2026-05-14
Two user-visible fixes plus the schema primitive they're built on. `dws doc update` now reads Markdown from a file or stdin, so long / multi-line / table-heavy content no longer gets mangled by shell escaping; `dws sheet find --query` stops returning `unknown flag` on the open-source build, restoring copy-paste from internal wukong docs. Underneath, schema/discovery envelopes get a generic `file_read` transform and a `CLIFlagOverride.MapsTo` field that lets two sibling CLI flags route into the same MCP parameter slot. Also suppresses a noisy WARN on normal stdio-plugin shutdown.
### Added
- **`file_read` transform + `CLIFlagOverride.MapsTo` field** (#291, closes #277 #278 #282 #288) — discovery envelopes can now declare a path-typed CLI flag that performs the "file path → file contents string" conversion client-side before the value reaches the upstream MCP parameter.
- `transform: "file_read"` (`internal/compat/transform.go`) — reads the file at the flag's value with UTF-8 validation; `-` means stdin. Any IO / encoding failure is surfaced as a validation error (exit 2), distinct from the generic transient-failure path (exit 1).
- `CLIFlagOverride.MapsTo` (`internal/market/registry.go`) — redirects the flag's final value (post-transform or literal) into a named MCP parameter slot instead of the default `params[propertyName]`. This lets a single MCP parameter (e.g. `markdown`) be fed by two sibling CLI flags — a literal `--content` and a file-reading `--content-file` — paired with the existing tool-level `MutuallyExclusive` / `RequireOneOf` to express "exclusive, at least one".
- Wired into the `internal/compat/dynamic_commands.go` normalizer via a separate `mapsToRoutes` collection + routing pass; empty `MapsTo` preserves the legacy `params[propertyName] = value` semantics, so every pre-existing dynamic_commands test passes unchanged. Pre-prod end-to-end verified across 6 cases (see PR #291's Validation table).
- **`dws doc update --content-file <path>` (envelope rollout)** — fixes "long Markdown can't reach the doc". The old command only accepted `--content "..."`, so long / multi-line / table-heavy Markdown got mangled by shell escaping and AI agents writing >2KB of content were stuck. The envelope now maps both `--content` (literal) and `--content-file` (`file_read` transform) to the `markdown` parameter, makes them mutually exclusive via cobra's `MarkFlagsMutuallyExclusive`, and requires at least one via `RequireOneOf`. `--content-file -` reads from stdin, so `cat long.md | dws doc update --content-file -` works directly. **Existing users must run `dws cache refresh` once** to pick up the new envelope.
- **`dws sheet find --query` hidden alias (envelope rollout)** — fixes "unknown flag when copy-pasting commands across editions". Users copying `dws sheet find --query "..."` from internal wukong docs onto open-source `dws` got `unknown flag: --query`, because the open-source primary flag is named `--find`. The envelope now registers `--query` as a hidden alias of `--find` via `CLIFlagOverride.Aliases` (the field shipped in 1.0.26) — it doesn't show up in `--help`, but accepts values and writes to the same MCP parameter. `--find` behaviour is unchanged. Also requires `dws cache refresh` once.
### Fixed
- **Noisy `failed to stop stdio client: exit status 1` WARN on normal stdio-plugin shutdown** (#285) — when `Stop()` explicitly `Kill`s the subprocess, the non-zero exit code returned by `cmd.Wait()` is expected behaviour, but it was being propagated as an error and logged to stderr on every CLI exit, polluting agent log parsing. `Stop()` now returns `nil` after Kill + Wait; the error path is reserved for "process exited on its own with non-zero" (e.g. stdin close without an explicit Kill). `internal/transport/stdio.go` + `stdio_integration_test.go` assert "Stop() returns nil after kill".
## [1.0.26] - 2026-05-12
Platform-stability round: Windows PAT-auth browser opener no longer truncates URLs at `&userCode=`, macOS sandbox hosts get an opt-in keychain fallback, and `dws doc download` rejects `axls` nodes before requesting `drive:download` consent. Two new global output formats `-f ndjson` and `-f csv` (matching `larksuite/cli`) land as first-class citizens with real-traffic-verified list detection. The `dws doc comment *` regression tracked in #240 is also resolved — fix is in the market metadata, users just need `dws cache refresh` once.
@@ -12,6 +114,14 @@ Platform-stability round: Windows PAT-auth browser opener no longer truncates UR
- **`-f ndjson` and `-f csv` global output formats** (#259, closes #252) — `ndjson` emits one compact JSON record per line (works straight with `jq -c` / `while read` / log pipelines); `csv` goes through `encoding/csv` (RFC-4180 — quoting, embedded newlines, CJK all handled by stdlib) and reuses the existing `-f table` column resolver (`normalizePayload` / `unwrapPrimaryObject` / `extractRowsFromMap` / `rowsFromSlice` / `formatValue`) so table and csv stay visually aligned. After a 7-product real-traffic sweep (contact / chat / doc / mail / todo / minutes / schema), the `preferredListKeys` whitelist was extended to cover the actual DingTalk envelope shapes — `contact user search` (`result`), `chat search` (`result.value`), `doc search` (`documents`), `mail mailbox list` (`emailAccounts`), `todo task list` (`result.todoCards`) — so these commands now degrade into a proper row stream instead of collapsing to a single-line `key,value` blob. Lives in `internal/output/ndjson.go` + `internal/output/csv.go`; `--format` help in `internal/app/flags.go` now lists `ndjson|csv` alongside `json|table|raw|pretty`.
### Changed
- **Sticky flag splitting is now schema-aware** (#272) — PreParse `StickyHandler` 此前会把任何前缀命中已知 flag 的 `--flagsuffix` 一律切成 `--flag suffix`,于是 `--starttime20260507` 这类拼错被静默改写成 `--start time20260507`,把假值传到下游。新行为按 flag 的 pflag 类型 / JSON Schema `format` / `enum` 校验 suffix 是否像合法 value(共享逻辑见 `pkg/cmdutil/sticky_suffix.go`),不像就保留原 token 让 cobra 报 `unknown flag`。slice/array/object 类型的 flag 永不切分。首 rune 读取使用 `utf8.DecodeRuneInString`,对中文等多字节 value 安全。
### Added
- **`available_flags` field on unknown-flag errors** (#272) — `dws -f json` 的 unknown-flag 错误体里新增 `available_flags`(已排序、过滤掉 hidden 与内部 `json` / `params`),方便 agent 不解析 `--help` 就能恢复。Human-readable 输出会附 `Flags: ...` 行,截断在 200 字节内。
### Fixed
- **`dws chat message send` 单聊缺 `--title` 时前置校验** (#250) — 单聊(`--user` / `--open-dingtalk-id`)的底层工具 `send_direct_message_as_user` 在 API 层强制要求 title,缺失时返回误导性的 `发群服务窗会话消息失败`。CLI 现在在 `buildChatMessageSendInvocation` 里前置校验,直接返回 `--title is required for direct messages (--user / --open-dingtalk-id)`;同时把 `Long` help、`--title` flag 描述、Example 和 `skills/references/products/chat.md` 全部对齐为「单聊必填,群聊可选」。群聊行为不变。
+11 -6
View File
@@ -21,7 +21,7 @@
> [!IMPORTANT]
> **Co-creation Phase**: This project accesses DingTalk enterprise data and requires enterprise admin authorization. Join the DingTalk DWS co-creation group for support and updates. See [Getting Started](#getting-started) below.
>
> <a href="https://qr.dingtalk.com/action/joingroup?code=v1,k1,v9/YMJG9qXhvFk5juktYnQziN70rF7QHebC/JLztTVRuRVJIwrSsXmL8oFqU5ajJ&_dt_no_comment=1&origin=11"><img src="https://img.alicdn.com/imgextra/i4/O1CN01Rijgk81gKqVSKMzdx_!!6000000004124-2-tps-654-644.png" alt="DingTalk Group QR Code" width="150"></a>
> <img src="https://img.alicdn.com/imgextra/i1/O1CN01WJyAsJ1prD2ovQACM_!!6000000005413-2-tps-718-720.png" alt="dws Open Source Community DingTalk Group QR Code" width="150">
<details>
<summary><strong>Table of Contents</strong></summary>
@@ -394,6 +394,8 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
--title "Weekly Report" --text @-
```
> **Note**: `@` is treated as the `@<path>` file-injection prefix only when the next character is an ASCII path-shaped character (`A-Z` / `a-z` / `0-9` / `.` / `/` / `~` / `_` / `-`), or `@-` for stdin. Chat-bot payloads like `--text "@所有人 周报"` or `--text "@张三 看一下"` pass through unchanged, so literal mentions reach the API as-is.
</details>
## Key Services
@@ -401,31 +403,34 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
| Service | Command | Commands | Subcommands | Description |
|---------|---------|:--------:|-------------|-------------|
| Contact | `contact` | 6 | `user` `dept` | Search users by name/mobile, batch query, departments, current user profile |
| Chat / IM | `chat` (alias `im`) | 23 | `message` `group` `bot` `conversation-info` `search` `search-common` `list-top-conversations` | Messages (send / list / list-all / by-sender / mentions / focused / unread / topic replies / search), group CRUD + member management (incl. `add-bot`), bot-identity messaging (`send-by-bot` / `recall-by-bot` / `send-by-webhook`), conversation info, common groups lookup |
| Chat / IM | `chat` (alias `im`) | 57 | `message` `group` `bot` `conversation-info` `search` `search-common` `list-top-conversations` `group-mute` `group-mute-member` `mute` `set-top` `list-categories` `list-conversations` | Messages (send / reply / list / list-all / by-sender / mentions / focused / unread / topic replies / search / advanced search / forward / cards / emoji & text-emotion reactions / recall / read & send status queries), group CRUD + member management (members add / remove / list / `add-bot`, member-role CRUD, invite URL, icon, settings, transfer-owner, set-admin, quit), bot-identity messaging (`send-by-bot` / `recall-by-bot` / `send-by-webhook`), conversation info, common-groups lookup, group/member/conversation mute, conversation set-top, conversation categories |
| Calendar | `calendar` | 14 | `event` `room` `participant` `busy` | Events CRUD + suggested times + attachments, meeting room booking, free-busy query, participant management |
| Todo | `todo` | 6 | `task` | Create, list, update, done, get detail, delete |
| Approval | `oa` | 9 | `approval` | Approve / reject / revoke, pending / initiated instances, process list, operation records |
| Attendance | `attendance` | 4 | `record` `shift` `summary` `rules` | Clock-in records, shift schedules, attendance summary, group rules |
| Ding | `ding` | 2 | `message` | Send / recall DING messages |
| Report | `report` | 7 | `create` `list` `detail` `template` `stats` `sent` | Create reports, sent/received list, templates, statistics |
| AI Tables | `aitable` | 41 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Full CRUD for Bases / datasheets / records / fields / views; charts & dashboards with public-share configs; data import/export; attachments; templates |
| AI Tables | `aitable` | 42 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Full CRUD for Bases / datasheets / records / fields / views; charts & dashboards with public-share configs; data import/export; attachments (prepare-only `upload` + one-shot `upload-file`); templates |
| Doc | `doc` | 21 | `search` `list` `info` `read` `create` `update` `upload` `download` `copy` `move` `rename` `file` `folder` `block` `comment` | Search / read / write docs, file & folder create, block-level editing, comments (list / create / reply / create-inline), upload / download |
| Drive | `drive` | 6 | `list` `info` `download` `mkdir` `upload-info` `commit` | DingTalk drive file ops: list, info, download, create folders, two-phase upload |
| Drive | `drive` | 9 | `list` `list-spaces` `info` `download` `mkdir` `upload` `upload-info` `commit` `delete` | DingTalk drive file ops: list spaces, list / info / download, create folders, one-shot `upload` (three-step composite) or two-phase `upload-info` + `commit`, delete |
| Minutes | `minutes` | 19 | `list` `get` `update` `mind-graph` `speaker` `hot-word` `upload` | List AI meeting notes (mine / shared), details (info / summary / keywords / transcription / todos / batch), title/summary updates, mind map, speaker replace, hot-word, upload session |
| Mail | `mail` | 4 | `mailbox` `message` | List mailbox addresses, KQL message search, get full message content, send email |
| Sheet | `sheet` | 34 | `range` `filter-view` (top-level: `create` `new` `list` `info` `find` `replace` `append` `merge-cells` `unmerge-cells` `add-dimension` `insert-dimension` `delete-dimension` `move-dimension` `update-dimension` `write-image` `copy_sheet` `update_sheet` `submit_export_job` `query_export_job` `create_filter` `get_filter` `update_filter` `delete_filter` `set_filter_criteria` `clear_filter_criteria` `sort_filter`) | Online spreadsheet (`contentType=ALIDOC`, `extension=axls`): worksheet CRUD, range read/write/append, dimension ops, cell merge, find/replace, named filter views + sheet-level filters, image write, async export (`submit_export_job` + `query_export_job` — no consolidated `export` in v1.0.25) |
| Wiki | `wiki` | 7 | `space` `member` | Knowledge base management: space `create` / `get` / `list` / `search` + member `add` / `list` / `update` |
| DevDoc | `devdoc` | 1 | `article` | Search the DingTalk Open Platform documentation |
| AI Search | `aisearch` | 1 | `person` | Enterprise people search by name / department / position / duty / supervisor / subordinate / phone / job-number (single command, multi-dimension filter) |
| AI App | `aiapp` | 3 | — | AI application lifecycle: `create` (with prompt / attachments / skills) / `query` (by task ID) / `modify` (by thread ID) |
| Live | `live` | 1 | `stream` | DingTalk live streaming: list my lives |
| Raw API | `api` | 1 | — | Call any DingTalk OpenAPI directly (api / oapi dual-form), with automatic app-level token management |
> **204 commands across 16 products.** Full listing with descriptions and usage scenarios: [`docs/command-index.md`](./docs/command-index.md). Run `dws --help` for the top-level tree, or `dws <service> --help` for subcommands.
> **213 commands across 19 products.** Full listing with descriptions and usage scenarios: [`docs/command-index.md`](./docs/command-index.md). Run `dws --help` for the top-level tree, or `dws <service> --help` for subcommands.
> **Note on `chat bot`**: bot capabilities (`send-by-bot` / `recall-by-bot` / `add-bot` / `send-by-webhook` / bot search) are merged into the relevant `chat` subtrees (e.g. `dws chat message send-by-bot`, `dws chat group members add-bot`) so the agent-facing command surface stays flat and discoverable. There is no longer a separate top-level `bot` product.
<details>
<summary>Coming soon</summary>
`conference` (video) · `aiapp` (AI apps) · `live` (streaming)
`conference` (video meetings)
</details>
+11 -6
View File
@@ -21,7 +21,7 @@
> [!IMPORTANT]
> **共创阶段**:本项目涉及钉钉企业数据访问,需企业管理员授权后方可使用。欢迎加入钉钉 DWS 共创群获取支持与最新动态。详见下方 [开始使用](#开始使用)。
>
> <a href="https://qr.dingtalk.com/action/joingroup?code=v1,k1,v9/YMJG9qXhvFk5juktYnQziN70rF7QHebC/JLztTVRuRVJIwrSsXmL8oFqU5ajJ&_dt_no_comment=1&origin=11"><img src="https://img.alicdn.com/imgextra/i4/O1CN01Rijgk81gKqVSKMzdx_!!6000000004124-2-tps-654-644.png" alt="DingTalk Group QR Code" width="150"></a>
> <img src="https://img.alicdn.com/imgextra/i1/O1CN01WJyAsJ1prD2ovQACM_!!6000000005413-2-tps-718-720.png" alt="dws 开源沟通群二维码" width="150">
<details>
<summary><strong>目录</strong></summary>
@@ -394,6 +394,8 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
--title "周报" --text @-
```
> **说明**:`@` 仅在其后是 ASCII 路径前缀字符(`A-Z` / `a-z` / `0-9` / `.` / `/` / `~` / `_` / `-`)或 `@-`(stdin)时,才会被识别为 `@<path>` 文件注入语法。`--text "@所有人 周报"` / `--text "@张三 看一下"` 这类机器人消息中的字面 `@` 提及会原样透传到 API。
</details>
## 核心服务
@@ -401,31 +403,34 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
| 服务 | 命令 | 命令数 | 子命令 | 描述 |
|------|------|:------:|--------|------|
| 通讯录 | `contact` | 6 | `user` `dept` | 按姓名/手机号搜索、批量查询、部门树、当前用户信息 |
| 群聊 | `chat`(别名 `im`)| 23 | `message` `group` `bot` `conversation-info` `search` `search-common` `list-top-conversations` | 消息(发送 / 列表 / list-all / 按发送者 / @我 / 关注 / 未读 / 话题回复 / 搜索)、群增删改 + 成员管理(含 `add-bot`)、机器人身份消息(`send-by-bot` / `recall-by-bot` / `send-by-webhook`)、会话信息查询、共同群聊 |
| 群聊 | `chat`(别名 `im`)| 57 | `message` `group` `bot` `conversation-info` `search` `search-common` `list-top-conversations` `group-mute` `group-mute-member` `mute` `set-top` `list-categories` `list-conversations` | 消息(发送 / 回复 / 列表 / list-all / 按发送者 / @我 / 关注 / 未读 / 话题回复 / 搜索 / 高级搜索 / 转发 / 卡片 / 表情与文本表情反应 / 撤回 / 已读与发送状态查询)、群增删改 + 成员管理(成员增 / 删 / 查 / `add-bot`、成员角色增删改查、邀请链接、群图标、群设置、转让群主、设置管理员、退群)、机器人身份消息(`send-by-bot` / `recall-by-bot` / `send-by-webhook`)、会话信息查询、共同群聊、群/成员/会话免打扰、会话置顶、会话分类 |
| 日历 | `calendar` | 14 | `event` `room` `participant` `busy` | 日程 CRUD + 建议时间 + 附件、会议室预订、闲忙查询、参与者管理 |
| 待办 | `todo` | 6 | `task` | 创建、列表、修改、完成、详情、删除 |
| 审批 | `oa` | 9 | `approval` | 同意 / 拒绝 / 撤销、待我审批 / 我发起的、流程列表、操作记录 |
| 考勤 | `attendance` | 4 | `record` `shift` `summary` `rules` | 打卡记录、排班查询、考勤摘要、考勤组规则 |
| DING | `ding` | 2 | `message` | 发送 / 撤回 DING 消息 |
| 日志 | `report` | 7 | `create` `list` `detail` `template` `stats` `sent` | 创建日志、收发列表、模版、详情、统计 |
| AI 表格 | `aitable` | 41 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Base / 数据表 / 记录 / 字段 / 视图 全量 CRUD;图表 + 仪表盘(含分享配置);数据导入导出;附件;模板 |
| AI 表格 | `aitable` | 42 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Base / 数据表 / 记录 / 字段 / 视图 全量 CRUD;图表 + 仪表盘(含分享配置);数据导入导出;附件(仅获取凭证的 `upload` + 一键上传 `upload-file`);模板 |
| 文档 | `doc` | 21 | `search` `list` `info` `read` `create` `update` `upload` `download` `copy` `move` `rename` `file` `folder` `block` `comment` | 搜索 / 读写文档、文件与文件夹创建、块级编辑、评论(list / create / reply / create-inline)、上传 / 下载 |
| 钉盘 | `drive` | 6 | `list` `info` `download` `mkdir` `upload-info` `commit` | 钉盘文件操作:列表、详情、下载、创建文件夹、两阶段上传 |
| 钉盘 | `drive` | 9 | `list` `list-spaces` `info` `download` `mkdir` `upload` `upload-info` `commit` `delete` | 钉盘文件操作:列出空间、文件列表 / 详情 / 下载、创建文件夹、一键 `upload`(三步合成)或两阶段 `upload-info` + `commit`、删除 |
| AI 听记 | `minutes` | 19 | `list` `get` `update` `mind-graph` `speaker` `hot-word` `upload` | 听记列表(我创建 / 共享给我)、详情(info / summary / keywords / transcription / todos / batch)、标题/摘要更新、思维导图、发言人替换、热词、上传会话 |
| 邮箱 | `mail` | 4 | `mailbox` `message` | 邮箱地址列表、KQL 邮件搜索、邮件详情、发送邮件 |
| 在线电子表格 | `sheet` | 34 | `range` `filter-view`(顶层:`create` `new` `list` `info` `find` `replace` `append` `merge-cells` `unmerge-cells` `add-dimension` `insert-dimension` `delete-dimension` `move-dimension` `update-dimension` `write-image` `copy_sheet` `update_sheet` `submit_export_job` `query_export_job` `create_filter` `get_filter` `update_filter` `delete_filter` `set_filter_criteria` `clear_filter_criteria` `sort_filter`) | 在线电子表格(`contentType=ALIDOC`、`extension=axls`):工作表 CRUD、区域读写/追加、行列操作、合并、查找替换、命名筛选视图 + 表级筛选、写入图片、异步导出(`submit_export_job` + `query_export_job`,v1.0.25 暂无合并的 `export` 命令) |
| 知识库 | `wiki` | 7 | `space` `member` | 知识库管理:空间 `create` / `get` / `list` / `search` + 成员 `add` / `list` / `update` |
| 开发者文档 | `devdoc` | 1 | `article` | 搜索钉钉开放平台文档 |
| AI 搜问 | `aisearch` | 1 | `person` | 企业人员搜索:按姓名 / 部门 / 职位 / 职责 / 上级 / 下级 / 手机号 / 工号 多维度过滤(单命令) |
| AI 应用 | `aiapp` | 3 | — | AI 应用生命周期:`create`(含 prompt / attachments / skills)/ `query`(按任务 ID)/ `modify`(按 thread ID) |
| 直播 | `live` | 1 | `stream` | 钉钉直播:查看我的直播列表 |
| Raw API | `api` | 1 | — | 直接调用任意钉钉 OpenAPI(api / oapi 双形态),自动管理应用级 Token |
> **16 个产品,204 条命令。** 完整命令清单(带描述与使用场景):[`docs/command-index.md`](./docs/command-index.md)。运行 `dws --help` 查看顶层命令树,或 `dws <service> --help` 查看子命令。
> **19 个产品,213 条命令。** 完整命令清单(带描述与使用场景):[`docs/command-index.md`](./docs/command-index.md)。运行 `dws --help` 查看顶层命令树,或 `dws <service> --help` 查看子命令。
> **关于 `chat bot`**:机器人能力(`send-by-bot` / `recall-by-bot` / `add-bot` / `send-by-webhook` / bot 搜索)已合并到对应的 `chat` 子树下(例如 `dws chat message send-by-bot`、`dws chat group members add-bot`),保持 agent 视角下的命令面扁平易发现。不再有独立的顶层 `bot` 产品。
<details>
<summary>即将推出</summary>
`conference`(视频会议)· `aiapp`(AI 应用)· `live`(直播)
`conference`(视频会议)
</details>
+22 -1
View File
@@ -210,6 +210,25 @@ func shouldUseDirectRuntime(invocation executor.Invocation) bool {
}
}
// directRuntimeToolEndpoint returns the MCP endpoint owned by the server
// whose toolOverrides registered this tool name. Used to correct catalog
// lookups when two envelope servers share the same cli.command and the
// per-product endpoint map collides (see runner.go cross-check).
func directRuntimeToolEndpoint(toolName string) (string, bool) {
toolName = strings.TrimSpace(toolName)
if toolName == "" {
return "", false
}
dynamicMu.RLock()
te := dynamicToolEndpoints
dynamicMu.RUnlock()
if te == nil {
return "", false
}
endpoint, ok := te[toolName]
return endpoint, ok && strings.TrimSpace(endpoint) != ""
}
func directRuntimeEndpoint(productID, toolName string) (string, bool) {
// Priority 0: env-var override always wins (DINGTALK_<PRODUCT>_MCP_URL).
normalized := normalizeDirectRuntimeProductID(productID)
@@ -310,7 +329,9 @@ func AppendDynamicServer(server market.ServerDescriptor) {
}
cmd := strings.TrimSpace(server.CLI.Command)
if cmd != "" && cmd != id && endpoint != "" {
dynamicEndpoints[cmd] = endpoint
if _, exists := dynamicEndpoints[cmd]; !exists {
dynamicEndpoints[cmd] = endpoint
}
dynamicProducts[cmd] = true
}
for _, alias := range server.CLI.Aliases {
@@ -270,6 +270,68 @@ func TestDirectRuntimeEndpoint_ProductLevelWinsOverConflictingToolLevel(t *testi
}
}
// --- Command field first-writer-wins regression test ---
//
// When two plugins declare the same CLI.Command but different CLI.ID values,
// AppendDynamicServer must NOT let the second registration overwrite the
// command → endpoint mapping established by the first. The fix uses a simple
// "if not exists" guard on dynamicEndpoints[cmd].
const (
testFirstEndpoint = "https://mcp-gw.dingtalk.com/server/first-plugin-hash"
testSecondEndpoint = "https://mcp-gw.dingtalk.com/server/second-plugin-hash"
)
func firstPluginDescriptor() market.ServerDescriptor {
return market.ServerDescriptor{
Endpoint: testFirstEndpoint,
CLI: market.CLIOverlay{
ID: "plugin-alpha",
Command: "shared-cmd",
},
}
}
func secondPluginDescriptor() market.ServerDescriptor {
return market.ServerDescriptor{
Endpoint: testSecondEndpoint,
CLI: market.CLIOverlay{
ID: "plugin-beta",
Command: "shared-cmd",
},
}
}
// TestAppendDynamicServer_CommandEndpointFirstWriterWins verifies that when
// two plugins declare the same Command (but different IDs), only the first
// registration takes effect for the command → endpoint mapping. The second
// plugin's own id-based endpoint is unaffected.
func TestAppendDynamicServer_CommandEndpointFirstWriterWins(t *testing.T) {
withCleanDynamicRegistry(t)
AppendDynamicServer(firstPluginDescriptor())
AppendDynamicServer(secondPluginDescriptor())
// The command "shared-cmd" must resolve to the first plugin's endpoint.
assertEndpoint(t, "shared-cmd", "", testFirstEndpoint)
// Each plugin's own id-based endpoint is always unconditionally written.
assertEndpoint(t, "plugin-alpha", "", testFirstEndpoint)
assertEndpoint(t, "plugin-beta", "", testSecondEndpoint)
// Command must appear in dynamicProducts (discovery) regardless.
ids := DirectRuntimeProductIDs()
if !ids["shared-cmd"] {
t.Fatal("shared-cmd not found in DirectRuntimeProductIDs()")
}
if !ids["plugin-alpha"] {
t.Fatal("plugin-alpha not found in DirectRuntimeProductIDs()")
}
if !ids["plugin-beta"] {
t.Fatal("plugin-beta not found in DirectRuntimeProductIDs()")
}
}
// TestDirectRuntimeEndpoint_ToolLevelFallbackWhenProductUnknown verifies that
// tool-level routing still works as a fallback when productID is empty or has
// no registered endpoint (the original design intent for tool-level Priority 1).
+75
View File
@@ -0,0 +1,75 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
stderrors "errors"
"fmt"
"strings"
"testing"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/spf13/cobra"
)
func TestFlagErrorWithSuggestions_authStructured(t *testing.T) {
t.Parallel()
cmd := &cobra.Command{Use: "login", Run: func(*cobra.Command, []string) {}}
orig := fmt.Errorf("unknown flag: --json")
err := flagErrorWithSuggestions(cmd, orig)
var ae *apperrors.Error
if !stderrors.As(err, &ae) {
t.Fatalf("want *apperrors.Error, got %T", err)
}
if ae.Message != orig.Error() {
t.Fatalf("Message = %q, want %q", ae.Message, orig.Error())
}
if ae.Reason != "unknown_flag" {
t.Fatalf("Reason = %q, want unknown_flag", ae.Reason)
}
if ae.Hint == "" || !strings.Contains(ae.Hint, "format json") {
t.Fatalf("Hint = %q", ae.Hint)
}
if ae.Cause != orig {
t.Fatalf("Cause = %v, want orig", ae.Cause)
}
if !stderrors.Is(err, orig) {
t.Fatal("errors.Is(err, orig) should hold via unwrap")
}
}
func TestFlagErrorWithSuggestions_unknownFlagHintAndFlags(t *testing.T) {
t.Parallel()
cmd := &cobra.Command{Use: "list", Run: func(*cobra.Command, []string) {}}
cmd.Flags().String("start", "", "begin time")
_ = cmd.Flags().SetAnnotation("start", "x-cli-format", []string{"date-time"})
orig := fmt.Errorf("unknown flag: --starttime1")
err := flagErrorWithSuggestions(cmd, orig)
var ae *apperrors.Error
if !stderrors.As(err, &ae) {
t.Fatalf("want *apperrors.Error, got %T", err)
}
if ae.Reason != "unknown_flag" {
t.Fatalf("Reason = %q", ae.Reason)
}
if strings.Contains(ae.Hint, "Space required") {
t.Fatalf("false glue must not suggest space: %q", ae.Hint)
}
if !strings.Contains(ae.Hint, "help") {
t.Fatalf("expected help fallback in hint, got %q", ae.Hint)
}
if len(ae.AvailableFlags) != 1 || ae.AvailableFlags[0] != "start" {
t.Fatalf("AvailableFlags = %v, want [start]", ae.AvailableFlags)
}
}
+5 -5
View File
@@ -624,7 +624,7 @@ func TestHandlePatAuthCheck_Approved(t *testing.T) {
if !retryHasKey {
t.Fatal("expected retry context to have patRetryingKey")
}
if _, err := os.Stat(filepath.Join(configDir, "app.json")); err != nil {
if _, err := os.Stat(authpkg.GetAppConfigPath(configDir)); err != nil {
t.Fatalf("expected approved PAT flow to persist app.json, stat error = %v", err)
}
// Verify SetClientIDFromMCP was called with the PAT response clientId.
@@ -700,7 +700,7 @@ func TestHandlePatAuthCheck_HostControlledFlowIDPassthrough(t *testing.T) {
if got := strings.TrimSpace(buf.String()); got != "" {
t.Fatalf("expected no human-readable output in host mode, got %q", got)
}
if _, err := os.Stat(filepath.Join(tmpDir, "app.json")); !os.IsNotExist(err) {
if _, err := os.Stat(authpkg.GetAppConfigPath(tmpDir)); !os.IsNotExist(err) {
t.Fatalf("host-owned PAT must not persist shared app.json, stat error = %v", err)
}
@@ -759,7 +759,7 @@ func TestHandlePatAuthCheck_HostControlledEmptyFlowID_StillReturnsContract(t *te
if got := strings.TrimSpace(buf.String()); got != "" {
t.Fatalf("expected no human-readable output in host mode, got %q", got)
}
if _, err := os.Stat(filepath.Join(tmpDir, "app.json")); !os.IsNotExist(err) {
if _, err := os.Stat(authpkg.GetAppConfigPath(tmpDir)); !os.IsNotExist(err) {
t.Fatalf("host-owned PAT must not persist shared app.json, stat error = %v", err)
}
patOut, ok := err.(*apperrors.PATError)
@@ -855,7 +855,7 @@ func TestHandlePatAuthCheck_JSONModeReturnsStructuredPATErrorWithoutRetry(t *tes
if got := strings.TrimSpace(buf.String()); got != "" {
t.Fatalf("expected no human-readable output in json PAT mode, got %q", got)
}
if _, err := os.Stat(filepath.Join(tmpDir, "app.json")); !os.IsNotExist(err) {
if _, err := os.Stat(authpkg.GetAppConfigPath(tmpDir)); !os.IsNotExist(err) {
t.Fatalf("json PAT mode must not persist shared app.json, stat error = %v", err)
}
@@ -918,7 +918,7 @@ func TestHandlePatAuthCheck_JSONModeCanOpenBrowserWithoutTextOutput(t *testing.T
if got := strings.TrimSpace(buf.String()); got != "" {
t.Fatalf("expected no human-readable output in json PAT mode, got %q", got)
}
if _, err := os.Stat(filepath.Join(tmpDir, "app.json")); !os.IsNotExist(err) {
if _, err := os.Stat(authpkg.GetAppConfigPath(tmpDir)); !os.IsNotExist(err) {
t.Fatalf("json PAT mode must not persist shared app.json, stat error = %v", err)
}
if opened != rawURI {
+24 -1
View File
@@ -47,6 +47,7 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/plugin"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/recovery"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/cmdutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
@@ -133,7 +134,28 @@ func flagErrorWithSuggestions(cmd *cobra.Command, err error) error {
for flag, suggestion := range suggestions {
if strings.Contains(errMsg, "unknown flag: "+flag) {
return fmt.Errorf("%w\n%s", err, suggestion)
return apperrors.NewValidation(
errMsg,
apperrors.WithHint(suggestion),
apperrors.WithReason("unknown_flag"),
apperrors.WithCause(err),
apperrors.WithActions(fmt.Sprintf("Run '%s --help' for valid flags", cmd.CommandPath())),
apperrors.WithAvailableFlags(cmdutil.VisibleFlagNames(cmd)...),
)
}
}
if strings.Contains(errMsg, "unknown flag:") {
fix := cmdutil.SuggestFlagFix(cmd, err)
if fix.Suggestion != "" {
return apperrors.NewValidation(
errMsg,
apperrors.WithHint(fix.Suggestion),
apperrors.WithReason("unknown_flag"),
apperrors.WithCause(err),
apperrors.WithActions(fmt.Sprintf("Run '%s --help' for valid flags", cmd.CommandPath())),
apperrors.WithAvailableFlags(cmdutil.VisibleFlagNames(cmd)...),
)
}
}
@@ -245,6 +267,7 @@ func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine)
root := &cobra.Command{
Use: "dws",
Short: "DWS CLI",
Long: `提示: 如果遇到能力缺失、命令报错、新功能未注册、或无法完成任务, 请先用 'dws upgrade' 升级到最新版本后再试. 钉钉 OpenAPI 和 dws CLI 持续迭代, 新能力和 bugfix 会先在新版本上线.`,
Args: cobra.NoArgs,
SilenceErrors: true,
SilenceUsage: true,
+10
View File
@@ -82,6 +82,16 @@ func renderRootHelp(root *cobra.Command) {
_, _ = fmt.Fprintln(w)
}
_, _ = fmt.Fprintln(w, `Use "dws <service> --help" for more information about a discovered MCP service or "dws <command> --help" for utility commands.`)
// Render root.Long after the command list so agents see the upgrade
// hint (or any other root-level guidance) after browsing all available
// commands and concluding none of them fit. Cobra's default help template
// would render Long automatically; the custom SetHelpFunc above replaces
// it and dropped this, so we restore it explicitly here.
if long := strings.TrimSpace(root.Long); long != "" {
_, _ = fmt.Fprintln(w)
_, _ = fmt.Fprintln(w, long)
}
}
// resolveVisibleProducts returns the set of top-level product IDs that should
+13
View File
@@ -219,6 +219,19 @@ func (r *runtimeRunner) Run(ctx context.Context, invocation executor.Invocation)
if override, ok := productEndpointOverride(invocation.CanonicalProduct); ok {
endpoint = override
}
// Multi-server tool-name authority correction.
//
// When two envelope servers share the same cli.command (e.g. group-chat
// and im both publish `dws chat ...`), the endpoints[cmd] map in
// registerDynamicServer is the second-writer wins, and catalog FindProduct
// may pick the wrong product's Endpoint for a tool whose real owner is
// a different server. Cross-check the canonical tool→endpoint map: when
// the per-tool endpoint exists and differs from the per-product endpoint
// catalog returned, trust the tool-owner endpoint (the server that
// actually declares this tool in its toolOverrides).
if toolEndpoint, ok := directRuntimeToolEndpoint(invocation.Tool); ok && toolEndpoint != "" && toolEndpoint != endpoint {
endpoint = toolEndpoint
}
return r.executeInvocation(ctx, endpoint, invocation)
}
+44 -6
View File
@@ -10,6 +10,7 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
@@ -580,13 +581,18 @@ func validateNewBinary(binaryPath, expectedVersion string) error {
return fmt.Errorf("设置执行权限失败: %w", err)
}
// Try running the binary
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, binaryPath, "version").CombinedOutput()
out, err := tryExecVersion(binaryPath)
if err != nil {
return fmt.Errorf("二进制无法执行: %w", err)
// Apple Silicon kills unsigned arm64 binaries with SIGKILL via amfid.
// Repair the binary in-place (ad-hoc codesign + drop quarantine) and retry once.
if runtime.GOOS == "darwin" && isLikelyAMFIKill(err) {
if repairErr := repairDarwinBinary(binaryPath); repairErr == nil {
out, err = tryExecVersion(binaryPath)
}
}
if err != nil {
return fmt.Errorf("二进制无法执行: %w", err)
}
}
if !strings.Contains(string(out), expectedVersion) {
@@ -596,6 +602,38 @@ func validateNewBinary(binaryPath, expectedVersion string) error {
return nil
}
func tryExecVersion(binaryPath string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return exec.CommandContext(ctx, binaryPath, "version").CombinedOutput()
}
// isLikelyAMFIKill returns true when err looks like macOS amfid SIGKILL'ing an
// unsigned binary. Go reports this as "signal: killed".
func isLikelyAMFIKill(err error) bool {
if err == nil {
return false
}
msg := err.Error()
return strings.Contains(msg, "signal: killed") || strings.Contains(msg, "signal: kill")
}
// repairDarwinBinary applies an ad-hoc codesign and clears the quarantine xattr.
// Used as a self-heal step when an unsigned binary is killed by amfid on Apple Silicon.
func repairDarwinBinary(binaryPath string) error {
// Best-effort: strip quarantine. Failure is fine (attribute often absent).
_ = exec.Command("xattr", "-d", "com.apple.quarantine", binaryPath).Run()
if _, err := exec.LookPath("codesign"); err != nil {
return fmt.Errorf("codesign 不可用: %w", err)
}
out, err := exec.Command("codesign", "--force", "--sign", "-", binaryPath).CombinedOutput()
if err != nil {
return fmt.Errorf("codesign 失败: %v: %s", err, strings.TrimSpace(string(out)))
}
return nil
}
// extractTarGz extracts a .tar.gz file using the system tar command.
func extractTarGz(archivePath, destDir string) error {
os.MkdirAll(destDir, 0755)
+80
View File
@@ -7,8 +7,11 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
@@ -428,3 +431,80 @@ func TestNewUpgradeCommand_Help(t *testing.T) {
t.Error("help should contain --rollback")
}
}
// --- isLikelyAMFIKill ---
func TestIsLikelyAMFIKill(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{"nil error", nil, false},
{"signal killed (real Go format)", errors.New("signal: killed"), true},
{"signal kill variant", errors.New("signal: kill"), true},
{"unrelated error", errors.New("exit status 1"), false},
{"file not found", errors.New("no such file or directory"), false},
{"wrapped killed in middle", errors.New("exec: signal: killed: cleanup"), true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isLikelyAMFIKill(tt.err); got != tt.want {
t.Errorf("isLikelyAMFIKill(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}
// --- validateNewBinary self-heal (darwin only) ---
//
// On macOS, an unsigned arm64 binary is SIGKILL'd by amfid. This test verifies
// validateNewBinary recovers via repairDarwinBinary (ad-hoc codesign) and
// successfully re-executes the binary. We use go itself as a stand-in for the
// new dws binary — it's a real signed Mach-O we can strip and re-sign.
func TestValidateNewBinary_RecoversFromUnsignedDarwin(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("amfid SIGKILL only happens on macOS")
}
if _, err := exec.LookPath("codesign"); err != nil {
t.Skip("codesign not available")
}
// Build a fresh dws binary into a temp dir.
tmpDir := t.TempDir()
bin := filepath.Join(tmpDir, "dws-test")
// Locate repo root from this test file's location.
wd, err := os.Getwd()
if err != nil {
t.Fatalf("getwd: %v", err)
}
repoRoot := filepath.Join(wd, "..", "..")
cmd := exec.Command("go", "build", "-o", bin, "./cmd")
cmd.Dir = repoRoot
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("go build failed: %v\n%s", err, out)
}
// Strip signature to reproduce the unsigned state from CI cross-compilation.
if out, err := exec.Command("codesign", "--remove-signature", bin).CombinedOutput(); err != nil {
t.Fatalf("strip signature: %v\n%s", err, out)
}
// Sanity: confirm direct exec is killed.
if _, err := tryExecVersion(bin); err == nil {
t.Skip("unsigned binary executed without amfid kill — likely Intel Mac or SIP disabled")
}
// validateNewBinary should self-heal and succeed.
if err := validateNewBinary(bin, "dev"); err != nil {
t.Fatalf("validateNewBinary did not recover: %v", err)
}
// Verify the binary now has an ad-hoc signature.
out, _ := exec.Command("codesign", "-dv", bin).CombinedOutput()
if !strings.Contains(string(out), "Signature=adhoc") {
t.Errorf("expected adhoc signature, got: %s", out)
}
}
+26
View File
@@ -14,6 +14,8 @@
package app
import (
"bytes"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/market"
@@ -123,3 +125,27 @@ func commandNames(cmds []*cobra.Command) []string {
}
return names
}
// TestRenderRootHelpIncludesLong guards that renderRootHelp surfaces the
// root command's Long description in `dws --help` output. The custom
// SetHelpFunc in root_help.go replaces cobra's default help template, which
// previously caused root.Long to be silently dropped. The production
// root.Long carries the "use 'dws upgrade' if a command is missing or
// failing" hint that AI agents rely on when they cannot find a suitable
// command — if this test fails after a help-rendering change, agents will
// silently lose that guidance.
func TestRenderRootHelpIncludesLong(t *testing.T) {
const sentinel = "SENTINEL-LONG-MUST-APPEAR-IN-HELP"
root := &cobra.Command{
Use: "dws",
Long: sentinel,
}
var out bytes.Buffer
root.SetOut(&out)
renderRootHelp(root)
if !strings.Contains(out.String(), sentinel) {
t.Fatalf("renderRootHelp must render root.Long verbatim in --help output; got:\n%s", out.String())
}
}
+49 -5
View File
@@ -16,21 +16,31 @@ package auth
import (
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"sync"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/helpers"
configpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
const (
// appConfigFile is the filename for storing app credentials.
appConfigFile = "app.json"
// appConfigFile is the filename for the open-source edition's app
// credentials store. Sibling editions get a name-suffixed file via
// config.EditionFileName so two dws binaries sharing the same config
// directory (~/.dws or DWS_CONFIG_DIR) cannot read/write each other's
// credentials. See GetAppConfigPath for the path derivation contract.
appConfigBase = "app"
appConfigExt = ".json"
appConfigFile = appConfigBase + appConfigExt
)
// AppConfig represents the application credentials configuration.
// This is stored in ~/.dws/app.json with the client secret securely stored in keychain.
// This is stored in the edition-specific app config file, with the client
// secret securely stored in keychain when present.
type AppConfig struct {
ClientID string `json:"clientId"`
ClientSecret SecretInput `json:"clientSecret"`
@@ -53,9 +63,14 @@ var (
cachedResolvedMu sync.RWMutex
)
// GetAppConfigPath returns the path to the app config file.
// GetAppConfigPath returns the path to the app config file for the
// currently-active edition. The filename is partitioned by edition so that
// two dws binaries from different editions sharing the same configDir
// (typically ~/.dws or DWS_CONFIG_DIR) cannot read or overwrite each
// other's credentials. Open-source stays on "app.json" for backwards
// compatibility; sibling editions land on "app-<edition>.json".
func GetAppConfigPath(configDir string) string {
return filepath.Join(configDir, appConfigFile)
return filepath.Join(configDir, configpkg.EditionFileName(edition.Get().Name, appConfigBase, appConfigExt))
}
// LoadAppConfig loads the app configuration from disk.
@@ -105,6 +120,7 @@ func SaveAppConfig(configDir string, config *AppConfig) error {
if err := helpers.AtomicWriteJSON(path, append(data, '\n')); err != nil {
return fmt.Errorf("writing app config: %w", err)
}
cleanupLegacySiblingAppConfig(configDir, config)
// Update cache
cachedAppConfigMu.Lock()
@@ -121,6 +137,34 @@ func SaveAppConfig(configDir string, config *AppConfig) error {
return nil
}
func cleanupLegacySiblingAppConfig(configDir string, config *AppConfig) {
if config == nil || config.ClientID == "" || configpkg.IsOpenEdition(edition.Get().Name) {
return
}
legacyPath := filepath.Join(configDir, appConfigFile)
if legacyPath == GetAppConfigPath(configDir) {
return
}
data, err := os.ReadFile(legacyPath)
if err != nil {
return
}
var legacy AppConfig
if err := json.Unmarshal(data, &legacy); err != nil {
return
}
if legacy.ClientID != config.ClientID {
return
}
if err := os.Remove(legacyPath); err != nil && !os.IsNotExist(err) {
slog.Debug("auth: best-effort cleanup of legacy app config failed", "path", legacyPath, "error", err)
}
}
// DeleteAppConfig removes the app configuration and associated keychain secrets.
func DeleteAppConfig(configDir string) error {
// Load existing config to clean up keychain
+256
View File
@@ -0,0 +1,256 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"os"
"path/filepath"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
// Verifies that two dws binaries from different editions sharing the same
// configDir (e.g. ~/.dws via DWS_CONFIG_DIR) read and write disjoint
// app.json files. Without partitioning, a sibling edition's post-login
// persistence path could leak its pinned ClientID into the open-source
// build by reading the shared file.
func TestGetAppConfigPath_OpenEditionUsesLegacyName(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() { edition.Override(prev) })
for _, name := range []string{"", "open"} {
edition.Override(&edition.Hooks{Name: name})
got := GetAppConfigPath("/tmp/cfg")
want := filepath.Join("/tmp/cfg", "app.json")
if got != want {
t.Fatalf("edition=%q: GetAppConfigPath = %q, want %q", name, got, want)
}
}
}
func TestGetAppConfigPath_SiblingEditionUsesSuffixedName(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() { edition.Override(prev) })
cases := []struct {
editionName string
wantFile string
}{
{"wukong", "app-wukong.json"},
{"dev", "app-dev.json"},
{"embedded", "app-embedded.json"},
}
for _, tc := range cases {
edition.Override(&edition.Hooks{Name: tc.editionName})
got := GetAppConfigPath("/tmp/cfg")
want := filepath.Join("/tmp/cfg", tc.wantFile)
if got != want {
t.Fatalf("edition=%q: GetAppConfigPath = %q, want %q", tc.editionName, got, want)
}
}
}
func TestGetAppConfigPath_OpenAndSiblingAreDisjoint(t *testing.T) {
// End-to-end invariant: when the same configDir is observed from two
// different editions, the resulting app.json paths must NOT collide.
prev := edition.Get()
t.Cleanup(func() { edition.Override(prev) })
const cfg = "/tmp/shared-cfg"
edition.Override(&edition.Hooks{Name: "open"})
openPath := GetAppConfigPath(cfg)
edition.Override(&edition.Hooks{Name: "wukong"})
wukongPath := GetAppConfigPath(cfg)
if openPath == wukongPath {
t.Fatalf("open and wukong editions share path %q; cross-edition leakage possible", openPath)
}
if filepath.Dir(openPath) != filepath.Dir(wukongPath) {
t.Fatalf("paths landed in different directories (%q vs %q); partitioning should only differ by filename", filepath.Dir(openPath), filepath.Dir(wukongPath))
}
}
func TestAppConfigIO_OpenEditionDoesNotReadSiblingCredentials(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() {
edition.Override(prev)
resetAppConfigCache()
})
configDir := t.TempDir()
edition.Override(&edition.Hooks{Name: "wukong"})
wukongPath := GetAppConfigPath(configDir)
if err := os.WriteFile(wukongPath, []byte(`{"clientId":"wukong-cid","createdAt":"2026-05-17T00:00:00+08:00"}`+"\n"), 0600); err != nil {
t.Fatalf("writing sibling app config: %v", err)
}
edition.Override(&edition.Hooks{Name: "open"})
got, err := LoadAppConfig(configDir)
if err != nil {
t.Fatalf("LoadAppConfig(open) error = %v", err)
}
if got != nil {
t.Fatalf("open edition read sibling app config: %#v", got)
}
}
func TestSaveAppConfig_SiblingEditionRemovesMatchingLegacyAppConfig(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() {
edition.Override(prev)
resetAppConfigCache()
})
configDir := t.TempDir()
legacyPath := filepath.Join(configDir, appConfigFile)
legacyJSON := []byte(`{"clientId":"wukong-cid","createdAt":"2026-05-17T00:00:00+08:00"}` + "\n")
if err := os.WriteFile(legacyPath, legacyJSON, 0600); err != nil {
t.Fatalf("writing legacy app config: %v", err)
}
edition.Override(&edition.Hooks{Name: "wukong"})
if err := SaveAppConfig(configDir, &AppConfig{ClientID: "wukong-cid"}); err != nil {
t.Fatalf("SaveAppConfig(wukong) error = %v", err)
}
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
t.Fatalf("matching legacy app config should be removed, stat error = %v", err)
}
if _, err := os.Stat(filepath.Join(configDir, "app-wukong.json")); err != nil {
t.Fatalf("sibling app config not written: %v", err)
}
}
func TestSaveAppConfig_SiblingEditionKeepsDifferentLegacyAppConfig(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() {
edition.Override(prev)
resetAppConfigCache()
})
configDir := t.TempDir()
legacyPath := filepath.Join(configDir, appConfigFile)
legacyJSON := []byte(`{"clientId":"open-cid","createdAt":"2026-05-17T00:00:00+08:00"}` + "\n")
if err := os.WriteFile(legacyPath, legacyJSON, 0600); err != nil {
t.Fatalf("writing legacy app config: %v", err)
}
edition.Override(&edition.Hooks{Name: "wukong"})
if err := SaveAppConfig(configDir, &AppConfig{ClientID: "wukong-cid"}); err != nil {
t.Fatalf("SaveAppConfig(wukong) error = %v", err)
}
got, err := os.ReadFile(legacyPath)
if err != nil {
t.Fatalf("different legacy app config should be preserved: %v", err)
}
if string(got) != string(legacyJSON) {
t.Fatalf("legacy app config changed: got %q, want %q", got, legacyJSON)
}
}
func TestSaveAppConfig_SiblingEditionKeepsMalformedLegacyAppConfig(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() {
edition.Override(prev)
resetAppConfigCache()
})
configDir := t.TempDir()
legacyPath := filepath.Join(configDir, appConfigFile)
legacyJSON := []byte(`{"clientId":"wukong-cid"`)
if err := os.WriteFile(legacyPath, legacyJSON, 0600); err != nil {
t.Fatalf("writing malformed legacy app config: %v", err)
}
edition.Override(&edition.Hooks{Name: "wukong"})
if err := SaveAppConfig(configDir, &AppConfig{ClientID: "wukong-cid"}); err != nil {
t.Fatalf("SaveAppConfig(wukong) error = %v", err)
}
got, err := os.ReadFile(legacyPath)
if err != nil {
t.Fatalf("malformed legacy app config should be preserved: %v", err)
}
if string(got) != string(legacyJSON) {
t.Fatalf("malformed legacy app config changed: got %q, want %q", got, legacyJSON)
}
}
func TestSaveAppConfig_OpenEditionDoesNotCleanSiblingAppConfigs(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() {
edition.Override(prev)
resetAppConfigCache()
})
configDir := t.TempDir()
siblingFiles := map[string][]byte{
"app-wukong.json": []byte(`{"clientId":"wukong-cid","createdAt":"2026-05-17T00:00:00+08:00"}` + "\n"),
"app-dev.json": []byte(`{"clientId":"dev-cid","createdAt":"2026-05-17T00:00:00+08:00"}` + "\n"),
}
for name, data := range siblingFiles {
if err := os.WriteFile(filepath.Join(configDir, name), data, 0600); err != nil {
t.Fatalf("writing sibling app config %s: %v", name, err)
}
}
edition.Override(&edition.Hooks{Name: "open"})
if err := SaveAppConfig(configDir, &AppConfig{ClientID: "open-cid"}); err != nil {
t.Fatalf("SaveAppConfig(open) error = %v", err)
}
for name, want := range siblingFiles {
got, err := os.ReadFile(filepath.Join(configDir, name))
if err != nil {
t.Fatalf("open edition should preserve sibling app config %s: %v", name, err)
}
if string(got) != string(want) {
t.Fatalf("sibling app config %s changed: got %q, want %q", name, got, want)
}
}
}
func TestSaveAppConfig_SiblingEditionKeepsLegacyAppConfigWhenClientIDEmpty(t *testing.T) {
prev := edition.Get()
t.Cleanup(func() {
edition.Override(prev)
resetAppConfigCache()
})
configDir := t.TempDir()
legacyPath := filepath.Join(configDir, appConfigFile)
legacyJSON := []byte(`{"clientId":"wukong-cid","createdAt":"2026-05-17T00:00:00+08:00"}` + "\n")
if err := os.WriteFile(legacyPath, legacyJSON, 0600); err != nil {
t.Fatalf("writing legacy app config: %v", err)
}
edition.Override(&edition.Hooks{Name: "wukong"})
if err := SaveAppConfig(configDir, &AppConfig{}); err != nil {
t.Fatalf("SaveAppConfig(wukong empty client ID) error = %v", err)
}
got, err := os.ReadFile(legacyPath)
if err != nil {
t.Fatalf("legacy app config should be preserved when client ID is empty: %v", err)
}
if string(got) != string(legacyJSON) {
t.Fatalf("legacy app config changed: got %q, want %q", got, legacyJSON)
}
}
+45 -9
View File
@@ -19,6 +19,7 @@ import (
"os"
"strings"
"sync"
"unicode"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
)
@@ -122,19 +123,51 @@ func readStdinBounded() (string, error) {
return string(data), nil
}
// looksLikeFilePath returns true when value should be interpreted as the
// `@<path>` file-injection syntax. Heuristic: value must start with '@', and
// the character right after '@' must be ASCII (letter, digit, or one of the
// common path-prefix characters: . / ~ _ -). This rules out mistaken matches
// for natural-language messages that happen to start with '@' followed by
// non-ASCII text — e.g. "@所有人" should be a chat mention, not a file path.
func looksLikeFilePath(value string) bool {
if !strings.HasPrefix(value, "@") || len(value) < 2 {
return false
}
rest := value[1:]
if rest == "-" {
return true // @- = stdin
}
first := rune(rest[0])
if first > unicode.MaxASCII {
// First byte is part of a multi-byte rune (e.g. Chinese) — not a path.
return false
}
switch {
case first >= 'A' && first <= 'Z',
first >= 'a' && first <= 'z',
first >= '0' && first <= '9',
first == '.', first == '/', first == '~', first == '_', first == '-':
return true
}
return false
}
// ReadFileArg reads the contents of a file referenced by the @filename syntax.
// Returns the original value unchanged if it does not start with "@".
// Returns the original value unchanged if it does not start with "@" or is
// otherwise not a file-path-shaped value (e.g. "@所有人" is treated as plain
// text, not a path).
// Returns an error if the file cannot be read or exceeds the size limit.
//
// Note: @- (stdin) is NOT handled here; use ResolveInputSource instead.
func ReadFileArg(value string) (string, bool, error) {
if !strings.HasPrefix(value, "@") {
// Preserve the historical bare-"@" behaviour (empty filename → error).
if value == "@" {
return "", false, apperrors.NewValidation("@file: filename must not be empty")
}
if !looksLikeFilePath(value) {
return value, false, nil
}
path := value[1:]
if path == "" {
return "", false, apperrors.NewValidation("@file: filename must not be empty")
}
// @- is stdin, not a file — callers should use ResolveInputSource.
if path == "-" {
return value, false, nil
@@ -156,14 +189,17 @@ func ReadFileArg(value string) (string, bool, error) {
//
// The flagName parameter is used only for error messages and StdinGuard tracking.
func ResolveInputSource(value string, flagName string, guard *StdinGuard) (string, error) {
if !strings.HasPrefix(value, "@") {
// Preserve the historical bare-"@" behaviour (empty filename → error).
if value == "@" {
return "", apperrors.NewValidation(fmt.Sprintf("--%s: @file filename must not be empty", flagName))
}
if !looksLikeFilePath(value) {
// Pass through natural-language strings that happen to start with
// '@' (e.g. "@所有人 早上好") so they reach the MCP payload intact.
return value, nil
}
path := value[1:]
if path == "" {
return "", apperrors.NewValidation(fmt.Sprintf("--%s: @file filename must not be empty", flagName))
}
// @- reads from stdin.
if path == "-" {
+32
View File
@@ -47,6 +47,38 @@ func TestReadFileArgPlainValue(t *testing.T) {
}
}
// TestReadFileArgChineseAtMention guards the @所有人-style mentions that the
// chat bot Webhook tests rely on: an '@' followed by non-ASCII text must be
// treated as a literal message, not as the @file injection syntax.
func TestReadFileArgChineseAtMention(t *testing.T) {
t.Parallel()
cases := []string{
"@所有人 这是 @ 所有人 的消息",
"@张三",
"@A 但接下来都是中文@测试",
}
for _, in := range cases {
val, isFile, err := ReadFileArg(in)
if in == "@A 但接下来都是中文@测试" {
// '@A' starts with ASCII, treated as path → expect file error
if err == nil {
t.Errorf("@A... should attempt file lookup; got val=%q isFile=%v", val, isFile)
}
continue
}
if err != nil {
t.Errorf("%q: unexpected error %v", in, err)
continue
}
if isFile {
t.Errorf("%q: should be plain text, got isFile=true", in)
}
if val != in {
t.Errorf("%q: got %q", in, val)
}
}
}
func TestReadFileArgReadsFile(t *testing.T) {
t.Parallel()
+105 -15
View File
@@ -236,10 +236,18 @@ func BuildDynamicCommands(servers []market.ServerDescriptor, runner executor.Run
for _, b := range built {
if b.parent == "" {
name := b.cmd.Name()
if _, exists := topLevel[name]; !exists {
if existing, exists := topLevel[name]; exists {
// Multiple servers contribute the same top-level command
// (e.g. group-chat and im both register `dws chat`). Move
// the incoming command's *children* into the existing top-
// level command instead of attaching the whole command (which
// would create `dws chat chat` because attachOrMerge would
// AddCommand(b.cmd) when no same-named sub exists).
mergeSubcommandsInto(existing, b.cmd)
} else {
topOrder = append(topOrder, name)
topLevel[name] = b.cmd
}
topLevel[name] = b.cmd
} else {
children = append(children, b)
}
@@ -248,12 +256,16 @@ func BuildDynamicCommands(servers []market.ServerDescriptor, runner executor.Run
if parent, ok := topLevel[child.parent]; ok {
attachOrMerge(parent, child.cmd)
} else {
// Parent not found among dynamic commands; emit as top-level.
// Parent not found among dynamic commands; emit as top-level,
// merging into an existing same-named top-level command if one
// is already registered (same reasoning as the loop above).
name := child.cmd.Name()
if _, exists := topLevel[name]; !exists {
if existing, exists := topLevel[name]; exists {
mergeSubcommandsInto(existing, child.cmd)
} else {
topOrder = append(topOrder, name)
topLevel[name] = child.cmd
}
topLevel[name] = child.cmd
}
}
@@ -283,10 +295,12 @@ type toolRequestSchema struct {
}
type toolRequestProp struct {
Type string `json:"type"`
Title string `json:"title"`
Description string `json:"description"`
Default string `json:"default,omitempty"`
Type string `json:"type"`
Title string `json:"title"`
Description string `json:"description"`
Default string `json:"default,omitempty"`
Format string `json:"format,omitempty"`
Enum []string `json:"enum,omitempty"`
}
// buildFlagsFromDetailSchema adds properly-typed cobra flags to cmd based on
@@ -371,6 +385,17 @@ func buildFlagsFromDetailSchema(cmd *cobra.Command, schemaJSON string, flagOverr
cmd.Flags().String(flagName, defaultVal, help)
}
// Carry schema "format" / "enum" hints onto the cobra flag via
// pflag annotations so PreParse handlers (e.g. StickyHandler)
// can reason about whether a glued suffix looks like a real
// value. The annotation keys are read by FlagInfoFromCommand.
if prop.Format != "" {
_ = cmd.Flags().SetAnnotation(flagName, "x-cli-format", []string{prop.Format})
}
if len(prop.Enum) > 0 {
_ = cmd.Flags().SetAnnotation(flagName, "x-cli-enum", append([]string{}, prop.Enum...))
}
if requiredSet[key] {
_ = cmd.MarkFlagRequired(flagName)
}
@@ -478,6 +503,24 @@ func resolveNestedGroup(root *cobra.Command, groupPath string, registry map[stri
return ensureNestedGroup(root, groupPath, groupPath, registry)
}
// mergeSubcommandsInto moves all sub-commands of src into dst, using
// attachOrMerge so subtree merges happen recursively. src itself is left
// empty after the call. Used when two envelope entries register the same
// top-level command (e.g. group-chat and im both `cli.command="chat"`):
// we want their *children* to coexist under one chat root, not have one
// nested inside the other.
func mergeSubcommandsInto(dst, src *cobra.Command) {
if dst == nil || src == nil {
return
}
subs := make([]*cobra.Command, len(src.Commands()))
copy(subs, src.Commands())
for _, sub := range subs {
src.RemoveCommand(sub)
attachOrMerge(dst, sub)
}
}
// attachOrMerge adds child as a sub-command of parent. If parent already has a
// sub-command with the same Name(), the two are merged recursively: child's
// sub-commands are moved onto the existing one and child itself is discarded.
@@ -532,10 +575,19 @@ func buildOverrideBindings(override market.CLIToolOverride) ([]FlagBinding, Norm
var bindings []FlagBinding
type transformEntry struct {
paramName string
mapsTo string
transform string
transformArgs map[string]any
}
var transforms []transformEntry
// mapsToRoutes captures flags that only need value-routing (no transform)
// — e.g. a literal --content flag that mapsTo "markdown". The dispatch
// loop moves params[paramName] → params[mapsTo] after CLI binding.
type mapsToRoute struct {
paramName string
mapsTo string
}
var mapsToRoutes []mapsToRoute
type envDefaultEntry struct {
paramName string
envVar string
@@ -664,9 +716,19 @@ func buildOverrideBindings(override market.CLIToolOverride) ([]FlagBinding, Norm
if flagOverride.Transform != "" {
transforms = append(transforms, transformEntry{
paramName: paramName,
mapsTo: strings.TrimSpace(flagOverride.MapsTo),
transform: flagOverride.Transform,
transformArgs: flagOverride.TransformArgs,
})
} else if mt := strings.TrimSpace(flagOverride.MapsTo); mt != "" {
// mapsTo without transform: just route the literal value into a
// different MCP parameter slot. Common case is --content (literal
// string) mapping to MCP parameter markdown, alongside a sibling
// --content-file (transform: file_read) mapping to the same slot.
mapsToRoutes = append(mapsToRoutes, mapsToRoute{
paramName: paramName,
mapsTo: mt,
})
}
if flagOverride.EnvDefault != "" {
envDefaults = append(envDefaults, envDefaultEntry{
@@ -699,12 +761,15 @@ func buildOverrideBindings(override market.CLIToolOverride) ([]FlagBinding, Norm
}
}
bodyWrapper := strings.TrimSpace(override.BodyWrapper)
if len(transforms) == 0 && len(envDefaults) == 0 && len(defaultInjects) == 0 && len(runtimeDefaults) == 0 && len(omits) == 0 && !needsDottedNesting && bodyWrapper == "" {
if len(transforms) == 0 && len(envDefaults) == 0 && len(defaultInjects) == 0 && len(runtimeDefaults) == 0 && len(omits) == 0 && len(mapsToRoutes) == 0 && !needsDottedNesting && bodyWrapper == "" {
return bindings, nil
}
// Build a normalizer that applies default injections + env defaults + runtime defaults
// + transforms + omitWhen + nesting + body wrap.
// Build a normalizer that applies default injections + env defaults +
// runtime defaults + transforms + mapsTo routing + omitWhen + nesting +
// body wrap. Tool-level cobra constraints (MutuallyExclusive /
// RequireOneOf) are wired separately via applyFlagConstraints and don't
// belong in this closure.
normalizer := func(cmd *cobra.Command, params map[string]any) error {
// §v3.2: Apply envelope flag.default for parameters not explicitly set.
// Coerce by Kind so number-typed schemas don't reject string defaults.
@@ -756,14 +821,21 @@ func buildOverrideBindings(override market.CLIToolOverride) ([]FlagBinding, Norm
}
}
// §3: Apply transforms
// §3: Apply transforms. When MapsTo is set, the transformed value is
// routed to params[MapsTo] and the original params[paramName] is
// dropped, so the MCP body carries a single (post-transform) entry
// at the target slot.
for _, t := range transforms {
val, exists := params[t.paramName]
if !exists {
// For enum_map with _default, apply default even when flag is omitted
if t.transform == "enum_map" && t.transformArgs != nil {
if defaultVal, hasDefault := t.transformArgs["_default"]; hasDefault {
params[t.paramName] = defaultVal
target := t.paramName
if t.mapsTo != "" {
target = t.mapsTo
}
params[target] = defaultVal
}
}
continue
@@ -772,7 +844,25 @@ func buildOverrideBindings(override market.CLIToolOverride) ([]FlagBinding, Norm
if err != nil {
return err
}
params[t.paramName] = transformed
if t.mapsTo != "" {
params[t.mapsTo] = transformed
delete(params, t.paramName)
} else {
params[t.paramName] = transformed
}
}
// §3b: mapsTo-only routes (no transform). Move params[paramName] →
// params[mapsTo] verbatim. Common pattern: a literal --content flag
// that routes to MCP parameter `markdown`, alongside a sibling
// --content-file flag that transforms + routes to the same slot.
for _, r := range mapsToRoutes {
val, exists := params[r.paramName]
if !exists {
continue
}
params[r.mapsTo] = val
delete(params, r.paramName)
}
// §v3.2.2: Apply omitWhen — drop keys whose value meets the omit
+282
View File
@@ -15,6 +15,8 @@ package compat
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
@@ -1945,3 +1947,283 @@ func TestBuildDynamicCommands_ParentMergeLeafCollision(t *testing.T) {
t.Fatalf("expected exactly one 'send' leaf, got %d", sendCount)
}
}
// TestBuildFlagsFromDetailSchema_FormatEnumAnnotations verifies that the
// JSON Schema "format" and "enum" hints are copied onto the cobra flag's
// pflag annotations under x-cli-format / x-cli-enum, so PreParse
// handlers can use them when deciding whether to split glued tokens.
func TestBuildFlagsFromDetailSchema_FormatEnumAnnotations(t *testing.T) {
t.Parallel()
servers := []market.ServerDescriptor{
{
Endpoint: "https://endpoint-calendar",
CLI: market.CLIOverlay{
ID: "calendar",
Command: "calendar",
ToolOverrides: map[string]market.CLIToolOverride{
"event_list": {CLIName: "list"},
},
},
},
}
details := map[string][]market.DetailTool{
"calendar": {
{
ToolName: "event_list",
ToolRequest: `{"properties":{` +
`"start":{"type":"string","format":"date-time","description":"开始时间"},` +
`"end":{"type":"string","format":"date-time","description":"结束时间"},` +
`"status":{"type":"string","enum":["confirmed","tentative","cancelled"]}` +
`}}`,
},
},
}
cmds := BuildDynamicCommands(servers, executor.EchoRunner{}, details)
list := findChild(cmds[0], "list")
if list == nil {
t.Fatal("list leaf not found")
}
startFlag := list.Flags().Lookup("start")
if startFlag == nil {
t.Fatal("--start flag missing")
}
if got := startFlag.Annotations["x-cli-format"]; len(got) != 1 || got[0] != "date-time" {
t.Errorf("--start x-cli-format = %v, want [date-time]", got)
}
endFlag := list.Flags().Lookup("end")
if endFlag == nil {
t.Fatal("--end flag missing")
}
if got := endFlag.Annotations["x-cli-format"]; len(got) != 1 || got[0] != "date-time" {
t.Errorf("--end x-cli-format = %v, want [date-time]", got)
}
statusFlag := list.Flags().Lookup("status")
if statusFlag == nil {
t.Fatal("--status flag missing")
}
gotEnum := statusFlag.Annotations["x-cli-enum"]
wantEnum := []string{"confirmed", "tentative", "cancelled"}
if !equalStringSlice(gotEnum, wantEnum) {
t.Errorf("--status x-cli-enum = %v, want %v", gotEnum, wantEnum)
}
// Status has no format and should not carry x-cli-format.
if got := statusFlag.Annotations["x-cli-format"]; len(got) != 0 {
t.Errorf("--status should not have x-cli-format, got %v", got)
}
}
// TestBuildDynamicCommands_MapsTo_WithoutTransform verifies that a flag
// carrying only MapsTo (no transform) moves its literal value to the
// target MCP parameter slot and drops the source key. The canonical use
// case is exposing --content as a sibling of --markdown that both feed
// the same upstream `markdown` parameter.
func TestBuildDynamicCommands_MapsTo_WithoutTransform(t *testing.T) {
t.Parallel()
runner := &captureRunner{}
servers := []market.ServerDescriptor{
{
Endpoint: "https://endpoint-doc",
CLI: market.CLIOverlay{
ID: "doc",
Command: "doc",
ToolOverrides: map[string]market.CLIToolOverride{
"update_document": {
CLIName: "update",
Flags: map[string]market.CLIFlagOverride{
"nodeId": {Alias: "node"},
"content": {Alias: "content", MapsTo: "markdown"},
},
},
},
},
},
}
cmds := BuildDynamicCommands(servers, runner, nil)
cmds[0].SetArgs([]string{"update", "--node", "n1", "--content", "# 标题"})
cmds[0].SilenceErrors = true
cmds[0].SilenceUsage = true
if err := cmds[0].Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if runner.lastParams["markdown"] != "# 标题" {
t.Errorf("params[markdown] = %v, want '# 标题'", runner.lastParams["markdown"])
}
if _, leftover := runner.lastParams["content"]; leftover {
t.Errorf("source key 'content' must be deleted after mapsTo, got params=%+v", runner.lastParams)
}
}
// TestBuildDynamicCommands_MapsTo_WithFileReadTransform verifies the full
// envelope shape that #277 needs: a path-typed flag (--content-file) that
// reads the file via the file_read transform AND routes the resulting
// string into a sibling MCP parameter (markdown). End-to-end: user types
// a path, the upstream tool receives file contents under the right key.
func TestBuildDynamicCommands_MapsTo_WithFileReadTransform(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "note.md")
contents := "# 项目周报\n\n- 完成 A\n- 完成 B\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatalf("setup: %v", err)
}
runner := &captureRunner{}
servers := []market.ServerDescriptor{
{
Endpoint: "https://endpoint-doc",
CLI: market.CLIOverlay{
ID: "doc",
Command: "doc",
ToolOverrides: map[string]market.CLIToolOverride{
"update_document": {
CLIName: "update",
Flags: map[string]market.CLIFlagOverride{
"nodeId": {Alias: "node"},
"contentFile": {
Alias: "content-file",
MapsTo: "markdown",
Transform: "file_read",
},
},
},
},
},
},
}
cmds := BuildDynamicCommands(servers, runner, nil)
cmds[0].SetArgs([]string{"update", "--node", "n1", "--content-file", path})
cmds[0].SilenceErrors = true
cmds[0].SilenceUsage = true
if err := cmds[0].Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if runner.lastParams["markdown"] != contents {
t.Errorf("params[markdown] = %v, want file contents", runner.lastParams["markdown"])
}
if _, leftover := runner.lastParams["contentFile"]; leftover {
t.Errorf("source key 'contentFile' must be deleted after mapsTo, got params=%+v", runner.lastParams)
}
}
// TestBuildDynamicCommands_MapsTo_SiblingFlagsExclusiveSetOne verifies the
// realistic pre-prod shape: two sibling flags (--content literal and
// --content-file path) both mapsTo "markdown", guarded by the existing
// tool-level cobra MutuallyExclusive constraint. When the user sets only
// one, it routes through cleanly; the other source key is absent.
func TestBuildDynamicCommands_MapsTo_SiblingFlagsExclusiveSetOne(t *testing.T) {
t.Parallel()
runner := &captureRunner{}
servers := []market.ServerDescriptor{
{
Endpoint: "https://endpoint-doc",
CLI: market.CLIOverlay{
ID: "doc",
Command: "doc",
ToolOverrides: map[string]market.CLIToolOverride{
"update_document": {
CLIName: "update",
Flags: map[string]market.CLIFlagOverride{
"nodeId": {Alias: "node"},
"content": {Alias: "content", MapsTo: "markdown"},
"contentFile": {
Alias: "content-file",
MapsTo: "markdown",
Transform: "file_read",
},
},
MutuallyExclusive: [][]string{{"content", "content-file"}},
},
},
},
},
}
cmds := BuildDynamicCommands(servers, runner, nil)
cmds[0].SetArgs([]string{"update", "--node", "n1", "--content", "literal body"})
cmds[0].SilenceErrors = true
cmds[0].SilenceUsage = true
if err := cmds[0].Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if runner.lastParams["markdown"] != "literal body" {
t.Errorf("params[markdown] = %v, want 'literal body'", runner.lastParams["markdown"])
}
if _, leftover := runner.lastParams["content"]; leftover {
t.Errorf("source key 'content' must be deleted, got params=%+v", runner.lastParams)
}
if _, leftover := runner.lastParams["contentFile"]; leftover {
t.Errorf("untouched sibling key 'contentFile' must not appear, got params=%+v", runner.lastParams)
}
}
// TestBuildDynamicCommands_MapsTo_BothSetIsRejectedByCobra verifies that
// when both mapsTo siblings are set, the existing tool-level
// MutuallyExclusive constraint produces a cobra error before dispatch
// runs. This is a sanity regression check — the cobra mechanism is
// pre-existing, but combining it with mapsTo is the realistic envelope
// shape #277 needs.
func TestBuildDynamicCommands_MapsTo_BothSetIsRejectedByCobra(t *testing.T) {
t.Parallel()
runner := &captureRunner{}
servers := []market.ServerDescriptor{
{
Endpoint: "https://endpoint-doc",
CLI: market.CLIOverlay{
ID: "doc",
Command: "doc",
ToolOverrides: map[string]market.CLIToolOverride{
"update_document": {
CLIName: "update",
Flags: map[string]market.CLIFlagOverride{
"nodeId": {Alias: "node"},
"content": {Alias: "content", MapsTo: "markdown"},
"contentFile": {Alias: "content-file", MapsTo: "markdown", Transform: "file_read"},
},
MutuallyExclusive: [][]string{{"content", "content-file"}},
},
},
},
},
}
cmds := BuildDynamicCommands(servers, runner, nil)
cmds[0].SetArgs([]string{"update", "--node", "n1", "--content", "x", "--content-file", "/tmp/y"})
cmds[0].SilenceErrors = true
cmds[0].SilenceUsage = true
err := cmds[0].Execute()
if err == nil {
t.Fatal("expected mutually-exclusive error, got nil")
}
msg := err.Error()
if !strings.Contains(msg, "none of the others") && !strings.Contains(msg, "mutually") && !strings.Contains(msg, "exclusive") {
t.Fatalf("expected mutually-exclusive error, got %v", err)
}
}
// equalStringSlice is a small helper for slice comparison in tests.
func equalStringSlice(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
+6 -6
View File
@@ -149,12 +149,12 @@ func executePipelineCall(
if result.Response == nil {
return map[string]any{}, nil
}
// Fail-fast on MCP business errors. Pre-execution validation (e.g.
// cobra MarkFlagRequired) only checks that the flag was set, not
// that the value is non-empty — so a `--required-flag ""` reaches
// here and the upstream tool rejects with errorCode. Without this
// check the pipeline would happily proceed to poll/download and
// either spin until PollTimeout or burn through retries.
// Fail-fast on MCP business errors. Pre-execution validation (cobra
// MarkFlagRequired) only checks that the flag was set, not that
// the value is non-empty — so a `--required-flag ""` reaches here
// and the upstream tool rejects with errorCode. Without this check
// the pipeline proceeds to poll/download and either spins until
// PollTimeout or burns through retries.
if errCode := getDotPath(result.Response, "content.errorCode"); errCode != nil && fmt.Sprint(errCode) != "" {
msg := getDotPath(result.Response, "content.errorMessage")
return nil, apperrors.NewValidation(fmt.Sprintf(
+2 -2
View File
@@ -169,10 +169,10 @@ func NewDirectCommand(route Route, runner executor.Runner) *cobra.Command {
strictMin = b.PositionalIndex + 1
}
}
var argsValidator cobra.PositionalArgs = cobra.NoArgs
var argsValidator cobra.PositionalArgs = cobra.ArbitraryArgs
switch {
case totalMax == 0:
argsValidator = cobra.NoArgs
argsValidator = cobra.ArbitraryArgs
case strictMin > 0 && strictMin == totalMax:
argsValidator = cobra.MinimumNArgs(strictMin)
case strictMin > 0:
+69 -1
View File
@@ -16,9 +16,12 @@ package compat
import (
"encoding/json"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"unicode/utf8"
"gopkg.in/yaml.v3"
@@ -27,7 +30,7 @@ import (
// ApplyTransform applies a named transform rule to a value.
// Supported transforms: iso8601_to_millis, csv_to_array, json_parse,
// json_parse_strict, enum_map.
// json_parse_strict, enum_map, file_read, invert_bool.
func ApplyTransform(value any, transform string, args map[string]any) (any, error) {
switch strings.TrimSpace(transform) {
case "":
@@ -42,6 +45,33 @@ func ApplyTransform(value any, transform string, args map[string]any) (any, erro
return transformJSONParseStrict(value)
case "enum_map":
return transformEnumMap(value, args)
case "file_read":
return transformFileRead(value)
case "invert_bool":
return transformInvertBool(value)
default:
return value, nil
}
}
// transformInvertBool flips a boolean: true → false, false → true. Strings
// "true"/"false" (any case) are accepted. Used by envelope flags whose CLI
// surface and MCP body have opposite semantics — e.g. `--off` (CLI) maps to
// `mute=true` (MCP) for "mute is enabled", so the flag override declares
// `transform: invert_bool` and the framework flips at send time.
func transformInvertBool(value any) (any, error) {
switch v := value.(type) {
case bool:
return !v, nil
case string:
s := strings.ToLower(strings.TrimSpace(v))
switch s {
case "true", "1", "yes", "on":
return false, nil
case "false", "0", "no", "off", "":
return true, nil
}
return value, nil
default:
return value, nil
}
@@ -194,6 +224,44 @@ func transformEnumMap(value any, args map[string]any) (any, error) {
return value, nil
}
// transformFileRead reads the file at the given path and returns its contents
// as a UTF-8 string. The special path "-" reads from stdin.
//
// Typical envelope use is paired with CLIFlagOverride.MapsTo so a path-typed
// CLI flag (e.g. --content-file ./a.md) routes the file contents into a
// content-typed MCP parameter (e.g. markdown), letting a sibling literal
// flag (--content "# 标题") feed the same parameter without conflict.
//
// Errors are surfaced as validation errors so the dispatcher returns exit code 2
// (user input) rather than the generic exit code 1 (transient failure).
func transformFileRead(value any) (any, error) {
s, ok := toString(value)
if !ok {
return nil, apperrors.NewValidation("file_read: expected string path, got non-string value")
}
s = strings.TrimSpace(s)
if s == "" {
return nil, apperrors.NewValidation("file_read: empty path")
}
var buf []byte
var err error
if s == "-" {
buf, err = io.ReadAll(os.Stdin)
if err != nil {
return nil, apperrors.NewValidation(fmt.Sprintf("file_read: read stdin: %v", err))
}
} else {
buf, err = os.ReadFile(s)
if err != nil {
return nil, apperrors.NewValidation(fmt.Sprintf("file_read: read %q: %v", s, err))
}
}
if !utf8.Valid(buf) {
return nil, apperrors.NewValidation(fmt.Sprintf("file_read: %q is not valid UTF-8", s))
}
return string(buf), nil
}
func toString(v any) (string, bool) {
switch val := v.(type) {
case string:
+162
View File
@@ -14,7 +14,10 @@
package compat
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)
@@ -123,3 +126,162 @@ func TestJSONParse_InvalidInput(t *testing.T) {
t.Fatal("error message should be non-empty")
}
}
// TestFileRead_BasicFile exercises the happy path: a UTF-8 file on disk is
// read in full and surfaced as a string value. This is the contract the
// `--content-file ./a.md` flag relies on so the upstream MCP tool sees the
// file contents in place of the path.
func TestFileRead_BasicFile(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "note.md")
contents := "# Heading\n\n- bullet one\n- bullet two\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatalf("setup: %v", err)
}
got, err := ApplyTransform(path, "file_read", nil)
if err != nil {
t.Fatalf("file_read should succeed, got err: %v", err)
}
if got != contents {
t.Errorf("file_read should return file contents verbatim; got %q want %q", got, contents)
}
}
// TestFileRead_EmptyPath rejects empty input with a validation error rather
// than silently reading "" / cwd. The dispatcher maps validation errors to
// exit code 2 so the user sees a usage problem.
func TestFileRead_EmptyPath(t *testing.T) {
t.Parallel()
_, err := ApplyTransform("", "file_read", nil)
if err == nil {
t.Fatal("expected validation error for empty path")
}
if !strings.Contains(err.Error(), "file_read") {
t.Errorf("error should mention the transform name, got %q", err.Error())
}
}
// TestFileRead_MissingFile surfaces a clear validation error when the path
// doesn't exist. The previous `os.ReadFile` error is wrapped so the user
// sees what they passed.
func TestFileRead_MissingFile(t *testing.T) {
t.Parallel()
missing := filepath.Join(t.TempDir(), "definitely-not-here.md")
_, err := ApplyTransform(missing, "file_read", nil)
if err == nil {
t.Fatal("expected error for missing file")
}
if !strings.Contains(err.Error(), "definitely-not-here.md") {
t.Errorf("error should mention the missing path, got %q", err.Error())
}
}
// TestFileRead_InvalidUTF8 rejects binary input. Upstream tools expect text
// content and silently shipping a corrupted byte string would mask a real
// user error.
func TestFileRead_InvalidUTF8(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "binary.dat")
if err := os.WriteFile(path, []byte{0xff, 0xfe, 0x00, 0x01}, 0o600); err != nil {
t.Fatalf("setup: %v", err)
}
_, err := ApplyTransform(path, "file_read", nil)
if err == nil {
t.Fatal("expected UTF-8 validation error for binary input")
}
if !strings.Contains(err.Error(), "UTF-8") {
t.Errorf("error should mention UTF-8, got %q", err.Error())
}
}
// TestFileRead_NonString rejects non-string flag values. CLI flags resolve to
// string by default but a misconfigured envelope (e.g. Type: int) shouldn't
// silently no-op.
func TestFileRead_NonString(t *testing.T) {
t.Parallel()
_, err := ApplyTransform(123, "file_read", nil)
if err == nil {
t.Fatal("expected validation error for non-string value")
}
}
// TestFileRead_StdinDashIsAccepted documents the contract: the special value
// "-" is reserved for stdin. We don't test stdin redirection here (that
// requires plumbing os.Stdin replacement which complicates the test) — this
// is a compile-time signal that "-" doesn't path-resolve to a file named "-"
// in the current directory. The end-to-end stdin path is covered in
// test/cli_compat once the envelope ships.
func TestFileRead_StdinDashIsAccepted(t *testing.T) {
t.Parallel()
// Run with stdin redirected from an empty pipe so we don't hang.
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("setup: %v", err)
}
defer r.Close()
if _, err := w.Write([]byte("piped content")); err != nil {
t.Fatalf("setup: %v", err)
}
w.Close()
origStdin := os.Stdin
os.Stdin = r
defer func() { os.Stdin = origStdin }()
got, err := ApplyTransform("-", "file_read", nil)
if err != nil {
t.Fatalf("file_read with '-' should read stdin, got err: %v", err)
}
if got != "piped content" {
t.Errorf("expected stdin contents, got %q", got)
}
}
// TestFileRead_UnknownTransformPassThrough double-checks that the new case
// is gated by name and doesn't regress when the transform name is missing.
func TestFileRead_UnknownTransformPassThrough(t *testing.T) {
t.Parallel()
got, err := ApplyTransform("./some-path", "", nil)
if err != nil {
t.Fatalf("empty transform should pass through, got err: %v", err)
}
if !reflect.DeepEqual(got, "./some-path") {
t.Errorf("expected pass-through, got %v", got)
}
}
func TestInvertBoolTransform(t *testing.T) {
cases := []struct {
in any
want any
}{
{true, false},
{false, true},
{"true", false},
{"false", true},
{"True", false},
{"FALSE", true},
{"on", false},
{"off", true},
{"", true},
}
for _, c := range cases {
got, err := ApplyTransform(c.in, "invert_bool", nil)
if err != nil {
t.Errorf("ApplyTransform(%v, invert_bool) err=%v", c.in, err)
}
if got != c.want {
t.Errorf("ApplyTransform(%v) = %v, want %v", c.in, got, c.want)
}
}
}
+58 -13
View File
@@ -37,19 +37,20 @@ const (
// Error is the structured repository-local error model for the Go rewrite.
type Error struct {
Category Category
Message string
Operation string
ServerKey string
Retryable bool
Reason string
Hint string
Actions []string
Snapshot string
RPCCode int `json:"rpc_code,omitempty"`
RPCData json.RawMessage `json:"rpc_data,omitempty"`
ServerDiag ServerDiagnostics `json:"-"`
Cause error `json:"-"`
Category Category
Message string
Operation string
ServerKey string
Retryable bool
Reason string
Hint string
Actions []string
AvailableFlags []string
Snapshot string
RPCCode int `json:"rpc_code,omitempty"`
RPCData json.RawMessage `json:"rpc_data,omitempty"`
ServerDiag ServerDiagnostics `json:"-"`
Cause error `json:"-"`
}
func (e *Error) Error() string {
@@ -135,6 +136,16 @@ func WithActions(actions ...string) Option {
}
}
// WithAvailableFlags records visible local flag names for agent recovery.
func WithAvailableFlags(names ...string) Option {
return func(err *Error) {
if len(names) == 0 {
return
}
err.AvailableFlags = append([]string{}, names...)
}
}
// WithSnapshot records the recovery snapshot path associated with the failure.
func WithSnapshot(path string) Option {
return func(err *Error) {
@@ -260,6 +271,9 @@ func PrintJSON(w io.Writer, err error) error {
if len(typed.Actions) > 0 {
errorPayload["actions"] = typed.Actions
}
if len(typed.AvailableFlags) > 0 {
errorPayload["available_flags"] = typed.AvailableFlags
}
if typed.Snapshot != "" {
errorPayload["snapshot_path"] = typed.Snapshot
}
@@ -359,6 +373,9 @@ func PrintHumanAt(w io.Writer, err error, v Verbosity) error {
lines = append(lines, fmt.Sprintf("Action: %s", action))
}
}
if line := formatAvailableFlagsHumanLine(typed.AvailableFlags); line != "" {
lines = append(lines, line)
}
if typed.Retryable {
lines = append(lines, "Retryable: true")
}
@@ -414,3 +431,31 @@ func category(err error) string {
}
return string(CategoryInternal)
}
const availableFlagsHumanMaxRunes = 200
func formatAvailableFlagsHumanLine(flags []string) string {
if len(flags) == 0 {
return ""
}
b := strings.Builder{}
b.WriteString("Flags: ")
written := 0
for i, name := range flags {
if i > 0 {
if written+2 > availableFlagsHumanMaxRunes {
b.WriteString("...")
return b.String()
}
b.WriteString(", ")
written += 2
}
if written+len(name) > availableFlagsHumanMaxRunes {
b.WriteString("...")
return b.String()
}
b.WriteString(name)
written += len(name)
}
return b.String()
}
+21
View File
@@ -77,6 +77,27 @@ func TestPrintJSON(t *testing.T) {
}
}
func TestPrintJSON_AvailableFlags(t *testing.T) {
t.Parallel()
var b strings.Builder
if err := PrintJSON(&b, NewValidation(
"unknown flag: --foo",
WithReason("unknown_flag"),
WithHint("Did you mean --bar?"),
WithAvailableFlags("bar", "baz"),
)); err != nil {
t.Fatalf("PrintJSON() error = %v", err)
}
got := b.String()
if !strings.Contains(got, `"available_flags"`) {
t.Fatalf("expected available_flags in output, got %q", got)
}
if !strings.Contains(got, `"bar"`) || !strings.Contains(got, `"baz"`) {
t.Fatalf("expected flag names in output, got %q", got)
}
}
func TestPrintHuman(t *testing.T) {
t.Parallel()
+9 -7
View File
@@ -393,13 +393,15 @@ func confirmDeletePrompt(cmd *cobra.Command, resourceType, resourceName string)
func newAITableUploadFileCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "upload-file",
Short: i18n.T("本地文件一键上传到 AITable 附件字段"),
Hidden: true,
Long: `完整流程 (自动执行 3 步):
1. dws aitable attachment upload → 获取 uploadUrl + fileToken
2. HTTP PUT 上传文件到 OSS
3. 返回 fileToken,可直接用于 record create/update`,
Use: "upload-file",
Short: i18n.T("本地文件一键上传到 AITable 附件字段 (3 步自动合一: prepare + PUT + 返回 fileToken)"),
Long: `本地文件一键上传到 AITable 附件字段, 一行命令完成 3 步:
1. prepare_attachment_upload → 获取 OSS 上传地址 uploadUrl + fileToken
2. HTTP PUT 文件二进制 → OSS
3. 返回 fileToken (可直接用于 dws aitable record create/update 的 attachment 字段)
推荐 AI Agent 优先使用此命令上传单个附件, 比手动调用 attachment upload (只 prepare)
之后再自己 PUT 文件二进制要可靠得多.`,
Example: " dws aitable attachment upload-file --base-id <BASE_ID> --file ./report.pdf",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
+11 -2
View File
@@ -594,8 +594,17 @@ func newAitableTemplateSearchCommand(runner executor.Runner) *cobra.Command {
func newAITableAttachmentUploadCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "upload",
Short: i18n.T("准备附件上传"),
Use: "upload",
Short: i18n.T("准备附件上传 (仅返回 uploadUrl + fileToken, 不上传文件)"),
Long: i18n.T(`准备附件上传 — 3 步流程的第 1 步.
本命令只调用 prepare_attachment_upload, 返回 OSS 上传地址 uploadUrl 和 fileToken,
不实际上传文件二进制. 拿到响应后你还需要:
2. HTTP PUT 文件二进制 → uploadUrl
3. 把 fileToken 填到 record 的 attachment 字段, 格式 [{"fileToken":"ft_xxx"}]
推荐 AI Agent 直接用 'dws aitable attachment upload-file --base-id X --file ./report.pdf'
一行完成 3 步, 不用自己处理 HTTP PUT 二进制.`),
Example: " dws aitable attachment upload --base-id BASE_ID --file-name report.pdf --size 1024",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
@@ -92,3 +92,18 @@ func TestAITableUploadFileUnwrapsRuntimeContent(t *testing.T) {
t.Fatalf("fileToken = %#v, want ft_test_123", got)
}
}
// TestAITableUploadFileCommandIsDiscoverable guards that the upload-file
// command stays visible via --help. It was previously marked Hidden:true,
// which caused AI agents (e.g. Lobster) to discover only the prepare-only
// `attachment upload` command and get stuck after step 1, falling back to
// "please use the UI to upload". Keeping this command discoverable is the
// single change that unlocks the end-to-end attachment upload flow for
// agents that only read --help.
func TestAITableUploadFileCommandIsDiscoverable(t *testing.T) {
runner := &uploadFileRunner{}
cmd := newAITableUploadFileCommand(runner)
if cmd.Hidden {
t.Fatalf("upload-file command must not be Hidden: AI agents discover it via --help; hiding it strands them after step 1 (see commit message for full rationale)")
}
}
+83 -299
View File
@@ -15,6 +15,7 @@ package helpers
import (
"context"
"encoding/json"
"strings"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cli"
@@ -30,6 +31,12 @@ func init() {
})
}
// chatHandler retains only the chat commands that carry real business logic
// (intelligent tool routing, current-user resolution, response normalization,
// or stdin/@file input support that dynamic commands do not yet provide).
// Thin wrappers — search, group rename, group members list/add/remove/add-bot,
// bot search — are now produced by the dynamic service-discovery envelope
// (envelope/pre-discovery.json) so the helper does not have to duplicate them.
type chatHandler struct{}
func (chatHandler) Name() string {
@@ -40,7 +47,7 @@ func (chatHandler) Command(runner executor.Runner) *cobra.Command {
root := &cobra.Command{
Use: "chat",
Short: "群聊 / 消息 / 机器人",
Long: "管理钉钉会话与群聊:创建群、搜索群、查看群成员、添加机器人到群、修改群名称、拉取会话消息、发送群消息、机器人消息与 Webhook。",
Long: "钉钉会话与群聊:发送消息(用户/机器人/Webhook)、撤回机器人消息、创建群。其余命令由服务发现 envelope 提供。",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
@@ -64,11 +71,12 @@ func (chatHandler) Command(runner executor.Runner) *cobra.Command {
newChatMessageSendByBotCommand(runner),
newChatMessageRecallByBotCommand(runner),
newChatMessageSendByWebhookCommand(runner),
newChatMessageReplyCommand(runner),
)
bot := &cobra.Command{
Use: "bot",
Short: "机器人管理",
group := &cobra.Command{
Use: "group",
Short: "群组管理",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
@@ -76,9 +84,9 @@ func (chatHandler) Command(runner executor.Runner) *cobra.Command {
return cmd.Help()
},
}
bot.AddCommand(newChatBotSearchCommand(runner))
group.AddCommand(newChatGroupCreateCommand(runner))
root.AddCommand(message, newChatSearchCommand(runner), newChatGroupCommand(runner), bot)
root.AddCommand(message, group)
return root
}
@@ -93,11 +101,11 @@ func newChatMessageSendCommand(runner executor.Runner) *cobra.Command {
三者只能选其一,不能同时指定。
消息内容通过 --text 传入,也可作为位置参数;支持 Markdown。
单聊消息(--user / --open-dingtalk-id)必须提供 --title 作为消息标题;群聊可选。
--title 是消息标题,群聊与单聊都必填(API 强制要求;缺失时返回误导性的 "发群服务窗会话消息失败")。
群聊场景下可用 --at-all / --at-users / --at-mobiles 进行 @ 提醒(仅 --group 时生效)。
注意 --text 中需包含对应的 <@userId> / <@all> 占位符才能在客户端渲染出 @ 效果。`,
Example: ` dws chat message send --group <openconversation_id> --text "hello"
Example: ` dws chat message send --group <openconversation_id> --title "周报" --text "请提交本周日报"
dws chat message send --user <userId> --title "提醒" --text "请查收"
dws chat message send --open-dingtalk-id <openDingTalkId> --title "提醒" --text "请确认"
dws chat message send --group <openconversation_id> --title "拉群通知" --text "<@uid> 你被 @ 了" --at-users uid`,
@@ -128,7 +136,7 @@ func newChatMessageSendCommand(runner executor.Runner) *cobra.Command {
cmd.Flags().String("user", "", "接收人 userId (单聊三选一)")
cmd.Flags().String("open-dingtalk-id", "", "接收人 openDingTalkId (单聊三选一)")
cmd.Flags().String("text", "", "消息内容,支持 Markdown (也可作位置参数)")
cmd.Flags().String("title", "", "消息标题 (单聊必填,群聊可选)")
cmd.Flags().String("title", "", "消息标题 (必填,群聊与单聊都必填)")
cmd.Flags().Bool("at-all", false, "@所有人 (仅 --group 群聊生效)")
cmd.Flags().String("at-users", "", "按 userId @ 指定成员,逗号分隔 (仅 --group 群聊生效)")
cmd.Flags().String("at-mobiles", "", "按手机号 @ 指定成员,逗号分隔 (仅 --group 群聊生效)")
@@ -196,10 +204,14 @@ func buildChatMessageSendInvocation(cmd *cobra.Command, args []string) (map[stri
if !hasGroup && (atAll || hasAtUsers || hasAtMobiles) {
return nil, "", apperrors.NewValidation("--at-all / --at-users / --at-mobiles only apply when --group is set")
}
// Direct-message tools (send_direct_message_as_user) reject an empty title at
// the API level with a misleading "发群服务窗会话消息失败" error, so fail loudly
// here instead. Group messages do not require a title.
if (hasUser || hasOpenID) && strings.TrimSpace(title) == "" {
// Both send_message_as_user (group) and send_direct_message_as_user (direct)
// reject an empty title at the API level with a misleading
// "发群服务窗会话消息失败" error, so fail loudly here instead. The schema
// declares title as a required parameter on both tools.
if strings.TrimSpace(title) == "" {
if hasGroup {
return nil, "", apperrors.NewValidation("--title is required for group messages (--group)")
}
return nil, "", apperrors.NewValidation("--title is required for direct messages (--user / --open-dingtalk-id)")
}
@@ -266,94 +278,6 @@ func newChatMessageSendByBotCommand(runner executor.Runner) *cobra.Command {
return cmd
}
func newChatSearchCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "search",
Short: "根据名称搜索会话列表",
Example: ` dws chat search --query "项目冲刺"`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
query, err := cmd.Flags().GetString("query")
if err != nil {
return apperrors.NewInternal("failed to read --query")
}
query = strings.TrimSpace(query)
if query == "" {
return apperrors.NewValidation("--query is required")
}
searchReq := map[string]any{"query": query}
cursor, err := cmd.Flags().GetString("cursor")
if err != nil {
return apperrors.NewInternal("failed to read --cursor")
}
if strings.TrimSpace(cursor) != "" {
searchReq["cursor"] = cursor
}
result, err := runner.Run(cmd.Context(), executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd),
"chat",
"search_groups_by_keyword",
map[string]any{"OpenSearchRequest": searchReq},
))
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("query", "", "搜索关键词 (必填)")
cmd.Flags().String("cursor", "", "分页游标 (首页留空)")
return cmd
}
func newChatGroupCommand(runner executor.Runner) *cobra.Command {
root := &cobra.Command{
Use: "group",
Short: "群组管理",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
members := &cobra.Command{
Use: "members",
Short: "群成员管理",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
// Keeps the helper-restructured group winning over the dynamic envelope's
// `members` leaf (which only exposes `get_group_members`); without this
// the merge layer treats the shape mismatch as "envelope is authority"
// and drops the entire helper subtree (issue #164).
preferLegacyLeaf(members)
members.AddCommand(
newChatGroupMembersListCommand(runner),
newChatGroupMemberAddCommand(runner),
newChatGroupMemberRemoveCommand(runner),
newChatGroupMembersAddBotCommand(runner),
)
root.AddCommand(
newChatGroupCreateCommand(runner),
members,
newChatGroupRenameCommand(runner),
)
return root
}
func newChatGroupCreateCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "create",
@@ -643,6 +567,10 @@ func newChatMessageRecallByBotCommand(runner executor.Runner) *cobra.Command {
}
// ── message send-by-webhook ────────────────────────────────
//
// Kept as a helper (rather than delegating to the dynamic envelope) because
// it needs --text @file / stdin pipe support via resolveStringFlag, which the
// dynamic-command layer does not yet provide.
func newChatMessageSendByWebhookCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
@@ -709,65 +637,63 @@ func newChatMessageSendByWebhookCommand(runner executor.Runner) *cobra.Command {
return cmd
}
// ── group members list ─────────────────────────────────────
// ── message reply ────────────────────────────────────────
//
// Kept as a helper because the underlying MCP tool send_personal_message
// requires the reply payload to be a JSON-encoded string assembled from
// --ref-msg-id / --ref-sender / --text. Envelope toolOverride does flat
// flag→param mapping only and cannot construct nested JSON, so this
// orchestration must live in CLI code.
func newChatGroupMembersListCommand(runner executor.Runner) *cobra.Command {
func newChatMessageReplyCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "查询群成员列表",
Example: ` dws chat group members list --id <openconversation_id>`,
Use: "reply",
Short: "引用回复消息(支持单聊/群聊)",
Long: "以当前用户身份引用某条消息并回复。需 --conversation-id 会话 ID、--ref-msg-id 被引用消息 ID、--ref-sender 原发送者 openDingTalkId、--text 回复内容。",
Example: ` dws chat message reply --conversation-id <openConversationId> --ref-msg-id <openMessageId> --ref-sender <openDingTalkId> --text "收到,马上处理"`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
groupID, _ := cmd.Flags().GetString("id")
if strings.TrimSpace(groupID) == "" {
return apperrors.NewValidation("--id is required")
convID, _ := cmd.Flags().GetString("conversation-id")
refMsgID, _ := cmd.Flags().GetString("ref-msg-id")
refSender, _ := cmd.Flags().GetString("ref-sender")
text, _ := cmd.Flags().GetString("text")
if strings.TrimSpace(convID) == "" {
return apperrors.NewValidation("--conversation-id is required")
}
params := map[string]any{
"openconversation_id": groupID,
if strings.TrimSpace(refMsgID) == "" {
return apperrors.NewValidation("--ref-msg-id is required")
}
if v, _ := cmd.Flags().GetString("cursor"); v != "" {
params["cursor"] = v
if strings.TrimSpace(refSender) == "" {
return apperrors.NewValidation("--ref-sender is required")
}
result, err := runner.Run(cmd.Context(), executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "chat", "get_group_members", params,
))
if strings.TrimSpace(text) == "" {
return apperrors.NewValidation("--text is required")
}
replyContent := map[string]any{
"referenceOpenMessageId": refMsgID,
"srcMsgSendOpenDingTalkId": refSender,
"replyMsgType": "text",
"content": text,
}
contentJSON, err := jsonMarshal(replyContent)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("id", "", "群 ID / openconversation_id (必填)")
cmd.Flags().String("cursor", "", "分页游标 (首页留空)")
return cmd
}
// ── group rename ───────────────────────────────────────────
func newChatGroupRenameCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "rename",
Short: "更新群名称",
Example: ` dws chat group rename --id <openconversation_id> --name "新群名"`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
groupID, _ := cmd.Flags().GetString("id")
name, _ := cmd.Flags().GetString("name")
if strings.TrimSpace(groupID) == "" {
return apperrors.NewValidation("--id is required")
}
if strings.TrimSpace(name) == "" {
return apperrors.NewValidation("--name is required")
return apperrors.NewInternal("marshal reply content: " + err.Error())
}
params := map[string]any{
"openconversation_id": groupID,
"group_name": name,
"openConversationId": convID,
"msgType": "reply",
"content": contentJSON,
"clawType": "wukong",
}
if uuid, _ := cmd.Flags().GetString("uuid"); strings.TrimSpace(uuid) != "" {
params["uuid"] = uuid
}
inv := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "chat", "update_group_name", params,
cobracmd.LegacyCommandPath(cmd),
"group-chat",
"send_personal_message",
params,
)
inv.DryRun = commandDryRun(cmd)
result, err := runner.Run(cmd.Context(), inv)
@@ -778,160 +704,18 @@ func newChatGroupRenameCommand(runner executor.Runner) *cobra.Command {
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("id", "", "群 ID / openconversation_id (必填)")
cmd.Flags().String("name", "", "新群名称 (必填)")
cmd.Flags().String("conversation-id", "", "会话 openConversationId (必填,支持单聊/群聊)")
cmd.Flags().String("ref-msg-id", "", "被引用的消息 openMessageId (必填)")
cmd.Flags().String("ref-sender", "", "被引用消息发送者 openDingTalkId (必填)")
cmd.Flags().String("text", "", "回复正文 (必填)")
cmd.Flags().String("uuid", "", "可选 uuid(幂等标识)")
return cmd
}
// ── group members add ──────────────────────────────────────
func newChatGroupMemberAddCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Short: "添加群成员",
Example: ` dws chat group members add --id <openconversation_id> --users userId1,userId2`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
groupID, _ := cmd.Flags().GetString("id")
usersStr, _ := cmd.Flags().GetString("users")
if strings.TrimSpace(groupID) == "" {
return apperrors.NewValidation("--id is required")
}
if strings.TrimSpace(usersStr) == "" {
return apperrors.NewValidation("--users is required")
}
params := map[string]any{
"openconversation_id": groupID,
"userId": splitCSV(usersStr),
}
inv := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "chat", "add_group_member", params,
)
inv.DryRun = commandDryRun(cmd)
result, err := runner.Run(cmd.Context(), inv)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
},
func jsonMarshal(v any) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err
}
preferLegacyLeaf(cmd)
cmd.Flags().String("id", "", "群 ID / openconversation_id (必填)")
cmd.Flags().String("users", "", "要添加的 userId 列表,逗号分隔 (必填)")
return cmd
}
// ── group members remove ───────────────────────────────────
func newChatGroupMemberRemoveCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "remove",
Short: "移除群成员",
Example: ` dws chat group members remove --id <openconversation_id> --users userId1,userId2`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
groupID, _ := cmd.Flags().GetString("id")
usersStr, _ := cmd.Flags().GetString("users")
if strings.TrimSpace(groupID) == "" {
return apperrors.NewValidation("--id is required")
}
if strings.TrimSpace(usersStr) == "" {
return apperrors.NewValidation("--users is required")
}
params := map[string]any{
"openconversationId": groupID,
"userIdList": splitCSV(usersStr),
}
inv := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "chat", "remove_group_member", params,
)
inv.DryRun = commandDryRun(cmd)
result, err := runner.Run(cmd.Context(), inv)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("id", "", "Group ID / openconversation_id (required)")
cmd.Flags().String("users", "", "Comma-separated userId list to remove (required)")
return cmd
}
// ── group members add-bot ──────────────────────────────────
func newChatGroupMembersAddBotCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "add-bot",
Short: "Add bot to group",
Example: ` dws chat group members add-bot --robot-code <robot-code> --id <openconversation_id>`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
robotCode, _ := cmd.Flags().GetString("robot-code")
groupID, _ := cmd.Flags().GetString("id")
if strings.TrimSpace(robotCode) == "" {
return apperrors.NewValidation("--robot-code is required")
}
if strings.TrimSpace(groupID) == "" {
return apperrors.NewValidation("--id is required")
}
params := map[string]any{
"robotCode": robotCode,
"openConversationId": groupID,
}
inv := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "bot", "add_robot_to_group", params,
)
inv.DryRun = commandDryRun(cmd)
result, err := runner.Run(cmd.Context(), inv)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("robot-code", "", "Bot code (required)")
cmd.Flags().String("id", "", "Group openConversationId (required)")
return cmd
}
// ── bot search ─────────────────────────────────────────────
func newChatBotSearchCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "search",
Short: "Search my bots",
Example: " dws chat bot search --page 1\n dws chat bot search --page 1 --size 10 --name \"日报\"",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
page, _ := cmd.Flags().GetInt("page")
params := map[string]any{
"currentPage": page,
}
if v, _ := cmd.Flags().GetInt("size"); v > 0 {
params["pageSize"] = v
}
if v, _ := cmd.Flags().GetString("name"); v != "" {
params["robotName"] = v
}
result, err := runner.Run(cmd.Context(), executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "bot", "search_my_robots", params,
))
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().Int("page", 1, "Page number, starting from 1")
cmd.Flags().Int("size", 0, "Items per page (default 50)")
cmd.Flags().String("name", "", "Search by name")
return cmd
return string(b), nil
}
+7 -73
View File
@@ -7,7 +7,6 @@ import (
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/spf13/cobra"
)
type captureRunner struct {
@@ -60,7 +59,7 @@ func TestChatMessageSendRoutesByDestination(t *testing.T) {
}{
{
name: "group",
args: []string{"--group", "cid-xyz", "--text", "hello"},
args: []string{"--group", "cid-xyz", "--title", "t", "--text", "hello"},
wantTool: "send_message_as_user",
wantKey: "openConversation_id",
wantValue: "cid-xyz",
@@ -81,7 +80,7 @@ func TestChatMessageSendRoutesByDestination(t *testing.T) {
},
{
name: "positional-text",
args: []string{"--group", "cid-xyz", "hello from positional"},
args: []string{"--group", "cid-xyz", "--title", "t", "hello from positional"},
wantTool: "send_message_as_user",
wantKey: "text",
wantValue: "hello from positional",
@@ -132,6 +131,11 @@ func TestChatMessageSendRejectsInvalidDestination(t *testing.T) {
args: []string{"--group", "cid-x"},
wantErr: "--text (or positional argument) is required",
},
{
name: "group-without-title",
args: []string{"--group", "cid-x", "--text", "hi"},
wantErr: "--title is required for group messages",
},
{
name: "direct-user-without-title",
args: []string{"--user", "034766", "--text", "hi"},
@@ -302,76 +306,6 @@ func equalAny(a, b any) bool {
}
}
// TestChatGroupMembersListSubcommand pins the explicit `list` subcommand
// added for issue #164: previously the bare `chat group members --id` was
// the list path, but it shape-mismatched the dynamic envelope's `members`
// leaf and got eaten by the merge layer. Now `dws chat group members list
// --id <cid>` is a proper leaf siblings of add/remove/add-bot.
func TestChatGroupMembersListSubcommand(t *testing.T) {
runner := &captureRunner{}
groupCmd := newChatGroupCommand(runner)
var members *cobra.Command
for _, sub := range groupCmd.Commands() {
if sub.Name() == "members" {
members = sub
break
}
}
if members == nil {
t.Fatalf("members subcommand missing under chat group")
}
want := map[string]bool{"list": false, "add": false, "remove": false, "add-bot": false}
for _, leaf := range members.Commands() {
if _, ok := want[leaf.Name()]; ok {
want[leaf.Name()] = true
}
}
for name, seen := range want {
if !seen {
t.Errorf("expected `chat group members %s` subcommand, missing", name)
}
}
if members.Flags().Lookup("id") != nil {
t.Errorf("members container should not declare --id (moved to `list` subcommand to avoid shape-mismatch with dynamic envelope)")
}
var listCmd *cobra.Command
for _, leaf := range members.Commands() {
if leaf.Name() == "list" {
listCmd = leaf
break
}
}
if listCmd == nil {
t.Fatalf("`list` subcommand not found")
}
if listCmd.Flags().Lookup("id") == nil {
t.Errorf("`list` subcommand must declare --id")
}
if listCmd.Flags().Lookup("cursor") == nil {
t.Errorf("`list` subcommand must declare --cursor")
}
// Drive execution via the group root so cobra resolves the subcommand
// path properly (calling Execute() on a child directly would re-enter
// the root help branch).
var out bytes.Buffer
groupCmd.SetOut(&out)
groupCmd.SetErr(&out)
groupCmd.SetArgs([]string{"members", "list", "--id", "cid-xyz"})
if err := groupCmd.Execute(); err != nil {
t.Fatalf("members list Execute error = %v\noutput: %s", err, out.String())
}
if got := runner.last.Tool; got != "get_group_members" {
t.Fatalf("Tool = %q, want get_group_members", got)
}
if got := runner.last.Params["openconversation_id"]; got != "cid-xyz" {
t.Fatalf("openconversation_id = %#v, want cid-xyz", got)
}
}
func TestChatMessageSendByBotRoutesToBotProduct(t *testing.T) {
cases := []struct {
name string
+352
View File
@@ -0,0 +1,352 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cobracmd"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/spf13/cobra"
)
func init() {
RegisterPublic(func() Handler {
return driveHandler{}
})
}
// driveHandler exposes the one drive subcommand that the service-discovery
// envelope cannot express on its own:
//
// - upload — three-step composite: drive.get_upload_info → HTTP PUT to OSS →
// drive.commit_upload. The envelope PipelineStep schema currently supports
// type:"call" (MCP tool invocation) and type:"download" (HTTP GET sink),
// but has no type:"upload" for streaming a local file to an OSS-signed
// PUT URL with per-URL headers. Until the envelope schema grows that
// capability, this helper is the canonical client-side glue.
//
// Other drive-vs-wukong gaps (list-spaces and delete) are covered purely via
// envelope toolOverrides — list_spaces as a plain alias map, delete_document
// via serverOverride to route to the doc MCP server. No Go code needed for
// those two; see envelope/pre-discovery.pre.json drive entry.
//
// The dynamic envelope still owns the six base commands (list / info /
// download / mkdir / upload-info / commit); pickCommands.MergeHardcodedLeaves
// guarantees dynamic leaves win on collision so this helper only fills the
// upload gap.
type driveHandler struct{}
func (driveHandler) Name() string {
return "drive"
}
func (driveHandler) Command(runner executor.Runner) *cobra.Command {
root := &cobra.Command{
Use: "drive",
Short: "钉盘扩展命令(合并到 dws drive 命令树)",
Long: "钉盘扩展子命令: upload 本地文件一键上传(三步合成)。其余命令均由服务发现 envelope 提供。",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
root.AddCommand(newDriveUploadCommand(runner))
return root
}
// ── upload (three-step composite) ───────────────────────────
func newDriveUploadCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "upload",
Short: "上传本地文件到钉盘",
Long: `将本地文件上传到钉盘(三步自动完成):
1. drive get_upload_info → 获取 OSS 上传凭证 (resourceUrl + uploadId + headers)
2. HTTP PUT 文件二进制 → OSS
3. drive commit_upload → 提交文件入库
--folder 指定父目录 dentryUuid,不传则上传到空间根目录。`,
Example: ` dws drive upload --file ./report.pdf
dws drive upload --file ./slides.pptx --file-name "Q1汇报.pptx"
dws drive upload --file ./data.xlsx --folder <dentryUuid>`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runDriveUpload(cmd, runner)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("file", "", "本地文件路径 (必填)")
cmd.Flags().String("file-name", "", "文件显示名称 (默认使用文件名)")
cmd.Flags().String("space-id", "", "目标空间 ID,不传则使用「我的文件」")
cmd.Flags().String("mime-type", "", "文件 MIME 类型,不传则自动推断")
cmd.Flags().String("folder", "", "父节点 ID (dentryUuid),不传则上传到空间根目录")
return cmd
}
func runDriveUpload(cmd *cobra.Command, runner executor.Runner) error {
filePath, _ := cmd.Flags().GetString("file")
if strings.TrimSpace(filePath) == "" {
return apperrors.NewValidation("--file is required")
}
absPath, err := filepath.Abs(filePath)
if err != nil {
return apperrors.NewValidation("无法解析文件路径: " + err.Error())
}
fi, err := os.Stat(absPath)
if err != nil {
return apperrors.NewValidation("文件不存在或无法读取: " + absPath)
}
if fi.IsDir() {
return apperrors.NewValidation("--file 不能是目录: " + absPath)
}
fileSize := fi.Size()
if fileSize <= 0 {
return apperrors.NewValidation("文件为空")
}
fileName, _ := cmd.Flags().GetString("file-name")
if strings.TrimSpace(fileName) == "" {
fileName = filepath.Base(absPath)
}
spaceID, _ := cmd.Flags().GetString("space-id")
mimeType, _ := cmd.Flags().GetString("mime-type")
if strings.TrimSpace(mimeType) == "" {
mimeType = detectMIME(fileName)
}
parentID, _ := cmd.Flags().GetString("folder")
if err := validateDriveParentID(parentID); err != nil {
return err
}
// Step 1 params
step1Params := map[string]any{
"fileName": fileName,
"fileSize": float64(fileSize),
}
if strings.TrimSpace(spaceID) != "" {
step1Params["spaceId"] = spaceID
}
if strings.TrimSpace(mimeType) != "" {
step1Params["mimeType"] = mimeType
}
if strings.TrimSpace(parentID) != "" {
step1Params["parentId"] = parentID
}
if commandDryRun(cmd) {
return writeCommandPayload(cmd, map[string]any{
"dry_run": true,
"step_1_get_upload_info": executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "drive", "get_upload_info", step1Params,
),
"step_2_http_put_oss": "PUT file bytes to resourceUrls[0].url with returned headers",
"step_3_commit_upload": "drive commit_upload with uploadId from step 1",
"file": absPath,
"size": fileSize,
"name": fileName,
})
}
// Step 1: get_upload_info
fmt.Fprintf(os.Stderr, "[1/3] 获取上传凭证 %s (%d 字节, %s)...\n", fileName, fileSize, mimeType)
step1 := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "drive", "get_upload_info", step1Params,
)
step1Result, err := runner.Run(cmd.Context(), step1)
if err != nil {
return fmt.Errorf("获取上传凭证失败: %w", err)
}
resourceURL, uploadID, ossHeaders, err := parseDriveUploadInfo(step1Result.Response)
if err != nil {
return err
}
// Step 2: HTTP PUT to OSS
fmt.Fprintln(os.Stderr, "[2/3] 上传文件到 OSS...")
if err := httpPutDriveFile(cmd.Context(), resourceURL, ossHeaders, absPath, fileSize); err != nil {
return err
}
// Step 3: commit_upload
fmt.Fprintln(os.Stderr, "[3/3] 提交文件入库...")
step3Params := map[string]any{
"fileName": fileName,
"fileSize": float64(fileSize),
"uploadId": uploadID,
}
if strings.TrimSpace(spaceID) != "" {
step3Params["spaceId"] = spaceID
}
if strings.TrimSpace(parentID) != "" {
step3Params["parentId"] = parentID
}
step3 := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "drive", "commit_upload", step3Params,
)
result, err := runner.Run(cmd.Context(), step3)
if err != nil {
return fmt.Errorf("提交文件入库失败: %w", err)
}
return writeCommandPayload(cmd, result)
}
// validateDriveParentID rejects pure-numeric IDs (which are dentryId values
// from the chat link namespace, not drive's dentryUuid).
func validateDriveParentID(parentID string) error {
value := strings.TrimSpace(parentID)
if value == "" {
return nil
}
for _, r := range value {
if r < '0' || r > '9' {
return nil
}
}
return apperrors.NewValidation(fmt.Sprintf(
"invalid drive --folder %q: pure numeric IDs are usually dentryId values from chat links, not drive dentryUuid; use a parent folder dentryUuid from drive list, or omit --folder to use the space root",
parentID,
))
}
// parseDriveUploadInfo extracts resourceUrl / uploadId / OSS headers from the
// drive.get_upload_info response. The actual server payload is:
//
// {
// "uploadId": "...",
// "resourceUrls": [
// { "url": "https://...", "headers": { ... } }
// ]
// }
//
// MCP gateway may wrap the payload with a "content" or "result" envelope, so we
// peel one layer if present, and also accept legacy flat resourceUrl/uploadUrl
// fields as a fallback.
func parseDriveUploadInfo(resp map[string]any) (resourceURL, uploadID string, headers map[string]string, err error) {
if resp == nil {
err = apperrors.NewValidation("get_upload_info 返回为空")
return
}
data := resp
if content, ok := data["content"].(map[string]any); ok && len(content) > 0 {
data = content
}
if result, ok := data["result"].(map[string]any); ok && len(result) > 0 {
data = result
}
uploadID, _ = data["uploadId"].(string)
if urls, ok := data["resourceUrls"].([]any); ok && len(urls) > 0 {
if first, ok := urls[0].(map[string]any); ok {
resourceURL, _ = first["url"].(string)
headers = make(map[string]string)
if h, ok := first["headers"].(map[string]any); ok {
for k, v := range h {
if s, ok := v.(string); ok {
headers[k] = s
}
}
}
}
}
if resourceURL == "" {
resourceURL, _ = data["resourceUrl"].(string)
}
if resourceURL == "" {
resourceURL, _ = data["uploadUrl"].(string)
}
if resourceURL == "" || uploadID == "" {
err = apperrors.NewValidation(fmt.Sprintf(
"get_upload_info 返回不完整: resourceUrl=%q, uploadId=%q", resourceURL, uploadID,
))
return
}
if headers == nil {
headers = make(map[string]string)
if h, ok := data["headers"].(map[string]any); ok {
for k, v := range h {
if s, ok := v.(string); ok {
headers[k] = s
}
}
}
}
return
}
// httpPutDriveFile uploads the file at filePath to a DingTalk drive OSS presigned URL.
//
// PROTOCOL CONTRACT: the headers map is authoritative. It contains the exact
// and complete set of HTTP headers required for the upload. An empty map means
// "no client-side headers needed" (this is the normal case for DingTalk drive,
// where the signature is embedded in the URL query string).
//
// DO NOT add Content-Type or any other client-inferred header here. DingTalk
// drive uses OSS v1 presigned URLs whose StringToSign includes the Content-Type
// header that the server saw at signing time (typically empty). Any client-side
// addition of Content-Type makes the signature computed by OSS at PUT time
// differ from the server's presignature → 403 SignatureDoesNotMatch.
//
// If a future OSS endpoint requires header-based signing (Authorization header
// instead of URL signing), introduce a separate helper rather than reintroducing
// a fallback here. The aitable attachment upload helper in aitable.go does set
// Content-Type because its OSS endpoint uses a different signing mode where the
// server includes the client-declared mime in its signature computation; do not
// unify the two helpers without re-validating both endpoints.
func httpPutDriveFile(ctx context.Context, resourceURL string, headers map[string]string, filePath string, fileSize int64) error {
f, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("无法打开文件: %w", err)
}
defer f.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodPut, resourceURL, f)
if err != nil {
return fmt.Errorf("构建 OSS 上传请求失败: %w", err)
}
req.ContentLength = fileSize
for k, v := range headers {
req.Header.Set(k, v)
}
client := &http.Client{Timeout: 10 * time.Minute}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("OSS 上传失败: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return fmt.Errorf("OSS 上传失败 HTTP %d: %s", resp.StatusCode, string(body))
}
return nil
}
+105
View File
@@ -0,0 +1,105 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
// TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty guards the fix for
// the SignatureDoesNotMatch bug on DingTalk drive presigned OSS uploads.
//
// DingTalk drive returns an OSS presigned URL (signature in the URL query
// string) and signs the upload with Content-Type left empty. Any client-side
// Content-Type makes the signature OSS computes at PUT time differ from the
// server presignature → 403 SignatureDoesNotMatch.
//
// Previous behavior: httpPutDriveFile fell back to a client-inferred mime when
// the server's `headers` map was empty, which is the normal case for DingTalk
// drive (`{"headers": {}}`). That fallback broke every PNG / image / typed-mime
// upload in production.
//
// This test asserts the PUT request body contains no Content-Type header when
// the server returns an empty headers map. If a future change reintroduces
// client-side Content-Type fallback this test will fail loudly.
func TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty(t *testing.T) {
var receivedContentType string
var receivedBody []byte
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
t.Fatalf("method = %s, want PUT", r.Method)
}
receivedContentType = r.Header.Get("Content-Type")
receivedBody, _ = io.ReadAll(r.Body)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
tmp := filepath.Join(t.TempDir(), "test.png")
wantBody := []byte("fake-png-bytes")
if err := os.WriteFile(tmp, wantBody, 0o644); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
err := httpPutDriveFile(context.Background(), server.URL, map[string]string{}, tmp, int64(len(wantBody)))
if err != nil {
t.Fatalf("httpPutDriveFile() error = %v", err)
}
if receivedContentType != "" {
t.Fatalf("Content-Type = %q, want empty (presigned URL signing requires no client-inferred headers)", receivedContentType)
}
if string(receivedBody) != string(wantBody) {
t.Fatalf("uploaded body = %q, want %q", string(receivedBody), string(wantBody))
}
}
// TestHttpPutDriveFile_PassthroughServerHeaders verifies that any header the
// server returns in its prepare response is forwarded verbatim to the PUT
// request. This is the symmetric guarantee to the test above: clients must
// neither add nor drop headers — they pass through exactly what the server
// declared.
func TestHttpPutDriveFile_PassthroughServerHeaders(t *testing.T) {
var receivedHeaders http.Header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHeaders = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
tmp := filepath.Join(t.TempDir(), "test.bin")
if err := os.WriteFile(tmp, []byte("x"), 0o644); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
headers := map[string]string{
"Content-Type": "application/octet-stream",
"x-oss-storage-class": "Standard",
}
err := httpPutDriveFile(context.Background(), server.URL, headers, tmp, 1)
if err != nil {
t.Fatalf("httpPutDriveFile() error = %v", err)
}
if got := receivedHeaders.Get("Content-Type"); got != "application/octet-stream" {
t.Fatalf("Content-Type = %q, want application/octet-stream", got)
}
if got := receivedHeaders.Get("x-oss-storage-class"); got != "Standard" {
t.Fatalf("x-oss-storage-class = %q, want Standard", got)
}
}
+52 -7
View File
@@ -283,7 +283,19 @@ type CLIFlagOverride struct {
// name and Alias, and reserved names ("json", "params") are skipped.
// When any alias is set by the user, the binding's Required check is
// satisfied and the value is written to params[Property].
Aliases []string `json:"aliases,omitempty"`
Aliases []string `json:"aliases,omitempty"`
// MapsTo redirects this flag's final value into a different MCP parameter
// slot. When empty (default), the value is written to params[propertyName]
// as today. When set, params[MapsTo] receives the (possibly transformed)
// value and params[propertyName] is NOT written. This is what lets a
// sibling CLI flag — e.g. --content-file with transform: file_read — feed
// the same MCP parameter (markdown) as the existing literal --content
// flag, without forcing one flag to do double-duty.
//
// Pair with the existing CLIToolOverride.MutuallyExclusive (tool-level
// cobra MarkFlagsMutuallyExclusive) when two sibling flags map to the
// same MCP slot but should not be set together.
MapsTo string `json:"mapsTo,omitempty"`
Transform string `json:"transform,omitempty"`
TransformArgs map[string]any `json:"transformArgs,omitempty"`
EnvDefault string `json:"envDefault,omitempty"`
@@ -635,18 +647,24 @@ func NormalizeServers(response ListResponse, source string) []ServerDescriptor {
descriptor.UpdatedAt = updatedAt
}
existing, exists := bestByEndpoint[descriptor.Key]
// Dedup key includes cli.id when present so that envelopes
// intentionally splitting one MCP endpoint into multiple CLI command
// trees (e.g. bot-root / bot-message / bot-group all serving
// .../server/4717... but exposing different command roots) are not
// collapsed by endpoint-only dedup. Without cli.id the key falls
// back to descriptor.Key (= endpoint) for backwards compatibility.
endpointKey := dedupKeyForEndpoint(descriptor)
existing, exists := bestByEndpoint[endpointKey]
if !exists || descriptorIsNewer(descriptor, existing) {
bestByEndpoint[descriptor.Key] = descriptor
bestByEndpoint[endpointKey] = descriptor
}
}
bestByName := make(map[string]ServerDescriptor)
for _, descriptor := range bestByEndpoint {
nameKey := normalizeDisplayNameKey(descriptor.DisplayName)
if nameKey == "" {
nameKey = descriptor.Key
}
// Same reasoning as endpoint dedup: append cli.id so three bot-*
// entries with displayName "机器人消息" don't collapse into one.
nameKey := dedupKeyForName(descriptor)
existing, exists := bestByName[nameKey]
if !exists || descriptorIsNewer(descriptor, existing) {
bestByName[nameKey] = descriptor
@@ -692,6 +710,33 @@ func normalizeDisplayNameKey(displayName string) string {
return strings.ToLower(strings.TrimSpace(displayName))
}
// dedupKeyForEndpoint returns the dedup key used when collapsing multiple
// envelope entries that share an MCP endpoint. cli.id is appended so an
// endpoint intentionally fronting multiple CLI command roots (bot-root /
// bot-message / bot-group all served by the same MCP server) stays as
// distinct descriptors. When cli.id is empty (or absent), the key is the
// endpoint alone to preserve historical dedup behaviour.
func dedupKeyForEndpoint(descriptor ServerDescriptor) string {
if cliID := strings.TrimSpace(descriptor.CLI.ID); cliID != "" {
return descriptor.Key + "#" + cliID
}
return descriptor.Key
}
// dedupKeyForName mirrors dedupKeyForEndpoint for the second-pass name-based
// dedup so two envelopes with the same displayName but distinct cli.id (the
// bot-* trio shares displayName "机器人消息") remain separate.
func dedupKeyForName(descriptor ServerDescriptor) string {
nameKey := normalizeDisplayNameKey(descriptor.DisplayName)
if nameKey == "" {
nameKey = descriptor.Key
}
if cliID := strings.TrimSpace(descriptor.CLI.ID); cliID != "" {
return nameKey + "#" + cliID
}
return nameKey
}
func markDeprecatedCandidate(displayName string, lifecycle LifecycleInfo) LifecycleInfo {
if lifecycle.DeprecatedCandidate {
return lifecycle
+59
View File
@@ -101,6 +101,65 @@ func TestNormalizeServersDeduplicatesSameNameAcrossEndpoints(t *testing.T) {
}
}
// TestNormalizeServersPreservesDistinctCLIIDsOnSharedEndpoint guards the
// bot-root / bot-message / bot-group split (issue: chat bot subtree vanished
// from the CLI after NormalizeServers collapsed three envelopes that share a
// single MCP endpoint and displayName but expose different cli.id values).
func TestNormalizeServersPreservesDistinctCLIIDsOnSharedEndpoint(t *testing.T) {
t.Parallel()
sharedURL := "https://example.com/server/4717"
sharedName := "机器人消息"
response := ListResponse{
Servers: []ServerEnvelope{
{
Server: RegistryServer{
Name: sharedName,
Remotes: []RegistryRemote{{Type: "streamable-http", URL: sharedURL}},
},
Meta: EnvelopeMeta{
Registry: RegistryMetadata{Status: "active", UpdatedAt: "2026-03-29T00:00:00Z"},
CLI: CLIOverlay{ID: "bot-root", Command: "bot"},
},
},
{
Server: RegistryServer{
Name: sharedName,
Remotes: []RegistryRemote{{Type: "streamable-http", URL: sharedURL}},
},
Meta: EnvelopeMeta{
Registry: RegistryMetadata{Status: "active", UpdatedAt: "2026-03-29T00:00:00Z"},
CLI: CLIOverlay{ID: "bot-message", Command: "message"},
},
},
{
Server: RegistryServer{
Name: sharedName,
Remotes: []RegistryRemote{{Type: "streamable-http", URL: sharedURL}},
},
Meta: EnvelopeMeta{
Registry: RegistryMetadata{Status: "active", UpdatedAt: "2026-03-29T00:00:00Z"},
CLI: CLIOverlay{ID: "bot-group", Command: "group"},
},
},
},
}
servers := NormalizeServers(response, "live_market")
if len(servers) != 3 {
t.Fatalf("NormalizeServers() len = %d, want 3 (one per cli.id)", len(servers))
}
seen := map[string]bool{}
for _, s := range servers {
seen[s.CLI.ID] = true
}
for _, want := range []string{"bot-root", "bot-message", "bot-group"} {
if !seen[want] {
t.Errorf("NormalizeServers() missing descriptor with cli.id %q", want)
}
}
}
func TestNormalizeServersMarksLegacyNameAsDeprecatedCandidate(t *testing.T) {
t.Parallel()
+25 -10
View File
@@ -79,6 +79,12 @@ func RunPreParse(root *cobra.Command, engine *Engine) {
// FlagInfoFromCommand extracts FlagInfo entries from a Cobra
// command's registered flags (both local and inherited).
//
// JSON Schema "format" and "enum" hints injected via pflag
// annotations (x-cli-format / x-cli-enum, see
// internal/compat/dynamic_commands.go) are surfaced on FlagInfo
// so PreParse handlers can validate sticky-split candidates against
// the actual schema, not just the pflag type.
func FlagInfoFromCommand(cmd *cobra.Command) []FlagInfo {
if cmd == nil {
return nil
@@ -92,11 +98,7 @@ func FlagInfoFromCommand(cmd *cobra.Command) []FlagInfo {
return
}
seen[f.Name] = true
infos = append(infos, FlagInfo{
Name: f.Name,
PropertyName: f.Name,
Type: f.Value.Type(),
})
infos = append(infos, flagInfoFromPflag(f))
})
cmd.InheritedFlags().VisitAll(func(f *pflag.Flag) {
@@ -104,12 +106,25 @@ func FlagInfoFromCommand(cmd *cobra.Command) []FlagInfo {
return
}
seen[f.Name] = true
infos = append(infos, FlagInfo{
Name: f.Name,
PropertyName: f.Name,
Type: f.Value.Type(),
})
infos = append(infos, flagInfoFromPflag(f))
})
return infos
}
// flagInfoFromPflag builds a FlagInfo from a pflag.Flag, copying
// schema metadata stashed in the flag's annotations map.
func flagInfoFromPflag(f *pflag.Flag) FlagInfo {
fi := FlagInfo{
Name: f.Name,
PropertyName: f.Name,
Type: f.Value.Type(),
}
if v := f.Annotations["x-cli-format"]; len(v) > 0 {
fi.Format = v[0]
}
if v := f.Annotations["x-cli-enum"]; len(v) > 0 {
fi.Enum = append([]string{}, v...)
}
return fi
}
+45 -12
View File
@@ -32,76 +32,101 @@ func TestFullPreParsePipeline(t *testing.T) {
ParamNameHandler{},
)
// Numeric / boolean flag typing matters for the sticky guard. The
// helper below declares known flags as int so digit-led suffixes
// pass the suffixLooksLikeValue check.
intSpecs := func(names ...string) []pipeline.FlagInfo {
out := make([]pipeline.FlagInfo, len(names))
for i, n := range names {
out[i] = pipeline.FlagInfo{Name: n, Type: "int"}
}
return out
}
tests := []struct {
name string
args []string
flags []string
flags []pipeline.FlagInfo
want string
corrections int
}{
{
name: "camelCase + sticky combined",
args: []string{"--userId", "123", "--pageSize50"},
flags: []string{"user-id", "page-size"},
flags: intSpecs("user-id", "page-size"),
want: "--user-id 123 --page-size 50",
corrections: 2, // alias(userId) + sticky(pageSize50)
},
{
name: "camelCase + typo combined",
args: []string{"--userId", "123", "--limt", "10"},
flags: []string{"user-id", "limit"},
flags: intSpecs("user-id", "limit"),
want: "--user-id 123 --limit 10",
corrections: 2, // alias(userId) + fuzzy(limt)
},
{
name: "triple error: case + sticky + typo",
args: []string{"--UserName", "alice", "--limit100", "--offse", "0"},
flags: []string{"user-name", "limit", "offset"},
flags: append(flagSpecs("user-name"), intSpecs("limit", "offset")...),
want: "--user-name alice --limit 100 --offset 0",
corrections: 3,
},
{
name: "snake_case + sticky",
args: []string{"--user_id", "42", "--pageSize20"},
flags: []string{"user-id", "page-size"},
flags: intSpecs("user-id", "page-size"),
want: "--user-id 42 --page-size 20",
corrections: 2,
},
{
name: "all correct — zero corrections",
args: []string{"--user-id", "123", "--limit", "10"},
flags: []string{"user-id", "limit"},
flags: intSpecs("user-id", "limit"),
want: "--user-id 123 --limit 10",
corrections: 0,
},
{
name: "UPPER case flags",
args: []string{"--USER-ID", "999"},
flags: []string{"user-id"},
flags: intSpecs("user-id"),
want: "--user-id 999",
corrections: 1,
},
{
name: "= syntax with camelCase",
args: []string{"--userId=123", "--pageSize=50"},
flags: []string{"user-id", "page-size"},
flags: intSpecs("user-id", "page-size"),
want: "--user-id=123 --page-size=50",
corrections: 2,
},
{
name: "camelCase sticky split with normalisation",
args: []string{"--limitValue100"},
flags: []string{"limit-value"},
flags: intSpecs("limit-value"),
want: "--limit-value 100",
corrections: 1, // sticky handles both kebab-normalisation and split
},
// Hardening: a mistyped flag whose name happens to start with
// a real flag must NOT be split. The pipeline should leave the
// token untouched so Cobra can raise "unknown flag".
{
name: "typo --starttime1 not split (date-time format)",
args: []string{"--starttime1", "2026-02-07"},
flags: []pipeline.FlagInfo{
{Name: "start", Type: "string", Format: "date-time"},
{Name: "end", Type: "string", Format: "date-time"},
},
want: "--starttime1 2026-02-07",
corrections: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := &pipeline.Context{
Args: append([]string{}, tt.args...),
FlagSpecs: flagSpecs(tt.flags...),
FlagSpecs: tt.flags,
}
if err := engine.RunPhase(pipeline.PreParse, ctx); err != nil {
t.Fatalf("RunPhase error: %v", err)
@@ -191,7 +216,11 @@ func TestFullPipelineEndToEnd(t *testing.T) {
"--pageSize50",
"--verbosetrue",
},
FlagSpecs: flagSpecs("user-id", "page-size", "verbose"),
FlagSpecs: []pipeline.FlagInfo{
{Name: "user-id", Type: "string"},
{Name: "page-size", Type: "int"},
{Name: "verbose", Type: "bool"},
},
}
if err := engine.RunPhase(pipeline.PreParse, ctx); err != nil {
@@ -287,7 +316,11 @@ func TestFullFivePhasePipeline(t *testing.T) {
"--pageSize50",
"--verbosetrue",
}
ctx.FlagSpecs = flagSpecs("user-id", "page-size", "verbose")
ctx.FlagSpecs = []pipeline.FlagInfo{
{Name: "user-id", Type: "string"},
{Name: "page-size", Type: "int"},
{Name: "verbose", Type: "bool"},
}
if err := engine.RunPhase(pipeline.PreParse, ctx); err != nil {
t.Fatalf("PreParse error: %v", err)
+45 -8
View File
@@ -17,6 +17,7 @@ import (
"strings"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pipeline"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/cmdutil"
)
// StickyHandler detects glued flag-value pairs in raw argv and splits
@@ -25,7 +26,12 @@ import (
//
// The handler only operates on tokens that start with "--" and do not
// contain "=". It tries to match the longest known flag name prefix
// and, if the remaining suffix is non-empty, splits the token.
// and, if the remaining suffix is non-empty AND looks like a plausible
// value for the matched flag's type/format, splits the token. The
// type/format guard prevents misinterpreting mistyped flag names like
// "--starttime1" as "--start time1" — when the suffix does not look
// like a value, the original token is left untouched so Cobra can
// report "unknown flag".
type StickyHandler struct{}
func (StickyHandler) Name() string { return "sticky" }
@@ -36,11 +42,11 @@ func (StickyHandler) Handle(ctx *pipeline.Context) error {
return nil
}
known := buildFlagSet(ctx.FlagSpecs)
specByName := buildFlagSpecIndex(ctx.FlagSpecs)
result := make([]string, 0, len(ctx.Args))
for _, arg := range ctx.Args {
split, ok := trySplitSticky(arg, known)
split, ok := trySplitSticky(arg, specByName)
if ok {
ctx.AddCorrection("sticky", pipeline.PreParse, split.flag, arg, split.flag+" "+split.value, "sticky")
result = append(result, split.flag, split.value)
@@ -65,12 +71,14 @@ type stickyPair struct {
// - the prefix matches a known flag name (directly or after
// kebab-case normalisation)
// - the remaining suffix is non-empty
// - the suffix looks like a plausible value for the matched flag's
// declared type/format/enum (suffixLooksLikeValue)
//
// When multiple flag names match as prefixes, the longest one wins.
// The handler also tries kebab-case normalisation of each prefix so
// that camelCase+glued values like "--pageSize50" are correctly
// split to "--page-size", "50".
func trySplitSticky(arg string, known map[string]bool) (stickyPair, bool) {
func trySplitSticky(arg string, specByName map[string]pipeline.FlagInfo) (stickyPair, bool) {
if !strings.HasPrefix(arg, "--") || strings.Contains(arg, "=") {
return stickyPair{}, false
}
@@ -83,7 +91,10 @@ func trySplitSticky(arg string, known map[string]bool) (stickyPair, bool) {
// If the whole token is a known flag, it is not sticky — it is
// a normal flag expecting a separate value token.
if known[bare] || known[toKebabCase(bare)] {
if _, ok := specByName[bare]; ok {
return stickyPair{}, false
}
if _, ok := specByName[toKebabCase(bare)]; ok {
return stickyPair{}, false
}
@@ -96,12 +107,14 @@ func trySplitSticky(arg string, known map[string]bool) (stickyPair, bool) {
prefix := bare[:i]
matchedFlag := ""
if known[prefix] {
if _, ok := specByName[prefix]; ok {
matchedFlag = prefix
} else {
kebab := toKebabCase(prefix)
if kebab != "" && known[kebab] {
matchedFlag = kebab
if kebab != "" {
if _, ok := specByName[kebab]; ok {
matchedFlag = kebab
}
}
}
@@ -120,14 +133,38 @@ func trySplitSticky(arg string, known map[string]bool) (stickyPair, bool) {
return stickyPair{}, false
}
// Guard: only split if the suffix plausibly looks like a value
// for this flag's declared type/format/enum. Otherwise leave the
// token untouched so Cobra reports "unknown flag" instead of
// silently corrupting the value.
fi := specByName[bestFlag]
if !cmdutil.SuffixLooksLikeValue(suffix, fi.Type, fi.Format, fi.Enum) {
return stickyPair{}, false
}
return stickyPair{
flag: "--" + bestFlag,
value: suffix,
}, true
}
// buildFlagSpecIndex creates an index of known flag names (without "--"
// prefix) to their FlagInfo entries from the context's FlagSpecs.
func buildFlagSpecIndex(specs []pipeline.FlagInfo) map[string]pipeline.FlagInfo {
m := make(map[string]pipeline.FlagInfo, len(specs))
for _, spec := range specs {
if spec.Name != "" {
m[spec.Name] = spec
}
}
return m
}
// buildFlagSet creates a set of known flag names (without "--" prefix)
// from the context's FlagSpecs.
//
// Retained for other PreParse handlers (alias, paramname) that only
// need name presence and do not consume the richer FlagInfo metadata.
func buildFlagSet(specs []pipeline.FlagInfo) map[string]bool {
m := make(map[string]bool, len(specs))
for _, spec := range specs {
+161 -27
View File
@@ -20,6 +20,12 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pipeline"
)
// flagSpecs is the legacy helper used by alias/paramname tests. It
// produces string-typed FlagInfo entries which is fine for those
// handlers because they don't consult the type.
//
// Sticky tests should use flagSpecsTyped (below) — the post-hardening
// sticky decision depends on Type/Format/Enum.
func flagSpecs(names ...string) []pipeline.FlagInfo {
specs := make([]pipeline.FlagInfo, len(names))
for i, name := range names {
@@ -28,126 +34,254 @@ func flagSpecs(names ...string) []pipeline.FlagInfo {
return specs
}
// flagSpec is a compact builder used by sticky tests to declare typed
// flags inline. Type defaults to "string" when unset.
type flagSpec struct {
name string
typ string
format string
enum []string
}
func specs(in ...flagSpec) []pipeline.FlagInfo {
out := make([]pipeline.FlagInfo, len(in))
for i, s := range in {
t := s.typ
if t == "" {
t = "string"
}
out[i] = pipeline.FlagInfo{
Name: s.name,
Type: t,
Format: s.format,
Enum: s.enum,
}
}
return out
}
func TestStickyHandler(t *testing.T) {
tests := []struct {
name string
args []string
flags []string
flags []pipeline.FlagInfo
want string
corrections int
}{
{
name: "basic split --limit100",
name: "basic split --limit100 (int)",
args: []string{"--limit100"},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--limit 100",
corrections: 1,
},
{
name: "no split when flag takes value separately",
args: []string{"--limit", "100"},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--limit 100",
corrections: 0,
},
{
name: "no split when = syntax used",
args: []string{"--limit=100"},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--limit=100",
corrections: 0,
},
{
name: "no split when flag name is not known",
args: []string{"--unknown100"},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--unknown100",
corrections: 0,
},
{
name: "split with string value",
args: []string{"--nameJohn"},
flags: []string{"name"},
want: "--name John",
corrections: 1,
},
{
name: "longest prefix wins",
args: []string{"--user-id123"},
flags: []string{"user", "user-id"},
flags: specs(flagSpec{name: "user"}, flagSpec{name: "user-id", typ: "int"}),
want: "--user-id 123",
corrections: 1,
},
{
name: "multiple sticky args in one invocation",
args: []string{"--limit100", "--offset50"},
flags: []string{"limit", "offset"},
flags: specs(flagSpec{name: "limit", typ: "int"}, flagSpec{name: "offset", typ: "int"}),
want: "--limit 100 --offset 50",
corrections: 2,
},
{
name: "mixed sticky and normal args",
args: []string{"--limit100", "--name", "test", "--offset50"},
flags: []string{"limit", "name", "offset"},
name: "mixed sticky and normal args",
args: []string{"--limit100", "--name", "test", "--offset50"},
flags: specs(
flagSpec{name: "limit", typ: "int"},
flagSpec{name: "name"},
flagSpec{name: "offset", typ: "int"},
),
want: "--limit 100 --name test --offset 50",
corrections: 2,
},
{
name: "single dash prefix is ignored",
args: []string{"-l100"},
flags: []string{"l"},
flags: specs(flagSpec{name: "l", typ: "int"}),
want: "-l100",
corrections: 0,
},
{
name: "empty args",
args: []string{},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "",
corrections: 0,
},
{
name: "bare double dash",
args: []string{"--"},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--",
corrections: 0,
},
{
name: "no flag specs available",
args: []string{"--limit100"},
flags: []string{},
flags: nil,
want: "--limit100",
corrections: 0,
},
{
name: "exact flag name is not split",
args: []string{"--limit"},
flags: []string{"limit"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--limit",
corrections: 0,
},
{
name: "boolean-like value still splits",
name: "boolean-like value splits when type is bool",
args: []string{"--verbosetrue"},
flags: []string{"verbose"},
flags: specs(flagSpec{name: "verbose", typ: "bool"}),
want: "--verbose true",
corrections: 1,
},
{
name: "hyphenated flag name with numeric suffix",
args: []string{"--page-size50"},
flags: []string{"page-size", "page"},
flags: specs(flagSpec{name: "page-size", typ: "int"}, flagSpec{name: "page", typ: "int"}),
want: "--page-size 50",
corrections: 1,
},
// --- Hardening cases: typo flags MUST NOT be misinterpreted ---
{
name: "typo --starttime1 not split (date-time format)",
args: []string{"--starttime1", "2026-02-07"},
flags: specs(flagSpec{
name: "start", typ: "string", format: "date-time",
}),
want: "--starttime1 2026-02-07",
corrections: 0,
},
{
name: "glued ISO date splits cleanly (date-time format)",
args: []string{"--start2026-02-07"},
flags: specs(flagSpec{
name: "start", typ: "string", format: "date-time",
}),
want: "--start 2026-02-07",
corrections: 1,
},
{
name: "int flag rejects alpha suffix",
args: []string{"--limitabc"},
flags: specs(flagSpec{name: "limit", typ: "int"}),
want: "--limitabc",
corrections: 0,
},
{
name: "bool flag rejects non-literal suffix",
args: []string{"--verbosehello"},
flags: specs(flagSpec{name: "verbose", typ: "bool"}),
want: "--verbosehello",
corrections: 0,
},
{
name: "string + enum: suffix hits enum splits",
args: []string{"--statusapproved"},
flags: specs(flagSpec{
name: "status", typ: "string", enum: []string{"approved", "pending"},
}),
want: "--status approved",
corrections: 1,
},
{
name: "string + enum: suffix not in enum refuses split",
args: []string{"--statusunknown"},
flags: specs(flagSpec{
name: "status", typ: "string", enum: []string{"approved", "pending"},
}),
want: "--statusunknown",
corrections: 0,
},
{
name: "email format: suffix containing @ splits",
args: []string{"--emailfoo@bar.com"},
flags: specs(flagSpec{
name: "email", typ: "string", format: "email",
}),
want: "--email foo@bar.com",
corrections: 1,
},
{
name: "email format: suffix without @ refuses split",
args: []string{"--emailalice"},
flags: specs(flagSpec{
name: "email", typ: "string", format: "email",
}),
want: "--emailalice",
corrections: 0,
},
{
name: "stringSlice: refuses to split (ambiguous)",
args: []string{"--tagsfoo,bar"},
flags: specs(flagSpec{name: "tags", typ: "stringSlice"}),
want: "--tagsfoo,bar",
corrections: 0,
},
{
name: "plain string + no metadata: alpha suffix refuses split",
args: []string{"--nameJohn"},
flags: specs(flagSpec{name: "name"}),
want: "--nameJohn",
corrections: 0,
},
{
name: "plain string + no metadata: digit-led suffix splits",
args: []string{"--name123"},
flags: specs(flagSpec{name: "name"}),
want: "--name 123",
corrections: 1,
},
{
name: "duration type: digit-led suffix splits",
args: []string{"--timeout30s"},
flags: specs(flagSpec{name: "timeout", typ: "duration"}),
want: "--timeout 30s",
corrections: 1,
},
{
name: "duration type: alpha suffix refuses split",
args: []string{"--timeoutever"},
flags: specs(flagSpec{name: "timeout", typ: "duration"}),
want: "--timeoutever",
corrections: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := &pipeline.Context{
Args: append([]string{}, tt.args...),
FlagSpecs: flagSpecs(tt.flags...),
FlagSpecs: tt.flags,
}
h := StickyHandler{}
if err := h.Handle(ctx); err != nil {
+13 -1
View File
@@ -120,8 +120,20 @@ type FlagInfo struct {
// PropertyName is the original schema property key (e.g. "userId").
PropertyName string
// Type is the JSON Schema type ("string", "integer", etc.).
// Type is the JSON Schema / pflag type ("string", "integer",
// "bool", "stringSlice", "duration", etc.).
Type string
// Format carries the JSON Schema "format" hint when present —
// e.g. "date", "date-time", "duration", "email", "uri", "ipv4".
// PreParse handlers use this to decide whether a suffix in a
// glued token (e.g. "--starttime1") looks like a plausible value.
Format string
// Enum carries the JSON Schema "enum" string values when present.
// PreParse handlers use this for sticky-split validation: a glued
// suffix is accepted only if it matches one of the enum entries.
Enum []string
}
// Correction records a single input correction applied by a handler.
+4
View File
@@ -106,6 +106,7 @@ func (s *StdioClient) Start(ctx context.Context) error {
}
// Stop kills the subprocess and waits for it to exit.
// A non-zero exit code after Kill is expected and not treated as an error.
func (s *StdioClient) Stop() error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -118,6 +119,9 @@ func (s *StdioClient) Stop() error {
if s.cmd.Process != nil {
_ = s.cmd.Process.Kill()
_ = s.cmd.Wait()
s.started = false
return nil
}
err := s.cmd.Wait()
s.started = false
+2 -3
View File
@@ -97,10 +97,9 @@ func TestStdioClientEndToEnd(t *testing.T) {
t.Error("CallTool with unknown tool should return error")
}
// Stop
// Stop — after kill, Stop should return nil (non-zero exit is suppressed)
if err := client.Stop(); err != nil {
// Process killed, expected to return an error
_ = err
t.Errorf("Stop after kill should return nil, got %v", err)
}
}
+78 -6
View File
@@ -15,6 +15,7 @@ package cmdutil
import (
"fmt"
"sort"
"strings"
"github.com/spf13/cobra"
@@ -75,6 +76,41 @@ func DetectNumericTypeError(err error) (flagName, badValue string, ok bool) {
return rest[:endIdx], badVal, true
}
// flagFixCandidate reports whether f should participate in unknown-flag
// suggestion candidates and Flags: listings. Hidden flags (e.g. wukong's
// MarkHidden compatibility aliases) and internal json/params merge flags
// are skipped so the hint candidate set stays a subset of what --help shows.
func flagFixCandidate(f *pflag.Flag) bool {
if f == nil || f.Hidden {
return false
}
switch f.Name {
case "json", "params":
return false
}
return true
}
// VisibleFlagNames returns sorted candidate flag names for cmd.Flags()
// using flagFixCandidate. Intended for agent-facing error recovery
// (available_flags).
func VisibleFlagNames(cmd *cobra.Command) []string {
if cmd == nil {
return nil
}
seen := make(map[string]bool)
var names []string
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !flagFixCandidate(f) || seen[f.Name] {
return
}
seen[f.Name] = true
names = append(names, f.Name)
})
sort.Strings(names)
return names
}
// SuggestFlagFix detects flag-value concatenation errors, common flag aliases,
// and Levenshtein-close typos.
func SuggestFlagFix(cmd *cobra.Command, flagErr error) FlagFixResult {
@@ -92,6 +128,9 @@ func SuggestFlagFix(cmd *cobra.Command, flagErr error) FlagFixResult {
var bestFlag, bestValue string
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !flagFixCandidate(f) {
return
}
name := f.Name
if strings.HasPrefix(body, name) && len(body) > len(name) {
if len(name) > len(bestFlag) {
@@ -101,16 +140,28 @@ func SuggestFlagFix(cmd *cobra.Command, flagErr error) FlagFixResult {
}
})
if bestFlag != "" {
canAutoFix := len(bestValue) > 0
suggestion := fmt.Sprintf("Space required between flag and value: --%s %s", bestFlag, bestValue)
if canAutoFix {
return FlagFixResult{Suggestion: suggestion, AutoFixFlag: bestFlag, AutoFixValue: bestValue}
lf := cmd.Flags().Lookup(bestFlag)
if lf != nil {
fmtStr := ""
if v := lf.Annotations["x-cli-format"]; len(v) > 0 {
fmtStr = v[0]
}
var enumCopy []string
if v := lf.Annotations["x-cli-enum"]; len(v) > 0 {
enumCopy = append([]string{}, v...)
}
if SuffixLooksLikeValue(bestValue, lf.Value.Type(), fmtStr, enumCopy) {
suggestion := fmt.Sprintf("Space required between flag and value: --%s %s", bestFlag, bestValue)
return FlagFixResult{Suggestion: suggestion, AutoFixFlag: bestFlag, AutoFixValue: bestValue}
}
}
return FlagFixResult{Suggestion: suggestion}
}
bestName, bestDist := "", 999
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !flagFixCandidate(f) {
return
}
d := LevenshteinDist(body, f.Name)
if d < bestDist {
bestDist = d
@@ -119,12 +170,33 @@ func SuggestFlagFix(cmd *cobra.Command, flagErr error) FlagFixResult {
})
threshold := LevenshteinThreshold(len(body))
if bestDist > 0 && bestDist <= threshold && bestName != "" {
return FlagFixResult{Suggestion: fmt.Sprintf("Did you mean --%s?", bestName)}
suf := formatFlagHintSuffix(cmd.Flags().Lookup(bestName))
return FlagFixResult{Suggestion: fmt.Sprintf("Did you mean --%s?%s", bestName, suf)}
}
return FlagFixResult{Suggestion: fmt.Sprintf("Run '%s --help' to see available options", cmd.CommandPath())}
}
func formatFlagHintSuffix(f *pflag.Flag) string {
if f == nil {
return ""
}
var parts []string
if u := strings.TrimSpace(f.Usage); u != "" {
if len(u) > 100 {
u = u[:97] + "..."
}
parts = append(parts, u)
}
if v := f.Annotations["x-cli-format"]; len(v) > 0 && v[0] != "" {
parts = append(parts, "format="+v[0])
}
if len(parts) == 0 {
return ""
}
return " (" + strings.Join(parts, ", ") + ")"
}
// LevenshteinThreshold returns the max edit distance allowed based on string length.
func LevenshteinThreshold(nameLen int) int {
if nameLen <= 3 {
+106
View File
@@ -0,0 +1,106 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmdutil
import (
"strings"
"testing"
"github.com/spf13/cobra"
)
func TestSuggestFlagFix_falseGlue_starttime1(t *testing.T) {
cmd := &cobra.Command{Use: "list"}
cmd.Flags().String("start", "", "begin time")
_ = cmd.Flags().SetAnnotation("start", "x-cli-format", []string{"date-time"})
err := errUnknownFlag("starttime1")
fix := SuggestFlagFix(cmd, err)
if strings.Contains(fix.Suggestion, "Space required") {
t.Fatalf("should not treat as glued value, got %q", fix.Suggestion)
}
if fix.AutoFixFlag != "" {
t.Fatalf("AutoFixFlag = %q, want empty", fix.AutoFixFlag)
}
if !strings.Contains(fix.Suggestion, "--help") {
t.Fatalf("expected help fallback, got %q", fix.Suggestion)
}
}
func TestSuggestFlagFix_trueGlue_isoDateSuffix(t *testing.T) {
cmd := &cobra.Command{Use: "list"}
cmd.Flags().String("start", "", "begin time")
_ = cmd.Flags().SetAnnotation("start", "x-cli-format", []string{"date-time"})
err := errUnknownFlag("start2026-02-07")
fix := SuggestFlagFix(cmd, err)
wantSub := "Space required between flag and value: --start 2026-02-07"
if fix.Suggestion != wantSub {
t.Fatalf("Suggestion = %q, want %q", fix.Suggestion, wantSub)
}
if fix.AutoFixFlag != "start" || fix.AutoFixValue != "2026-02-07" {
t.Fatalf("AutoFix = %q/%q, want start/2026-02-07", fix.AutoFixFlag, fix.AutoFixValue)
}
}
func TestSuggestFlagFix_levenshteinAddsUsage(t *testing.T) {
cmd := &cobra.Command{Use: "send"}
cmd.Flags().String("conversation-id", "", "Conversation id")
err := errUnknownFlag("conversaton-id")
fix := SuggestFlagFix(cmd, err)
if !strings.HasPrefix(fix.Suggestion, "Did you mean --conversation-id?") {
t.Fatalf("unexpected: %q", fix.Suggestion)
}
if !strings.Contains(fix.Suggestion, "Conversation id") {
t.Fatalf("expected usage in hint, got %q", fix.Suggestion)
}
}
func TestSuggestFlagFix_skipsHiddenAlias(t *testing.T) {
cmd := &cobra.Command{Use: "list"}
cmd.Flags().String("start", "", "begin time")
_ = cmd.Flags().SetAnnotation("start", "x-cli-format", []string{"date-time"})
cmd.Flags().String("start-time", "", "")
_ = cmd.Flags().MarkHidden("start-time")
fix := SuggestFlagFix(cmd, errUnknownFlag("starttime1"))
if strings.Contains(fix.Suggestion, "start-time") {
t.Fatalf("must not recommend hidden alias, got %q", fix.Suggestion)
}
if !strings.Contains(fix.Suggestion, "--help") {
t.Fatalf("expected help fallback, got %q", fix.Suggestion)
}
}
func TestVisibleFlagNames_skipsHiddenAndInternal(t *testing.T) {
cmd := &cobra.Command{Use: "x"}
cmd.Flags().String("alpha", "", "")
cmd.Flags().String("json", "", "")
cmd.Flags().String("beta", "", "")
_ = cmd.Flags().MarkHidden("beta")
names := VisibleFlagNames(cmd)
if len(names) != 1 || names[0] != "alpha" {
t.Fatalf("got %v, want [alpha]", names)
}
}
func errUnknownFlag(body string) error {
return &stubFlagErr{msg: "unknown flag: --" + body}
}
type stubFlagErr struct{ msg string }
func (e *stubFlagErr) Error() string { return e.msg }
+133
View File
@@ -0,0 +1,133 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmdutil
import (
"strings"
"unicode"
"unicode/utf8"
)
// SuffixLooksLikeValue decides whether a candidate suffix from a glued
// "--flagsuffix" token plausibly represents a value for a flag's
// declared type/format/enum. Shared by StickyHandler (PreParse) and
// SuggestFlagFix (unknown-flag recovery).
//
// typ is a pflag value type string (e.g. "int", "bool", "string");
// format is JSON Schema "format" when present (e.g. "date-time");
// enum is the schema enum list when present.
func SuffixLooksLikeValue(suffix, typ, format string, enum []string) bool {
if suffix == "" {
return false
}
switch typ {
case "int", "int8", "int16", "int32", "int64",
"uint", "uint8", "uint16", "uint32", "uint64",
"integer", "number", "float", "float32", "float64",
"count":
return startsWithNumericSuffix(suffix)
case "bool", "boolean":
return isBoolLiteralSuffix(suffix)
case "duration":
return startsWithDigitSuffix(suffix) || startsWithSignSuffix(suffix)
case "stringSlice", "stringArray", "intSlice", "boolSlice", "float32Slice",
"float64Slice", "uintSlice", "durationSlice", "ipSlice", "array":
return false
case "object":
return false
}
if len(enum) > 0 {
return matchesEnumSuffix(suffix, enum)
}
switch strings.ToLower(format) {
case "date", "date-time", "datetime", "time":
return startsWithDigitSuffix(suffix)
case "duration":
return startsWithDigitSuffix(suffix) || startsWithSignSuffix(suffix)
case "email":
return strings.Contains(suffix, "@")
case "uri", "url":
lower := strings.ToLower(suffix)
return strings.HasPrefix(lower, "http") ||
strings.HasPrefix(lower, "ftp") ||
strings.HasPrefix(lower, "mailto:")
case "ipv4", "ipv6", "hostname":
return startsWithDigitSuffix(suffix)
case "uuid":
first, _ := utf8.DecodeRuneInString(suffix)
return isHexRuneSuffix(first)
}
first, _ := utf8.DecodeRuneInString(suffix)
if first == utf8.RuneError || unicode.IsLetter(first) {
return false
}
return true
}
func startsWithDigitSuffix(s string) bool {
if s == "" {
return false
}
c := s[0]
return c >= '0' && c <= '9'
}
func startsWithSignSuffix(s string) bool {
if s == "" {
return false
}
c := s[0]
return c == '+' || c == '-'
}
func startsWithNumericSuffix(s string) bool {
if startsWithDigitSuffix(s) {
return true
}
if startsWithSignSuffix(s) && len(s) > 1 {
c := s[1]
return c >= '0' && c <= '9'
}
return false
}
func isBoolLiteralSuffix(s string) bool {
switch strings.ToLower(s) {
case "true", "false", "1", "0", "t", "f", "yes", "no", "on", "off", "y", "n":
return true
}
return false
}
func matchesEnumSuffix(s string, enum []string) bool {
lower := strings.ToLower(s)
for _, e := range enum {
if strings.ToLower(e) == lower {
return true
}
}
return false
}
func isHexRuneSuffix(r rune) bool {
return (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')
}
+91
View File
@@ -0,0 +1,91 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmdutil
import "testing"
// TestSuffixLooksLikeValue_UTF8FirstRune locks in the UTF-8 first-rune
// reading contract on SuffixLooksLikeValue. The function previously read
// suffix[0] (a single byte) which produced incorrect splits / matches for
// any multi-byte first rune — relevant because dws is a Chinese-language
// CLI and value text often starts with CJK characters.
func TestSuffixLooksLikeValue_UTF8FirstRune(t *testing.T) {
t.Parallel()
cases := []struct {
name string
suffix string
typ string
format string
enum []string
want bool
}{
{
// --name张三 must NOT be split: with no metadata the fallback
// branch should treat a CJK letter as "not a value-looking
// suffix" so cobra reports unknown flag instead of cutting
// the user's typo into --name + 张三.
name: "plain string + CJK letter suffix refuses split",
suffix: "张三",
typ: "string",
want: false,
},
{
// CJK leading rune is fine as long as the email-format guard
// ('@' anywhere in suffix) still passes.
name: "email format + CJK leading + @ allows split",
suffix: "张三@example.com",
typ: "string",
format: "email",
want: true,
},
{
// uuid format: first rune must be hex. CJK starting char is
// not hex so the suffix must be rejected.
name: "uuid format + CJK leading rejects split",
suffix: "张abcd",
typ: "string",
format: "uuid",
want: false,
},
{
// Baseline: digit-led suffix on int still splits — guards
// against accidental over-tightening of the fallback path.
name: "int + digit-led baseline still splits",
suffix: "100",
typ: "int",
want: true,
},
{
// Invalid UTF-8 (lone continuation byte 0x80) decodes as
// utf8.RuneError; the RuneError guard makes the fallback
// reject it instead of treating it as "non-letter, splittable".
name: "plain string + invalid UTF-8 leading byte refuses split",
suffix: "\x80abc",
typ: "string",
want: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got := SuffixLooksLikeValue(tc.suffix, tc.typ, tc.format, tc.enum)
if got != tc.want {
t.Errorf("SuffixLooksLikeValue(%q, %q, %q, %v) = %v, want %v",
tc.suffix, tc.typ, tc.format, tc.enum, got, tc.want)
}
})
}
}
+20 -5
View File
@@ -74,23 +74,38 @@ const (
DefaultPartition = "default/default"
)
// EditionPartition returns the cache partition for a given edition name.
// The open-source core (name == "" or "open") uses DefaultPartition; every
// other edition gets its own namespace to prevent cross-edition data
// leakage in the disk cache.
// IsOpenEdition reports whether an edition name maps to the open-source core.
//
// This helper takes the edition name as a parameter instead of calling
// edition.Get() so that pkg/config remains a leaf dependency — importable
// from internal/cli, internal/app, internal/cache, etc. without risking
// import cycles.
func IsOpenEdition(name string) bool {
name = strings.TrimSpace(name)
return name == "" || name == "open"
}
// EditionPartition returns the cache partition for a given edition name.
// The open-source core (name == "" or "open") uses DefaultPartition; every
// other edition gets its own namespace to prevent cross-edition data
// leakage in the disk cache.
func EditionPartition(name string) string {
name = strings.TrimSpace(name)
if name == "" || name == "open" {
if IsOpenEdition(name) {
return DefaultPartition
}
return name + "/default"
}
// EditionFileName returns the edition-partitioned file name for base+ext.
func EditionFileName(name, base, ext string) string {
name = strings.TrimSpace(name)
if IsOpenEdition(name) {
return base + ext
}
return base + "-" + name + ext
}
// ── Auth flow timeouts ──────────────────────────────────────────────────
const (
+42
View File
@@ -96,6 +96,48 @@ func TestEditionPartition(t *testing.T) {
}
}
func TestIsOpenEdition(t *testing.T) {
t.Parallel()
cases := []struct {
name string
input string
want bool
}{
{"empty is open", "", true},
{"open is open", "open", true},
{"whitespace open is open", " open ", true},
{"wukong is sibling", "wukong", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := IsOpenEdition(tc.input); got != tc.want {
t.Fatalf("IsOpenEdition(%q) = %v, want %v", tc.input, got, tc.want)
}
})
}
}
func TestEditionFileName(t *testing.T) {
t.Parallel()
cases := []struct {
name string
edition string
want string
}{
{"empty uses legacy filename", "", "app.json"},
{"open uses legacy filename", "open", "app.json"},
{"whitespace is trimmed", " wukong ", "app-wukong.json"},
{"sibling is suffixed", "wukong", "app-wukong.json"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := EditionFileName(tc.edition, "app", ".json"); got != tc.want {
t.Fatalf("EditionFileName(%q, \"app\", \".json\") = %q, want %q", tc.edition, got, tc.want)
}
})
}
}
func TestManualTokenExpiry(t *testing.T) {
t.Parallel()
if ManualTokenExpiry <= 0 {
+71
View File
@@ -174,6 +174,74 @@ create_skills_zip() {
)
}
# ---------- darwin ad-hoc signing ----------
#
# Unsigned arm64 binaries are SIGKILL'd by amfid on Apple Silicon (macOS 11+).
# We unpack each dws-darwin-*.tar.gz, ad-hoc sign the dws binary, repack
# deterministically, and rewrite the corresponding line in checksums.txt.
sign_one_darwin_binary() {
bin="$1"
if command -v codesign >/dev/null 2>&1; then
codesign --force --sign - "$bin"
return
fi
if command -v rcodesign >/dev/null 2>&1; then
rcodesign sign "$bin"
return
fi
err "neither codesign nor rcodesign found — install rcodesign (cargo install apple-codesign) to ad-hoc sign darwin builds"
}
update_checksum_entry() {
filename="$1"
new_sha="$2"
checksum_path="$DIST_DIR/checksums.txt"
[ -f "$checksum_path" ] || return 0
tmp="$(mktemp)"
grep -v " ${filename}\$" "$checksum_path" > "$tmp" 2>/dev/null || true
printf '%s %s\n' "$new_sha" "$filename" >> "$tmp"
mv "$tmp" "$checksum_path"
}
sign_darwin_archives() {
work="$(mktemp -d)"
found_any=0
for archive in "$DIST_DIR"/dws-darwin-*.tar.gz; do
[ -f "$archive" ] || continue
found_any=1
name="$(basename "$archive")"
say " signing $name"
stage="$work/${name%.tar.gz}"
rm -rf "$stage"
mkdir -p "$stage"
tar -xzf "$archive" -C "$stage"
bin="$stage/dws"
if [ ! -f "$bin" ]; then
err "dws binary not found inside $name after extraction"
fi
sign_one_darwin_binary "$bin"
# Repack deterministically: sorted file order, zeroed owner/mtime so
# rerunning the script produces byte-identical archives (and sha256s).
(
cd "$stage" \
&& tar --sort=name --owner=0 --group=0 --numeric-owner \
--mtime='2020-01-01 00:00Z' \
-czf "$archive.new" .
)
mv "$archive.new" "$archive"
update_checksum_entry "$name" "$(sha256_file "$archive")"
done
rm -rf "$work"
if [ "$found_any" -eq 0 ]; then
say " (no darwin archives found, skipping)"
fi
}
write_checksums() {
checksum_path="$DIST_DIR/checksums.txt"
# Append skills zip checksum to goreleaser's checksums file
@@ -186,6 +254,9 @@ write_checksums() {
version="$(resolve_version)"
say "==> Ad-hoc signing darwin binaries"
sign_darwin_archives
say "==> Creating skills zip"
create_skills_zip
+2
View File
@@ -103,6 +103,7 @@ Step 3 → 加 --yes 执行命令
## 核心流程
作为一个智能助手,你的首要任务是**理解用户的真实、完整的意图**,而不是简单地执行命令。在选择 `dws` 的产品命令前,必须严格遵循以下四步流程:
0. **URL 预检**:输入含 `alidocs.dingtalk.com` URL 时,该域名下存在多种路径格式(`/i/nodes/...`、`/i/p/...`、`/spreadsheetv2/...`、`/document/edit|preview?dentryKey=...` 等),每种的处理流程不同。**必须先读取 [url-patterns.md](./references/url-patterns.md) 中的「alidocs URL 分流决策」**,按其中规则识别 URL 类型后再选择对应产品。含 `shanji.dingtalk.com` URL 时直接路由到 `minutes`。URL 已识别后直接进入对应产品流程,无需后续步骤。
1. 意图分类:首先,判断用户指令的核心 动词/动作 属于哪一类。这比关注名词更重要。
2. 歧义处理与信息追问:如果用户指令模糊或包含多个产品的关键字,严禁猜测。必须主动向用户追问以澄清意图。这是你作为智能助手而非命令执行器的核心价值。
3. 精准产品映射:在完成前两步,意图已经清晰后,参考产品总览和意图判断决策树 来选择产品。
@@ -144,6 +145,7 @@ dws schema <path> --jq '.tool.required' # 只看必填字段
- [references/products/](./references/products/) — 各产品命令详细参考(flag 细节以 `--help` / `dws schema` 为准)
- [references/intent-guide.md](./references/intent-guide.md) — 意图路由指南(易混淆场景对照)
- [references/url-patterns.md](./references/url-patterns.md) — URL 格式规范 + alidocs URL 分流决策与类型探测流程(含钉盘 `document/edit|preview?dentryKey=` 链接)
- [references/global-reference.md](./references/global-reference.md) — 全局标志、认证、输出格式
- [references/field-rules.md](./references/field-rules.md) — AI表格字段类型规则
- [references/error-codes.md](./references/error-codes.md) — 错误码 + 调试流程
+9 -8
View File
@@ -183,7 +183,7 @@ Flags:
## message send — 以当前用户身份发消息
--group 指定群聊 ID 发群消息;--user 指定用户 userId 发单聊;--open-dingtalk-id 指定用户 openDingTalkId 发单聊。三者只能选其一,不能同时指定。消息内容为位置参数(恰好 1 个),支持 Markdown。单聊消息(--user / --open-dingtalk-id)必须提供 --title 作为消息标题;群聊可选。
--group 指定群聊 ID 发群消息;--user 指定用户 userId 发单聊;--open-dingtalk-id 指定用户 openDingTalkId 发单聊。三者只能选其一,不能同时指定。消息内容为位置参数(恰好 1 个),支持 Markdown。`--title` 是消息标题,**群聊与单聊都必填**(API 强制要求;缺失时服务端返回误导性的 "发群服务窗会话消息失败",CLI 现在前置校验直接报错)。
--群聊时可选 --at-all @所有人,或 --at-users 指定成员(仅群聊时生效)。
--发送图片消息:指定 --media-id(通过 dt_media_upload 工具上传获得),自动设置 msgType=image,此时不需要传文本内容。
@@ -191,15 +191,15 @@ Flags:
Usage:
dws chat message send [flags] [<text>]
Example:
dws chat message send --group <openconversation_id> --text "hello"
dws chat message send --group <openconversation_id> --title "周报" --text "请提交本周日报"
dws chat message send --user <userId> --title "提醒" --text "请查收"
dws chat message send --open-dingtalk-id <openDingTalkId> --title "提醒" --text "请查收"
dws chat message send --group <openconversation_id> "hello"
dws chat message send --group <openconversation_id> --title "通知" "hello"
dws chat message send --group <openconversation_id> --title "周报提醒" --text "请大家本周五前提交周报"
dws chat message send --group <openconversation_id> --at-all "<@all> 请大家注意"
dws chat message send --group <openconversation_id> --at-users userId1,userId2 "<@userId1> <@userId2> 请查收"
dws chat message send --group <openconversation_id> --media-id <mediaId>
dws chat message send --open-dingtalk-id <openDingTalkId> --media-id <mediaId>
dws chat message send --group <openconversation_id> --title "通知" --at-all "<@all> 请大家注意"
dws chat message send --group <openconversation_id> --title "通知" --at-users userId1,userId2 "<@userId1> <@userId2> 请查收"
dws chat message send --group <openconversation_id> --title "图片" --media-id <mediaId>
dws chat message send --open-dingtalk-id <openDingTalkId> --title "图片" --media-id <mediaId>
Flags:
--text string 消息内容(推荐使用,也可用位置参数)
--group string 群聊 openconversation_id(群聊时必填)
@@ -219,6 +219,7 @@ Flags:
注意:
- --text 和位置参数二选一,--text 优先
- --title 必填(群聊与单聊都必填,API 强制要求)
- --group、--user、--open-dingtalk-id 三者互斥,只需指定其一:群聊用 --group,单聊用 --user 或 --open-dingtalk-id
- --group 的别名: --id, --chat, --conversation-id (均可替代 --group)
- --at-all / --at-users / --at-mobiles 仅在 --group 群聊时生效;当设置--at-all时,消息内容中一定要包含对应的占位符<@all>;当设置--at-users userId1,userId2时,消息内容中一定要包含对应格式的占位符<@userId1> <@userId2>
@@ -722,7 +723,7 @@ dws drive download --file-id <dentryUuid> --format json
# Step 5: 用 Markdown 图片语法发送
dws chat message send --group <openconversation_id> \
--text "![截图](下载链接)" --format json
--title "截图" --text "![截图](下载链接)" --format json
```
## 上下文传递表
+16 -5
View File
@@ -50,6 +50,8 @@ Usage:
Example:
dws doc info --node <DOC_ID>
dws doc info --node "https://alidocs.dingtalk.com/i/nodes/<DOC_UUID>"
dws doc info --node "https://alidocs.dingtalk.com/document/edit?dentryKey=<DENTRY_KEY>"
dws doc info --node "https://alidocs.dingtalk.com/document/preview?dentryKey=<DENTRY_KEY>"
Flags:
--node string 文档 ID 或 URL (必填)
```
@@ -61,6 +63,8 @@ Usage:
Example:
dws doc read --node <DOC_ID>
dws doc read --node "https://alidocs.dingtalk.com/i/nodes/<DOC_UUID>"
dws doc read --node "https://alidocs.dingtalk.com/document/edit?dentryKey=<DENTRY_KEY>"
dws doc read --node "https://alidocs.dingtalk.com/document/preview?dentryKey=<DENTRY_KEY>"
Flags:
--node string 文档 ID 或 URL (必填)
```
@@ -328,12 +332,14 @@ Flags:
|------|------|----------------|
| `alidocs.dingtalk.com/i/nodes/{id}` | `https://alidocs.dingtalk.com/i/nodes/9E05BDRVQePjzLkZt2p2vE7kV63zgkYA` | 取 URL 路径最后一段:`9E05BDRVQePjzLkZt2p2vE7kV63zgkYA` |
| `alidocs.dingtalk.com/i/nodes/{id}?queryParams` | `https://alidocs.dingtalk.com/i/nodes/abc123?doc_type=wiki_doc` | 忽略 query 参数,取路径最后一段:`abc123` |
| `alidocs.dingtalk.com/document/{edit\|preview}?...&dentryKey={key}` | `https://alidocs.dingtalk.com/document/edit?dentryKey=wo1g3x54FzVEJ5yE` | **不要提取 `dentryKey` 单独使用**,必须将完整 URL 原样传给 `--node` |
### 提取规则
1. 匹配 URL 中 `alidocs.dingtalk.com` 域名
2. 取 URL path 的最后一段作为 DOC_ID(去掉 query string 和 fragment)
3. 提取出的 DOC_ID 可直接用于所有 `--node` 参数,也可将完整 URL 传给 `--node`(CLI 会自动解析)
2. 路径为 `/i/nodes/{id}` 时,取 URL path 的最后一段作为 DOC_ID(去掉 query string 和 fragment)
3. 路径为 `/document/edit` 或 `/document/preview` 且 query 含 `dentryKey` 时,**禁止**提取 `dentryKey` 当 DOC_ID;将整段 URL 原样传给 `--node`,CLI 会自动解析(追踪参数如 `utm_source`、`chInfo` 也不必清理)
4. 提取出的 DOC_ID 可直接用于所有 `--node` 参数,也可将完整 URL 传给 `--node`(CLI 会自动解析)
### 处理流程
@@ -532,18 +538,23 @@ dws doc rename --node <DOC_ID> --name "项目周报 v2" --format json
| `file create` | `nodeId` | 后续 read / update / block 操作的 --node(仅 adoc 支持 read/update,axls/amind 等类型用各自产品的命令) |
| `copy` / `move` | 新 `nodeId`(copy)或原 nodeId(move) | 后续 read / info 等的 --node |
## nodeId 双格式说明
## nodeId 多格式说明
所有 `--node` 参数同时支持两种格式,系统自动识别:
所有 `--node` 参数同时支持以下格式,系统自动识别:
- **文档 ID**: 字母数字字符串,如 `9E05BDRVQePjzLkZt2p2vE7kV63zgkYA`
- **文档 URL**: `https://alidocs.dingtalk.com/i/nodes/{dentryUuid}`,如 `https://alidocs.dingtalk.com/i/nodes/9E05BDRVQePjzLkZt2p2vE7kV63zgkYA`
- **文档链接(edit/preview)**: `https://alidocs.dingtalk.com/document/{edit|preview}?...&dentryKey={key}`(必须传入完整 URL,不要提取其中的 query 参数单独使用)
两种方式等价,以下命令效果相同:
以下命令效果相同:
```bash
dws doc read --node 9E05BDRVQePjzLkZt2p2vE7kV63zgkYA
dws doc read --node "https://alidocs.dingtalk.com/i/nodes/9E05BDRVQePjzLkZt2p2vE7kV63zgkYA"
dws doc read --node "https://alidocs.dingtalk.com/document/edit?dentryKey=wo1g3x54FzVEJ5yE"
dws doc read --node "https://alidocs.dingtalk.com/document/preview?cid=74993670680&type=d&docKey=Pd6l2Z7V8ZWydl7M&dentryKey=rBGBr2r1HmwanAGW"
```
> **注意**:`document/edit` 和 `document/preview` 格式 URL 中的 `dentryKey` 参数值不是合法的独立 nodeId,禁止提取后单独使用,必须传入完整 URL。URL 中可能包含 `utm_source`、`chInfo` 等追踪参数,无需手动去除,直接传入完整 URL 即可。
`--folder` 参数同样支持文件夹 URL 或 ID。
## 注意事项
+127
View File
@@ -0,0 +1,127 @@
# URL 格式与处理规范
## alidocs URL 分流决策(必须首先执行)
收到 `alidocs.dingtalk.com` URL 时,**必须按以下顺序判断,禁止跳过**:
1. URL 路径含 `/i/p/` → **分享短链**,禁止调用 `dws doc` 任何子命令 → 按下方 [分享短链处理](#分享短链处理) 执行
2. URL 路径含 `/i/nodes/` → **节点链接**,需探测类型 → 按下方 [alidocs URL 类型探测流程](#alidocs-url-类型探测流程) 执行
3. URL 路径含 `/spreadsheetv2/` → **电子表格直链**,直接路由到 `sheet`,将完整 URL 原样传给 `--node` 参数
4. URL 路径含 `/document/edit` 或 `/document/preview` 且 query 参数包含 `dentryKey` → **文档链接**,直接路由到 `doc`,将完整 URL 原样传给 `--node` 参数(URL 中不一定有 `type=d`,只需匹配路径和 `dentryKey` 参数即可)
5. 其他 alidocs URL 格式 → 告知用户当前暂不支持该链接格式
---
## 已知 URL 格式
需要自行拼接链接时,只能使用以下模板:
| 产品 | 用途 | URL 格式 | ID 来源 |
|------|------|----------|---------|
| `aitable` | AI表格 Base 链接 | `https://alidocs.dingtalk.com/i/nodes/{baseId}` | `base list/search/create/get` 返回的 `baseId` |
| `aitable` | AI表格模板预览 | `https://docs.dingtalk.com/table/template/{templateId}` | `template search` 返回的 `templateId` |
| `doc` | 文档链接 | `https://alidocs.dingtalk.com/i/nodes/{dentryUuid}` | `doc` 命令返回的 `dentryUuid` |
| `sheet` | 电子表格链接 | `https://alidocs.dingtalk.com/i/nodes/{dentryUuid}` | `sheet create` 返回的 `dentryUuid` |
| `sheet` | 电子表格直链 | `https://alidocs.dingtalk.com/spreadsheetv2/{key}/...?dentryKey={key}&type=s` | 用户提供的完整 URL,直接传给 `--node` |
| `doc` | 文档链接(edit/preview) | `https://alidocs.dingtalk.com/document/{edit\|preview}?...&dentryKey={key}` | 用户提供的完整 URL,直接传给 `--node` |
| `minutes` | 听记链接 | `https://shanji.dingtalk.com/app/transcribes/{taskUuid}` | `list mine/shared` 返回的 `taskUuid` |
不在此表中的产品,禁止自行拼接 URL。命令返回中包含完整链接时直接使用,否则告知用户无法提供。
## 分享短链处理
`alidocs.dingtalk.com/i/p/{shortKey}` 是钉钉文档的**对外分享短链**,`dws doc` 命令无法解析此格式。
### 识别规则
URL 路径中包含 `/i/p/` 即为分享短链(无论后面是否还有子路径),例如:
- `https://alidocs.dingtalk.com/i/p/Y7kmbokZp3pgGLq2`
- `https://alidocs.dingtalk.com/i/p/Y7kmbokZp3pgGLq2/docs/AY39rGpMPmeVNpXZevZm8OZkXKnaoNQ7`
- `https://alidocs.dingtalk.com/i/p/AbCdEfGh1234`
- `https://alidocs.dingtalk.com/i/p/AbCdEfGh1234/sheets/XYZ789`
> **关键**:只要 URL 中出现 `/i/p/`,无论后面跟什么子路径(`/docs/...`、`/sheets/...` 等),都属于分享短链,一律禁止调用 `dws doc`。
### 处理方式
**不要调用 `dws doc` 任何子命令**(包括 `doc info`、`doc read` 等),`dws` 无法解析此格式。
- **需要获取文档内容时**:使用 `read_url` 工具直接读取该链接
- **其他操作(如移动、复制、权限管理等)**:告知用户此链接为分享短链,无法直接执行复制、移动、权限管理等操作。如需保存该文档内容,建议用户在钉钉客户端中打开该页面,手动复制文本内容,然后可通过 `dws doc create` 创建一篇新文档并将内容写入
```
# 需要读取文档内容时(无论 /i/p/ 后面有没有子路径,都用 read_url)
read_url("https://alidocs.dingtalk.com/i/p/Y7kmbokZp3pgGLq2")
read_url("https://alidocs.dingtalk.com/i/p/Y7kmbokZp3pgGLq2/docs/AY39rGpMPmeVNpXZevZm8OZkXKnaoNQ7")
# 禁止(以下全部会失败,dws 无法解析任何含 /i/p/ 的 URL)
dws doc info --node "https://alidocs.dingtalk.com/i/p/Y7kmbokZp3pgGLq2" --format json
dws doc read --node "https://alidocs.dingtalk.com/i/p/Y7kmbokZp3pgGLq2/docs/AY39rGpMPmeVNpXZevZm8OZkXKnaoNQ7" --format json
```
### 当 `read_url` 返回内容不完整时
钉钉文档分享页是动态渲染的,`read_url` 可能只能获取到页面标题等有限信息,无法获取文档正文。此时**禁止猜测原因**(如"权限不足""文档为空""文档已删除"等),**禁止建议用户"提供 `/i/nodes/` 格式链接"**(分享短链和节点链接是不同体系,普通用户无法自行转换)。应直接告知用户:
> 这个链接是钉钉文档的分享短链,由于页面是动态渲染的,我无法通过该链接直接获取文档的完整正文内容。
>
> 你可以:
> 1. 在钉钉客户端中打开该文档,将正文内容复制粘贴给我
> 2. 如果文档已保存在你的文档空间中,可以告诉我文档名称,我通过 `dws doc search` 搜索后再读取
---
## alidocs URL 类型探测流程
`alidocs.dingtalk.com/i/nodes/{id}` 是钉钉文档空间的统一 URL,可能指向**文档、电子表格、多维表、文件、文件夹**等不同类型。**禁止仅凭 URL 就假定为文档**,必须先探测类型再路由到正确的产品。
### 探测步骤
```
Step 1 → dws doc info --node "<URL>" --format json
Step 2 → 从返回中提取 contentType、extension、nodeType 字段
Step 3 → 按下方路由规则映射到对应产品
```
### 路由映射表
| 条件 | 路由到产品 | 后续操作 |
|------|-----------|---------|
| `contentType=ALIDOC`, `extension=adoc` | `doc` | 按 [doc.md](./products/doc.md) 操作 |
| `contentType=ALIDOC`, `extension=axls` | `sheet` | 按 [sheet.md](./products/sheet.md) 操作(仅 `axls` 在线电子表格) |
| `contentType=ALIDOC`, `extension=able` | `aitable` | 将 nodeId 作为 baseId,按 [aitable.md](./products/aitable.md) 操作 |
| `contentType=DOCUMENT`, `extension=xlsx` / `xls` / `xlsm` / `csv` | `doc` | 必须用 `dws doc download` 下载到本地处理,禁止走 `sheet`(非在线表格,sheet 命令无法操作) |
| `contentType≠ALIDOC`, `nodeType=file` | `doc` | 调用 `dws doc download` 下载,返回文件下载链接 |
| `nodeType=folder` | `doc` | 调用 `dws doc list --folder <ID>` 列出指定文件夹直接子节点列表 |
| 以上均不匹配 | — | 告知用户当前暂不支持该类型 |
> axls vs xlsx 关键区分:
> - `axls`(钉钉在线电子表格,`contentType=ALIDOC`)→ 走 `sheet` 产品线(读/写/筛选/导出等服务端原子操作)
> - `xlsx` / `xls` / `xlsm` / `csv`(上传到文档空间的本地表格文件,`contentType=DOCUMENT`)→ 必须走 `dws doc download` 下载到本地后再解析处理,严禁错误路由到 `sheet` 产品线(sheet 命令只支持在线表格,调用 xlsx 节点会直接报错)
> - 用户想把在线表格导出为 xlsx 文件 → 用 `dws sheet submit_export_job` 提交导出任务(输入是 `axls`,输出是 xlsx,这是 axls → xlsx 的格式转换,不属于 xlsx 读取场景)
### 示例
```bash
# 用户传入: https://alidocs.dingtalk.com/i/nodes/abc123
dws doc info --node "https://alidocs.dingtalk.com/i/nodes/abc123" --format json
# 返回 contentType=ALIDOC, extension=axls → 在线电子表格,路由到 sheet
dws sheet list --node "https://alidocs.dingtalk.com/i/nodes/abc123" --format json
# 返回 contentType≠ALIDOC, extension=xlsx/xls/csv → 本地表格文件,必须下载处理(禁止走 sheet)
dws doc download --node "https://alidocs.dingtalk.com/i/nodes/xlsx456"
# 返回 contentType≠ALIDOC, nodeType=file → 普通文件,下载
dws doc download --node "https://alidocs.dingtalk.com/i/nodes/def456"
# 返回 nodeType=folder → 文件夹,列出子节点
dws doc list --folder "https://alidocs.dingtalk.com/i/nodes/ghi789" --format json
```
### 何时可跳过探测
当用户指令中已明确指定产品(如"帮我读这个文档"、"看下这个表格的数据"),可结合用户意图**跳过探测**直接路由。仅在以下情况**必须执行探测**:
- 用户只粘贴 URL,无其他上下文
- 用户指令与 URL 实际类型可能不一致(如说"文档"但实际是表格)
- 用户直接粘贴的是原始 `alidocs` URL,且没有上游命令返回来确认类型