Compare commits

..
325 Commits
Author SHA1 Message Date
修雨 4c5f1faeb1 feat: align open CLI with dws-wukong via cedar discovery version code (#509)
Switches the discovery version code bamboo -> cedar and aligns the open edition CLI with dws-wukong across communication (calendar book/acl/attendee, minutes tag, mail folder/template/contact, chat file upload, todo add-attachment, attendance transforms) and structured-office (aitable advperm/view/section/workflow/record, sheet/drive/wiki/doc) domains. Includes output-envelope parity, parse_bool/attendance_class_check_time transforms, --calendar-id support, CHANGELOG 1.0.43 and README command-index refresh. cedar config validated on pre and prod endpoints.
2026-06-26 21:49:38 +08:00
修雨 5833e71751 ci(mirror): localize README for the Gitee mirror (#513)
The Gitee mirror force-pushes main verbatim, so Chinese users saw a
README whose top install commands point at raw.githubusercontent.com
(hard to reach in China) and a coverage badge that fails to render
(the relative .github/badges/coverage.svg can't be served by Gitee —
gitee raw returns a signed, expiring URL with content-type text/plain).

Add a Gitee-only post-process step: build a gitee-main branch on top of
origin/main and rewrite README.md / README_zh.md before pushing —
(1) raw.githubusercontent.com/<repo>/main -> gitee.com/<repo>/raw/main
(2) the coverage badge -> a shields.io static badge whose percentage is
read from the repo's coverage.svg and colored by threshold.

GitHub's README is untouched; only the Gitee copy is rewritten. The
branch is rebuilt from origin/main every run, so it stays a clean
single-commit delta and never drifts.
2026-06-26 16:55:04 +08:00
修雨 0e690fbe4e fix(install): define $LatestUrl in install.ps1 so version resolution works (#512)
Resolve-LatestVersion referenced $LatestUrl (lines 185/197) but the
variable was never defined, so on the default GitHub path both
Invoke-WebRequest calls failed with a null Uri. With
$ErrorActionPreference = "Stop" the script then hit Write-Err and
exit 1 — closing freshly-launched PowerShell windows instantly
(the reported "闪退"). Every user on the default `latest` path was
affected; the Bash installer was unaffected because it inlines the URL.

Define $LatestUrl = "https://github.com/$Repo/releases/latest", mirroring
the Bash installer. Verified end-to-end with pwsh 7.5: the script now
resolves the latest tag, downloads, checksum-verifies and installs.
2026-06-26 16:27:31 +08:00
Ariand修雨 f7e8106a72 docs(devapp): add image-upload recipe + "discovering commands" to dingtalk-dev skill (#508)
* docs(devapp): add image-upload recipe + "discovering commands" to dingtalk-dev skill

The dingtalk-dev skill could set an app/robot icon via --icon-media-id but
never documented where a mediaId comes from: the dev command set has no
upload command, so a mediaId must be fetched from DingTalk's OpenAPI. Agents
had to guess the flow. The per-resource refs also lacked a uniform pointer to
self-discover commands and params, so they leaned on memory instead of --help
/ schema.

recipes.md: new "上传图片拿 mediaId" recipe — credentials get -> gettoken ->
OpenAPI /media/upload (multipart field `media`, type=image) -> robot config /
app update --icon-media-id -> read back. Includes a curl example and notes the
token TTL (~7200s, rate-limited) and a square-icon hint.

references/*.md: append a Chinese "发现命令" block to each of the 10 product
refs (app, credentials, webapp, permission, member, security, robot, version,
event, connect). Each block shows that group's own `--help` plus
`dws schema dev.app.<group>.<method>` (connect uses `dws schema dev.connect`),
mirroring SKILL.md's MUST DO.

Verified end-to-end on a real app (unifiedAppId via dws dev): uploaded a PNG
through /media/upload, set the robot icon with the returned mediaId, and
`robot get` reflected the new iconMediaId with robotStatus=ONLINE. All 10
`--help` targets and the 9 `dws schema dev.app.*` paths + `dws schema
dev.connect` resolve.

* docs(changelog): note dingtalk-dev mediaId recipe + command discovery (#508)

---------

Co-authored-by: 修雨 <47820304+PeterGuy326@users.noreply.github.com>
2026-06-25 23:46:48 +08:00
修雨 87a9b5b9be chore: drop dead fork dev-app cruft (feat/dws-devapp) (#507)
Two leftovers referenced the decommissioned wxianfeng fork branch
`feat/dws-devapp`, both now obsolete after the dev-app work landed on main
(v1.0.42) and the installers were repointed to DingTalk-Real-AI (#505):

  - .github/workflows/auto-dev-release.yml — triggered only on push to
    feat/dws-devapp (a branch that does not exist on this repo, so it never
    fires). Its purpose — auto-publishing fork dev-preview releases for
    install-devapp.sh — is gone now that install-devapp.sh pulls stable
    releases from DingTalk-Real-AI.
  - docs/devapp-yulan-command-routing.md — a 2026-06-05 draft design doc
    pinned to the fork branch and the pre-rename `devapp` command tree,
    superseded by the shipped `dws dev` command set and the rewritten
    docs/devapp-agent-install-guide.md.

After this, the repo has zero `wxianfeng` / `feat/dws-devapp` references.
2026-06-25 21:49:10 +08:00
修雨 97678e6441 fix(devapp): drop the fork — repoint dev installer + docs to DingTalk-Real-AI (#505)
* fix(devapp): point dev installer at DingTalk-Real-AI, drop the fork

install-devapp.sh / .ps1 and the robot quickstart still pulled the dev
binary + dingtalk-dev skill from wxianfeng/dingtalk-workspace-cli's
feat/dws-devapp fork branch. The dev-app work has since landed on main and
shipped in stable v1.0.42 under DingTalk-Real-AI, so the fork dependency is
obsolete.

  - DEVAPP_REPO default: wxianfeng/... → DingTalk-Real-AI/...
  - Bootstrap URLs in headers + quickstart: fork feat/dws-devapp → main.
  - Drop "preview/prerelease" wording — releases are now stable; the
    newest-release resolution still works either way.
  - Quickstart China note now points at the standard install.sh Gitee
    mirror (which carries dws dev in v1.0.42); install-devapp.sh pulls its
    binary from github.com, so a gitee-raw script alone would not help China.

Verified: releases?per_page=1 on DingTalk-Real-AI resolves v1.0.42 and the
darwin/​skills assets are present.

Note: docs/devapp-agent-install-guide.md is separately stale (describes the
old source-build flow + the pre-rename `dws devapp` command) and needs its
own rewrite — left out of this change.

* docs(devapp): rewrite agent install guide for binary install + `dws dev`

The guide was stale on two axes:
  - It described the old source-build flow (clone the fork branch + go/make,
    env vars DEVAPP_REPO_URL / DEVAPP_BRANCH / DEVAPP_SOURCE_DIR), but
    install-devapp.sh now downloads a pre-built binary (curl + tar, no
    git/go/make) from DingTalk-Real-AI.
  - Every command used the pre-rename `dws devapp ...`; the command is now
    `dws dev app ...`.

Rewrite against the real `dws dev` tree (verified from the binary):
  - install: DingTalk-Real-AI binary installer + correct env (DEVAPP_REPO /
    DEVAPP_VERSION / DWS_INSTALL_DIR / DWS_NO_SKILLS) + a China Gitee note.
  - skill name corrected to `dingtalk-dev`.
  - commands: `dws dev app {list,get,create,update,enable,disable,delete,
    credentials,permission,member,robot,security,version,webapp,event}` with
    real flags (--confirm-name, --scope-values, --user-ids, --redirect-urls,
    --version-id/--confirmed-sensitive), async robot create via submit/result,
    version publish gated by check-approval.
2026-06-25 21:04:38 +08:00
修雨 67090ae09f docs: add China (Gitee) install for the standalone Skills installer (#504)
The China-mirror section documented the main install.sh and the npm
package, but not the standalone install-skills.sh — even though that
script already honours DWS_GITEE_REPO and auto-falls back to Gitee when
GitHub is unreachable. The Skills install section only showed the GitHub
URL, so China users (and docs curated from this README) had no China
entry point for skills.

Add a "Skills only (Gitee mirror)" item to both China-mirror sections and
a pointer next to the Skills install command, in README.md and README_zh.md.
2026-06-25 21:04:34 +08:00
修雨 6f042f9167 fix(release): Gitee mirror reads real attach ids + dedups duplicate assets (#502)
The verify-replace mirror listed attachments via /releases/{id}, whose
"assets" array omits the attach id. DELETE /attach_files/{id} was therefore
called with an empty id and silently no-op'd, so a stale asset was never
removed — instead a second (correct) copy was uploaded. Gitee then serves the
OLDER attachment by name, so the stale darwin binaries kept winning and failed
install.sh's checksums.txt verification on macOS (国内 install broken).

Fix:
  - List attachments via the dedicated /attach_files endpoint, which DOES
    return the numeric id needed for deletion.
  - Treat duplicates: collect every attach id carrying a given name; when >1,
    delete them all and upload exactly one fresh, correct file. count==1 still
    does the byte-identical skip / stale-replace; count==0 uploads new.

Self-heals the existing v1.0.42 darwin duplicates on the next mirror run.
2026-06-25 20:10:34 +08:00
meng93 78dd4aaa4b Merge pull request #501 from DingTalk-Real-AI/fix/gitee-mirror-verify-replace
fix(release): Gitee mirror verifies content + replaces stale assets
2026-06-25 17:07:23 +08:00
修雨 088a4d67ae fix(release): Gitee mirror verifies content and replaces stale assets
The v1.0.42 Gitee release served darwin-amd64/arm64 binaries that did NOT
match checksums.txt (the macOS binaries are ad-hoc signed and differed
between the GitHub release and the earlier mirror run), so install.sh's
checksum verification failed for China macOS users. The previous skip-if-name-
present logic could not repair this — it skipped the stale assets.

sync-to-gitee.sh now verifies by content: for each artifact it compares the
sha256 of the asset already on Gitee against the local file (downloaded from
the GitHub release), and

  • skips it when byte-identical,
  • deletes + re-uploads it when present but stale,
  • uploads it when missing,

bringing the Gitee release into byte-for-byte agreement with the GitHub
release that checksums.txt describes. Re-running the Sync-release-to-gitee
workflow now self-heals a mismatched mirror.

bash -n + sha256 helper validated locally.
2026-06-25 16:54:46 +08:00
修雨 81f5245c8a Merge pull request #499 from DingTalk-Real-AI/fix/gitee-release-sync-idempotent
fix(release): idempotent Gitee mirror + standalone repair workflow
2026-06-25 16:33:20 +08:00
修雨 c4946c3eaf fix(release): make Gitee mirror idempotent + add standalone repair workflow
The v1.0.42 Release job hit timeout-minutes: 30 mid-upload while mirroring
release assets to Gitee, so the Gitee release ended up missing
dws-windows-arm64.zip and checksums.txt. Root cause + fixes:

- sync-to-gitee.sh now skips assets already attached to the Gitee release,
  so a re-run only uploads what is missing (instead of re-uploading every
  artifact and creating duplicates). It no longer fails when everything is
  already present.
- New workflow sync-release-to-gitee.yml (workflow_dispatch, version input)
  mirrors a published GitHub release's assets to Gitee on its own — it
  downloads the assets from the GitHub release and runs the idempotent sync,
  without running GoReleaser or touching the GitHub release (no outage). Use
  it to repair an incomplete Gitee mirror.
- Bump the Release job timeout 30 -> 60 so a full Gitee upload has room.

bash -n + YAML validated.
2026-06-25 16:21:34 +08:00
修雨 a0b956a780 Merge pull request #496 from wxianfeng/feat/dws-devapp
feat(devapp+connect): dev app management, robot connect, opencode server sessions
2026-06-25 15:19:39 +08:00
修雨 5e4d974039 Merge pull request #23 from wxianfeng/release/changelog-1.0.42
docs(changelog): cut 1.0.42
2026-06-25 14:47:24 +08:00
修雨 bb641c2098 docs(changelog): cut 1.0.42
Promote the [Unreleased] section to 1.0.42 (2026-06-25) ahead of封包:
robot connect custom channel, /new vs /clear session commands, and the
opencode 30s timeout fix. A fresh empty [Unreleased] stays on top.
2026-06-25 14:39:20 +08:00
修雨 7e1e93478b Merge pull request #22 from wxianfeng/docs/readme-connect-section
docs(readme): add DingTalk bot connect section with /new /clear
2026-06-25 14:33:06 +08:00
修雨 101e7be98d docs(readme): add a DingTalk bot connect section with /new /clear
README.md / README_zh.md had no connect coverage at all. Add a short
"connect a robot to your local AI" section above Key Services: the one-line
`dws dev connect` usage, the in-chat /new vs /clear session commands (with
the per-channel real-session-op behaviour, opencode DELETE /session), and a
pointer to docs/robot-quickstart.md. Docs only.
2026-06-25 14:21:32 +08:00
修雨 9545c1dde5 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	.github/badges/coverage.svg
2026-06-25 14:12:58 +08:00
修雨 81367b2861 Merge pull request #21 from wxianfeng/docs/changelog-connect-fixes
docs(connect): changelog + quickstart for /new /clear and the 30s timeout fix
2026-06-25 14:03:31 +08:00
修雨 97bab33c71 Merge pull request #494 from shangguanxuan633-lab/codex/dws-auth-login-recommend
feat(tui): apply DingTalk auth console styling
2026-06-25 14:02:21 +08:00
修雨 ef6d65087f docs(connect): changelog + quickstart for /new /clear and the 30s timeout fix
Document this release's two connect changes that landed via #19 and #20:
- CHANGELOG [Unreleased]: Added entry for /new vs /clear using each
  channel's real session op (opencode DELETE /session); Fixed entry for
  the opencode 30s client-timeout that aborted long agent turns.
- robot-quickstart.md: a 会话指令 section explaining /new (open fresh,
  keep old) vs /clear (real per-channel wipe; opencode deletes the
  server session).

Docs only; no code change.
2026-06-25 13:59:41 +08:00
shangguanxuan.sgx 30a024e615 fix(auth): keep chmod batch grants gated 2026-06-25 12:16:31 +08:00
shangguanxuan.sgx 00e5ce7367 fix(auth): skip recommend tui when no scopes remain 2026-06-25 11:23:08 +08:00
shangguanxuan.sgx 760c40dd71 Merge upstream main 2026-06-25 11:10:25 +08:00
修雨 aaa2d7d3be Merge pull request #20 from wxianfeng/feat/connect-session-commands
feat(connect): /new vs /clear use each channel's real session op
2026-06-25 11:01:11 +08:00
修雨 fbfcd69c2b feat(connect): make /new vs /clear use each channel's real session op
Before, /new and /clear were identical: both just dropped the local
conversationId->sessionId mapping. The agent-side session was never
disposed (opencode sessions leaked), and the two commands had no real
difference beyond their ack text.

Align them to each channel's real capability:
- /new (resetSession): drop the local mapping only; the old agent session
  is left intact and stays resumable where the agent supports it.
- /clear (new sessionClearer): actively dispose the current session via the
  agent's real delete primitive. opencode implements it with
  DELETE /session/:id (idempotent on 404). Channels whose agent exposes no
  delete in the mode DWS drives it (Codex app-server, Qoder stream, Claude
  exec) fall back to resetSession, so /clear behaves like /new there.

Tests pin both directions: /clear issues exactly one DELETE and drops the
mapping; /new (resetSession) issues zero DELETEs so the old session stays
resumable. Doc updated to describe the per-channel behavior.

go build ./... ok; go vet ok; go test ./internal/helpers ok.
2026-06-25 10:43:21 +08:00
修雨 fab9e5be52 Merge remote-tracking branch 'upstream/main' into feat/dws-devapp
# Conflicts:
#	CHANGELOG.md
2026-06-24 22:32:25 +08:00
修雨 ad056a8d83 fix(config): revert DefaultMCPBaseURL to production (mcp.dingtalk.com)
The fork's dev branch had the pre-release URL (pre-mcp.dingtalk.com)
hardcoded as the default MCP base, which would leak prepub config into
any release build. Revert to the upstream production default.

🤖 Generated with [Qoder][https://qoder.com]
2026-06-24 22:31:09 +08:00
修雨 0de6e46ef4 docs: cut 1.0.41 changelog + backfill 1.0.40 #488 (#495)
- 1.0.41: install auto-fallback to Gitee (#492) + CI auto-push mirror (#493)
- 1.0.40: add the missing #488 (skills embedded in binary) entry
2026-06-24 22:26:54 +08:00
修雨 9a8157a4cd ci(mirror): auto-push code to Gitee via HTTPS token (no SSH key) (#493)
Rewrite mirror-to-gitee.yml to push main + tags to the Gitee mirror using
HTTPS + GITEE_TOKEN (reusing the existing secret) instead of hub-mirror-action
+ an SSH key. Gated on GITEE_TOKEN; needs GITEE_USER + GITEE_REPO secrets.
Keeps Gitee code/raw in sync automatically on every push to main + tags, so
no more manual git push after each release.
2026-06-24 22:26:47 +08:00
修雨 b8e915edfb feat(install): auto-fallback to Gitee when GitHub unreachable (#492)
Probe GitHub Releases on startup; if it is unreachable (typical in mainland
China), automatically switch to the Gitee mirror — so a plain
`curl … | sh` (or .ps1 / install-skills.sh) works everywhere with no
DWS_GITEE_REPO env var. Explicit DWS_GITEE_REPO still wins; DWS_NO_FALLBACK=1
disables the probe; local source-checkout installs skip it.
2026-06-24 22:26:40 +08:00
xianfeng wang 5e254b4745 Merge pull request #17 from wxianfeng/sync/upstream-main-2026-06-24
sync: merge upstream/main into feat/dws-devapp (1.0.35–1.0.40)
2026-06-24 22:19:42 +08:00
修雨 29a8a14760 Merge pull request #19 from wxianfeng/fix/opencode-message-timeout
fix(connect): opencode message turns use per-turn ctx, not a 30s client cap
2026-06-24 21:54:20 +08:00
shangguanxuan.sgx 00bef0a809 fix(auth): skip login scope tui when grants are complete 2026-06-24 21:53:18 +08:00
修雨 3f5b2fa8d3 fix(connect): let opencode message turns use the per-turn ctx, not a 30s client cap
The shared opencode http.Client had a hardcoded 30s Timeout used for every
request including POST /session/{id}/message. Long agent turns (e.g. a web
research report) take longer than 30s, so the client aborted mid-flight with
"context deadline exceeded (Client.Timeout exceeded while awaiting headers)",
even though the per-turn budget (DWS_AGENT_TIMEOUT_MS, default 300s) was far
larger. Retrying hit the same wall.

Drop the client-level deadline (rely on the per-request ctx that doJSON already
wires via http.NewRequestWithContext) and bound only the /global/health probe
with a short 10s timeout so startup detection stays snappy.

Tests: pin Timeout==0 on the default client, and assert a slow reply succeeds
within the turn budget but is cut when the turn ctx is shorter than the reply.
2026-06-24 21:39:40 +08:00
shangguanxuan.sgx b0e7b58e95 feat(tui): apply DingTalk auth console styling 2026-06-24 21:32:49 +08:00
修雨 fe46cd4dc2 Merge pull request #18 from wxianfeng/codex/qoder-stream-sessions
[codex] keep Qoder sessions on stream-json
2026-06-24 20:57:47 +08:00
quanming c993086d9d feat(connect): keep qoder sessions on stream-json 2026-06-24 20:36:26 +08:00
修雨 f522a9c2c2 Merge upstream/main into feat/dws-devapp
Sync with DingTalk-Real-AI/main (1.0.35–1.0.40):
- 1.0.35–1.0.39: chat @-mentions, sheet export, doc strip unsafe chars,
  PAT batch grants, devdoc RAG, agent_code detection, AI-tag opt-in
- 1.0.40 (#486): China mirror via Gitee + npmmirror
- (#488) embed skills/ into binary
- (#464) strip duplicate H1 on JSONML doc-create

# Conflicts:
#	.github/workflows/release.yml
#	CHANGELOG.md
#	README.md
#	README_zh.md
#	docs/command-index.md
#	internal/app/runner.go
#	internal/app/runner_test.go
#	internal/auth/channel.go
#	internal/helpers/devdoc.go
#	internal/helpers/devdoc_test.go
#	internal/pat/chmod.go
#	internal/pat/chmod_test.go
#	internal/pat/pat.go
#	internal/transport/client.go
#	scripts/install-skills.sh
#	scripts/install.ps1
#	scripts/install.sh
#	skills/mono/references/products/devdoc.md
#	skills/mono/references/products/simple.md
#	skills/multi/dingtalk-devdoc/references/devdoc.md
#	skills/multi/dingtalk-skill/references/skill.md
#	test/cli_compat/devdoc_test.go
#	test/cli_compat/helpers_test.go
#	test/skill_tests.md
#	test/skill_tests_results.md
#	test/unit/pat_host_owned_signal_test.go
2026-06-24 20:15:53 +08:00
修雨 bd370ed0e9 fix(doc): strip duplicate title H1 on the JSONML doc-create path (#464)
PR #448 stripped a leading H1 matching --name on the markdown path of
`dws doc create`, but the JSONML path (--content-format jsonml) was never
covered. Rich documents — tables, callouts, styled blocks — go through
create_document + update_document(jsonml=...), which writes the body
verbatim, so a leading h1 whose text equals the document name renders the
title twice (the "two headings" effect the doc platform shows because it
already renders --name as the page title).

Add stripLeadingDuplicateTitleJSONML: parse the marshaled JSONML body,
skip an optional ["root", {}, ...] wrapper, and drop the first node when
it is an h1 whose concatenated leaf text equals --name (trimmed,
case-insensitive). Any parse failure or non-match leaves the body
untouched, so a valid write is never blocked. A stderr note mirrors the
markdown path so agents learn the convention.
2026-06-24 18:34:16 +08:00
修雨 9fa76f8598 docs: cut 1.0.40 changelog + fix gitee mirror gate (#489)
- CHANGELOG: 1.0.40 (China mirror via Gitee + npmmirror, #486)
- mirror-to-gitee.yml: gate on GITEE_PRIVATE_KEY so it skips cleanly when the
  SSH key is unset (code mirror handled by Gitee-side pull-mirror) instead of
  failing the run.
2026-06-24 17:55:35 +08:00
修雨 b175acb48f feat(skill): embed skills/ into the binary, default skill setup to it (#488)
go:embed the skills/ tree (mono + multi) into the binary and make
`dws skill setup` install from the embedded bundle by default. Upgrading
the binary now refreshes the installed skill, instead of silently reusing
a stale copy probed from the current working directory. An explicit
--source / DWS_SKILL_SOURCE still overrides for development.

Replants the change from #441 onto main: #441 was stacked on the
abandoned feat/chat-bot-provisioning-openclaw base (PRs #407/#397 closed),
which is why its CI was red. The embedded-bundle test asserted a
connect.md doc that only existed on that dead base; retargeted it to a
reference doc that exists on main.
2026-06-24 17:55:23 +08:00
wxianfeng d89649f9bb event search first 2026-06-24 17:53:08 +08:00
Aemeathandquanming f218a05ead [codex] use opencode server sessions for OpenCode connect
Co-authored-by: quanming <quanming@code.alibaba-inc.com>
2026-06-24 17:18:58 +08:00
修雨 ed1cbd6f06 feat(install): China mirror via Gitee + npmmirror (#486)
国内安装加速:DWS_GITEE_REPO 开关从 Gitee 解析下载脚本/二进制/skill(默认仍 GitHub,向后兼容);release.yml 发版后 CI 自动镜像 release 附件到 Gitee;README 加国内安装说明。Approved-by: wxianfeng.
2026-06-24 17:14:40 +08:00
修雨 62aef1cc96 Merge pull request #15 from wxianfeng/codex/connect-appserver-qoder-memory
[codex] align connect memory for Codex and Qoder
2026-06-24 15:16:39 +08:00
quanming fc5e4d0d8d fix(connect): align codex and qoder sessions 2026-06-24 15:09:50 +08:00
xianfeng wang 34248fabf3 Merge pull request #14 from PeterGuy326/feat/connect-channel-memory
feat(connect): slash commands + all-channel session memory + interactive onboarding
2026-06-24 13:43:25 +08:00
修雨 430d20f2ee ci(release): auto-sync release artifacts to China OSS mirror
Add scripts/release/sync-to-oss.sh and wire it into release.yml. After
the GitHub release, artifacts (binaries, checksums, dws-skills.zip) plus
the install scripts are pushed to an OSS bucket in the
<base>/<version>/<file> layout the install.sh DWS_RELEASE_BASE switch
expects, with a latest.txt pointer.

Gated on OSS_* repo secrets: skips cleanly when unset, so forks without
the secrets keep releasing to GitHub only.
2026-06-24 11:43:06 +08:00
修雨 ada4acc395 feat(connect): interactive onboarding to provision or pick a robot app
When `dev connect` runs with no credentials (no --robot-client-id/secret, no
--unified-app-id) in a real terminal, it now guides the user instead of failing:

- Ask "new app or existing app?".
- Existing: read a unified-app-id (reuses the credentials-get path) or an
  explicit clientId/clientSecret pair.
- New: read the app name, robot display name and description, submit the async
  robot-create task, then poll for the result to obtain credentials. This has a
  real side effect (it provisions a real robot app).

connect_onboarding.go keeps the flow channel-agnostic and io-injected so the
whole decision tree is unit-tested with a mock runner and scripted stdin (no
network, no real provisioning). Non-interactive invocations — scripts, daemons,
pipes, and --dry-run — are unchanged: they still require an explicit credential
flag, so nothing that worked before starts prompting.

Tests cover: existing/unified, existing/raw-creds, new-app submit+poll (asserts
the submit_robot_create_task / query_robot_create_result calls and params),
invalid choice, and a missing required field (no side-effecting call).

Note: the real provisioning path shares the same unverified credential field
names as devAppFetchCredentials (clientId/appKey, clientSecret/appSecret — see
its TODO(verify)); the live create→credentials flow is to be verified on the
pre-prod gateway with the -dws-devapp prerelease before relying on it.
2026-06-24 11:41:49 +08:00
修雨 8bebd77dfa feat(install): add DWS_RELEASE_BASE/DWS_LATEST_URL mirror switch for China
Parameterize the hardcoded GitHub Releases domain in install.sh,
install.ps1 and install-skills.sh so domestic users can point asset
downloads (binary tarball, checksums, skills zip) and latest-version
resolution at a China-accessible mirror (e.g. OSS+CDN / dingtalk domain).
Defaults stay on GitHub — fully backward compatible.
2026-06-24 11:30:12 +08:00
修雨 b096fa06db feat(connect): give opencode per-conversation memory via captured sessions
opencode persists its own sessions but, unlike the Claude family, will not let
the caller mint the session id up front: `opencode run` creates a session on the
first turn and only reports its id in the `--format json` event stream, then
continues it with `--session <id>`. So the connector now CAPTURES the id from
the output (like codex's thread id) instead of minting a UUID:

- connect_opencode.go: a dedicated opencodeForwarder that runs
  `opencode run --pure --format json`, accumulates reply text from `text`
  events, captures the top-level sessionID, and on the first turn persists the
  convID->sessionID map to <config>/connect/<clientId>/opencode-sessions.json
  (best-effort, restored on startup). The next message — and a connector
  restart — replays it with `--session <id>`. Implements streamingForwarder and
  sessionResetter, so /new and /clear work and streaming cards stream.
- forwarderForChannel routes the opencode channel to it.
- connectAgentOptionsPayload reports opencode memory as
  "per-conversation-captured"; --agent-memory help now lists codex/opencode too.

Verified end to end against the real opencode CLI: turn 1 captures the session
id, turn 2 with --session recalls a fact from turn 1. Unit tests cover capture +
resume (stub bin), store persistence across restart, and reset.

gemini also exposes --session-id/--resume but could not be verified end to end
here (no GEMINI_API_KEY) and its --resume id semantics are unconfirmed, so it is
left for a follow-up rather than wired blind. qoder's qodercli still has only
--resume (no addressable id) and cannot do per-conversation memory.
2026-06-24 10:57:25 +08:00
修雨 107f3eaf6e feat(connect): add /new /clear slash commands and persist codex session context
Two connector improvements for the linked-bot chat experience, modelled on
codex / OpenClaw connect:

1. Built-in slash commands. A user can type /new (aliases /start, /reset) to
   open a fresh session or /clear to wipe the current one, instead of the
   message being forwarded to the agent. The command set is fixed (never
   dynamically extended) so behaviour stays predictable. Matching requires the
   whole message to be the bare command, so a normal question that merely starts
   with a slash is forwarded untouched. Costs no agent turn / tokens.

   - connect_command.go: channel-agnostic parser + action table (+ tests).
   - sessionResetter optional interface; execForwarder (Claude family) and the
     codex app-server forwarder both implement it. The main loop intercepts a
     command right after the owner-decision interceptor and acks via webhook.

2. Persist codex per-conversation context. codexThreadSessions previously kept
   the convID->threadID map in memory only, so a codex connector restart lost
   every conversation's context — unlike the Claude-family convSessions store
   which already persisted. The thread identity is now the authoritative,
   mutex-guarded map persisted to <config>/connect/<clientId>/codex-threads.json
   (best-effort, atomic write), restored on startup. An empty clientId keeps it
   in memory only, preserving the original behaviour. This also removes a data
   race on threadID by moving it off the per-conversation state into the
   sessions store.
2026-06-24 10:30:04 +08:00
shangguanxuan.sgx df0c0f7545 revert(auth): restore pat authorization link output 2026-06-24 10:26:05 +08:00
qinzeandClaude Opus 4.8 91e67e2e45 docs(dev): event.md 事件码改用 event list 查询
去掉"以开放平台文档为准/dev doc search",改成"可订阅事件码通过 event list 查询
(返回 events[] 列出 eventCode/eventName/subscribed)"——event list 本就列出所有可订阅事件,更准。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 09:58:40 +08:00
shangguanxuan.sgx 75468dca1e fix(auth): hide raw pat url after browser open 2026-06-24 09:41:03 +08:00
shangguanxuan.sgx ef5c05a2e6 fix(auth): avoid duplicate pat authorization link output 2026-06-24 00:04:32 +08:00
shangguanxuan.sgx 1ac8636418 fix(auth): restore login authorization selectors 2026-06-23 23:09:11 +08:00
shangguanxuan.sgx 86086437d8 fix(auth): default login to recommended cli authorization 2026-06-23 21:57:17 +08:00
wxianfeng d432029d84 Merge branch 'feat/dws-devapp' of github.com:wxianfeng/dingtalk-workspace-cli into feat/dws-devapp 2026-06-23 19:45:19 +08:00
wxianfeng 029bfdd2ed version publish approval 2026-06-23 19:44:36 +08:00
修雨 8c0551f359 fix(install-devapp): handle GitHub API rate limit when resolving version
Unauthenticated curl is limited to 60 req/h, and once exhausted the API
returns 403. The previous `curl -fsSL ... | grep tag_name` swallowed the
403 silently, leaving DEVAPP_VERSION empty and surfacing a misleading
"No release found" error even though the fork has plenty of releases.

- Prefer `gh api` when available (authenticated, 5 000 req/h).
- Fall back to curl while capturing the HTTP status; on 403/429 fail
  with an actionable message instead of pretending no release exists.
2026-06-23 16:55:25 +08:00
xianfeng wang b839ee664e Merge pull request #12 from wxianfeng/fix/opencode-connect-pure
fix(connect): run opencode with --pure to neutralise operator plugins
2026-06-23 15:43:57 +08:00
修雨 c16c4aa59a fix(connect): run opencode with --pure to neutralise operator plugins
The opencode channel forwarded to `opencode run` without isolating the
operator's interactive environment. claudecode already neutralises via
`--setting-sources project --strict-mcp-config`; opencode had no equivalent.

When the operator runs a plugin suite that swaps the global default agent at
runtime (e.g. OhMyOpenCode's rotating Greek-codename agents), headless
`opencode run` crashes resolving a default agent that no longer exists
("default agent ... not found"), and the crash trace is sent back to DingTalk
as the bot reply. Verified by reproducing in a clean /tmp dir: plain
`opencode run` crashes, `opencode run --pure` replies normally.

Add --pure to the opencode argvTail so the bot answers in a clean,
plugin-free environment, consistent with the claudecode channel.
2026-06-23 15:07:19 +08:00
修雨 aecc0bc588 Merge pull request #11 from PeterGuy326/fix/mono-skill-dev-routing
fix(skill/mono): add dev product routing, prevent robot-creation mis-routing to chat
2026-06-23 14:06:18 +08:00
wxianfeng cfad3bbf4a name 2026-06-23 13:57:21 +08:00
修雨 40736e2ae1 fix(skill/mono): add dev product routing to prevent robot-creation mis-routing to chat
Without a dev entry in the product table and intent tree, agents reading the
mono skill routed 'create robot' / 'connect' requests to dws chat (because
'机器人' appeared in the chat product description), then landed on
dws chat bot search — wrong path.

Changes:
- skills/mono/SKILL.md: add dev row to product table; annotate chat row to
  scope it to IM-only; add dev intent-tree rule covering 创建机器人/建联/
  接入 agent/opencode/…; prepend dev-vs-chat disambiguation rule
- skills/mono/references/products/dev.md: new file — full command reference
  for dws dev app (lifecycle/robot build-号/credentials/permission/event/
  version) and dws dev connect (建联 flags, channel list, dry-run cli check,
  codex gotcha), sourced from dingtalk-dev multi-skill references
2026-06-23 13:53:53 +08:00
xianfeng wang 9aeb60da37 Merge pull request #10 from PeterGuy326/release/dws-devapp
feat(connect+devapp): 数字分身建联整套(已合 dev 重构)
2026-06-23 11:00:00 +08:00
修雨 d3fcd814f3 docs(quickstart): 安装改用勤泽的一键脚本;移除对 wxianfeng 无效的 release step
- quickstart 第一步从手动 curl 直链改为引用 scripts/install-devapp.sh /
  install-devapp.ps1。直链走 /releases/latest 在 wxianfeng 会 404(它只发
  -dev 预览版,无非 prerelease release);一键脚本走 GitHub API 取最新预览版,
  现在即可装到 v2.0.0.dev,且和团队安装入口统一
- 移除我此前加的 'Mark dws-devapp release as latest' step:其触发条件
  contains('-dws-devapp') 在 wxianfeng 永不成立(这边发 -dev tag),是死代码;
  改用一键脚本后也不再依赖 /releases/latest。release.yml 现与 base 完全一致
2026-06-23 10:45:15 +08:00
修雨 5ed69744cc Merge wxianfeng/feat/dws-devapp into release/dws-devapp
解决 devapp→dev 重构与 connect/数字分身工作的合并冲突,方向:全面对齐
wxianfeng 的 dev 命名空间,保留我方两处实质内容(动态端点 + connect 功能)。

冲突解决要点:
- release.yml:取 wxianfeng 更干净的 npm 守卫(repository_owner + 注释);
  保留我新增的「-dws-devapp 翻成非 prerelease+latest」步骤
- devapp.go / devapp_test.go / 路由文档:取 wxianfeng(新 MCP 工具名
  *_dev_app_*/extension、新增 event 工具、删 robot create、config 合 upsert)
- 端点:保留我方动态 devappMCPEndpoint()(网关 base 推导、生产默认),
  否则会把「建号对所有人打预发」的 bug 倒灌回来;同步修 helper_tool_fetcher.go
  与 direct_runtime_test.go 改用该函数 + wxianfeng 工具名 list_dev_app
- devapp_connect.go:connect 命令对齐 dev connect 命名,保留我方 --agent-cmd
  自研渠道示例(#37),建号引用修正为真实存在的 robot submit
- skills:跟随 wxianfeng 删除旧 dingtalk-devapp(已被重写的 dingtalk-dev 覆盖)
- robot-quickstart.md:命令全改 dws dev(建号两步 submit+result、dev connect),
  下载源改 wxianfeng,去掉写死版本号用 releases/latest

验证:go build ./... 通过;go vet 干净;internal/app、internal/helpers 单测全过
2026-06-23 10:21:29 +08:00
修雨 e5c9c91342 fix(release+docs): 让 -dws-devapp 可被'装最新',文档去掉写死版本号
问题:-dws-devapp 全系列被 goreleaser 标成 prerelease(semver 后缀触发),
GitHub 的 /releases/latest 跳过 prerelease,导致:
- 文档写死的 v1.0.53 每发一版就过期(现已落后到 v1.0.60)
- releases/latest/download 与 install.sh 的 latest 解析对 devapp 全失效

修复:
- release.yml 新增一步,仅当 tag 含 -dws-devapp 时把该 release 翻成
  非 prerelease 并标记 latest;goreleaser 仍保持 prerelease: auto,
  不影响 -dev.x 等其他预发版的语义
- robot-quickstart.md 三处下载/链接改用 releases/latest,去掉写死版本号,
  提示语软化为'能打印版本即成功'
2026-06-23 09:53:29 +08:00
qinzeandClaude Opus 4.8 0e59fedbbb ci: dev 分支 push 自动出预览 release(测试通过才发)
- 新增 auto-dev-release.yml: push feat/dws-devapp → 跑 build+test →
  通过则自增 dev 版本号、打 tag、自包含发 release(不靠 tag 触发 release.yml,
  绕开 GITHUB_TOKEN 不触发的限制); 不含 npm 步骤天然绿; concurrency 串行防撞号
- release.yml: npm publish 加 owner 条件, fork 跳过避免红叉

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 09:36:42 +08:00
修雨 c39378864d fix(release): goreleaser owner 用 GITHUB_REPOSITORY_OWNER 而非写死 fork
对齐 wxianfeng/feat/dws-devapp 已有写法:官方 CI 发到官方、fork CI 发到
fork,两边都对,避免合并时把动态 owner 顶回写死 PeterGuy326。
2026-06-23 09:32:52 +08:00
qinze 7cb33e970c Merge branch 'feat/dws-devapp' of https://github.com/wxianfeng/dingtalk-workspace-cli into feat/dws-devapp
# Conflicts:
#	skills/multi/dingtalk-dev/references/event.md
2026-06-23 09:19:27 +08:00
qinzeandClaude Opus 4.8 567cf163f1 docs(dev): event.md 澄清 connect/event 在 Stream 上的差异 + Stream 建立指向官方文档
- 加「connect 与事件订阅的关系」: connect 收机器人消息、event 只是配置订阅,
  dws 当前不消费事件; 两者唯一关联是先 connect 让长连在线 subscribe 才成功
- 「Stream 长连怎么建」改为命令视角 + 指向官方 SDK 文档(事件 RegisterAllEventHandler
  vs 机器人 RegisterChatBotCallbackRouter 别混), 不固化易过时的 SDK 代码

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 09:18:37 +08:00
wxianfeng d9ae15f9a6 Merge branch 'feat/dws-devapp' of github.com:wxianfeng/dingtalk-workspace-cli into feat/dws-devapp 2026-06-22 20:46:12 +08:00
wxianfeng 922745f318 event search 2026-06-22 20:45:14 +08:00
qinzeandClaude Opus 4.8 58dced0c8a feat(install): dev 安装支持 Windows(sh 加 Windows 分支 + 新增 ps1)
- install-devapp.sh: detect_os 加 MINGW/MSYS/CYGWIN, 按平台选 .zip/.tar.gz
  和 dws/dws.exe, 覆盖 mac/linux + Git Bash/WSL 下的 Windows
- 新增 install-devapp.ps1: 原生 Windows 用 irm|iex 一键装, 自包含下
  dev release 的 dws.exe + dingtalk-dev skill(含 opencode 目录)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:54:49 +08:00
qinzeandClaude Opus 4.8 3427b65da6 feat(install): install-devapp.sh skill 目录增加 opencode
opencode 全局 skill 目录是 ~/.config/opencode/skills(在 .config 下,
与其它 agent 的 ~/.xxx 不同),加入安装列表; gate 检查 ~/.config/opencode 存在才装。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:46:40 +08:00
qinzeandClaude Opus 4.8 9d38a3be54 fix(release): goreleaser owner 用 GITHUB_REPOSITORY_OWNER
写死 DingTalk-Real-AI 导致 fork CI 想往官方仓库发 release 被 403 拒绝。
改用 CI 自带的 GITHUB_REPOSITORY_OWNER, fork CI 发到 fork、官方 CI 发到官方。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:31:24 +08:00
qinzeandClaude Opus 4.8 1cda263e0e feat(install): install-devapp.sh 改为自包含下二进制安装(cli+skill)
- 从 fork 的 dev release 下预编译二进制 + dws-skills.zip, 只需 curl+tar,
  不再 clone 源码编译(去掉 go/make/git 依赖)
- 装 dingtalk-dev skill(不改名), 命令名对齐 dws dev
- 版本默认取 fork 最新 release(含 prerelease)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:24:56 +08:00
qinzeandClaude Opus 4.8 5d5884a0d7 fix(dev): 校准 dingtalk-dev skill 与真机一致 + 清理重复安装脚本
- skill 订正(以真机/schema 为准): app appStatus 字符串/permission 状态字段与
  apiPreview/credentials 去掉不存在的 showSecret/webapp 结构化空态/connect 去过时
  警告并补 flag/robot 去掉错误的 success 字段; version 用远端结构化审批字段
- 删除重复的 install-dev.sh, 保留 install-devapp.sh 并去掉会误拦用户的 go/make 检查

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:07:14 +08:00
玉澜 4a26f1ebd2 Merge remote-tracking branch 'origin/feat/dws-devapp' into feat/dws-devapp 2026-06-22 17:06:47 +08:00
玉澜 b65be61599 fix: limit devapp installer skills 2026-06-22 16:18:58 +08:00
玉澜 e193ba97f4 feat: add devapp install script 2026-06-22 16:08:51 +08:00
wxianfeng 787a40ffcb fix cr problem 2026-06-18 22:54:24 +08:00
quanming f69d9ed281 fix: align devapp member user ids 2026-06-18 19:37:17 +08:00
wxianfeng f2b2de89f4 fix cr problem 2026-06-18 18:34:12 +08:00
shangguanxuan.sgx 7915a5a4e1 docs: refresh batch auth release evidence 2026-06-18 17:18:46 +08:00
修雨 91f44a1efd docs: cut 1.0.39 changelog (#475 wukong-leak fix + #477 ai-tag opt-in) (#478) 2026-06-18 14:10:07 +08:00
shangguanxuan.sgx 6067906c55 fix(devdoc): fallback empty rag article search 2026-06-18 13:08:34 +08:00
shangguanxuan.sgx 493ca36e08 fix(pat): carry agentCode in batch auth args 2026-06-18 13:08:15 +08:00
修雨 1a7ba01e36 feat(chat): make AI-sent badge opt-in via --ai-tag (default off) (#477)
Previously every user-identity send/reply attached clawType=edition.ClawType()
unconditionally, so the IM server rendered an AI-sent badge ("通过AI发送" on the
open edition) under every message — surprising users by branding all their sends.

Make it opt-in: by default no clawType is attached (no badge). Passing --ai-tag
on 'chat message send' / 'chat message reply' attaches edition.ClawType() so the
badge shows (open=openClaw -> 通过AI发送, wukong overlay -> 悟空AI发送). Bot and
webhook sends remain untouched.

Follow-up to #475 (which fixed the hardcoded wukong leak, #474).
2026-06-18 12:22:19 +08:00
修雨 6310dcc39e feat(chat): tag user-identity message sends with edition clawType (#475)
Attach the clawType tool argument to every user-identity send path
(send_personal_message text/rich-media/reply and
send_direct_message_as_user) so the IM server can render the
"Send from AI" indicator on delivered messages. The value comes from a
new edition hook (Hooks.ClawTypeValue, exposed via edition.ClawType())
that falls back to DefaultOSSClawType ("openClaw"); overlays such as
wukong set their own identity to get their branded indicator.

Also fixes the reply command, which hardcoded clawType="wukong" and
made open-source replies carry the Wukong AI identity.

Bot sends intentionally stay untouched: they already render as bot
messages and must not carry the user-identity claw tag.
2026-06-18 10:53:52 +08:00
qinze 518b1cb631 Merge remote-tracking branch 'origin/feat/dws-devapp' into feat/dws-devapp
# Conflicts:
#	skills/multi/dingtalk-dev/references/version.md
2026-06-18 10:48:58 +08:00
玉澜 f29655e7e4 fix(devapp): let server assign app version 2026-06-18 10:32:52 +08:00
qinzeandClaude Opus 4.8 cc8a726b0a docs(dev): dingtalk-dev references 二次精简
- permission/robot/version 删 bash 命令示例堆叠(schema/--help 已覆盖),
  保留状态机/枚举语义/链路/gotcha
- 去掉所有 reference 的"概念锚点"自造词标签,保留指向概念地图的引语
- SKILL.md 生效模型去"(最重要)";connect 去加粗

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 09:09:04 +08:00
shangguanxuan.sgx f0552dd20e docs: record latest auth login prepub evidence 2026-06-18 02:53:00 +08:00
shangguanxuan.sgx a040b57be7 fix: stop auth login post-approval tui retry 2026-06-18 01:44:31 +08:00
shangguanxuan.sgx a2e8700beb docs: record caller-only recommend fallback 2026-06-18 00:48:01 +08:00
shangguanxuan.sgx 98804801c9 docs: record recommend empty-plan recheck 2026-06-17 23:17:40 +08:00
shangguanxuan.sgx 6946dd1e35 docs: record empty plan guard verification 2026-06-17 22:21:38 +08:00
shangguanxuan.sgx d09fca4b9b fix: guard empty login recommend all-scope plan 2026-06-17 22:16:58 +08:00
qinzeandClaude Opus 4.8 70d66daa5f feat(dev): schema 覆盖 dev doc + dingtalk-dev skill 精简
- dws schema 支持 dev.doc.search:fetcher 按 source 取(op-app 钉死 pre/
  devdoc 走运行时解析),给 doc search 叶子加 mcp-tool/mcp-source 注解
- dev doc search flag 对齐 MCP 参数名(--keyword/--size 为主,旧名隐藏兼容)
- dingtalk-dev SKILL.md:顶部加 MUST DO(每次先 --help/schema 查),核心规则
  瘦身、去重、去加粗/箭头符号
- references 精简:删参数表/flag 列表(schema/--help 已实时提供),只留状态机/
  覆盖语义/链路/gotcha;event 补"订阅前需先建联"业务规则;新增 recipes.md
  端到端链路;典型任务收成指针

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 21:56:11 +08:00
shangguanxuan.sgx 1926bd17b9 docs: update latest bff prepub instance 2026-06-17 21:48:12 +08:00
shangguanxuan.sgx 6a392e611c docs: record prepub deployment recheck 2026-06-17 21:25:45 +08:00
shangguanxuan.sgx 710844382e docs: record bff selected scopes hardening 2026-06-17 20:34:49 +08:00
shangguanxuan.sgx b1a88106e5 docs: record current cli recommend verification 2026-06-17 19:49:50 +08:00
shangguanxuan.sgx dcf132a7e3 fix: discover products before all-scope plan 2026-06-17 19:21:54 +08:00
shangguanxuan.sgx d2fd7e00b5 fix: skip tui for recommend login 2026-06-17 18:47:51 +08:00
shangguanxuan.sgx 7720e3ec9b docs: clarify post-login recommend tui 2026-06-17 17:56:36 +08:00
shangguanxuan.sgx 537719c677 fix: run recommend tui after login 2026-06-17 17:51:24 +08:00
qinzeandClaude Opus 4.8 51db546686 Merge origin/feat/dws-devapp into feat/dws-dev
合并远端团队的 MCP 对齐与 CR 修复,与本地 dev 命令重构 + schema 实时拉取 + flag 对齐 MCP 参数名集成。

冲突解决要点:
- 工具名常量:两边已收敛到同一组 op-app 真实工具名,取 dev 子树(ours)标识
- 保留 schema 能力:32 个 annotateDevAppTool 注解 + flag=kebab(MCP参数名)不变
- 吸收远端 CR 修复:normalizeDevAppServiceResult 解包 ServiceResult、
  remove_dev_app_permissions 结果扁平化、生命周期工具状态标记
- 旧 dingtalk-devapp 技能目录保持删除(已重命名为 dingtalk-dev)
- devdoc article search 统一 --page-size/pageSize,--size 留兼容别名

构建/vet/internal 测试全绿(28 包,0 失败)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:01:50 +08:00
shangguanxuan.sgx e9d50a659f docs: correct recommend tui chain 2026-06-17 16:54:17 +08:00
shangguanxuan.sgx 2264743e78 fix: model recommend login tui chain 2026-06-17 16:47:16 +08:00
qinzeandClaude Opus 4.8 6244222adf feat(dev): schema 实时拉取 MCP + flag 全面对齐 MCP 参数名
- 新增 dws schema dev.* 实时从 op-app tools/list 拉取参数(gws 扁平格式),
  description/type/required/default 全部 verbatim 来自服务端,零本地合成
- flag 全部改为 kebab(MCP 参数名),去掉别名,schema 展示与 CLI flag 完全一致,
  修掉 schema 显示假参数名的问题
- CLI 同步新 MCP 契约(工具名复数化、参数名 rename)
- dingtalk-dev skill 文档同步新 flag 名

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:43:19 +08:00
shangguanxuan.sgx a31a29e0ab docs: record recommend yes gate 2026-06-17 16:02:25 +08:00
shangguanxuan.sgx 3ec35e30e8 fix: respect yes for recommend login grants 2026-06-17 15:50:42 +08:00
shangguanxuan.sgx da08e84e80 docs: record mgdone tui evidence 2026-06-17 15:13:26 +08:00
shangguanxuan.sgx 5e1983b3df fix: align recommend tui interaction 2026-06-17 15:06:14 +08:00
wxianfeng 8984f7b8be fix cr problem 2026-06-17 12:13:28 +08:00
wxianfeng dd08db54d8 Merge branch 'feat/dws-devapp' of github.com:wxianfeng/dingtalk-workspace-cli into feat/dws-devapp 2026-06-17 10:03:55 +08:00
wxianfeng 591609fdee fix cr problem 2026-06-17 10:03:04 +08:00
quanming 6447bdd45f fix: align devapp member security app id flag 2026-06-17 09:53:31 +08:00
玉澜 2610c8ce87 Merge branch 'feat/dws-devapp' of https://github.com/wxianfeng/dingtalk-workspace-cli into feat/dws-devapp 2026-06-17 03:32:19 +08:00
玉澜 0e6cb46f58 fix: align devapp mcp compatibility 2026-06-17 03:29:46 +08:00
shangguanxuan.sgx a613728fbd docs: record recommend tui human flow 2026-06-17 01:03:04 +08:00
shangguanxuan.sgx 70b9f39715 fix: use human recommend flow by default 2026-06-17 00:58:27 +08:00
shangguanxuan.sgx d29aebeecd docs: record current batch auth gate status 2026-06-17 00:44:58 +08:00
wxianfeng 844059a77b fix cr problem 2026-06-17 00:43:19 +08:00
shangguanxuan.sgx 9ee8ea5524 fix: show recommend selector by default 2026-06-17 00:34:23 +08:00
shangguanxuan.sgx 42c71c9c54 docs: add frontend cdn verification 2026-06-17 00:08:51 +08:00
shangguanxuan.sgx 690d0788e3 docs: refresh batch auth release evidence 2026-06-17 00:05:44 +08:00
shangguanxuan.sgx 5a7c0748e3 feat: add recommend login product TUI 2026-06-16 23:19:24 +08:00
wxianfeng 410949cdf3 fix cr problem 2026-06-16 21:02:38 +08:00
修雨 f1a68f2424 docs: cut 1.0.38 changelog (#469) 2026-06-16 20:20:20 +08:00
patrickmen 497e4f87d8 feat: support to disable auto open browser (#365) 2026-06-16 20:08:29 +08:00
Jackjin a8d009aec8 fix(upgrade): honor --dry-run as preview-only instead of silently upgrading (#416)
dws upgrade registered no --dry-run flag and never read the global one,
so --dry-run fell through to runUpgrade and performed a real, irreversible
upgrade (download + replace binary). This contradicts the flag's documented
contract (预览操作内容,不实际执行).

Resolve the target release and platform asset (so a missing build / 'already
latest' is still reported), then render the planned 1-5 steps and return
before any side effect: no backup, no download, no replace. Advertise
--dry-run in the command examples.

Fixes #364
2026-06-16 20:08:25 +08:00
thisred 1f413fa322 fix: pipeline PollUntil case-insensitive comparison to fix sheet export hang (#462) 2026-06-16 20:08:17 +08:00
玉澜 0197dbc81a fix: align devapp DTO field names 2026-06-16 19:18:27 +08:00
shangguanxuan.sgx b85353e042 fix: emit single PAT authorization URL 2026-06-16 18:07:56 +08:00
修雨 ece91bfa3c feat(agent): accurate agent_code detection + per-channel agentId for stats (#467)
Tag each MCP request with which agent host is driving dws (agent_code) and a
per-(machine × agent_code) instance id, so usage can be sliced by channel and
instance in the data warehouse. Root cause it fixes: agent_code was only sent
when the host injected DINGTALK_DWS_AGENTCODE (~99.98% empty), so the gateway
logged none.

Detection ladder (every signature observed on a real host / official docs, not
guessed; unknown -> custom):
  T0 explicit DINGTALK_DWS_AGENTCODE
  T1 verified env signatures: claudecode (CLAUDECODE), codex (CODEX_SANDBOX),
     openclaw (OPENCLAW_BUNDLE_ROOT), hermes (HERMES_HOME)
  T2 VSCODE_BRAND value (covers the whole VS Code fork family)
  T3 macOS __CFBundleIdentifier map (qoder/cursor/vscode/workbuddy)
  T4 custom fallback

identity.json v2 (machineId + per-agent_code agents map), deterministic
dwsa_<base62> derivation, transparent v1 migration. Backward-compatible wiring:
x-dws-agent-id stays machine-level; new x-dws-agent-instance-id carries the
per-channel id; X-Cli-Version emitted so old/new clients are distinguishable.

Trust boundary (docs/agent-code.md): agent_code and the ids are self-reported
and spoofable — fit for statistics ONLY, never for auth/limit/billing.

Includes unit tests for every tier and the integration doc.
2026-06-16 17:55:29 +08:00
qinzeandClaude Opus 4.8 f740955423 chore(dev): skill 测试基建适配 dev 命令集
run_skill_tests / skill_e2e / skill_static / skill_tests 更新到 dev 技能。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:12:05 +08:00
qinzeandClaude Opus 4.8 166f665708 chore(dev): devapp→dev 重命名收尾(docs/mono/install/README/gitignore)
删除旧 devapp docs;mono 技能与 intent-guide 去 devapp;install 脚本改名
install-dev.sh;README 更新;.gitignore 放行 skill credentials.md 文档。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:11:50 +08:00
qinzeandClaude Opus 4.8 55f5e0c3d0 chore(dev): 删除旧 skills/multi/dingtalk-devapp
multi 模式旧 devapp 技能整组下线,已被 dingtalk-dev 替代。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:11:32 +08:00
qinzeandClaude Opus 4.8 f58b426381 chore(dev): 删除旧 skills/dingtalk-devapp(root 模式)
devapp 旧技能整组下线,已被 multi/dingtalk-dev 替代。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:11:32 +08:00
qinzeandClaude Opus 4.8 2640338803 docs(dev): dingtalk-dev skill reference (2/2) + dev 功能测试
webapp 产品文档;dev 命令集功能测试用例与报告(测试产物 results.jsonl 不入库)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:11:21 +08:00
qinzeandClaude Opus 4.8 dbcbb1de85 docs(dev): dingtalk-dev skill 概念结构 + 产品 reference (1/2)
SKILL.md 重构为「概念地图 + 核心规则/通用出参约定 + 典型任务 + 产品索引」;
reference 改为一命令组一文件;不在 agent 文档暴露内部 MCP tool 名。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:11:09 +08:00
qinzeandClaude Opus 4.8 63b6112fa2 test(dev): dev 命令集测试 + 建联/端点路由适配
helpers 单测、connect/card/stream 测试,app runner 与 direct_runtime devapp
端点路由。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:09:18 +08:00
qinzeandClaude Opus 4.8 eaeb9ac05d feat(dev): 开放平台 dev 命令集核心实现
dev 伞形命令(app/connect/doc)、应用全生命周期、权限/成员/安全/机器人/
版本/事件、cursor 透传分页、pretty 状态标注、connect 建联。MCP 工具名对齐
服务端实际注册名。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:09:06 +08:00
shangguanxuan.sgx e82ccd3496 docs: refresh batch auth verification state 2026-06-16 16:34:10 +08:00
修雨 b4c9db8807 feat(connect): custom channel for self-built/unsupported AI (issue #37)
Add a generic 'custom' channel plus an --agent-cmd flag so 'dws devapp
robot connect' can forward to ANY headless AI CLI (question appended as
the trailing arg, stdout used as the reply). Onboards tools that aren't
built-in (e.g. LobsterAI) or self-built agents with no code changes:
--agent-cmd forces channel=custom unless --channel is set explicitly,
and auto-detection falls back to custom when DWS_AGENT_CMD is present.

Also (issue #39): print a one-time hint at connect start when neither a
work dir nor a knowledge source is set, pointing at --agent-workdir /
--knowledge-* / --agent-model so the bot can match terminal answer
quality. Quickstart gains matching FAQ entries plus a note that step 3
(robot connect) produces no approval ticket (issue #19).
2026-06-16 15:04:04 +08:00
shangguanxuan.sgx aa76f01015 docs: record PAT app dev API build fix 2026-06-16 15:03:40 +08:00
shangguanxuan.sgx 931d7e59ef docs: refresh PAT prepub dependency status 2026-06-16 14:57:58 +08:00
shangguanxuan.sgx db2043c82b docs: record batch auth prepub status 2026-06-16 14:45:10 +08:00
wxianfeng c2f3653ec4 get_extension_robot_config 2026-06-16 14:40:17 +08:00
shangguanxuan.sgx 11dfd4ccf2 feat: add dws recommended batch auth flow 2026-06-16 14:09:15 +08:00
wxianfeng ef60d99b26 get_robot_config 2026-06-16 12:12:19 +08:00
wxianfeng 1b6e197426 fix conflict 2026-06-16 11:04:12 +08:00
wxianfeng 41b743de77 test 2026-06-16 11:02:42 +08:00
wxianfeng caf672699f tool name rename 2026-06-16 11:01:33 +08:00
修雨 ff33114b2c feat(doc): strip server-rejected unsafe chars on markdown write path (#465)
The doc write boundary only stripped a fixed dangerous-Unicode set, and only
on the JSONML path. C0 control characters (except tab/newline), DEL (0x7F),
and a few zero-width / line-separator codepoints still reached the server,
where RejectControlChars rejects them — so doc create/update failed on content
that pasted in such characters (common with LLM-generated or copy-pasted text).

- Rename stripDocDangerousUnicode -> stripDocInputUnsafe and extend it to drop
  C0 controls (except \t and \n) and DEL, matching apiclient.rejectDangerousChars.
- Add U+200D, U+2028, U+2029 to the dangerous-Unicode set so it covers the
  full server-rejected range.
- Apply the strip on the markdown write path (doc create/update) and the JSONML
  node path, not just the JSONML body.
- Add unit tests for stripDocInputUnsafe.

Ported from dws-wukong (feat: 增加输入安全字符过滤功能).
2026-06-16 10:56:53 +08:00
玉澜 67ac777657 Merge remote-tracking branch 'origin/feat/dws-devapp' into feat/dws-devapp 2026-06-16 10:13:57 +08:00
玉澜 c9ba0373c2 fix: align devapp cli tool mappings 2026-06-16 10:10:43 +08:00
quanming 4a19530fd0 fix: align devapp MCP tool names 2026-06-16 09:57:11 +08:00
修雨 7a28d97739 Merge pull request #38 from PeterGuy326/fix/issue-35-robot-create-async
fix(devapp): robot create routes to async submit/poll (issue #35)
2026-06-16 09:38:50 +08:00
修雨 d63f7e5836 fix(devapp): robot create routes to async submit/poll (issue #35)
The synchronous `create_dingtalk_robot` MCP action is broken server-side:
it dispatches to a connect-engine action template (detailId G-ACT-... /
versionId G-ACT-VER-...) that the engine can no longer find, returning
PARAM_ERROR / "找不到执行动作" for every caller (the orgId in the error is
hardcoded server-side, not the caller's). The async path
(submit_robot_create_task + query_robot_create_result) still works.

`dws devapp robot create` now submits the async task and polls the result
until a terminal status, returning the same agentId/clientId/robotCode/
clientSecret payload. User experience is unchanged — one command still
creates the robot. --dry-run previews the submit call.

- runDevAppRobotCreate orchestrates submit + interval-based polling
  (pending set WAITING/PROCESSING/RUNNING/PENDING/INIT/DOING, max 24 polls).
- Tests: create routing now expects submit; add poll-until-terminal and
  status-classification unit tests.
- Docs/skills updated to reflect the new routing.
2026-06-16 09:35:05 +08:00
玉澜 8aaf0fb6e8 fix: unwrap devapp service result responses 2026-06-16 08:03:47 +08:00
玉澜 0f3c4ccbdd fix: align devapp cli with MCP schema 2026-06-16 00:31:27 +08:00
修雨 1f21fdf7be Merge pull request #36 from PeterGuy326/feat/connect-kb-observability
feat(connect): knowledge-base observability + wider text formats (#32)
2026-06-15 22:30:49 +08:00
修雨 b2fd204e67 feat(connect): knowledge-base observability + wider text formats (issue #32)
"挂载的本地知识库不生效" was hard to diagnose: a dir of pdf/docx/json indexes
nothing, and a per-message retrieval miss was silent — both look identical to
the operator. Make the knowledge path observable and a bit more forgiving.

- index the .md/.txt FAMILY (.md/.markdown/.mdx/.txt/.text), not just .md/.txt
- loadKnowledgeBase logs how many files indexed vs skipped, and the empty-dir
  error now says only text is indexed (pdf/docx/json are not)
- augment logs per message whether it injected N chunks or missed (so a wrong
  knowledge dir / non-overlapping question is visible, not silent)

Tests: isKnowledgeTextExt, markdown-family indexing, clear no-text-files error.
2026-06-15 22:27:14 +08:00
wxianfeng 6f8c9173d3 Merge branch 'feat/dws-devapp' of github.com:wxianfeng/dingtalk-workspace-cli into feat/dws-devapp 2026-06-15 21:00:31 +08:00
shangguanxuan.sgx 1921e5e37e feat(devdoc): support cursor pagination 2026-06-15 20:41:53 +08:00
wxianfeng 6480c035fa Fix review problem 2026-06-15 20:29:50 +08:00
修雨 1c88dd6a0d Merge pull request #34 from PeterGuy326/feat/connect-twin-confirm-policy
feat(connect): confirm_policy — manual / auto / remember
2026-06-15 17:30:25 +08:00
修雨 6ce4a635b2 style: gofmt connect_approval.go (struct tag alignment) 2026-06-15 17:26:59 +08:00
修雨 ee2fa735b2 feat(connect): confirm_policy — manual / auto / remember for others' requests
RoleConfig.confirm_policy was parsed but never acted on. Wire the three
strategies for how OTHERS' action requests are confirmed (the owner's own
requests always auto-run regardless):

- manual (default): ask the owner every time
- auto: run without asking — full trust — still fully audited
- remember: ask once per action verb, then reuse that decision (approve →
  auto-run same verb; reject → auto-decline same verb)

- gateDecision(requester, verb) returns auto / ask / reject
- ApprovalRequest.Verb carries the action verb (remember key + audit)
- handleOwnerDecision caches the decision per verb under the remember policy
- applyRoleConfig fills opts.ConfirmPolicy; launchConnector wires + logs it

Tests: auto runs without asking, manual asks, remember reuses the 1st decision.
2026-06-15 17:22:45 +08:00
修雨 a9df88654d Merge pull request #33 from PeterGuy326/feat/connect-twin-scope-enforce
feat(connect): enforce role capability scopes — keep a twin in its lane
2026-06-15 17:16:11 +08:00
修雨 e58e805b17 feat(connect): enforce role capability scopes — keep a twin in its lane
RoleConfig.allowed_scopes was parsed but never enforced. Now an action whose
product is outside the role's allowlist is refused before it reaches the gate,
so an HR-assistant role can't be made to touch code/drive.

- applyRoleConfig fills opts.RoleScopes from the role's allowed_scopes
- the orchestrator gains allowedScopes + scopeAllows(product); empty = allow all
- handleReply refuses an out-of-scope action up front and tells the requester
  it is out of the twin's lane (a capability boundary, not an approval, so safe
  to surface); nothing reaches the gate or the owner
- launchConnector wires opts.RoleScopes into both orchestrators and logs the
  boundary at startup

Tests: out-of-scope refused (not gated), in-scope proceeds, empty = allow all.
2026-06-15 17:13:02 +08:00
修雨 d1d6d9e74c Merge pull request #31 from PeterGuy326/feat/connect-twin-auto-retry
feat(connect): auto-retry deferred backlog — no manual 重试 needed
2026-06-15 17:07:36 +08:00
修雨 b75f07547f feat(connect): auto-retry deferred backlog — no manual retry needed
A deferred backlog (queued while the connector's dws login was not yet the
bot owner) now drains by itself once the owner's identity is back, instead of
requiring the owner to manually reply 重试.

- startAutoRetry runs a 2-minute background ticker (text mode) that calls
  autoFlushDeferred until the connector context is cancelled
- autoFlushDeferred replays the backlog but messages the owner ONLY when
  something actually completed — a tick while the identity is still wrong is
  silent (no spam); each completed requester is still notified
- flushDeferred (manual 重试) and the auto path share flushDeferredOnce
- the deferred notice now tells the owner it will auto-recover after login,
  with 重试 as an optional 'do it now'

Tests: auto-retry stays silent while stuck, drains + notifies on recovery.
2026-06-15 17:04:28 +08:00
修雨 ccb4927c48 Merge pull request #30 from PeterGuy326/feat/connect-twin-more-actions
feat(connect): twin can also create calendar events and docs
2026-06-15 16:59:37 +08:00
修雨 1a2454a5ab feat(connect): twin can also create calendar events and docs, not just todos
The digital twin previously only knew one action (todo.create). Add two more
owner-scoped write actions so it can act as a real stand-in:

- calendar.create → calendar/create_calendar_event (summary + start/end)
- doc.create → doc/create_document (name)

Both flow through the same gate: detected via [[ACTION:...]] marker, classified
as write (gated), approved/deferred/audited identically. The agent system hint
now lists all three action markers. A shared firstNonEmpty arg helper.

Tests: toPlannedAction maps each verb to the right product/tool, missing
required args degrade to not-an-action, and every action classifies as write.
2026-06-15 16:55:37 +08:00
shangguanxuan.sgx 0a8de62041 Revert "feat(skills): add self-contained dingtalk-open-platform doc skill"
This reverts commit 2c51774150.
2026-06-15 16:47:35 +08:00
修雨 d6f44143ad Merge pull request #29 from PeterGuy326/feat/connect-twin-polish
fix(connect): retry audit-sheet throttles; flush reports completed items
2026-06-15 16:37:12 +08:00
修雨 4d831e5054 fix(connect): retry audit-sheet throttles; flush reports completed items
Two polish items surfaced during the digital-twin smoke test:

- audit-sheet append now retries transient throttles (THREADPOOL_BUSY /
  timeout / 429) up to 3x with backoff, instead of silently dropping the
  audit row on the first busy response. isTransientSheetErr keeps permanent
  errors (bad node id, permission) non-retried.
- flushDeferred reports WHAT it completed (a numbered per-item list), not just
  a count. When the owner is also the requester — the common self-request
  case — this list is their only completion receipt, since notifyRequester
  skips owner==requester to avoid double-messaging.

Tests: isTransientSheetErr classification, flush per-item completion report.
2026-06-15 16:32:41 +08:00
shangguanxuan.sgxandCursor 2c51774150 feat(skills): add self-contained dingtalk-open-platform doc skill
DingTalk open-platform documentation skill as an agent execution manual
(discover -> auth -> call -> verify -> recover), fully self-contained
(no cross-skill references; dws is only a reference tool), with a
built-in doc index llm.md of verified open.dingtalk.com/document links.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-15 15:38:21 +08:00
修雨 a10169344f Merge pull request #28 from PeterGuy326/feat/connect-deferred-execution
feat(connect): deferred execution — hold + retry when the twin can't act yet
2026-06-15 15:09:19 +08:00
修雨 82d625603f feat(connect): deferred execution — don't lose a task when the twin can't act yet
When an approved action can't execute right now (most often the connector's
dws login is not the bot owner, so an owner-scoped action like creating a
personal todo fails), the request is no longer dropped with an opaque error.
Instead it is held and retried after the owner recovers.

- new 'deferred' state: an approved request whose execution didn't complete;
  persisted like any other, distinct from terminal 'failed'
- on execution failure (auto-approve path and owner-approve path), mark
  deferred instead of failed, and privately DM the owner what went wrong and
  how to recover (log dws in as the bot owner, then reply 「重试」). The
  requester is NOT told it failed — their task is held, not lost
- 「重试/恢复」owner keyword flushes the backlog: re-execute each deferred
  request oldest-first; on success mark executed and send the requester the
  outcome, on failure keep it deferred
- markDeferred / allDeferred on the gate; deferred counts as approved() so the
  retry can still mark it executed
- tests: deferred-hold-then-retry end to end, isRetryWord

This is the graceful-degradation half of the digital twin: a request survives
an owner-offline / wrong-identity window and completes once the owner is back.
2026-06-15 15:05:45 +08:00
修雨 11780ae3b0 Merge pull request #27 from PeterGuy326/feat/connect-twin-private-approval-audit
feat(connect): private owner approval, self auto-approve, online-sheet audit
2026-06-15 14:50:50 +08:00
修雨 79bab762bf feat(connect): private owner approval, self auto-approve, online-sheet audit
Builds on the text-approval gate with the digital-twin model the owner asked
for: the approval stays strictly between the bot and its owner, and every
action is auditable in DingTalk.

- private owner DM: an action request is no longer posted into the requester's
  conversation; the bot DMs the OWNER privately (robot oToMessages/batchSend,
  reusing the bot's own credentials) and the requester sees nothing until the
  result. Decision matching moved from per-conversation to latestPending, since
  the owner replies from their own 1:1 chat, not the request conversation.
- owner self auto-approve: when the requester IS the owner, asking is the
  authorization — the action runs immediately with no second confirmation, but
  is still recorded (auto_approved=true, decided_by=owner) for audit.
- online-sheet audit: optional --audit-sheet / --audit-sheet-tab appends one
  row per terminal action (time, summary, requester, state, decided_by, auto,
  error, id) to a DingTalk online sheet via sheet append_rows, reviewable in
  DingTalk on any device — beyond the local approvals JSON.
- aiCardClient.sendOTOText: proactive 1:1 robot text send primitive.
- requester gets the final outcome (executed/failed/rejected) by 1:1 message;
  the approval process itself is never exposed to them.

Tests: parseDecisionWord, latestPending, private-DM approve/reject,
owner self auto-approve, audit terminal records, classifier wiring intact.
2026-06-15 14:47:02 +08:00
修雨 e840cac3cc Merge pull request #26 from PeterGuy326/feat/connect-text-approval
feat(connect): text approval fallback — owner confirms in chat, no card needed
2026-06-14 11:08:40 +08:00
修雨 45b4f088af feat(connect): text approval fallback — owner confirms in chat, no card needed
The confirmation gate previously REQUIRED a hand-built interactive card
template (per app, manual button param binding in the card console) — and
without one the gate silently turned off. That manual step is too clunky to
be the default. Add a text-approval mode so the digital twin works with zero
card-platform setup: when --owner-user-id is set but no --approval-card-
template, the bot posts a plain confirmation and the owner replies 「同意」/
「拒绝」 in chat to decide.

- newTextApprovalOrchestrator: gate enabled on owner alone (no card sender)
- text mode is async, NOT blocking: handleReply posts the prompt and returns;
  the owner's decision arrives as an ordinary inbound message captured by
  handleOwnerDecision (blocking on Await would deadlock the per-conversation
  worker that must also process that reply)
- gate.pendingForConv maps an owner reply (carries only the conversation) back
  to its request; parseDecisionWord matches a WHOLE-message keyword so an
  embedded 「同意」 never accidentally approves
- only the configured owner can decide; non-owner / non-keyword pass through
- devapp_connect: no card template now falls back to text mode instead of
  disabling the gate
- existing card flow refactored into handleReplyCard, unchanged behavior
- tests: parseDecisionWord, pendingForConv, text-mode approve/reject,
  non-owner rejected, non-decision pass-through
2026-06-14 11:05:13 +08:00
修雨 b28ca6364e Merge pull request #25 from PeterGuy326/feat/connect-role-runtime
feat(connect): wire role config into the connector runtime
2026-06-14 10:45:10 +08:00
修雨 8b39dac5db feat(connect): wire role config into the connector runtime
Sprint 2 item 2: a digital-employee role config (connect_role.go) was a
defined-but-unused schema. Wire it into the connector so a single
--role-config <file> supplies the bot's owner, persona and knowledge
sources instead of scattering them across flags.

- add --role-config / DWS_ROLE_CONFIG; load + validate in launchConnector
  with a client_id-must-match-this-bot guard (one role == one bot)
- applyRoleConfig merges role -> options with explicit-flag-wins semantics
  (a flag/env always overrides the role; knowledge sources are additive)
- owner feeds the approval gate; persona is prepended to every forwarded
  prompt; role knowledge sources load and merge into the same retriever
- AllowedScopes / ConfirmPolicy are parsed and logged but not yet enforced
  (scope gating + auto/remember strategies are a later slice; no dead opts
  fields carried for them)
- tests: applyRoleConfig flag-wins / fill-empty / nil-role

Scope enforcement and confirm-policy behavior intentionally deferred.
2026-06-14 10:41:37 +08:00
修雨 7ecfe85696 Merge pull request #24 from PeterGuy326/feat/connect-gate-classifier
feat(connect): gate engages via read/write classifier, not every marker
2026-06-14 10:27:16 +08:00
修雨 9af7f9a034 feat(connect): gate engages via read/write classifier, not every marker
Sprint 2 item 1: wire the dws command read/write classifier into the
digital-twin approval gate. Previously any detected [[ACTION:...]] marker
was unconditionally routed through the owner-confirmation gate. Now the
gate consults ClassifyDwsCommand on the planned command: a read-class
action bypasses the gate and replies normally, while write — and Unknown,
per the CmdClass safety contract — keep the owner sign-off requirement.

- add classifyPlannedAction bridging plannedAction -> CmdClass (classifies
  on LegacyPath, falls back to product + RPC tool verb)
- handleReply skips Submit/card/Await for a read-class action
- tests: classifyPlannedAction table + handleReply read-class bypass
  (override-driven, exercises the wiring end to end)
2026-06-14 10:22:01 +08:00
修雨 c50494775c Merge pull request #23 from PeterGuy326/feat/connect-cmd-classify
feat(connect): classify dws commands as read vs write for approval gating
2026-06-14 00:12:04 +08:00
修雨 1fe4842525 Merge pull request #22 from PeterGuy326/feat/connect-role-config
feat(connect): role config schema for per-role digital personas
2026-06-14 00:11:57 +08:00
修雨 5708e1c2d2 Merge pull request #21 from PeterGuy326/feat/connect-approval-gate
feat(connect): approval gate — execution requests need owner sign-off before running
2026-06-14 00:11:51 +08:00
修雨 d43ec228aa feat(connect): digital-twin confirmation gate vertical slice
Add the M2 confirmation gate (digital twin): an action request from a
group member is not executed directly. The bot sends an [Approve]/[Reject]
card to the owner over the existing Stream long-connection and only runs the
planned command after the owner approves.

- connect_approval.go: gate engine. ApprovalRequest model, Pending to
  Approved/Rejected to Executed/Failed state machine, thread-safe store with
  crash-safe atomic on-disk persistence (~/.dws/connect/<clientId>/approvals,
  0600, restart-recoverable), Submit/Decide/Await/Get API, and the simplified
  [[ACTION:...]] marker detection for execution-class requests.
- connect_approval_card.go: approvalCardSender boundary (DI-fakeable), the
  card-callback decoder (approval id + decision from action params, OutTrackId
  fallback), the orchestrator driving Submit to card to Await to execute to
  reply, and the real DingTalk interactive-card sender.
- connect_stream.go / devapp_connect.go: minimal wiring. Register the card
  callback router, decorate the prompt for action detection, route a marked
  reply through the gate, --owner-user-id / --approval-card-template flags.

Tests: state machine + persistence/recovery, card-action decode, reject path
(no execution), and a no-network end-to-end approve chain. gofmt/vet/build/
test all green.
2026-06-13 23:34:37 +08:00
修雨 fb335fb403 feat(connect): add dws command read/write classifier
Add ClassifyDwsCommand, a standalone heuristic classifier that labels a
dws command (by path segments) as read / write / unknown. It is the
signal a connector confirmation gate consumes to decide whether a robot
may run a command directly (read-only) or must first ask the principal
to approve it (write / mutating).

- Read/write verb tables calibrated against real dws cobra Use: verbs
  scanned from the repo (list/get/search/status/export/download vs
  create/update/delete/send/done/upload/recall/mkdir/chmod ...).
- Segments scanned right-to-left so the leaf action verb dominates a
  container/placeholder segment; falls back toward the root when the
  leaf is unrecognised (e.g. a trailing id).
- Compound leaf verbs normalised by their leading token before the
  first '-'/'_' (send-by-bot, list-forms, batch-update, add-bot ...).
- Override mechanism: per-call map (ClassifyDwsCommandWith) and a
  process-wide table (SetCmdClassOverride), keyed by single verb or
  full space-joined path, full-path winning. Overrides beat heuristics.
- Unknown is returned losslessly; the CmdClass doc comment documents the
  safety contract that callers must treat Unknown conservatively as
  write (require confirmation), never auto-allow.

This is the classifier component only; wiring it into the confirmation
gate is a separate change.
2026-06-13 23:25:04 +08:00
修雨 fd61526707 feat(connect): add digital-employee role config schema and loader
Introduce internal/helpers/connect_role.go: a standalone configuration
component for the one-role-per-bot digital-employee model. Each role binds
to a single bot via client_id and carries its persona, knowledge sources,
allowed capability scopes, owner userId and confirmation policy.

- RoleConfig struct (YAML) with manual/auto/remember confirm policy enum.
- LoadRoleConfig: read + parse + validate with clear, non-panicking errors
  (required name/client_id/owner_user_id, policy enum, source grammar).
- knowledge_sources reuse the existing parseKnowledgeSource grammar so the
  schema stays in lockstep with --knowledge-source (path / wiki: / doc:).
- LoadRoleConfigs: index roles by client_id for multi-bot deployments,
  rejecting duplicate client_id.
- RoleConfigExample documents a full role and is asserted in tests.

Schema only; no runtime wiring.
2026-06-13 23:21:16 +08:00
修雨 c858241b68 Merge pull request #20 from PeterGuy326/fix/forwarder-test-arity
fix(connect): repair forwarderForChannel test arity after #15/#16 merge
2026-06-13 23:07:09 +08:00
修雨 b826440995 fix(connect): update provider-model test for forwarderForChannel clientID arg
PR #15's connect_provider_model_test.go calls forwarderForChannel with the
old 2-arg signature; PR #16 added a clientID parameter. Both branches passed
in isolation but the merged release broke 'go test ./internal/helpers/'.
Pass an empty clientID (the test exercises model-arg injection, unrelated to
session persistence).
2026-06-13 23:03:12 +08:00
修雨 25f69b867e Merge pull request #18 from PeterGuy326/feat/connect-knowledge-wiki
feat(connect): mount DingTalk wiki space as a knowledge source
2026-06-13 22:58:23 +08:00
修雨 172060b868 Merge pull request #17 from PeterGuy326/feat/connect-daemon
feat(connect): daemonize the connector with crash-restart, status and stop
2026-06-13 22:58:17 +08:00
修雨 dd0990691e Merge pull request #16 from PeterGuy326/feat/connect-session-persist
feat(connect): persist conversation sessions across connector restarts
2026-06-13 22:58:11 +08:00
修雨 02bc7ce880 Merge pull request #15 from PeterGuy326/fix/reply-card-422-fallback
fix(connect): stop echoing provider 422 into chat; drop haiku pin for custom providers
2026-06-13 22:58:04 +08:00
修雨 4d476ed317 style: gofmt wiki knowledge source sources 2026-06-13 22:23:58 +08:00
修雨 ff89ffed69 style: gofmt connect_daemon sources 2026-06-13 22:23:48 +08:00
修雨 65ab1a3076 feat(connect): add daemon mode with crash-restart, status and stop
Turn `dws devapp robot connect` into a 7x24 background service.

- `connect --daemon` re-execs dws into a detached supervisor (POSIX setsid),
  prints pid + log path, and exits. Windows is unsupported (stub errors out).
- A supervisor process keeps a worker connector alive, restarting it with
  exponential backoff (1s..60s cap, 10 consecutive fast-failure ceiling).
- `connect status` reports running/stale/not-running, pid, uptime and log path.
- `connect stop` sends SIGTERM (worker releases the single-instance lock and
  Stream connection), escalates to SIGKILL on a timeout, and cleans the pid file.
- stdout/stderr are archived to ~/.dws/connect/<clientId>/daemon.log via the
  existing size-based rotator (new additive logging.NewRotatingFile).
- docs/connect-daemon-service.md ships launchd and systemd templates for
  boot-time auto-start.

The single-instance lock (connect_lock.go) is reused unchanged. The foreground
forwarding/session/knowledge logic is untouched; devapp_connect.go only gains
the --daemon flag, two hidden re-exec flags, and the status/stop subcommands.
2026-06-13 21:44:47 +08:00
修雨 cf277f3c8f feat(connect): add wiki/doc knowledge source for the Q&A connector
Extend the connector's knowledge retrieval (previously local .md/.txt only)
to a DingTalk knowledge base via --knowledge-source wiki:<spaceId> (and
doc:<docId>). On startup the connector pulls the space by reusing the existing
`doc` tools that back `dws doc list` / `dws doc read` (list_nodes +
get_document_content) through the shared executor.Runner -- no new DingTalk API
call is implemented. Pulled documents are dumped as markdown into a local cache
(~/.dws/connect/<clientId>/knowledge/wiki-<spaceId>/) and indexed by the same
chunker/retriever as the local-directory source.

Refresh on startup; on a pull failure (network/permission) fall back to a stale
cache if present, otherwise an empty knowledge base -- the connection is never
blocked. The legacy --knowledge-dir source is untouched and coexists.

Node listing uses a shallow id lookup so a response wrapper object is not
mistaken for a single node (which would drop sibling nodes).
2026-06-13 21:43:48 +08:00
修雨 59100407dc feat(connect): persist conversation sessions across connector restarts
convSessions held the DingTalk-conversation to agent-session map purely
in memory, so a connector restart dropped every chat's multi-turn
context - the core weakness of an always-on digital employee.

Persist the map to ~/.dws/connect/<clientId>/sessions.json (scoped per
clientId so multiple bots on one machine stay isolated), reusing the
existing config dir, 0600 FilePerm and lock-id sanitizer conventions:

- newConvSessions restores the map on startup; a missing or corrupt
  file degrades to an empty map with a warning, never a panic or a
  blocked connection.
- args/reset persist after every mutation, under the existing mutex so
  the snapshot is race-free, via a temp-file + rename atomic write.
- saves are best-effort: a write failure only logs a warning and never
  blocks message handling.
- an empty path (clientId missing or --agent-memory off) keeps the map
  in memory only, preserving the original behaviour exactly.

forwarderForChannel now takes clientId to derive the per-bot store path.
Adds unit tests for reload, corrupt-file degradation, in-memory mode and
concurrent access (race-clean).
2026-06-13 21:39:45 +08:00
修雨 10de987e81 fix(connect): stop echoing provider 422 into chat; drop haiku pin for custom providers
issue #14: the "422" seen in the group was not from the DingTalk card API but
from the claude subprocess's model provider, echoed back as the reply.

Root cause:
- claudecode's spec pins --model claude-haiku-4-5-20251001 in both argvTail and
  streamArgvTail.
- claudeUserSettingsEnv (issue #10) injects the user's ANTHROPIC_BASE_URL /
  ANTHROPIC_AUTH_TOKEN into the claude subprocess. With a third-party provider
  relay that has no mapping for that exact haiku pin, the provider returns
  "API Error: 422 ...".
- execForwarder.forward used cmd.Output() and returned any non-empty stdout as
  the answer without checking err, so the raw 422 text was forwarded to the chat
  on every message.

Fix (A + B):
A. In forwarderForChannel, when a custom provider base URL is in effect
   (injected via Claude settings or already in the process env) and the user did
   not pick a model (--agent-model / DWS_AGENT_MODEL), strip the built-in model
   pin so the provider's default model applies. Official-login users keep the
   pin; an explicit --agent-model still wins.
B. In forward and forwardStream, treat stdout that starts with "API Error:"
   (or a process error) as a failure: return a short, actionable Chinese hint
   ("...请用 --agent-model <model> 指定模型后重连.") instead of echoing the raw
   backend error. Normal replies are unaffected.

Adds unit tests for the haiku-drop wiring, the API-Error guard, and the new
helpers.
2026-06-13 14:43:24 +08:00
修雨 c36fcaaf70 Merge pull request #13 from PeterGuy326/fix/quickstart-paste-safe-placeholders
docs(quickstart): paste-safe placeholders for the connect example
2026-06-12 18:05:55 +08:00
修雨 0cf97cea55 Merge pull request #12 from PeterGuy326/fix/skill-setup-embedded-source
fix(skill): embed skill sources in binary + cover qoder dirs in upgrade refresh
2026-06-12 18:05:49 +08:00
修雨 47354b918a docs(quickstart): make the connect example paste-safe in zsh
The step-3 example used <第二步的clientId> style placeholders; pasting
them verbatim makes zsh treat the angle brackets as redirections and
fail with "parse error near \n" before the CLI even runs (issue
PeterGuy326#11). Use realistic dummy values plus an explicit replace-me
note instead, and add a FAQ entry for anyone still hitting the error
from the old wording. Also bump install snippets to v1.0.53-dws-devapp.
2026-06-12 18:00:56 +08:00
修雨 df1e33442b fix(skill): embed skill sources in the binary and cover qoder dirs in upgrade refresh
Two distribution defects left installed skills stale (issue PeterGuy326#8):

1. skill setup resolved its source from cwd / exe-adjacent checkouts, so
   an upgraded binary happily re-installed whatever stale checkout it was
   run from, and agents kept routing 'create robot' into the chat dead end.
   The skills/mono and skills/multi trees are now embedded (go:embed) and
   setup defaults to that copy, materialized into ~/.dws/skills/<mode> —
   upgrading the binary upgrades what setup installs. --source and
   DWS_SKILL_SOURCE stay as explicit overrides, and an override that has
   no skill root errors out instead of silently falling back.

2. dws upgrade's skill refresh (knownSkillDirs) skipped ~/.qoder and
   ~/.qoderwork, so Qoder/QoderWork hosts never got refreshed routing.
   Added both to the dir table and its seven mirrors (npm install.js,
   install.sh/ps1, install-skills.sh, homebrew template, package test,
   verify-package-managers.sh).

setup-side detection and --target qoder/qoderwork already work on this
branch; this closes the remaining upgrade-side and source-side gaps.
2026-06-12 17:57:48 +08:00
修雨 a7ca1e1a5b fix(connect): pass user-level Claude settings env through to the claudecode channel
The claudecode channel spawns claude with --setting-sources project to
keep the bot persona neutral, but that also drops the user-level
settings.json env block where third-party provider tools (cc-switch
etc.) store ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN. claude then
fell back to the official login and replied "Not logged in - Please
run /login" for anyone on a relayed model.

Re-expose that env block as process environment for the spawned CLI
(both one-shot and streaming paths) via the channel envFn hook.
Variables already exported by the operator are not overridden, and
user hooks/plugins still stay out of replies.

Fixes PeterGuy326#10.
2026-06-12 16:14:50 +08:00
修雨 211a06c05a fix(devapp): resolve op-app MCP endpoint from gateway base URL
The devapp endpoint was hardcoded to the pre gateway, so robot
create/list hit the pre environment for everyone. Derive it from the
configured MCP gateway base URL instead: production by default, pre
when ~/.dws/mcp_url points at the pre gateway.

Also bump quickstart doc to v1.0.51-dws-devapp and add a FAQ entry for
the production-side developer-identity check.
2026-06-12 14:54:05 +08:00
修雨 bb52a505dc docs: add customer-facing robot quickstart guide (install, create, connect, add to group) 2026-06-12 14:20:26 +08:00
修雨 f899f4f6b6 chore(release): target PeterGuy326 fork for goreleaser, guard npm publish to official repo 2026-06-12 12:04:22 +08:00
wxianfeng 3adeffb09d event subscribe 2026-06-12 11:33:55 +08:00
xianfeng wang 435bf3151c Merge pull request #9 from PeterGuy326/feat/connect-qa-hardening
feat(connect): Q&A-bot hardening — picture messages, knowledge retrieval, allowlist/rate-limit, per-chat FIFO, single-instance lock
2026-06-12 10:02:47 +08:00
修雨 1c90edb92a fix(connect): drain buffered app-server frames before honoring read EOF
The codex app-server read loop reports EOF before closing the message
channel, so when the process exits right after its final frame, both
channels are ready and select picks one at random — runTurn could drop
an already-received turn/completed and fail with "stream ended before
turn/completed: EOF" (the CI flake on this PR and #8). Drain buffered
frames first; reproduced at ~7%/300 runs before, 0/300 after.
2026-06-12 09:42:51 +08:00
修雨 36b89a04b1 Merge remote-tracking branch 'wxianfeng/feat/dws-devapp' into HEAD
# Conflicts:
#	internal/helpers/connect_stream.go
2026-06-12 09:18:10 +08:00
Aemeath 9d3980f90a Merge pull request #8 from wxianfeng/codex/codex-channel-lab
[codex] add Codex app-server robot bridge
2026-06-11 19:49:11 +08:00
quanming ae5ef70bb8 fix: harden codex app-server client concurrency 2026-06-11 19:27:50 +08:00
玉澜 89c3aba2ed docs(devapp): capture publish workflow edge cases 2026-06-11 13:09:27 +08:00
修雨 c151756168 feat(connect): Q&A-bot hardening for the stream bridge
Five operational gaps that bite when a connector-backed bot answers
questions in real groups:

- Single-instance lock: one connector per robot per machine (pid file,
  stale-lock takeover). Duplicate Stream connections on one clientId get
  messages load-balanced between them, so the bot answers intermittently
  (verified live).
- Access policy: --allowed-users / --allowed-groups allowlists plus a
  per-sender rate limit (--user-rate-limit, default 20/min). Every
  message is an LLM call; without this anyone who can reach the bot can
  spend on its behalf.
- Per-conversation FIFO queue: same-chat messages run in arrival order
  (follow-ups need the previous turn's --resume session; parallel CLIs
  racing one session corrupt it); different chats stay parallel.
- Picture messages: resolve the callback downloadCode via robot
  messageFiles/download to a local temp file and hand the path to the
  agent CLI — error screenshots are the top Q&A inbound and were
  previously dropped silently. The claudecode persona now permits
  reading attached files.
- --knowledge-dir: lightweight local retrieval (markdown chunking,
  latin-token + CJK-bigram scoring) prepends top-k matching chunks to
  each question while the agent keeps running from the clean scratch
  dir, so replies stay inside DingTalk's AI-assistant response window.

All knobs have env mirrors (DWS_ALLOWED_USERS / DWS_ALLOWED_GROUPS /
DWS_USER_RATE_LIMIT / DWS_KNOWLEDGE_DIR) for service-style runs.

go build ./... clean; go test ./internal/helpers -race passes with new
tests for lock/gate/queue/knowledge/media. test/cli_compat, test/scripts
and test/unit fail identically on the unmodified base (pre-existing
fixture issues).
2026-06-11 12:18:25 +08:00
玉澜 473d2f9aaf docs(devapp): document status handling 2026-06-11 12:00:27 +08:00
quanming 3dcb40c634 feat: add codex app-server robot bridge 2026-06-11 11:10:25 +08:00
玉澜 5e4b5e4eda docs(devapp): add one-click install guide 2026-06-11 10:26:17 +08:00
john d873b9c017 Merge pull request #7 from PeterGuy326/fix/connect-card-doc-hermes-guidance
docs(connect): fix stale CardTemplate comment + document AI-assistant reply window for hermes channel
2026-06-11 09:13:19 +08:00
修雨 4b8acc8e73 docs(connect): fix stale CardTemplate comment; document AI-assistant reply window in hermes channel guidance
- ConnectOptions.CardTemplate said an empty value falls back to the public
  openclaw template, but the code (newAICardClient/hasTemplate) treats empty
  as cards-off, and the explicit "public" alias exists precisely for that
  opt-in. Align the comment with the actual contract.
- hermes official-channel steps now warn about the trap verified live: a
  devapp robot renders replies through the AI-assistant response window, so
  a slow agent's plain-text reply gets the Done reaction (HTTP 200) but never
  shows up, leaving the loading card stuck. Point users to enabling AI cards
  on the hermes side.
2026-06-10 23:54:15 +08:00
xianfeng wang 0f65cb0064 Merge pull request #6 from PeterGuy326/feat/devapp-robot-connect
feat(devapp): robot connect 回复升级——AI 卡片 + Thinking/Done 状态 + 真流式
2026-06-10 21:58:49 +08:00
修雨 f013536aac Merge upstream feat/dws-devapp: adopt upstream's hardcoded-endpoint priority
Conflict resolutions:
- internal/app/direct_runtime.go: take upstream (532fcb4) — the maintainer
  stabilized the endpoint tests by documenting the hardcoded devapp endpoint
  as authoritative (tests renamed *DoesNotOverrideHardcoded), superseding our
  demote-to-fallback fix for the same failing tests.
- skills/mono devapp.md: union — keep our reply-card/card-template/CLI
  preflight bullets and upstream's Codex DWS_AGENT_CMD guidance.
2026-06-10 21:51:25 +08:00
Aemeath c56eb7f8c2 Merge pull request #5 from wxianfeng/codex/devapp-codex-connect-skill 2026-06-10 21:48:07 +08:00
修雨 f9abc79ecc feat(devapp): cards opt-in via template; default replies are plain text + reactions
Mirror hermes' semantics: without a configured card template, replies go as
plain text/markdown with the Thinking/Done reaction chips (which need no
template and always render); cards activate only when --card-template /
DWS_CARD_TEMPLATE is set ('public' opts into the openclaw shared template
explicitly). This removes the silent-failure trap where every card API call
succeeds but the client cannot render a template it is not authorized for —
the previous default left users staring at 内容加载失败 instead of falling
back to text.
2026-06-10 21:43:42 +08:00
修雨 99893e473a feat(devapp): CLI dependency preflight in robot connect dry-run
The channel CLIs (claude/codebuddy/qodercli/...) may be missing on the
user's machine. Runtime already preflights at connect (auto-installing
package-manager CLIs, erroring with a hint otherwise), but agents had no
machine-readable way to check BEFORE starting the connector. dry-run now
reports a cli block ({required, installed, path, autoInstall, installHint})
per channel — desktop-app channels and openclaw/hermes report their
onboarding hint. Skill docs gain the agent preflight workflow: check
dry-run first; npm channels may auto-install; desktop-app channels must
have the app installed by the user before connecting.
2026-06-10 21:32:25 +08:00
修雨 51b3316187 feat(devapp): configurable AI-card template via --card-template / DWS_CARD_TEMPLATE
Card templates are app-scoped — the hermes docs prescribe grabbing the
template ID from YOUR app's AI Card settings in the developer console, and
our live A/B confirmed another app's template renders 内容加载失败. Expose
the template as a flag (default: the openclaw public template, best-effort)
so operators can register an app-owned template for reliable, branded
rendering. Skill docs updated with the developer-console path.
2026-06-10 21:18:45 +08:00
shangguanxuan.sgx 9f744caafd chore(config): default mcp endpoint to prepub 2026-06-10 21:07:13 +08:00
InternZzp 532fcb4874 fix: stabilize direct runtime endpoint tests 2026-06-10 21:07:03 +08:00
修雨 28d556c5e9 fix(devapp): demote the built-in devapp endpoint to a fallback; gofmt
The hardcoded devapp endpoint was checked BEFORE dynamic registration and
edition static/supplement lookups, short-circuiting every configurable
source — the TestDirectRuntimeEndpoint_Devapp*WithoutRegistry tests encode
the intended priority (built-in = last resort so operators can repoint the
product without a rebuild) and have been failing on the branch. Move the
built-in check after Priority 4; env override > dynamic > PAT > edition >
built-in. Also gofmt two files the Lint job flagged.
2026-06-10 21:02:22 +08:00
修雨 c106de8361 feat(devapp): AI-card replies with thinking/done states and live streaming for robot connect
Bring the official-channel reply experience (hermes/openclaw) to every
stream-bridge channel:

- "🤔Thinking" reaction chip on the user's message while the agent runs,
  swapped to "🥳Done" when the reply lands — the hermes text-emotion contract
  (POST /v1.0/robot/emotion/reply|recall, emotionId 2659900).
- AI-card reply using the openclaw connector's public template + payload
  contract (msgContent + flowStatus state machine). Card templates are
  app-scoped: hermes' own template renders "内容加载失败" for any other app —
  confirmed by live A/B on the same robot.
- Live streaming into the card where the channel CLI supports it (verified
  per CLI): claude/codebuddy stream-json text deltas (thinking deltas
  filtered), qodercli stream-json per-turn snapshots; codex/gemini/opencode
  stay one-shot. Frames are full-content and throttled at 800ms per card.
- --reply-card flag (default on, env DWS_REPLY_CARD=0) with full fallback
  chain: any card failure → plain text/markdown webhook reply; stuck cards
  are best-effort marked failed.
- Deliver responses are checked for business-level failures inside HTTP 200
  ({"result":[{"success":false,...}]} observed live), and every card API
  response body is logged for operability.
- workbuddy persona now forbids tool use: headless codebuddy otherwise
  stalls on permission gates trying to write memory files.
- Skill docs: reply-card flag, version-publish approver-selection workflow
  (check-approval → present approver list to the user → publish --approver).

Known issue under investigation: after a batch of invalid-template test
cards, the reporting device renders all subsequent cards as "内容加载失败"
even though every API call succeeds and identical payloads rendered earlier
the same day — suspected client-side card/template cache poisoning; pending
verification on a second client.
2026-06-10 20:46:38 +08:00
shangguanxuan.sgx 2e11a23381 fix(keychain): add windows storage dir for packaging 2026-06-10 20:44:59 +08:00
InternZzp 2c1be7a8fb docs: document codex robot connect command 2026-06-10 20:44:45 +08:00
shangguanxuan.sgx e637d793b0 fix(pat): verify chmod fallback agent code 2026-06-10 20:40:15 +08:00
shangguanxuan.sgx 864f94e80e docs(skill): add devdoc rag troubleshooting guidance 2026-06-10 20:20:13 +08:00
shangguanxuan.sgx 7f1d36c9ac fix(pat): require yes for batch chmod 2026-06-10 17:25:12 +08:00
shangguanxuan.sgx 4eea61897d fix(pat): guard chmod agent code mismatch 2026-06-10 16:48:52 +08:00
john c99ac87839 Merge pull request #3 from PeterGuy326/feat/devapp-robot-connect
feat(devapp): robot connect — 建联收口进 devapp 指令集(渠道感知 Stream 转发)
2026-06-10 12:08:52 +08:00
修雨 1b3319603d fix(devapp): surface Stream SDK connection lifecycle on stderr
The SDK's default logger is a doNothingLogger, so the connector printed
nothing on connect/reconnect/read errors — a dead connection was
indistinguishable from a healthy idle one. Wire an ILogger that writes
Info/Warning/Error to stderr (debug frames stay silent). Verified live:
'[stream] connect success, sessionId=...' now appears at startup.
2026-06-10 12:08:15 +08:00
修雨 995d490a76 feat(devapp): give robot connect session memory, model and workdir tuning
Users reported the linked bot feels dumb. Root cause: the forwarder was
hard-pinned to a stateless one-shot haiku run from an empty directory. Expose
the trade-offs as command-set flags instead of hardcoding them:

- --agent-memory (default on): per-conversation session resume. First message
  of a DingTalk conversation mints a UUID and passes `--session-id`,
  follow-ups pass `--resume`, so multi-turn context survives. Only on CLIs
  with addressable sessions (claudecode/codebuddy/workbuddy — verified against
  their --help); qodercli has --resume but no --session-id, so the qoder
  family stays stateless. Broken sessions self-heal: on forward error the
  conversation mapping is dropped and the next message starts fresh.
- --agent-model / DWS_AGENT_MODEL: override the channel CLI's model via each
  spec's model flag (replaces claudecode's built-in haiku pin in place).
- --agent-workdir / DWS_AGENT_WORKDIR: run the agent from a knowledge
  directory for context, instead of the clean temp dir (which stays the
  default to keep cold-start inside DingTalk's reply window).

A DWS_AGENT_CMD override disables flag splicing entirely — that argv is
user-owned and we cannot know which flags it accepts. Dry-run now previews
the effective agent tuning (model/workdir/memory) per channel.
2026-06-10 11:24:54 +08:00
修雨 5a401ddc1b fix(skill): detect ~/.qoder and ~/.qoderwork in skill setup, add qoderwork install path
Ported from PR #407: `robot connect` supports the qoder/qoderwork channels,
but skill setup neither probed ~/.qoder / ~/.qoderwork in its all-targets
checklist nor knew a qoderwork install path, so Qoder/QoderWork hosts missed
the skill routing. Consistency is enforced by TestAgentSkillPathsCoversSetupHomes.
2026-06-10 10:29:27 +08:00
修雨 f5bdb7118a feat(devapp): add robot connect to fold bot linking into the devapp command set
Bring the channel-aware Stream linking ("建联") from PR #407 into the devapp
command tree as `dws devapp robot connect`, so the full lifecycle
(create app -> create robot -> link to a local agent) lives under one
`dws devapp` domain instead of a separate `dws connect` command.

- Reuse, not duplicate: provisioning ("建号") stays on devapp's existing
  `robot create/submit/result`; this commit ports only the linking half.
- connect_stream.go: the Go-native in-process Stream forwarder + channel
  agent registry, ported verbatim from #407 (package helpers, self-contained).
- devapp_connect.go: trimmed channel routing (resolveConnectChannel /
  launchConnector / buildConnectPlan / ...) plus the new subcommand. The
  standalone `connect` cobra command, `connect start` and `connect bot create`
  are intentionally NOT brought over — the capability is consolidated under
  `dws devapp robot`.
- Credentials: `--robot-client-id` / `--robot-client-secret` for an existing
  robot, or `--unified-app-id` to auto-fetch via devapp's credentials get.
  The flags are named `robot-client-*` (not `client-id`/`client-secret`) to
  avoid shadowing the global OAuth client-override persistent flags.
- Adds the dingtalk-stream-sdk-go v0.9.1 dependency.
- Skill docs (devapp.md, robot.md mono+multi) document `robot connect`.

Known follow-up (marked in code + docs): the get_open_dev_app_credentials
response field names used by `--unified-app-id` auto-fetch are not yet
confirmed against the real gateway; the path degrades safely (empty -> fall
back to explicit flags) and must be verified against pre-prod before relying
on it.
2026-06-10 10:06:31 +08:00
shangguanxuan.sgx 4c86a9f8e1 fix(pat): carry agentCode in batch auth args 2026-06-10 09:49:53 +08:00
玉澜andClaude Opus 4.6 3117ad5d86 fix: restore credentials-webapp.md name, add gitignore exception
Add `!**/credentials-webapp.md` to .gitignore so the skill reference
doc is not blocked by the `credentials*` rule. Revert the cred-webapp
rename from the previous commit.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-09 17:35:09 +08:00
玉澜andClaude Opus 4.6 0e484bb189 fix: rename credentials-webapp.md to cred-webapp.md to avoid gitignore
.gitignore rule `credentials*` was blocking the file from being tracked.
Rename to cred-webapp.md, update SKILL.md links, and fix workflows.md
stale text (version is now implemented, only event remains pending).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-09 17:31:18 +08:00
wxianfeng de4a292174 devapp robot version 2026-06-09 15:58:01 +08:00
玉澜andClaude Opus 4.6 ad43e1ba28 docs: add pagination (--limit/--offset) to permission list skill docs
Permission list can return 150+ items. Document --limit and --offset
for paging across all three skill locations (standalone, multi, mono).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-09 15:43:37 +08:00
InternZzp ac825ad293 fix(devapp): use placeholders in security examples 2026-06-09 14:17:00 +08:00
玉澜andClaude Opus 4.6 8411211a8c docs: complete workflows.md with all 17 commands verified
Add missing flows: webapp get verification, member list/remove,
security config. All 17 devapp commands now E2E verified:
- member list/add/remove: tested on PR407验收 app
- security config: IP whitelist tested
- webapp get: verified returns after config

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-09 14:02:34 +08:00
玉澜andClaude Opus 4.6 449d731239 docs: refactor devapp skill to progressive layered structure
Restructure all three devapp skill locations (standalone, multi, mono)
from monolithic flat docs into progressive layered references:
- SKILL.md: lean routing entry (45 lines vs 325 before)
- references/app-crud.md: list/get/create/update/inactive/active/delete
- references/credentials-webapp.md: credentials get, webapp get/config
- references/permissions.md: permission list/add/remove
- references/member-security.md: member list/add/remove, security config
- references/workflows.md: end-to-end operational flows

Also adds inactive/active commands missing from prior skill docs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-09 13:59:15 +08:00
玉澜andClaude Opus 4.6 13d77ee7b7 feat: add credentials get command and hardcode devapp endpoint
- Add `dws devapp credentials get` helper command calling
  `get_open_dev_app_credentials` MCP tool
- Hardcode devapp endpoint to pre-mcp-gw.dingtalk.com/server/op-app
  in direct_runtime.go (same pattern as robotCreate in PR 407)
- Update docs/skills from "Pending" to "Implemented" for credentials
- Remove obsolete showSecret/confirmSecret references
- Expand lifecycle tests to table-driven covering delete/inactive/active

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-09 13:40:33 +08:00
InternZzp 694288cfbc feat(devapp): guard member and security writes 2026-06-09 10:41:19 +08:00
玉澜 6f5a0afdf7 docs: sync devapp webapp skill guidance 2026-06-08 20:48:40 +08:00
玉澜 248c6602ac Merge remote-tracking branch 'origin/feat/dws-devapp' into feat/dws-devapp
# Conflicts:
#	docs/devapp-yulan-command-routing.md
#	skills/mono/references/products/devapp.md
#	skills/multi/dingtalk-devapp/SKILL.md
#	skills/multi/dingtalk-devapp/references/devapp.md
2026-06-08 19:32:57 +08:00
玉澜 9589c23796 feat: complete devapp command routing 2026-06-08 19:07:30 +08:00
玉澜 9460437c9a test: add ambiguous app routing cases 2026-06-08 17:53:16 +08:00
玉澜 34d691906e test: cover devapp intent disambiguation 2026-06-08 17:53:16 +08:00
玉澜 a78765bb42 docs: clarify devapp branch status 2026-06-08 17:53:16 +08:00
玉澜 836f5bdb25 feat: add devapp command routing design 2026-06-08 17:53:16 +08:00
修雨 3282957958 Revert "fix(cli): JSON errors to stdout; no interactive confirm on piped stdin (#413)" (#415)
This reverts commit f826375556.
2026-06-08 17:53:16 +08:00
xuanandshangguanxuan.sgx 252c61aff6 fix(pat): pass agent code to chmod batch tools (#414)
Co-authored-by: shangguanxuan.sgx <shangguanxuan.sgx@alibaba-inc.com>
2026-06-08 17:53:16 +08:00
修雨 ffefc53861 fix(cli): JSON errors to stdout; no interactive confirm on piped stdin (#413)
- printExecutionError: in JSON mode emit the structured error to stdout
  (not stderr) so machine consumers parsing stdout get a parseable result;
  update the 3 root_execute tests to assert the new contract.
- requireYesForDelete prompt: when stdin is not a TTY (piped/scripted/JSON
  pipelines), do not show an interactive confirm that emits non-JSON and
  blocks on stdin; return a structured validation error requiring --yes.
2026-06-08 17:53:16 +08:00
InternZzp 8cbc56edd2 feat: add devapp helper commands 2026-06-08 17:24:59 +08:00
shangguanxuan.sgx fc0873b0c6 docs,test(pat): carry chmod batch auth updates 2026-06-08 15:36:57 +08:00
玉澜 eea85bd989 test: add ambiguous app routing cases 2026-06-05 17:08:55 +08:00
玉澜 43560afa78 test: cover devapp intent disambiguation 2026-06-05 16:30:12 +08:00
玉澜 7ef46c1288 docs: clarify devapp branch status 2026-06-05 16:20:38 +08:00
玉澜 08413a6903 feat: add devapp command routing design 2026-06-05 16:12:17 +08:00
玉澜 c488421423 Merge remote-tracking branch 'upstream/main' into feat/dws-devapp 2026-06-05 15:46:45 +08:00
wxianfeng b3e8783c4f Merge remote-tracking branch 'upstream/main' 2026-06-04 18:01:41 +08:00
wxianfeng 1c2c96617a Merge remote-tracking branch 'upstream/main' 2026-06-03 20:21:59 +08:00
wxianfeng 5fe366eddd fix conflict 2026-06-03 20:21:54 +08:00
wxianfeng a7d109384b merge upstream 2026-06-03 19:14:19 +08:00
shangguanxuan.sgx 9e7e7dbc7f Merge remote-tracking branch 'upstream/main'
# Conflicts:
#	.github/badges/coverage.svg
2026-06-02 21:30:14 +08:00
shangguanxuan.sgx 7652bda320 fix(pat): align chmod session env handling 2026-06-02 20:38:38 +08:00
shangguanxuan.sgx dd1c4e34fd chore(config): use public example MCP override URL 2026-06-02 16:01:38 +08:00
shangguanxuan.sgx e653616aa3 fix(pat): align dry-run session and schema docs 2026-06-02 14:56:23 +08:00
shangguanxuan.sgx 3ce64db2fc fix(pat): preserve batch session metadata 2026-06-02 14:36:59 +08:00
github-actions[bot] 4bbd52fc58 chore: update coverage badge [skip ci] 2026-06-02 01:38:39 +00:00
shangguanxuan.sgx 9eb3099881 feat(pat): summarize chmod output by default 2026-06-02 09:36:24 +08:00
github-actions[bot] 73e2de7fe8 chore: update coverage badge [skip ci] 2026-06-01 14:18:49 +00:00
shangguanxuan.sgx 8b4f05e44e Merge release/v1.0.29 into main 2026-06-01 22:09:55 +08:00
shangguanxuan.sgx a7879edca1 feat: infer product grant auth metadata 2026-06-01 21:02:15 +08:00
shangguanxuan.sgx 3f09eb5c0f feat: surface tool auth metadata 2026-06-01 20:50:15 +08:00
shangguanxuan.sgx 202cb509a0 feat: use server default agentCode for chmod 2026-05-29 16:48:09 +08:00
shangguanxuan.sgx dd42fd833b feat(pat): support batch chmod flows 2026-05-29 15:22:00 +08:00
github-actions[bot] b5f241c719 chore: update coverage badge [skip ci] 2026-05-28 04:16:11 +00:00
wxianfeng 4cdc3e7320 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-05-28 12:13:45 +08:00
wxianfeng b558bda6df Merge remote-tracking branch 'upstream/main' 2026-05-28 12:11:15 +08:00
github-actions[bot] 1063a6425d chore: update coverage badge [skip ci] 2026-05-25 06:15:24 +00:00
wxianfeng 0a8517432f Merge remote-tracking branch 'origin/main' 2026-05-25 14:12:18 +08:00
wxianfeng 83bfca8d35 Merge remote-tracking branch 'upstream/main' 2026-05-25 14:09:29 +08:00
github-actions[bot] 9e58a062f8 chore: update coverage badge [skip ci] 2026-05-25 06:06:21 +00:00
wxianfeng aa06d9d5c9 Merge remote-tracking branch 'upstream/main' 2026-05-12 00:06:48 +08:00
wxianfeng bb3d1270b9 Merge remote-tracking branch 'upstream/main' 2026-05-09 11:49:26 +08:00
wxianfeng 7d40210a00 Merge remote-tracking branch 'upstream/main' 2026-05-07 16:45:19 +08:00
wxianfeng ab445813b7 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-04-30 10:20:38 +08:00
wxianfeng 631a3829e4 1.0.19 changelog 2026-04-30 10:20:17 +08:00
github-actions[bot] 88b4f4eeaa chore: update coverage badge [skip ci] 2026-04-30 02:17:55 +00:00
wxianfeng ee8af0c7d0 merge upstream main and fix conflict 2026-04-30 10:15:37 +08:00
github-actions[bot] 4f3501e904 chore: update coverage badge [skip ci] 2026-04-27 16:55:32 +00:00
wxianfeng b0108b9c21 merge upstream main 2026-04-28 00:53:11 +08:00
wxianfeng 4dc79fc931 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-04-26 11:24:22 +08:00
wxianfeng 130387eb36 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-04-24 21:04:30 +08:00
github-actions[bot] 0c2b2b4703 chore: update coverage badge [skip ci] 2026-04-24 13:04:24 +00:00
xianfeng wang fed83761e5 Merge branch 'DingTalk-Real-AI:main' into main 2026-04-24 21:02:19 +08:00
wxianfeng 55eb481899 Merge remote-tracking branch 'upstream/main' 2026-04-24 20:55:47 +08:00
github-actions[bot] eb3eecab1d chore: update coverage badge [skip ci] 2026-04-24 06:51:58 +00:00
wxianfeng 3afbc046d8 Merge remote-tracking branch 'upstream/main' 2026-04-24 14:48:43 +08:00
github-actions[bot] 738b64eaf4 chore: update coverage badge [skip ci] 2026-04-23 03:30:15 +00:00
339 changed files with 46696 additions and 5493 deletions
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="108" height="20" role="img" aria-label="coverage: 57.5%"><title>coverage: 57.5%</title><filter id="blur"><feGaussianBlur in="SourceGraphic" stdDeviation="16"/></filter><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="108" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="61" height="20" fill="#555"/><rect x="61" width="47" height="20" fill="#dd4343"/><rect width="108" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".80" filter="url(#blur)" transform="scale(.1)" textLength="510">coverage</text><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text><text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text><text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".80" filter="url(#blur)" transform="scale(.1)" textLength="370">57.5%</text><text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="370">57.5%</text><text x="835" y="140" transform="scale(.1)" fill="#fff" textLength="370">57.5%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="108" height="20" role="img" aria-label="coverage: 54.2%"><title>coverage: 54.2%</title><filter id="blur"><feGaussianBlur in="SourceGraphic" stdDeviation="16"/></filter><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="108" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="61" height="20" fill="#555"/><rect x="61" width="47" height="20" fill="#dd4343"/><rect width="108" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".80" filter="url(#blur)" transform="scale(.1)" textLength="510">coverage</text><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text><text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text><text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".80" filter="url(#blur)" transform="scale(.1)" textLength="370">54.2%</text><text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="370">54.2%</text><text x="835" y="140" transform="scale(.1)" fill="#fff" textLength="370">54.2%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

+75
View File
@@ -0,0 +1,75 @@
# 把本仓库代码自动镜像到 Gitee,供国内用户访问(raw 脚本入口 + tags)。
# 用 HTTPS + 令牌直接 git push(无需 SSH key),复用已配置的 secret:
# GITEE_TOKEN —— Gitee 私人令牌(勾 projects)
# GITEE_USER —— 令牌所属 Gitee 用户名(用于 https 推送鉴权)
# GITEE_REPO —— "owner/repo",如 DingTalk-Real-AI/dingtalk-workspace-cli
# 未配置 GITEE_TOKEN 时(如 fork)自动跳过,不报红叉。
name: Mirror code to Gitee
on:
push:
branches:
- main
tags:
- 'v*'
schedule:
- cron: '0 18 * * *'
workflow_dispatch:
jobs:
mirror:
runs-on: ubuntu-latest
# GitHub Actions 不允许在 job-level if 直接引用 secrets,故先用 env 暴露再在 step 守卫。
env:
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
GITEE_USER: ${{ secrets.GITEE_USER }}
GITEE_REPO: ${{ secrets.GITEE_REPO }}
steps:
- name: Checkout (full history + tags)
if: env.GITEE_TOKEN != ''
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Push main + tags to Gitee (with README localization)
if: env.GITEE_TOKEN != ''
run: |
set -eu
REMOTE="https://${GITEE_USER}:${GITEE_TOKEN}@gitee.com/${GITEE_REPO}.git"
# 取到 main 与所有 tag(落到 origin/* 与本地 tags,避免推当前分支引用冲突)
git fetch --force --tags origin 'refs/heads/main:refs/remotes/origin/main'
# Gitee 专属分支:在 origin/main 之上叠加一个 README 本地化 commit。
# GitHub 那份 README 不变;只有推往 Gitee 的副本被改写。
git checkout -B gitee-main origin/main
git config user.email "actions@github.com"
git config user.name "github-actions[bot]"
# 1) 安装命令本地化:raw.githubusercontent → gitee raw(国内可达)。
for f in README.md README_zh.md; do
[ -f "$f" ] || continue
sed -i "s#raw.githubusercontent.com/${GITEE_REPO}/main#gitee.com/${GITEE_REPO}/raw/main#g" "$f"
done
# 2) coverage 徽章:仓库内相对路径 svg 在 Gitee 渲染不出来(gitee raw 对 svg
# 返回需签名、会过期的 URL,且 content-type 为 text/plain)。改成 shields.io
# 静态徽章——数值取自仓库 coverage.svg,颜色按覆盖率阈值。
SVG=".github/badges/coverage.svg"
if [ -f "$SVG" ]; then
PCT="$(grep -oE '[0-9]+(\.[0-9]+)?%' "$SVG" | head -1)"
NUM="${PCT%\%}"; INT="${NUM%.*}"
if [ "${INT:-0}" -ge 80 ]; then C=brightgreen; elif [ "${INT:-0}" -ge 60 ]; then C=yellow; else C=red; fi
BADGE="https://img.shields.io/badge/coverage-${NUM}%25-${C}"
for f in README.md README_zh.md; do
[ -f "$f" ] || continue
sed -i "s#\.github/badges/coverage\.svg#${BADGE}#g" "$f"
done
fi
git add README.md README_zh.md 2>/dev/null || true
git commit -m "docs(gitee): localize install commands + coverage badge for Gitee mirror" || true
# 镜像对齐(force:Gitee 始终跟随 GitHub + Gitee 专属 README 本地化)
git push --force "$REMOTE" 'gitee-main:refs/heads/main'
git push --force --tags "$REMOTE"
echo "✅ 已镜像 main(+Gitee README 本地化) + tags 到 Gitee ${GITEE_REPO}"
+28 -1
View File
@@ -12,7 +12,10 @@ permissions:
jobs:
release:
runs-on: ubuntu-latest
timeout-minutes: 30
# 60 (not 30): mirroring every release asset to Gitee is slow; 30 min cut the
# Gitee step off mid-upload on the v1.0.42 release. The Gitee step is now also
# idempotent (re-runs only upload missing assets).
timeout-minutes: 60
steps:
- name: Check out repository
@@ -58,6 +61,28 @@ jobs:
run: |
gh release upload "${{ github.ref_name }}" dist/dws-skills.zip --clobber
- name: Sync release to China OSS mirror
# 自动同步到国内镜像,供 install.sh 的 DWS_RELEASE_BASE 开关消费。
# 脚本自带门控:未配置 OSS_* secret 时优雅跳过,不影响海外发布。
run: ./scripts/release/sync-to-oss.sh
env:
VERSION: ${{ github.ref_name }}
OSS_ACCESS_KEY_ID: ${{ secrets.OSS_ACCESS_KEY_ID }}
OSS_ACCESS_KEY_SECRET: ${{ secrets.OSS_ACCESS_KEY_SECRET }}
OSS_ENDPOINT: ${{ secrets.OSS_ENDPOINT }}
OSS_BUCKET: ${{ secrets.OSS_BUCKET }}
OSS_PREFIX: ${{ secrets.OSS_PREFIX }}
- name: Mirror release to Gitee (China)
# 把 release 附件(二进制/校验和/skills 包)镜像到 Gitee release,供 install.sh
# 的 DWS_GITEE_REPO 开关消费(仓库代码由 Gitee 仓库镜像功能自动同步,附件不在其内)。
# 脚本自带门控:未配置 GITEE_TOKEN / GITEE_REPO 时优雅跳过,不影响海外发布。
run: ./scripts/release/sync-to-gitee.sh
env:
VERSION: ${{ github.ref_name }}
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
GITEE_REPO: ${{ secrets.GITEE_REPO }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -65,6 +90,8 @@ jobs:
registry-url: "https://registry.npmjs.org"
- name: Publish to npm
# 只有官方仓库发 npm;fork(dev 预览)没有 NPM_TOKEN,跳过以免红叉
if: ${{ github.repository_owner == 'DingTalk-Real-AI' }}
working-directory: dist/npm/dingtalk-workspace-cli
run: npm publish --access public
env:
@@ -0,0 +1,49 @@
name: Sync release to Gitee
# Manually mirror a published GitHub release's assets to the matching Gitee
# release. Use this to repair a release whose Gitee mirror is incomplete (e.g.
# the Release job timed out mid-upload). It runs ONLY the idempotent Gitee sync
# step — it does not run GoReleaser and does not touch the GitHub release, so
# there is no release outage. The sync script skips assets already on Gitee, so
# this only uploads what is missing.
on:
workflow_dispatch:
inputs:
version:
description: "Release tag to mirror to Gitee (e.g. v1.0.42)"
required: true
type: string
permissions:
contents: read
jobs:
sync-gitee:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Download GitHub release assets
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -eu
mkdir -p dist
gh release download "${{ inputs.version }}" \
--repo "${{ github.repository }}" \
--dir dist \
--pattern 'dws-*' \
--pattern 'checksums.txt' \
--clobber
ls -la dist
- name: Mirror release to Gitee (China)
# Idempotent: uploads only assets not already present on the Gitee release.
run: ./scripts/release/sync-to-gitee.sh
env:
VERSION: ${{ inputs.version }}
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
GITEE_REPO: ${{ secrets.GITEE_REPO }}
+8
View File
@@ -26,6 +26,7 @@ test/cli_compat/testdata/
*.pem
*.key
credentials*
!skills/**/credentials.md
plans
_docs
dws.zip
@@ -34,3 +35,10 @@ dws.zip
# envelope/discovery.pre.json synced via Portal, not git-tracked
/envelope/discovery.pre.json
# local/pre-release MCP service configs may contain personal gateway keys
/docs/mcp/serviceconfig-pre*
# 功能测试运行产物
results.jsonl
test/dev_functional/results.jsonl
+2 -1
View File
@@ -64,7 +64,8 @@ changelog:
release:
github:
owner: DingTalk-Real-AI
# 用当前运行 CI 的仓库 owner: fork CI 发到 fork, 官方 CI 发到官方, 两边都对
owner: "{{ .Env.GITHUB_REPOSITORY_OWNER }}"
name: dingtalk-workspace-cli
draft: false
prerelease: auto
+97
View File
@@ -6,6 +6,103 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/) and th
## [Unreleased]
### Added
- **`dingtalk-dev` skill: image-upload → `mediaId` recipe + per-resource command discovery** (`skills/multi/dingtalk-dev/references/`) — documents how to obtain a `mediaId` for app / robot icons via the DingTalk OpenAPI (`credentials get` → `gettoken` → `/media/upload?type=image` → `--icon-media-id` → read back), since the dev command set has no upload command; and adds a "discovering commands" block to all 10 product refs pointing at each group's `--help` and `dws schema dev.app.<group>.<method>` (`dws schema dev.connect` for connect), so agents inspect commands instead of relying on memory.
## [1.0.43] - 2026-06-26
This release aligns the open edition's CLI surface with **dws-wukong** across the communication domain (chat / mail / minutes / todo / calendar / contact / aisearch / live / report / ding) and the structured-office domain (aitable / sheet / drive / wiki / doc), and switches the discovery version code from `bamboo` to `cedar` so the aligned command tree is served from its own discovery config.
### Added
- **`calendar book get|search` and `calendar acl list`** (cedar discovery overrides) — query a specific calendar (primary via `--id primary`), fuzzy-search calendars by name, and list a calendar's access-control entries. Maps to the calendar MCP `get_calendar` / `search_calendar` / `list_acls` tools.
- **`calendar attendee list|add|delete`** (`internal/helpers/calendar_commands.go`) — manage event participants under the wukong-aligned `attendee` naming (equivalent to the legacy `participant` group; calls `get/add/remove_calendar_participant`).
- **`minutes tag list` and `minutes tag query --tag-id`** — list a user's AI-minutes tags and query minutes by tag (`query_user_tag_list` / `query_minutes_by_tag_id`).
- **`minutes list mine|shared|all`** (`internal/helpers/minutes_commands.go`) — list own / shared / all minutes with renamed output fields.
- **`mail folder create|update|delete`, `mail template create|list|get|update|delete`, `mail contact create|list|update|batch-delete`, and `mail message list`** — full mail folder / message-template / contact CRUD plus folder-scoped message listing.
- **`chat file upload`** (`internal/helpers/chat_file.go`) — upload a local file (init/PUT/commit) or a remote URL to a conversation's file space.
- **`todo task add-attachment`** (`internal/helpers/todo_commands.go`) — attach a local file to a todo (multi-step upload).
- **aitable extensions** (`internal/helpers/aitable_extra.go`) — advanced permission / roles, view sub-commands (lock / duplicate / frozen-cols / row-height / fill-color-rule / card / timebar), section node management, workflow enable/disable, record `upsert` / `share-url` / `history-list` / primary-doc, and field search-options. Helper tools route to the hardcoded `aitable-helper` supplement endpoint.
- **sheet, drive, wiki, doc helper coverage** synced from dws-wukong (`internal/helpers/sheet.go`, `drive.go`, `wiki.go`, `doc.go`).
### Changed
- **Discovery version code `bamboo` → `cedar`** (`internal/market/registry.go`; `discoveryAPIPath = "/cli/discovery/apis/cedar"`) — version codes step by first letter (bamboo → cedar → …); `cedar` carries the dws-wukong alignment. Older binaries keep reading `bamboo`, so the change is isolated to this release line. All test/mock/generator fixtures updated to the cedar path.
- **CLI output envelope aligned with wukong for cross-edition parity** (`internal/app/runner.go`, `internal/compat/registry.go`) — dry-run prints a `DRY-RUN Arguments:` line, successful results carry `success: true`, missing-required-flag wording is unified to `missing required flag(s): --x`, and OutputTransform applies to the response content layer.
- **New flag transforms** (`internal/compat/transform.go`) — `parse_bool` (explicit boolean strings so `--flag false` is honoured) and `attendance_class_check_time` (`HH:mm` → UTC+8 milliseconds for shift check-times).
- **`--calendar-id` accepted on calendar event / participant / room / attachment commands** so calendars other than the primary can be targeted.
### Fixed
- **Client-side validation** for calendar recurrence completeness and attendance schedule / class / group inputs, surfacing input errors before they reach the server.
## [1.0.42] - 2026-06-25
This release rounds out `dws dev connect` — bridge a DingTalk robot to your local AI (Claude Code / Codex / opencode / Qoder / …): a generic `custom` channel for any headless CLI tool, in-chat `/new` / `/clear` session commands aligned to each agent's real session op, and a fix for long opencode turns being cut at 30 seconds.
### Added
- **`dws devapp robot connect` — generic `custom` channel for self-built / unsupported AI tools** (issue #37; `internal/helpers/devapp_connect.go`, `internal/helpers/connect_stream.go`) — a new `--agent-cmd "<command>"` flag (and `custom` channel) lets the bot forward to any headless AI CLI that takes a question as its trailing argument and prints the answer to stdout, so tools that aren't built-in (e.g. 网易有道龙虾 LobsterAI) or self-built agents can be onboarded without code changes. `--agent-cmd` forces the `custom` channel unless `--channel` is set explicitly; detection also falls back to `custom` when `DWS_AGENT_CMD` is present.
### Changed
- **`robot connect` now hints how to match terminal answer quality** (issue #39; `internal/helpers/devapp_connect.go`) — when neither a work dir nor a knowledge source is configured, the connector prints a one-time note that the bot runs in a clean temp dir without local project context, pointing at `--agent-workdir` / `--knowledge-dir` / `--knowledge-source` / `--agent-model`. The robot quickstart gains matching FAQ entries, plus a clarification that step 3 (`robot connect`) produces no approval ticket (issue #19).
- **`robot connect` session commands `/new` vs `/clear` now use each channel's real session op** (PR #20; `internal/helpers/connect_opencode.go`, `internal/helpers/connect_stream.go`) — `/new` (and `/start`, `/reset`) opens a fresh session and leaves the previous one intact (resumable where the agent supports it); `/clear` actively disposes the current session through the agent's real delete primitive — opencode issues `DELETE /session/:id`. Channels whose agent exposes no delete in the mode DWS drives it (Codex app-server, Qoder stream, Claude-family exec) fall back to a reset, so `/clear` behaves like `/new` there. Previously both commands only dropped the local `conversationId → sessionId` mapping, so the two were indistinguishable and opencode sessions were never disposed (they leaked).
### Fixed
- **`robot connect` no longer aborts long opencode turns at 30 seconds** (PR #19; `internal/helpers/connect_opencode.go`) — the shared opencode HTTP client hard-coded a 30s `Timeout` that covered every request, including `POST /session/{id}/message`, so a long agent turn (e.g. a multi-minute research report) was killed mid-flight with `context deadline exceeded (Client.Timeout exceeded while awaiting headers)` even though the per-turn budget (`DWS_AGENT_TIMEOUT_MS`, default 300s) was far larger. The client-level deadline is removed so the per-request ctx governs the round-trip; only the `/global/health` probe keeps a short 10s timeout so startup detection stays snappy.
## [1.0.41] - 2026-06-24
This release makes the installers work from mainland China out of the box (no env var) and keeps the Gitee mirror in sync automatically.
### Added
- **Auto-fallback to the Gitee mirror when GitHub is unreachable** (#492; `scripts/install.sh`, `scripts/install.ps1`, `scripts/install-skills.sh`) — the installers probe GitHub Releases on startup and, when it is unreachable (typical in mainland China), automatically resolve the version and download every asset (binary, `checksums.txt`, `dws-skills.zip`) from the Gitee mirror instead. A plain `curl … | sh` now works in China with no `DWS_GITEE_REPO` needed. Explicit `DWS_GITEE_REPO` still wins, `DWS_NO_FALLBACK=1` forces GitHub, and local source-checkout installs skip the probe.
### Changed
- **CI mirrors repo code to Gitee automatically** (#493; `.github/workflows/mirror-to-gitee.yml`) — the mirror workflow now pushes `main` + tags to the Gitee mirror over HTTPS using `GITEE_TOKEN` (no SSH key), on every push to `main` and every tag, keeping the Gitee `raw/main` install scripts and tags in sync without any manual `git push`. Gated on `GITEE_TOKEN`; skips cleanly when unset.
## [1.0.40] - 2026-06-24
This release adds China-accessible install mirrors so the CLI installs reliably from mainland China, where GitHub raw + Releases are slow or fail.
### Added
- **China mirror via Gitee + npmmirror** (#486; `scripts/install.sh`, `scripts/install.ps1`, `scripts/install-skills.sh`, `scripts/release/sync-to-gitee.sh`, `.github/workflows/release.yml`, `.github/workflows/mirror-to-gitee.yml`) — an opt-in `DWS_GITEE_REPO` env var makes all three installers resolve the latest version and every release asset (binary, `checksums.txt`, `dws-skills.zip`) from the Gitee OpenAPI v5 instead of GitHub; with it unset, installation defaults to GitHub (fully backward compatible). The release pipeline mirrors release attachments to the matching Gitee release after each tag (gated on `GITEE_TOKEN`/`GITEE_REPO`), and a hub-mirror workflow keeps the repo code in sync (gated on `GITEE_PRIVATE_KEY`). README documents three China install channels: Gitee raw script, Gitee release binaries, and the npm package via `registry.npmmirror.com`.
- **Skills embedded in the binary** (#488; `skills_embed.go`, `internal/app/skill_setup.go`, `internal/app/skill_setup_embed.go`) — the `skills/` tree (mono + multi) is embedded into the `dws` binary via `go:embed` and `dws skill setup` defaults to the embedded copy, refreshing the installed skill instead of silently reusing a stale copy probed from the current working directory — so skills install offline with no separate download.
## [1.0.39] - 2026-06-18
This release makes the AI-sent indicator opt-in. 1.0.38 unconditionally tagged every user-identity send/reply with the edition claw identity, so the IM server rendered a "Send from AI" badge under every message — and on the open edition a stale hardcoded value even leaked the Wukong-branded label (「悟空AI发送」) to external users. The badge is now off by default and shown only when the caller explicitly asks for it.
### Added
- **`--ai-tag` opt-in flag for `chat message send` / `chat message reply`** (#477; `internal/helpers/chat.go`) — by default no `clawType` tool argument is attached, so delivered messages carry no "Send from AI" badge. Passing `--ai-tag` attaches `edition.ClawType()` so the IM server renders the badge (open edition `openClaw` → 「通过AI发送」; the wukong overlay sets its own value → 「悟空AI发送」). Covers the text/Markdown, rich-media, and `--user`/`--open-dingtalk-id` direct send paths plus `reply`. Bot (`send-by-bot`) and webhook sends are intentionally untouched — they already render as bot messages. The badge is opt-in so dws does not brand every message a user sends.
### Fixed
- **`dws chat message reply` no longer leaks the Wukong AI label on the open edition** (#475, fixes #474; `internal/helpers/chat.go`, `pkg/edition/edition.go`) — the reply path hardcoded `clawType: "wukong"`, so open-source quoted replies were tagged 「悟空AI发送」 by the IM server, leaking Wukong branding to external users (reported by an external customer integrating via openclaw). The value now derives from the edition via the new `edition.ClawType()` accessor (open → `DefaultOSSClawType` = `openClaw`), and — together with #477 — is only attached when `--ai-tag` is passed. The earlier fix existed on a branch (PR #450) but was never merged to main; #475 cherry-picked it.
## [1.0.38] - 2026-06-16
This release adds client-side agent attribution for usage stats, fixes two commands that silently misbehaved (`dws sheet export` hanging, `dws upgrade --dry-run` actually upgrading), hardens the document write path against server-rejected characters, and makes the long-broken `--no-browser` login flag actually work.
### Added
- **Client-side `agent_code` detection + per-channel agent instance id for usage stats** (#467; `internal/auth/agent_code_detect.go`, `internal/auth/identity.go`, `docs/agent-code.md`) — every MCP request now carries `x-dingtalk-dws-agent-code` (which agent host is driving dws — e.g. `claudecode` / `codex` / `qoder` / `cursor` / `hermes` / `openclaw`, falling back to `custom`), `x-dws-agent-instance-id` (a per-machine×channel id, `dwsa_<base62(sha256(machineId|agent_code))>`), the existing machine-level `x-dws-agent-id`, and `X-Cli-Version`. Detection is a confidence ladder, each signature verified on real hosts / official docs (never guessed; anything unrecognized resolves to `custom`): T0 explicit `DINGTALK_DWS_AGENTCODE`, T1 per-agent env signatures, T2 `VSCODE_BRAND` covering the whole VS Code fork family, T3 the macOS `__CFBundleIdentifier` map, T4 `custom`. `identity.json` migrates v1 → v2 transparently and keeps `x-dws-agent-id` machine-level for continuity. **Trust boundary:** `agent_code` and both ids are client self-reported and forgeable — they are for stats / observability only and must not be used for auth, authorization, rate-limiting, billing, or revocation. Server-side gateway work (header passthrough allowlist + logging the fields into the warehouse) is required before the data lands and is tracked separately.
### Fixed
- **`dws sheet export` no longer hangs for the full ~5-minute poll timeout** (#462; `internal/compat/pipeline.go`) — the pipeline poll loop compared the API status against `pollUntilValue` with case-sensitive `==`, but the API returns `"success"` while the pipeline config declares `"SUCCESS"`, so the match never fired and the loop spun until timeout. Switched to `strings.EqualFold`, aligning with the case-insensitive `normalizeAsyncStatus` helper already used for `doc export` / `aitable export`.
- **`dws upgrade --dry-run` now previews instead of performing a real upgrade** (#416, fixes #364; `internal/app/upgrade.go`) — `newUpgradeCommand` registered no `--dry-run` flag and never read the global persistent one, so `--dry-run` fell through and ran a real, irreversible upgrade (download + binary replace), directly contradicting the flag's documented `预览操作内容,不实际执行` contract. It now resolves the target release and platform asset (so "already latest" / "no build for this platform" is still surfaced), prints the 1–5 steps it *would* perform via the side-effect-free `writeDryRunPlan`, and returns before any backup / download / replace. Covered by `TestWriteDryRunPlan_*` and an updated help test.
- **`dws doc create` / `dws doc update` strip server-rejected characters instead of failing** (#465; `internal/helpers/doc.go`, `internal/helpers/doc_jsonml.go`) — the Markdown write path sent raw content straight through, and the dangerous-Unicode strip only ran on the JSONML branch, so content carrying C0 control characters (anything `< 0x20` except `\t` / `\n`), DEL (`0x7F`), or zero-width / line-separator codepoints (`U+200D`, `U+2028`, `U+2029`) — common in LLM-generated or copy-pasted text — was rejected by the server-side `RejectControlChars` validator and the command failed. `stripDocDangerousUnicode` is renamed to `stripDocInputUnsafe`, extended to match the authoritative `apiclient.rejectDangerousChars` set, and applied on both the Markdown and JSONML node write paths. Tab and newline are preserved. Ported from dws-wukong.
- **`dws auth login --no-browser` is now honored** (#365; `internal/app/auth_command.go`, `internal/auth/device_flow.go`, `internal/auth/oauth_provider.go`) — the flag was already defined (and hidden) but never wired to the login providers, so the browser always opened regardless. The value is now passed into `DeviceFlowProvider.NoBrowser` / `OAuthProvider.NoBrowser` and gates the `openBrowser` call; the flag is also unhidden so headless / remote sessions can discover it.
## [1.0.37] - 2026-06-11
This release realigns the npm channel and hardens PAT batch grants. Background on the npm realignment: 1.0.36 was re-cut on GitHub on 2026-06-11 to fold in the canonical-tree poisoned-cache guard (#454), but the npm registry permanently forbids republishing a version number, so the npm package stayed on the original, unguarded cut. 1.0.37 is therefore the first version where **every** distribution channel — GitHub releases, `dws upgrade`, the install scripts, and npm — ships the same guarded build. If you installed 1.0.36 from npm, upgrade to this version.
+61 -11
View File
@@ -113,6 +113,36 @@ cp dws ~/.local/bin/ # install to PATH
</details>
## China mirror
For users in mainland China, the following channels avoid GitHub network issues. By default (without setting these environment variables) the installer pulls from GitHub.
**1. Install script + pre-built binary (Gitee mirror):**
Repository mirror: `https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli`
```bash
DWS_GITEE_REPO=DingTalk-Real-AI/dingtalk-workspace-cli curl -fsSL https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli/raw/main/scripts/install.sh | sh
```
> With `DWS_GITEE_REPO` set, the installer resolves the latest version and every release asset (binary, checksums, skills) from the Gitee API instead of GitHub. If it is unset, installation defaults to GitHub.
**2. npm package (npmmirror mirror):**
```bash
npm install -g dingtalk-workspace-cli --registry=https://registry.npmmirror.com
```
> npmmirror automatically syncs public packages from the public npm registry, so this works directly in China.
**3. Skills only (Gitee mirror):**
```bash
DWS_GITEE_REPO=DingTalk-Real-AI/dingtalk-workspace-cli curl -fsSL https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli/raw/main/scripts/install-skills.sh | sh
```
> With `DWS_GITEE_REPO` set, `install-skills.sh` resolves the version and skills package from Gitee; it also auto-falls back to the Gitee mirror when GitHub is unreachable.
## Upgrade
> Requires **v1.0.7** or later. For earlier versions, please re-run the [install script](#installation) to upgrade.
@@ -277,7 +307,7 @@ dws aitable record query --base-id BASE_ID --table-id TABLE_ID --limit 10
The repo ships a complete Agent Skill system under `skills/`, now organized into two layouts:
- `skills/mono/` — single-skill layout (one `SKILL.md` + `references/products/`), recommended default.
- `skills/multi/` — per-product skills (`dingtalk-aitable/`, `dingtalk-calendar/`, `dingtalk-chat/`, ... 18 products in total), each with its own `SKILL.md`. 🧪 **EXPERIMENTAL / preview — see banner in each multi `SKILL.md` for caveats.**
- `skills/multi/` — per-product skills (`dingtalk-aitable/`, `dingtalk-calendar/`, `dingtalk-chat/`, ... 20 products in total), each with its own `SKILL.md`. 🧪 **EXPERIMENTAL / preview — see banner in each multi `SKILL.md` for caveats.**
After installing, AI tools like Claude Code / Cursor can operate DingTalk directly through natural language:
@@ -287,6 +317,8 @@ curl -fsSL https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace
```
> `install.sh` installs to `$HOME/.agents/skills/dws` (global); `install-skills.sh` installs to `./.agents/skills/dws` (current project).
>
> China users: prefix `DWS_GITEE_REPO` to use the Gitee mirror — see [China mirror](#china-mirror).
**Switching or re-installing with `dws skill setup`:**
@@ -473,31 +505,48 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
</details>
## DingTalk bot — connect a robot to your local AI
`dws dev connect` bridges a DingTalk robot to a local AI CLI (Claude Code / Codex / opencode / Qoder / Gemini, or any tool via `--agent-cmd`): @-mention the bot in a chat and it answers using your local agent, keeping per-conversation multi-turn memory.
```bash
dws dev connect --channel auto --robot-client-id <id> --robot-client-secret <secret>
```
In-chat **session commands** (send the bare command as the whole message — no agent turn, no tokens):
| Command | Effect |
|---------|--------|
| `/new` (aliases `/start`, `/reset`) | Start a fresh session; the previous one is left intact (resumable where the agent supports it) |
| `/clear` | Wipe the current session — disposed through the agent's real session op (opencode issues `DELETE /session/:id`); channels whose agent exposes no delete primitive fall back to a reset |
See [`docs/robot-quickstart.md`](./docs/robot-quickstart.md) for the full 4-step walkthrough (install → create robot → connect → add to a group).
## Key Services
| Service | Command | Commands | Subcommands | Description |
|---------|---------|:--------:|-------------|-------------|
| Contact | `contact` | 15 | `user` `dept` `label` `relation` | Search users by name / mobile / job-number, batch query, departments, labels & roles, person relations, roster profile & dismissions, current user |
| Chat / IM | `chat` (alias `im`) | 65 | `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` | 17 | `event` `room` `participant` `busy` | Events CRUD + suggested times + attachments, meeting room booking, free-busy query, participant management |
| Calendar | `calendar` | 23 | `event` `book` `acl` `attendee` `participant` `room` `busy` `attachment` | Events CRUD + suggested times + attachments, calendar books (get / search / primary via `--id primary`), access-control list, attendee management (wukong-aligned naming, `--calendar-id` aware), meeting room booking, free-busy query |
| Todo | `todo` | 16 | `task` `comment` | Create / list / update / done / get / delete tasks, plus task comments |
| Approval | `oa` | 15 | `approval` | Approve / reject / revoke / redirect tasks, pending / initiated / submitted / executed / cc instances, process forms, comments, 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` | 20 | `create` `submit` `list` `detail` `template` `stats` `inbox` `outbox` `entry` | Create / submit reports, sent & received (inbox / outbox) lists, templates (get / list), statistics, single-entry get |
| AI Tables | `aitable` | 52 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` `form` | 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`); datasheet forms; templates |
| Doc | `doc` | 28 | `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` | 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` | 18 | `mailbox` `message` `draft` `folder` `tag` `thread` `attachment` `user` | List mailboxes, KQL message search, read & send messages, drafts, folders, tags, threads, attachments, address-book user search |
| Sheet | `sheet` | 23 | `range` `filter-view` (top-level: `create` `new` `list` `info` `read` `get` `update` `find` `replace` `append` `merge-cells` `unmerge-cells` `add-dimension` `insert-dimension` `delete-dimension` `move-dimension` `update-dimension` `write-image`) | Online spreadsheet (`contentType=ALIDOC`, `extension=axls`): worksheet CRUD, range read / write / append, dimension ops, cell merge / unmerge, find / replace, named filter views + sheet-level filters, image write |
| Wiki | `wiki` | 21 | `space` `member` `node` `doc` `file` | Knowledge base management: spaces (`create` / `get` / `list` / `search`), members (`add` / `list` / `update`), node tree, docs & files |
| DevDoc | `devdoc` | 2 | `article` `error` | Search Open Platform documentation and troubleshoot API errors |
| AI Tables | `aitable` | 102 | `base` `table` `record` `field` `view` `section` `advperm` `workflow` `dashboard` `chart` `import` `export` `attachment` `template` `form` | Full CRUD for Bases / datasheets / records / fields / views; node (section) management, advanced permission & roles, automation workflows; record upsert / share-url / history / primary-doc; view lock / duplicate / frozen-cols / row-height / fill-color-rule / card / timebar; charts & dashboards; import/export; attachments; forms; templates |
| Doc | `doc` | 29 | `search` `list` `info` `read` `create` `update` `upload` `download` `copy` `move` `rename` `file` `folder` `block` `comment` `permission` `media` | Search / read / write docs, file & folder create, block-level editing, comments (list / create / reply / create-inline), permission management, media, upload / download |
| Drive | `drive` | 17 | `list` `list-spaces` `info` `download` `mkdir` `upload` `upload-info` `commit` `delete` `copy` `move` `rename` `search` `permission` | DingTalk drive file ops: list / search / info / download, create folders, upload (one-shot or two-phase), copy / move / rename, permission management (list / mutation / remove), doc-transfer, delete |
| Minutes | `minutes` | 31 | `list` `get` `tag` `update` `mind-graph` `speaker` `permission` `hot-word` `record` `upload` `replace-text` | List AI meeting notes (mine / shared / all), tags (list / query by tag), details (info / summary / keywords / transcription / todos / batch), title/summary updates, mind map, speaker, member permission, hot-word, recording control, upload session |
| Mail | `mail` | 33 | `mailbox` `message` `send` `draft` `folder` `template` `contact` `tag` `thread` `attachment` `user` | List mailboxes, KQL search + folder-scoped message list, read & send messages, drafts, folder CRUD, message templates (CRUD), mail contacts (CRUD), tags, threads, attachments, address-book user search |
| Sheet | `sheet` | 60 | `range` `filter` `filter-view` `cond-format` (+ dimension, float-image, dropdown, csv, merge, find/replace, write-image, …) | Online spreadsheet (`contentType=ALIDOC`, `extension=axls`): worksheet CRUD, range read / write / copy / fill / sort / style, dimension ops, filters & filter views, conditional formatting, float images, dropdowns, CSV get/put, cell merge / unmerge, find / replace, image write |
| Wiki | `wiki` | 27 | `space` `member` `node` `doc` `file` | Knowledge base management: spaces (create / get / list / search / delete), members (add / list / update / remove), node tree (create / delete / list / search / move / copy / transfer), docs & files |
| DevDoc | `devdoc` | 2 | `article` `error` | Search the DingTalk Open Platform documentation and diagnose API errors |
| AI Search | `aisearch` | 3 | `person` | Enterprise people search by name / department / position / duty / supervisor / subordinate / phone / job-number (single command, multi-dimension filter) |
| 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 |
> **331 commands across 18 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.
> **466 commands across 18 products** (after the dws-wukong alignment in 1.0.43). 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.
@@ -557,6 +606,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
- [Command Index](./docs/command-index.md) — every runtime command with description and when-to-use guidance
- [Reference](./docs/reference.md) — environment variables, exit codes, output formats, shell completion
- [Architecture](./docs/architecture.md) — discovery-driven pipeline, IR, transport layer
- [Open Platform App Command Routing](./docs/dev-yulan-command-routing.md) — yulan dev app command design, MCP overlay, permission flow, and Agent routing
- [Changelog](./CHANGELOG.md) — release history and migration notes
## Contributing
+53 -3
View File
@@ -71,9 +71,9 @@ irm https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace-cli/ma
| 模式 | 安装内容 | 适合场景 |
|------|----------|----------|
| **mono**(稳定,默认) | 一个 `dws` skill,覆盖全部产品 | 跨产品组合操作;单一入口召唤 |
| **multi** 🧪 **试验版 / Preview** | 18 个独立产品 skill(`dingtalk-aitable` / `dingtalk-calendar` / `dingtalk-chat` ...) | 单产品任务;每次召唤上下文更小 |
| **multi** 🧪 **试验版 / Preview** | 20 个独立产品 skill(`dingtalk-aitable` / `dingtalk-calendar` / `dingtalk-chat` ...) | 单产品任务;每次召唤上下文更小 |
> 🧪 **multi 模式当前为 EXPERIMENTAL(试验版 / Preview)**。18 个独立 skill 全部通过 dispatch verifier,但接口、命名、跨 skill 引用后续可能调整。生产 / 共享环境建议优先用 `mono`。问题请提 issue 反馈。
> 🧪 **multi 模式当前为 EXPERIMENTAL(试验版 / Preview)**。20 个独立 skill 全部通过 dispatch verifier,但接口、命名、跨 skill 引用后续可能调整。生产 / 共享环境建议优先用 `mono`。问题请提 issue 反馈。
怎么选:
@@ -113,6 +113,36 @@ cp dws ~/.local/bin/ # 安装到 PATH
</details>
## 国内加速安装
国内用户可使用以下通道,避免 GitHub 网络问题。默认(不设置这些环境变量)走 GitHub。
**1. 安装脚本 + 预编译二进制(Gitee 镜像):**
仓库镜像地址:`https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli`
```bash
DWS_GITEE_REPO=DingTalk-Real-AI/dingtalk-workspace-cli curl -fsSL https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli/raw/main/scripts/install.sh | sh
```
> 设置 `DWS_GITEE_REPO` 后,安装脚本会改从 Gitee API 解析最新版本和各个 release 产物(二进制、校验和、skills 包),而不是走 GitHub。不设置时默认从 GitHub 安装。
**2. npm 包(npmmirror 镜像):**
```bash
npm install -g dingtalk-workspace-cli --registry=https://registry.npmmirror.com
```
> npmmirror 会自动同步公网 npm 的公开包,国内可直接使用。
**3. 单独安装 Skills(Gitee 镜像):**
```bash
DWS_GITEE_REPO=DingTalk-Real-AI/dingtalk-workspace-cli curl -fsSL https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli/raw/main/scripts/install-skills.sh | sh
```
> 同样设置 `DWS_GITEE_REPO`,`install-skills.sh` 会从 Gitee 解析版本和 skills 包;GitHub 不可达时也会自动回退到 Gitee 镜像。
## 升级
> 需要 **v1.0.7** 及以上版本。更早版本请重新执行[安装脚本](#安装)进行升级。
@@ -284,6 +314,8 @@ curl -fsSL https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace
```
> `install.sh` 安装到 `$HOME/.agents/skills/dws`(全局);`install-skills.sh` 安装到 `./.agents/skills/dws`(当前项目)。
>
> 国内用户加 `DWS_GITEE_REPO` 走 Gitee 镜像,见 [国内加速安装](#国内加速安装)。
**用 `dws skill setup` 切换或重装:**
@@ -469,6 +501,23 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
</details>
## 钉钉机器人 —— 把机器人接到你本地的 AI
`dws dev connect` 把一个钉钉机器人接到本地 AI CLI(Claude Code / Codex / opencode / Qoder / Gemini,或用 `--agent-cmd` 接任意工具):群里 @ 机器人提问,它用你本地的 agent 回答,按会话保留多轮上下文。
```bash
dws dev connect --channel auto --robot-client-id <id> --robot-client-secret <secret>
```
聊天里的**会话指令**(整条消息就是指令时生效,不消耗一次 AI 调用):
| 指令 | 作用 |
|------|------|
| `/new`(别名 `/start`、`/reset`) | 开启新会话;旧会话保留(agent 支持的话仍可回溯) |
| `/clear` | 清空当前会话 —— 调 agent 真实会话原语真删(opencode 走 `DELETE /session/:id`);驱动接口没有删除原语的渠道退化为重置 |
完整四步教程见 [`docs/robot-quickstart.md`](./docs/robot-quickstart.md)(装工具 → 建机器人 → 接上 AI → 拉进群)。
## 核心服务
| 服务 | 命令 | 命令数 | 子命令 | 描述 |
@@ -488,7 +537,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
| 邮箱 | `mail` | 18 | `mailbox` `message` `draft` `folder` `tag` `thread` `attachment` `user` | 邮箱地址列表、KQL 邮件搜索、读取与发送邮件、草稿、文件夹、标签、会话、附件、通讯录用户搜索 |
| 在线电子表格 | `sheet` | 23 | `range` `filter-view`(顶层:`create` `new` `list` `info` `read` `get` `update` `find` `replace` `append` `merge-cells` `unmerge-cells` `add-dimension` `insert-dimension` `delete-dimension` `move-dimension` `update-dimension` `write-image`) | 在线电子表格(`contentType=ALIDOC`、`extension=axls`):工作表 CRUD、区域读写/追加、行列操作、合并/取消合并、查找替换、命名筛选视图 + 表级筛选、写入图片 |
| 知识库 | `wiki` | 21 | `space` `member` `node` `doc` `file` | 知识库管理:空间(`create` / `get` / `list` / `search`)、成员(`add` / `list` / `update`)、节点树、文档与文件 |
| 开发者文档 | `devdoc` | 2 | `article` `error` | 搜索钉钉开放平台文档、排查开放平台调用错误 |
| 开发者文档 | `devdoc` | 2 | `article` `error` | 搜索钉钉开放平台文档并排查 API 调用错误 |
| AI 搜问 | `aisearch` | 3 | `person` | 企业人员搜索:按姓名 / 部门 / 职位 / 职责 / 上级 / 下级 / 手机号 / 工号 多维度过滤(单命令) |
| 直播 | `live` | 1 | `stream` | 钉钉直播:查看我的直播列表 |
| Raw API | `api` | 1 | — | 直接调用任意钉钉 OpenAPI(api / oapi 双形态),自动管理应用级 Token |
@@ -555,6 +604,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
- [命令索引](./docs/command-index.md) — 全部运行时命令,带描述与使用场景
- [参考手册](./docs/reference.md) — 环境变量、退出码、输出格式、Shell 补全
- [架构设计](./docs/architecture.md) — 发现驱动管道、IR、Transport 层
- [开放平台应用指令设计](./docs/dev-yulan-command-routing.md) — yulan dev app 应用侧命令、MCP overlay、权限流程与 Agent 路由
- [更新日志](./CHANGELOG.md) — 版本历史与迁移说明
## 贡献指南
+2
View File
@@ -43,6 +43,8 @@ __KEG_ONLY_LINE__
Pathname.new(File.join(Dir.home, ".agents/skills/dws")),
Pathname.new(File.join(Dir.home, ".claude/skills/dws")),
Pathname.new(File.join(Dir.home, ".cursor/skills/dws")),
Pathname.new(File.join(Dir.home, ".qoder/skills/dws")),
Pathname.new(File.join(Dir.home, ".qoderwork/skills/dws")),
Pathname.new(File.join(Dir.home, ".gemini/skills/dws")),
Pathname.new(File.join(Dir.home, ".codex/skills/dws")),
Pathname.new(File.join(Dir.home, ".github/skills/dws")),
+2
View File
@@ -12,6 +12,8 @@ const AGENT_DIRS = [
".agents/skills",
".claude/skills",
".cursor/skills",
".qoder/skills",
".qoderwork/skills",
".gemini/skills",
".codex/skills",
".github/skills",
+93
View File
@@ -0,0 +1,93 @@
# Agent identification (agent_code & agentId)
dws tags every MCP request with **which agent host is driving it** and a
**per-instance id**, so usage can be sliced by channel/instance in the data
warehouse. This page is the integration contract.
## What dws sends on the wire
| Header | Meaning | Granularity |
|--------|---------|-------------|
| `x-dingtalk-dws-agent-code` | which agent host (claudecode / codex / qoder / cursor / custom …) | channel |
| `x-dws-agent-instance-id` | `dwsa_<base62>` derived from `machineId + agent_code` | machine × channel |
| `x-dws-agent-id` | stable per-install machine id (v1-compatible) | machine |
| `X-Cli-Version` | dws CLI version (segments old vs new clients) | — |
`x-dws-agent-id` keeps its original machine-level meaning for backward
compatibility; `x-dws-agent-instance-id` is the new per-channel value. Old
clients send no `agent_code` / instance id — treat their absence as
"legacy/unknown", not an error.
## How `agent_code` is resolved (confidence ladder)
1. **T0 — explicit declaration:** `DINGTALK_DWS_AGENTCODE=<code>`. **Use this.**
2. **T1 — verified env signature:** an agent that auto-sets a distinctive var
(`CLAUDECODE`, `CODEX_SANDBOX`, `OPENCLAW_BUNDLE_ROOT`, `HERMES_HOME`).
3. **T2 — `VSCODE_BRAND`:** every VS Code fork declares its brand — one rule
covers Cursor / Windsurf / Trae / Qoder / Kiro / … incl. future forks.
4. **T3 — macOS `__CFBundleIdentifier`:** known agent app bundles.
5. **T4 — `custom`:** unknown host. Never guessed.
## Declaring your agent (recommended — the only fully-general path)
Auto-detection cannot cover every agent: most terminal agents (gemini/
antigravity, aider, opencode, qwen-code, crush, goose, kimi, amazon-q,
continue, …) expose **no reliable self-identifying env var** — only user-set
API keys, which must not be used as identity. The robust answer is: **the host
sets `DINGTALK_DWS_AGENTCODE` in the env block where it launches dws as an MCP
server.** This is accurate for any agent, on any OS, and is future-proof.
MCP server config example (JSON-style hosts):
```jsonc
{
"mcpServers": {
"dingtalk-workspace": {
"command": "dws",
"args": ["mcp", "..."],
"env": { "DINGTALK_DWS_AGENTCODE": "your-agent-code" }
}
}
}
```
### Canonical codes
`claudecode`, `codex`, `cursor`, `vscode`, `qoder`, `windsurf`, `trae`,
`workbuddy`, `openclaw`, `hermes`, `codebuddy`, `comate`, `lingma`, `gemini`,
`aider`, `opencode`, `goose`, `crush`, `kimi`, `amazonq`, `continue`, …
Use a stable lowercase slug; unknown values are kept as-is (lowercased,
spaces stripped), so a new agent name flows through cleanly.
## Trust & limitations — READ THIS
**`agent_code` AND the ids (`x-dws-agent-id`, `x-dws-agent-instance-id`) are
self-reported, best-effort signals, NOT an authenticated identity.**
- `agent_code`: every declaration/auto-detect signal is an env var the
host/user controls — spoofable (`export CLAUDECODE=1` → dws reports
`claudecode`).
- The ids are **even easier to forge**: they are generated, stored, and sent
entirely client-side. `machineId` is a random UUID in the plaintext
`~/.dws/identity.json` (which the user owns), and the instance id is just
`sha256(machineId + agent_code)`. Editing that one file — or rewriting the
header — lets anyone mint, split, rotate, or impersonate ids at will. The
`dwsa_` prefix does NOT make it a secure identifier.
- ✅ **Fit for statistics / observability** (the intended use): there is no
incentive to misreport one's own agent, and real hosts emit real signals, so
aggregate per-channel metrics are reliable in practice.
- ❌ **NOT fit for authentication, authorization, rate-limiting, billing, or
revocation.** Anything where a party benefits from lying must not trust this
field. For control-plane use you need a gateway-issued **authoritative**
agentId bound to a verified credential (clientId / PAT / OAuth) — a separate,
heavier mechanism, deliberately out of scope here.
Treat `agent_code` / `x-dws-agent-instance-id` as analytics dimensions only.
## Gateway side (required for the data to land)
dws sending the headers is necessary but not sufficient. The gateway must:
1. add `x-dingtalk-dws-agent-code`, `x-dws-agent-instance-id`, `X-Cli-Version`
to the upstream-header pass-through allowlist (otherwise they are stripped);
2. log them as fields, and deliver them to the warehouse (alongside the
existing flow-control / execution logs).
+1 -1
View File
@@ -187,7 +187,7 @@ _Search the DingTalk Open Platform documentation._
| Command | Description | When to use |
|---|---|---|
| `dws devdoc article search` | Search the DingTalk Open Platform documentation by keyword. | When the agent needs authoritative API reference or guides to answer a developer question. |
| `dws devdoc error diagnose` | Troubleshoot an Open Platform API failure by requestId, error code, error message, or context. | When the agent has a requestId, traceId, error code, or failure description and needs diagnostic facts plus references. |
| `dws devdoc error diagnose` | Troubleshoot an Open Platform API failure by requestId, traceId, error code, error message, or context. | When the agent has a requestId, traceId, error code, or failure description and needs diagnostic facts plus references. |
## `dws ding` — DING Messages
+128
View File
@@ -0,0 +1,128 @@
# Running the connector as a 7x24 service
`dws devapp robot connect` keeps a DingTalk robot wired to a local agent over a
Stream long-connection. By default it runs in the foreground and dies when the
terminal closes. For an unattended "digital employee" you have two options.
## Option A: built-in daemon (recommended for a quick start)
```bash
# Detach into a background supervisor that restarts the connector if it crashes.
dws devapp robot connect --daemon \
--channel claudecode \
--robot-client-id <clientId> --robot-client-secret <clientSecret>
# Inspect / stop it.
dws devapp robot connect status --robot-client-id <clientId>
dws devapp robot connect stop --robot-client-id <clientId>
```
- The parent prints the daemon pid and the log path, then exits.
- A supervisor process (POSIX `setsid`, detached from the terminal) keeps a
worker connector alive, restarting it with exponential backoff (1s..60s, up to
10 consecutive fast failures) when it exits abnormally.
- The single-instance lock (one connector per robot per machine) is reused, so a
duplicate daemon refuses to start.
- Logs go to `~/.dws/connect/<clientId>/daemon.log` with size-based rotation
(5 MB x 2 backups), and the pid file lives at
`~/.dws/connect/<clientId>/daemon.pid`.
- The daemon does NOT survive a reboot. For that, use Option B.
> Windows: `--daemon` is not supported (no `setsid` / POSIX signal stop). Use a
> Windows service wrapper around the foreground command instead.
## Option B: OS service manager (survives reboot)
Use the foreground command (NOT `--daemon`) and let the OS supervise and
restart it. This is the most robust way to get boot-time auto-start.
### macOS — launchd
Save as `~/Library/LaunchAgents/com.dingtalk.dws.connect.plist`, edit the paths
and credentials, then `launchctl load -w <path>`.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.dingtalk.dws.connect</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/dws</string>
<string>devapp</string>
<string>robot</string>
<string>connect</string>
<string>--channel</string>
<string>claudecode</string>
<string>--robot-client-id</string>
<string>REPLACE_CLIENT_ID</string>
<string>--robot-client-secret</string>
<string>REPLACE_CLIENT_SECRET</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>ThrottleInterval</key>
<integer>10</integer>
<key>StandardOutPath</key>
<string>/tmp/dws-connect.out.log</string>
<key>StandardErrorPath</key>
<string>/tmp/dws-connect.err.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/local/bin:/usr/bin:/bin</string>
</dict>
</dict>
</plist>
```
`KeepAlive=true` makes launchd restart the connector if it exits; the connector
itself relies on the single-instance lock to avoid duplicates.
### Linux — systemd (user service)
Save as `~/.config/systemd/user/dws-connect.service`, edit paths/credentials,
then:
```bash
systemctl --user daemon-reload
systemctl --user enable --now dws-connect.service
# allow it to keep running after logout:
loginctl enable-linger "$USER"
```
```ini
[Unit]
Description=DWS DingTalk robot connector
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/dws devapp robot connect \
--channel claudecode \
--robot-client-id REPLACE_CLIENT_ID \
--robot-client-secret REPLACE_CLIENT_SECRET
Restart=always
RestartSec=5
# Optional hardening:
# NoNewPrivileges=true
# PrivateTmp=true
[Install]
WantedBy=default.target
```
`Restart=always` + `RestartSec` gives crash recovery; systemd captures stdout/
stderr into the journal (`journalctl --user -u dws-connect -f`).
## Which to choose
- Just need it to outlive the terminal and self-heal on crash → `--daemon`.
- Need it to come back after a reboot, with the OS owning the lifecycle → use
launchd / systemd with the foreground command.
+137
View File
@@ -0,0 +1,137 @@
# dws dev 命令集 · Agent 人肉手工评测集(10 条复合用例)
> 性质:**人肉手工评测集**——由测评人逐条手工跑、肉眼核对、人工判分,不是自动化脚本。
> 用途:评测 agent(加载 `dingtalk-dev` 技能后)能否正确处理开放平台 dev 任务。
> 特点:10 条**复合用例**,每条串多个子任务,一条覆盖一类完整场景;10 条合起来覆盖全部 34 个子命令 + 8 类横切行为。
> 约定:所有命令应带 `--format json`;写操作应先 `--dry-run` 预览、用户确认后再 `--yes`;应用定位只用 `--unified-app-id`。
## 手工评测流程
逐条执行,每条三步:
1. **发起**:在一个干净的 agent 会话里,把该条的「用户说」原样发给 agent(不给额外提示)。
2. **观察**:看 agent 选了哪些命令、什么 flag、做了哪些判断/追问。
3. **判分**:对照「通过判据」人工打分。复合用例含多个判据,**全部满足才记 PASS**;部分满足记 PASS\*(半通过)并在备注写清缺哪条。记一行 `用例# | PASS / PASS* / FAIL | 备注(错在哪)`。
> 「易错点」是常见扣分项,重点盯。建议每次技能改动后整套重跑,对比上次。
## 覆盖矩阵
| 用例 | 覆盖的子命令 | 横切行为 |
|------|-------------|---------|
| C1 建应用配齐基础 | app create / get / credentials get / update | dry-run/yes、定位符、密钥脱敏 |
| C2 列表与定位 | app list | cursor 分页、按名定位、多命中候选 |
| C3 生命周期 | app disable / enable / delete | 写后回读、appStatus、pretty 标签、confirm-name 防误删 |
| C4 网页应用到生效 | webapp get / config | 生效模型(改配置≠生效) |
| C5 版本发布全流程 | version create / list / get / check-approval / publish / status | 生效模型、审批人由用户拍板 |
| C6 权限全流程 | permission list / add / remove | 过滤分页、生效模型、批量聚合出参 |
| C7 成员与安全 | member list / add / remove、security config | 整组覆盖语义 |
| C8 机器人与建联 | robot submit / result / get / config / enable / disable、dev connect | 异步轮询、robot info not exist、建联依赖预检、长驻进程 |
| C9 事件与文档排查 | event list / subscribe / unsubscribe、dev doc search | 错误码透传、文档 RAG |
| C10 意图消歧 | (不进 dev,先澄清) | 泛词边界、转其它技能出口 |
---
## 用例
### C1. 新建应用并配齐基础
- **用户说**:「建一个内部应用叫 DemoApp,描述『内部测试』;建好后给我看看它的详情,把它的 AppKey/AppSecret 也取出来;对了名字再改成 DemoApp2。」
- **覆盖**:`app create` / `get` / `credentials get` / `update`;dry-run/yes、定位符、密钥脱敏。
- **期望(分步)**:
1. `app create --name DemoApp --desc 内部测试 --dry-run` → 给用户看 `invocation.params` 确认 → `--yes`,记下返回的 `unifiedAppId`。
2. `app get --unified-app-id <id> --format json` 看详情。
3. `credentials get --unified-app-id <id> --format json` 取凭证。
4. `app update --unified-app-id <id> --name DemoApp2 --dry-run` → `--yes`。
- **通过判据**:每个写操作先 dry-run 再 yes;全程用 `unifiedAppId` 定位;取凭证走 `credentials get`(不是 app get);`clientSecret/appSecret` 按敏感处理、不明文写进回答。
- **易错点**:不 dry-run 直接 yes;把 secret 打印给用户;用 `app get` 当取凭证。
### C2. 应用列表与按名定位
- **用户说**:「列出我们企业的开放平台应用,一页 20 条,有下一页继续翻;再帮我找名字叫『早晚会』的那个应用,看它详情。」
- **覆盖**:`app list`;cursor 分页、按名定位、多命中。
- **期望(分步)**:
1. `app list --page-size 20 --format json`;出参有 `nextCursor` 则续翻 `--cursor <上次 nextCursor>` 直到为空。
2. `app list --name 早晚会 --format json` 找 `unifiedAppId` → 唯一命中后 `app get --unified-app-id <id>`。
- **通过判据**:首次不传 `--cursor`,续翻原样回传 `nextCursor`,不自己构造/解析、不跨命令复用;用 list 过滤拿 id 再 get;多条命中时展示候选让用户选、不取第一条。
- **易错点**:用 `--page/--offset` 翻页;`app get --name xxx`(get 不接受 name 定位)。
### C3. 应用生命周期(停用 / 启用 / 删除)
- **用户说**:「先把 DemoApp2 停用,确认停好了告诉我;然后再启用回来;最后这个应用不要了,删掉。」
- **覆盖**:`app disable` / `enable` / `delete`;写后回读、appStatus、pretty、confirm-name。
- **期望(分步)**:
1. `disable --unified-app-id <id> --dry-run` → `--yes` → 回读 `app get`(可 `--format pretty` 看 `appStatusText`),确认 `appStatus=0` 才算停用完成。
2. `enable --dry-run` → `--yes` → 回读确认 `appStatus=1`。
3. 删除:先 `app get` 展示摘要 → `delete --dry-run` → 真删需 `--confirm-name <应用真实名>`(与定位到的名一致)+ `--yes`。
- **通过判据**:写成功 ≠ 状态已变,每步回读 appStatus(0停/1激活/2待激活/3过期);删除前展示摘要并让用户确认;confirm-name 匹配才删,读不到应用名时中止(fail-closed)。
- **易错点**:看到 success 就回报已停/已删不回读;不带 confirm-name 直接删。
### C4. 网页应用配置到生效
- **用户说**:「给这个应用配个钉钉里打开的移动端首页 https://example.com/m,配完要真正能用。」
- **覆盖**:`webapp config` / `get`;生效模型。
- **期望(分步)**:`webapp config --unified-app-id <id> --homepage-url https://example.com/m --dry-run` → `--yes` → `webapp get` 回读;明确说明「改配置 ≠ 线上生效,需走版本通道」:`version create → check-approval → publish`(详见 C5)。
- **通过判据**:先 dry-run 再 yes;配完回读 webapp get;主动点明需发版本才生效,不谎称「已生效」。
- **易错点**:配完直接说已生效,不提版本通道。
### C5. 版本发布全流程(含选审批人)
- **用户说**:「我刚改了配置,发个版本上线;先看下历史版本和这次要发的版本详情;需要审批的话我来选审批人。」
- **覆盖**:`version create` / `list` / `get` / `check-approval` / `publish` / `status`;生效模型、审批人由用户拍板。
- **期望(分步)**:
1. `version create --unified-app-id <id> --version <号> --desc <说明> --yes`,记 `versionId`(新应用 `version list` 空时先 create,不要误判无可发布)。
2. `version list` 看历史、`version get --version-id <id>` 看详情。
3. `version check-approval --version-id <id>`(预检,不发布,返回是否需审批 + 候选审批人)。
4. 把候选审批人列表给用户选 → `version publish --version-id <id> --approver <用户选的> --yes`(含高敏权限加 `--confirm-sensitive`)。
5. `version status --version-id <id>` 跟踪到 `versionStatus=RELEASE` 才算生效。
- **通过判据**:check-approval 不实际发布;审批人由用户拍板、agent 不默认取第一个;发布后回读 status 到 RELEASE。
- **易错点**:跳过 check-approval 直接 publish;agent 自己选审批人;version list 空就说没东西可发。
### C6. 权限全流程(查 / 申请 / 批量取消)
- **用户说**:「查下跟『机器人发消息』有关、还没开通的权限;开通其中合适的那个,要真正生效;再把另外两个不需要的权限点 A、B 一起取消掉。」
- **覆盖**:`permission list` / `add` / `remove`;过滤分页、生效模型、批量聚合。
- **期望(分步)**:
1. `permission list --unified-app-id <id> --keyword 机器人发消息 --status UNAUTHED --page-size 50` 找 `scopeValue`(150+ 时用 `nextCursor` 续翻)。
2. `permission add --permissions <scopeValue> --dry-run` → `--yes`;若 `requiredApproval=true`,走版本通道生效(接 C5)。
3. `permission remove --permissions A,B --dry-run` → `--yes`,读出参 `{results, ok, total, failedCount}` 逐条判断。
- **通过判据**:只传 `scopeValue`(不传 API/分组名);用 keyword+status 过滤、分页不漏;需审批的明确走版本;批量取消读 `ok/failedCount` 报告部分失败,不只看命令成功。
- **易错点**:把 API 名当权限点;add 后就说开通了;批量 remove 漏报部分失败。
### C7. 成员与安全配置
- **用户说**:「把 userId 张三、李四加成这个应用的开发者,加完看下成员列表,回头把李四移除;另外给应用加一个登录重定向地址 https://b.example.com/cb,别把原来的地址冲掉。」
- **覆盖**:`member list` / `add` / `remove`、`security config`;整组覆盖。
- **期望(分步)**:
1. `member add --unified-app-id <id> --user-ids 张三id,李四id --member-type DEVELOPER --dry-run` → `--yes` → `member list` 回读 → `member remove --user-ids 李四id --member-type DEVELOPER --dry-run` → `--yes`。
2. 安全配置:提醒 `--redirect-urls` 是**整组覆盖、不是追加**——要保留原地址需把旧+新一起传:`security config --redirect-urls <旧1,旧2,新> --dry-run` → `--yes`。
- **通过判据**:`--user-ids` 逗号分隔、`--member-type` 必填、用 userId 不用姓名;识别整组覆盖语义、避免只传新地址冲掉旧的;未提供的字段(如 ip-whitelist)不动。
- **易错点**:漏 `--member-type`;security 只传新 redirect-urls 把旧的清空。
### C8. 机器人建号、配置与本地建联
- **用户说**:「帮我建一个叫『小助手』的答疑机器人;另外这个现有应用还没机器人,给它也配上并启用;最后把机器人接到我本地的 Claude Code 调试。」
- **覆盖**:`robot submit` / `result` / `get` / `config` / `enable` / `disable`、`dev connect`;异步轮询、robot info not exist、建联依赖预检、长驻进程、密钥脱敏。
- **期望(分步)**:
1. 新建:`robot submit --name <应用名> --robot-name 小助手 --desc <功能> --dry-run` → `--yes`(拿 taskId)→ 按 `intervalSeconds` 轮询 `robot result --task-id <taskId>`,只有 `SUCCESS` 才用返回 `robotCode/clientId/clientSecret`(敏感)。
2. 现有应用:`robot get` 若 `robotStatus=UNCONFIGURED` → `robot config --unified-app-id <id> --name ... --mode STREAM --dry-run` → `--yes`(upsert 首次即创建)→ 回读 `robot get` 看 `robotStatus=ONLINE` → 需要时 `robot enable`(停用 `robot disable`)。
3. 建联:`dev connect --channel auto --robot-client-id x --robot-client-secret y --dry-run` 看出参 `cli` 字段做依赖预检;正式 connect 是前台长驻进程,对话里跑要后台运行并告诉用户怎么停,或引导自己开终端。
- **通过判据**:走异步 submit/result(同步建号已下线),轮询到 SUCCESS 再用凭证;未配置时走 config 不是 enable;config 是 upsert;写后回读 `robotStatus`;建联先 dry-run 预检、处理好长驻/缺凭证(先 submit/result 建号)。
- **易错点**:找「同步一次建好」的命令;WAITING 就用凭证;robot info not exist 时去 enable;前台直接起 connect 卡住对话。
### C9. 事件订阅与上游错误排查
- **用户说**:「让这个应用订阅『群成员入群』事件,订阅完看下当前订阅了哪些,再把它取消掉;对了我之前发版本报了个 errcode 62012,这是啥意思?」
- **覆盖**:`event list` / `subscribe` / `unsubscribe`、`dev doc search`;错误码透传、文档 RAG。
- **期望(分步)**:
1. `event list --unified-app-id <id> --page-size 20 --format json` 取 `eventCode` → `event subscribe --unified-app-id <id> --event-codes chat_add_member_org --dry-run` → `--yes` → `event list` 回读 → `event unsubscribe --unified-app-id <id> --event-codes chat_add_member_org --dry-run` → `--yes`。事件码不确定先 `event list` 翻页查。
2. 错误码:业务错误 `ServiceResult.success=false` 原样透传 `errorCode/errorMsg`,再 `dev doc search --keyword "errcode 62012 <message>" --format json` 做官方文档 RAG,结论基于命中条目。
- **通过判据**:`--event-codes` 逗号分隔,写操作先 dry-run;`event list` 使用 `hasMore/nextCursor` 翻页;不编造事件码/错误含义;先透传原始错误再走 RAG,结论不臆测、不编不存在的命令。
- **易错点**:编事件码;把事件回调地址塞进事件订阅命令;凭空解释错误码。
### C10. 意图消歧(泛词边界)
- **用户说**:「帮我建个机器人。」(无任何开放平台上下文)
- **覆盖**:泛词消歧、边界与角色。
- **期望**:`应用`/`机器人` 是泛词——先追问确认是不是开发者后台的「企业内部应用机器人」,还是工作台应用、或群里发消息的机器人(→ `dingtalk-chat`);确认是开放平台场景后才走 dev 流程(接 C8)。
- **通过判据**:不直接假设走 dev,先澄清;能正确指向其它技能出口。
- **易错点**:上来就 `robot submit`,没确认是不是开放平台场景。
---
## 备注
- 10 条合起来覆盖全部 34 个子命令 + 8 类横切行为(见覆盖矩阵)。
- 评测可分两层:**静态**——无环境,只看 agent 选的命令/flag/判断是否符合「期望/通过判据」;**真机**——有联调环境时核对真实出参。
- 真机注意:`dev connect` 正式连接是长驻进程;`version publish`/`app delete` 等写操作请用占位应用或停在 dry-run,避免动真实数据。
+321
View File
@@ -0,0 +1,321 @@
# dws dev 一键安装与 Agent 接入指南
面向希望用 Codex、Claude、Cursor 等开发 Agent 管理钉钉开放平台应用的开发者。
这份指南参考 Notion Developer Platform 的引导方式:先给出一条可复制的安装命令,再用最短路径完成验证、登录、Agent 调用和排障。
## 一键安装
`dws dev` 能力已经合入主干并随正式版发布。专用安装脚本会下载预编译二进制 + `dingtalk-dev` skill,**只需要 curl + tar,不需要 git / go / make**。
### macOS / Linux
```bash
curl -fsSL https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace-cli/main/scripts/install-devapp.sh | sh
```
### Windows(PowerShell)
```powershell
irm https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace-cli/main/scripts/install-devapp.ps1 | iex
```
这个脚本会:
1. 从 `DingTalk-Real-AI/dingtalk-workspace-cli` 的最新 Release 下载对应平台的预编译二进制。
2. 安装 `dws` 到默认目录 `~/.local/bin`。
3. 从 Release 的 skills 包里安装 `dingtalk-dev` skill 到本机已检测到的 Agent 目录。
支持这些环境变量(全部可选):
| 变量 | 说明 |
|---|---|
| `DEVAPP_REPO` | 覆盖发布仓库,默认 `DingTalk-Real-AI/dingtalk-workspace-cli` |
| `DEVAPP_VERSION` | 钉某个 release tag,默认取最新 release |
| `DWS_INSTALL_DIR` | 二进制安装目录,默认 `~/.local/bin` |
| `DWS_NO_SKILLS` | 设为 `1` 跳过 `dingtalk-dev` skill 安装 |
> `dws dev` 已在正式版里,所以你也可以直接用标准安装脚本 `install.sh`,二者都会带上 `dws dev`。
### 国内加速
`dws dev` 已在正式版里,国内用户直接用标准安装脚本的 Gitee 镜像即可(二进制和 skill 都从 Gitee 拉,避免 GitHub 网络问题):
```bash
DWS_GITEE_REPO=DingTalk-Real-AI/dingtalk-workspace-cli curl -fsSL https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli/raw/main/scripts/install.sh | sh
```
## 安装后验证
先确认 `dws` 可执行:
```bash
dws version
```
确认 `dws dev app` 命令存在:
```bash
dws dev app --help --format json
```
如果能看到 `list`、`get`、`create`、`update`、`permission`、`member`、`robot`、`security`、`version`、`webapp`、`event`、`credentials` 等子命令,说明已安装成功。
确认登录状态:
```bash
dws auth status
```
如果尚未登录:
```bash
dws auth login
```
登录完成后读取应用列表:
```bash
dws dev app list --format json
```
## dws dev 是什么
`dws dev` 是钉钉开放平台开发者命令组,三块能力:
- `dws dev app` — 开放平台企业内部应用的全生命周期管理(创建、配置、权限、成员、安全、机器人、版本发布、事件订阅)。
- `dws dev connect` — 把现成机器人接到当前本地 agent(起 Stream 连接做本地转发,不建号、不产生审批工单)。
- `dws dev doc` — 开放平台开发文档搜索。
安装后,开发者和 Agent 可以用统一命令管理企业内部应用,而不需要反复进入开发者后台页面。它让 Agent 可以完成这些工作:
- 查询、创建、更新、启用、停用、删除开放平台应用。
- 查询应用凭证,读取 `clientId` / `appKey`,敏感凭证走专用命令。
- 配置网页应用首页和管理后台地址。
- 查询、申请、移除权限点。
- 管理应用成员。
- 配置安全项,包括 IP 白名单、登录重定向 URL、端内免登地址。
- 异步创建机器人、配置/启停现有机器人。
- 创建版本、发起发布、查询审批和发布状态。
## 给 Agent 使用
安装完成后,可以直接让 Agent 操作 `dws dev`。
示例:
```text
帮我查一下最近创建的开放平台应用。
```
```text
帮我给 unifiedAppId=<unifiedAppId> 的应用配置机器人,先 dry-run 给我确认。
```
```text
帮我查询这个应用缺哪些权限点,并申请 Contact.User.mobile。
```
```text
帮我发布这个应用版本,先预检是否需要审批。
```
Agent 写操作必须遵循:
1. 先查询定位应用。
2. 先 dry-run 预览。
3. 明确展示将要修改的应用、字段和值。
4. 用户确认后加 `--yes` 执行。
5. 执行后回读验证。
## 第一个写操作
推荐用机器人配置作为 smoke test。建号是异步的,分两步。
提交建号任务(记下返回的 `taskId`):
```bash
dws dev app robot submit \
--name "告警助手" \
--robot-name "告警机器人" \
--desc "处理告警通知和事件回调" \
--dry-run \
--format json
```
确认预览无误后去掉 `--dry-run`、加 `--yes` 执行,再用返回的 `taskId` 查结果,直到 `status` 变成 `SUCCESS`:
```bash
dws dev app robot result --task-id <taskId> --format json
```
对**已有机器人**的应用,改配置/启停用 `robot config` / `robot enable` / `robot disable`:
```bash
dws dev app robot get --unified-app-id <unifiedAppId> --format json
dws dev app robot config --unified-app-id <unifiedAppId> --name "新机器人名称" --dry-run --format json
```
## 常用命令
### 应用管理
```bash
dws dev app list --format json
dws dev app get --unified-app-id <unifiedAppId> --format json
dws dev app create --name "考勤应用" --dry-run --format json
dws dev app update --unified-app-id <unifiedAppId> --name "新应用名" --dry-run --format json
dws dev app enable --unified-app-id <unifiedAppId> --dry-run --format json
dws dev app disable --unified-app-id <unifiedAppId> --dry-run --format json
dws dev app delete --unified-app-id <unifiedAppId> --confirm-name "<应用名>" --format json
```
> 删除不可逆,需要用 `--confirm-name` 传入应用名做二次确认。
### 凭证查询
```bash
dws dev app credentials get --unified-app-id <unifiedAppId> --format json
```
凭证输出可能包含敏感字段,不要把完整结果写入文档、日志或长期记忆。
### 权限点管理
```bash
dws dev app permission list --unified-app-id <unifiedAppId> --format json
dws dev app permission add --unified-app-id <unifiedAppId> --scope-values Contact.User.mobile --dry-run --format json
dws dev app permission remove --unified-app-id <unifiedAppId> --scope-values Contact.User.mobile --dry-run --format json
```
权限申请和移除只使用 `scopeValue`,不要传 API 名或权限分组名。
### 机器人能力
```bash
dws dev app robot get --unified-app-id <unifiedAppId> --format json
dws dev app robot submit --name "<智能体名>" --robot-name "<机器人名>" --desc "<描述>" --dry-run --format json
dws dev app robot result --task-id <taskId> --format json
dws dev app robot config --unified-app-id <unifiedAppId> --name "机器人名称" --dry-run --format json
dws dev app robot enable --unified-app-id <unifiedAppId> --dry-run --format json
dws dev app robot disable --unified-app-id <unifiedAppId> --dry-run --format json
```
### 成员与安全
```bash
dws dev app member list --unified-app-id <unifiedAppId> --format json
dws dev app member add --unified-app-id <unifiedAppId> --user-ids <userId> --dry-run --format json
dws dev app member remove --unified-app-id <unifiedAppId> --user-ids <userId> --dry-run --format json
dws dev app security config --unified-app-id <unifiedAppId> --redirect-urls <url> --dry-run --format json
dws dev app security config --unified-app-id <unifiedAppId> --ip-whitelist <ip> --dry-run --format json
```
### 网页应用与事件
```bash
dws dev app webapp get --unified-app-id <unifiedAppId> --format json
dws dev app webapp config --unified-app-id <unifiedAppId> --homepage-url <url> --dry-run --format json
dws dev app event list --unified-app-id <unifiedAppId> --format json
dws dev app event subscribe --unified-app-id <unifiedAppId> --dry-run --format json
dws dev app event unsubscribe --unified-app-id <unifiedAppId> --dry-run --format json
```
### 版本发布
```bash
dws dev app version list --unified-app-id <unifiedAppId> --format json
dws dev app version create --unified-app-id <unifiedAppId> --dry-run --format json
dws dev app version check-approval --unified-app-id <unifiedAppId> --version-id <versionId> --format json
dws dev app version publish --unified-app-id <unifiedAppId> --version-id <versionId> --dry-run --format json
dws dev app version status --unified-app-id <unifiedAppId> --version-id <versionId> --format json
```
> 发布前先用 `version check-approval` 预检是否需要审批。含高敏权限的版本,`publish` 需加 `--confirmed-sensitive`。
## 安全边界
`dws dev` 的目标不是绕过开发者后台权限,而是让 CLI、MCP 和 Web 后台保持一致。
默认安全策略:
- 写操作先 dry-run。
- 删除、停用、发布必须由用户确认(删除还需 `--confirm-name` 二次确认)。
- Agent 不接收用户手动传入的 access token、cookie、`clientSecret`、`appSecret`。
- 应用定位优先使用 `unifiedAppId`、`agentId`、`appKey`。
- 对权限点申请、成员变更、安全配置、版本发布记录操作结果,便于审计和回滚。
## 排障
### `dws dev app` 不存在
先确认装上的是带 `dws dev` 的版本:
```bash
dws version
dws dev app --help --format json
```
如果命令缺失,重新执行本文的一键安装命令(或标准 `install.sh`)升级到最新正式版。
### `dws dev app list` 失败
优先检查登录态:
```bash
dws auth status
dws auth login
```
然后确认当前账号能访问目标企业,并且当前用户在目标企业内。
### 提示"当前用户没有开发者身份"
创建应用需要开放平台开发者权限。请企业管理员在钉钉开放平台(open-dev.dingtalk.com)的「权限管理」中把你的账号添加为开发者,然后重试。
### 页面能操作,但 CLI 或 MCP 提示无权限
通常说明 CLI/MCP 后端鉴权和 Web 后台权限没有对齐。先确认当前用户是否满足以下任一条件:
- 应用 owner。
- 应用管理员。
- 应用开发者。
- 企业管理员或具备开放平台应用管理权限的角色。
### 机器人配置失败
先查当前机器人状态:
```bash
dws dev app robot get --unified-app-id <unifiedAppId> --format json
```
如果机器人不存在,用 `robot submit` 异步创建;如果已存在,用 `robot config` 修改,或用 `robot enable` 重新启用。
## 页面文案建议
用于产品页顶部:
```text
Install dws dev in one command.
Let your coding agents manage DingTalk Open Platform apps from the terminal:
create apps, configure robots, apply permissions, manage security settings,
and publish versions with dry-run safety built in.
```
中文版本:
```text
一行命令接入 dws dev。
让 Codex、Claude、Cursor 等开发 Agent 直接管理钉钉开放平台应用:
创建应用、配置机器人、申请权限、管理安全配置、发布版本。
所有写操作先预览,再确认执行。
```
## 参考
- Notion Developer Platform: https://www.notion.com/product/dev
- Notion CLI Help: https://www.notion.com/help/use-notion-from-your-terminal-with-notion-cli
- Notion Developer Platform Blog: https://www.notion.com/blog/introducing-developer-platform
+147
View File
@@ -0,0 +1,147 @@
# 钉钉 AI 群机器人快速上手
10 分钟搭一个自己的钉钉群答疑机器人:群里 @它 提问,它用你本地的 AI(Claude Code / Codex / Qoder 等)回答,支持发文字和报错截图。
只需四步:装工具 → 建机器人 → 接上 AI → 拉进群。
## 第一步:安装 dws
一键脚本会自动下载最新版二进制 + `dingtalk-dev` skill,只需要 curl(无需 go / git)。
### macOS / Linux
打开终端,整段复制执行:
```bash
curl -fsSL https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace-cli/main/scripts/install-devapp.sh | sh
```
> 国内用户:`dws dev` 已在正式版里,直接用标准安装脚本的 Gitee 镜像即可(二进制和 skill 都从 Gitee 拉,避免 GitHub 网络问题):
> ```bash
> DWS_GITEE_REPO=DingTalk-Real-AI/dingtalk-workspace-cli curl -fsSL https://gitee.com/DingTalk-Real-AI/dingtalk-workspace-cli/raw/main/scripts/install.sh | sh
> ```
装完按提示把 `~/.local/bin` 加进 `PATH`(脚本会在末尾提示),然后执行 `dws version` 确认。
### Windows
打开 PowerShell,整段复制执行:
```powershell
irm https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace-cli/main/scripts/install-devapp.ps1 | iex
```
然后**重新打开一个 PowerShell 窗口**,执行 `dws version` 确认。
> 能打印出版本号即安装成功(脚本默认装最新正式版)。脚本走 GitHub API 取最新 release,无需手动填版本号;想钉某个版本可设环境变量 `DEVAPP_VERSION`。
### 登录钉钉
```bash
dws auth login
```
按提示扫码登录即可。
## 第二步:创建机器人
建号是异步的,两步(名字、描述可以改成你自己的):
```bash
# 1) 提交建号任务,记下返回的 taskId
dws dev app robot submit --name 我的智能体 --robot-name 小助手 --desc "群内答疑" --yes --format json
# 2) 用上一步的 taskId 查结果,直到 status 变成 SUCCESS(还是 WAITING 就过几秒再查一次)
dws dev app robot result --task-id 上一步返回的taskId --format json
```
`status` 变成 `SUCCESS` 后,返回结果里的 `clientId` 和 `clientSecret` **保存好**,下一步要用。
## 第三步:把机器人接上你本地的 AI
```bash
dws dev connect --channel auto --robot-client-id dingxxxxxxxxxxxxxxxx --robot-client-secret yyyyyyyyyyyyyyyyyyyy
```
- 把 `dingxxxxxxxxxxxxxxxx` 和 `yyyyyyyyyyyyyyyyyyyy` 换成第二步返回的 `clientId` 和 `clientSecret` 的实际值
- `--channel auto` 自动识别你电脑上装的 AI 工具(Claude Code / Codex / Qoder / Gemini 等)
- 这个命令是前台运行的:窗口开着机器人在线,关掉窗口机器人下线
## 第四步:拉进群聊
在钉钉里打开目标群:
**群设置 → 机器人 → 添加机器人 → 在企业机器人里搜"小助手"(你起的名字)→ 添加**
完成。现在在群里 @小助手 提问试试,发文字、发报错截图都能答。
## 进阶配置(可选)
按需加在第三步的命令后面:
| 参数 | 作用 |
|------|------|
| `--agent-workdir ./项目目录` | 让机器人在你的项目目录里跑,能读到和终端一样的本地文件(详见下方「机器人答得不如终端准?」) |
| `--knowledge-dir ./docs` | 挂本地知识目录(.md/.txt),回答自动带上你的资料 |
| `--agent-cmd "<命令>"` | 接入内置列表之外的 AI 工具(自研的、或还没内置支持的),详见下方「想用没在列表里的 AI 工具?」 |
| `--allowed-users 工号1,工号2` | 用户白名单,名单外的人无法触发机器人 |
| `--allowed-groups 群ID` | 群白名单 |
| `--user-rate-limit 0` | 关闭限流(默认每人每分钟 20 条) |
### 想用没在列表里的 AI 工具?(自研 / 未内置支持)
`--channel auto` 只认内置的几款工具(Claude Code / Codex / Qoder / Gemini 等)。如果你用的是自研的、或还没内置支持的 AI(比如网易有道龙虾 LobsterAI),用 `--agent-cmd` 把它接进来——只要它能在命令行「一次性」跑(给一段问题、把答案打到标准输出),就能接:
```bash
dws dev connect \
--agent-cmd "你的AI命令 一次性问答参数" \
--robot-client-id dingxxxx --robot-client-secret yyyy
```
机器人收到群消息后,会执行 `你的AI命令 一次性问答参数 "用户的问题"`(问题作为最后一个参数追加),把它打印出来的内容当作回复发回群里。
举例:假设龙虾的命令行叫 `lobster`、一次性问答用 `-p` 参数,就写 `--agent-cmd "lobster -p"`。命令里有空格就整体用引号括起来。
## 常见问题
**执行命令报 `zsh: parse error near '\n'`?**
命令里残留了 `<...>` 尖括号占位符(旧版文档的写法),shell 会把尖括号当成重定向符。把占位符整体替换成实际值、不要保留尖括号,再执行。
**群里 @机器人 没反应?**
确认第三步的 `dev connect` 窗口还开着——关掉窗口机器人就下线了。
**第二步提示"当前用户没有开发者身份"?**
创建应用需要开放平台开发者权限。请企业管理员在钉钉开放平台(open-dev.dingtalk.com)的「权限管理」中把你的账号添加为开发者,然后重试第二步。
**提示找不到 dws 命令?**
macOS 重开一个终端窗口;Windows 重开一个 PowerShell 窗口(安装时改了 PATH,需要新窗口才生效)。
**提示本地没有装 AI 工具?**
机器人背后需要一个本地 AI CLI。推荐先装 [Claude Code](https://claude.com/claude-code) 或 Codex,装好后重新执行第三步。
**机器人回复"调用失败"?**
通常是本地 AI 工具未登录或额度用尽,单独运行一次该 AI 工具确认其本身可用。
**机器人答得不如终端准?(同样的问题,终端对、机器人不对)**
这通常不是模型问题,而是"机器人看到的上下文比终端少":
- **工作目录不同**:默认机器人在一个空白临时目录里跑(为了启动快、回复中立),它看不到你终端所在项目里的文件。要让它和终端读到同样的资料,在第三步加 `--agent-workdir ./你的项目目录`(指到你平时在终端里跑 AI 的那个目录)。
- **知识没挂上**:如果靠的是本地文档/知识库,加 `--knowledge-dir ./docs`(或 `--knowledge-source wiki:<spaceId>`)把资料显式挂给机器人,别指望它自己去翻。
- **模型不同**:机器人默认走一个偏快的小模型;如果你终端用的是更强的模型,给机器人也指定同一个:`--agent-model <模型名>`。
- **回答"水位"上下浮动**:先确认没关 `--agent-memory`(默认开)。Codex 走 app-server thread 续聊;Qoder/Claude Code/CodeBuddy/WorkBuddy 走可恢复会话,其中 Qoder 的映射只保存在当前 DWS 进程内,重启后会重新开始;Gemini 仍是一次性调用。
一句话:让机器人和终端"看到一样的东西、用一样的模型",差距基本就抹平了。
## 会话指令:`/new` 和 `/clear`
机器人默认记住同一个会话的上下文(多轮对话)。想重置上下文,直接在聊天里发这两个斜杠指令——整条消息就是指令时才生效(普通问题不受影响),不消耗一次 AI 调用,秒回提示:
| 指令 | 作用 |
|------|------|
| `/new`(或 `/start`、`/reset`) | **开启新会话**:之前的上下文不再带入,旧会话保留(agent 支持的话仍可回溯) |
| `/clear` | **清空当前会话**:彻底从头开始 |
两者按各渠道**真实能力**对齐:`/clear` 在 opencode 渠道会真正删除当前会话(调 opencode 的 `DELETE /session/:id`);Codex / Qoder / Claude 系等驱动接口没有删除原语的渠道,`/clear` 退化为与 `/new` 相同的重置。
**第三步执行完,在蚂蚁钉/开放平台搜不到审批工单?**
这是正常的,不是出错。第三步 `dev connect`(把机器人接到本地 AI)只是用现成机器人的凭证起一条连接、本地转发,**不产生任何审批工单**。会产生审批工单的是第二步「建机器人」(`dev app robot submit`),由平台/管理员审批。所以第三步之后搜不到工单是预期内的。
+4 -2
View File
@@ -3,9 +3,12 @@ module github.com/DingTalk-Real-AI/dingtalk-workspace-cli
go 1.25.8
require (
github.com/RealAlexandreAI/json-repair v0.0.15
github.com/charmbracelet/huh v1.0.0
github.com/fatih/color v1.18.0
github.com/google/uuid v1.6.0
github.com/itchyny/gojq v0.12.18
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1
github.com/spf13/cobra v1.10.2
github.com/zalando/go-keyring v0.2.8
golang.org/x/crypto v0.49.0
@@ -14,14 +17,12 @@ require (
)
require (
github.com/RealAlexandreAI/json-repair v0.0.15 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/catppuccin/go v0.3.0 // indirect
github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect
github.com/charmbracelet/bubbletea v1.3.6 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/huh v1.0.0 // indirect
github.com/charmbracelet/lipgloss v1.1.0 // indirect
github.com/charmbracelet/x/ansi v0.9.3 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
@@ -33,6 +34,7 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/itchyny/timefmt-go v0.1.7 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
+22
View File
@@ -1,9 +1,13 @@
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/RealAlexandreAI/json-repair v0.0.15 h1:AN8/yt8rcphwQrIs/FZeki+cKaIERUNr25zf1flirIs=
github.com/RealAlexandreAI/json-repair v0.0.15/go.mod h1:GKJi5borR78O8c7HCVbgqjhoiVibZ6hJldxbc6dGrAI=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=
github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E=
github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws=
@@ -20,15 +24,27 @@ github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh
github.com/charmbracelet/x/ansi v0.9.3/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=
github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U=
github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ=
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI=
github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -43,6 +59,8 @@ github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/itchyny/gojq v0.12.18 h1:gFGHyt/MLbG9n6dqnvlliiya2TaMMh6FFaR2b1H6Drc=
@@ -68,6 +86,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1 h1:Lb/Uzkiw2Ugt2Xf03J5wmv81PdkYOiWbI8CNBi1boC8=
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1/go.mod h1:ln3IqPYYocZbYvl9TAOrG/cxGR9xcn4pnZRLdCTEGEU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
@@ -88,6 +108,8 @@ github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cma
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+415 -24
View File
@@ -30,18 +30,39 @@ import (
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/helpers"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pat"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/spf13/cobra"
)
type authLoginConfig struct {
Token string
Force bool
Device bool
Token string
Force bool
Device bool
Recommend bool
Yes bool
}
func buildAuthCommand() *cobra.Command {
type authLoginGuideAction string
const (
authLoginGuideDirectCLI authLoginGuideAction = "direct_cli"
authLoginGuideConfigureAgentApp authLoginGuideAction = "configure_agent_app"
authLoginGuideManualCredentials authLoginGuideAction = "manual_credentials"
)
var (
authLoginBrandBlue = lipgloss.AdaptiveColor{Light: "#1677FF", Dark: "#69B1FF"}
authLoginInk = lipgloss.AdaptiveColor{Light: "#1F2937", Dark: "#EAF2FF"}
authLoginMuted = lipgloss.AdaptiveColor{Light: "#667085", Dark: "#8A96A8"}
authLoginLine = lipgloss.AdaptiveColor{Light: "#D6E4FF", Dark: "#2F3B52"}
authLoginDanger = lipgloss.AdaptiveColor{Light: "#D92D20", Dark: "#FF6B6B"}
)
func buildAuthCommand(patCaller edition.ToolCaller) *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "认证管理",
@@ -55,7 +76,7 @@ func buildAuthCommand() *cobra.Command {
}
if !edition.Get().HideAuthLogin {
cmd.AddCommand(newAuthLoginCommand())
cmd.AddCommand(newAuthLoginCommand(patCaller))
}
cmd.AddCommand(
newAuthLogoutCommand(),
@@ -68,7 +89,7 @@ func buildAuthCommand() *cobra.Command {
return cmd
}
func newAuthLoginCommand() *cobra.Command {
func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Short: "登录钉钉(自动刷新 token,必要时扫码)",
@@ -88,7 +109,8 @@ func newAuthLoginCommand() *cobra.Command {
否则 OAuth 回调会跳到本机不可达的 127.0.0.1 链接,授权完成后无法回写 token。
示例:
dws auth login # 本机扫码登录 (loopback 流)
dws auth login # 本机登录后选择推荐/全部权限与授权业务域
dws auth login --recommend # 无交互批量授权服务端推荐权限
dws auth login --device # SSH 远程 / 无头环境登录 (设备流)
dws auth login --force # 强制重新登录 (忽略缓存 token)
dws auth login --token xxx # 使用指定 token`,
@@ -100,6 +122,10 @@ func newAuthLoginCommand() *cobra.Command {
}
configDir := defaultConfigDir()
var tokenData *authpkg.TokenData
format, _ := cmd.Root().PersistentFlags().GetString("format")
postLoginTUIMode := !cfg.Yes && authLoginShouldUsePostLoginTUIMode(cmd, format, cfg.Recommend)
recommendAuthMode := cfg.Recommend || postLoginTUIMode
humanAuthMode := !cfg.Yes && authLoginShouldUseHumanAuthorizationMode(cmd, format, recommendAuthMode)
switch {
case strings.TrimSpace(cfg.Token) != "":
@@ -116,6 +142,7 @@ func newAuthLoginCommand() *cobra.Command {
provider := authpkg.NewDeviceFlowProvider(configDir, nil)
provider.Output = cmd.ErrOrStderr()
provider.NoBrowser, _ = cmd.Flags().GetBool("no-browser")
tokenData, err = provider.Login(loginCtx)
if err != nil {
return apperrors.NewAuth(fmt.Sprintf("device authorization failed: %v", err))
@@ -126,6 +153,7 @@ func newAuthLoginCommand() *cobra.Command {
provider := authpkg.NewOAuthProvider(configDir, nil)
provider.Output = cmd.ErrOrStderr()
provider.NoBrowser, _ = cmd.Flags().GetBool("no-browser")
configureOAuthProviderCompatibility(provider, configDir)
tokenData, err = provider.Login(loginCtx, cfg.Force)
if err != nil {
@@ -137,41 +165,93 @@ func newAuthLoginCommand() *cobra.Command {
clearCompatCache()
w := cmd.OutOrStdout()
runPostLoginAuthorization := func() error {
if !recommendAuthMode {
return nil
}
recommendScopeMode := pat.LoginRecommendScopeRecommended
var initialPlan *pat.LoginRecommendPlan
if postLoginTUIMode {
var planErr error
initialPlan, planErr = pat.PlanLoginRecommendAuthorization(cmd.Context(), patCaller)
if planErr != nil {
return planErr
}
if authLoginRecommendPlanSkipsInteractiveAuthorization(initialPlan) {
fmt.Fprintln(cmd.ErrOrStderr(), "推荐权限已全部授权或没有可授权项")
return nil
}
var err error
recommendScopeMode, err = loginRecommendScopeModeSelector()
if err != nil {
return err
}
}
opts := pat.LoginRecommendOptions{Confirmed: cfg.Yes, ScopeMode: recommendScopeMode, InitialPlan: initialPlan}
if postLoginTUIMode {
opts.ProductSelector = func(products []pat.LoginRecommendProduct) ([]string, error) {
return loginRecommendProductSelector(products)
}
}
retryFormat := format
if humanAuthMode {
retryFormat = "table"
}
run := func(ctx context.Context) error {
return pat.RunLoginRecommendAuthorizationWithOptions(ctx, patCaller, cmd.ErrOrStderr(), opts)
}
err := run(cmd.Context())
if patErr := apperrors.AsPatAuthCheckError(err); patErr != nil {
return runDirectPATAuthCheckWaitOnly(
cmd.Context(),
&GlobalFlags{Format: retryFormat},
patErr,
cmd.ErrOrStderr(),
)
}
return err
}
// Check if JSON output is requested
format, _ := cmd.Root().PersistentFlags().GetString("format")
if strings.EqualFold(strings.TrimSpace(format), "json") {
if strings.EqualFold(strings.TrimSpace(format), "json") && !humanAuthMode {
if err := runPostLoginAuthorization(); err != nil {
return err
}
return writeAuthLoginJSON(w, tokenData, cfg.Force)
}
// Default table output
if err := runPostLoginAuthorization(); err != nil {
return err
}
fmt.Fprintln(w)
if !cfg.Device && tokenData != nil && tokenData.IsAccessTokenValid() && !cfg.Force {
fmt.Fprintf(w, "[OK] Token 有效,无需重新登录\n")
fmt.Fprintln(w, authLoginStatusLine("Token 有效,无需重新登录"))
} else {
fmt.Fprintf(w, "[OK] 登录成功!\n")
fmt.Fprintln(w, authLoginStatusLine("登录成功!"))
}
if tokenData != nil {
if tokenData.CorpName != "" {
fmt.Fprintf(w, "%-16s%s\n", "企业:", tokenData.CorpName)
fmt.Fprintln(w, authLoginInfoLine("企业", tokenData.CorpName))
}
if tokenData.CorpID != "" {
fmt.Fprintf(w, "%-16s%s\n", "企业 ID:", tokenData.CorpID)
fmt.Fprintln(w, authLoginInfoLine("企业 ID", tokenData.CorpID))
}
if tokenData.UserName != "" {
fmt.Fprintf(w, "%-16s%s\n", "用户:", tokenData.UserName)
fmt.Fprintln(w, authLoginInfoLine("用户", tokenData.UserName))
}
if expiry := authLoginDisplayExpiry(tokenData); expiry != "" {
fmt.Fprintf(w, "%-16s%s\n", "有效期:", expiry)
fmt.Fprintln(w, authLoginInfoLine("有效期", expiry))
}
}
fmt.Fprintf(w, "Token 将自动刷新,无需重复登录\n")
fmt.Fprintln(w, authLoginMutedStyle().Render("Token 将自动刷新,无需重复登录"))
return nil
},
}
cmd.Flags().String("token", "", "Access token")
cmd.Flags().Bool("device", false, "Use device authorization flow")
cmd.Flags().Bool("force", false, "Force interactive login (ignore cached token)")
cmd.Flags().Bool("recommend", false, "登录成功后无交互批量授权服务端推荐权限")
// Hidden compatibility flags
cmd.Flags().String("redirect-url", "", "Loopback redirect URL")
cmd.Flags().String("scopes", "", "Space-separated DingTalk OAuth scopes")
@@ -186,10 +266,112 @@ func newAuthLoginCommand() *cobra.Command {
_ = cmd.Flags().MarkHidden("token-url")
_ = cmd.Flags().MarkHidden("refresh-url")
_ = cmd.Flags().MarkHidden("login-timeout")
_ = cmd.Flags().MarkHidden("no-browser")
return cmd
}
var (
authLoginGuideActionSelector = selectAuthLoginGuideAction
authLoginGuideActionApplier = applyAuthLoginGuideAction
loginRecommendScopeModeSelector = selectLoginRecommendScopeMode
loginRecommendProductSelector = selectLoginRecommendProducts
authLoginInteractiveTerminal = isInteractiveTerminal
)
func selectAuthLoginGuideAction() (authLoginGuideAction, error) {
choice := authLoginGuideDirectCLI
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[authLoginGuideAction]().
Title("选择操作").
Options(
huh.NewOption("直接使用CLI", authLoginGuideDirectCLI),
huh.NewOption("一键配置智能体应用", authLoginGuideConfigureAgentApp),
huh.NewOption("手动输入应用凭证", authLoginGuideManualCredentials),
).
Value(&choice),
),
).WithTheme(authLoginHuhTheme())
if err := form.Run(); err != nil {
return "", fmt.Errorf("使用引导选择中止: %w", err)
}
return choice, nil
}
func applyAuthLoginGuideAction(cmd *cobra.Command, configDir string, action authLoginGuideAction) error {
switch action {
case authLoginGuideDirectCLI:
return nil
case authLoginGuideConfigureAgentApp:
fmt.Fprintln(cmd.ErrOrStderr(), "一键配置智能体应用暂未开放,已继续使用 CLI 登录")
return nil
case authLoginGuideManualCredentials:
clientID, clientSecret, err := promptAuthLoginManualCredentials()
if err != nil {
return err
}
authpkg.SetClientID(clientID)
authpkg.SetClientSecret(clientSecret)
if err := authpkg.SaveAppConfig(configDir, &authpkg.AppConfig{
ClientID: clientID,
ClientSecret: authpkg.PlainSecret(clientSecret),
}); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to persist app credentials: %v", err))
}
return nil
default:
return fmt.Errorf("未知操作: %s", action)
}
}
func promptAuthLoginManualCredentials() (string, string, error) {
var clientID, clientSecret string
nonEmpty := func(label string) func(string) error {
return func(value string) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s 不能为空", label)
}
return nil
}
}
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("输入 AppKey").
Value(&clientID).
Validate(nonEmpty("AppKey")),
huh.NewInput().
Title("输入 AppSecret").
EchoMode(huh.EchoModePassword).
Value(&clientSecret).
Validate(nonEmpty("AppSecret")),
),
).WithTheme(authLoginHuhTheme())
if err := form.Run(); err != nil {
return "", "", fmt.Errorf("应用凭证输入中止: %w", err)
}
return strings.TrimSpace(clientID), strings.TrimSpace(clientSecret), nil
}
func selectLoginRecommendScopeMode() (pat.LoginRecommendScopeMode, error) {
choice := pat.LoginRecommendScopeRecommended
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[pat.LoginRecommendScopeMode]().
Title("选择授权范围").
Description("空格选择 回车确认").
Options(
huh.NewOption("推荐授权", pat.LoginRecommendScopeRecommended),
huh.NewOption("全部授权", pat.LoginRecommendScopeAll),
).
Value(&choice),
),
).WithTheme(authLoginHuhTheme())
if err := form.Run(); err != nil {
return "", fmt.Errorf("授权范围选择中止: %w", err)
}
return choice, nil
}
func newAuthLogoutCommand() *cobra.Command {
return &cobra.Command{
Use: "logout",
@@ -229,7 +411,7 @@ func newAuthLogoutCommand() *cobra.Command {
w := cmd.OutOrStdout()
fmt.Fprintln(w, "[OK] 已清除所有认证信息")
if !edition.Get().IsEmbedded {
fmt.Fprintln(w, "请运行 dws auth login 重新登录")
fmt.Fprintln(w, "请运行 dws auth login --recommend 重新登录")
}
return nil
},
@@ -297,7 +479,7 @@ func newAuthStatusCommand() *cobra.Command {
} else {
fmt.Fprintf(w, "%-16s%s\n", "状态:", "未登录")
if !edition.Get().IsEmbedded {
fmt.Fprintln(w, "运行 dws auth login 进行登录")
fmt.Fprintln(w, "运行 dws auth login --recommend 进行登录")
}
}
return nil
@@ -337,7 +519,7 @@ func newAuthExportCommand() *cobra.Command {
))
}
if !authpkg.PortableAuthSourceReady() {
return apperrors.NewValidation("尚未登录,请先运行 dws auth login")
return apperrors.NewValidation("尚未登录,请先运行 dws auth login --recommend")
}
var bundle bytes.Buffer
@@ -511,7 +693,7 @@ func newAuthResetCommand() *cobra.Command {
w := cmd.OutOrStdout()
fmt.Fprintln(w, "[OK] 认证信息已重置")
if !edition.Get().IsEmbedded {
fmt.Fprintln(w, "请运行 dws auth login 重新登录")
fmt.Fprintln(w, "请运行 dws auth login --recommend 重新登录")
}
return nil
},
@@ -552,6 +734,205 @@ func authLoginDisplayExpiry(data *authpkg.TokenData) string {
return ""
}
func selectLoginRecommendProducts(products []pat.LoginRecommendProduct) ([]string, error) {
if len(products) == 0 {
return nil, nil
}
selected := make([]string, 0, len(products))
options := make([]huh.Option[string], 0, len(products))
for _, product := range products {
code := strings.TrimSpace(product.ProductCode)
if code == "" {
continue
}
selected = append(selected, code)
options = append(options, huh.NewOption(loginRecommendProductLabel(product), code).Selected(true))
}
if len(options) == 0 {
return nil, nil
}
height := len(options)
if height > 15 {
height = 15
}
form := huh.NewForm(
huh.NewGroup(
huh.NewMultiSelect[string]().
Title("选择要授权的业务域").
Description("空格选择 回车确认").
Options(options...).
Height(height).
Value(&selected).
Validate(func(values []string) error {
if len(values) == 0 {
return fmt.Errorf("至少选择一个授权业务域")
}
return nil
}),
),
).WithTheme(authLoginHuhTheme())
if err := form.Run(); err != nil {
return nil, fmt.Errorf("授权业务域选择中止: %w", err)
}
return selected, nil
}
func authLoginHuhTheme() *huh.Theme {
t := huh.ThemeBase()
t.Form.Base = lipgloss.NewStyle().Foreground(authLoginInk)
t.FieldSeparator = lipgloss.NewStyle().SetString("\n")
t.Focused.Base = t.Focused.Base.BorderForeground(authLoginBrandBlue)
t.Focused.Card = t.Focused.Base
t.Focused.Title = lipgloss.NewStyle().Foreground(authLoginBrandBlue).Bold(true)
t.Focused.NoteTitle = t.Focused.Title.MarginBottom(1)
t.Focused.Description = authLoginMutedStyle()
t.Focused.ErrorIndicator = lipgloss.NewStyle().SetString(" *").Foreground(authLoginDanger)
t.Focused.ErrorMessage = lipgloss.NewStyle().SetString(" *").Foreground(authLoginDanger)
t.Focused.SelectSelector = lipgloss.NewStyle().SetString("› ").Foreground(authLoginBrandBlue).Bold(true)
t.Focused.MultiSelectSelector = t.Focused.SelectSelector
t.Focused.Option = lipgloss.NewStyle().Foreground(authLoginInk)
t.Focused.SelectedOption = lipgloss.NewStyle().Foreground(authLoginBrandBlue).Bold(true)
t.Focused.SelectedPrefix = lipgloss.NewStyle().SetString("● ").Foreground(authLoginBrandBlue)
t.Focused.UnselectedOption = lipgloss.NewStyle().Foreground(authLoginInk)
t.Focused.UnselectedPrefix = lipgloss.NewStyle().SetString("○ ").Foreground(authLoginMuted)
t.Focused.NextIndicator = lipgloss.NewStyle().SetString("→").Foreground(authLoginBrandBlue)
t.Focused.PrevIndicator = lipgloss.NewStyle().SetString("←").Foreground(authLoginMuted)
t.Focused.FocusedButton = lipgloss.NewStyle().
Foreground(lipgloss.AdaptiveColor{Light: "#FFFFFF", Dark: "#0B1220"}).
Background(authLoginBrandBlue).
Padding(0, 2).
Bold(true)
t.Focused.BlurredButton = lipgloss.NewStyle().
Foreground(authLoginInk).
Background(authLoginLine).
Padding(0, 2)
t.Focused.Next = t.Focused.FocusedButton
t.Focused.TextInput.Cursor = lipgloss.NewStyle().Foreground(authLoginBrandBlue)
t.Focused.TextInput.CursorText = lipgloss.NewStyle().Foreground(authLoginInk)
t.Focused.TextInput.Placeholder = authLoginMutedStyle()
t.Focused.TextInput.Prompt = lipgloss.NewStyle().Foreground(authLoginBrandBlue)
t.Focused.TextInput.Text = lipgloss.NewStyle().Foreground(authLoginInk)
t.Blurred = t.Focused
t.Blurred.Base = t.Focused.Base.BorderStyle(lipgloss.HiddenBorder()).BorderForeground(authLoginLine)
t.Blurred.Card = t.Blurred.Base
t.Blurred.Title = lipgloss.NewStyle().Foreground(authLoginInk)
t.Blurred.NoteTitle = t.Blurred.Title.MarginBottom(1)
t.Blurred.Description = authLoginMutedStyle()
t.Blurred.SelectSelector = lipgloss.NewStyle().SetString(" ")
t.Blurred.MultiSelectSelector = t.Blurred.SelectSelector
t.Blurred.SelectedOption = lipgloss.NewStyle().Foreground(authLoginInk)
t.Blurred.SelectedPrefix = lipgloss.NewStyle().SetString("● ").Foreground(authLoginBrandBlue)
t.Blurred.UnselectedOption = lipgloss.NewStyle().Foreground(authLoginMuted)
t.Blurred.UnselectedPrefix = lipgloss.NewStyle().SetString("○ ").Foreground(authLoginMuted)
t.Blurred.NextIndicator = lipgloss.NewStyle()
t.Blurred.PrevIndicator = lipgloss.NewStyle()
t.Blurred.TextInput.Prompt = lipgloss.NewStyle().Foreground(authLoginMuted)
t.Blurred.TextInput.Text = lipgloss.NewStyle().Foreground(authLoginInk)
t.Group.Title = t.Focused.Title
t.Group.Description = t.Focused.Description
t.Help.ShortKey = authLoginMutedStyle()
t.Help.ShortDesc = authLoginMutedStyle()
t.Help.ShortSeparator = authLoginMutedStyle()
t.Help.FullKey = authLoginMutedStyle()
t.Help.FullDesc = authLoginMutedStyle()
t.Help.FullSeparator = authLoginMutedStyle()
t.Help.Ellipsis = authLoginMutedStyle()
return t
}
func authLoginStatusLine(message string) string {
return fmt.Sprintf("%s %s",
lipgloss.NewStyle().Foreground(authLoginBrandBlue).Bold(true).Render("[OK]"),
lipgloss.NewStyle().Foreground(authLoginInk).Bold(true).Render(message),
)
}
func authLoginInfoLine(key, value string) string {
label := authLoginMutedStyle().Width(14).Render(key + ":")
return fmt.Sprintf("%s %s", label, value)
}
func authLoginMutedStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(authLoginMuted)
}
func authLoginShouldShowPostLoginTUI(cmd *cobra.Command, format string, recommend bool) bool {
return authLoginShouldUsePostLoginTUIModeForTerminal(cmd, format, recommend, authLoginInteractiveTerminal())
}
func authLoginShouldShowPostLoginTUIForTerminal(cmd *cobra.Command, format string, recommend bool, interactive bool) bool {
return authLoginShouldUsePostLoginTUIModeForTerminal(cmd, format, recommend, interactive)
}
func authLoginShouldUsePostLoginTUIMode(cmd *cobra.Command, format string, recommend bool) bool {
return authLoginShouldUsePostLoginTUIModeForTerminal(cmd, format, recommend, authLoginInteractiveTerminal())
}
func authLoginShouldUsePostLoginTUIModeForTerminal(cmd *cobra.Command, format string, recommend bool, interactive bool) bool {
if recommend || !interactive {
return false
}
return authLoginAllowsInteractiveDefault(cmd, format)
}
func authLoginShouldUseHumanAuthorizationMode(cmd *cobra.Command, format string, hasAuthorizationFlow bool) bool {
return authLoginShouldUseHumanAuthorizationModeForTerminal(cmd, format, hasAuthorizationFlow, authLoginInteractiveTerminal())
}
func authLoginShouldUseHumanAuthorizationModeForTerminal(cmd *cobra.Command, format string, hasAuthorizationFlow bool, interactive bool) bool {
if !hasAuthorizationFlow || !interactive {
return false
}
return authLoginAllowsInteractiveDefault(cmd, format)
}
func authLoginRecommendPlanSkipsInteractiveAuthorization(plan *pat.LoginRecommendPlan) bool {
if plan == nil {
return false
}
return plan.AllGranted || len(plan.Scopes) == 0
}
func authLoginAllowsInteractiveDefault(cmd *cobra.Command, format string) bool {
if cmd == nil || cmd.Root() == nil {
return false
}
if !strings.EqualFold(strings.TrimSpace(format), "json") {
return true
}
flags := cmd.Root().PersistentFlags()
return !flags.Changed("format")
}
func loginRecommendProductLabel(product pat.LoginRecommendProduct) string {
name := strings.TrimSpace(product.ProductName)
if name == "" || name == product.ProductCode {
name = product.ProductCode
}
summary := strings.TrimSpace(product.Summary)
if summary != "" {
summary = " - " + clipRunes(summary, 42)
}
return fmt.Sprintf("%-10s %s%s", product.ProductCode, name, summary)
}
func clipRunes(value string, limit int) string {
if limit <= 0 {
return ""
}
runes := []rune(value)
if len(runes) <= limit {
return value
}
return string(runes[:limit]) + "..."
}
func clearCompatCache() {
store := cacheStoreFromEnv()
if store != nil {
@@ -572,10 +953,20 @@ func resolveAuthLoginConfig(cmd *cobra.Command) (authLoginConfig, error) {
if err != nil {
return authLoginConfig{}, apperrors.NewInternal("failed to read --force")
}
recommend, err := cmd.Flags().GetBool("recommend")
if err != nil {
return authLoginConfig{}, apperrors.NewInternal("failed to read --recommend")
}
yes := false
if cmd.Root() != nil {
yes, _ = cmd.Root().PersistentFlags().GetBool("yes")
}
return authLoginConfig{
Token: strings.TrimSpace(token),
Force: force,
Device: device,
Token: strings.TrimSpace(token),
Force: force,
Device: device,
Recommend: recommend,
Yes: yes,
}, nil
}
+457
View File
@@ -15,6 +15,7 @@ package app
import (
"bytes"
"context"
"errors"
"net/http"
"os"
@@ -26,6 +27,9 @@ import (
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pat"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
func TestAuthExportImportBase64RoundTrip(t *testing.T) {
@@ -180,8 +184,461 @@ func TestAuthStatusRefreshFailureLeavesStoredTokenIntact(t *testing.T) {
}
}
func TestAuthLoginPostLoginTUIModeRespectsRecommendAndFormat(t *testing.T) {
newRoot := func(t *testing.T) *cobra.Command {
t.Helper()
root := &cobra.Command{Use: "dws"}
root.PersistentFlags().String("format", "json", "")
return root
}
t.Run("recommend skips tui but keeps human auth for interactive login", func(t *testing.T) {
root := newRoot(t)
if authLoginShouldShowPostLoginTUIForTerminal(root, "json", true, true) {
t.Fatal("--recommend must not show the post-login product TUI")
}
if !authLoginShouldUseHumanAuthorizationModeForTerminal(root, "json", true, true) {
t.Fatal("default interactive --recommend should still use human authorization flow")
}
})
t.Run("without recommend shows two-step authorization tui", func(t *testing.T) {
root := newRoot(t)
if !authLoginShouldShowPostLoginTUIForTerminal(root, "json", false, true) {
t.Fatal("default interactive login should show post-login authorization TUI")
}
if !authLoginShouldUseHumanAuthorizationModeForTerminal(root, "json", true, true) {
t.Fatal("default interactive post-login authorization should use human authorization flow")
}
})
t.Run("explicit json keeps machine mode", func(t *testing.T) {
root := newRoot(t)
if err := root.PersistentFlags().Set("format", "json"); err != nil {
t.Fatalf("set format: %v", err)
}
if authLoginShouldShowPostLoginTUIForTerminal(root, "json", false, true) {
t.Fatal("explicit --format json must not show post-login TUI")
}
if authLoginShouldUseHumanAuthorizationModeForTerminal(root, "json", true, true) {
t.Fatal("explicit --format json must keep machine-readable authorization flow")
}
})
t.Run("table without recommend shows authorization tui", func(t *testing.T) {
root := newRoot(t)
if err := root.PersistentFlags().Set("format", "table"); err != nil {
t.Fatalf("set format: %v", err)
}
if !authLoginShouldShowPostLoginTUIForTerminal(root, "table", false, true) {
t.Fatal("table format should show post-login TUI without --recommend")
}
if !authLoginShouldUseHumanAuthorizationModeForTerminal(root, "table", true, true) {
t.Fatal("table format should use human authorization flow in an interactive terminal")
}
})
t.Run("non interactive skips selector", func(t *testing.T) {
root := newRoot(t)
if authLoginShouldShowPostLoginTUIForTerminal(root, "json", false, false) {
t.Fatal("non-interactive login should skip post-login TUI")
}
if authLoginShouldUseHumanAuthorizationModeForTerminal(root, "json", true, false) {
t.Fatal("non-interactive login should keep machine-readable authorization flow")
}
})
t.Run("without authorization flow keeps normal login output contract", func(t *testing.T) {
root := newRoot(t)
if authLoginShouldUseHumanAuthorizationModeForTerminal(root, "json", false, true) {
t.Fatal("login without a post-login authorization flow should not switch default json to human mode")
}
})
}
func TestLoginRecommendProductLabelMatchesTUITarget(t *testing.T) {
label := loginRecommendProductLabel(pat.LoginRecommendProduct{
ProductCode: "approval",
ProductName: "审批",
Summary: "审批实例,审批模板,审批任务管理",
ScopeCount: 12,
})
if label != "approval 审批 - 审批实例,审批模板,审批任务管理" {
t.Fatalf("label = %q", label)
}
}
func TestResolveAuthLoginConfigReadsInheritedYes(t *testing.T) {
root := &cobra.Command{Use: "dws"}
root.PersistentFlags().Bool("yes", false, "")
login := &cobra.Command{Use: "login"}
login.Flags().String("token", "", "")
login.Flags().Bool("device", false, "")
login.Flags().Bool("force", false, "")
login.Flags().Bool("recommend", false, "")
root.AddCommand(login)
if err := root.PersistentFlags().Set("yes", "true"); err != nil {
t.Fatalf("set yes: %v", err)
}
if err := login.Flags().Set("recommend", "true"); err != nil {
t.Fatalf("set recommend: %v", err)
}
cfg, err := resolveAuthLoginConfig(login)
if err != nil {
t.Fatalf("resolveAuthLoginConfig error = %v", err)
}
if !cfg.Recommend {
t.Fatal("Recommend = false, want true")
}
if !cfg.Yes {
t.Fatal("Yes = false, want true")
}
}
func TestAuthLoginRecommendSkipsPostLoginTUI(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, t.TempDir())
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldGuideSelector := authLoginGuideActionSelector
oldGuideApplier := authLoginGuideActionApplier
oldScopeSelector := loginRecommendScopeModeSelector
oldProductSelector := loginRecommendProductSelector
oldInteractiveTerminal := authLoginInteractiveTerminal
t.Cleanup(func() {
authLoginGuideActionSelector = oldGuideSelector
authLoginGuideActionApplier = oldGuideApplier
loginRecommendScopeModeSelector = oldScopeSelector
loginRecommendProductSelector = oldProductSelector
authLoginInteractiveTerminal = oldInteractiveTerminal
})
authLoginInteractiveTerminal = func() bool { return true }
authLoginGuideActionSelector = func() (authLoginGuideAction, error) {
t.Fatal("--recommend must not call the post-login guide selector")
return "", nil
}
authLoginGuideActionApplier = func(*cobra.Command, string, authLoginGuideAction) error {
t.Fatal("--recommend must not apply a post-login guide action")
return nil
}
loginRecommendScopeModeSelector = func() (pat.LoginRecommendScopeMode, error) {
t.Fatal("--recommend must not call the scope-mode TUI")
return "", nil
}
loginRecommendProductSelector = func([]pat.LoginRecommendProduct) ([]string, error) {
t.Fatal("--recommend must not call the product-domain TUI")
return nil, nil
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"data":{"items":[{"scope":"calendar.event:read","productCode":"calendar","productName":"日历"}],"selectedScopes":["calendar.event:read"]}}`,
`{"success":true,"data":{"grantedScopes":["calendar.event:read"]}}`,
}}
cmd := newAuthLoginCommand(fake)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--token", "login-token", "--recommend"})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth login --recommend error = %v\noutput:\n%s", err, out.String())
}
if len(fake.tools) != 2 {
t.Fatalf("CallTool count = %d, want plan + grant", len(fake.tools))
}
if fake.tools[0] != "pat.batch_plan" || fake.tools[1] != "pat.batch_grant" {
t.Fatalf("tool sequence = %v, want plan, grant", fake.tools)
}
if got := fake.args[0]["recommend"]; got != true {
t.Fatalf("--recommend plan recommend = %#v, want true", got)
}
}
func TestAuthLoginDefaultTUIModeSkipsSelectorWhenAllGranted(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, t.TempDir())
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldGuideSelector := authLoginGuideActionSelector
oldGuideApplier := authLoginGuideActionApplier
oldScopeSelector := loginRecommendScopeModeSelector
oldProductSelector := loginRecommendProductSelector
oldInteractiveTerminal := authLoginInteractiveTerminal
t.Cleanup(func() {
authLoginGuideActionSelector = oldGuideSelector
authLoginGuideActionApplier = oldGuideApplier
loginRecommendScopeModeSelector = oldScopeSelector
loginRecommendProductSelector = oldProductSelector
authLoginInteractiveTerminal = oldInteractiveTerminal
})
authLoginInteractiveTerminal = func() bool { return true }
authLoginGuideActionSelector = func() (authLoginGuideAction, error) {
t.Fatal("default auth login must not call the operation guide selector")
return "", nil
}
authLoginGuideActionApplier = func(*cobra.Command, string, authLoginGuideAction) error {
t.Fatal("default auth login must not apply a post-login guide action")
return nil
}
loginRecommendScopeModeSelector = func() (pat.LoginRecommendScopeMode, error) {
t.Fatal("all-granted recommend plan must not call the scope-mode TUI")
return "", nil
}
loginRecommendProductSelector = func([]pat.LoginRecommendProduct) ([]string, error) {
t.Fatal("all-granted recommend plan must not call the product-domain TUI")
return nil, nil
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"data":{"allGranted":true,"selectedScopes":[]}}`,
}}
cmd := newAuthLoginCommand(fake)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--token", "login-token"})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth login error = %v\noutput:\n%s", err, out.String())
}
if len(fake.tools) != 1 {
t.Fatalf("CallTool count = %d, want only preflight plan", len(fake.tools))
}
if fake.tools[0] != "pat.batch_plan" {
t.Fatalf("tool sequence = %v, want only plan", fake.tools)
}
if !strings.Contains(out.String(), "推荐权限已全部授权或没有可授权项") {
t.Fatalf("output = %q, want all-granted message", out.String())
}
}
func TestAuthLoginDefaultTUIModeRecommendedAlreadyGrantedSkipsTUIAndAuthorizationPage(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, t.TempDir())
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldGuideSelector := authLoginGuideActionSelector
oldGuideApplier := authLoginGuideActionApplier
oldScopeSelector := loginRecommendScopeModeSelector
oldProductSelector := loginRecommendProductSelector
oldInteractiveTerminal := authLoginInteractiveTerminal
t.Cleanup(func() {
authLoginGuideActionSelector = oldGuideSelector
authLoginGuideActionApplier = oldGuideApplier
loginRecommendScopeModeSelector = oldScopeSelector
loginRecommendProductSelector = oldProductSelector
authLoginInteractiveTerminal = oldInteractiveTerminal
})
authLoginInteractiveTerminal = func() bool { return true }
authLoginGuideActionSelector = func() (authLoginGuideAction, error) {
t.Fatal("default auth login must not call the operation guide selector")
return "", nil
}
authLoginGuideActionApplier = func(*cobra.Command, string, authLoginGuideAction) error {
t.Fatal("default auth login must not apply a post-login guide action")
return nil
}
loginRecommendScopeModeSelector = func() (pat.LoginRecommendScopeMode, error) {
t.Fatal("already-granted recommended auth must not call the scope-mode TUI")
return "", nil
}
loginRecommendProductSelector = func([]pat.LoginRecommendProduct) ([]string, error) {
t.Fatal("already-granted recommended auth must not call product-domain TUI")
return nil, nil
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"data":{"allGranted":false,"items":[{"scope":"calendar.event:read","productCode":"calendar","productName":"日历"}],"selectedScopes":[]}}`,
}}
cmd := newAuthLoginCommand(fake)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--token", "login-token"})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth login error = %v\noutput:\n%s", err, out.String())
}
if len(fake.tools) != 1 {
t.Fatalf("CallTool count = %d, want only preflight recommend plan", len(fake.tools))
}
if fake.tools[0] != "pat.batch_plan" {
t.Fatalf("tool sequence = %v, want only plan", fake.tools)
}
if !strings.Contains(out.String(), "推荐权限已全部授权或没有可授权项") {
t.Fatalf("output = %q, want already-granted message", out.String())
}
}
func TestAuthLoginDefaultTUIRunsAfterLoginTokenSaved(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, t.TempDir())
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
oldGuideSelector := authLoginGuideActionSelector
oldGuideApplier := authLoginGuideActionApplier
oldScopeSelector := loginRecommendScopeModeSelector
oldProductSelector := loginRecommendProductSelector
oldInteractiveTerminal := authLoginInteractiveTerminal
t.Cleanup(func() {
authLoginGuideActionSelector = oldGuideSelector
authLoginGuideActionApplier = oldGuideApplier
loginRecommendScopeModeSelector = oldScopeSelector
loginRecommendProductSelector = oldProductSelector
authLoginInteractiveTerminal = oldInteractiveTerminal
})
authLoginInteractiveTerminal = func() bool { return true }
var sawTokenBeforeScopeTUI bool
var sawTokenBeforeProductTUI bool
var sawTokenBeforePlan bool
authLoginGuideActionSelector = func() (authLoginGuideAction, error) {
t.Fatal("default login must not call the operation guide selector")
return "", nil
}
authLoginGuideActionApplier = func(*cobra.Command, string, authLoginGuideAction) error {
t.Fatal("default login must not apply a post-login guide action")
return nil
}
loginRecommendScopeModeSelector = func() (pat.LoginRecommendScopeMode, error) {
token, err := authpkg.LoadTokenData(configDir)
if err != nil {
t.Fatalf("LoadTokenData before scope TUI error = %v", err)
}
if token.AccessToken != "login-token" {
t.Fatalf("AccessToken before scope TUI = %q, want login-token", token.AccessToken)
}
sawTokenBeforeScopeTUI = true
return pat.LoginRecommendScopeAll, nil
}
loginRecommendProductSelector = func(products []pat.LoginRecommendProduct) ([]string, error) {
token, err := authpkg.LoadTokenData(configDir)
if err != nil {
t.Fatalf("LoadTokenData before product TUI error = %v", err)
}
if token.AccessToken != "login-token" {
t.Fatalf("AccessToken before product TUI = %q, want login-token", token.AccessToken)
}
sawTokenBeforeProductTUI = true
if len(products) != 1 || products[0].ProductCode != "calendar" {
t.Fatalf("selector products = %+v, want calendar", products)
}
return []string{"calendar"}, nil
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"data":{"items":[{"scope":"calendar.event:read","productCode":"calendar","productName":"日历"}],"selectedScopes":["calendar.event:read"]}}`,
`{"success":true,"data":{"items":[{"scope":"calendar.event:read","productCode":"calendar","productName":"日历"}],"selectedScopes":["calendar.event:read"]}}`,
`{"success":true,"data":{"grantedScopes":["calendar.event:read"]}}`,
}, beforeCall: func(toolName string) {
token, err := authpkg.LoadTokenData(configDir)
if err != nil {
t.Fatalf("LoadTokenData before %s error = %v", toolName, err)
}
if token.AccessToken != "login-token" {
t.Fatalf("AccessToken before %s = %q, want login-token", toolName, token.AccessToken)
}
sawTokenBeforePlan = true
}}
cmd := newAuthLoginCommand(fake)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--token", "login-token"})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth login error = %v\noutput:\n%s", err, out.String())
}
if !sawTokenBeforeScopeTUI {
t.Fatal("scope-mode TUI was not called after token save")
}
if !sawTokenBeforeProductTUI {
t.Fatal("product-domain TUI was not called after token save")
}
if !sawTokenBeforePlan {
t.Fatal("authorization plan was not called after token save")
}
if len(fake.tools) != 3 {
t.Fatalf("CallTool count = %d, want discovery plan + selected plan + grant", len(fake.tools))
}
if fake.tools[0] != "pat.batch_plan" || fake.tools[1] != "pat.batch_plan" || fake.tools[2] != "pat.batch_grant" {
t.Fatalf("tool sequence = %v, want plan, plan, grant", fake.tools)
}
if got := fake.args[0]["recommend"]; got != true {
t.Fatalf("discovery plan recommend = %#v, want true", got)
}
if got := fake.args[1]["recommend"]; got != false {
t.Fatalf("selected all-scope plan recommend = %#v, want false", got)
}
if got := fake.args[1]["productCodes"]; !stringSliceArgEqual(got, []string{"calendar"}) {
t.Fatalf("selected all-scope plan productCodes = %#v, want calendar", got)
}
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
type authLoginRecommendSequenceCaller struct {
responses []string
tools []string
args []map[string]any
beforeCall func(toolName string)
}
func (f *authLoginRecommendSequenceCaller) CallTool(_ context.Context, _ string, toolName string, args map[string]any) (*edition.ToolResult, error) {
if f.beforeCall != nil {
f.beforeCall(toolName)
}
f.tools = append(f.tools, toolName)
copiedArgs := make(map[string]any, len(args))
for key, value := range args {
copiedArgs[key] = value
}
f.args = append(f.args, copiedArgs)
response := `{"success":true,"data":{}}`
if len(f.responses) > 0 {
response = f.responses[0]
f.responses = f.responses[1:]
}
return &edition.ToolResult{Content: []edition.ContentBlock{{Type: "text", Text: response}}}, nil
}
func (f *authLoginRecommendSequenceCaller) Format() string { return "table" }
func (f *authLoginRecommendSequenceCaller) DryRun() bool { return false }
func stringSliceArgEqual(got any, want []string) bool {
if got == nil {
return len(want) == 0
}
switch values := got.(type) {
case []string:
if len(values) != len(want) {
return false
}
for i := range values {
if values[i] != want[i] {
return false
}
}
return true
case []any:
if len(values) != len(want) {
return false
}
for i := range values {
if values[i] != want[i] {
return false
}
}
return true
default:
return false
}
}
+203
View File
@@ -0,0 +1,203 @@
// 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 (
"encoding/json"
"os"
"strings"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cli"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/ir"
"github.com/spf13/cobra"
)
// toolMappingParam 描述一个 MCP 参数到 CLI flag + 中文友好名的映射。
type toolMappingParam struct {
Flag string `json:"flag"`
Label string `json:"label"`
Type string `json:"type,omitempty"`
}
// toolMappingEntry 是单个 MCP 工具的映射条目。key 用 RPCName,对齐 SLS 日志的 tool 字段。
type toolMappingEntry struct {
Product string `json:"product"`
CLICommand string `json:"cliCommand"`
DisplayName string `json:"displayName"`
Params map[string]toolMappingParam `json:"params,omitempty"`
}
// toolMapping 是给开放平台日志页渲染用的全量映射契约。
type toolMapping struct {
Version string `json:"version"`
Count int `json:"count"`
Tools map[string]toolMappingEntry `json:"tools"`
}
// newCatalogCommand 提供 `dws catalog export`:把已发现的工具目录投影成
// tool→指令 映射 JSON,供开放平台 MCP/DWS 日志页把 tool/args 渲染成中文友好名。
// 复用 root 注入的带 auth 的 loader(缓存优先;建议先 `dws cache refresh`)。
func newCatalogCommand(loader cli.CatalogLoader) *cobra.Command {
catalogCmd := &cobra.Command{
Use: "catalog",
Short: "导出已发现的工具目录(内部用)",
Hidden: true,
}
var out string
var version string
exportCmd := &cobra.Command{
Use: "export",
Short: "导出 tool→指令 映射 JSON(供开放平台日志页渲染)",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
catalog, err := loader.Load(cmd.Context())
if err != nil {
return err
}
mapping := projectToolMapping(catalog, version)
data, err := json.MarshalIndent(mapping, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
if strings.TrimSpace(out) == "" {
_, werr := os.Stdout.Write(data)
return werr
}
return os.WriteFile(out, data, 0o644)
},
}
exportCmd.Flags().StringVar(&out, "out", "", "输出文件路径(默认 stdout)")
exportCmd.Flags().StringVar(&version, "version", "dev", "版本号标记")
catalogCmd.AddCommand(exportCmd)
return catalogCmd
}
// projectToolMapping 把 ir.Catalog 投影成 toolMapping 契约。
func projectToolMapping(catalog ir.Catalog, version string) toolMapping {
mapping := toolMapping{Version: version, Tools: make(map[string]toolMappingEntry)}
for _, product := range catalog.Products {
command := ""
if product.CLI != nil {
command = strings.TrimSpace(product.CLI.Command)
}
if command == "" {
command = product.ID
}
for _, tool := range product.Tools {
if tool.Hidden {
continue
}
entry := toolMappingEntry{
Product: command,
CLICommand: tmBuildCLICommand(command, tool),
DisplayName: tmFirstNonEmpty(tool.Title, tmFirstNonEmpty(tmFirstLine(tool.Description), tool.RPCName)),
Params: make(map[string]toolMappingParam),
}
for name, raw := range tmSchemaProperties(tool.InputSchema) {
prop, _ := raw.(map[string]any)
overlay, hasOverlay := tool.FlagOverlay[name]
if hasOverlay && overlay.Hidden {
continue
}
flag := tmKebab(name)
if hasOverlay && strings.TrimSpace(overlay.Alias) != "" {
flag = strings.TrimSpace(overlay.Alias)
}
label := tmMapStr(prop, "title")
if label == "" {
label = tmFirstLine(tmMapStr(prop, "description"))
}
entry.Params[name] = toolMappingParam{
Flag: flag,
Label: label,
Type: tmMapStr(prop, "type"),
}
}
if len(entry.Params) == 0 {
entry.Params = nil
}
mapping.Tools[tool.RPCName] = entry
}
}
mapping.Count = len(mapping.Tools)
return mapping
}
// tmBuildCLICommand 拼出 CLI 命令路径,如 chat + message + list -> "chat message list"。
func tmBuildCLICommand(command string, tool ir.ToolDescriptor) string {
parts := make([]string, 0, 3)
if command != "" {
parts = append(parts, command)
}
if g := strings.TrimSpace(tool.Group); g != "" {
parts = append(parts, g)
}
name := strings.TrimSpace(tool.CLIName)
if name == "" {
name = tool.RPCName
}
parts = append(parts, name)
return strings.Join(parts, " ")
}
func tmSchemaProperties(schema map[string]any) map[string]any {
if schema == nil {
return nil
}
props, _ := schema["properties"].(map[string]any)
return props
}
func tmMapStr(m map[string]any, key string) string {
if m == nil {
return ""
}
s, _ := m[key].(string)
return strings.TrimSpace(s)
}
// tmFirstLine 取第一句中文/换行前的片段,作为长描述的短标签兜底。
func tmFirstLine(s string) string {
s = strings.TrimSpace(s)
if i := strings.IndexAny(s, "\n。"); i >= 0 {
return strings.TrimSpace(s[:i])
}
return s
}
func tmFirstNonEmpty(a, b string) string {
if strings.TrimSpace(a) != "" {
return strings.TrimSpace(a)
}
return strings.TrimSpace(b)
}
// tmKebab 把 camelCase 参数名转 kebab-case 作为默认 flag。
func tmKebab(s string) string {
var b strings.Builder
for i, r := range s {
if r >= 'A' && r <= 'Z' {
if i > 0 {
b.WriteByte('-')
}
b.WriteRune(r - 'A' + 'a')
continue
}
b.WriteRune(r)
}
return b.String()
}
+91 -29
View File
@@ -24,6 +24,7 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cli"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/market"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
var (
@@ -45,8 +46,17 @@ const (
defaultPATProductID = "pat"
defaultPATDisplayName = "行为授权"
defaultPATServerID = "abc3c880fb90f04b52d1426aaf093766e5fc9ec38411688cbb74df42a584d374"
devappProductID = "devapp"
devappServerPath = "/server/op-app"
)
// devappMCPEndpoint resolves the open-platform app-management MCP endpoint
// from the configured gateway base URL, so it follows the active environment
// (production by default, pre when ~/.dws/mcp_url points at the pre gateway).
func devappMCPEndpoint() string {
return defaultPATGatewayBaseURL() + devappServerPath
}
func defaultPATServerDescriptor() market.ServerDescriptor {
return market.ServerDescriptor{
Key: defaultPATProductID,
@@ -220,12 +230,9 @@ func directRuntimeToolEndpoint(toolName string) (string, bool) {
return "", false
}
dynamicMu.RLock()
te := dynamicToolEndpoints
dynamicMu.RUnlock()
if te == nil {
return "", false
}
endpoint, ok := te[toolName]
defer dynamicMu.RUnlock()
endpoint, ok := dynamicToolEndpoints[toolName]
return endpoint, ok && strings.TrimSpace(endpoint) != ""
}
@@ -241,24 +248,27 @@ func directRuntimeEndpoint(productID, toolName string) (string, bool) {
}
}
dynamicMu.RLock()
de := dynamicEndpoints
te := dynamicToolEndpoints
dynamicMu.RUnlock()
// Hardcoded built-in: devapp is pinned to the open-platform app-management
// MCP server in source (NOT service discovery), per product decision.
for _, candidate := range []string{strings.TrimSpace(productID), normalized} {
if candidate == devappProductID {
return devappMCPEndpoint(), true
}
}
// Priority 1: product-level endpoint.
// When the caller already knows the productID (e.g. "drive"), the product
// endpoint is authoritative. This prevents cross-product tool name
// collisions (e.g. both "drive" and "doc" register "create_folder") from
// routing the request to the wrong MCP server. See issue #219.
dynamicMu.RLock()
for _, candidate := range []string{strings.TrimSpace(productID), normalized} {
if candidate == "" {
continue
}
if de != nil {
if endpoint, ok := de[candidate]; ok {
return endpoint, true
}
if endpoint, ok := dynamicEndpoints[candidate]; ok {
dynamicMu.RUnlock()
return endpoint, true
}
}
@@ -266,11 +276,13 @@ func directRuntimeEndpoint(productID, toolName string) (string, bool) {
// This path is used when the caller does not know the productID but has a
// tool name, e.g. in helper invocations or plugin routes where only the
// tool name is available.
if tool := strings.TrimSpace(toolName); tool != "" && te != nil {
if endpoint, ok := te[tool]; ok {
if tool := strings.TrimSpace(toolName); tool != "" {
if endpoint, ok := dynamicToolEndpoints[tool]; ok {
dynamicMu.RUnlock()
return endpoint, true
}
}
dynamicMu.RUnlock()
// Priority 3: built-in PAT fallback for cold-start paths that run before
// discovery/plugin registration has populated the dynamic registry.
@@ -279,18 +291,69 @@ func directRuntimeEndpoint(productID, toolName string) (string, bool) {
return defaultPATMCPEndpoint(), true
}
}
// Priority 4: edition-owned static/supplement endpoints. Helper-only
// products such as devapp intentionally do not depend on Market discovery,
// so the internal edition may provide only an endpoint and no tool list.
for _, candidate := range []string{strings.TrimSpace(productID), normalized} {
if endpoint, ok := editionServerEndpoint(candidate); ok {
return endpoint, true
}
}
return "", false
}
// DirectRuntimeProductIDs returns the set of product IDs that have direct
// runtime endpoints configured, sourced from dynamic server discovery.
func editionServerEndpoint(productID string) (string, bool) {
productID = strings.TrimSpace(productID)
if productID == "" {
return "", false
}
hooks := edition.Get()
if hooks == nil {
return "", false
}
if endpoint, ok := endpointFromEditionServers(productID, hooks.StaticServers); ok {
return endpoint, true
}
if endpoint, ok := endpointFromEditionServers(productID, hooks.SupplementServers); ok {
return endpoint, true
}
return "", false
}
func endpointFromEditionServers(productID string, fn func() []edition.ServerInfo) (string, bool) {
if fn == nil {
return "", false
}
for _, server := range fn() {
endpoint := strings.TrimSpace(server.Endpoint)
if endpoint == "" {
continue
}
if strings.TrimSpace(server.ID) == productID {
return endpoint, true
}
for _, prefix := range server.Prefixes {
if strings.TrimSpace(prefix) == productID {
return endpoint, true
}
}
}
return "", false
}
// DirectRuntimeProductIDs returns product IDs that should stay visible for
// direct runtime execution. Dynamic products come from MCP discovery/plugin
// registration; built-in helper products such as devapp resolve their endpoint
// through DINGTALK_<PRODUCT>_MCP_URL instead of requiring discovery.
func DirectRuntimeProductIDs() map[string]bool {
dynamicMu.RLock()
dp := dynamicProducts
dynamicMu.RUnlock()
ids := make(map[string]bool, len(dp)+1)
defer dynamicMu.RUnlock()
ids := make(map[string]bool, len(dynamicProducts)+2)
ids[defaultPATProductID] = true
for key := range dp {
ids[devappProductID] = true
for key := range dynamicProducts {
ids[key] = true
}
return ids
@@ -365,15 +428,14 @@ func AppendDynamicServer(server market.ServerDescriptor) {
}
func normalizeDirectRuntimeProductID(productID string) string {
dynamicMu.RLock()
da := dynamicAliases
dynamicMu.RUnlock()
trimmed := strings.TrimSpace(productID)
if da != nil {
if normalizedID, ok := da[trimmed]; ok && normalizedID != "" {
return normalizedID
}
dynamicMu.RLock()
if normalizedID, ok := dynamicAliases[trimmed]; ok && normalizedID != "" {
dynamicMu.RUnlock()
return normalizedID
}
dynamicMu.RUnlock()
if normalizedID, ok := legacyDirectRuntimeAliases[trimmed]; ok {
return normalizedID
}
+102
View File
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/market"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
func TestDefaultPATServerDescriptorUsesBehaviorAuthorizationName(t *testing.T) {
@@ -38,6 +39,107 @@ func TestDirectRuntimeProductIDsIncludesDefaultPAT(t *testing.T) {
}
}
func TestDirectRuntimeProductIDsIncludesDevappHelper(t *testing.T) {
withCleanDynamicRegistry(t)
ids := DirectRuntimeProductIDs()
if !ids["devapp"] {
t.Fatalf("DirectRuntimeProductIDs() missing devapp helper product: %#v", ids)
}
}
func TestDirectRuntimeEndpoint_DevappEnvOverrideWithoutRegistry(t *testing.T) {
withCleanDynamicRegistry(t)
t.Setenv("DINGTALK_DEVAPP_MCP_URL", "https://example.test/server/devapp")
assertEndpoint(t, "devapp", "list_dev_app", "https://example.test/server/devapp")
}
func TestDirectRuntimeEndpoint_DevappEnvOverridePreservesQuery(t *testing.T) {
withCleanDynamicRegistry(t)
t.Setenv("DINGTALK_DEVAPP_MCP_URL", "https://example.test/server/devapp?key=secret")
assertEndpoint(t, "devapp", "list_dev_app", "https://example.test/server/devapp?key=secret")
}
func TestDirectRuntimeEndpoint_DevappDynamicServerDoesNotOverrideHardcoded(t *testing.T) {
withCleanDynamicRegistry(t)
SetDynamicServers([]market.ServerDescriptor{
{
Endpoint: "https://example.test/server/devapp-supplement",
CLI: market.CLIOverlay{
ID: "devapp",
Command: "devapp",
},
},
})
assertEndpoint(t, "devapp", "list_dev_app", devappMCPEndpoint())
}
func TestDirectRuntimeEndpoint_DevappEditionSupplementDoesNotOverrideHardcoded(t *testing.T) {
withCleanDynamicRegistry(t)
prev := edition.Get()
edition.Override(&edition.Hooks{
Name: "wukong",
SupplementServers: func() []edition.ServerInfo {
return []edition.ServerInfo{
{
ID: "devapp",
Name: "开放平台应用管理",
Endpoint: "https://example.test/server/devapp-edition-supplement?key=secret",
Prefixes: []string{"devapp", "app"},
},
}
},
})
t.Cleanup(func() { edition.Override(prev) })
assertEndpoint(t, "devapp", "list_dev_app", devappMCPEndpoint())
}
func TestDirectRuntimeEndpoint_DevappEditionStaticDoesNotOverrideHardcoded(t *testing.T) {
withCleanDynamicRegistry(t)
prev := edition.Get()
edition.Override(&edition.Hooks{
Name: "wukong",
StaticServers: func() []edition.ServerInfo {
return []edition.ServerInfo{
{
ID: "devapp",
Name: "开放平台应用管理",
Endpoint: "https://example.test/server/devapp-edition-static",
Prefixes: []string{"devapp", "app"},
},
}
},
})
t.Cleanup(func() { edition.Override(prev) })
assertEndpoint(t, "devapp", "list_dev_app", devappMCPEndpoint())
}
func TestDirectRuntimeEndpoint_DevappEnvOverrideWinsOverEditionSupplement(t *testing.T) {
withCleanDynamicRegistry(t)
t.Setenv("DINGTALK_DEVAPP_MCP_URL", "https://example.test/server/devapp-env")
prev := edition.Get()
edition.Override(&edition.Hooks{
Name: "wukong",
SupplementServers: func() []edition.ServerInfo {
return []edition.ServerInfo{
{
ID: "devapp",
Name: "开放平台应用管理",
Endpoint: "https://example.test/server/devapp-edition-supplement",
},
}
},
})
t.Cleanup(func() { edition.Override(prev) })
assertEndpoint(t, "devapp", "list_dev_app", "https://example.test/server/devapp-env")
}
func TestDirectRuntimeEndpoint_DefaultPATFallbackWhenRegistryMissing(t *testing.T) {
withCleanDynamicRegistry(t)
assertEndpoint(t, "pat", "", defaultPATMCPEndpoint())
+19 -8
View File
@@ -24,6 +24,7 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cache"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/market"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/output"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/tui"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/upgrade"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
@@ -112,7 +113,8 @@ func runDoctor(cmd *cobra.Command, _ []string) error {
return output.WriteJSON(w, result)
}
fmt.Fprintf(w, "\n诊断完成: %d 项通过, %d 项警告, %d 项失败\n", pass, warn, fail)
fmt.Fprintf(w, "\n%s\n", tui.Header("Doctor", fmt.Sprintf("%d pass · %d warn · %d fail", pass, warn, fail)))
fmt.Fprintf(w, "%s 诊断完成: %d 项通过, %d 项警告, %d 项失败\n", tui.StateMark("ok"), pass, warn, fail)
if fail > 0 {
return fmt.Errorf("诊断发现 %d 项失败", fail)
}
@@ -123,7 +125,7 @@ func runDoctor(cmd *cobra.Command, _ []string) error {
func doctorCheckAuth(ctx context.Context, w io.Writer, jsonOut bool) checkResult {
if !jsonOut {
fmt.Fprint(w, "检查登录状态... ")
fmt.Fprint(w, tui.Dim("检查登录状态... "))
}
configDir := defaultConfigDir()
@@ -186,7 +188,7 @@ func doctorCheckAuth(ctx context.Context, w io.Writer, jsonOut bool) checkResult
func doctorCheckNetwork(ctx context.Context, w io.Writer, jsonOut bool, timeout time.Duration) checkResult {
if !jsonOut {
fmt.Fprint(w, "检查网络连通性... ")
fmt.Fprint(w, tui.Dim("检查网络连通性... "))
}
baseURL := config.GetMCPBaseURL()
@@ -228,7 +230,7 @@ func doctorCheckNetwork(ctx context.Context, w io.Writer, jsonOut bool, timeout
func doctorCheckCache(w io.Writer, jsonOut bool) checkResult {
if !jsonOut {
fmt.Fprint(w, "检查缓存状态... ")
fmt.Fprint(w, tui.Dim("检查缓存状态... "))
}
store := cacheStoreFromEnv()
@@ -300,7 +302,7 @@ func doctorCheckCache(w io.Writer, jsonOut bool) checkResult {
func doctorCheckVersion(w io.Writer, jsonOut bool, timeout time.Duration) checkResult {
if !jsonOut {
fmt.Fprint(w, "检查版本更新... ")
fmt.Fprint(w, tui.Dim("检查版本更新... "))
}
currentVer := version
@@ -348,9 +350,18 @@ func doctorCheckVersion(w io.Writer, jsonOut bool, timeout time.Duration) checkR
func printCheckResult(w io.Writer, r checkResult) {
icon := statusIcon(r.Status)
fmt.Fprintf(w, "%s %s\n", icon, r.Message)
message := r.Message
switch r.Status {
case statusPass:
message = tui.Success(message)
case statusWarn:
message = tui.Warning(message)
case statusFail:
message = tui.Danger(message)
}
fmt.Fprintf(w, "%s %s\n", icon, message)
if r.Hint != "" {
fmt.Fprintf(w, " %s\n", r.Hint)
fmt.Fprintf(w, " %s\n", tui.Dim(r.Hint))
}
}
@@ -385,7 +396,7 @@ func countResults(checks []checkResult) (pass, warn, fail int) {
func doctorCheckPerf(w io.Writer, jsonOut bool) checkResult {
if !jsonOut {
fmt.Fprint(w, "检查性能报告... ")
fmt.Fprint(w, tui.Dim("检查性能报告... "))
}
report, err := LoadLatestReport()
+3 -1
View File
@@ -55,9 +55,11 @@ func TestRootCommandDoesNotInjectPatchedHelpCommands(t *testing.T) {
t.Cleanup(func() { SetDiscoveryBaseURL("") })
root := NewRootCommand()
// `minutes list all` is intentionally provided as a hardcoded helper
// (see internal/helpers/minutes_commands.go) to align with the wukong
// baseline, so it is expected to resolve and is no longer asserted here.
for _, path := range []string{
"chat message list-topic-replies",
"minutes list all",
} {
if cmd := lookupCommand(root, path); cmd != nil {
t.Fatalf("findCommand(%q) = %q, want nil", path, cmd.CommandPath())
+136
View File
@@ -0,0 +1,136 @@
// 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 (
"context"
"fmt"
"sync"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cli"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
)
// newHelperToolFetcher returns a cli.HelperToolFetcher that loads a helper MCP
// server's tools/list LIVE (by source) and projects each tool into a
// cli.HelperToolSchema (name, description, inputSchema properties/required). It
// is injected into the schema command so the cli package can render
// `dws schema dev.*` from real server schema without importing app/transport.
//
// Sources: "op-app" backs the dev app commands (pinned endpoint); "devdoc"
// backs `dws dev doc search` (endpoint resolved dynamically, see
// helperSourceEndpoint). Results are memoized per source per process so
// repeated `dws schema dev.*` hit the network at most once per source. A failed
// fetch is not cached, allowing a later retry within the same process.
func newHelperToolFetcher() cli.HelperToolFetcher {
var (
mu sync.Mutex
cached = map[string]map[string]cli.HelperToolSchema{}
)
return func(ctx context.Context, source string) (map[string]cli.HelperToolSchema, error) {
mu.Lock()
if got, ok := cached[source]; ok {
mu.Unlock()
return got, nil
}
mu.Unlock()
endpoint, err := helperSourceEndpoint(source)
if err != nil {
return nil, err
}
schemas, err := fetchHelperToolSchemas(ctx, endpoint)
if err != nil {
return nil, err
}
mu.Lock()
cached[source] = schemas
mu.Unlock()
return schemas, nil
}
}
// helperSourceEndpoint maps a schema source to its MCP endpoint. op-app (dev
// app) is pinned in source (devappMCPEndpoint, derived from the active gateway
// base — production by default, pre when ~/.dws/mcp_url points at pre); other
// sources (e.g. devdoc) are resolved the same way the runner resolves a product
// endpoint — env override → discovery → edition StaticServers/SupplementServers.
func helperSourceEndpoint(source string) (string, error) {
switch source {
case "", "op-app", "devapp":
return devappMCPEndpoint(), nil
default:
if endpoint, ok := directRuntimeEndpoint(source, ""); ok {
return endpoint, nil
}
return "", fmt.Errorf("no MCP endpoint resolved for source %q (not injected by edition/discovery)", source)
}
}
// fetchHelperToolSchemas performs the live tools/list call against endpoint and
// converts the descriptors. Auth and identity headers are resolved the same way
// the runner does for direct-runtime invocations.
func fetchHelperToolSchemas(ctx context.Context, endpoint string) (map[string]cli.HelperToolSchema, error) {
token := resolveRuntimeAuthToken(ctx, "")
headers := resolveIdentityHeaders()
client := transport.NewClient(nil).WithAuth(token, headers)
result, err := client.ListTools(ctx, endpoint)
if err != nil {
return nil, err
}
out := make(map[string]cli.HelperToolSchema, len(result.Tools))
for _, td := range result.Tools {
out[td.Name] = cli.HelperToolSchema{
Name: td.Name,
Description: td.Description,
Properties: inputSchemaProperties(td.InputSchema),
Required: inputSchemaRequired(td.InputSchema),
}
}
return out, nil
}
// inputSchemaProperties pulls the "properties" object out of a deserialized
// MCP inputSchema map. Returns an empty (non-nil) map when absent.
func inputSchemaProperties(schema map[string]any) map[string]any {
if schema == nil {
return map[string]any{}
}
props, _ := schema["properties"].(map[string]any)
if props == nil {
return map[string]any{}
}
return props
}
// inputSchemaRequired pulls the "required" string list out of a deserialized
// MCP inputSchema map.
func inputSchemaRequired(schema map[string]any) []string {
if schema == nil {
return nil
}
raw, ok := schema["required"].([]any)
if !ok {
return nil
}
out := make([]string, 0, len(raw))
for _, v := range raw {
if s, ok := v.(string); ok && s != "" {
out = append(out, s)
}
}
return out
}
+9 -2
View File
@@ -310,7 +310,7 @@ func loadDynamicCommands(ctx context.Context, runner executor.Runner) []*cobra.C
// no-op: fall through to FallbackServers check below
}
} else {
servers = market.NormalizeServers(resp, "market")
servers = market.NormalizeServersForBaseURL(resp, "market", registryDiscoveryBaseURL())
if discoveryTraceEnabled() {
slog.Info("loadDynamicCommands: sync discovery fetch ok",
"partition", partition,
@@ -568,6 +568,13 @@ func fetchRegistryServers(ctx context.Context, httpClient *http.Client) (market.
return client.FetchServers(ctx, config.DefaultFetchServersLimit)
}
func registryDiscoveryBaseURL() string {
if editionURL := strings.TrimSpace(edition.Get().DiscoveryURL); editionURL != "" {
return editionURL
}
return DiscoveryBaseURL()
}
// asyncRevalidateRegistry refreshes the registry cache in the background.
// Uses a short timeout derived from the parent context and silently ignores
// errors — the next CLI invocation will pick up the refreshed cache or retry.
@@ -580,7 +587,7 @@ func asyncRevalidateRegistry(parent context.Context, store *cache.Store, partiti
slog.Debug("asyncRevalidateRegistry: fetch failed", "error", err)
return
}
servers := market.NormalizeServers(resp, "market")
servers := market.NormalizeServersForBaseURL(resp, "market", registryDiscoveryBaseURL())
if saveErr := store.SaveRegistry(partition, cache.RegistrySnapshot{Servers: servers}); saveErr != nil {
slog.Debug("asyncRevalidateRegistry: save failed", "error", saveErr)
}
+2 -2
View File
@@ -359,7 +359,7 @@ func TestLoadDynamicCommandsDoesNotSynchronouslyFetchDetailMetadata(t *testing.T
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/cli/discovery/apis/bamboo":
case r.URL.Path == "/cli/discovery/apis/cedar":
payload := map[string]any{
"metadata": map[string]any{"count": 2, "nextCursor": ""},
"servers": []any{
@@ -433,7 +433,7 @@ func TestLoadDynamicCommandsDoesNotSynchronouslyFetchDetailMetadataWhenRegistryT
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/cli/discovery/apis/bamboo":
case r.URL.Path == "/cli/discovery/apis/cedar":
_ = json.NewEncoder(w).Encode(map[string]any{
"metadata": map[string]any{"count": 2, "nextCursor": ""},
"servers": []any{
+200 -71
View File
@@ -33,8 +33,9 @@ import (
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/jsonutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pat"
"github.com/fatih/color"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/tui"
)
const (
@@ -51,6 +52,10 @@ const (
var openBrowserFunc = tryOpenBrowser
type patSuppressBrowserOpenKeyType struct{}
var patSuppressBrowserOpenKey = patSuppressBrowserOpenKeyType{}
// PatScopeError holds information about a missing PAT scope.
type PatScopeError struct {
OriginalError string
@@ -153,36 +158,31 @@ func extractPatScopeError(err error) *PatScopeError {
// PrintPatAuthError prints a human-readable PAT authorization error.
func PrintPatAuthError(w io.Writer, scopeErr *PatScopeError) {
bold := color.New(color.Bold).SprintFunc()
cyan := color.New(color.FgCyan).SprintFunc()
dim := color.New(color.Faint).SprintFunc()
green := color.New(color.FgGreen).SprintFunc()
fmt.Fprintln(w)
fmt.Fprintf(w, "{\n")
fmt.Fprintf(w, " %s: %s,\n", bold("\"ok\""), "false")
fmt.Fprintf(w, " %s: %q,\n", bold("\"identity\""), scopeErr.Identity)
fmt.Fprintf(w, " %s: {\n", bold("\"error\""))
fmt.Fprintf(w, " %s: %q,\n", bold("\"type\""), scopeErr.ErrorType)
fmt.Fprintf(w, " %s: %q,\n", bold("\"message\""), scopeErr.Message)
fmt.Fprintf(w, " %s: %q\n", bold("\"hint\""), scopeErr.Hint)
fmt.Fprintf(w, " %s: %s,\n", tui.Bold("\"ok\""), "false")
fmt.Fprintf(w, " %s: %q,\n", tui.Bold("\"identity\""), scopeErr.Identity)
fmt.Fprintf(w, " %s: {\n", tui.Bold("\"error\""))
fmt.Fprintf(w, " %s: %q,\n", tui.Bold("\"type\""), scopeErr.ErrorType)
fmt.Fprintf(w, " %s: %q,\n", tui.Bold("\"message\""), scopeErr.Message)
fmt.Fprintf(w, " %s: %q\n", tui.Bold("\"hint\""), scopeErr.Hint)
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, "}\n")
fmt.Fprintln(w)
// Print authorization instructions
fmt.Fprintf(w, "%s %s\n", green("▶"), bold("需要额外授权"))
fmt.Fprintf(w, "%s %s\n", tui.StateMark("warning"), tui.Bold("需要额外授权"))
fmt.Fprintln(w)
fmt.Fprintf(w, " %s %s\n", dim("#"), dim("运行以下命令完成授权"))
fmt.Fprintf(w, " %s %s\n", tui.Dim("#"), tui.Dim("运行以下命令完成授权"))
if scopeErr.MissingScope != "" {
fmt.Fprintf(w, " %s %s\n", cyan("$"), cyan(fmt.Sprintf("dws auth login --scope %q", scopeErr.MissingScope)))
fmt.Fprintf(w, " %s %s\n", tui.Cyan("$"), tui.Cyan(fmt.Sprintf("dws auth login --scope %q", scopeErr.MissingScope)))
} else {
fmt.Fprintf(w, " %s %s\n", cyan("$"), cyan("dws auth login"))
fmt.Fprintf(w, " %s %s\n", tui.Cyan("$"), tui.Cyan("dws auth login"))
}
fmt.Fprintln(w)
fmt.Fprintf(w, " %s 在浏览器中打开授权链接,完成授权后重新执行命令\n", dim("ℹ"))
fmt.Fprintf(w, " %s 在浏览器中打开授权链接,完成授权后重新执行命令\n", tui.Dim("ℹ"))
fmt.Fprintln(w)
}
@@ -206,7 +206,10 @@ func wantsStructuredPATOutputFromRunner(runner executor.Runner) bool {
return wantsStructuredPATOutput(rr)
}
func currentPATOpenBrowser(configDir string) bool {
func currentPATOpenBrowser(ctx context.Context, configDir string) bool {
if suppressed, _ := ctx.Value(patSuppressBrowserOpenKey).(bool); suppressed {
return false
}
return pat.EffectiveOpenBrowser(configDir)
}
@@ -225,8 +228,11 @@ func enrichPATErrorWithOpenBrowser(raw string, openBrowser bool) string {
data = map[string]any{}
payload["data"] = data
}
if rawURI, ok := data["uri"].(string); ok && strings.TrimSpace(rawURI) != "" {
data["authorizationUrl"] = apperrors.PATAuthorizationURL(rawURI)
if rawURI := patAuthorizationURIFromData(data); rawURI != "" {
authURL := apperrors.PATAuthorizationURL(rawURI)
data["uri"] = authURL
delete(data, "authUrl")
delete(data, "authorizationUrl")
}
data["openBrowser"] = openBrowser
@@ -237,15 +243,19 @@ func enrichPATErrorWithOpenBrowser(raw string, openBrowser bool) string {
return string(encoded)
}
func patAuthorizationURIFromData(data map[string]any) string {
for _, key := range []string{"uri", "authUrl", "authorizationUrl"} {
value, _ := data[key].(string)
if strings.TrimSpace(value) != "" {
return strings.TrimSpace(value)
}
}
return ""
}
// WaitForPatAuthorization polls until the user completes authorization or timeout.
// It returns true if authorization was completed, false if timed out or cancelled.
func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Writer) bool {
bold := color.New(color.Bold).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
green := color.New(color.FgGreen).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
dim := color.New(color.Faint).SprintFunc()
timeout := PatAuthRetryTimeout
deadline := time.Now().Add(timeout)
pollTicker := time.NewTicker(PatAuthPollInterval)
@@ -253,21 +263,21 @@ func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Wr
start := time.Now()
fmt.Fprintln(output)
fmt.Fprintf(output, "%s %s\n", yellow("⏳"), bold("等待用户授权..."))
fmt.Fprintf(output, " %s 请在另一个终端完成 dws auth login 授权\n", dim("ℹ"))
fmt.Fprintf(output, " %s 超时时间: %s\n", dim("⏱"), timeout)
fmt.Fprintf(output, "%s %s\n", tui.StateMark("pending"), tui.Bold("等待用户授权..."))
fmt.Fprintf(output, " %s 请在另一个终端完成 dws auth login 授权\n", tui.Dim("ℹ"))
fmt.Fprintf(output, " %s 超时时间: %s\n", tui.Dim("⏱"), timeout)
fmt.Fprintln(output)
pollCount := 0
for {
select {
case <-ctx.Done():
fmt.Fprintf(output, "%s 操作已取消\n", red("✗"))
fmt.Fprintf(output, "%s 操作已取消\n", tui.StateMark("error"))
return false
case <-time.After(time.Until(deadline)):
fmt.Fprintf(output, "%s 等待授权超时 (%s)\n", red("✗"), timeout)
fmt.Fprintf(output, " %s 请重新执行命令\n", dim("ℹ"))
fmt.Fprintf(output, "%s 等待授权超时 (%s)\n", tui.StateMark("error"), timeout)
fmt.Fprintf(output, " %s 请重新执行命令\n", tui.Dim("ℹ"))
return false
case <-pollTicker.C:
@@ -280,7 +290,7 @@ func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Wr
if err == nil && tokenData != nil {
if tokenData.IsAccessTokenValid() || tokenData.IsRefreshTokenValid() {
fmt.Fprintf(output, "\r%s %s (%s 已用, %s 剩余) \n",
green("✓"), bold("授权成功!"), elapsed, remaining)
tui.StateMark("ok"), tui.Bold("授权成功!"), elapsed, remaining)
fmt.Fprintln(output)
return true
}
@@ -288,7 +298,7 @@ func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Wr
// Show polling status
fmt.Fprintf(output, "\r%s [%d] 等待授权中... (%s 已用, %s 剩余) ",
dim("⟳"), pollCount, elapsed, remaining)
tui.Dim("⟳"), pollCount, elapsed, remaining)
}
}
}
@@ -328,8 +338,7 @@ func retryWithPatAuthRetry(ctx context.Context, runner executor.Runner, invocati
// Retry the invocation
fmt.Fprintln(output)
fmt.Fprintf(output, "%s %s\n", color.New(color.FgGreen).SprintFunc()("▶"),
color.New(color.Bold).SprintFunc()("授权完成,正在重试..."))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("ok"), tui.Bold("授权完成,正在重试..."))
fmt.Fprintln(output)
return runner.Run(ctx, invocation)
@@ -340,6 +349,9 @@ func retryWithPatAuthRetry(ctx context.Context, runner executor.Runner, invocati
const (
// patPollInterval is how often we poll the device flow status endpoint.
patPollInterval = 2 * time.Second
// patMaxPollInterval caps a server-provided poll interval so a malformed
// response cannot make the CLI look permanently stuck.
patMaxPollInterval = 30 * time.Second
// patPollTimeout is the maximum time to wait for user authorization via device flow.
patPollTimeout = 10 * time.Minute
)
@@ -350,6 +362,12 @@ type patRetryingKeyType struct{}
var patRetryingKey = patRetryingKeyType{}
type patRetryRunnerFunc func(context.Context, executor.Invocation) (executor.Result, error)
func (f patRetryRunnerFunc) Run(ctx context.Context, invocation executor.Invocation) (executor.Result, error) {
return f(ctx, invocation)
}
// IsPatRetrying returns true if the current context is already in a PAT retry.
func IsPatRetrying(ctx context.Context) bool {
v, _ := ctx.Value(patRetryingKey).(bool)
@@ -364,8 +382,8 @@ func openPATAuthorizationURI(rawURI string) error {
}
// The PAT service returns the complete authorization URL. Treat it as an
// opaque string unless it is the known legacy DingTalk hash-route variant.
// That variant is normalized by the PAT error contract helper while still
// preserving the original data.uri in structured output.
// That variant is normalized by the PAT error contract helper before being
// printed, opened, or returned in structured output.
return openBrowserFunc(apperrors.PATAuthorizationURL(rawURI))
}
@@ -382,6 +400,70 @@ func printPATPollDebugResponse(output io.Writer, statusCode int, body []byte) {
fmt.Fprintf(output, " %s\n", trimmed)
}
func runDirectPATAuthCheck(
ctx context.Context,
globalFlags *GlobalFlags,
patErr *apperrors.PATError,
retry func(context.Context) error,
output io.Writer,
) error {
if retry == nil {
return patErr
}
return runDirectPATAuthCheckWithMode(ctx, globalFlags, patErr, retry, output, true)
}
func runDirectPATAuthCheckWaitOnly(
ctx context.Context,
globalFlags *GlobalFlags,
patErr *apperrors.PATError,
output io.Writer,
) error {
ctx = context.WithValue(ctx, patSuppressBrowserOpenKey, true)
return runDirectPATAuthCheckWithMode(ctx, globalFlags, patErr, nil, output, false)
}
func runDirectPATAuthCheckWithMode(
ctx context.Context,
globalFlags *GlobalFlags,
patErr *apperrors.PATError,
retry func(context.Context) error,
output io.Writer,
retryAfterApproval bool,
) error {
if retryAfterApproval && retry == nil {
return patErr
}
runner := &runtimeRunner{
globalFlags: globalFlags,
fallback: patRetryRunnerFunc(func(retryCtx context.Context, invocation executor.Invocation) (executor.Result, error) {
if retry != nil {
if err := retry(retryCtx); err != nil {
return executor.Result{}, err
}
}
invocation.Implemented = true
return executor.Result{
Invocation: invocation,
Response: map[string]any{
"ok": true,
},
}, nil
}),
}
_, err := handlePatAuthCheck(ctx, runner, executor.Invocation{
Kind: "direct_pat_authorization",
Stage: "auth_login_recommend",
CanonicalProduct: defaultPATProductID,
Tool: "pat.batch_grant",
CanonicalPath: "pat.batch_grant",
Params: map[string]any{
"retryAfterApproval": retryAfterApproval,
},
}, patErr, defaultConfigDir(), output)
return err
}
// handlePatAuthCheck is called by runner.executeInvocation when a PAT
// authorization error is detected. It injects the server-assigned clientId
// as x-robot-uid header, prints authorization details, opens the browser,
@@ -399,16 +481,25 @@ func handlePatAuthCheck(
var patData struct {
Code string `json:"code"`
Data struct {
Desc string `json:"desc"`
FlowID string `json:"flowId"`
URI string `json:"uri"`
ClientID string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
Desc string `json:"desc"`
FlowID string `json:"flowId"`
URI string `json:"uri"`
AuthURL string `json:"authUrl"`
AuthorizationURL string `json:"authorizationUrl"`
ClientID string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
PollIntervalSecs int `json:"pollIntervalSeconds"`
} `json:"data"`
}
if err := json.Unmarshal([]byte(patErr.RawJSON), &patData); err != nil {
return executor.Result{}, patErr
}
if patData.Data.URI == "" {
patData.Data.URI = patData.Data.AuthURL
}
if patData.Data.URI == "" {
patData.Data.URI = patData.Data.AuthorizationURL
}
slog.Debug("PAT auth check",
"clientId", patData.Data.ClientID,
@@ -416,7 +507,7 @@ func handlePatAuthCheck(
"hasSecret", patData.Data.ClientSecret != "",
)
hostOwnedPAT := authpkg.HostOwnsPATFlow()
openBrowser := currentPATOpenBrowser(configDir)
openBrowser := currentPATOpenBrowser(ctx, configDir)
slog.Debug("pat.host_owned_decision",
"site", "handlePatAuthCheck",
"hostOwned", hostOwnedPAT,
@@ -466,44 +557,40 @@ func handlePatAuthCheck(
return executor.Result{}, &apperrors.PATError{RawJSON: enrichPATErrorWithOpenBrowser(patErr.RawJSON, openBrowser)}
}
bold := color.New(color.Bold).SprintFunc()
cyan := color.New(color.FgCyan).SprintFunc()
greenFn := color.New(color.FgGreen).SprintFunc()
yellowFn := color.New(color.FgYellow).SprintFunc()
redFn := color.New(color.FgRed).SprintFunc()
dim := color.New(color.Faint).SprintFunc()
fmt.Fprintln(output)
fmt.Fprintf(output, "%s %s\n", greenFn("▶"), bold("需要 PAT 授权"))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("warning"), tui.Bold("需要 PAT 授权"))
if patData.Data.Desc != "" {
fmt.Fprintf(output, " %s %s\n", dim("ℹ"), patData.Data.Desc)
fmt.Fprintf(output, " %s %s\n", tui.Dim("ℹ"), patData.Data.Desc)
}
if patData.Data.URI != "" {
authURL := apperrors.PATAuthorizationURL(patData.Data.URI)
fmt.Fprintf(output, " %s 授权链接: %s\n", dim("🔗"), cyan(authURL))
fmt.Fprintf(output, " PAT_AUTHORIZATION_URL=%s\n\n", authURL)
fmt.Fprintf(output, " %s 授权链接: %s\n", tui.Dim("🔗"), authURL)
fmt.Fprintln(output)
if openBrowser {
_ = openPATAuthorizationURI(authURL)
}
}
// Poll the device flow status until user authorizes, rejects, or timeout.
fmt.Fprintf(output, "%s %s\n", yellowFn("⏳"), bold("等待用户授权..."))
fmt.Fprintf(output, " %s 请在浏览器中完成授权,超时时间: %s\n", dim("ℹ"), patPollTimeout)
fmt.Fprintf(output, "%s %s\n", tui.StateMark("pending"), tui.Bold("等待用户授权..."))
fmt.Fprintf(output, " %s 请在浏览器中完成授权,超时时间: %s\n", tui.Dim("ℹ"), patPollTimeout)
fmt.Fprintln(output)
pollCtx, cancel := context.WithTimeout(ctx, patPollTimeout)
defer cancel()
status, authCode, err := pollPatDeviceFlow(pollCtx, patData.Data.FlowID, configDir, output)
status, authCode, err := pollPatDeviceFlowWithInterval(
pollCtx, patData.Data.FlowID, configDir, output,
resolvePATPollInterval(patData.Data.PollIntervalSecs),
)
if err != nil {
fmt.Fprintf(output, "%s 轮询授权状态失败: %v\n", redFn("✗"), err)
fmt.Fprintf(output, "%s 轮询授权状态失败: %v\n", tui.StateMark("error"), err)
return executor.Result{}, patErr
}
switch status {
case authpkg.StatusApproved:
fmt.Fprintf(output, "%s %s\n", greenFn("✓"), bold("授权成功!"))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("ok"), tui.Bold("授权成功!"))
fmt.Fprintln(output)
if appCfg != nil {
@@ -519,11 +606,11 @@ func handlePatAuthCheck(
tokenData, exchErr := authpkg.ExchangeCodeForToken(ctx, configDir, authCode)
if exchErr != nil {
slog.Warn("PAT retry: exchangeCode failed, retrying with existing token", "error", exchErr)
fmt.Fprintf(output, " %s 换取新 token 失败: %v (将使用现有凭证重试)\n", yellowFn("⚠"), exchErr)
fmt.Fprintf(output, " %s 换取新 token 失败: %v (将使用现有凭证重试)\n", tui.StateMark("warning"), exchErr)
} else {
if err := authpkg.SaveTokenData(configDir, tokenData); err != nil {
slog.Warn("PAT retry: failed to save new token", "error", err)
fmt.Fprintf(output, " %s 保存新 token 失败: %v\n", yellowFn("⚠"), err)
fmt.Fprintf(output, " %s 保存新 token 失败: %v\n", tui.StateMark("warning"), err)
} else {
slog.Debug("PAT retry: token refreshed and saved")
}
@@ -533,13 +620,23 @@ func handlePatAuthCheck(
// Clear token cache so the new credentials take effect.
ResetRuntimeTokenCache()
if shouldSkipPATRetryAfterApproval(invocation) {
invocation.Implemented = true
return executor.Result{
Invocation: invocation,
Response: map[string]any{
"ok": true,
},
}, nil
}
// Workaround: brief delay to let server-side authorization state propagate
// before retrying. Without this the retry may use stale credentials.
slog.Debug("PAT retry: waiting for server-side state propagation", "delay", "1s")
time.Sleep(1 * time.Second)
// Retry the original invocation with pat-retrying flag to prevent recursion.
fmt.Fprintf(output, "%s %s\n", greenFn("▶"), bold("授权完成,正在重试..."))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("ok"), tui.Bold("授权完成,正在重试..."))
fmt.Fprintln(output)
slog.Debug("PAT retry: identity env check",
"DWS_CLIENT_ID", os.Getenv("DWS_CLIENT_ID"),
@@ -548,7 +645,7 @@ func handlePatAuthCheck(
return r.Run(retryCtx, invocation)
case authpkg.StatusRejected:
fmt.Fprintf(output, "%s %s\n", redFn("✗"), bold("用户已拒绝授权"))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("error"), tui.Bold("用户已拒绝授权"))
return executor.Result{}, apperrors.NewAuth(
"用户已拒绝授权",
apperrors.WithReason("pat_auth_rejected"),
@@ -556,7 +653,7 @@ func handlePatAuthCheck(
)
case authpkg.StatusExpired:
fmt.Fprintf(output, "%s %s\n", redFn("✗"), bold("授权超时"))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("error"), tui.Bold("授权超时"))
return executor.Result{}, apperrors.NewAuth(
"授权超时",
apperrors.WithReason("pat_auth_expired"),
@@ -564,7 +661,7 @@ func handlePatAuthCheck(
)
case authpkg.StatusCancelled:
fmt.Fprintf(output, "%s %s\n", redFn("✗"), bold("操作已取消"))
fmt.Fprintf(output, "%s %s\n", tui.StateMark("error"), tui.Bold("操作已取消"))
return executor.Result{}, apperrors.NewAuth(
"操作已取消",
apperrors.WithReason("pat_auth_cancelled"),
@@ -572,11 +669,23 @@ func handlePatAuthCheck(
)
default:
fmt.Fprintf(output, "%s 未知授权状态: %s\n", redFn("✗"), status)
fmt.Fprintf(output, "%s 未知授权状态: %s\n", tui.StateMark("error"), status)
return executor.Result{}, patErr
}
}
func shouldSkipPATRetryAfterApproval(invocation executor.Invocation) bool {
if invocation.Params == nil {
return false
}
value, ok := invocation.Params["retryAfterApproval"]
if !ok {
return false
}
retry, ok := value.(bool)
return ok && !retry
}
func enrichPATErrorForHostControl(raw string) string {
if strings.TrimSpace(raw) == "" {
return raw
@@ -630,7 +739,7 @@ func buildPATScopeJSON(scopeErr *PatScopeError, includeHostControl bool) string
"data": data,
}
// stderr JSON MUST be single-line.
b, err := json.Marshal(payload)
b, err := jsonutil.Marshal(payload)
if err != nil {
return `{"success":false,"code":"PAT_SCOPE_AUTH_REQUIRED"}`
}
@@ -655,6 +764,13 @@ func marshalSingleLineJSONNoHTMLEscape(v any) ([]byte, error) {
// state (APPROVED/REJECTED/EXPIRED) is reached or the context is cancelled.
// Returns the final status string and the authCode (non-empty only on APPROVED).
func pollPatDeviceFlow(ctx context.Context, flowID string, configDir string, output io.Writer) (string, string, error) {
return pollPatDeviceFlowWithInterval(ctx, flowID, configDir, output, patPollInterval)
}
func pollPatDeviceFlowWithInterval(ctx context.Context, flowID string, configDir string, output io.Writer, interval time.Duration) (string, string, error) {
if interval <= 0 {
interval = patPollInterval
}
pollURL := fmt.Sprintf("%s%s?flowId=%s",
authpkg.GetMCPBaseURL(), authpkg.DevicePollPath, url.QueryEscape(flowID))
@@ -671,10 +787,9 @@ func pollPatDeviceFlow(ctx context.Context, flowID string, configDir string, out
},
}
ticker := time.NewTicker(patPollInterval)
ticker := time.NewTicker(interval)
defer ticker.Stop()
dim := color.New(color.Faint).SprintFunc()
pollCount := 0
for {
@@ -686,7 +801,7 @@ func pollPatDeviceFlow(ctx context.Context, flowID string, configDir string, out
return authpkg.StatusExpired, "", nil
case <-ticker.C:
pollCount++
fmt.Fprintf(output, "\r%s [%d] 等待授权中... ", dim("⟳"), pollCount)
fmt.Fprintf(output, "\r%s [%d] 等待授权中... ", tui.Dim("⟳"), pollCount)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, pollURL, nil)
if err != nil {
@@ -738,6 +853,20 @@ func pollPatDeviceFlow(ctx context.Context, flowID string, configDir string, out
}
}
func resolvePATPollInterval(seconds int) time.Duration {
if seconds <= 0 {
return patPollInterval
}
interval := time.Duration(seconds) * time.Second
if interval < time.Second {
return time.Second
}
if interval > patMaxPollInterval {
return patMaxPollInterval
}
return interval
}
func browserOpenCommand(goos, rawURL string) *exec.Cmd {
switch goos {
case "darwin":
+216 -9
View File
@@ -608,8 +608,14 @@ func TestEnrichPATErrorWithOpenBrowserKeepsAuthorizationURLAmpersandReadable(t *
t.Fatalf("json.Unmarshal(enriched PAT payload) error = %v\nraw=%s", err, out)
}
data, _ := payload["data"].(map[string]any)
if got, _ := data["authorizationUrl"].(string); got != rawURI {
t.Fatalf("data.authorizationUrl = %q, want %q", got, rawURI)
if got, _ := data["uri"].(string); got != rawURI {
t.Fatalf("data.uri = %q, want %q", got, rawURI)
}
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted from enriched PAT payload")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted from enriched PAT payload")
}
}
@@ -656,6 +662,192 @@ func TestHandlePatAuthCheck_Approved(t *testing.T) {
}
}
func TestRunDirectPATAuthCheck_ApprovedRetriesCallback(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
server, _ := setupHandlePATServer(t, "APPROVED", "")
defer server.Close()
patErr := &apperrors.PATError{RawJSON: makePATErrorJSONWithURI("flow-direct", "test-client-id", "https://example.com/pat")}
var retried atomic.Bool
var retryHadKey atomic.Bool
err := runDirectPATAuthCheck(context.Background(), &GlobalFlags{}, patErr, func(ctx context.Context) error {
retried.Store(true)
retryHadKey.Store(IsPatRetrying(ctx))
return nil
}, &bytes.Buffer{})
if err != nil {
t.Fatalf("runDirectPATAuthCheck error = %v", err)
}
if !retried.Load() {
t.Fatal("expected direct PAT auth retry callback to run")
}
if !retryHadKey.Load() {
t.Fatal("expected direct PAT auth retry context to be marked as PAT retrying")
}
}
func TestRunDirectPATAuthCheckWaitOnly_ApprovedDoesNotRetry(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
server, _ := setupHandlePATServer(t, "APPROVED", "")
defer server.Close()
patErr := &apperrors.PATError{RawJSON: makePATErrorJSONWithURI("flow-direct", "test-client-id", "https://example.com/pat")}
var out bytes.Buffer
err := runDirectPATAuthCheckWaitOnly(context.Background(), &GlobalFlags{}, patErr, &out)
if err != nil {
t.Fatalf("runDirectPATAuthCheckWaitOnly error = %v", err)
}
if strings.Contains(out.String(), "授权完成,正在重试") {
t.Fatalf("wait-only auth must not print retry prompt, output:\n%s", out.String())
}
if !strings.Contains(out.String(), "授权成功") {
t.Fatalf("wait-only auth should still report success, output:\n%s", out.String())
}
}
func TestRunDirectPATAuthCheckWaitOnly_SuppressesBrowserOpen(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
server, configDir := setupHandlePATServer(t, "APPROVED", "")
defer server.Close()
if _, err := pat.SetBrowserPolicy(configDir, "", true); err != nil {
t.Fatalf("SetBrowserPolicy(default) error = %v", err)
}
var opened bool
origOpenBrowser := openBrowserFunc
openBrowserFunc = func(rawURL string) error {
opened = true
return nil
}
t.Cleanup(func() { openBrowserFunc = origOpenBrowser })
patErr := &apperrors.PATError{RawJSON: makePATErrorJSONWithURI("flow-direct", "test-client-id", "https://example.com/pat")}
var out bytes.Buffer
err := runDirectPATAuthCheckWaitOnly(context.Background(), &GlobalFlags{}, patErr, &out)
if err != nil {
t.Fatalf("runDirectPATAuthCheckWaitOnly error = %v", err)
}
if opened {
t.Fatal("wait-only auth must not open a second browser tab")
}
if !strings.Contains(out.String(), "授权链接:") {
t.Fatalf("wait-only auth should still print the authorization URL, output:\n%s", out.String())
}
}
func TestResolvePATPollInterval(t *testing.T) {
tests := []struct {
name string
seconds int
want time.Duration
}{
{name: "default", seconds: 0, want: patPollInterval},
{name: "server value", seconds: 3, want: 3 * time.Second},
{name: "cap excessive value", seconds: 90, want: patMaxPollInterval},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := resolvePATPollInterval(tt.seconds); got != tt.want {
t.Fatalf("resolvePATPollInterval(%d) = %s, want %s", tt.seconds, got, tt.want)
}
})
}
}
func TestRunDirectPATAuthCheck_JSONModeReturnsStructuredPending(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
if _, err := pat.SetBrowserPolicy(configDir, "", false); err != nil {
t.Fatalf("SetBrowserPolicy(default) error = %v", err)
}
rawURI := "https://example.com/personalAuthorization?flowId=flow-json&userCode=ABCD-EFGH"
raw := `{"success":false,"code":"PAT_BATCH_AUTH_PENDING","data":{"flowId":"flow-json","uri":"` + rawURI + `","authUrl":"` + rawURI + `","clientId":"test-client-id"}}`
err := runDirectPATAuthCheck(context.Background(), &GlobalFlags{Format: "json"},
&apperrors.PATError{RawJSON: raw},
func(ctx context.Context) error {
t.Fatal("retry callback should not run in structured PAT output mode")
return nil
},
&bytes.Buffer{},
)
if err == nil {
t.Fatal("expected structured PATError")
}
patOut, ok := err.(*apperrors.PATError)
if !ok {
t.Fatalf("expected *PATError, got %T: %v", err, err)
}
var payload map[string]any
if err := json.Unmarshal([]byte(patOut.RawJSON), &payload); err != nil {
t.Fatalf("json.Unmarshal(PAT payload) error = %v\nraw=%s", err, patOut.RawJSON)
}
if got, _ := payload["code"].(string); got != "PAT_BATCH_AUTH_PENDING" {
t.Fatalf("code = %q, want PAT_BATCH_AUTH_PENDING", got)
}
data, _ := payload["data"].(map[string]any)
if got, _ := data["uri"].(string); got != rawURI {
t.Fatalf("data.uri = %q, want %q", got, rawURI)
}
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted from structured PAT output")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted from structured PAT output")
}
if got, ok := data["openBrowser"].(bool); !ok || got {
t.Fatalf("data.openBrowser = %#v, want false", data["openBrowser"])
}
}
func TestRunDirectPATAuthCheck_JSONModeBackfillsSingleURIFromAuthURL(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
if _, err := pat.SetBrowserPolicy(configDir, "", false); err != nil {
t.Fatalf("SetBrowserPolicy(default) error = %v", err)
}
rawURL := "https://open-dev.dingtalk.com/fe/old#%2FpersonalAuthorization%3FflowId%3Dflow-json%26userCode%3DABCD-EFGH"
wantURL := "https://open-dev.dingtalk.com/fe/old?hash=%23%2FpersonalAuthorization%3FflowId%3Dflow-json%26userCode%3DABCD-EFGH#/personalAuthorization?flowId=flow-json&userCode=ABCD-EFGH"
raw := `{"success":false,"code":"PAT_BATCH_AUTH_PENDING","data":{"flowId":"flow-json","authUrl":"` + rawURL + `","clientId":"test-client-id"}}`
err := runDirectPATAuthCheck(context.Background(), &GlobalFlags{Format: "json"},
&apperrors.PATError{RawJSON: raw},
func(ctx context.Context) error {
t.Fatal("retry callback should not run in structured PAT output mode")
return nil
},
&bytes.Buffer{},
)
if err == nil {
t.Fatal("expected structured PATError")
}
patOut, ok := err.(*apperrors.PATError)
if !ok {
t.Fatalf("expected *PATError, got %T: %v", err, err)
}
var payload map[string]any
if err := json.Unmarshal([]byte(patOut.RawJSON), &payload); err != nil {
t.Fatalf("json.Unmarshal(PAT payload) error = %v\nraw=%s", err, patOut.RawJSON)
}
if strings.Contains(patOut.RawJSON, `\u0026`) {
t.Fatalf("PAT output escaped URL separators: %s", patOut.RawJSON)
}
data, _ := payload["data"].(map[string]any)
if got, _ := data["uri"].(string); got != wantURL {
t.Fatalf("data.uri = %q, want %q", got, wantURL)
}
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted after backfilling data.uri")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted after backfilling data.uri")
}
}
func TestHandlePatAuthCheck_Rejected(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
server, configDir := setupHandlePATServer(t, "REJECTED", "")
@@ -951,6 +1143,12 @@ func TestHandlePatAuthCheck_JSONModeCanOpenBrowserWithoutTextOutput(t *testing.T
if !ok {
t.Fatalf("expected *PATError, got %T: %v", err, err)
}
if strings.Contains(patOut.RawJSON, `\u0026`) {
t.Fatalf("PATError RawJSON escaped ampersands in authorization URL: %s", patOut.RawJSON)
}
if !strings.Contains(patOut.RawJSON, "&userCode=98JV-JSBL") {
t.Fatalf("PATError RawJSON missing literal ampersand route separator: %s", patOut.RawJSON)
}
var payload map[string]any
if err := json.Unmarshal([]byte(patOut.RawJSON), &payload); err != nil {
t.Fatalf("json.Unmarshal(json PAT payload) error = %v\nraw=%s", err, patOut.RawJSON)
@@ -959,8 +1157,11 @@ func TestHandlePatAuthCheck_JSONModeCanOpenBrowserWithoutTextOutput(t *testing.T
if got, _ := data["uri"].(string); got != rawURI {
t.Fatalf("data.uri = %q, want verbatim %q", got, rawURI)
}
if got, _ := data["authorizationUrl"].(string); got != rawURI {
t.Fatalf("data.authorizationUrl = %q, want %q", got, rawURI)
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted from json PAT output")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted from json PAT output")
}
if got, ok := data["openBrowser"].(bool); !ok || !got {
t.Fatalf("data.openBrowser = %#v, want true", data["openBrowser"])
@@ -995,7 +1196,7 @@ func TestHandlePatAuthCheck_NonJSONModeRespectsBrowserPolicy(t *testing.T) {
fallback: mock,
globalFlags: &GlobalFlags{Format: "table"},
}
raw := `{"code":"AGENT_CODE_NOT_EXISTS","data":{"desc":"test auth","flowId":"flow-approved","uri":"https://example.com/pat","clientId":"test-client-id"}}`
raw := `{"code":"AGENT_CODE_NOT_EXISTS","data":{"desc":"test auth","flowId":"flow-approved","authorizationUrl":"https://example.com/pat","clientId":"test-client-id"}}`
var buf bytes.Buffer
_, err := handlePatAuthCheck(context.Background(), runner, executor.Invocation{
@@ -1015,6 +1216,12 @@ func TestHandlePatAuthCheck_NonJSONModeRespectsBrowserPolicy(t *testing.T) {
if !strings.Contains(buf.String(), "需要 PAT 授权") {
t.Fatalf("expected human-readable PAT output, got %q", buf.String())
}
if !strings.Contains(buf.String(), "授权链接: https://example.com/pat") {
t.Fatalf("expected authorization URL in human-readable PAT output, got %q", buf.String())
}
if strings.Contains(buf.String(), "PAT_AUTHORIZATION_URL=") {
t.Fatalf("human-readable PAT output should not emit a second machine-readable URL line, got %q", buf.String())
}
}
func TestRetryWithPatAuthRetry_JSONModeReturnsStructuredPATError(t *testing.T) {
@@ -1246,8 +1453,8 @@ func TestHandlePatAuthCheck_OpensOpaqueURIWithoutRebuild(t *testing.T) {
if opened != rawURI {
t.Fatalf("opened url = %q, want verbatim %q", opened, rawURI)
}
if got := buf.String(); !strings.Contains(got, "PAT_AUTHORIZATION_URL="+rawURI) {
t.Fatalf("output missing copy-safe PAT_AUTHORIZATION_URL line:\n%s", got)
if got := buf.String(); strings.Contains(got, "PAT_AUTHORIZATION_URL=") {
t.Fatalf("human-readable PAT output should not emit PAT_AUTHORIZATION_URL line:\n%s", got)
}
}
@@ -1292,8 +1499,8 @@ func TestHandlePatAuthCheck_NormalizesLegacyHashRouteForBrowserAndOutput(t *test
if opened != wantURL {
t.Fatalf("opened url = %q, want normalized %q", opened, wantURL)
}
if got := buf.String(); !strings.Contains(got, "PAT_AUTHORIZATION_URL="+wantURL) {
t.Fatalf("output missing normalized PAT_AUTHORIZATION_URL line:\n%s", got)
if got := buf.String(); strings.Contains(got, "PAT_AUTHORIZATION_URL=") {
t.Fatalf("human-readable PAT output should not emit PAT_AUTHORIZATION_URL line:\n%s", got)
}
}
+38 -6
View File
@@ -96,6 +96,7 @@ func Execute() (exitCode int) {
if executed == nil {
executed = root
}
err = rewordRequiredFlagError(err)
if isUnknownCommandError(err) {
executed.SetOut(os.Stderr)
_ = executed.Help()
@@ -114,6 +115,36 @@ func isUnknownCommandError(err error) bool {
return err != nil && strings.Contains(err.Error(), "unknown command")
}
// rewordRequiredFlagError rewrites cobra's default missing-required-flag message
// (`required flag(s) "email" not set`) into the wukong-aligned form
// (`missing required flag(s): --email`). cobra's ValidateRequiredFlags returns
// this error directly (it does not pass through FlagErrorFunc), so it is
// normalised here. The substring "required flag" is preserved for compatibility
// with existing assertions; flag names gain the "--" prefix and quotes are
// dropped so error output matches hardcoded cmdutil.ValidateRequiredFlags.
func rewordRequiredFlagError(err error) error {
if err == nil {
return err
}
const pfx = "required flag(s) "
const sfx = " not set"
msg := err.Error()
if !strings.HasPrefix(msg, pfx) || !strings.HasSuffix(msg, sfx) {
return err
}
mid := strings.TrimSuffix(strings.TrimPrefix(msg, pfx), sfx)
var flags []string
for _, part := range strings.Split(mid, ", ") {
if name := strings.Trim(strings.TrimSpace(part), "\""); name != "" {
flags = append(flags, "--"+name)
}
}
if len(flags) == 0 {
return err
}
return apperrors.NewValidation(fmt.Sprintf("missing required flag(s): %s", strings.Join(flags, ", ")))
}
// flagErrorWithSuggestions provides helpful suggestions for common flag mistakes.
//
// 所有 flag 解析错误都会在 message 末尾追加 "See '<CommandPath> --help' for usage.",
@@ -323,12 +354,14 @@ func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine)
genSkillsCmd.Hidden = true
mcpCmd := newMCPCommand(rootCtx, loader, runner, engine)
mcpCmd.Hidden = true
patCaller := newToolCallerAdapter(runner, flags)
utilityCommands := []*cobra.Command{
newAuthCommand(),
newAuthCommand(patCaller),
newAPICommand(flags),
newSkillCommand(),
newCacheCommand(),
newCatalogCommand(loader),
newConfigCommand(),
newDoctorCommand(),
newCompletionCommand(root),
@@ -354,7 +387,6 @@ func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine)
}
// PAT authorization commands (open-source core)
patCaller := newToolCallerAdapter(runner, flags)
pat.RegisterCommands(root, patCaller)
if fn := edition.Get().RegisterExtraCommands; fn != nil {
@@ -372,8 +404,8 @@ func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine)
return root
}
func newAuthCommand() *cobra.Command {
return buildAuthCommand()
func newAuthCommand(patCaller edition.ToolCaller) *cobra.Command {
return buildAuthCommand(patCaller)
}
func newSkillCommand() *cobra.Command {
@@ -474,7 +506,7 @@ func newCacheCommand() *cobra.Command {
if err != nil {
return apperrors.NewDiscovery(fmt.Sprintf("cache refresh: fetch server list failed: %v", err))
}
servers := market.NormalizeServers(resp, "live_market")
servers := market.NormalizeServersForBaseURL(resp, "live_market", registryDiscoveryBaseURL())
_ = store.SaveRegistry(service.CachePartition(), cache.RegistrySnapshot{Servers: servers})
selected := selectServersForProduct(servers, product)
@@ -596,7 +628,7 @@ func newVersionCommand() *cobra.Command {
}
func newSchemaCommand(loader cli.CatalogLoader) *cobra.Command {
return cli.NewSchemaCommand(loader)
return cli.NewSchemaCommand(loader, newHelperToolFetcher())
}
func newGenerateSkillsCommand() *cobra.Command {
+2 -2
View File
@@ -24,7 +24,7 @@ func TestCacheRefreshClearsExistingCachesAndSkipsCLISkippedServers(t *testing.T)
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/cli/discovery/apis/bamboo":
case "/cli/discovery/apis/cedar":
_ = json.NewEncoder(w).Encode(market.ListResponse{
Metadata: market.ListMetadata{Count: 2},
Servers: []market.ServerEnvelope{
@@ -146,7 +146,7 @@ func TestCacheRefreshHonorsEditionDiscoveryURL(t *testing.T) {
},
},
})
case "/cli/discovery/apis/bamboo":
case "/cli/discovery/apis/cedar":
marketHits.Add(1)
http.Error(w, "market endpoint must not be called when edition DiscoveryURL is set", http.StatusNotFound)
default:
+26 -10
View File
@@ -6,6 +6,7 @@ import (
"text/tabwriter"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/i18n"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/tui"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
@@ -50,38 +51,42 @@ func renderRootHelp(root *cobra.Command) {
utilities := visibleUtilityRootCommands(root)
w := root.OutOrStdout()
_, _ = fmt.Fprintln(w, tui.Header("Workspace CLI", "DingTalk blue-white technical console"))
_, _ = fmt.Fprintln(w, tui.Rule(76))
_, _ = fmt.Fprintln(w)
if len(services) == 0 {
_, _ = fmt.Fprintln(w, "No MCP services discovered.")
_, _ = fmt.Fprintf(w, "%s %s\n", tui.StateMark("warning"), tui.Warning("No MCP services discovered."))
_, _ = fmt.Fprintln(w)
} else {
_, _ = fmt.Fprintln(w, "Discovered MCP Services:")
_, _ = fmt.Fprintln(w, tui.Section("Discovered MCP Services:"))
_, _ = fmt.Fprintln(w)
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
for _, service := range services {
_, _ = fmt.Fprintf(tw, " %s\t%s\n", service.Name(), strings.TrimSpace(service.Short))
_, _ = fmt.Fprintf(tw, " %s %s\t%s\n", tui.StateMark("ok"), tui.Bold(service.Name()), tui.Dim(strings.TrimSpace(service.Short)))
}
_ = tw.Flush()
_, _ = fmt.Fprintln(w)
}
_, _ = fmt.Fprintln(w, "Usage:")
_, _ = fmt.Fprintln(w, " dws <service> [command] [flags]")
_, _ = fmt.Fprintln(w, tui.Section("Usage:"))
_, _ = fmt.Fprintf(w, " %s %s\n", tui.Bullet(), tui.White("dws <service> [command] [flags]"))
if len(utilities) > 0 {
_, _ = fmt.Fprintln(w, " dws <command> [flags]")
_, _ = fmt.Fprintf(w, " %s %s\n", tui.Bullet(), tui.White("dws <command> [flags]"))
}
_, _ = fmt.Fprintln(w)
if len(utilities) > 0 {
_, _ = fmt.Fprintln(w, "Utility Commands:")
_, _ = fmt.Fprintln(w, tui.Section("Utility Commands:"))
_, _ = fmt.Fprintln(w)
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
for _, utility := range utilities {
_, _ = fmt.Fprintf(tw, " %s\t%s\n", utility.Name(), strings.TrimSpace(utility.Short))
_, _ = fmt.Fprintf(tw, " %s %s\t%s\n", tui.Bullet(), tui.Bold(utility.Name()), tui.Dim(commandShort(utility)))
}
_ = tw.Flush()
_, _ = 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.`)
_, _ = fmt.Fprintf(w, "%s %s\n", tui.Key("Next"), `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
@@ -90,10 +95,21 @@ func renderRootHelp(root *cobra.Command) {
// it and dropped this, so we restore it explicitly here.
if long := strings.TrimSpace(root.Long); long != "" {
_, _ = fmt.Fprintln(w)
_, _ = fmt.Fprintln(w, long)
_, _ = fmt.Fprintln(w, tui.Dim(long))
}
}
func commandShort(cmd *cobra.Command) string {
if cmd == nil {
return ""
}
short := strings.TrimSpace(cmd.Short)
if cmd.Name() == "help" && short == "Help about any command" {
return i18n.T("查看任意命令的帮助信息")
}
return short
}
// resolveVisibleProducts returns the set of top-level product IDs that should
// be treated as visible. It unions the edition's VisibleProducts hook (when
// set) with DirectRuntimeProductIDs(), so dynamically-registered products —
+84 -5
View File
@@ -17,6 +17,7 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
@@ -259,13 +260,22 @@ func (r *runtimeRunner) handleCatalogMiss(ctx context.Context, invocation execut
invocation.DryRun = true
return r.fallback.Run(ctx, invocation)
}
hint := "产品 envelope 可能未下发到 discovery,或已经被 serverDeps fail-fast 丢弃;可执行 'dws cache refresh' 强制重新 discovery,仍失败请向 Portal 确认 envelope 状态。"
actions := []string{"dws cache refresh"}
if strings.TrimSpace(invocation.CanonicalProduct) == devappProductID {
hint = "dev app(product id: devapp)是 helper-only 产品,命令树不依赖 discovery;真实调用需要内部版通过 SupplementServers/StaticServers 注入 MCP endpoint,或本地调试临时设置 DINGTALK_DEVAPP_MCP_URL。"
actions = []string{
"检查内部版 SupplementServers/StaticServers 是否包含 devapp endpoint",
"本地调试可临时设置 DINGTALK_DEVAPP_MCP_URL 后重试",
}
}
return executor.Result{}, apperrors.NewAPI(
fmt.Sprintf("endpoint not resolved for product %q (tool %q): %s", invocation.CanonicalProduct, invocation.Tool, detail),
apperrors.WithOperation("discovery.resolve"),
apperrors.WithReason("endpoint_not_resolved"),
apperrors.WithServerKey(invocation.CanonicalProduct),
apperrors.WithHint("产品 envelope 可能未下发到 discovery,或已经被 serverDeps fail-fast 丢弃;可执行 'dws cache refresh' 强制重新 discovery,仍失败请向 Portal 确认 envelope 状态。"),
apperrors.WithActions("dws cache refresh"),
apperrors.WithHint(hint),
apperrors.WithActions(actions...),
)
}
@@ -324,6 +334,14 @@ func (r *runtimeRunner) executeInvocation(ctx context.Context, endpoint string,
invocation.CanonicalProduct, invocation.Tool, endpoint, version, authToken != "", timeoutSec)
if invocation.DryRun {
// Emit a wukong-aligned human-readable preview on stderr so the dry-run
// surface advertises the resolved MCP arguments without polluting the
// stdout payload (which stays valid JSON in --format json mode). Mirrors
// wukong's "Arguments: {...}" dry-run line; stderr keeps it out of the
// machine-readable channel.
if argsJSON, err := json.Marshal(invocation.Params); err == nil {
fmt.Fprintf(os.Stderr, "DRY-RUN Arguments: %s\n", argsJSON)
}
return executor.Result{
Invocation: invocation,
Response: map[string]any{
@@ -483,6 +501,15 @@ func (r *runtimeRunner) executeInvocation(ctx context.Context, endpoint string,
}
invocation.Implemented = true
// Align with wukong's response envelope: stamp a top-level success=true on
// map payloads that don't already carry a success flag. Business errors
// (success=false) are intercepted above, so reaching here means the call
// succeeded. Additive only — existing keys are never overwritten.
if callResult.Content != nil {
if _, has := callResult.Content["success"]; !has {
callResult.Content["success"] = true
}
}
response := map[string]any{
"endpoint": transport.RedactURL(endpoint),
"content": callResult.Content,
@@ -687,7 +714,27 @@ func resolveIdentityHeaders() map[string]string {
if sessionID == "" {
sessionID = os.Getenv(envRewindSessionID)
}
agentCode, _ := authpkg.AgentCodeFromEnv()
// Resolve the agent_code (accuracy-first; unknown hosts -> custom) and the
// per-(machine × agent_code) instance id. This is what makes agent_code
// actually report a value: previously it was sent only when the host
// injected DINGTALK_DWS_AGENTCODE (empty ~99.98% of the time), so the
// gateway logged no agent_code at all. DetectAgentCode always yields a code.
//
// Backward-compat by design (additive, not breaking):
// - x-dws-agent-id keeps its v1 meaning = machine-level install UUID
// (set by id.Headers() above), so old/new clients stay comparable.
// - x-dws-agent-instance-id is NEW: the per-(machine × agent_code) id.
// Old clients don't send it, which is itself a clean old/new signal.
// Note: x-dws-channel (DWS_CHANNEL) is a separate axis, untouched.
agentCode, agentCodeSig := authpkg.DetectAgentCode()
headers["x-dws-agent-instance-id"] = id.ResolveAgentID(defaultConfigDir(), agentCode, agentCodeSig)
// Emit the CLI version on the wire so the gateway can segment old vs new
// clients (and scope agent_code coverage / adoption). The header constant
// existed but was never set; wire it here.
if version != "" {
headers[transport.HeaderVersion] = version
}
envHeaders := map[string]string{
"x-dingtalk-agent": os.Getenv(envDingtalkAgent),
"x-dingtalk-dws-agent-code": agentCode,
@@ -717,13 +764,23 @@ func resolveIdentityHeaders() map[string]string {
// errors (success=false + errorCode/errorMsg) that are not flagged at the MCP
// protocol level. Returns the error message, or "" if the response is OK.
func detectBusinessError(content map[string]any) string {
return detectBusinessErrorAtDepth(content, 0)
}
func detectBusinessErrorAtDepth(content map[string]any, depth int) string {
if content == nil || depth > 8 {
return ""
}
success, ok := content["success"]
if !ok {
return ""
return detectNestedBusinessError(content, depth)
}
b, ok := success.(bool)
if !ok || b {
return ""
return detectNestedBusinessError(content, depth)
}
if nested := detectNestedBusinessError(content, depth); nested != "" {
return nested
}
if msg, ok := content["errorMsg"].(string); ok && strings.TrimSpace(msg) != "" {
return strings.TrimSpace(msg)
@@ -734,6 +791,28 @@ func detectBusinessError(content map[string]any) string {
return "business error: success=false"
}
func detectNestedBusinessError(content map[string]any, depth int) string {
for _, key := range []string{"content", "result", "data"} {
switch child := content[key].(type) {
case map[string]any:
if msg := detectBusinessErrorAtDepth(child, depth+1); msg != "" {
return msg
}
case []any:
for _, item := range child {
childMap, ok := item.(map[string]any)
if !ok {
continue
}
if msg := detectBusinessErrorAtDepth(childMap, depth+1); msg != "" {
return msg
}
}
}
}
return ""
}
// extractMCPErrorMessage builds an error message from a ToolCallResult with
// isError=true. It extracts text from content blocks when available.
func extractMCPErrorMessage(result transport.ToolCallResult) string {
+65 -2
View File
@@ -321,6 +321,7 @@ func TestRuntimeRunnerInjectsAuthTokenFromFlag(t *testing.T) {
func TestResolveIdentityHeadersForwardsAgentCode(t *testing.T) {
setupRuntimeCommandTest(t)
t.Setenv(authpkg.AgentCodeEnv, " cursor ")
t.Setenv(authpkg.AgentCodeEnvCompat, "")
headers := resolveIdentityHeaders()
if got := headers["x-dingtalk-dws-agent-code"]; got != "cursor" {
@@ -328,14 +329,62 @@ func TestResolveIdentityHeadersForwardsAgentCode(t *testing.T) {
}
}
func TestResolveIdentityHeadersAgentIdentityFields(t *testing.T) {
setupRuntimeCommandTest(t)
t.Setenv(authpkg.AgentCodeEnv, "qoder")
headers := resolveIdentityHeaders()
// x-dws-agent-id stays machine-level (v1 install UUID): non-empty and NOT
// the dwsa_ instance form — this is the cross-version continuity anchor.
machineID := headers["x-dws-agent-id"]
if machineID == "" {
t.Fatal("x-dws-agent-id must stay populated (machine-level)")
}
if strings.HasPrefix(machineID, "dwsa_") {
t.Fatalf("x-dws-agent-id must remain machine-level, got instance form %q", machineID)
}
// x-dws-agent-instance-id is the NEW per-(machine × agent_code) id.
instID := headers["x-dws-agent-instance-id"]
if !strings.HasPrefix(instID, "dwsa_") {
t.Fatalf("x-dws-agent-instance-id must be a derived instance id, got %q", instID)
}
if instID == machineID {
t.Fatal("instance id must differ from machine id")
}
// CLI version must now be on the wire so the gateway can segment old/new.
if headers[transport.HeaderVersion] == "" {
t.Fatalf("%s must be emitted", transport.HeaderVersion)
}
}
func TestResolveIdentityHeadersIgnoresReversedAgentCodeEnv(t *testing.T) {
setupRuntimeCommandTest(t)
t.Setenv(authpkg.AgentCodeEnv, "")
t.Setenv("DWS_DINGTALK_AGENTCODE", " compat ")
// Isolate from ambient agent-host detection signals so this test asserts
// only the reversed-env-name behavior (the suite itself may run under
// Claude Code / Qoder / VS Code, whose signals would otherwise be detected).
for _, k := range []string{
"CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT",
"OPENCLAW_BUNDLE_ROOT", "OPENCLAW_RUNTIME_ROLE", "HERMES_HOME",
"CODEX_SANDBOX", "VSCODE_BRAND", "__CFBundleIdentifier",
} {
t.Setenv(k, "")
}
headers := resolveIdentityHeaders()
if got := headers["x-dingtalk-dws-agent-code"]; got != "" {
t.Fatalf("x-dingtalk-dws-agent-code = %q, want empty because reversed env is ignored", got)
// The reversed env name must never be consumed. With no canonical
// declaration and no host signature, agent_code resolves to the honest
// "custom" fallback — and crucially is NOT the reversed value.
got := headers["x-dingtalk-dws-agent-code"]
if got == "compat" {
t.Fatalf("x-dingtalk-dws-agent-code = %q, reversed env must be ignored", got)
}
if got != authpkg.AgentCodeCustom {
t.Fatalf("x-dingtalk-dws-agent-code = %q, want %q (fallback)", got, authpkg.AgentCodeCustom)
}
}
@@ -895,6 +944,20 @@ func jsonRPCToolName(req map[string]any) string {
return name
}
func TestDetectBusinessErrorNestedServiceResult(t *testing.T) {
content := map[string]any{
"success": false,
"result": map[string]any{
"success": false,
"errorCode": "ROBOT_NOT_FOUND",
"errorMsg": "robot info is not exist",
},
}
if got := detectBusinessError(content); got != "robot info is not exist" {
t.Fatalf("detectBusinessError() = %q, want nested errorMsg", got)
}
}
func writeJSONRPCToolResult(t *testing.T, w http.ResponseWriter, req map[string]any, content map[string]any, isError bool) {
t.Helper()
_ = json.NewEncoder(w).Encode(map[string]any{
+7 -6
View File
@@ -95,12 +95,13 @@ var agentSkillPaths = map[string]string{
// `agents` is the generic-agent sentinel: install scripts and `setup`
// special-case ~/.agents/skills as a no-checks-required fallback so a
// fresh machine without any IDE/agent registry still gets skills.
"agents": ".agents/skills",
"qoder": ".qoder/skills",
"claude": ".claude/skills",
"cursor": ".cursor/skills",
"codex": ".codex/skills",
"opencode": filepath.Join(".config", "opencode", "skills"),
"agents": ".agents/skills",
"qoder": ".qoder/skills",
"qoderwork": ".qoderwork/skills",
"claude": ".claude/skills",
"cursor": ".cursor/skills",
"codex": ".codex/skills",
"opencode": filepath.Join(".config", "opencode", "skills"),
// IDE / agent registries also probed by `dws skill setup --target all`.
"gemini": ".gemini/skills",
"github": ".github/skills",
+40 -5
View File
@@ -21,6 +21,8 @@ var skillSetupAgentHomes = []string{
".agents/skills",
".claude/skills",
".cursor/skills",
".qoder/skills",
".qoderwork/skills",
".gemini/skills",
".codex/skills",
".github/skills",
@@ -56,7 +58,8 @@ multi 模式支持按产品挑选:
-x/--exclude 从全装里剔除指定子 skill(可重复,与 --skill 互斥)
未列出的已有 dingtalk-* skill 会保留(additive 叠加语义)
不带 --mode 时进入交互式询问;不带 --target 时铺到所有检测到的 Agent 目录。`,
不带 --mode 时进入交互式询问;不带 --target 时铺到所有检测到的 Agent 目录。
skill 源默认取二进制内嵌的版本(升级二进制即升级 skill);--source / DWS_SKILL_SOURCE 可显式覆盖。`,
Example: ` dws skill setup # 交互式
dws skill setup --mode mono --yes # 非交互装 mono
dws skill setup --mode multi --target claude # multi 全装到 ~/.claude/skills/
@@ -68,7 +71,7 @@ multi 模式支持按产品挑选:
}
cmd.Flags().String("mode", "", "skill 模式:mono | multi(不指定则交互询问)")
cmd.Flags().String("target", "all", "目标 Agent:all | "+supportedTargets())
cmd.Flags().String("source", "", "skill 源目录(默认自动查找二进制旁边或当前目录)")
cmd.Flags().String("source", "", "skill 源目录(默认使用二进制内嵌的 skill 源,与当前版本一致)")
cmd.Flags().Bool("yes", false, "跳过所有确认提示")
cmd.Flags().StringSliceP("skill", "s", nil, "multi 模式:仅安装指定子 skill(可重复,接受短名 aitable 或全名 dingtalk-aitable)")
cmd.Flags().StringSliceP("exclude", "x", nil, "multi 模式:从全装中剔除指定子 skill(可重复,与 --skill 互斥)")
@@ -95,10 +98,11 @@ func runSkillSetup(cmd *cobra.Command, _ []string) error {
return fmt.Errorf("--skill / --exclude 仅在 --mode multi 下有效(mono 只有一个 skill,无需挑选)")
}
skillSrc, err := resolveSkillSetupSource(source, mode)
skillSrc, srcCleanup, err := resolveSkillSetupSourceOrEmbedded(source, mode)
if err != nil {
return err
}
defer srcCleanup()
dests, err := resolveSkillSetupTargets(target, mode)
if err != nil {
@@ -313,7 +317,31 @@ func resolveSkillSetupMode(mode string, autoYes bool, out io.Writer) (string, er
func resolveSkillSetupSource(explicit, mode string) (string, error) {
subdir := mode // "mono" or "multi"
candidates := skillSourceCandidates(explicit, subdir)
// An explicit override (--source flag or DWS_SKILL_SOURCE) wins, and an
// override that does not contain a skill root is an error — never a
// silent fallback to another source the user did not ask for.
var overrides []string
if explicit != "" {
overrides = append(overrides, explicit, filepath.Join(explicit, "skills", subdir))
}
if env := strings.TrimSpace(os.Getenv("DWS_SKILL_SOURCE")); env != "" {
overrides = append(overrides, env, filepath.Join(env, "skills", subdir))
}
if len(overrides) > 0 {
for _, c := range overrides {
if isSkillSourceRoot(c, mode) {
return c, nil
}
}
hint := strings.Join(overrides, "\n - ")
return "", fmt.Errorf("未找到 %s 模式的 skill 源目录(--source / DWS_SKILL_SOURCE 显式指定时不回退到内嵌源),已尝试:\n - %s", mode, hint)
}
// No explicit override: legacy fallback only — embedded materialization
// is handled by resolveSkillSetupSourceOrEmbedded (skill_setup_embed.go),
// the wrapper that callers use. This branch is reachable only when the
// wrapper passes through with an empty explicit/env (legacy direct call).
candidates := skillSourceCandidates("", subdir)
for _, c := range candidates {
if isSkillSourceRoot(c, mode) {
return c, nil
@@ -639,7 +667,14 @@ func copyFileContent(src, dst string, mode os.FileMode) error {
}
func isInteractiveTerminal() bool {
fi, err := os.Stdin.Stat()
return isCharDevice(os.Stdin) && isCharDevice(os.Stdout) && isCharDevice(os.Stderr)
}
func isCharDevice(file *os.File) bool {
if file == nil {
return false
}
fi, err := file.Stat()
if err != nil {
return false
}
+86
View File
@@ -0,0 +1,86 @@
// 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 (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
dwsroot "github.com/DingTalk-Real-AI/dingtalk-workspace-cli"
)
// resolveSkillSetupSourceOrEmbedded resolves the skill source for `skill
// setup`. An explicit --source or DWS_SKILL_SOURCE is honored as a developer
// override (validated as an on-disk dir). Otherwise it falls back to the skill
// bundle embedded in THIS binary, so a plain `dws skill setup` always installs
// the version shipped with the running binary — upgrading the binary therefore
// refreshes the installed skill, instead of silently reusing a stale copy from
// the current working directory.
//
// The returned cleanup func removes any temp dir created for the embedded
// bundle; it is a no-op when an on-disk source is used. Always call it.
func resolveSkillSetupSourceOrEmbedded(explicit, mode string) (string, func(), error) {
noop := func() {}
explicit = strings.TrimSpace(explicit)
env := strings.TrimSpace(os.Getenv("DWS_SKILL_SOURCE"))
if explicit != "" || env != "" {
dir, err := resolveSkillSetupSource(explicit, mode)
return dir, noop, err
}
return materializeEmbeddedSkillSource(mode)
}
// materializeEmbeddedSkillSource extracts the embedded skills/<mode> subtree
// into a fresh temp dir and returns its path plus a cleanup func. Reusing a
// real directory lets the existing dir-based install/copy logic stay unchanged.
func materializeEmbeddedSkillSource(mode string) (string, func(), error) {
noop := func() {}
sub := "skills/" + mode // embed.FS always uses forward slashes
if _, err := fs.Stat(dwsroot.EmbeddedSkills, sub); err != nil {
return "", noop, fmt.Errorf("内嵌 skill 不含 %q(二进制可能未随 skills/ 重新构建): %w", sub, err)
}
tmp, err := os.MkdirTemp("", "dws-skill-"+mode+"-")
if err != nil {
return "", noop, fmt.Errorf("创建临时 skill 目录失败: %w", err)
}
cleanup := func() { _ = os.RemoveAll(tmp) }
walkErr := fs.WalkDir(dwsroot.EmbeddedSkills, sub, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel := strings.TrimPrefix(strings.TrimPrefix(p, sub), "/")
dst := filepath.Join(tmp, filepath.FromSlash(rel))
if d.IsDir() {
return os.MkdirAll(dst, 0o755)
}
data, readErr := dwsroot.EmbeddedSkills.ReadFile(p)
if readErr != nil {
return readErr
}
if mkErr := os.MkdirAll(filepath.Dir(dst), 0o755); mkErr != nil {
return mkErr
}
return os.WriteFile(dst, data, 0o644)
})
if walkErr != nil {
cleanup()
return "", noop, fmt.Errorf("展开内嵌 skill 到临时目录失败: %w", walkErr)
}
return tmp, cleanup, nil
}
+68
View File
@@ -0,0 +1,68 @@
// 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 (
"os"
"path/filepath"
"testing"
)
// TestMaterializeEmbeddedSkillSourceMono verifies that the mono skill bundle
// baked into the binary can be extracted to a temp dir and is a valid skill
// source root (so `dws skill setup` works with zero local checkout). The
// nested-reference and _common checks guard against the embed dropping nested
// docs or the `all:` prefix being lost (which would silently skip
// dot/underscore dirs).
func TestMaterializeEmbeddedSkillSourceMono(t *testing.T) {
dir, cleanup, err := materializeEmbeddedSkillSource(skillSetupModeMono)
if err != nil {
t.Fatalf("materializeEmbeddedSkillSource: %v", err)
}
defer cleanup()
if !isSkillSourceRoot(dir, skillSetupModeMono) {
t.Fatalf("extracted dir %s is not a valid mono skill source root", dir)
}
for _, rel := range []string{
"SKILL.md",
filepath.Join("references", "global-reference.md"),
filepath.Join("references", "best_practices", "_common"),
} {
if _, err := os.Stat(filepath.Join(dir, rel)); err != nil {
t.Errorf("expected embedded skill to contain %s: %v", rel, err)
}
}
// cleanup must actually remove the temp dir.
cleanup()
if _, err := os.Stat(dir); !os.IsNotExist(err) {
t.Errorf("cleanup did not remove temp dir %s (err=%v)", dir, err)
}
}
// TestResolveSkillSetupSourceOrEmbeddedFallsBackToEmbedded verifies that with
// no --source and no DWS_SKILL_SOURCE, resolution uses the embedded bundle
// rather than probing the current working directory (the stale-skill footgun).
func TestResolveSkillSetupSourceOrEmbeddedFallsBackToEmbedded(t *testing.T) {
t.Setenv("DWS_SKILL_SOURCE", "")
dir, cleanup, err := resolveSkillSetupSourceOrEmbedded("", skillSetupModeMono)
if err != nil {
t.Fatalf("resolveSkillSetupSourceOrEmbedded: %v", err)
}
defer cleanup()
if !isSkillSourceRoot(dir, skillSetupModeMono) {
t.Fatalf("embedded fallback returned non-source-root dir %s", dir)
}
}
+16 -30
View File
@@ -47,6 +47,22 @@ func TestResolveSkillSetupModeNonInteractiveDefaultsMono(t *testing.T) {
}
}
func TestIsCharDeviceRejectsNilAndRegularFiles(t *testing.T) {
if isCharDevice(nil) {
t.Fatal("nil file must not be treated as interactive")
}
file, err := os.CreateTemp(t.TempDir(), "stdout")
if err != nil {
t.Fatal(err)
}
defer file.Close()
if isCharDevice(file) {
t.Fatal("regular files must not be treated as interactive terminals")
}
}
func TestResolveSkillSetupSourceFindsMonoRoot(t *testing.T) {
tmp := t.TempDir()
monoDir := filepath.Join(tmp, "skills", "mono")
@@ -317,36 +333,6 @@ func TestSkillSourceCandidatesIncludesUserCache(t *testing.T) {
// TestResolveSkillSetupSourceFallsBackToUserCache verifies that when no
// --source / DWS_SKILL_SOURCE / source checkout is available, the resolver
// successfully discovers ~/.dws/skills/multi/ as the source.
func TestResolveSkillSetupSourceFallsBackToUserCache(t *testing.T) {
fakeHome := t.TempDir()
t.Setenv("HOME", fakeHome)
t.Setenv("DWS_SKILL_SOURCE", "")
cacheRoot := filepath.Join(fakeHome, ".dws", "skills", "multi")
for _, n := range []string{"dingtalk-aitable", "dingtalk-doc"} {
if err := os.MkdirAll(filepath.Join(cacheRoot, n), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(cacheRoot, n, "SKILL.md"), []byte("# "+n), 0o644); err != nil {
t.Fatal(err)
}
}
// Run resolver from a tempdir that has no skills/ on disk, simulating a
// fresh user machine without a source checkout.
scratch := t.TempDir()
t.Chdir(scratch)
got, err := resolveSkillSetupSource("", skillSetupModeMulti)
if err != nil {
t.Fatalf("expected user-cache fallback to succeed, got err=%v", err)
}
if got != cacheRoot {
t.Fatalf("expected %s, got %s", cacheRoot, got)
}
}
func TestNormalizeMultiSkillName(t *testing.T) {
cases := []struct {
in, want string
+4 -4
View File
@@ -15,10 +15,10 @@ package app
import (
"context"
"encoding/json"
"log/slog"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/jsonutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
@@ -77,7 +77,7 @@ func convertResult(r executor.Result) *edition.ToolResult {
contentRaw, ok := resp["content"]
if !ok {
// Dry-run or echo mode: serialize the whole response as text.
data, _ := json.Marshal(resp)
data, _ := jsonutil.Marshal(resp)
return &edition.ToolResult{
Content: []edition.ContentBlock{{Type: "text", Text: string(data)}},
}
@@ -98,12 +98,12 @@ func convertResult(r executor.Result) *edition.ToolResult {
}
return &edition.ToolResult{Content: blocks}
case map[string]any:
data, _ := json.Marshal(v)
data, _ := jsonutil.Marshal(v)
return &edition.ToolResult{
Content: []edition.ContentBlock{{Type: "text", Text: string(data)}},
}
default:
data, _ := json.Marshal(contentRaw)
data, _ := jsonutil.Marshal(contentRaw)
return &edition.ToolResult{
Content: []edition.ContentBlock{{Type: "text", Text: string(data)}},
}
+50 -8
View File
@@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
@@ -14,20 +15,20 @@ import (
"strings"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/tui"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/upgrade"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/fatih/color"
"github.com/spf13/cobra"
)
var (
ugBold = color.New(color.Bold).SprintFunc()
ugGreen = color.New(color.FgGreen).SprintFunc()
ugYellow = color.New(color.FgYellow).SprintFunc()
ugRed = color.New(color.FgRed).SprintFunc()
ugCyan = color.New(color.FgCyan).SprintFunc()
ugDim = color.New(color.Faint).SprintFunc()
ugBoldGrn = color.New(color.Bold, color.FgGreen).SprintFunc()
ugBold = tui.Bold
ugGreen = tui.Success
ugYellow = tui.Warning
ugRed = tui.Danger
ugCyan = tui.Cyan
ugDim = tui.Dim
ugBoldGrn = tui.Success
)
const defaultListLimit = 10
@@ -56,6 +57,7 @@ func newUpgradeCommand() *cobra.Command {
dws upgrade --list --all # 列出所有版本
dws upgrade --version v1.0.5 # 升级到指定版本
dws upgrade --rollback # 回滚到上一版本
dws upgrade --dry-run # 仅预览升级步骤,不实际执行
dws upgrade -y # 跳过确认直接升级`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -68,6 +70,7 @@ func newUpgradeCommand() *cobra.Command {
}
yes, _ := cmd.Flags().GetBool("yes")
dryRun, _ := cmd.Flags().GetBool("dry-run")
format := resolveUpgradeFormat(cmd)
if flagList {
@@ -88,6 +91,7 @@ func newUpgradeCommand() *cobra.Command {
force: flagForce,
skipSkills: flagSkipSkills,
yes: yes,
dryRun: dryRun,
})
},
}
@@ -108,6 +112,7 @@ type upgradeOptions struct {
force bool
skipSkills bool
yes bool
dryRun bool
}
// --- dws upgrade --check ---
@@ -298,6 +303,29 @@ func runUpgradeRollback(yes bool) error {
// Phase 2 (Apply): replace binary + install skills — only runs if Phase 1 fully succeeds.
// If anything fails in Phase 1, no files on disk are modified.
// writeDryRunPlan renders the steps that `dws upgrade` would perform, without
// touching the filesystem. Kept side-effect-free and writer-injectable so the
// --dry-run contract can be asserted in tests.
func writeDryRunPlan(w io.Writer, currentVer, binaryAssetName string, hasSkills bool) {
fmt.Fprintln(w)
fmt.Fprintf(w, " %s 预览模式,不会下载或修改任何文件\n", ugBold("[dry-run]"))
fmt.Fprintf(w, " 将执行以下操作:\n")
fmt.Fprintf(w, " [1/5] 备份当前版本 %s\n", ugDim(ensureV(currentVer)))
fmt.Fprintf(w, " [2/5] 下载 %s\n", ugCyan(binaryAssetName))
if hasSkills {
fmt.Fprintf(w, " 下载 %s\n", ugCyan("dws-skills.zip"))
}
fmt.Fprintf(w, " [3/5] 校验 SHA256\n")
fmt.Fprintf(w, " [4/5] 解压并验证\n")
replaceStep := "替换二进制"
if hasSkills {
replaceStep += " 并安装技能包"
}
fmt.Fprintf(w, " [5/5] %s\n", replaceStep)
fmt.Fprintln(w)
fmt.Fprintf(w, " %s\n", ugDim("移除 --dry-run 以实际执行升级"))
}
func runUpgrade(ctx context.Context, opts upgradeOptions) error {
fmt.Printf(" %s\n", ugDim("检查更新..."))
@@ -339,6 +367,20 @@ func runUpgrade(ctx context.Context, opts upgradeOptions) error {
fmt.Printf(" %s %s\n", ugBold("通道: "), ugYellow("pre-release"))
}
// --dry-run: preview only. Resolve the platform asset so a missing build is
// still reported, then describe the steps that *would* run and return before
// any side effect (no backup, no download, no replace). Matches the global
// flag's contract: "预览操作内容,不实际执行".
if opts.dryRun {
binaryAsset, err := upgrade.FindBinaryAsset(release.Assets)
if err != nil {
return err
}
hasSkills := upgrade.FindSkillsAsset(release.Assets) != nil && !opts.skipSkills
writeDryRunPlan(os.Stdout, currentVer, binaryAsset.Name, hasSkills)
return nil
}
if !opts.yes {
fmt.Println()
fmt.Printf("是否升级? [y/N] ")
+1 -1
View File
@@ -11,7 +11,7 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
func TestUpgradeCommand_BlockedInEmbeddedMode(t *testing.T) {
func TestUpgradeCommand_BlockedWhenEmbedded(t *testing.T) {
prev := edition.Get()
edition.Override(&edition.Hooks{IsEmbedded: true, Name: "embedded"})
t.Cleanup(func() { edition.Override(prev) })
+54
View File
@@ -430,6 +430,60 @@ func TestNewUpgradeCommand_Help(t *testing.T) {
if !strings.Contains(help, "--rollback") {
t.Error("help should contain --rollback")
}
// Regression for #364: --dry-run must be discoverable from upgrade help so
// users know it is supported (and is now actually honored).
if !strings.Contains(help, "--dry-run") {
t.Error("help should advertise --dry-run for upgrade")
}
}
// --- writeDryRunPlan (#364) ---
//
// Regression for #364: `dws upgrade --dry-run` previously performed a real
// upgrade because the flag was silently ignored. The dry-run path must now be
// preview-only — it describes the steps without downloading or replacing
// anything. writeDryRunPlan is the side-effect-free renderer for that preview.
func TestWriteDryRunPlan_PreviewOnly(t *testing.T) {
var buf bytes.Buffer
writeDryRunPlan(&buf, "v1.0.30", "dws-darwin-arm64.tar.gz", false)
out := buf.String()
if !strings.Contains(out, "dry-run") {
t.Errorf("output should be marked as dry-run, got:\n%s", out)
}
if !strings.Contains(out, "不会下载或修改任何文件") {
t.Errorf("output should state nothing is downloaded or modified, got:\n%s", out)
}
if !strings.Contains(out, "dws-darwin-arm64.tar.gz") {
t.Errorf("output should name the resolved platform asset, got:\n%s", out)
}
// All five steps should be previewed, including the (skipped) replace step.
for _, step := range []string{"[1/5]", "[2/5]", "[3/5]", "[4/5]", "[5/5]"} {
if !strings.Contains(out, step) {
t.Errorf("output missing step %s, got:\n%s", step, out)
}
}
}
func TestWriteDryRunPlan_WithSkills(t *testing.T) {
var buf bytes.Buffer
writeDryRunPlan(&buf, "v1.0.30", "dws-linux-amd64.tar.gz", true)
out := buf.String()
if !strings.Contains(out, "dws-skills.zip") {
t.Errorf("with skills, output should mention dws-skills.zip, got:\n%s", out)
}
if !strings.Contains(out, "安装技能包") {
t.Errorf("with skills, replace step should mention installing skills, got:\n%s", out)
}
// Without skills, neither should appear.
var buf2 bytes.Buffer
writeDryRunPlan(&buf2, "v1.0.30", "dws-linux-amd64.tar.gz", false)
if strings.Contains(buf2.String(), "dws-skills.zip") {
t.Errorf("without skills, output should not mention dws-skills.zip, got:\n%s", buf2.String())
}
}
// --- isLikelyAMFIKill ---
+161
View File
@@ -0,0 +1,161 @@
// 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.
// agent_code_detect.go resolves the agent_code — which agent HOST is driving
// dws (claudecode / qoder / cursor / vscode / openclaw / hermes / ...). It
// fills the x-dingtalk-dws-agent-code header for per-channel statistics.
//
// SEPARATE axis from DWS_CHANNEL / x-dws-channel (a distribution channel code);
// the two are never conflated here.
//
// Design contract — ACCURACY OVER COVERAGE, but maximize accurate coverage:
// - Prefer generalizable, host-declared signals so one rule covers a whole
// family (VSCODE_BRAND covers every VS Code fork, present and future).
// - Every per-host signature below is OBSERVED on a real host (live process
// env via `ps eww`, or the app bundle Info.plist), not guessed.
// - Anything unidentified falls back to AgentCodeCustom — never guess.
// - Deliberately NOT used: TERM_PROGRAM (reports the terminal, e.g. iTerm,
// not the agent host) and fuzzy parent-process name matching.
package auth
import (
"os"
"strings"
)
// AgentCodeCustom is the honest fallback for any host we cannot identify.
const AgentCodeCustom = "custom"
// hostSignature is a verified env fingerprint for a known agent host. EnvKeys
// match when any listed key is present and non-empty.
type hostSignature struct {
Code string
EnvKeys []string
}
// knownSignatures: CLI / daemon agents that inject a distinctive env var, which
// the dws subprocess they spawn inherits. All verified on a real machine
// (2026-06-16) via live process env / launch env — not guessed.
var knownSignatures = []hostSignature{
// Claude Code — verified: CLAUDECODE=1, CLAUDE_CODE_ENTRYPOINT=cli.
{Code: "claudecode", EnvKeys: []string{"CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"}},
// OpenClaw — verified on the running daemon: OPENCLAW_BUNDLE_ROOT.
{Code: "openclaw", EnvKeys: []string{"OPENCLAW_BUNDLE_ROOT", "OPENCLAW_RUNTIME_ROLE"}},
// Hermes — verified on the running gateway: HERMES_HOME.
{Code: "hermes", EnvKeys: []string{"HERMES_HOME"}},
// OpenAI Codex — CODEX_SANDBOX is auto-set by Codex for the subprocesses it
// spawns (e.g. CODEX_SANDBOX=seatbelt on macOS), and Codex filters this
// CODEX_-prefixed name out of user .env to prevent spoofing — so its
// presence reliably means "running under Codex".
// Source: developers.openai.com/codex/concepts/sandboxing
{Code: "codex", EnvKeys: []string{"CODEX_SANDBOX"}},
}
// NOTE on coverage limits (honest, not a TODO to silently ignore):
// Most terminal agents (gemini-cli/antigravity, aider, opencode, qwen-code,
// crush, goose, kimi, amazon-q, continue, ...) expose NO reliable
// self-identifying env marker — only user-set API-key/config vars, which we
// must not key off (a user setting GEMINI_API_KEY is not "running under
// gemini"). They therefore resolve to custom unless they declare themselves.
//
// The authoritative, fully-general path to 100% coverage is the T0 declaration
// contract: a host sets DINGTALK_DWS_AGENTCODE=<code> when it launches dws.
// That is accurate for ANY agent (present or future) on ANY OS, and is what an
// integrating host should wire up. Auto-detection (signatures / VSCODE_BRAND /
// bundle id) is a best-effort supplement for hosts that have not declared.
// bundleIDToCode maps macOS app bundle identifiers to agent codes. The bundle
// id is exposed via __CFBundleIdentifier and inherited by child processes the
// IDE spawns (including dws), so it identifies the host even from an integrated
// terminal. Verified from each app's Info.plist (2026-06-16). Only known agent
// bundles map; everything else (iTerm, Terminal, ...) falls through to custom.
//
// macOS-only signal: __CFBundleIdentifier does not exist on Linux/Windows, so
// this map is simply a no-op there (os.Getenv returns "").
var bundleIDToCode = map[string]string{
"com.qoder.ide": "qoder",
"com.todesktop.230313mzl4w4u92": "cursor", // Cursor's ToDesktop bundle id
"com.microsoft.VSCode": "vscode",
"com.workbuddy.workbuddy": "workbuddy",
}
// DetectAgentCode resolves the agent_code via a confidence ladder and returns
// the normalized code plus the signal that decided it:
//
// T0 explicit host declaration (DINGTALK_DWS_AGENTCODE — dedicated field)
// T1 verified per-agent env signature (CLI/daemon agents)
// T2 VSCODE_BRAND value (every VS Code fork declares its brand)
// T3 macOS app bundle id (known agent bundles only)
// T4 fallback -> custom (never guess)
func DetectAgentCode() (code string, signal string) {
// T0: host explicitly declares its agent_code — highest confidence.
if v, name := AgentCodeFromEnv(); v != "" {
return normalizeAgentCode(v), "env:" + name
}
// T1: verified per-agent env signature (most specific — wins over the IDE
// it may be running inside).
for _, sig := range knownSignatures {
for _, k := range sig.EnvKeys {
if strings.TrimSpace(os.Getenv(k)) != "" {
return sig.Code, "sig:" + k
}
}
}
// T2: VS Code fork family. The brand value IS the host's self-declaration,
// so this single rule covers Qoder/Cursor/VS Code/Windsurf/Trae/Kiro/... —
// including forks that don't exist yet.
if b := strings.TrimSpace(os.Getenv("VSCODE_BRAND")); b != "" {
return normalizeAgentCode(b), "env:VSCODE_BRAND"
}
// T3: macOS app bundle id (known agent bundles only).
if id := strings.TrimSpace(os.Getenv("__CFBundleIdentifier")); id != "" {
if c, ok := bundleIDToCode[id]; ok {
return c, "bundle:" + id
}
}
// T4: unknown host — honest fallback, no guessing.
return AgentCodeCustom, "fallback"
}
// normalizeAgentCode maps host-declared names/brands to canonical agent_code
// values. Unrecognized but non-empty input is lowercased, space-stripped and
// kept as-is — still a host declaration, so still accurate (this is what gives
// automatic coverage of new VS Code forks via VSCODE_BRAND).
func normalizeAgentCode(raw string) string {
s := strings.ToLower(strings.TrimSpace(raw))
s = strings.ReplaceAll(s, " ", "")
switch s {
case "":
return AgentCodeCustom
case "claude", "claude-code", "claude_code", "claudecode":
return "claudecode"
case "qoder", "qoderwork":
return "qoder"
case "workbuddy", "work-buddy":
return "workbuddy"
case "visualstudiocode", "code", "code-oss", "vscode":
return "vscode"
case "cursor":
return "cursor"
case "windsurf":
return "windsurf"
case "trae", "traecn":
return "trae"
default:
return s
}
}
+187
View File
@@ -0,0 +1,187 @@
// 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 (
"strings"
"testing"
)
// agentCodeSignalEnvs is every env DetectAgentCode consults. Tests clear them
// all so each case starts clean (the suite itself runs under a real host).
var agentCodeSignalEnvs = []string{
AgentCodeEnv,
"CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT",
"OPENCLAW_BUNDLE_ROOT", "OPENCLAW_RUNTIME_ROLE",
"HERMES_HOME", "CODEX_SANDBOX",
"VSCODE_BRAND", "__CFBundleIdentifier",
"TERM_PROGRAM", "DWS_CHANNEL",
}
func clearAgentCodeEnv(t *testing.T) {
t.Helper()
for _, k := range agentCodeSignalEnvs {
t.Setenv(k, "")
}
}
func TestDetectAgentCode_HostDeclaration_T0(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv(AgentCodeEnv, "Qoder")
code, sig := DetectAgentCode()
if code != "qoder" {
t.Fatalf("want qoder, got %q", code)
}
if !strings.HasPrefix(sig, "env:"+AgentCodeEnv) {
t.Fatalf("want env signal, got %q", sig)
}
}
func TestDetectAgentCode_VerifiedSignatures_T1(t *testing.T) {
cases := []struct {
env, val, want string
}{
{"CLAUDECODE", "1", "claudecode"},
{"CLAUDE_CODE_ENTRYPOINT", "cli", "claudecode"},
{"OPENCLAW_BUNDLE_ROOT", "/Users/x/.openclaw-bundle", "openclaw"},
{"HERMES_HOME", "/Users/x/.hermes", "hermes"},
{"CODEX_SANDBOX", "seatbelt", "codex"},
}
for _, c := range cases {
t.Run(c.env, func(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv(c.env, c.val)
code, sig := DetectAgentCode()
if code != c.want {
t.Fatalf("%s=%s: want %q, got %q", c.env, c.val, c.want, code)
}
if !strings.HasPrefix(sig, "sig:") {
t.Fatalf("want sig:* signal, got %q", sig)
}
})
}
}
func TestDetectAgentCode_VSCodeBrand_T2(t *testing.T) {
cases := map[string]string{
"Qoder": "qoder",
"Cursor": "cursor",
"Visual Studio Code": "vscode",
"Windsurf": "windsurf",
"Trae": "trae",
"SomeNewFork": "somenewfork", // generic coverage of future forks
}
for brand, want := range cases {
t.Run(brand, func(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv("VSCODE_BRAND", brand)
code, sig := DetectAgentCode()
if code != want {
t.Fatalf("VSCODE_BRAND=%q: want %q, got %q", brand, want, code)
}
if sig != "env:VSCODE_BRAND" {
t.Fatalf("want env:VSCODE_BRAND signal, got %q", sig)
}
})
}
}
func TestDetectAgentCode_BundleID_T3(t *testing.T) {
cases := map[string]string{
"com.qoder.ide": "qoder",
"com.todesktop.230313mzl4w4u92": "cursor",
"com.microsoft.VSCode": "vscode",
"com.workbuddy.workbuddy": "workbuddy",
}
for id, want := range cases {
t.Run(id, func(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv("__CFBundleIdentifier", id)
code, sig := DetectAgentCode()
if code != want {
t.Fatalf("bundle %q: want %q, got %q", id, want, code)
}
if !strings.HasPrefix(sig, "bundle:") {
t.Fatalf("want bundle:* signal, got %q", sig)
}
})
}
}
// An unknown bundle id (e.g. a plain terminal) must NOT be labeled — falls to
// custom.
func TestDetectAgentCode_UnknownBundleIsCustom(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv("__CFBundleIdentifier", "com.googlecode.iterm2")
code, _ := DetectAgentCode()
if code != AgentCodeCustom {
t.Fatalf("unknown bundle must be custom, got %q", code)
}
}
func TestDetectAgentCode_Fallback_Custom(t *testing.T) {
clearAgentCodeEnv(t)
code, sig := DetectAgentCode()
if code != AgentCodeCustom {
t.Fatalf("want custom, got %q", code)
}
if sig != "fallback" {
t.Fatalf("want fallback, got %q", sig)
}
}
// TERM_PROGRAM and DWS_CHANNEL must never decide agent_code.
func TestDetectAgentCode_IgnoresNoise(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv("TERM_PROGRAM", "iTerm.app")
t.Setenv("DWS_CHANNEL", "Qoderwork")
code, _ := DetectAgentCode()
if code != AgentCodeCustom {
t.Fatalf("noise must not decide agent_code; want custom, got %q", code)
}
}
// Precedence: explicit declaration (T0) > env signature (T1) > VSCODE_BRAND
// (T2). A CLI agent running inside an IDE reports the CLI agent.
func TestDetectAgentCode_Precedence(t *testing.T) {
clearAgentCodeEnv(t)
t.Setenv("CLAUDECODE", "1") // T1
t.Setenv("VSCODE_BRAND", "Qoder") // T2
if code, _ := DetectAgentCode(); code != "claudecode" {
t.Fatalf("T1 must beat T2, got %q", code)
}
t.Setenv(AgentCodeEnv, "workbuddy") // T0
if code, _ := DetectAgentCode(); code != "workbuddy" {
t.Fatalf("T0 must beat all, got %q", code)
}
}
func TestNormalizeAgentCode(t *testing.T) {
cases := map[string]string{
"claude": "claudecode",
"Claude-Code": "claudecode",
"CLAUDECODE": "claudecode",
"Qoderwork": "qoder",
"WorkBuddy": "workbuddy",
"Visual Studio Code": "vscode",
"Cursor": "cursor",
"": AgentCodeCustom,
"some-new-ide": "some-new-ide",
}
for in, want := range cases {
if got := normalizeAgentCode(in); got != want {
t.Errorf("normalizeAgentCode(%q) = %q, want %q", in, got, want)
}
}
}
+4
View File
@@ -23,6 +23,10 @@ const (
// injects to declare "this process is driven by a third-party Agent host,
// render authorization UI yourselves".
AgentCodeEnv = "DINGTALK_DWS_AGENTCODE"
// AgentCodeEnvCompat is a compatibility alias for hosts that shipped the
// reversed prefix before AgentCodeEnv became the public spelling.
AgentCodeEnvCompat = "DWS_DINGTALK_AGENTCODE"
)
// AgentCodeFromEnv returns the effective host agent code and the env name that
+46 -55
View File
@@ -27,8 +27,8 @@ import (
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/i18n"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/tui"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/fatih/color"
)
const (
@@ -52,6 +52,7 @@ type DeviceFlowProvider struct {
logger *slog.Logger
Output io.Writer
httpClient *http.Client
NoBrowser bool
}
func NewDeviceFlowProvider(configDir string, logger *slog.Logger) *DeviceFlowProvider {
@@ -146,13 +147,14 @@ type serviceResult struct {
}
// resetCredentialState clears any stale credential state inherited from
// previous login methods (OAuth, PAT, etc.) so that device flow always
// starts fresh by fetching clientID from MCP.
// previous login methods (OAuth, PAT, etc.) before device flow falls back to
// MCP-managed credentials.
//
// This is a defensive measure: no matter what a prior login wrote to
// app.json or runtime globals, device flow will re-fetch from MCP and
// set the correct clientIDFromMCP flag, ensuring exchangeCode() uses
// the MCP proxy path (which doesn't require clientSecret).
// app.json, device flow will re-fetch from MCP and set the correct
// clientIDFromMCP flag, ensuring exchangeCode() uses the MCP proxy path
// (which doesn't require clientSecret). Complete runtime AppKey/AppSecret
// overrides intentionally skip this reset.
func (p *DeviceFlowProvider) resetCredentialState() {
p.clientID = ""
clientMu.Lock()
@@ -161,22 +163,29 @@ func (p *DeviceFlowProvider) resetCredentialState() {
}
func (p *DeviceFlowProvider) Login(ctx context.Context) (*TokenData, error) {
// Defensive reset: clear any stale credential state from previous login
// methods (OAuth scan, PAT, etc.) so we always re-fetch from MCP.
// This ensures --device login works regardless of what app.json contains.
p.resetCredentialState()
if runtimeClientID, _, ok := getCompleteRuntimeCredentials(); ok {
p.clientID = runtimeClientID
clientMu.Lock()
clientIDFromMCP = false
clientMu.Unlock()
} else {
// Defensive reset: clear any stale credential state from previous login
// methods (OAuth scan, PAT, etc.) so we can re-fetch from MCP. This
// ensures --device login works regardless of what app.json contains.
p.resetCredentialState()
if p.logger != nil {
p.logger.Debug("fetching client ID from MCP server (device flow always re-fetches)")
}
mcpClientID, mcpErr := FetchClientIDFromMCP(ctx)
if mcpErr != nil {
return nil, fmt.Errorf("%s: %w", i18n.T("获取 Client ID 失败"), mcpErr)
}
p.clientID = mcpClientID
SetClientIDFromMCP(mcpClientID)
if p.logger != nil {
p.logger.Debug("fetched client ID from MCP server", "clientID", mcpClientID)
if p.logger != nil {
p.logger.Debug("fetching client ID from MCP server (device flow always re-fetches)")
}
mcpClientID, mcpErr := FetchClientIDFromMCP(ctx)
if mcpErr != nil {
return nil, fmt.Errorf("%s: %w", i18n.T("获取 Client ID 失败"), mcpErr)
}
p.clientID = mcpClientID
SetClientIDFromMCP(mcpClientID)
if p.logger != nil {
p.logger.Debug("fetched client ID from MCP server", "clientID", mcpClientID)
}
}
const maxAttempts = 3
@@ -205,7 +214,7 @@ func (p *DeviceFlowProvider) loginOnce(ctx context.Context, attempt int) (*Token
}
dfPrintDeviceCodeBox(p.output(), authResp)
if authResp.VerificationURIComplete != "" {
if authResp.VerificationURIComplete != "" && !p.NoBrowser {
if bErr := openBrowser(authResp.VerificationURIComplete); bErr != nil && p.logger != nil {
p.logger.Debug("could not open browser", "error", bErr)
}
@@ -582,20 +591,21 @@ func truncateBody(body []byte, maxLen int) string {
}
var (
dfBold = color.New(color.Bold).SprintFunc()
dfGreen = color.New(color.FgGreen).SprintFunc()
dfYellow = color.New(color.FgYellow).SprintFunc()
dfRed = color.New(color.FgRed).SprintFunc()
dfCyan = color.New(color.FgCyan).SprintFunc()
dfDim = color.New(color.Faint).SprintFunc()
dfBold = tui.Bold
dfGreen = tui.Success
dfYellow = tui.Warning
dfRed = tui.Danger
dfCyan = tui.Cyan
dfDim = tui.Dim
)
func dfPrintStep(w io.Writer, step int, message string, attempt int) {
label := fmt.Sprintf("Step %d", step)
if attempt > 1 {
_, _ = fmt.Fprintf(w, i18n.T("%s (第 %d 次尝试)\\n"), dfBold(fmt.Sprintf("▶ Step %d: %s", step, message)), attempt)
_, _ = fmt.Fprintf(w, i18n.T("%s %s: %s (第 %d 次尝试)\\n"), tui.StateMark("ok"), dfBold(label), message, attempt)
return
}
_, _ = fmt.Fprintf(w, "%s\n", dfBold(fmt.Sprintf("▶ Step %d: %s", step, message)))
_, _ = fmt.Fprintf(w, "%s %s: %s\n", tui.StateMark("ok"), dfBold(label), message)
}
func dfPrintDeviceCodeBox(w io.Writer, auth *DeviceAuthResponse) {
@@ -621,7 +631,7 @@ func dfPrintDeviceCodeBox(w io.Writer, auth *DeviceAuthResponse) {
func dfPrintBox(w io.Writer, lines []string) {
maxLen := 0
for _, line := range lines {
if l := dfPlainLength(line); l > maxLen {
if l := tui.PlainRuneWidth(line); l > maxLen {
maxLen = l
}
}
@@ -630,38 +640,19 @@ func dfPrintBox(w io.Writer, lines []string) {
}
border := strings.Repeat("─", maxLen+4)
_, _ = fmt.Fprintf(w, " ┌%s┐\n", border)
_, _ = fmt.Fprintf(w, " %s\n", tui.Blue("╭"+border+"╮"))
for _, line := range lines {
pad := maxLen - dfPlainLength(line)
pad := maxLen - tui.PlainRuneWidth(line)
if pad < 0 {
pad = 0
}
_, _ = fmt.Fprintf(w, " │ %s%s │\n", line, strings.Repeat(" ", pad))
_, _ = fmt.Fprintf(w, " %s %s%s %s\n", tui.Blue("│"), line, strings.Repeat(" ", pad), tui.Blue("│"))
}
_, _ = fmt.Fprintf(w, " └%s┘\n", border)
}
func dfPlainLength(s string) int {
inEscape := false
length := 0
for _, r := range s {
if r == '\033' {
inEscape = true
continue
}
if inEscape {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
inEscape = false
}
continue
}
length++
}
return length
_, _ = fmt.Fprintf(w, " %s\n", tui.Blue("╰"+border+"╯"))
}
func dfPrintPollStatus(w io.Writer, count, elapsedSec int) {
_, _ = fmt.Fprintf(w, " %s ", dfDim(fmt.Sprintf(i18n.T("[%d] 轮询中... (%ds)"), count, elapsedSec)))
_, _ = fmt.Fprintf(w, " %s %s ", tui.StateMark("pending"), dfDim(fmt.Sprintf(i18n.T("[%d] 轮询中... (%ds)"), count, elapsedSec)))
}
func dfPrintPollResult(w io.Writer, status, message string) {
+5
View File
@@ -290,6 +290,11 @@ func getRuntimeCredentials() (clientID, clientSecret string) {
return runtimeClientID, runtimeClientSecret
}
func getCompleteRuntimeCredentials() (clientID, clientSecret string, ok bool) {
clientID, clientSecret = getRuntimeCredentials()
return clientID, clientSecret, strings.TrimSpace(clientID) != "" && strings.TrimSpace(clientSecret) != ""
}
// getDefaultConfigDir returns the default configuration directory.
// Priority: DWS_CONFIG_DIR env var > ~/.dws
func getDefaultConfigDir() string {
+151 -14
View File
@@ -13,17 +13,27 @@
// identity.go manages agent instance identification for tracking.
//
// Each agent installation gets a unique agentId (UUID v4) that persists across
// version upgrades but regenerates on reinstall. This identity is transparently
// injected into MCP HTTP headers for gateway-side data collection.
// Identity has two granularities, both injected into MCP HTTP headers for
// gateway-side statistics:
//
// - machineId: a stable per-install UUID v4 (persists across upgrades,
// regenerates on reinstall). Non-PII.
// - agentId: a per-(machine × agentCode) id derived deterministically from
// machineId + agent_code, so one machine running multiple agent hosts
// (e.g. claudecode + cursor) yields a distinct, idempotent agentId per
// agent_code. Computed client-side — no gateway round-trip required.
//
// The agent_code itself is resolved by DetectAgentCode (agent_code_detect.go).
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/json"
"fmt"
"math/big"
"os"
"path/filepath"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
@@ -31,14 +41,34 @@ import (
const identityFile = "identity.json"
// identityVersion is the current on-disk schema version. v1 files (no
// machineId/agents) are migrated transparently on load.
const identityVersion = 2
// AgentEntry records the derived agentId for a single agent_code on this
// machine.
type AgentEntry struct {
AgentID string `json:"agentId"`
FirstSeen string `json:"firstSeen,omitempty"`
Detect string `json:"detect,omitempty"` // signal that decided the agent_code
}
// Identity holds the agent instance identification fields.
//
// AgentID is retained for backward compatibility with v1 readers: on a fresh
// install it is written equal to MachineID, and a v1 file's agentId is migrated
// into MachineID on load.
type Identity struct {
AgentID string `json:"agentId"` // UUID v4, generated at install time
Source string `json:"source"` // data source, default "dws"
Version int `json:"version,omitempty"`
AgentID string `json:"agentId"` // v1 install UUID; == MachineID on v2 installs
MachineID string `json:"machineId,omitempty"` // stable per-install machine seed
Source string `json:"source"` // data source, default "dws"
Agents map[string]*AgentEntry `json:"agents,omitempty"` // agent_code -> derived agentId
}
// Load reads the identity from <configDir>/identity.json.
// Returns nil if the file does not exist or cannot be parsed.
// v1 files are migrated in-memory (machineId backfilled from agentId).
func Load(configDir string) *Identity {
path := filepath.Join(configDir, identityFile)
data, err := os.ReadFile(path)
@@ -49,21 +79,43 @@ func Load(configDir string) *Identity {
if err := json.Unmarshal(data, &id); err != nil {
return nil
}
if id.AgentID == "" {
if id.AgentID == "" && id.MachineID == "" {
return nil
}
id.migrate()
return &id
}
// migrate backfills v2 fields from a v1 file in-memory (does not persist).
func (id *Identity) migrate() {
if id.MachineID == "" {
id.MachineID = id.AgentID // v1 install UUID becomes the machine seed
}
if id.AgentID == "" {
id.AgentID = id.MachineID
}
if id.Source == "" {
id.Source = "dws"
}
if id.Agents == nil {
id.Agents = make(map[string]*AgentEntry)
}
id.Version = identityVersion
}
// EnsureExists loads existing identity or creates a new one if not present.
func EnsureExists(configDir string) *Identity {
if id := Load(configDir); id != nil {
return id
}
u := generateUUID()
id := &Identity{
AgentID: generateUUID(),
Source: "dws",
Version: identityVersion,
AgentID: u, // kept == MachineID for backward-compat
MachineID: u,
Source: "dws",
Agents: make(map[string]*AgentEntry),
}
// Best-effort persist — don't fail the CLI if write fails.
@@ -71,14 +123,51 @@ func EnsureExists(configDir string) *Identity {
return id
}
// Headers returns the identity as HTTP header key-value pairs.
// machineSeed returns the stable seed used to derive per-channel agentIds.
func (id *Identity) machineSeed() string {
if id.MachineID != "" {
return id.MachineID
}
return id.AgentID
}
// ResolveAgentID returns the per-(machine × agentCode) agentId, deriving and
// persisting it on first sight of an agentCode. Idempotent: the same machine
// and agentCode always yields the same id, which is what makes cumulative
// per-agent_code statistics possible. An empty agentCode is treated as the
// custom bucket.
func (id *Identity) ResolveAgentID(configDir, agentCode, signal string) string {
if agentCode == "" {
agentCode = AgentCodeCustom
}
if id.Agents == nil {
id.Agents = make(map[string]*AgentEntry)
}
if e, ok := id.Agents[agentCode]; ok && e.AgentID != "" {
return e.AgentID
}
aid := deriveAgentID(id.machineSeed(), agentCode)
id.Agents[agentCode] = &AgentEntry{
AgentID: aid,
FirstSeen: time.Now().UTC().Format(time.RFC3339),
Detect: signal,
}
_ = save(configDir, id) // best-effort cache; recomputable if it fails
return aid
}
// Headers returns the identity as static HTTP header key-value pairs.
// x-dws-agent-id carries the stable machine-level id (== v1 install UUID), kept
// continuous across versions. The per-(machine × agent_code) instance id is a
// SEPARATE header (x-dws-agent-instance-id) injected by the caller via
// ResolveAgentID — it does not override x-dws-agent-id.
func (id *Identity) Headers() map[string]string {
if id == nil {
return nil
}
h := make(map[string]string, 5)
if id.AgentID != "" {
h["x-dws-agent-id"] = id.AgentID
if seed := id.machineSeed(); seed != "" {
h["x-dws-agent-id"] = seed
}
if id.Source != "" {
h["x-dws-source"] = id.Source
@@ -104,6 +193,38 @@ func save(configDir string, id *Identity) error {
return os.WriteFile(filepath.Join(configDir, identityFile), data, config.FilePerm)
}
// deriveAgentID computes a stable, client-side agentId for a (machine,
// agentCode) pair: dwsa_<12 base62 chars of sha256(seed|agentCode)>.
// Deterministic and idempotent; no gateway allocation needed for statistics.
func deriveAgentID(seed, agentCode string) string {
sum := sha256.Sum256([]byte(seed + "|" + agentCode))
enc := base62Encode(sum[:])
for len(enc) < 12 {
enc = "0" + enc
}
return "dwsa_" + enc[:12]
}
const base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
func base62Encode(b []byte) string {
n := new(big.Int).SetBytes(b)
if n.Sign() == 0 {
return "0"
}
base := big.NewInt(62)
mod := new(big.Int)
var out []byte
for n.Sign() > 0 {
n.DivMod(n, base, mod)
out = append(out, base62Alphabet[mod.Int64()])
}
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
return string(out)
}
// generateUUID produces a UUID v4 string.
func generateUUID() string {
var u [16]byte
@@ -113,6 +234,22 @@ func generateUUID() string {
}
u[6] = (u[6] & 0x0f) | 0x40 // version 4
u[8] = (u[8] & 0x3f) | 0x80 // variant 10
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
u[0:4], u[4:6], u[6:8], u[8:10], u[10:16])
return fmtUUID(u)
}
func fmtUUID(u [16]byte) string {
const hexdig = "0123456789abcdef"
// 8-4-4-4-12 with dashes => 36 bytes
buf := make([]byte, 36)
pos := 0
for i := 0; i < 16; i++ {
if i == 4 || i == 6 || i == 8 || i == 10 {
buf[pos] = '-'
pos++
}
buf[pos] = hexdig[u[i]>>4]
buf[pos+1] = hexdig[u[i]&0x0f]
pos += 2
}
return string(buf)
}
+111
View File
@@ -0,0 +1,111 @@
// 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"
"strings"
"testing"
)
func TestDeriveAgentID_Format(t *testing.T) {
id := deriveAgentID("machine-abc", "claudecode")
if !strings.HasPrefix(id, "dwsa_") {
t.Fatalf("want dwsa_ prefix, got %q", id)
}
if len(id) != len("dwsa_")+12 {
t.Fatalf("want 12 base62 chars after prefix, got %q (len %d)", id, len(id))
}
}
func TestDeriveAgentID_Deterministic(t *testing.T) {
a := deriveAgentID("seed", "claudecode")
b := deriveAgentID("seed", "claudecode")
if a != b {
t.Fatalf("derivation must be deterministic: %q != %q", a, b)
}
}
func TestDeriveAgentID_DistinctByChannelAndMachine(t *testing.T) {
m1c1 := deriveAgentID("machine1", "claudecode")
m1c2 := deriveAgentID("machine1", "cursor")
m2c1 := deriveAgentID("machine2", "claudecode")
if m1c1 == m1c2 {
t.Errorf("same machine, different channel must differ: %q", m1c1)
}
if m1c1 == m2c1 {
t.Errorf("different machine, same channel must differ: %q", m1c1)
}
}
func TestResolveAgentID_IdempotentAndPersisted(t *testing.T) {
dir := t.TempDir()
id := EnsureExists(dir)
first := id.ResolveAgentID(dir, "claudecode", "sig:CLAUDECODE")
second := id.ResolveAgentID(dir, "claudecode", "sig:CLAUDECODE")
if first != second {
t.Fatalf("ResolveAgentID must be idempotent: %q != %q", first, second)
}
// Reload from disk — the channel entry must have persisted.
reloaded := Load(dir)
if reloaded == nil {
t.Fatal("expected identity to persist")
}
e, ok := reloaded.Agents["claudecode"]
if !ok || e.AgentID != first {
t.Fatalf("persisted agentId mismatch: %+v", reloaded.Agents)
}
if e.Detect != "sig:CLAUDECODE" {
t.Errorf("want detect signal recorded, got %q", e.Detect)
}
}
func TestResolveAgentID_EmptyAgentCodeGoesCustom(t *testing.T) {
dir := t.TempDir()
id := EnsureExists(dir)
got := id.ResolveAgentID(dir, "", "fallback")
want := id.ResolveAgentID(dir, AgentCodeCustom, "fallback")
if got != want {
t.Fatalf("empty agent_code must map to custom bucket: %q != %q", got, want)
}
}
// A v1 file ({agentId, source}) must migrate: machineId backfilled from the
// legacy agentId, and per-channel derivation keyed off that stable seed.
func TestLoad_MigratesV1(t *testing.T) {
dir := t.TempDir()
v1 := `{"agentId":"504ddd36-3acf-45f6-9c1f-82f99260a419","source":"dws"}`
if err := os.WriteFile(filepath.Join(dir, identityFile), []byte(v1), 0o600); err != nil {
t.Fatal(err)
}
id := Load(dir)
if id == nil {
t.Fatal("v1 file should load")
}
if id.MachineID != "504ddd36-3acf-45f6-9c1f-82f99260a419" {
t.Fatalf("machineId must backfill from legacy agentId, got %q", id.MachineID)
}
if id.machineSeed() != id.MachineID {
t.Fatalf("seed should be machineId, got %q", id.machineSeed())
}
// Derivation is stable against the migrated seed.
want := deriveAgentID(id.MachineID, "claudecode")
if got := id.ResolveAgentID(dir, "claudecode", "sig:CLAUDECODE"); got != want {
t.Fatalf("post-migration derivation mismatch: %q != %q", got, want)
}
}
+29 -19
View File
@@ -42,6 +42,7 @@ type OAuthProvider struct {
logger *slog.Logger
Output io.Writer
httpClient *http.Client
NoBrowser bool
}
// NewOAuthProvider creates a new OAuth provider.
@@ -56,8 +57,8 @@ func NewOAuthProvider(configDir string, logger *slog.Logger) *OAuthProvider {
}
// resetCredentialState clears any stale credential state inherited from
// previous login methods so that OAuth flow always starts fresh by
// fetching clientID from MCP.
// previous login methods before the OAuth flow falls back to MCP-managed
// credentials. Complete runtime AppKey/AppSecret overrides skip this reset.
func (p *OAuthProvider) resetCredentialState() {
p.clientID = ""
clientMu.Lock()
@@ -109,22 +110,29 @@ func (p *OAuthProvider) Login(ctx context.Context, force bool) (*TokenData, erro
}
// Fall through: full browser OAuth flow.
// Defensive reset: clear any stale credential state from previous login
// methods so we always re-fetch clientID from MCP. This ensures
// --force login works regardless of what app.json contains.
p.resetCredentialState()
if runtimeClientID, _, ok := getCompleteRuntimeCredentials(); ok {
p.clientID = runtimeClientID
clientMu.Lock()
clientIDFromMCP = false
clientMu.Unlock()
} else {
// Defensive reset: clear any stale credential state from previous login
// methods so we can re-fetch clientID from MCP. This ensures --force
// login works regardless of what app.json contains.
p.resetCredentialState()
if p.logger != nil {
p.logger.Debug("fetching client ID from MCP server (OAuth flow always re-fetches)")
}
mcpClientID, mcpErr := FetchClientIDFromMCP(ctx)
if mcpErr != nil {
return nil, fmt.Errorf("%s: %w", i18n.T("获取 Client ID 失败"), mcpErr)
}
p.clientID = mcpClientID
SetClientIDFromMCP(mcpClientID)
if p.logger != nil {
p.logger.Debug("fetched client ID from MCP server", "clientID", mcpClientID)
if p.logger != nil {
p.logger.Debug("fetching client ID from MCP server (OAuth flow always re-fetches)")
}
mcpClientID, mcpErr := FetchClientIDFromMCP(ctx)
if mcpErr != nil {
return nil, fmt.Errorf("%s: %w", i18n.T("获取 Client ID 失败"), mcpErr)
}
p.clientID = mcpClientID
SetClientIDFromMCP(mcpClientID)
if p.logger != nil {
p.logger.Debug("fetched client ID from MCP server", "clientID", mcpClientID)
}
}
// Find a free port for the callback server.
@@ -393,8 +401,10 @@ func (p *OAuthProvider) Login(ctx context.Context, force bool) (*TokenData, erro
if p.logger != nil {
p.logger.Debug("authorization URL", "url", authURL)
}
if err := openBrowser(authURL); err != nil && p.logger != nil {
p.logger.Warn(i18n.T("无法自动打开浏览器"), "error", err)
if !p.NoBrowser {
if err := openBrowser(authURL); err != nil && p.logger != nil {
p.logger.Warn(i18n.T("无法自动打开浏览器"), "error", err)
}
}
_, _ = fmt.Fprintln(p.output(), "")
+42 -2
View File
@@ -103,7 +103,7 @@ func NewMCPCommand(ctx context.Context, loader CatalogLoader, runner executor.Ru
return cmd
}
func NewSchemaCommand(loader CatalogLoader) *cobra.Command {
func NewSchemaCommand(loader CatalogLoader, helperTools HelperToolFetcher) *cobra.Command {
cmd := &cobra.Command{
Use: "schema [path]",
Short: "查看 MCP 工具 Schema (产品列表 / 工具参数)",
@@ -125,7 +125,13 @@ func NewSchemaCommand(loader CatalogLoader) *cobra.Command {
dws schema --cli-path "ding message send" # 同上,显式 flag(脚本友好)
dws schema calendar.create_event --jq '.tool.auth'
dws schema -f pretty ding.send_ding_message # ANSI 彩色分区展示
dws schema --jq '.tool.flag_overlay' # 只看 CLI overlay`,
dws schema --jq '.tool.flag_overlay' # 只看 CLI overlay
helper-only 命令组(如 dev,不走服务发现)也支持查询,schema 从 op-app
MCP 服务端实时拉取,输出对齐 gws 的扁平格式(parameters 内联 required,
键为 CLI flag):
dws schema "dev app robot config" # 实时 MCP 参数 schema(gws-flat)
dws schema "dev app" # 列出该分组下的子命令`,
Args: cobra.MaximumNArgs(1),
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -137,6 +143,29 @@ func NewSchemaCommand(loader CatalogLoader) *cobra.Command {
}
args = []string{cliPath}
}
// Helper-only subtrees (e.g. `dws dev ...`) aren't in the discovery
// catalog; their schema CONTENT is fetched LIVE from the helper's
// pinned MCP server (op-app) and rendered in the gws-flat shape, so
// `dws schema "dev app robot config"` answers without touching
// discovery. Only the `dev` root claims this path; everything else
// falls through to the catalog below.
if len(args) > 0 {
payload, ok, err := renderHelperSchema(cmd.Context(), cmd.Root(), args[0], helperTools)
if err != nil {
return err
}
if ok {
return output.WriteFiltered(
cmd.OutOrStdout(),
output.ResolveFormat(cmd, output.FormatJSON),
payload,
output.ResolveFields(cmd),
output.ResolveJQ(cmd),
)
}
}
catalog, err := loader.Load(cmd.Context())
if err != nil {
var degraded *CatalogDegraded
@@ -166,6 +195,17 @@ func NewSchemaCommand(loader CatalogLoader) *cobra.Command {
return err
}
// Append helper-only subtrees (e.g. `dev`) to the no-arg product
// listing so browsing all products also surfaces helper commands.
if len(args) == 0 {
if helpers := helperProductSummaries(cmd.Root()); len(helpers) > 0 {
if products, ok := payload["products"].([]map[string]any); ok {
payload["products"] = append(products, helpers...)
payload["count"] = len(payload["products"].([]map[string]any))
}
}
}
return output.WriteFiltered(
cmd.OutOrStdout(),
output.ResolveFormat(cmd, output.FormatJSON),
+6 -6
View File
@@ -288,7 +288,7 @@ func TestSchemaCommandCLIPathFlag(t *testing.T) {
}}
t.Run("resolves via --cli-path", func(t *testing.T) {
cmd := NewSchemaCommand(loader)
cmd := NewSchemaCommand(loader, nil)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&bytes.Buffer{})
@@ -310,7 +310,7 @@ func TestSchemaCommandCLIPathFlag(t *testing.T) {
})
t.Run("rejects positional + flag collision", func(t *testing.T) {
cmd := NewSchemaCommand(loader)
cmd := NewSchemaCommand(loader, nil)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&bytes.Buffer{})
@@ -1252,7 +1252,7 @@ func TestSchemaCommandOutputsDegradedOnUnauthenticated(t *testing.T) {
Reason: DegradedUnauthenticated,
Hint: "未登录,无法发现 MCP 服务。请先执行: dws auth login",
}
cmd := NewSchemaCommand(errorLoader{err: degradedErr})
cmd := NewSchemaCommand(errorLoader{err: degradedErr}, nil)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
@@ -1285,9 +1285,9 @@ func TestSchemaCommandOutputsDegradedOnMarketUnreachable(t *testing.T) {
degradedErr := &CatalogDegraded{
Reason: DegradedMarketUnreachable,
Hint: "无法连接 MCP 市场 (mcp.dingtalk.com),请检查网络",
Hint: "无法连接 MCP 市场,请检查网络",
}
cmd := NewSchemaCommand(errorLoader{err: degradedErr})
cmd := NewSchemaCommand(errorLoader{err: degradedErr}, nil)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
@@ -1310,7 +1310,7 @@ func TestSchemaCommandPropagatesNonDegradedError(t *testing.T) {
t.Parallel()
wantErr := errors.New("unexpected failure")
cmd := NewSchemaCommand(errorLoader{err: wantErr})
cmd := NewSchemaCommand(errorLoader{err: wantErr}, nil)
var out bytes.Buffer
cmd.SetOut(&out)
+345
View File
@@ -0,0 +1,345 @@
// 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 cli
import (
"context"
"fmt"
"sort"
"strings"
"unicode"
"github.com/spf13/cobra"
)
// helperSchemaRoots are top-level command names whose subtrees are helper-only
// (hard-coded cobra commands, not in the discovery catalog). `dws schema` still
// answers for them, but unlike discovery products the schema CONTENT is fetched
// LIVE from the helper's pinned MCP server (op-app) and rendered in the flat
// gws-aligned shape — never synthesized from local cobra flags, never
// hardcoded. The mapping from a leaf command to its MCP tool comes from the
// `mcp-tool` cobra annotation set in internal/helpers/devapp.go.
var helperSchemaRoots = map[string]bool{"dev": true}
// HelperToolSchema is the live op-app tool schema the renderer needs: the raw
// MCP description plus the inputSchema's properties/required, exactly as the
// server returned them (no local transformation of CONTENT).
type HelperToolSchema struct {
Name string
Description string
Properties map[string]any // MCP param name → property object {type,description,default?,...}
Required []string // MCP param names that are required
}
// HelperToolFetcher loads a helper MCP server's tools/list LIVE and returns
// toolName→schema for the given source (e.g. "op-app" for dev app commands,
// "devdoc" for dev doc commands). The schema command injects this so
// dev_schema.go can resolve a command's MCP tool and render its real schema
// without the cli package importing app/transport. Implementations should
// cache per-source per-process so repeated `dws schema dev.*` only hit the
// network once per source.
type HelperToolFetcher func(ctx context.Context, source string) (map[string]HelperToolSchema, error)
// renderHelperSchema builds the `dws schema` payload for helper-only command
// subtrees. Returns (payload, true) when the path targets a helper subtree (so
// the caller skips catalog resolution); (nil, false) otherwise so the caller
// falls back to the discovery catalog.
//
// Leaf commands render the gws-flat object {description, path, source,
// parameters{<kebab>:{type,description,default?,required}}} with all CONTENT
// pulled live from the MCP tool named by the command's `mcp-tool` annotation.
// Group/root paths render a browse listing {path, commands:[...]} from the
// cobra tree (no MCP needed).
func renderHelperSchema(ctx context.Context, root *cobra.Command, rawPath string, fetch HelperToolFetcher) (map[string]any, bool, error) {
if root == nil {
return nil, false, nil
}
tokens := splitSchemaPathTokens(rawPath)
if len(tokens) == 0 || !helperSchemaRoots[tokens[0]] {
return nil, false, nil
}
target, rest, err := root.Find(tokens)
if err != nil || target == nil {
target = root
rest = tokens[1:]
}
// Find resolves to the deepest matching command and returns trailing tokens
// it couldn't match as (sub)commands. Any non-flag leftover means a typo'd
// or unknown subcommand — surface it with the closest group's children.
if unknown := firstNonFlag(rest); unknown != "" {
return map[string]any{
"path": rawPath,
"error": "unknown subcommand \"" + unknown + "\" under \"" + helperCommandPath(target) + "\"",
"available": helperSubcommands(target),
}, true, nil
}
// A runnable leaf → emit its live MCP schema in gws-flat shape.
// A group → browse its subcommands.
if target.Runnable() && !target.HasAvailableSubCommands() {
payload, err := helperLeafSchema(ctx, target, fetch)
return payload, true, err
}
return map[string]any{
"path": helperCommandPath(target),
"commands": helperSubcommands(target),
}, true, nil
}
// helperLeafSchema renders a single leaf command as the gws-flat object,
// fetching its MCP tool schema live. The command must carry an `mcp-tool`
// annotation; commands without one (e.g. `dev connect`, `dev doc search`) are
// not devapp tools and get a clear, non-fatal explanation instead.
func helperLeafSchema(ctx context.Context, cmd *cobra.Command, fetch HelperToolFetcher) (map[string]any, error) {
toolName, source := "", ""
if cmd.Annotations != nil {
toolName = strings.TrimSpace(cmd.Annotations["mcp-tool"])
source = strings.TrimSpace(cmd.Annotations["mcp-source"])
}
// Default source is op-app (dev app commands); dev doc commands annotate
// mcp-source=devdoc to pull from the devdoc MCP server instead.
if source == "" {
source = "op-app"
}
path := helperCommandPath(cmd)
if toolName == "" {
return map[string]any{
"path": path,
"error": "no MCP tool bound to this command; schema is unavailable",
}, nil
}
if fetch == nil {
return map[string]any{
"path": path,
"error": "live MCP schema fetcher not configured",
}, nil
}
tools, err := fetch(ctx, source)
if err != nil {
return nil, fmt.Errorf("fetch %s tool schemas: %w", source, err)
}
tool, ok := tools[toolName]
if !ok {
return map[string]any{
"path": path,
"error": fmt.Sprintf("MCP tool %q not found in %s tools/list", toolName, source),
}, nil
}
return map[string]any{
"description": tool.Description,
"path": path,
"source": "mcp:" + source,
"parameters": helperFlatParameters(tool),
}, nil
}
// helperFlatParameters projects an MCP tool's inputSchema into the gws-flat
// per-parameter object. Keys are kebab-case of the MCP param name (== the CLI
// flag); each value is {type, description, default?, required} with type mapped
// to a JSON-type string, description verbatim from MCP, default only when MCP
// provides one (stringified), and required inline (true iff the param is in the
// tool's required[]).
func helperFlatParameters(tool HelperToolSchema) map[string]any {
required := make(map[string]bool, len(tool.Required))
for _, r := range tool.Required {
required[r] = true
}
params := make(map[string]any, len(tool.Properties))
for name, raw := range tool.Properties {
prop, _ := raw.(map[string]any)
entry := map[string]any{
"type": mcpJSONType(prop),
"description": mcpString(prop, "description"),
"required": required[name],
}
if def, ok := mcpDefault(prop); ok {
entry["default"] = def
}
params[kebabCase(name)] = entry
}
return params
}
// mcpJSONType normalizes the MCP property "type" to a JSON-type string. MCP
// reports standard JSON Schema types; pass them through, defaulting to "string"
// when absent/unknown so the contract is always populated.
func mcpJSONType(prop map[string]any) string {
t, _ := prop["type"].(string)
switch t {
case "string", "integer", "number", "boolean", "array", "object":
return t
default:
return "string"
}
}
// mcpString reads a string field from an MCP property object.
func mcpString(prop map[string]any, key string) string {
if prop == nil {
return ""
}
v, _ := prop[key].(string)
return v
}
// mcpDefault returns the MCP-provided default, stringified, only when present.
// gws renders default as a string; mirror that. Non-string JSON defaults
// (numbers/bools) are formatted with %v so e.g. 0 → "0", true → "true".
func mcpDefault(prop map[string]any) (string, bool) {
if prop == nil {
return "", false
}
v, ok := prop["default"]
if !ok || v == nil {
return "", false
}
switch tv := v.(type) {
case string:
return tv, true
case float64:
// JSON numbers decode to float64; render integers without a fraction.
if tv == float64(int64(tv)) {
return fmt.Sprintf("%d", int64(tv)), true
}
return fmt.Sprintf("%v", tv), true
default:
return fmt.Sprintf("%v", tv), true
}
}
// kebabCase converts an MCP camelCase param name to the CLI flag's kebab form,
// matching how flags are registered in internal/helpers/devapp.go:
//
// eventCallbackUrl → event-callback-url
// unifiedAppId → unified-app-id
// disableSSLVerify → disable-ssl-verify
//
// A boundary is inserted before an uppercase letter that follows a lowercase
// letter or digit, and before the final uppercase of a run that starts a new
// lowercase word (so SSLVerify → ssl-verify, not s-s-l-verify).
func kebabCase(name string) string {
runes := []rune(name)
var b strings.Builder
for i, r := range runes {
if unicode.IsUpper(r) {
prevLowerOrDigit := i > 0 && (unicode.IsLower(runes[i-1]) || unicode.IsDigit(runes[i-1]))
nextLower := i+1 < len(runes) && unicode.IsLower(runes[i+1])
if i > 0 && (prevLowerOrDigit || nextLower) {
b.WriteByte('-')
}
b.WriteRune(unicode.ToLower(r))
continue
}
b.WriteRune(r)
}
// Collapse any accidental double dashes and trim, just in case the source
// already contained separators.
out := strings.ReplaceAll(b.String(), "_", "-")
for strings.Contains(out, "--") {
out = strings.ReplaceAll(out, "--", "-")
}
return strings.Trim(out, "-")
}
// helperProductSummaries returns light product entries for every helper-only
// subtree, appended to the no-arg `dws schema` product listing so agents
// browsing all products also see helper commands. Tools are listed by path +
// summary only; drill in with `dws schema "<path>"` for full parameter schema.
func helperProductSummaries(root *cobra.Command) []map[string]any {
if root == nil {
return nil
}
out := []map[string]any{}
for name := range helperSchemaRoots {
top, _, err := root.Find([]string{name})
if err != nil || top == nil || !top.HasParent() {
continue
}
leaves := []map[string]any{}
walkLeafCommands(top, func(leaf *cobra.Command) {
leaves = append(leaves, map[string]any{
"cli_name": leaf.Name(),
"cli_path": helperCommandPath(leaf),
"description": strings.TrimSpace(leaf.Short),
})
})
out = append(out, map[string]any{
"id": name,
"name": strings.TrimSpace(top.Short),
"description": "helper-only 命令组(不走服务发现);schema 从 op-app MCP 实时拉取,用 `dws schema \"" + helperCommandPath(top) + " ...\"` 查具体参数",
"helper": true,
"tools": leaves,
})
}
return out
}
// walkLeafCommands invokes fn for every runnable leaf under cmd (depth-first).
func walkLeafCommands(cmd *cobra.Command, fn func(*cobra.Command)) {
if cmd.Runnable() && !cmd.HasAvailableSubCommands() {
fn(cmd)
return
}
for _, sub := range cmd.Commands() {
if !sub.IsAvailableCommand() || sub.Name() == "help" {
continue
}
walkLeafCommands(sub, fn)
}
}
// helperSubcommands lists a group's runnable children for browse mode, sorted
// by name for deterministic output.
func helperSubcommands(cmd *cobra.Command) []map[string]any {
out := []map[string]any{}
for _, sub := range cmd.Commands() {
if !sub.IsAvailableCommand() || sub.Name() == "help" {
continue
}
out = append(out, map[string]any{
"cli_path": helperCommandPath(sub),
"description": strings.TrimSpace(sub.Short),
})
}
sort.Slice(out, func(i, j int) bool {
return out[i]["cli_path"].(string) < out[j]["cli_path"].(string)
})
return out
}
// helperCommandPath returns the space-joined path from root to cmd, e.g.
// "dev app robot config".
func helperCommandPath(cmd *cobra.Command) string {
parts := []string{}
for c := cmd; c != nil && c.HasParent(); c = c.Parent() {
parts = append([]string{c.Name()}, parts...)
}
return strings.Join(parts, " ")
}
// firstNonFlag returns the first token that is not a flag (does not start with
// "-"), or "" if there is none.
func firstNonFlag(tokens []string) string {
for _, t := range tokens {
if t != "" && !strings.HasPrefix(t, "-") {
return t
}
}
return ""
}
+254
View File
@@ -0,0 +1,254 @@
// 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 cli
import (
"context"
"errors"
"testing"
"github.com/spf13/cobra"
)
// buildHelperTestTree mirrors the shape of the real `dws dev` subtree closely
// enough to exercise the live-schema renderer: a group and leaves carrying the
// `mcp-tool` annotation that names the op-app tool to fetch.
func buildHelperTestTree() *cobra.Command {
root := &cobra.Command{Use: "dws"}
create := &cobra.Command{
Use: "create",
Short: "创建应用",
Annotations: map[string]string{"mcp-tool": "create_dev_app"},
Run: func(*cobra.Command, []string) {},
}
config := &cobra.Command{
Use: "config",
Short: "配置机器人",
Annotations: map[string]string{"mcp-tool": "set_extension_robot_config"},
Run: func(*cobra.Command, []string) {},
}
// A leaf without an mcp-tool annotation (e.g. dev connect / dev doc search).
noTool := &cobra.Command{Use: "connect", Short: "无 MCP 工具", Run: func(*cobra.Command, []string) {}}
robot := &cobra.Command{Use: "robot", Short: "机器人能力"}
robot.AddCommand(config)
app := &cobra.Command{Use: "app", Short: "应用"}
app.AddCommand(create, robot)
dev := &cobra.Command{Use: "dev", Short: "开放平台开发者命令"}
dev.AddCommand(app, noTool)
root.AddCommand(dev)
return root
}
// fakeFetcher returns a canned op-app tools/list so the renderer is exercised
// without network. It mirrors the MCP shape: properties keyed by camelCase param
// name, required[] listing the camelCase names.
func fakeFetcher(tools map[string]HelperToolSchema) HelperToolFetcher {
return func(context.Context, string) (map[string]HelperToolSchema, error) {
return tools, nil
}
}
func robotConfigToolSchema() HelperToolSchema {
return HelperToolSchema{
Name: "set_extension_robot_config",
Description: "创建或更新现有应用的机器人配置",
Properties: map[string]any{
"unifiedAppId": map[string]any{"type": "string", "description": "统一应用 ID"},
"eventCallbackUrl": map[string]any{"type": "string", "description": "事件回调地址"},
"skills": map[string]any{"type": "array", "description": "技能列表"},
"mode": map[string]any{"type": "string", "description": "机器人模式", "enum": []any{"HTTPS", "STREAM", "AISKILL"}},
},
Required: []string{"unifiedAppId"},
}
}
func TestRenderHelperSchema_LeafGwsFlat(t *testing.T) {
root := buildHelperTestTree()
fetch := fakeFetcher(map[string]HelperToolSchema{
"set_extension_robot_config": robotConfigToolSchema(),
})
payload, ok, err := renderHelperSchema(context.Background(), root, "dev app robot config", fetch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !ok {
t.Fatal("expected helper renderer to claim the path")
}
// Flat top-level: description / path / source / parameters; no wrapper.
if payload["description"] != "创建或更新现有应用的机器人配置" {
t.Fatalf("description = %v", payload["description"])
}
if payload["path"] != "dev app robot config" {
t.Fatalf("path = %v", payload["path"])
}
if payload["source"] != "mcp:op-app" {
t.Fatalf("source = %v", payload["source"])
}
for _, leaked := range []string{"kind", "tool", "product", "helper"} {
if _, present := payload[leaked]; present {
t.Fatalf("gws-flat output must not carry %q wrapper key", leaked)
}
}
params, _ := payload["parameters"].(map[string]any)
if params == nil {
t.Fatalf("no parameters: %#v", payload)
}
// Keys are kebab-case of the MCP param name == the CLI flag.
uid, _ := params["unified-app-id"].(map[string]any)
if uid == nil {
t.Fatalf("missing unified-app-id param: %#v", params)
}
if uid["type"] != "string" || uid["required"] != true {
t.Fatalf("unified-app-id = %#v, want string+required", uid)
}
if _, hasDefault := uid["default"]; hasDefault {
t.Fatal("unified-app-id must not carry a default (MCP provides none)")
}
cb, _ := params["event-callback-url"].(map[string]any)
if cb == nil || cb["required"] != false {
t.Fatalf("event-callback-url = %#v, want required=false", cb)
}
skills, _ := params["skills"].(map[string]any)
if skills == nil || skills["type"] != "array" {
t.Fatalf("skills = %#v, want array", skills)
}
mode, _ := params["mode"].(map[string]any)
if mode == nil || mode["type"] != "string" {
t.Fatalf("mode = %#v, want string", mode)
}
if _, hasDefault := mode["default"]; hasDefault {
t.Fatalf("mode default = %v, want none", mode["default"])
}
if mode["required"] != false {
t.Fatalf("mode required = %v, want false", mode["required"])
}
}
func TestRenderHelperSchema_Group(t *testing.T) {
root := buildHelperTestTree()
payload, ok, err := renderHelperSchema(context.Background(), root, "dev app", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !ok {
t.Fatal("expected claim")
}
if payload["path"] != "dev app" {
t.Fatalf("path = %v", payload["path"])
}
cmds, _ := payload["commands"].([]map[string]any)
if len(cmds) != 2 { // create + robot
t.Fatalf("commands count = %d, want 2", len(cmds))
}
}
func TestRenderHelperSchema_NoAnnotation(t *testing.T) {
root := buildHelperTestTree()
payload, ok, err := renderHelperSchema(context.Background(), root, "dev connect", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !ok {
t.Fatal("expected claim")
}
if payload["error"] == nil {
t.Fatalf("expected a clear no-MCP-tool error, got %#v", payload)
}
if _, present := payload["parameters"]; present {
t.Fatal("no-tool command must not emit parameters")
}
}
func TestRenderHelperSchema_UnknownSubcommand(t *testing.T) {
root := buildHelperTestTree()
payload, ok, err := renderHelperSchema(context.Background(), root, "dev app nope", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !ok {
t.Fatal("expected claim")
}
if payload["error"] == nil {
t.Fatalf("expected error for unknown subcommand, got %#v", payload)
}
if avail, _ := payload["available"].([]map[string]any); len(avail) == 0 {
t.Fatal("expected available subcommands listed")
}
}
func TestRenderHelperSchema_ToolMissingInList(t *testing.T) {
root := buildHelperTestTree()
// Fetcher returns an empty list — the annotated tool isn't present.
payload, ok, err := renderHelperSchema(context.Background(), root, "dev app create", fakeFetcher(map[string]HelperToolSchema{}))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !ok {
t.Fatal("expected claim")
}
if payload["error"] == nil {
t.Fatalf("expected not-found error, got %#v", payload)
}
}
func TestRenderHelperSchema_FetchError(t *testing.T) {
root := buildHelperTestTree()
failing := func(context.Context, string) (map[string]HelperToolSchema, error) {
return nil, errors.New("network down")
}
_, ok, err := renderHelperSchema(context.Background(), root, "dev app create", failing)
if !ok {
t.Fatal("expected claim even on fetch error")
}
if err == nil {
t.Fatal("expected the fetch error to surface")
}
}
func TestRenderHelperSchema_NonHelperPathDeclined(t *testing.T) {
root := buildHelperTestTree()
if _, ok, _ := renderHelperSchema(context.Background(), root, "ding.message.send", nil); ok {
t.Fatal("non-helper path must not be claimed by the helper renderer")
}
}
func TestKebabCase(t *testing.T) {
cases := map[string]string{
"eventCallbackUrl": "event-callback-url",
"unifiedAppId": "unified-app-id",
"disableSSLVerify": "disable-ssl-verify",
"mode": "mode",
"skills": "skills",
"i18nName": "i18n-name",
}
for in, want := range cases {
if got := kebabCase(in); got != want {
t.Errorf("kebabCase(%q) = %q, want %q", in, got, want)
}
}
}
+2 -2
View File
@@ -90,7 +90,7 @@ func degradedHint(reason CatalogDegradedReason, serverCount int) string {
if embedded {
return "无法连接 MCP 市场,请检查网络"
}
return "无法连接 MCP 市场 (mcp.dingtalk.com),请检查网络"
return "无法连接 MCP 市场,请检查网络"
case DegradedRuntimeAllFailed:
if embedded {
return fmt.Sprintf("已发现 %d 个服务但连接全部失败,请稍后重试", serverCount)
@@ -279,7 +279,7 @@ func (l EnvironmentLoader) Load(ctx context.Context) (ir.Catalog, error) {
// accepted subset. See plan fix-wukong-discovery-missing-servers Phase 4.3.
logDiscoveryWarnings(response.Metadata.Warnings)
servers := market.NormalizeServers(response, "live_market")
servers := market.NormalizeServersForBaseURL(response, "live_market", baseURL)
_ = store.SaveRegistry(partition, cache.RegistrySnapshot{Servers: servers})
changedKeys := cache.ChangedServerKeysByUpdatedAt(cached.Registry.Servers, servers)
+192
View File
@@ -0,0 +1,192 @@
// 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 compat
import (
"encoding/json"
"strings"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// attendanceScheduleInnerRequired are the fields every scheduleVOS item must
// carry; the backend rejects partial items with an opaque error, so the CLI
// validates them up front (mirrors wukong's attendance.go).
var attendanceScheduleInnerRequired = []string{"userId", "workDate", "classId", "isRest"}
var attendanceGroupTypes = map[string]bool{"FIXED": true, "TURN": true, "NONE": true}
var attendanceApproveTypes = map[string]bool{
"overtime": true, "trip": true, "travel": true, "business_trip": true,
"business-trip": true, "out": true, "leave": true, "patch": true,
"repair_check": true, "repair-check": true,
}
// installAttendanceHook wires attendance-specific PreRunE validators that
// mirror wukong's client-side checks (inner-JSON required fields, group type,
// FIXED conditional requirements, group-update no-op). No-op for other
// products / tools. Preserves any PreRunE NewDirectCommand already installed.
func installAttendanceHook(cmd *cobra.Command, canonicalProduct, toolName string) {
if cmd == nil || strings.TrimSpace(canonicalProduct) != "attendance" {
return
}
var validate func(*cobra.Command) error
switch toolName {
case "generateTurnSchedule":
validate = validateAttendanceScheduleImport
case "create_class_setting":
validate = validateAttendanceClassCreate
case "create_group_setting":
validate = validateAttendanceGroupCreate
case "update_group_setting":
validate = validateAttendanceGroupUpdate
case "update_group_member":
validate = validateAttendanceUpdateMembers
case "save_self_setting":
validate = validateAttendanceSelfSettingSave
case "query_at_approve_template":
validate = validateAttendanceApproveTemplates
default:
return
}
original := cmd.PreRunE
cmd.PreRunE = func(c *cobra.Command, args []string) error {
if original != nil {
if err := original(c, args); err != nil {
return err
}
}
return validate(c)
}
}
func attFlagString(cmd *cobra.Command, names ...string) string {
for _, n := range names {
if cmd.Flags().Lookup(n) == nil {
continue
}
if v, err := cmd.Flags().GetString(n); err == nil && strings.TrimSpace(v) != "" {
return v
}
}
return ""
}
func validateAttendanceScheduleImport(cmd *cobra.Command) error {
raw := attFlagString(cmd, "scheduleVOS", "schedules")
if raw == "" {
return nil // empty is owned by the required-flag check
}
var items []map[string]any
if err := json.Unmarshal([]byte(raw), &items); err != nil {
return nil // malformed JSON is owned by a separate check
}
if len(items) == 0 {
return apperrors.NewValidation("--scheduleVOS requires at least one schedule entry (empty array not allowed)")
}
for _, item := range items {
for _, f := range attendanceScheduleInnerRequired {
if _, ok := item[f]; !ok {
return apperrors.NewValidation("missing required field: " + f + "(--scheduleVOS 每个排班项必填)")
}
}
}
return nil
}
func validateAttendanceClassCreate(cmd *cobra.Command) error {
raw := attFlagString(cmd, "class-vo", "TopAtClassVO")
if raw == "" {
return nil
}
var vo map[string]any
if err := json.Unmarshal([]byte(raw), &vo); err != nil {
return nil
}
if _, ok := vo["sections"]; !ok {
return apperrors.NewValidation("missing required field: sections(班次时段,--class-vo 内必填)")
}
return nil
}
func validateAttendanceGroupCreate(cmd *cobra.Command) error {
typ := strings.TrimSpace(attFlagString(cmd, "type"))
if typ != "" && !attendanceGroupTypes[typ] {
return apperrors.NewValidation("考勤组类型不合法:--type 应为 FIXED / TURN / NONE 之一")
}
if typ == "FIXED" {
var vo map[string]any
if raw := attFlagString(cmd, "group-vo", "groupVO"); raw != "" {
_ = json.Unmarshal([]byte(raw), &vo)
}
if vo == nil {
vo = map[string]any{}
}
if _, ok := vo["workDayClassList"]; !ok {
return apperrors.NewValidation("type=FIXED 时 --group-vo 内必填 workDayClassList(工作日班次列表)")
}
if _, ok := vo["defaultClassId"]; !ok {
return apperrors.NewValidation("type=FIXED 时 --group-vo 内必填 defaultClassId(默认班次 ID)")
}
}
return nil
}
func validateAttendanceGroupUpdate(cmd *cobra.Command) error {
if v := strings.TrimSpace(attFlagString(cmd, "enable-outside-check")); v != "" && v != "true" && v != "false" {
return apperrors.NewValidation("--enable-outside-check must be true or false")
}
for _, f := range []string{"name", "type", "owner", "enable-outside-check", "classIds", "group-vo"} {
if fl := cmd.Flags().Lookup(f); fl != nil && cmd.Flags().Changed(f) {
return nil
}
}
return apperrors.NewValidation("至少需要指定一个修改项(--name / --type / --owner / --enable-outside-check / --classIds / --group-vo)")
}
func validateAttendanceUpdateMembers(cmd *cobra.Command) error {
for _, f := range []string{"add-users", "remove-users", "add-extra-users", "remove-extra-users", "add-depts", "remove-depts"} {
if fl := cmd.Flags().Lookup(f); fl != nil && cmd.Flags().Changed(f) {
return nil
}
}
return apperrors.NewValidation("至少需要指定一个变更项(--add-users / --remove-users / --add-extra-users / --remove-extra-users / --add-depts / --remove-depts)")
}
func validateAttendanceSelfSettingSave(cmd *cobra.Command) error {
hasField := false
cmd.Flags().Visit(func(f *pflag.Flag) {
switch f.Name {
case "setting-scene", "user", "yes", "format", "debug", "verbose", "dry-run",
"client-id", "client-secret", "fields", "jq", "mock", "timeout":
// control / identity flags, not setting fields
default:
hasField = true
}
})
if !hasField {
return apperrors.NewValidation("至少需要指定一个设置项(--setting-scene / --user 之外的任一字段)")
}
return nil
}
func validateAttendanceApproveTemplates(cmd *cobra.Command) error {
typ := strings.TrimSpace(attFlagString(cmd, "type"))
if typ != "" && !attendanceApproveTypes[typ] {
return apperrors.NewValidation("无效的审批类型:--type 应为 overtime / leave / patch / trip(travel) / business_trip 之一")
}
return nil
}
+123
View File
@@ -0,0 +1,123 @@
// 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 compat
import (
"strings"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/spf13/cobra"
)
// calendarRecurrenceTools are the calendar leaves whose recurrence fields must
// be supplied as a complete set (the MCP backend does not merge partial
// recurrence, so a partial update would silently overwrite the rule). Mirrors
// wukong's calendar.go event create/update validation.
var calendarRecurrenceTools = map[string]bool{
"create_calendar_event": true,
"update_calendar_event": true,
}
// calendarRecurrenceFlags is the full set of --recurrence-* flags; touching any
// of them requires the core structural fields to be present.
var calendarRecurrenceFlags = []string{
"recurrence-type", "recurrence-interval", "recurrence-range-type",
"recurrence-count", "recurrence-end-date", "recurrence-days-of-week",
"recurrence-day-of-month", "recurrence-month", "recurrence-week-index",
"recurrence-first-day-of-week",
}
// installCalendarHook wires calendar-specific PreRunE validators onto leaf
// commands emitted by BuildDynamicCommands. No-op for non-calendar products and
// calendar tools without extra client-side checks. The hook chain preserves the
// PreRunE that NewDirectCommand already installed by invoking it first.
func installCalendarHook(cmd *cobra.Command, canonicalProduct, toolName string) {
if cmd == nil || strings.TrimSpace(canonicalProduct) != "calendar" {
return
}
if !calendarRecurrenceTools[toolName] {
return
}
original := cmd.PreRunE
cmd.PreRunE = func(c *cobra.Command, args []string) error {
if original != nil {
if err := original(c, args); err != nil {
return err
}
}
return validateCalendarRecurrence(c)
}
}
// validateCalendarRecurrence refuses a partial recurrence structure. If any
// --recurrence-* flag is set, recurrence-type / interval / range-type must be
// present, and weekly / relativeMonthly patterns require days-of-week. Error
// wording carries the kebab flag names so the messages match wukong and the
// auto-test substring assertions (days-of-week / recurrence-type).
func validateCalendarRecurrence(cmd *cobra.Command) error {
if cmd == nil {
return nil
}
used := false
for _, f := range calendarRecurrenceFlags {
if fl := cmd.Flags().Lookup(f); fl != nil && cmd.Flags().Changed(f) {
used = true
break
}
}
if !used {
return nil
}
recType := strings.TrimSpace(calendarFlagString(cmd, "recurrence-type"))
if recType == "" {
return apperrors.NewValidation(
"recurrence 结构不完整:使用任一 --recurrence-* 时必须整体重传完整循环字段" +
"(至少 --recurrence-type / --recurrence-interval / --recurrence-range-type," +
"MCP 不合并部分字段)")
}
if !calendarFlagSet(cmd, "recurrence-interval") {
return apperrors.NewValidation(
"recurrence 结构不完整:缺少 --recurrence-interval(循环间隔,recurrence 整体必填)")
}
if !calendarFlagSet(cmd, "recurrence-range-type") {
return apperrors.NewValidation(
"recurrence 结构不完整:缺少 --recurrence-range-type(循环范围类型,recurrence 整体必填)")
}
if recType == "weekly" || recType == "relativeMonthly" {
if strings.TrimSpace(calendarFlagString(cmd, "recurrence-days-of-week")) == "" {
return apperrors.NewValidation(
"weekly / relativeMonthly 循环必须提供 --recurrence-days-of-week (daysOfWeek)")
}
}
return nil
}
func calendarFlagString(cmd *cobra.Command, name string) string {
if cmd.Flags().Lookup(name) == nil {
return ""
}
v, _ := cmd.Flags().GetString(name)
return v
}
// calendarFlagSet reports whether a flag was explicitly provided by the user,
// tolerating both string and int (--recurrence-interval) flag kinds.
func calendarFlagSet(cmd *cobra.Command, name string) bool {
fl := cmd.Flags().Lookup(name)
if fl == nil {
return false
}
return cmd.Flags().Changed(name)
}
+9
View File
@@ -239,6 +239,15 @@ func BuildDynamicCommands(servers []market.ServerDescriptor, runner executor.Run
// todo_hooks.go for the full rationale). No-op for non-todo.
installTodoHook(cmd, canonicalProduct, toolName)
// §calendar-hook: reject partial recurrence on event create/update
// (see calendar_hooks.go). No-op for non-calendar.
installCalendarHook(cmd, canonicalProduct, toolName)
// §attendance-hook: inner-JSON required fields, group type and
// FIXED conditional checks (see attendance_hooks.go). No-op for
// non-attendance.
installAttendanceHook(cmd, canonicalProduct, toolName)
// §1.4: Add to the right parent group
attachToGroup(rootCmd, override.Group, groupCmds, cmd)
}
+1 -1
View File
@@ -185,7 +185,7 @@ func executePipelineCall(
return nil, err
}
actual := getDotPath(resp, step.PollUntilField)
if actual != nil && fmt.Sprint(actual) == step.PollUntilValue {
if actual != nil && strings.EqualFold(fmt.Sprint(actual), step.PollUntilValue) {
return resp, nil
}
if time.Now().After(deadline) {
+11 -2
View File
@@ -336,7 +336,16 @@ func NewDirectCommand(route Route, runner executor.Runner) *cobra.Command {
Response: resp,
}
if route.OutputTransform != nil && result.Response != nil {
result.Response = route.OutputTransform(result.Response)
// Shape the MCP content payload (the actual data), not the
// {endpoint, content} runtime envelope, so rename/drop/table
// paths resolve against response fields (e.g. result.items)
// rather than the wrapper. Falls back to the whole Response
// when no content map is present (degraded/echo paths).
if content, ok := result.Response["content"].(map[string]any); ok {
result.Response["content"] = route.OutputTransform(content)
} else {
result.Response = route.OutputTransform(result.Response)
}
}
return output.WriteCommandPayload(cmd, result, output.FormatJSON)
}
@@ -862,7 +871,7 @@ func CollectBindings(cmd *cobra.Command, bindings []FlagBinding, existing map[st
if _, ok := existing[binding.Property]; ok {
continue
}
return nil, apperrors.NewValidation(fmt.Sprintf("--%s is required", primaryName))
return nil, apperrors.NewValidation(fmt.Sprintf("missing required flag: --%s is required", primaryName))
}
if !anyChanged {
continue
+76 -1
View File
@@ -30,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, file_read, invert_bool, string_to_int64.
// json_parse_strict, enum_map, file_read, invert_bool, parse_bool, string_to_int64.
func ApplyTransform(value any, transform string, args map[string]any) (any, error) {
switch strings.TrimSpace(transform) {
case "":
@@ -49,6 +49,10 @@ func ApplyTransform(value any, transform string, args map[string]any) (any, erro
return transformFileRead(value)
case "invert_bool":
return transformInvertBool(value)
case "parse_bool":
return transformParseBool(value)
case "attendance_class_check_time":
return transformAttendanceClassCheckTime(value)
case "string_to_int64":
return transformStringToInt64(value)
default:
@@ -79,6 +83,77 @@ func transformInvertBool(value any) (any, error) {
}
}
// transformParseBool coerces a CLI string flag into a real JSON boolean so the
// MCP body carries `false`/`true` (not the string "false"/"true" or a swallowed
// zero value). Used by envelope flags that are semantically boolean but must be
// declared as string flags to accept an explicit `false` on the command line
// (cobra bool flags drop the space-form value). Unknown tokens pass through
// unchanged so upstream validators own the error wording.
func transformParseBool(value any) (any, error) {
switch v := value.(type) {
case bool:
return v, nil
case string:
switch strings.ToLower(strings.TrimSpace(v)) {
case "true", "1", "yes", "on":
return true, nil
case "false", "0", "no", "off":
return false, nil
}
return value, nil
default:
return value, nil
}
}
// transformAttendanceClassCheckTime parses a class-VO JSON string and converts
// every "HH:mm" checkTime under sections[*].times[*] and
// setting.topRestTimeList[*] into a Unix-millis number (1970-01-01 HH:mm in
// UTC+8), mirroring wukong's convertClassCheckTime. The MCP backend expects the
// numeric form; the envelope cannot express this nested walk, so it lives here.
func transformAttendanceClassCheckTime(value any) (any, error) {
parsed, err := transformJSONParseStrict(value)
if err != nil {
return nil, err
}
classVO, ok := parsed.(map[string]any)
if !ok {
return parsed, nil
}
cst := time.FixedZone("CST", 8*3600)
convertOne := func(obj map[string]any) {
if ct, ok := obj["checkTime"].(string); ok {
ct = strings.TrimSpace(ct)
if t, err := time.ParseInLocation("2006-01-02 15:04", "1970-01-01 "+ct, cst); err == nil {
obj["checkTime"] = float64(t.UnixMilli())
}
}
}
if sections, ok := classVO["sections"].([]any); ok {
for _, sec := range sections {
if secMap, ok := sec.(map[string]any); ok {
if times, ok := secMap["times"].([]any); ok {
for _, t := range times {
if tMap, ok := t.(map[string]any); ok {
convertOne(tMap)
}
}
}
}
}
}
if setting, ok := classVO["setting"].(map[string]any); ok {
if restList, ok := setting["topRestTimeList"].([]any); ok {
for _, item := range restList {
if itemMap, ok := item.(map[string]any); ok {
convertOne(itemMap)
}
}
}
}
return classVO, nil
}
func transformISO8601ToMillis(value any) (any, error) {
s, ok := toString(value)
if !ok {
+1 -1
View File
@@ -94,7 +94,7 @@ func (s *Service) DiscoverServers(ctx context.Context) ([]market.ServerDescripto
response, err := s.MarketClient.FetchServers(ctx, 200)
if err == nil {
servers := market.NormalizeServers(response, "live_market")
servers := market.NormalizeServersForBaseURL(response, "live_market", s.MarketClient.BaseURL)
_ = s.Cache.SaveRegistry(partition, cache.RegistrySnapshot{Servers: servers})
return servers, nil
}
+2 -2
View File
@@ -13,13 +13,13 @@ import (
)
// newTestMCPServer returns an httptest.Server that handles both market registry
// and MCP JSON-RPC endpoints. marketOK controls whether /cli/discovery/apis/bamboo
// and MCP JSON-RPC endpoints. marketOK controls whether /cli/discovery/apis/cedar
// succeeds, and mcpOK controls whether initialize+tools/list succeed.
func newTestMCPServer(t *testing.T, marketOK, mcpOK bool) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/cli/discovery/apis/bamboo", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/cli/discovery/apis/cedar", func(w http.ResponseWriter, r *http.Request) {
if !marketOK {
http.Error(w, "market unavailable", http.StatusInternalServerError)
return
+21 -19
View File
@@ -21,6 +21,8 @@ import (
"io"
"strings"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/jsonutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/tui"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
)
@@ -309,7 +311,7 @@ func PrintJSON(w io.Writer, err error) error {
}
payload := map[string]any{"error": errorPayload}
data, marshalErr := json.MarshalIndent(payload, "", " ")
data, marshalErr := jsonutil.MarshalIndent(payload, "", " ")
if marshalErr != nil {
_, writeErr := fmt.Fprintf(w, "{\"error\":{\"code\":5,\"category\":\"internal\",\"message\":\"failed to encode error output\"}}\n")
return writeErr
@@ -344,25 +346,25 @@ func PrintHumanAt(w io.Writer, err error, v Verbosity) error {
var typed *Error
if !stderrors.As(err, &typed) {
_, writeErr := fmt.Fprintf(w, "Error: %s\n", err.Error())
_, writeErr := fmt.Fprintf(w, "%s %s\n", tui.StateMark("error"), tui.Danger("Error: "+err.Error()))
return writeErr
}
// Line 1: Error summary
lines := []string{
fmt.Sprintf("Error: [%s] %s", strings.ToUpper(string(typed.Category)), typed.Message),
fmt.Sprintf("%s %s", tui.StateMark("error"), tui.Danger(fmt.Sprintf("Error: [%s] %s", strings.ToUpper(string(typed.Category)), typed.Message))),
}
// Always shown: hint, actions, retryable
if typed.Hint != "" {
lines = append(lines, fmt.Sprintf("Hint: %s", typed.Hint))
lines = append(lines, tui.Cyan(fmt.Sprintf("Hint: %s", typed.Hint)))
}
// Add user-friendly hint for specific server error codes
switch typed.ServerDiag.ServerErrorCode {
case "TOKEN_VERIFIED_FAILED", "CLI_ORG_NOT_AUTHORIZED":
lines = append(lines, "Hint: 该组织尚未开启 CLI 数据访问权限,请联系组织主管理员开启。")
lines = append(lines, "Action: 开启地址: "+config.GetDeveloperSettingsURL())
lines = append(lines, tui.Cyan("Hint: 该组织尚未开启 CLI 数据访问权限,请联系组织主管理员开启。"))
lines = append(lines, tui.White("Action: 开启地址: "+config.GetDeveloperSettingsURL()))
}
if len(typed.Actions) > 0 {
@@ -370,53 +372,53 @@ func PrintHumanAt(w io.Writer, err error, v Verbosity) error {
if strings.TrimSpace(action) == "" {
continue
}
lines = append(lines, fmt.Sprintf("Action: %s", action))
lines = append(lines, tui.White(fmt.Sprintf("Action: %s", action)))
}
}
if line := formatAvailableFlagsHumanLine(typed.AvailableFlags); line != "" {
lines = append(lines, line)
lines = append(lines, tui.Dim(line))
}
if typed.Retryable {
lines = append(lines, "Retryable: true")
lines = append(lines, tui.Warning("Retryable: true"))
}
// Always shown when present: Trace ID, Server Code
if typed.ServerDiag.TraceID != "" {
lines = append(lines, fmt.Sprintf("Trace ID: %s", typed.ServerDiag.TraceID))
lines = append(lines, tui.Dim(fmt.Sprintf("Trace ID: %s", typed.ServerDiag.TraceID)))
}
if typed.ServerDiag.ServerErrorCode != "" {
lines = append(lines, fmt.Sprintf("Server Code: %s", typed.ServerDiag.ServerErrorCode))
lines = append(lines, tui.Dim(fmt.Sprintf("Server Code: %s", typed.ServerDiag.ServerErrorCode)))
}
// Verbose+: technical detail, snapshot, reason, server key
if v >= VerbosityVerbose {
if typed.ServerDiag.TechnicalDetail != "" {
lines = append(lines, fmt.Sprintf("Detail: %s", typed.ServerDiag.TechnicalDetail))
lines = append(lines, tui.Dim(fmt.Sprintf("Detail: %s", typed.ServerDiag.TechnicalDetail)))
}
if typed.Reason != "" {
lines = append(lines, fmt.Sprintf("Reason: %s", typed.Reason))
lines = append(lines, tui.Dim(fmt.Sprintf("Reason: %s", typed.Reason)))
}
if typed.ServerKey != "" {
lines = append(lines, fmt.Sprintf("Server: %s", typed.ServerKey))
lines = append(lines, tui.Dim(fmt.Sprintf("Server: %s", typed.ServerKey)))
}
if typed.Snapshot != "" {
lines = append(lines, fmt.Sprintf("Snapshot: %s", typed.Snapshot))
lines = append(lines, tui.Dim(fmt.Sprintf("Snapshot: %s", typed.Snapshot)))
}
if typed.Cause != nil {
lines = append(lines, fmt.Sprintf("Cause: %s", typed.Cause.Error()))
lines = append(lines, tui.Dim(fmt.Sprintf("Cause: %s", typed.Cause.Error())))
}
}
// Debug: all internal diagnostics
if v >= VerbosityDebug {
if typed.Operation != "" {
lines = append(lines, fmt.Sprintf("Operation: %s", typed.Operation))
lines = append(lines, tui.Dim(fmt.Sprintf("Operation: %s", typed.Operation)))
}
if typed.RPCCode != 0 {
lines = append(lines, fmt.Sprintf("RPC Code: %d", typed.RPCCode))
lines = append(lines, tui.Dim(fmt.Sprintf("RPC Code: %d", typed.RPCCode)))
}
if len(typed.RPCData) > 0 {
lines = append(lines, fmt.Sprintf("RPC Data: %s", string(typed.RPCData)))
lines = append(lines, tui.Dim(fmt.Sprintf("RPC Data: %s", string(typed.RPCData))))
}
}
+26 -12
View File
@@ -21,6 +21,8 @@ import (
"net/url"
"strings"
"sync"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/jsonutil"
)
// hostControlProvider returns the host-owned clawType for the current
@@ -105,12 +107,10 @@ const ExitCodePermission = 4
// json.Unmarshal-able payload of the form
// {"success":false,"code":<frozen enum>,"data":{...}}.
//
// When the payload includes data.uri, that URL is the authoritative
// server-provided authorization link. Hosts must treat it as opaque and open
// it verbatim instead of parsing and reconstructing it locally, because
// required parameters may live in query, encoded hash, or fragment sections.
// New hosts may prefer data.authorizationUrl when present; it preserves data.uri
// while adding a copy/open-safe URL for legacy DingTalk hash-route variants.
// When the payload includes data.uri/authUrl/authorizationUrl, that value is
// the authoritative server-provided authorization link. The CLI accepts all
// legacy aliases, normalizes the known DingTalk hash-route variant, and emits a
// single data.uri field so terminals and hosts do not need to deduplicate links.
type PATError struct {
RawJSON string
}
@@ -147,6 +147,7 @@ var patNoPermissionCodes = map[string]bool{
// `dws auth login --scope <data.missingScope>`.
var patAuthRequiredCodes = map[string]bool{
"AGENT_CODE_NOT_EXISTS": true,
"PAT_BATCH_AUTH_PENDING": true,
"PAT_SCOPE_AUTH_REQUIRED": true,
}
@@ -241,7 +242,7 @@ func isBusinessError(body map[string]any) bool {
// Check order: DWS gateway auth > PAT permission.
func ClassifyToolResultContent(content map[string]any) error {
if _, ok := getDWSGatewayErrorCode(content); ok {
raw, _ := json.Marshal(content)
raw, _ := jsonutil.Marshal(content)
return NewAuth(string(raw),
WithReason("gateway_auth_expired"),
WithHint(authExpiredHint()),
@@ -353,8 +354,11 @@ func ApplyHostMutations(out map[string]any) {
data = map[string]any{}
out["data"] = data
}
if rawURI, ok := data["uri"].(string); ok && strings.TrimSpace(rawURI) != "" {
data["authorizationUrl"] = PATAuthorizationURL(rawURI)
if rawURI := patAuthorizationURIFromData(data); rawURI != "" {
authURL := PATAuthorizationURL(rawURI)
data["uri"] = authURL
delete(data, "authUrl")
delete(data, "authorizationUrl")
}
if block := HostControlBlock(); block != nil {
delete(data, "callbacks")
@@ -363,6 +367,16 @@ func ApplyHostMutations(out map[string]any) {
data["openBrowser"] = PATOpenBrowserValue()
}
func patAuthorizationURIFromData(data map[string]any) string {
for _, key := range []string{"uri", "authUrl", "authorizationUrl"} {
value, _ := data[key].(string)
if strings.TrimSpace(value) != "" {
return strings.TrimSpace(value)
}
}
return ""
}
// PATAuthorizationURL returns the best URL for hosts to open or show to users.
// It keeps already-complete PAT URLs unchanged. For DingTalk's legacy
// /fe/old#%2FpersonalAuthorization?... hash-route form, it adds the explicit
@@ -443,9 +457,9 @@ func cleanPATJSON(body map[string]any, code string) string {
"code": code,
}
if data, ok := body["data"]; ok {
// Keep data.uri exactly as returned by the service. Host consumers open
// that link directly, so local normalization would risk dropping
// parameters embedded in query/hash/fragment sections.
// ApplyHostMutations canonicalizes PAT URL aliases into one data.uri
// before JSON encoding, while stripClassFields keeps the rest of the
// service payload intact.
out["data"] = stripClassFields(data)
} else {
fallback := map[string]any{}
+73 -7
View File
@@ -378,6 +378,25 @@ func TestClassifyMCPResponseText_PATAuthRequired(t *testing.T) {
}
}
func TestClassifyMCPResponseText_PATBatchAuthPending(t *testing.T) {
t.Parallel()
text := `{"success":false,"code":"PAT_BATCH_AUTH_PENDING","data":{"flowId":"flow-1","uri":"https://example.test/auth"}}`
err := ClassifyMCPResponseText(text)
if err == nil {
t.Fatal("expected non-nil error")
}
var patErr *PATError
if !stderrors.As(err, &patErr) {
t.Fatalf("expected *PATError, got %T", err)
}
if !strings.Contains(patErr.RawJSON, "PAT_BATCH_AUTH_PENDING") {
t.Errorf("RawJSON should contain PAT_BATCH_AUTH_PENDING, got: %s", patErr.RawJSON)
}
if !strings.Contains(patErr.RawJSON, "flow-1") {
t.Errorf("RawJSON should preserve flowId, got: %s", patErr.RawJSON)
}
}
func TestClassifyMCPResponseText_BusinessError(t *testing.T) {
t.Parallel()
text := `{"success":false,"errorMsg":"搜索内容不能为空"}`
@@ -729,6 +748,12 @@ func TestCleanPATJSON_PreservesOpaqueURIVerbatim(t *testing.T) {
}
result := cleanPATJSON(body, "PAT_MEDIUM_RISK_NO_PERMISSION")
if strings.Contains(result, `\u0026`) {
t.Fatalf("cleanPATJSON escaped ampersands in URL: %s", result)
}
if !strings.Contains(result, "&userCode=Q8RY-X6E9") {
t.Fatalf("cleanPATJSON output missing literal ampersand route separator: %s", result)
}
if strings.Contains(result, `\u0026`) {
t.Fatalf("cleanPATJSON should keep URL ampersands readable for mobile copy/linkify, got: %s", result)
@@ -745,8 +770,40 @@ func TestCleanPATJSON_PreservesOpaqueURIVerbatim(t *testing.T) {
if got, _ := data["uri"].(string); got != rawURI {
t.Fatalf("data.uri = %q, want verbatim %q", got, rawURI)
}
if got, _ := data["authorizationUrl"].(string); got != rawURI {
t.Fatalf("data.authorizationUrl = %q, want %q", got, rawURI)
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted when data.uri is present")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted when data.uri is present")
}
}
func TestCleanPATJSON_BackfillsSingleURIFromAuthURL(t *testing.T) {
t.Parallel()
rawURI := "https://open-dev.dingtalk.com/fe/old?hash=%23%2FpersonalAuthorization%3FflowId%3D50dff7654b7444e88ced7489b07cce8d%26userCode%3DQ8RY-X6E9#/personalAuthorization?flowId=50dff7654b7444e88ced7489b07cce8d&userCode=Q8RY-X6E9"
body := map[string]any{
"success": false,
"code": "PAT_BATCH_AUTH_PENDING",
"data": map[string]any{
"flowId": "50dff7654b7444e88ced7489b07cce8d",
"authUrl": rawURI,
},
}
result := cleanPATJSON(body, "PAT_BATCH_AUTH_PENDING")
var parsed map[string]any
if err := json.Unmarshal([]byte(result), &parsed); err != nil {
t.Fatalf("unmarshal cleanPATJSON output: %v\nraw=%s", err, result)
}
data, _ := parsed["data"].(map[string]any)
if got, _ := data["uri"].(string); got != rawURI {
t.Fatalf("data.uri = %q, want %q", got, rawURI)
}
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted after backfilling data.uri")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted after backfilling data.uri")
}
}
@@ -802,7 +859,7 @@ func TestPATAuthorizationURL_NormalizesLegacyHashRoutePreservesExtraQuery(t *tes
}
}
func TestCleanPATJSON_AddsNormalizedAuthorizationURL(t *testing.T) {
func TestCleanPATJSON_NormalizesSingleURI(t *testing.T) {
t.Parallel()
rawURI := "https://open-dev.dingtalk.com/fe/old#%2FpersonalAuthorization%3FflowId%3D56b12fd3201d4efab9a9138672cf4deb%26userCode%3DCFTC-27ZN"
want := "https://open-dev.dingtalk.com/fe/old?hash=%23%2FpersonalAuthorization%3FflowId%3D56b12fd3201d4efab9a9138672cf4deb%26userCode%3DCFTC-27ZN#/personalAuthorization?flowId=56b12fd3201d4efab9a9138672cf4deb&userCode=CFTC-27ZN"
@@ -817,17 +874,26 @@ func TestCleanPATJSON_AddsNormalizedAuthorizationURL(t *testing.T) {
}
result := cleanPATJSON(body, "PAT_MEDIUM_RISK_NO_PERMISSION")
if strings.Contains(result, `\u0026`) {
t.Fatalf("cleanPATJSON escaped ampersands in normalized URL: %s", result)
}
if !strings.Contains(result, "&userCode=CFTC-27ZN") {
t.Fatalf("cleanPATJSON output missing literal ampersand route separator: %s", result)
}
var parsed map[string]any
if err := json.Unmarshal([]byte(result), &parsed); err != nil {
t.Fatalf("unmarshal cleanPATJSON output: %v\nraw=%s", err, result)
}
data, _ := parsed["data"].(map[string]any)
if got, _ := data["uri"].(string); got != rawURI {
t.Fatalf("data.uri = %q, want verbatim %q", got, rawURI)
if got, _ := data["uri"].(string); got != want {
t.Fatalf("data.uri = %q, want normalized %q", got, want)
}
if got, _ := data["authorizationUrl"].(string); got != want {
t.Fatalf("data.authorizationUrl = %q, want %q", got, want)
if _, ok := data["authUrl"]; ok {
t.Fatalf("data.authUrl should be omitted after normalizing data.uri")
}
if _, ok := data["authorizationUrl"]; ok {
t.Fatalf("data.authorizationUrl should be omitted after normalizing data.uri")
}
}
+1 -1
View File
@@ -259,7 +259,7 @@ func newDocsMCPGateway(expectations []docsServerExpectation) *httptest.Server {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
mux.HandleFunc("/cli/discovery/apis/bamboo", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/cli/discovery/apis/cedar", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
+49 -3
View File
@@ -110,6 +110,7 @@ func (aitableHandler) Command(runner executor.Runner) *cobra.Command {
newAitableFieldCreateCommand(runner),
newAitableFieldUpdateCommand(runner),
newAitableFieldDeleteCommand(runner),
newAitableFieldSearchOptionsCommand(runner),
newAitableFieldListAlias(runner),
)
@@ -129,7 +130,13 @@ func (aitableHandler) Command(runner executor.Runner) *cobra.Command {
newAitableRecordCreateCommand(runner),
newAitableRecordUpdateCommand(runner),
newAitableRecordBatchUpdateCommand(runner),
newAitableRecordQueryEmptyCommand(runner),
newAitableRecordDeleteCommand(runner),
newAitableRecordHistoryListCommand(runner),
newAitableRecordShareURLCommand(runner),
newAitableRecordUpsertCommand(runner),
newAitableRecordPrimaryDocGetCommand(runner),
newAitableRecordPrimaryDocCreateCommand(runner),
newAitableRecordListAlias(runner),
)
@@ -251,6 +258,7 @@ func (aitableHandler) Command(runner executor.Runner) *cobra.Command {
newAitableDashboardUpdateCommand(runner),
newAitableDashboardDeleteCommand(runner),
newAitableDashboardConfigExampleCommand(runner),
newAitableDashboardArrangeCommand(runner),
dashboardShare,
)
@@ -264,15 +272,53 @@ func (aitableHandler) Command(runner executor.Runner) *cobra.Command {
return cmd.Help()
},
}
viewGet := newAitableViewGetCommand(runner)
viewGet.AddCommand(
newAitableViewGetCardCommand(runner),
newAitableViewGetTimebarCommand(runner),
newAitableViewGetAggregateCommand(runner),
newAitableViewGetFilterCommand(runner),
newAitableViewGetSortCommand(runner),
newAitableViewGetGroupCommand(runner),
newAitableViewGetVisibleFieldsCommand(runner),
newAitableViewGetFieldWidthsCommand(runner),
newAitableViewGetLockCommand(runner),
newAitableViewGetFrozenColsCommand(runner),
newAitableViewGetRowHeightCommand(runner),
newAitableViewGetFillColorRuleCommand(runner),
)
viewUpdate := newAitableViewUpdateCommand(runner)
viewUpdate.AddCommand(
newAitableViewUpdateCardCommand(runner),
newAitableViewUpdateTimebarCommand(runner),
newAitableViewUpdateAggregateCommand(runner),
newAitableViewUpdateFieldWidthsCommand(runner),
newAitableViewUpdateVisibleFieldsCommand(runner),
newAitableViewUpdateFilterCommand(runner),
newAitableViewUpdateSortCommand(runner),
newAitableViewUpdateGroupCommand(runner),
newAitableViewUpdateNameCommand(runner),
newAitableViewUpdateFrozenColsCommand(runner),
newAitableViewUpdateRowHeightCommand(runner),
newAitableViewUpdateFillColorRuleCommand(runner),
)
view.AddCommand(
newAitableViewGetCommand(runner),
viewGet,
newAitableViewListCommand(runner),
newAitableViewCreateCommand(runner),
newAitableViewUpdateCommand(runner),
viewUpdate,
newAitableViewDeleteCommand(runner),
newAitableViewLockCommand(runner),
newAitableViewDuplicateCommand(runner),
)
root.AddCommand(base, table, field, record, newAitableFormCommand(runner), template, attachment, export, importCmd, dashboard, chart, view)
root.AddCommand(
base, table, field, record, newAitableFormCommand(runner),
newAitableWorkflowCommand(runner),
template, attachment, export, importCmd, dashboard, chart, view,
newAitableAdvpermCommand(runner),
newAitableSectionCommand(runner),
)
// 顶层别名:dws aitable search/list/create/info → base search/list/create/get
// 每个 alias 复用现有 constructor,独立 cobra.Command 实例(避免与 base.* 共享 flag 指针)
+51 -10
View File
@@ -130,7 +130,33 @@ func newAitableBaseCreateCommand(runner executor.Runner) *cobra.Command {
if folderID := aitableStringFlag(cmd, "folder-id"); folderID != "" {
params["folderId"] = folderID
}
return runAitableTool(cmd, runner, "create_base", params)
// dry-run 或带模板:保持单步 create_base 语义。
if commandDryRun(cmd) {
return runAitableTool(cmd, runner, "create_base", params)
}
result, err := runAitableProductToolResult(cmd, runner, "aitable", "create_base", params)
if err != nil {
return err
}
// 默认表由服务端按 scenario 决定:wukong 场景建、openClaw 不建。
// 为与 wukong 行为对齐,无模板时在 CLI 侧兜底补建一张默认表,
// 使新 base 立即可用(含 tableId)。输出仍保持原 create_base 结果,
// 不把内部补建步骤暴露给调用方。
if _, hasTemplate := params["templateId"]; !hasTemplate {
if baseID := findStringDeep(result.Response, "baseId", "baseID"); baseID != "" {
if _, terr := runAitableProductToolResult(cmd, runner, "aitable", "create_table", map[string]any{
"baseId": baseID,
"tableName": "表格1",
"fields": []any{map[string]any{
"fieldName": "标题",
"type": "text",
}},
}); terr != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "warning: created base %s but default table creation failed: %v\n", baseID, terr)
}
}
}
return writeCommandPayload(cmd, result)
},
}
preferLegacyLeaf(cmd)
@@ -1440,6 +1466,9 @@ func newAitableViewUpdateCommand(runner executor.Runner) *cobra.Command {
if err != nil {
return err
}
if err := normalizeAitableViewConfigBlock(cmd, config); err != nil {
return err
}
params["config"] = config
}
if _, hasName := params["newViewName"]; !hasName {
@@ -1499,6 +1528,14 @@ func runAitableFormTool(cmd *cobra.Command, runner executor.Runner, tool string,
}
func runAitableProductTool(cmd *cobra.Command, runner executor.Runner, product, tool string, params map[string]any) error {
result, err := runAitableProductToolResult(cmd, runner, product, tool, params)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
}
func runAitableProductToolResult(cmd *cobra.Command, runner executor.Runner, product, tool string, params map[string]any) (executor.Result, error) {
invocation := executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd),
product,
@@ -1509,9 +1546,9 @@ func runAitableProductTool(cmd *cobra.Command, runner executor.Runner, product,
if invocation.DryRun {
result, err := runner.Run(cmd.Context(), invocation)
if err != nil {
return err
return executor.Result{}, err
}
return writeCommandPayload(cmd, result)
return result, nil
}
var lastErr error
@@ -1523,7 +1560,7 @@ func runAitableProductTool(cmd *cobra.Command, runner executor.Runner, product,
select {
case <-cmd.Context().Done():
timer.Stop()
return cmd.Context().Err()
return executor.Result{}, cmd.Context().Err()
case <-timer.C:
}
}
@@ -1531,16 +1568,16 @@ func runAitableProductTool(cmd *cobra.Command, runner executor.Runner, product,
result, err := runner.Run(cmd.Context(), invocation)
lastErr = err
if err == nil {
return writeCommandPayload(cmd, result)
return result, nil
}
if !aitableErrorRetryable(err) {
return err
return executor.Result{}, err
}
}
if lastErr != nil {
return lastErr
return executor.Result{}, lastErr
}
return nil
return executor.Result{}, nil
}
const aitableHelperMaxRetries = 3
@@ -1906,11 +1943,15 @@ func normalizeAitableSort(items []any) []any {
}
func parseAitableJSONArray(raw, flagName string) ([]any, error) {
var value []any
var value any
if err := json.Unmarshal([]byte(raw), &value); err != nil {
return nil, apperrors.NewValidation(fmt.Sprintf("--%s JSON parse failed: %v", flagName, err))
}
return value, nil
arr, ok := value.([]any)
if !ok {
return nil, apperrors.NewValidation(fmt.Sprintf("--%s must be a JSON array / 数组, got %T", flagName, value))
}
return arr, nil
}
func parseAitableJSONObject(raw, flagName string) (map[string]any, error) {
+52
View File
@@ -1393,3 +1393,55 @@ func singleAitableRecord(t *testing.T, value any) map[string]any {
}
return record
}
// base create 无模板时,CLI 兜底补建一张默认表(与 wukong 场景行为对齐:
// 服务端对 openClaw 不建默认表,CLI 侧补齐使新 base 立即含 tableId)。
func TestAitableBaseCreateAddsDefaultTableWithoutTemplate(t *testing.T) {
t.Parallel()
runner := &aitableSequencedRunner{responses: []map[string]any{
{"data": map[string]any{"baseId": "BASE_001"}},
{"data": map[string]any{"tableId": "TABLE_001"}},
}}
cmd := newAitableBaseCreateCommand(runner)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs([]string{"--name", "项目跟踪"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\nstderr:\n%s", err, errOut.String())
}
if len(runner.calls) != 2 {
t.Fatalf("calls = %d, want create_base + create_table", len(runner.calls))
}
if got := runner.calls[0].Tool; got != "create_base" {
t.Fatalf("first tool = %q, want create_base", got)
}
if got := runner.calls[1].Tool; got != "create_table" {
t.Fatalf("second tool = %q, want create_table", got)
}
if got := runner.calls[1].Params["baseId"]; got != "BASE_001" {
t.Fatalf("create_table baseId = %#v, want BASE_001", got)
}
}
// base create 带 --template-id 时不补建默认表(模板自带结构)。
func TestAitableBaseCreateWithTemplateSkipsDefaultTable(t *testing.T) {
t.Parallel()
runner := &aitableSequencedRunner{responses: []map[string]any{
{"data": map[string]any{"baseId": "BASE_001"}},
}}
cmd := newAitableBaseCreateCommand(runner)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs([]string{"--name", "项目跟踪", "--template-id", "TPL_001"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\nstderr:\n%s", err, errOut.String())
}
if len(runner.calls) != 1 {
t.Fatalf("calls = %d, want only create_base", len(runner.calls))
}
if got := runner.calls[0].Tool; got != "create_base" {
t.Fatalf("tool = %q, want create_base", got)
}
}
File diff suppressed because it is too large Load Diff
+420
View File
@@ -0,0 +1,420 @@
package helpers
import (
"bytes"
"context"
"encoding/json"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/spf13/cobra"
)
func executeAitableExtraCommand(t *testing.T, cmd *cobra.Command, args ...string) {
t.Helper()
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs(args)
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\nstderr:\n%s", err, errOut.String())
}
}
type aitableSequencedRunner struct {
calls []executor.Invocation
responses []map[string]any
}
func (r *aitableSequencedRunner) Run(_ context.Context, invocation executor.Invocation) (executor.Result, error) {
r.calls = append(r.calls, invocation)
var response map[string]any
if idx := len(r.calls) - 1; idx >= 0 && idx < len(r.responses) {
response = r.responses[idx]
}
return executor.Result{Invocation: invocation, Response: response}, nil
}
func TestAitableFieldSearchOptionsRoutesToAitable(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableFieldSearchOptionsCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--field-id", "FIELD_001",
"--keyword", "已",
"--limit", "10",
)
if got := runner.last.CanonicalProduct; got != "aitable" {
t.Fatalf("CanonicalProduct = %q, want aitable", got)
}
if got := runner.last.Tool; got != "search_field_options" {
t.Fatalf("Tool = %q, want search_field_options", got)
}
if got := runner.last.Params["keyword"]; got != "已" {
t.Fatalf("keyword = %#v, want 已", got)
}
if got := runner.last.Params["limit"]; got != 10 {
t.Fatalf("limit = %#v, want 10", got)
}
}
func TestAitableViewGetFieldWidthsProjectsCustomWidthMap(t *testing.T) {
t.Parallel()
runner := &aitableSequencedRunner{responses: []map[string]any{{
"content": map[string]any{
"status": "success",
"data": map[string]any{"views": []any{map[string]any{
"viewId": "VIEW_001",
"viewType": "Grid",
"custom": map[string]any{
"widthMap": map[string]any{"FIELD_001": 240},
},
}}},
},
}}}
cmd := newAitableViewGetFieldWidthsCommand(runner)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs([]string{
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--view-id", "VIEW_001",
})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\nstderr:\n%s", err, errOut.String())
}
var payload map[string]any
if err := json.Unmarshal(out.Bytes(), &payload); err != nil {
t.Fatalf("output JSON parse error = %v\nstdout:\n%s", err, out.String())
}
data, ok := payload["data"].(map[string]any)
if !ok {
t.Fatalf("data = %#v, want object", payload["data"])
}
if got := data["FIELD_001"]; got != float64(240) {
t.Fatalf("FIELD_001 width = %#v, want 240", got)
}
}
func TestAitableViewUpdateCardDispatchesGalleryConfig(t *testing.T) {
t.Parallel()
runner := &aitableSequencedRunner{responses: []map[string]any{
{"content": map[string]any{
"status": "success",
"data": map[string]any{"views": []any{map[string]any{
"viewId": "VIEW_001",
"viewType": "Gallery",
}}},
}},
{"content": map[string]any{"status": "success"}},
}}
cmd := newAitableViewUpdateCardCommand(runner)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs([]string{
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--view-id", "VIEW_001",
"--cover-mode", "custom",
"--cover-field-id", "FIELD_001",
})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\nstderr:\n%s", err, errOut.String())
}
if len(runner.calls) != 2 {
t.Fatalf("calls = %d, want 2", len(runner.calls))
}
update := runner.calls[1]
if update.Tool != "update_view" {
t.Fatalf("second tool = %q, want update_view", update.Tool)
}
config, ok := update.Params["config"].(map[string]any)
if !ok {
t.Fatalf("config = %#v, want object", update.Params["config"])
}
card, ok := config["galleryCard"].(map[string]any)
if !ok {
t.Fatalf("galleryCard = %#v, want object", config["galleryCard"])
}
if got := card["coverMode"]; got != "custom" {
t.Fatalf("coverMode = %#v, want custom", got)
}
}
func TestAitableViewUpdateConfigRoutedKeyHintsSubcommand(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableViewUpdateCommand(runner)
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs([]string{
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--view-id", "VIEW_001",
"--config", `{"frozenColCount":2}`,
})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\nstderr:\n%s", err, errOut.String())
}
if !strings.Contains(errOut.String(), "frozen-cols") {
t.Fatalf("stderr missing frozen-cols hint:\n%s", errOut.String())
}
}
func TestAitableRecordHistoryListRoutesToHelper(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableRecordHistoryListCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--record-id", "REC_001",
"--offset", "10",
"--limit", "30",
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "query_record_history" {
t.Fatalf("Tool = %q, want query_record_history", got)
}
if got := runner.last.Params["recordId"]; got != "REC_001" {
t.Fatalf("recordId = %#v, want REC_001", got)
}
if got := runner.last.Params["offset"]; got != 10 {
t.Fatalf("offset = %#v, want 10", got)
}
if got := runner.last.Params["limit"]; got != 30 {
t.Fatalf("limit = %#v, want 30", got)
}
}
func TestAitableRecordUpsertAcceptsFieldsAlias(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableRecordUpsertCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--fields", `[{"recordId":"REC_001","cells":{"fld":"updated"}},{"cells":{"fld":"new"}}]`,
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "record_upsert" {
t.Fatalf("Tool = %q, want record_upsert", got)
}
records, ok := runner.last.Params["records"].([]any)
if !ok {
t.Fatalf("records type = %T, want []any", runner.last.Params["records"])
}
if len(records) != 2 {
t.Fatalf("records len = %d, want 2", len(records))
}
}
func TestAitableViewExtraCommandsRouteToExpectedTools(t *testing.T) {
t.Parallel()
t.Run("lock unlock", func(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableViewLockCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--view-id", "VIEW_001",
"--off",
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "lock_or_unlock_view" {
t.Fatalf("Tool = %q, want lock_or_unlock_view", got)
}
if got := runner.last.Params["action"]; got != "unlock" {
t.Fatalf("action = %#v, want unlock", got)
}
})
t.Run("fill color rule", func(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableViewUpdateFillColorRuleCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--view-id", "VIEW_001",
"--json", `[]`,
)
if got := runner.last.CanonicalProduct; got != "aitable" {
t.Fatalf("CanonicalProduct = %q, want aitable", got)
}
if got := runner.last.Tool; got != "set_view_fill_color_rule" {
t.Fatalf("Tool = %q, want set_view_fill_color_rule", got)
}
if formats, ok := runner.last.Params["conditionalFormats"].([]any); !ok || len(formats) != 0 {
t.Fatalf("conditionalFormats = %#v, want empty []any", runner.last.Params["conditionalFormats"])
}
})
}
func TestAitableWorkflowListRoutesToHelper(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableWorkflowListCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--limit", "50",
"--offset", "100",
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "list_workflows" {
t.Fatalf("Tool = %q, want list_workflows", got)
}
if got := runner.last.Params["limit"]; got != 50 {
t.Fatalf("limit = %#v, want 50", got)
}
if got := runner.last.Params["offset"]; got != 100 {
t.Fatalf("offset = %#v, want 100", got)
}
}
func TestAitableRecordQueryEmptyRoutesToHelper(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableRecordQueryEmptyCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--limit", "50",
"--cursor", "CUR_001",
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "query_empty_records" {
t.Fatalf("Tool = %q, want query_empty_records", got)
}
if got := runner.last.Params["limit"]; got != 50 {
t.Fatalf("limit = %#v, want 50", got)
}
if got := runner.last.Params["cursor"]; got != "CUR_001" {
t.Fatalf("cursor = %#v, want CUR_001", got)
}
}
func TestAitableRecordQueryEmptyRejectsOutOfRangeLimit(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableRecordQueryEmptyCommand(runner)
cmd.SetArgs([]string{
"--base-id", "BASE_001",
"--table-id", "TABLE_001",
"--limit", "200",
})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
if err := cmd.Execute(); err == nil {
t.Fatal("expected error for --limit 200, got nil")
}
if runner.last.Tool != "" {
t.Fatalf("runner should not be called on invalid limit, got tool %q", runner.last.Tool)
}
}
func TestAitableDashboardArrangeRoutesToHelper(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableDashboardArrangeCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--dashboard-id", "DASH_001",
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "align_dashboard" {
t.Fatalf("Tool = %q, want align_dashboard", got)
}
if got := runner.last.Params["dashboardId"]; got != "DASH_001" {
t.Fatalf("dashboardId = %#v, want DASH_001", got)
}
}
func TestAitableAdvpermRoleCreateParsesSubRoles(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableAdvpermRoleCreateCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--name", "市场可读",
"--sub-roles", `[{"targetId":"TABLE_001","targetType":"sheet","authLevel":"read"}]`,
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "create_role" {
t.Fatalf("Tool = %q, want create_role", got)
}
subRoles, ok := runner.last.Params["subRoles"].([]any)
if !ok || len(subRoles) != 1 {
t.Fatalf("subRoles = %#v, want single-item []any", runner.last.Params["subRoles"])
}
}
func TestAitableSectionMoveNodeAllowsRootParent(t *testing.T) {
t.Parallel()
runner := &aitableCommandRunner{}
cmd := newAitableSectionMoveNodeCommand(runner)
executeAitableExtraCommand(t, cmd,
"--base-id", "BASE_001",
"--node-id", "NODE_001",
"--new-parent-section-id", "",
"--target-index", "0",
)
if got := runner.last.CanonicalProduct; got != "aitable-helper" {
t.Fatalf("CanonicalProduct = %q, want aitable-helper", got)
}
if got := runner.last.Tool; got != "move_nsheet_node" {
t.Fatalf("Tool = %q, want move_nsheet_node", got)
}
if got := runner.last.Params["newParentSectionId"]; got != "" {
t.Fatalf("newParentSectionId = %#v, want empty string", got)
}
if got := runner.last.Params["targetIndex"]; got != 0 {
t.Fatalf("targetIndex = %#v, want 0", got)
}
}
+167
View File
@@ -0,0 +1,167 @@
// 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 (
"strings"
"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/DingTalk-Real-AI/dingtalk-workspace-cli/internal/i18n"
"github.com/spf13/cobra"
)
func init() {
RegisterPublic(func() Handler { return calendarHandler{} })
}
// calendarHandler contributes the `calendar attendee list|add|delete` group.
// wukong renamed the calendar participant commands to "attendee" (former name:
// participant); the envelope still exposes them under "participant". These
// leaves call the same MCP tools (get/add/remove_calendar_participant) so the
// wukong command surface is aligned without dropping the legacy participant
// path. MergeCommandTree folds the attendee group into the calendar tree.
type calendarHandler struct{}
func (calendarHandler) Name() string { return "calendar" }
func (calendarHandler) Command(runner executor.Runner) *cobra.Command {
root := &cobra.Command{
Use: "calendar",
Short: i18n.T("日历"),
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error { return cmd.Help() },
}
attendee := &cobra.Command{
Use: "attendee",
Short: i18n.T("参会人管理(与 participant 等价,对齐 wukong 命名)"),
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error { return cmd.Help() },
}
attendee.AddCommand(
newCalendarAttendeeListCommand(runner),
newCalendarAttendeeAddCommand(runner),
newCalendarAttendeeDeleteCommand(runner),
)
root.AddCommand(attendee)
return root
}
func newCalendarAttendeeListCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "list", Short: i18n.T("查询日程参会人"),
Example: " dws calendar attendee list --event <eventId>", Args: cobra.NoArgs, DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
eventID := strings.TrimSpace(firstNonEmptyFlag(cmd, "event", "event-id"))
if eventID == "" {
return apperrors.NewValidation("missing required flag(s): --event")
}
params := map[string]any{"eventId": eventID}
if v := strings.TrimSpace(firstNonEmptyFlag(cmd, "calendar-id", "calendarId")); v != "" {
params["calendarId"] = v
}
return runCalendarTool(cmd, runner, "get_calendar_participants", params)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("event", "", i18n.T("日程 eventId (必填)"))
cmd.Flags().String("calendar-id", "", i18n.T("日历 ID (可选, 默认主日历)"))
return cmd
}
func newCalendarAttendeeAddCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "add", Short: i18n.T("添加日程参会人"),
Example: " dws calendar attendee add --event <eventId> --users userId1,userId2", Args: cobra.NoArgs, DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
eventID := strings.TrimSpace(firstNonEmptyFlag(cmd, "event", "event-id"))
users := strings.TrimSpace(firstNonEmptyFlag(cmd, "users", "attendees", "user-ids"))
if eventID == "" {
return apperrors.NewValidation("missing required flag(s): --event")
}
if users == "" {
return apperrors.NewValidation("missing required flag(s): --users")
}
params := map[string]any{"eventId": eventID, "attendeesToAdd": csvToList(users)}
if v := strings.TrimSpace(firstNonEmptyFlag(cmd, "optional")); v != "" {
params["optional"] = v
}
if v := strings.TrimSpace(firstNonEmptyFlag(cmd, "calendar-id", "calendarId")); v != "" {
params["calendarId"] = v
}
return runCalendarTool(cmd, runner, "add_calendar_participant", params)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("event", "", i18n.T("日程 eventId (必填)"))
cmd.Flags().String("users", "", i18n.T("参会人 userId 列表,逗号分隔 (必填)"))
cmd.Flags().String("optional", "", i18n.T("是否可选参会人 (可选)"))
cmd.Flags().String("calendar-id", "", i18n.T("日历 ID (可选)"))
return cmd
}
func newCalendarAttendeeDeleteCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "delete", Short: i18n.T("移除日程参会人"),
Example: " dws calendar attendee delete --event <eventId> --users userId1", Args: cobra.NoArgs, DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
eventID := strings.TrimSpace(firstNonEmptyFlag(cmd, "event", "event-id"))
users := strings.TrimSpace(firstNonEmptyFlag(cmd, "users", "attendees", "user-ids"))
if eventID == "" {
return apperrors.NewValidation("missing required flag(s): --event")
}
if users == "" {
return apperrors.NewValidation("missing required flag(s): --users")
}
params := map[string]any{"eventId": eventID, "attendeesToRemove": csvToList(users)}
if v := strings.TrimSpace(firstNonEmptyFlag(cmd, "calendar-id", "calendarId")); v != "" {
params["calendarId"] = v
}
return runCalendarTool(cmd, runner, "remove_calendar_participant", params)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("event", "", i18n.T("日程 eventId (必填)"))
cmd.Flags().String("users", "", i18n.T("参会人 userId 列表,逗号分隔 (必填)"))
cmd.Flags().String("calendar-id", "", i18n.T("日历 ID (可选)"))
return cmd
}
func runCalendarTool(cmd *cobra.Command, runner executor.Runner, tool string, params map[string]any) error {
inv := executor.NewHelperInvocation(cobracmd.LegacyCommandPath(cmd), "calendar", tool, params)
if commandDryRun(cmd) {
return writeCommandPayload(cmd, inv)
}
result, err := runner.Run(cmd.Context(), inv)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
}
func csvToList(s string) []any {
parts := strings.Split(s, ",")
out := make([]any, 0, len(parts))
for _, p := range parts {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
+20 -2
View File
@@ -23,6 +23,7 @@ import (
"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/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
@@ -120,7 +121,7 @@ func (chatHandler) Command(runner executor.Runner) *cobra.Command {
newChatBotSearchCommand(runner),
)
root.AddCommand(message, group, bot)
root.AddCommand(message, group, bot, newChatFileGroup(runner))
return root
}
@@ -333,9 +334,19 @@ func newChatMessageSendCommand(runner executor.Runner) *cobra.Command {
cmd.Flags().String("file-type", "", "文件类型/扩展名 (msg-type=file)")
cmd.Flags().String("file-path", "", "文件展示路径 (msg-type=file)")
cmd.Flags().Int64("file-size", 0, "文件大小,单位字节 (msg-type=file)")
cmd.Flags().Bool("ai-tag", false, "标记为「通过AI发送」(默认不带;仅传 --ai-tag 时才在消息下方显示 AI 发送角标)")
return cmd
}
// attachAITag 仅在用户显式传入 --ai-tag 时,给发送参数加上 clawType,
// 由 IM 服务端据此渲染「通过AI发送」角标 (悟空版渲染「悟空AI发送」)。
// 默认不带:是否标记 AI 发送交由用户自行选择,不强加。
func attachAITag(cmd *cobra.Command, params map[string]any) {
if on, _ := cmd.Flags().GetBool("ai-tag"); on {
params["clawType"] = edition.ClawType()
}
}
// deriveTitleFromText 在未显式指定 --title 时,从正文截取一个标题
// (首行、最多 20 个字符),与 wukong 行为对齐 (send_personal_message 的
// content 内携带 title)。
@@ -442,6 +453,7 @@ func buildChatMessageSendInvocation(cmd *cobra.Command, args []string) (map[stri
return nil, "", apperrors.NewValidation("unsupported --msg-type: " + msgType + " (supported: image, file)")
}
params := map[string]any{"msgType": msgType, "content": contentJSON}
attachAITag(cmd, params)
if strings.TrimSpace(uuid) != "" {
params["uuid"] = uuid
}
@@ -481,6 +493,7 @@ func buildChatMessageSendInvocation(cmd *cobra.Command, args []string) (map[stri
"msgType": "markdown",
"content": marshalMessageContent(title, text),
}
attachAITag(cmd, params)
if atAll {
params["atAll"] = true
}
@@ -493,6 +506,7 @@ func buildChatMessageSendInvocation(cmd *cobra.Command, args []string) (map[stri
return params, "send_personal_message", nil
case hasUser:
params := map[string]any{"title": title, "text": text, "receiverUserId": user}
attachAITag(cmd, params)
return params, "send_direct_message_as_user", nil
default:
params := map[string]any{
@@ -500,6 +514,7 @@ func buildChatMessageSendInvocation(cmd *cobra.Command, args []string) (map[stri
"msgType": "markdown",
"content": marshalMessageContent(title, text),
}
attachAITag(cmd, params)
if strings.TrimSpace(uuid) != "" {
params["uuid"] = uuid
}
@@ -975,8 +990,10 @@ func newChatMessageReplyCommand(runner executor.Runner) *cobra.Command {
"openConversationId": convID,
"msgType": "reply",
"content": contentJSON,
"clawType": "wukong",
}
// clawType 仅在 --ai-tag 时携带;默认不带,回复不强加 AI 角标。
// edition 决定取值 (开源 openClaw / 悟空 wukong)。
attachAITag(cmd, params)
if uuid, _ := cmd.Flags().GetString("uuid"); strings.TrimSpace(uuid) != "" {
params["uuid"] = uuid
}
@@ -1000,6 +1017,7 @@ func newChatMessageReplyCommand(runner executor.Runner) *cobra.Command {
cmd.Flags().String("ref-sender", "", "被引用消息发送者 openDingTalkId (必填)")
cmd.Flags().String("text", "", "回复正文 (必填)")
cmd.Flags().String("uuid", "", "可选 uuid(幂等标识)")
cmd.Flags().Bool("ai-tag", false, "标记为「通过AI发送」(默认不带;仅传 --ai-tag 时才显示 AI 发送角标)")
return cmd
}
+206
View File
@@ -0,0 +1,206 @@
// 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"
"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"
)
// newChatFileGroup builds `dws chat file upload`. wukong implements it as a
// multi-step upload to the conversation file space: for --file it does
// init_conversation_file_upload (im) -> HTTP PUT -> commit_conversation_file_upload
// (im); for --url it calls upload_conversation_file_by_url (chat). The envelope
// cannot express the local pipeline, so it lives here. Wired into the chat
// handler (see chat.go).
func newChatFileGroup(runner executor.Runner) *cobra.Command {
file := &cobra.Command{
Use: "file",
Short: "会话文件上传",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error { return cmd.Help() },
}
file.AddCommand(newChatFileUploadCommand(runner))
return file
}
func newChatFileUploadCommand(runner executor.Runner) *cobra.Command {
cmd := &cobra.Command{
Use: "upload",
Short: "上传本地文件或 URL 文件到会话文件空间",
Example: " dws chat file upload --group <openConversationId> --file ./report.pdf\n" +
" dws chat file upload --user <userId> --url https://example.com/a.pdf --file-name a.pdf",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
target, err := chatConversationTargetArgs(cmd)
if err != nil {
return err
}
filePath := strings.TrimSpace(firstNonEmptyFlag(cmd, "file", "file-path"))
fileURL := strings.TrimSpace(firstNonEmptyFlag(cmd, "url"))
if filePath == "" && fileURL == "" {
return apperrors.NewValidation("--file or --url is required")
}
if filePath != "" && fileURL != "" {
return apperrors.NewValidation("--file and --url are mutually exclusive")
}
fileName := strings.TrimSpace(firstNonEmptyFlag(cmd, "file-name"))
md5v := strings.TrimSpace(firstNonEmptyFlag(cmd, "md5"))
uuid := strings.TrimSpace(firstNonEmptyFlag(cmd, "uuid"))
// URL path: server pulls the file (chat server).
if fileURL != "" {
if fileName == "" {
fileName = filepath.Base(fileURL)
}
params := cloneStringAnyMap(target)
params["fileUrl"] = fileURL
params["fileName"] = fileName
if md5v != "" {
params["md5"] = md5v
}
if uuid != "" {
params["uuid"] = uuid
}
inv := executor.NewHelperInvocation(cobracmd.LegacyCommandPath(cmd), "chat", "upload_conversation_file_by_url", params)
if commandDryRun(cmd) {
return writeCommandPayload(cmd, inv)
}
result, err := runner.Run(cmd.Context(), inv)
if err != nil {
return err
}
return writeCommandPayload(cmd, result)
}
// Local path: init (im) -> HTTP PUT -> commit (im).
fi, err := os.Stat(filePath)
if err != nil {
return apperrors.NewValidation("cannot read file " + filePath + ": " + err.Error())
}
if fi.IsDir() {
return apperrors.NewValidation(filePath + " is a directory, not a file")
}
if fileName == "" {
fileName = filepath.Base(filePath)
}
fileSize := fi.Size()
if md5v == "" {
if md5v, err = fileMD5Hex(filePath); err != nil {
return err
}
}
if commandDryRun(cmd) {
preview := cloneStringAnyMap(target)
preview["fileName"] = fileName
preview["fileSize"] = fileSize
preview["md5"] = md5v
return writeCommandPayload(cmd, executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "im", "init_conversation_file_upload", preview))
}
ctx, cancel := context.WithTimeout(cmd.Context(), 10*time.Minute)
defer cancel()
initParams := cloneStringAnyMap(target)
initParams["fileName"] = fileName
initParams["fileSize"] = fileSize
initParams["md5"] = md5v
initRes, err := runner.Run(ctx, executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "im", "init_conversation_file_upload", initParams))
if err != nil {
return err
}
resourceURL := findStringDeep(initRes.Response, "resourceUrl", "resourceURL", "url")
if resourceURL == "" {
resourceURL = findFirstInStringArrayDeep(initRes.Response, "resourceUrls", "resourceURLs")
}
uploadKey := findStringDeep(initRes.Response, "uploadKey", "key")
if resourceURL == "" || uploadKey == "" {
return apperrors.NewAPI("incomplete upload credentials: resourceUrl=" + resourceURL + " uploadKey=" + uploadKey)
}
headers := findHeadersDeep(initRes.Response, "headers", "ossHeaders")
if err := httpPutLocalFile(ctx, resourceURL, headers, filePath, fileSize); err != nil {
return err
}
commitParams := cloneStringAnyMap(target)
commitParams["uploadKey"] = uploadKey
commitParams["fileName"] = fileName
commitParams["fileSize"] = fileSize
commitParams["md5"] = md5v
if uuid != "" {
commitParams["uuid"] = uuid
}
commitRes, err := runner.Run(ctx, executor.NewHelperInvocation(
cobracmd.LegacyCommandPath(cmd), "im", "commit_conversation_file_upload", commitParams))
if err != nil {
return err
}
return writeCommandPayload(cmd, commitRes)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("group", "", "群聊 openConversationId(群聊时使用)")
cmd.Flags().String("conversation-id", "", "--group 的别名")
cmd.Flags().String("id", "", "--group 的别名")
cmd.Flags().String("user", "", "单聊对方 userId(单聊时使用)")
cmd.Flags().String("open-dingtalk-id", "", "单聊对方 openDingTalkId(单聊时使用)")
cmd.Flags().String("file", "", "本地文件路径(与 --url 二选一)")
cmd.Flags().String("file-path", "", "--file 的别名")
cmd.Flags().String("url", "", "远程文件 URL(与 --file 二选一,服务端代传)")
cmd.Flags().String("file-name", "", "文件名(可选)")
cmd.Flags().String("md5", "", "文件 MD5(可选,本地不传自动计算)")
cmd.Flags().String("uuid", "", "幂等 UUID(可选)")
return cmd
}
func chatConversationTargetArgs(cmd *cobra.Command) (map[string]any, error) {
group := strings.TrimSpace(firstNonEmptyFlag(cmd, "group", "conversation-id", "id"))
user := strings.TrimSpace(firstNonEmptyFlag(cmd, "user"))
openDingTalkID := strings.TrimSpace(firstNonEmptyFlag(cmd, "open-dingtalk-id"))
if group == "" && user == "" && openDingTalkID == "" {
return nil, apperrors.NewValidation("需指定会话目标:--group(群聊)或 --user / --open-dingtalk-id(单聊)之一")
}
m := map[string]any{}
if group != "" {
m["openConversationId"] = group
}
if user != "" {
m["userId"] = user
}
if openDingTalkID != "" {
m["openDingTalkId"] = openDingTalkID
}
return m, nil
}
func cloneStringAnyMap(in map[string]any) map[string]any {
out := make(map[string]any, len(in)+4)
for k, v := range in {
out[k] = v
}
return out
}
+100
View File
@@ -7,6 +7,8 @@ import (
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
type captureRunner struct {
@@ -308,6 +310,104 @@ func TestChatMessageSendRejectsAtMentionsOutsideGroup(t *testing.T) {
}
}
// TestChatMessageAITagControlsClawType guards the opt-in "Send from AI" indicator:
// by default NO user-identity send carries the clawType tool argument (so the IM
// server renders no AI badge). Only when --ai-tag is passed does each path attach
// the edition claw identity (open-source build pins it to edition.DefaultOSSClawType,
// "openClaw"); the wukong overlay would attach its own value. The label is opt-in so
// dws does not surprise users by branding every message they send.
func TestChatMessageAITagControlsClawType(t *testing.T) {
cases := []struct {
name string
make func(runner executor.Runner) *cobra.Command
args []string
}{
{
name: "group-markdown",
make: newChatMessageSendCommand,
args: []string{"--group", "cid-xyz", "--title", "t", "--text", "hello"},
},
{
name: "user-direct",
make: newChatMessageSendCommand,
args: []string{"--user", "034766", "--title", "t", "--text", "hi"},
},
{
name: "open-dingtalk-id-direct",
make: newChatMessageSendCommand,
args: []string{"--open-dingtalk-id", "OP123", "--title", "t", "--text", "hi"},
},
{
name: "group-rich-media-image",
make: newChatMessageSendCommand,
args: []string{"--group", "cid-xyz", "--msg-type", "image", "--media-id", "media-1"},
},
{
name: "reply",
make: newChatMessageReplyCommand,
args: []string{
"--conversation-id", "cid-xyz",
"--ref-msg-id", "msg-1",
"--ref-sender", "op-1",
"--text", "got it",
},
},
}
for _, tc := range cases {
// Default: no --ai-tag → must omit clawType entirely (no badge).
t.Run(tc.name+"/default-no-tag", func(t *testing.T) {
runner := &captureRunner{}
cmd := tc.make(runner)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs(tc.args)
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\noutput:\n%s", err, out.String())
}
if v, ok := runner.last.Params["clawType"]; ok {
t.Fatalf("default send must omit clawType, got %#v", v)
}
})
// Opt-in: --ai-tag → attach the edition claw identity.
t.Run(tc.name+"/with-ai-tag", func(t *testing.T) {
runner := &captureRunner{}
cmd := tc.make(runner)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs(append(append([]string{}, tc.args...), "--ai-tag"))
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\noutput:\n%s", err, out.String())
}
got, ok := runner.last.Params["clawType"]
if !ok {
t.Fatalf("--ai-tag send missing clawType; got %#v", runner.last.Params)
}
if got != edition.DefaultOSSClawType {
t.Fatalf("clawType = %#v, want %q", got, edition.DefaultOSSClawType)
}
})
}
}
// Robot sends are rendered as bot messages already; they must NOT carry the
// user-identity clawType argument.
func TestChatMessageSendByBotOmitsClawType(t *testing.T) {
runner := &captureRunner{}
cmd := newChatMessageSendByBotCommand(runner)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--group", "cid-xyz", "--robot-code", "robot-001", "--title", "t", "--text", "x"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\noutput:\n%s", err, out.String())
}
if _, ok := runner.last.Params["clawType"]; ok {
t.Fatalf("bot send must not carry clawType; got %#v", runner.last.Params)
}
}
func equalAny(a, b any) bool {
switch av := a.(type) {
case []any:
+115
View File
@@ -0,0 +1,115 @@
// 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 (
"strings"
"sync"
"time"
)
// connectGate enforces the connector's access policy: optional user/group
// allowlists plus a per-sender rate limit. A long-lived Q&A bot is otherwise
// drivable (and billable — every message is an LLM call) by anyone who can
// reach it in a group.
type connectGate struct {
allowedUsers map[string]struct{}
allowedGroups map[string]struct{}
perMinute int
mu sync.Mutex
hits map[string][]time.Time
now func() time.Time // test hook
}
// splitCommaList splits a comma-separated flag/env value, trimming blanks.
func splitCommaList(s string) []string {
var out []string
for _, p := range strings.Split(s, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// newConnectGate builds a gate from staffId / openConversationId allowlists
// and a per-sender messages-per-minute cap (0 = unlimited).
func newConnectGate(users, groups []string, perMinute int) *connectGate {
g := &connectGate{perMinute: perMinute, hits: map[string][]time.Time{}, now: time.Now}
for _, u := range users {
if u = strings.TrimSpace(u); u != "" {
if g.allowedUsers == nil {
g.allowedUsers = map[string]struct{}{}
}
g.allowedUsers[u] = struct{}{}
}
}
for _, grp := range groups {
if grp = strings.TrimSpace(grp); grp != "" {
if g.allowedGroups == nil {
g.allowedGroups = map[string]struct{}{}
}
g.allowedGroups[grp] = struct{}{}
}
}
return g
}
// enabled reports whether any policy is configured at all.
func (g *connectGate) enabled() bool {
return g != nil && (len(g.allowedUsers) > 0 || len(g.allowedGroups) > 0 || g.perMinute > 0)
}
// allow reports whether a message may proceed; on denial, reason names the
// rule that fired (for the connector log). Group messages must pass the group
// allowlist AND, when a user allowlist is set, the sender allowlist too.
func (g *connectGate) allow(staffID, convType, convID string) (bool, string) {
if g == nil {
return true, ""
}
if convType == "2" && len(g.allowedGroups) > 0 {
if _, ok := g.allowedGroups[convID]; !ok {
return false, "group-not-allowed"
}
}
if len(g.allowedUsers) > 0 {
if _, ok := g.allowedUsers[staffID]; !ok {
return false, "user-not-allowed"
}
}
if g.perMinute > 0 && staffID != "" {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
cutoff := now.Add(-time.Minute)
kept := g.hits[staffID][:0]
for _, t := range g.hits[staffID] {
if t.After(cutoff) {
kept = append(kept, t)
}
}
if len(kept) >= g.perMinute {
g.hits[staffID] = kept
return false, "rate-limited"
}
g.hits[staffID] = append(kept, now)
// Bound memory against sender-id churn: keep only the current sender
// when the map grows absurdly large.
if len(g.hits) > 4096 {
g.hits = map[string][]time.Time{staffID: g.hits[staffID]}
}
}
return true, ""
}
+97
View File
@@ -0,0 +1,97 @@
// 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 (
"testing"
"time"
)
func TestConnectGateAllowlists(t *testing.T) {
cases := []struct {
name string
users []string
groups []string
staff string
convType string
convID string
wantOK bool
wantReason string
}{
{"no policy allows everyone", nil, nil, "u1", "1", "", true, ""},
{"user in list", []string{"u1", "u2"}, nil, "u1", "1", "", true, ""},
{"user not in list", []string{"u1"}, nil, "u9", "1", "", false, "user-not-allowed"},
{"group in list", nil, []string{"cid-a"}, "u9", "2", "cid-a", true, ""},
{"group not in list", nil, []string{"cid-a"}, "u9", "2", "cid-b", false, "group-not-allowed"},
{"group list does not gate DMs", nil, []string{"cid-a"}, "u9", "1", "", true, ""},
{"both lists: group ok user not", []string{"u1"}, []string{"cid-a"}, "u9", "2", "cid-a", false, "user-not-allowed"},
{"both lists: both ok", []string{"u1"}, []string{"cid-a"}, "u1", "2", "cid-a", true, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
g := newConnectGate(tc.users, tc.groups, 0)
ok, reason := g.allow(tc.staff, tc.convType, tc.convID)
if ok != tc.wantOK || reason != tc.wantReason {
t.Fatalf("allow = (%v, %q), want (%v, %q)", ok, reason, tc.wantOK, tc.wantReason)
}
})
}
}
func TestConnectGateRateLimit(t *testing.T) {
g := newConnectGate(nil, nil, 2)
now := time.Unix(1_700_000_000, 0)
g.now = func() time.Time { return now }
for i := 0; i < 2; i++ {
if ok, _ := g.allow("u1", "1", ""); !ok {
t.Fatalf("message %d should pass", i+1)
}
}
if ok, reason := g.allow("u1", "1", ""); ok || reason != "rate-limited" {
t.Fatalf("3rd message = (%v, %q), want rate-limited", ok, reason)
}
// Another sender is unaffected.
if ok, _ := g.allow("u2", "1", ""); !ok {
t.Fatal("other sender should pass")
}
// The window slides: a minute later the sender passes again.
now = now.Add(61 * time.Second)
if ok, _ := g.allow("u1", "1", ""); !ok {
t.Fatal("after window slides the sender should pass")
}
}
func TestConnectGateDisabled(t *testing.T) {
var nilGate *connectGate
if nilGate.enabled() {
t.Fatal("nil gate must report disabled")
}
if ok, _ := nilGate.allow("u", "1", ""); !ok {
t.Fatal("nil gate must allow")
}
if newConnectGate(nil, nil, 0).enabled() {
t.Fatal("empty gate must report disabled")
}
}
func TestSplitCommaList(t *testing.T) {
got := splitCommaList(" a, b ,, c ")
if len(got) != 3 || got[0] != "a" || got[1] != "b" || got[2] != "c" {
t.Fatalf("splitCommaList = %v", got)
}
if splitCommaList("") != nil {
t.Fatal("empty input should yield nil")
}
}
@@ -0,0 +1,239 @@
// 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 (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
// writeExecStub drops an executable shell stub named name into dir so PATH
// lookups resolve without the real CLI installed.
func writeExecStub(dir, name string) error {
return os.WriteFile(filepath.Join(dir, name), []byte("#!/bin/sh\n"), 0o755)
}
// TestConvSessions covers the per-conversation session contract: first message
// creates (--session-id), follow-ups resume (--resume), reset re-mints.
func TestConvSessions(t *testing.T) {
s := newConvSessions("")
first := s.args("conv-1")
if len(first) != 2 || first[0] != "--session-id" || first[1] == "" {
t.Fatalf("first args = %v, want [--session-id <uuid>]", first)
}
second := s.args("conv-1")
if len(second) != 2 || second[0] != "--resume" || second[1] != first[1] {
t.Fatalf("second args = %v, want [--resume %s]", second, first[1])
}
// A different conversation gets its own session.
other := s.args("conv-2")
if other[0] != "--session-id" || other[1] == first[1] {
t.Fatalf("conv-2 args = %v, want a fresh --session-id distinct from %s", other, first[1])
}
// reset self-heals a broken session: next message starts fresh with a NEW
// uuid (the old one may or may not exist agent-side; a new one is safe).
s.reset("conv-1")
again := s.args("conv-1")
if again[0] != "--session-id" || again[1] == first[1] {
t.Fatalf("post-reset args = %v, want fresh --session-id != %s", again, first[1])
}
}
// TestApplyModelArg covers both shapes: replacing an existing model pin
// (claudecode's built-in haiku) and inserting before the tail (gemini-style
// tails that end with -p and need the prompt to stay trailing).
func TestApplyModelArg(t *testing.T) {
replaced := applyModelArg(
[]string{"claude", "-p", "--model", "claude-haiku-4-5-20251001", "--strict-mcp-config"},
"--model", "claude-sonnet-4-6")
want := []string{"claude", "-p", "--model", "claude-sonnet-4-6", "--strict-mcp-config"}
if strings.Join(replaced, " ") != strings.Join(want, " ") {
t.Fatalf("replace: got %v, want %v", replaced, want)
}
inserted := applyModelArg([]string{"gemini", "-p"}, "-m", "gemini-2.5-pro")
wantIns := []string{"gemini", "-m", "gemini-2.5-pro", "-p"}
if strings.Join(inserted, " ") != strings.Join(wantIns, " ") {
t.Fatalf("insert: got %v, want %v", inserted, wantIns)
}
}
// TestForwarderSessionAndModelWiring checks forwarderForChannel applies the
// options: memory only on ccSessions channels, model only via the spec's flag.
func TestForwarderSessionAndModelWiring(t *testing.T) {
t.Setenv("DWS_CONNECT_NO_INSTALL", "1")
t.Setenv("DWS_AGENT_CMD", "") // ensure no override
// Use DWS_AGENT_CMD-free resolution; claudecode requires the binary on
// PATH, which CI may lack — fake it via DWS_AGENT_CMD is wrong (disables
// extras by design), so point PATH at a stub.
stub := t.TempDir()
for _, name := range []string{"claude", "qodercli"} {
if err := writeExecStub(stub, name); err != nil {
t.Fatalf("stub %s: %v", name, err)
}
}
t.Setenv("PATH", stub)
fwd, err := forwarderForChannel("claudecode", "", connectAgentOptions{Memory: true, Model: "claude-sonnet-4-6"})
if err != nil {
t.Fatalf("claudecode forwarder: %v", err)
}
ef := fwd.(*execForwarder)
if ef.sessions == nil {
t.Fatal("claudecode with Memory=true should have sessions enabled")
}
if !strings.Contains(strings.Join(ef.argv, " "), "--model claude-sonnet-4-6") {
t.Fatalf("model not applied: %v", ef.argv)
}
if strings.Contains(strings.Join(ef.argv, " "), "haiku") {
t.Fatalf("built-in haiku pin should be replaced: %v", ef.argv)
}
// qoder family runs a persistent stream-json subprocess and carries the
// addressable Qoder session id inside each JSON user message. DWS persists
// the mapping so a connector restart can resume the same conversation.
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
qf, err := forwarderForChannel("qoder", "qoder-client", connectAgentOptions{Memory: true})
if err != nil {
t.Fatalf("qoder forwarder: %v", err)
}
qsf := qf.(*qoderStreamForwarder)
if qsf.sessions == nil {
t.Fatal("qoder with Memory=true should have sessions")
}
if qsf.sessions.path == "" {
t.Fatal("qoder sessions should persist to disk")
}
if got := strings.Join(qsf.commandArgs(), " "); !strings.Contains(got, "--input-format stream-json") || !strings.Contains(got, "--output-format stream-json") {
t.Fatalf("qoder stream-json args mismatch: argv = %v", qsf.commandArgs())
}
qwf, err := forwarderForChannel("qoderwork", "robot-client", connectAgentOptions{Memory: true})
if err != nil {
t.Fatalf("qoderwork forwarder: %v", err)
}
qwsf := qwf.(*qoderStreamForwarder)
if qwsf.sessions == nil {
t.Fatal("qoderwork with Memory=true should have sessions")
}
if qwsf.sessions.path == "" {
t.Fatal("qoderwork sessions should persist to disk")
}
// Memory off on a supporting channel.
off, err := forwarderForChannel("claudecode", "", connectAgentOptions{Memory: false})
if err != nil {
t.Fatalf("claudecode memory-off forwarder: %v", err)
}
if off.(*execForwarder).sessions != nil {
t.Fatal("Memory=false must disable sessions")
}
}
// TestRobotConnectAgentFlagsInDryRun checks the new flags surface in the
// dry-run preview so callers can see the effective agent tuning.
func TestRobotConnectAgentFlagsInDryRun(t *testing.T) {
root := newDevAppTestRoot(&captureRunner{})
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs([]string{"dev", "connect",
"--channel", "claudecode",
"--robot-client-id", "id1", "--robot-client-secret", "sec1",
"--agent-model", "claude-sonnet-4-6", "--agent-workdir", "/tmp/kb",
"--dry-run"})
if err := root.Execute(); err != nil {
t.Fatalf("Execute() error = %v\n%s", err, out.String())
}
for _, sub := range []string{"claude-sonnet-4-6", "/tmp/kb", "per-conversation"} {
if !strings.Contains(out.String(), sub) {
t.Fatalf("dry-run output missing %q:\n%s", sub, out.String())
}
}
// memory=false shows as disabled.
out.Reset()
root = newDevAppTestRoot(&captureRunner{})
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs([]string{"dev", "connect",
"--channel", "claudecode",
"--robot-client-id", "id1", "--robot-client-secret", "sec1",
"--agent-memory=false", "--dry-run"})
if err := root.Execute(); err != nil {
t.Fatalf("Execute() error = %v\n%s", err, out.String())
}
if !strings.Contains(out.String(), `"memory": "disabled"`) {
t.Fatalf("dry-run output missing disabled memory:\n%s", out.String())
}
}
func TestQoderAgentMemoryPayloadIsPerConversation(t *testing.T) {
payload := connectAgentOptionsPayload("qoder", connectAgentOptions{Memory: true})
if got := payload["memory"]; got != "per-conversation-qoder-stream" {
t.Fatalf("qoder memory = %v, want per-conversation-qoder-stream", got)
}
payload = connectAgentOptionsPayload("qoderwork", connectAgentOptions{Memory: true})
if got := payload["memory"]; got != "per-conversation-qoder-stream" {
t.Fatalf("qoderwork memory = %v, want per-conversation-qoder-stream", got)
}
payload = connectAgentOptionsPayload("qoder", connectAgentOptions{Memory: false})
if got := payload["memory"]; got != "disabled" {
t.Fatalf("qoder memory disabled = %v, want disabled", got)
}
}
// TestRobotConnectDryRunShowsCliStatus checks the dependency preflight agents
// rely on: dry-run reports whether the channel CLI is installed, with the
// install hint when missing.
func TestRobotConnectDryRunShowsCliStatus(t *testing.T) {
t.Setenv("DWS_CONNECT_NO_INSTALL", "1")
stub := t.TempDir()
if err := writeExecStub(stub, "claude"); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", stub)
run := func(channel string) string {
root := newDevAppTestRoot(&captureRunner{})
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs([]string{"dev", "connect", "--channel", channel,
"--robot-client-id", "a", "--robot-client-secret", "b", "--dry-run"})
if err := root.Execute(); err != nil {
t.Fatalf("Execute(%s): %v\n%s", channel, err, out.String())
}
return out.String()
}
// claude on PATH → installed true with path
if got := run("claudecode"); !strings.Contains(got, `"installed": true`) {
t.Fatalf("claudecode should be installed:\n%s", got)
}
// codex NOT on PATH → installed false + hint
got := run("codex")
if !strings.Contains(got, `"installed": false`) || !strings.Contains(got, "@openai/codex") {
t.Fatalf("codex should be missing with hint:\n%s", got)
}
if !strings.Contains(got, "per-conversation-app-server") {
t.Fatalf("codex dry-run should advertise app-server memory:\n%s", got)
}
}
+698
View File
@@ -0,0 +1,698 @@
// 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"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
)
// The "digital twin" confirmation gate. When someone @-mentions the bot with an
// *action* request ("create a todo for me"), the bot does NOT execute it: it
// records an ApprovalRequest, sends an interactive card with [Approve]/[Reject]
// buttons to the owner, and only runs the planned action after the owner taps
// Approve. A Reject (or timeout) declines without executing.
//
// This file owns the gate engine: the request/state model, the thread-safe
// store with crash-safe on-disk persistence (so a Pending request survives a
// connector restart), and the Submit/Decide/Await/Get API. Card delivery and
// the connector wiring live in connect_approval_card.go and connect_stream.go.
// approvalState is the request lifecycle: Pending → Approved|Rejected →
// Executed|Failed. A decision (Approve/Reject) is the owner's call; execution
// is what the orchestrator does afterwards on an approved request.
type approvalState string
const (
approvalPending approvalState = "pending"
approvalApproved approvalState = "approved"
approvalRejected approvalState = "rejected"
approvalExecuted approvalState = "executed"
approvalFailed approvalState = "failed"
// approvalDeferred is an approved request whose execution could not complete
// right now — typically because the connector's dws login is not (yet) the
// bot's owner, so an owner-scoped action can't run. The request is NOT lost:
// it stays on disk in this state, the owner is told to recover (log in), and
// a later "retry" flushes it. Distinct from Failed, which is terminal.
approvalDeferred approvalState = "deferred"
)
// plannedAction is the structured command the gate will run once approved. It
// is intentionally generic (product + tool + params) so it maps straight onto
// executor.NewHelperInvocation without the gate knowing about any specific
// command. For the M2 vertical slice the orchestrator only emits todo.create,
// but the shape already supports any helper tool.
type plannedAction struct {
// Product/Tool/LegacyPath feed executor.NewHelperInvocation. Product is the
// canonical product (e.g. "todo"); Tool is the RPC name (e.g.
// "create_personal_todo"); LegacyPath is the human command path for logs.
Product string `json:"product"`
Tool string `json:"tool"`
LegacyPath string `json:"legacy_path,omitempty"`
Params map[string]any `json:"params,omitempty"`
}
// ApprovalRequest is one pending/decided confirmation. It is the on-disk record
// too (marshalled as-is), so every field is JSON-tagged and self-describing.
type ApprovalRequest struct {
ID string `json:"id"`
Requester string `json:"requester"` // staffId of who asked
ConvID string `json:"conv_id"` // conversation to reply into
Summary string `json:"summary"` // human-readable "what will happen"
Verb string `json:"verb,omitempty"` // action verb, e.g. "todo.create" (remember key)
Action plannedAction `json:"action"` // structured command to run on approve
State approvalState `json:"state"`
// OutTrackID is the delivered card's instance id, recorded so a button
// callback that only carries the card id (not the approval id in its action
// params) can still be mapped back to this request.
OutTrackID string `json:"out_track_id,omitempty"`
DecidedBy string `json:"decided_by,omitempty"` // staffId who approved/rejected
ExecErr string `json:"exec_err,omitempty"` // failure detail when State=failed
// AutoApproved marks a request the owner made of THEMSELVES: no second
// confirmation is asked (the owner asking IS the authorization), but the
// full record is still persisted for audit, with DecidedBy=owner. Lets the
// audit trail distinguish an auto-run from an explicitly-confirmed one.
AutoApproved bool `json:"auto_approved,omitempty"`
CreatedAt time.Time `json:"created_at"`
DecidedAt time.Time `json:"decided_at,omitempty"`
}
// decided reports whether the owner has made a call (approved or rejected),
// regardless of any later execution outcome.
func (r *ApprovalRequest) decided() bool {
switch r.State {
case approvalApproved, approvalRejected, approvalExecuted, approvalFailed, approvalDeferred:
return true
}
return false
}
// approved reports whether the owner approved (in any post-approval state,
// including deferred — a deferred request WAS approved, its execution just
// hasn't completed yet).
func (r *ApprovalRequest) approved() bool {
switch r.State {
case approvalApproved, approvalExecuted, approvalFailed, approvalDeferred:
return true
}
return false
}
// approvalGate is the thread-safe confirmation-gate store. It keeps every
// request in memory and mirrors each one to <config>/connect/<clientId>/
// approvals/<id>.json so a Pending request survives a connector restart.
// Persistence is best-effort and never blocks a decision: a write failure only
// logs (mirroring connect_sessions_store's contract). An empty clientId means
// in-memory only (used by tests).
type approvalGate struct {
clientID string
mu sync.Mutex
reqs map[string]*ApprovalRequest
waiters map[string]chan struct{} // id → closed when the request is decided
}
// newApprovalGate builds the gate and eagerly loads any persisted requests from
// disk (so a restart can still resolve a card tapped while the bot was down).
func newApprovalGate(clientID string) *approvalGate {
g := &approvalGate{
clientID: strings.TrimSpace(clientID),
reqs: make(map[string]*ApprovalRequest),
waiters: make(map[string]chan struct{}),
}
g.loadAll()
return g
}
// approvalDir returns the on-disk directory for this gate's requests, or "" when
// persistence is disabled (empty clientId). The clientId is sanitized exactly
// like the session store / lock file so it is always filesystem-safe.
func (g *approvalGate) approvalDir() string {
if g.clientID == "" {
return ""
}
return filepath.Join(config.DefaultConfigDir(), "connect", sanitizeLockID(g.clientID), "approvals")
}
// Submit records a new request in the Pending state, persists it, and returns
// the stored request (with a generated ID and CreatedAt). A blank requester or
// summary is allowed — the gate does not police content, it only sequences the
// approval — but an empty action means "nothing to run on approve", which the
// orchestrator must guard before calling Submit.
func (g *approvalGate) Submit(req ApprovalRequest) *ApprovalRequest {
g.mu.Lock()
defer g.mu.Unlock()
if strings.TrimSpace(req.ID) == "" {
req.ID = uuid.NewString()
}
req.State = approvalPending
if req.CreatedAt.IsZero() {
req.CreatedAt = time.Now()
}
stored := req // copy
g.reqs[stored.ID] = &stored
g.persist(&stored)
return &stored
}
// setOutTrackID records the delivered card instance id for a request so a
// callback that carries only the card id can be mapped back. No-op for unknown
// ids; persists on success.
func (g *approvalGate) setOutTrackID(id, outTrackID string) {
g.mu.Lock()
defer g.mu.Unlock()
r, ok := g.reqs[id]
if !ok {
return
}
r.OutTrackID = outTrackID
g.persist(r)
}
// findByOutTrackID returns the request whose delivered card has the given
// instance id, used as the fallback association when a callback's action params
// did not carry the approval id. Returns nil when none match.
func (g *approvalGate) findByOutTrackID(outTrackID string) *ApprovalRequest {
outTrackID = strings.TrimSpace(outTrackID)
if outTrackID == "" {
return nil
}
g.mu.Lock()
defer g.mu.Unlock()
for _, r := range g.reqs {
if r.OutTrackID == outTrackID {
cp := *r
return &cp
}
}
return nil
}
// pendingForConv returns a snapshot of the most-recent still-Pending request in
// the given conversation, or nil when none is awaiting a decision there. It is
// the lookup the text-approval mode needs to map an owner's "同意/拒绝" reply
// (which only carries the conversation, not an approval id) back to its request.
func (g *approvalGate) pendingForConv(convID string) *ApprovalRequest {
convID = strings.TrimSpace(convID)
if convID == "" {
return nil
}
g.mu.Lock()
defer g.mu.Unlock()
var best *ApprovalRequest
for _, r := range g.reqs {
if r.State == approvalPending && r.ConvID == convID {
if best == nil || r.CreatedAt.After(best.CreatedAt) {
best = r
}
}
}
if best == nil {
return nil
}
cp := *best
return &cp
}
// latestPending returns a snapshot of the most-recent still-Pending request
// across all conversations, or nil when none awaits a decision. Text approval
// uses it to map the owner's "同意/拒绝" — sent from the owner's OWN 1:1 chat
// with the bot, a different conversation than where the request originated —
// onto the request they are deciding. One bot has one owner, so every pending
// request belongs to that owner; newest-first matches "decide what I was just
// asked about".
func (g *approvalGate) latestPending() *ApprovalRequest {
g.mu.Lock()
defer g.mu.Unlock()
var best *ApprovalRequest
for _, r := range g.reqs {
if r.State == approvalPending {
if best == nil || r.CreatedAt.After(best.CreatedAt) {
best = r
}
}
}
if best == nil {
return nil
}
cp := *best
return &cp
}
// Decide records the owner's call on a Pending request and wakes any Await.
// It is idempotent and race-safe: a second decision (e.g. a double-tap, or a
// reject after an approve) is ignored once the request has already been
// decided, and the function reports whether THIS call was the deciding one.
func (g *approvalGate) Decide(id string, approve bool, by string) (*ApprovalRequest, bool) {
g.mu.Lock()
defer g.mu.Unlock()
r, ok := g.reqs[id]
if !ok {
return nil, false
}
if r.decided() {
cp := *r
return &cp, false // already decided; not the deciding call
}
if approve {
r.State = approvalApproved
} else {
r.State = approvalRejected
}
r.DecidedBy = strings.TrimSpace(by)
r.DecidedAt = time.Now()
g.persist(r)
g.wake(id)
cp := *r
return &cp, true
}
// markExecuted / markFailed record the post-approval execution outcome. They do
// not gate or wake anything (Await already returned on the decision); they exist
// so the on-disk record reflects what actually happened, for audit and restart.
func (g *approvalGate) markExecuted(id string) {
g.mu.Lock()
defer g.mu.Unlock()
if r, ok := g.reqs[id]; ok && r.approved() {
r.State = approvalExecuted
g.persist(r)
}
}
func (g *approvalGate) markFailed(id string, cause string) {
g.mu.Lock()
defer g.mu.Unlock()
if r, ok := g.reqs[id]; ok && r.approved() {
r.State = approvalFailed
r.ExecErr = truncateRunes(strings.TrimSpace(cause), 500)
g.persist(r)
}
}
// markDeferred records that an approved request could not execute now and is
// being held for a later retry (it is NOT lost). The cause is kept so the owner
// and the audit trail can see why. Persisted so a connector restart still
// remembers the backlog.
func (g *approvalGate) markDeferred(id string, cause string) {
g.mu.Lock()
defer g.mu.Unlock()
if r, ok := g.reqs[id]; ok && r.approved() {
r.State = approvalDeferred
r.ExecErr = truncateRunes(strings.TrimSpace(cause), 500)
g.persist(r)
}
}
// allDeferred returns snapshots of every request awaiting retry, oldest first
// (so a flush replays them in the order they were asked).
func (g *approvalGate) allDeferred() []*ApprovalRequest {
g.mu.Lock()
defer g.mu.Unlock()
out := make([]*ApprovalRequest, 0)
for _, r := range g.reqs {
if r.State == approvalDeferred {
cp := *r
out = append(out, &cp)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.Before(out[j].CreatedAt) })
return out
}
// Get returns a snapshot copy of a request, or nil if unknown.
func (g *approvalGate) Get(id string) *ApprovalRequest {
g.mu.Lock()
defer g.mu.Unlock()
if r, ok := g.reqs[id]; ok {
cp := *r
return &cp
}
return nil
}
// Await blocks until the request is decided (approved or rejected), the context
// is cancelled, or the timeout elapses, and returns the final snapshot. A
// request already decided returns immediately. On timeout the request stays
// Pending (a late tap can still resolve it) and Await returns (snapshot, false).
// The bool reports whether a decision was observed within the wait.
func (g *approvalGate) Await(ctx context.Context, id string, timeout time.Duration) (*ApprovalRequest, bool) {
// Fast path + waiter registration under the lock so we never miss a Decide
// that lands between the check and the channel subscribe.
g.mu.Lock()
r, ok := g.reqs[id]
if !ok {
g.mu.Unlock()
return nil, false
}
if r.decided() {
cp := *r
g.mu.Unlock()
return &cp, true
}
ch, exists := g.waiters[id]
if !exists {
ch = make(chan struct{})
g.waiters[id] = ch
}
g.mu.Unlock()
var timer *time.Timer
var timeout_c <-chan time.Time
if timeout > 0 {
timer = time.NewTimer(timeout)
defer timer.Stop()
timeout_c = timer.C
}
select {
case <-ch:
return g.Get(id), true
case <-ctx.Done():
return g.Get(id), false
case <-timeout_c:
return g.Get(id), false
}
}
// wake closes and clears the waiter channel for id (must hold g.mu). Safe to
// call when there is no waiter.
func (g *approvalGate) wake(id string) {
if ch, ok := g.waiters[id]; ok {
close(ch)
delete(g.waiters, id)
}
}
// persist atomically writes one request to disk (must hold g.mu). Best-effort:
// a failure only logs and never blocks the decision path, exactly like
// saveConvSessionMap. No-op when persistence is disabled.
func (g *approvalGate) persist(r *ApprovalRequest) {
dir := g.approvalDir()
if dir == "" {
return
}
if err := os.MkdirAll(dir, 0o700); err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 创建审批目录失败,跳过落盘:%v\n", err)
return
}
data, err := json.MarshalIndent(r, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 序列化审批失败,跳过落盘:%v\n", err)
return
}
path := filepath.Join(dir, sanitizeLockID(r.ID)+".json")
tmp, err := os.CreateTemp(dir, "approval-*.json.tmp")
if err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 创建审批临时文件失败,跳过落盘:%v\n", err)
return
}
tmpName := tmp.Name()
if err := tmp.Chmod(config.FilePerm); err != nil {
tmp.Close()
_ = os.Remove(tmpName)
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 设置审批文件权限失败,跳过落盘:%v\n", err)
return
}
if _, err := tmp.Write(data); err != nil {
tmp.Close()
_ = os.Remove(tmpName)
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 写入审批临时文件失败,跳过落盘:%v\n", err)
return
}
if err := tmp.Close(); err != nil {
_ = os.Remove(tmpName)
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 关闭审批临时文件失败,跳过落盘:%v\n", err)
return
}
if err := os.Rename(tmpName, path); err != nil {
_ = os.Remove(tmpName)
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 原子替换审批存档失败,跳过落盘:%v\n", err)
}
}
// loadAll reads every persisted request back into memory at startup. It is
// forgiving like loadConvSessionMap: a missing dir (first run) is silent, and a
// single corrupt file is skipped with a warning rather than aborting the load.
func (g *approvalGate) loadAll() {
dir := g.approvalDir()
if dir == "" {
return
}
entries, err := os.ReadDir(dir)
if err != nil {
if !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 读取审批目录失败,按空起:%v\n", err)
}
return
}
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
continue
}
raw, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 读取审批存档 %s 失败,跳过:%v\n", e.Name(), err)
continue
}
var r ApprovalRequest
if err := json.Unmarshal(raw, &r); err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval][warn] 审批存档 %s 已损坏,跳过:%v\n", e.Name(), err)
continue
}
if strings.TrimSpace(r.ID) == "" {
continue
}
g.reqs[r.ID] = &r
}
}
// ---- "Execution-class" request detection (simplified for the M2 slice) ----
//
// We do NOT build a general NLP intent classifier here (that is a later task).
// Instead the orchestrator instructs the agent to emit a structured marker for
// any action it would take, and we parse that marker out of the reply:
//
// [[ACTION:todo.create title="交方案" due="2026-06-14T18:00:00+08:00"]]
//
// Matched → route through the gate. No marker → ordinary Q&A, replied directly.
// The grammar is deliberately tiny: ACTION:<verb> followed by key="value"
// pairs. The only verb wired end-to-end in this slice is todo.create.
var actionMarkerRe = regexp.MustCompile(`\[\[ACTION:\s*([a-zA-Z0-9_.]+)\s*(.*?)\]\]`)
// actionKVRe captures key="value" (or key='value') pairs inside a marker.
var actionKVRe = regexp.MustCompile(`([a-zA-Z0-9_]+)\s*=\s*"([^"]*)"|([a-zA-Z0-9_]+)\s*=\s*'([^']*)'`)
// detectedAction is one parsed [[ACTION:...]] marker: its verb (e.g.
// "todo.create") and its key/value arguments.
type detectedAction struct {
Verb string
Args map[string]string
}
// parseActionMarker extracts the first [[ACTION:...]] marker from an agent
// reply, returning (action, cleaned-reply, found). cleanedReply is the reply
// with the marker stripped (and surrounding whitespace tidied) so it can be
// shown to a human without the machine syntax leaking through.
func parseActionMarker(reply string) (detectedAction, string, bool) {
loc := actionMarkerRe.FindStringSubmatchIndex(reply)
if loc == nil {
return detectedAction{}, reply, false
}
verb := strings.TrimSpace(reply[loc[2]:loc[3]])
argStr := reply[loc[4]:loc[5]]
act := detectedAction{Verb: verb, Args: map[string]string{}}
for _, m := range actionKVRe.FindAllStringSubmatch(argStr, -1) {
if m[1] != "" {
act.Args[m[1]] = m[2]
} else if m[3] != "" {
act.Args[m[3]] = m[4]
}
}
cleaned := strings.TrimSpace(reply[:loc[0]] + reply[loc[1]:])
return act, cleaned, true
}
// toPlannedAction maps a detected marker onto the structured command the gate
// will execute. It returns (action, summary, ok): ok is false for an unknown or
// malformed verb (e.g. todo.create without a title), so the orchestrator can
// fall back to a plain reply instead of submitting a no-op approval.
//
// ownerStaffID is the todo executor (the owner is who the reminder is for); the
// slice intentionally creates the todo for the owner, matching "create a todo
// for me" where "me" is the digital-twin owner.
func toPlannedAction(act detectedAction, ownerStaffID string) (plannedAction, string, bool) {
switch act.Verb {
case "todo.create":
title := strings.TrimSpace(act.Args["title"])
if title == "" {
title = strings.TrimSpace(act.Args["subject"])
}
if title == "" {
return plannedAction{}, "", false
}
vo := map[string]any{
"subject": title,
"executorIds": []string{ownerStaffID},
}
summary := fmt.Sprintf("创建待办:%s", title)
if due := strings.TrimSpace(act.Args["due"]); due != "" {
if ms, err := parseDueToMillis(due); err == nil {
vo["dueTime"] = ms
summary += fmt.Sprintf("(截止 %s)", due)
}
}
pa := plannedAction{
Product: "todo",
Tool: "create_personal_todo",
LegacyPath: "todo task create",
Params: map[string]any{"PersonalTodoCreateVO": vo},
}
return pa, summary, true
case "calendar.create":
title := firstNonEmpty(act.Args["title"], act.Args["summary"])
start := strings.TrimSpace(act.Args["start"])
end := strings.TrimSpace(act.Args["end"])
if title == "" || start == "" || end == "" {
return plannedAction{}, "", false
}
pa := plannedAction{
Product: "calendar",
Tool: "create_calendar_event",
LegacyPath: "calendar event create",
Params: map[string]any{
"summary": title,
"startDateTime": start,
"endDateTime": end,
},
}
return pa, fmt.Sprintf("创建日程:%s(%s ~ %s)", title, start, end), true
case "doc.create":
name := firstNonEmpty(act.Args["name"], act.Args["title"])
if name == "" {
return plannedAction{}, "", false
}
pa := plannedAction{
Product: "doc",
Tool: "create_document",
LegacyPath: "doc create",
Params: map[string]any{"name": name},
}
return pa, fmt.Sprintf("创建文档:%s", name), true
default:
return plannedAction{}, "", false
}
}
// firstNonEmpty returns the first trimmed non-empty string among the args.
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if t := strings.TrimSpace(v); t != "" {
return t
}
}
return ""
}
// approveWords / rejectWords are the whole-message replies the text-approval
// mode treats as the owner's decision. The match is on the ENTIRE trimmed
// message (case-insensitive) so a casual mention ("同意他的看法") never
// accidentally approves an action — only a bare "同意" / "拒绝" decides.
var (
approveWords = map[string]struct{}{
"同意": {}, "通过": {}, "批准": {}, "确认": {}, "同意执行": {},
"approve": {}, "ok": {}, "yes": {}, "y": {},
}
rejectWords = map[string]struct{}{
"拒绝": {}, "驳回": {}, "不行": {}, "不同意": {}, "取消": {}, "否决": {},
"reject": {}, "no": {}, "n": {},
}
)
// retryWords are the whole-message replies that flush the deferred backlog
// (the owner has recovered — e.g. logged dws in as themselves — and wants the
// held requests replayed).
var retryWords = map[string]struct{}{
"重试": {}, "恢复": {}, "补做": {}, "重新执行": {}, "继续": {},
"retry": {}, "resume": {},
}
// isRetryWord reports whether a whole message is a bare "flush the backlog"
// command.
func isRetryWord(msg string) bool {
_, ok := retryWords[strings.ToLower(strings.TrimSpace(msg))]
return ok
}
// parseDecisionWord classifies a whole message as an approve/reject decision.
// It returns (approve, ok): ok is false when the message is not a bare decision
// keyword, so the caller forwards it to the agent as an ordinary message.
func parseDecisionWord(msg string) (approve bool, ok bool) {
m := strings.ToLower(strings.TrimSpace(msg))
if _, yes := approveWords[m]; yes {
return true, true
}
if _, no := rejectWords[m]; no {
return false, true
}
return false, false
}
// classifyPlannedAction maps a planned command onto its read/write class so the
// gate can honor the "写类才拦" design: only a write (or Unknown — per the
// CmdClass safety contract) action needs the owner's sign-off; a read-class
// action is safe to let through without gating.
//
// It classifies on the human command path (LegacyPath, e.g. "todo task create")
// first, since that is exactly the space-joined segment shape ClassifyDwsCommand
// expects. When LegacyPath is absent or yields Unknown, it falls back to the
// product + RPC tool name (e.g. "todo" + "create_personal_todo"), whose leading
// verb token ("create") the classifier can still recognise.
func classifyPlannedAction(pa plannedAction) CmdClass {
if path := strings.TrimSpace(pa.LegacyPath); path != "" {
if c := ClassifyDwsCommand(strings.Fields(path)...); c != CmdClassUnknown {
return c
}
}
return ClassifyDwsCommand(pa.Product, pa.Tool)
}
// parseDueToMillis converts an ISO-8601 due string to epoch millis, accepting
// the common RFC3339 shapes the agent is asked to emit. Kept local to the gate
// so detection has no dependency on the cobra todo command's flag plumbing.
func parseDueToMillis(due string) (int64, error) {
for _, layout := range []string{time.RFC3339, "2006-01-02T15:04:05Z07:00", "2006-01-02T15:04:05", "2006-01-02 15:04", "2006-01-02"} {
if t, err := time.Parse(layout, due); err == nil {
return t.UnixMilli(), nil
}
}
return 0, fmt.Errorf("unrecognized due time %q", due)
}
+857
View File
@@ -0,0 +1,857 @@
// 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"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/card"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
)
// This file wires the confirmation gate to DingTalk:
// - approvalCardSender: the dependency-injected boundary that delivers the
// [Approve]/[Reject] card to the owner and updates it with the outcome.
// Tests inject a fake; production uses dingtalkApprovalCardSender (HTTP).
// - approvalOrchestrator: the connector-side glue. It owns the gate + sender +
// runner, decides whether an agent reply is an action request, drives the
// Submit → card → Await → execute → reply loop, and routes button callbacks
// into gate.Decide. connect_stream.go calls into it; it never imports stream
// internals back, so it stays unit-testable without a live connection.
// Button action constants. The card's two buttons each carry a fixed action
// id; the approval id and the decision travel as private action params so a
// callback can be associated and resolved without any server-side lookup table.
const (
approvalActionApprove = "dws_approval_approve"
approvalActionReject = "dws_approval_reject"
approvalParamID = "dwsApprovalId" // approval request id
approvalParamDecision = "dwsDecision" // "approve" | "reject"
approvalDecisionApprove = "approve"
approvalDecisionReject = "reject"
)
// approvalCardSender delivers and updates the owner-facing confirmation card.
// It is an interface so the orchestrator and its tests never touch the network:
// the real sender talks to the DingTalk card API, the fake records calls.
type approvalCardSender interface {
// SendApprovalCard delivers an interactive card with [Approve]/[Reject]
// buttons (each carrying req.ID + its decision in the action params) to the
// owner's 1:1 chat with the bot, returning the delivered card instance id
// (outTrackId) for later result updates and callback association.
SendApprovalCard(ctx context.Context, ownerUserID string, req *ApprovalRequest) (string, error)
// UpdateApprovalCard replaces the card body with the final outcome text
// (best-effort; an error must not fail the surrounding flow).
UpdateApprovalCard(ctx context.Context, outTrackID, text string) error
}
// approvalRunner is the subset of executor.Runner the orchestrator needs. Kept
// as a named alias so the dependency is explicit and easy to fake.
type approvalRunner interface {
Run(context.Context, executor.Invocation) (executor.Result, error)
}
// approvalReplier abstracts "send a plain text line back into the conversation"
// (the group reply after approve/reject). connect_stream.go supplies a closure
// over the chatbot replier + sessionWebhook; tests supply a recorder.
type approvalReplier func(ctx context.Context, convID, text string) error
// ownerNotifier sends a proactive 1:1 message to specific users (the owner, the
// requester), independent of any inbound sessionWebhook. Text approval needs it
// because the approval conversation (owner's 1:1 with the bot) is not the
// conversation the request arrived on, and because the decision can land minutes
// later when the original webhook is stale. *aiCardClient implements it.
type ownerNotifier interface {
sendOTOText(ctx context.Context, userIDs []string, text string) error
}
// auditSink records a terminal-state request to a durable, reviewable place
// (e.g. a DingTalk online sheet) so every action the twin takes is auditable
// beyond the local approvals JSON. Best-effort: a sink failure must never block
// or fail the action.
type auditSink interface {
record(ctx context.Context, req *ApprovalRequest)
}
// sheetAuditSink appends one row per action to a DingTalk online sheet (axls)
// via the sheet `append_rows` tool, run under the connector's (bot) identity.
// Columns: 时间 | 摘要 | 请求人 | 状态 | 批准人 | 是否自动 | 失败原因 | 单据ID.
type sheetAuditSink struct {
runner approvalRunner
nodeID string // axls doc id / URL
sheetID string // worksheet id or name (e.g. "Sheet1")
}
func (s *sheetAuditSink) record(ctx context.Context, req *ApprovalRequest) {
if s == nil || s.runner == nil || req == nil {
return
}
auto := ""
if req.AutoApproved {
auto = "自动"
}
decidedAt := ""
if !req.DecidedAt.IsZero() {
decidedAt = req.DecidedAt.Format("2006-01-02 15:04:05")
}
row := []any{
req.CreatedAt.Format("2006-01-02 15:04:05"),
req.Summary,
req.Requester,
string(req.State),
req.DecidedBy,
auto,
req.ExecErr,
req.ID,
decidedAt,
}
inv := executor.NewHelperInvocation("sheet append", "sheet", "append_rows", map[string]any{
"nodeId": s.nodeID,
"sheetId": s.sheetID,
"values": [][]any{row},
})
// The online-sheet API throttles (e.g. THREADPOOL_BUSY) under bursts, dropping
// an audit row on a transient error. Retry a few times with backoff so the
// trail stays complete; still best-effort — give up (log) after the last try.
var err error
for attempt := 1; attempt <= 3; attempt++ {
if _, err = s.runner.Run(ctx, inv); err == nil {
return
}
if attempt < 3 && isTransientSheetErr(err) {
time.Sleep(time.Duration(attempt) * 600 * time.Millisecond)
continue
}
break
}
if err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval][audit] 写审计表格失败(已重试)approvalId=%s: %v\n", req.ID, err)
}
}
// isTransientSheetErr reports whether a sheet-append error is a transient
// throttle/timeout worth retrying (vs. a permanent error like a bad node id).
func isTransientSheetErr(err error) bool {
if err == nil {
return false
}
s := strings.ToUpper(err.Error())
for _, sig := range []string{"BUSY", "THREADPOOL", "TIMEOUT", "RATE", "LIMIT", "TOO MANY", "503", "429"} {
if strings.Contains(s, sig) {
return true
}
}
return false
}
// approvalOrchestrator is the connector-side controller for the gate. It is
// constructed per connector with the owner's userId, the gate, the card sender
// and the runner. Zero owner / nil sender disables the gate (the connector then
// behaves exactly as before — plain Q&A).
type approvalOrchestrator struct {
gate *approvalGate
sender approvalCardSender
runner approvalRunner
ownerUserID string
awaitWindow time.Duration
// textMode swaps the interactive [Approve]/[Reject] card for a private
// text confirmation: the bot DMs the OWNER "X 请求执行……" and the owner
// replies "同意"/"拒绝" in their own 1:1 chat with the bot. The requester
// never sees the approval — they only get the final result. Used when no
// approval-card template is configured, so the gate works with zero
// card-platform setup. The decision is captured asynchronously (see
// handleOwnerDecision), not by blocking on Await.
textMode bool
// notifier delivers the proactive owner/requester 1:1 messages text mode
// needs (nil in card mode).
notifier ownerNotifier
// audit, when set, records every terminal-state request to a durable sink
// (e.g. a DingTalk online sheet) on top of the local approvals JSON. nil =
// local-file audit only.
audit auditSink
// allowedScopes is the role's capability allowlist (product names). When
// non-empty, an action whose product is not listed is refused before it ever
// reaches the gate, keeping the role in its lane. Empty = no restriction.
allowedScopes []string
// confirmPolicy governs how OTHERS' requests are confirmed: "manual" (ask
// every time, the default), "auto" (run without asking, still audited),
// "remember" (ask once per action verb then reuse). The owner's own requests
// always auto-run regardless.
confirmPolicy string
// remembered caches the owner's decision per action verb for the "remember"
// policy (verb → approved). Guarded by rememberMu.
rememberMu sync.Mutex
remembered map[string]bool
}
// gateDecision decides how to handle a write action: "auto" (run now), "ask"
// (route to the owner), or "reject" (a remembered rejection). The owner's own
// requests always auto-run. For others it follows confirmPolicy.
func (o *approvalOrchestrator) gateDecision(requester, verb string) string {
if strings.TrimSpace(requester) != "" && strings.TrimSpace(requester) == o.ownerUserID {
return "auto"
}
switch strings.ToLower(strings.TrimSpace(o.confirmPolicy)) {
case "auto":
return "auto"
case "remember":
o.rememberMu.Lock()
decided, ok := o.remembered[verb]
o.rememberMu.Unlock()
if !ok {
return "ask"
}
if decided {
return "auto"
}
return "reject"
default: // manual / empty
return "ask"
}
}
// rememberDecision records the owner's decision for an action verb so the
// "remember" policy can reuse it. No-op unless the policy is "remember".
func (o *approvalOrchestrator) rememberDecision(verb string, approved bool) {
if strings.ToLower(strings.TrimSpace(o.confirmPolicy)) != "remember" || strings.TrimSpace(verb) == "" {
return
}
o.rememberMu.Lock()
if o.remembered == nil {
o.remembered = make(map[string]bool)
}
o.remembered[verb] = approved
o.rememberMu.Unlock()
}
// scopeAllows reports whether the role may use the given product. An empty
// allowlist means no restriction (allow all).
func (o *approvalOrchestrator) scopeAllows(product string) bool {
if len(o.allowedScopes) == 0 {
return true
}
product = strings.ToLower(strings.TrimSpace(product))
for _, s := range o.allowedScopes {
if strings.ToLower(strings.TrimSpace(s)) == product {
return true
}
}
return false
}
// recordAudit writes the request's current (terminal) state to the audit sink,
// fetching the fresh snapshot so state/exec_err reflect the final outcome.
// No-op when no sink is configured; best-effort.
func (o *approvalOrchestrator) recordAudit(ctx context.Context, id string) {
if o == nil || o.audit == nil {
return
}
if r := o.gate.Get(id); r != nil {
o.audit.record(ctx, r)
}
}
// newApprovalOrchestrator builds the card-mode controller. awaitWindow caps how
// long the connector blocks for the owner's decision before giving up (the
// request stays Pending on disk, so a late tap still records and executes
// nothing twice).
func newApprovalOrchestrator(gate *approvalGate, sender approvalCardSender, runner approvalRunner, ownerUserID string) *approvalOrchestrator {
return &approvalOrchestrator{
gate: gate,
sender: sender,
runner: runner,
ownerUserID: strings.TrimSpace(ownerUserID),
awaitWindow: 10 * time.Minute,
}
}
// newTextApprovalOrchestrator builds the text-mode controller (no card sender).
// notifier delivers the private owner/requester messages. The owner confirms by
// replying "同意"/"拒绝" in their 1:1 chat with the bot; the decision is captured
// by handleOwnerDecision on the next inbound message, so handleReply must NOT
// block waiting for it.
func newTextApprovalOrchestrator(gate *approvalGate, runner approvalRunner, ownerUserID string, notifier ownerNotifier) *approvalOrchestrator {
o := newApprovalOrchestrator(gate, nil, runner, ownerUserID)
o.textMode = true
o.notifier = notifier
return o
}
// enabled reports whether the gate is active. Card mode needs an owner + a card
// sender; text mode needs an owner + a notifier to reach them privately.
func (o *approvalOrchestrator) enabled() bool {
if o == nil || o.ownerUserID == "" || o.gate == nil {
return false
}
if o.textMode {
return o.notifier != nil
}
return o.sender != nil
}
// agentSystemHint is appended to the forwarded prompt so the agent emits the
// structured action marker (see parseActionMarker) instead of executing
// anything itself. It is the simplified "intent detection" for the slice.
const agentSystemHint = "\n\n[系统提示] 如果用户的请求是要执行一个动作(而不是单纯提问)," +
"不要假装已经完成,而是在回复末尾用下面其中一个标记声明这个动作,由主人确认后再执行:\n" +
`· 建待办:[[ACTION:todo.create title="待办标题" due="2026-06-14T18:00:00+08:00"]](due 可省略)` + "\n" +
`· 建日程:[[ACTION:calendar.create title="日程标题" start="2026-06-20T10:00:00+08:00" end="2026-06-20T11:00:00+08:00"]]` + "\n" +
`· 建文档:[[ACTION:doc.create name="文档名"]]` + "\n" +
"时间一律用 ISO-8601(带时区)。如果只是普通提问,正常回答即可,不要输出任何标记。"
// decorateForActionDetection appends the action-marker instruction to a prompt
// when the gate is enabled. A no-op when disabled, so plain Q&A is untouched.
func (o *approvalOrchestrator) decorateForActionDetection(prompt string) string {
if !o.enabled() {
return prompt
}
return prompt + agentSystemHint
}
// handleReply is the orchestration hook the connector calls with the agent's
// raw reply. It returns (finalReply, handled): when handled is true the gate
// took over (it has already sent the card / will reply asynchronously via
// reply) and the connector must NOT send finalReply itself. When false the
// connector replies normally with finalReply (the marker, if any, is stripped).
//
// requester is the staffId who asked; convID is where the group answer goes;
// reply is the function used to post the approve/reject outcome back.
func (o *approvalOrchestrator) handleReply(ctx context.Context, requester, convID, agentReply string, reply approvalReplier) (string, bool) {
if !o.enabled() {
return agentReply, false
}
act, cleaned, found := parseActionMarker(agentReply)
if !found {
return agentReply, false // plain Q&A
}
pa, summary, ok := toPlannedAction(act, o.ownerUserID)
if !ok {
// Unknown/blank action: degrade to a plain reply (marker stripped) so a
// malformed marker never silently swallows the answer.
return cleaned, false
}
// Role scope: an action outside the role's capability allowlist is refused
// up front (never reaches the gate or the owner). The requester is told it is
// out of lane — this is a capability boundary, not an approval, so it is fine
// to surface to them.
if !o.scopeAllows(pa.Product) {
fmt.Fprintf(os.Stderr, "[connect][approval] 越权拦截:角色无 %q 能力,拒绝动作 %s\n", pa.Product, summary)
return fmt.Sprintf("(该数字员工没有「%s」能力,无法执行此操作:%s)", pa.Product, summary), false
}
// 写类才拦:route the gate-or-not decision through the read/write classifier
// instead of gating every detected marker. A definitively read-class action
// is safe and bypasses the gate (the marker is stripped and the reply goes
// out normally). Write — and Unknown, per the CmdClass safety contract — keep
// the owner's sign-off requirement.
if classifyPlannedAction(pa) == CmdClassRead {
return cleaned, false
}
// Confirmation strategy: owner-self always auto-runs; others follow
// confirmPolicy (manual=ask / auto=run / remember=reuse last decision).
decision := o.gateDecision(requester, act.Verb)
req := o.gate.Submit(ApprovalRequest{
Requester: requester,
ConvID: convID,
Summary: summary,
Verb: act.Verb,
Action: pa,
AutoApproved: decision == "auto",
})
switch decision {
case "auto":
// Asking IS the authorization (owner-self), or the policy pre-authorized
// it (auto / remembered-approve). Execute directly; still fully audited.
return o.autoApproveAndExecute(ctx, req, convID, reply)
case "reject":
// Remembered rejection for this action kind — decline without bothering
// the owner, and tell the requester.
o.gate.Decide(req.ID, false, o.ownerUserID)
o.recordAudit(ctx, req.ID)
fmt.Fprintf(os.Stderr, "[connect][approval] 记忆策略:%q 此前被拒,自动拒绝 approvalId=%s\n", act.Verb, req.ID)
return fmt.Sprintf("(主人此前已拒绝这类操作,本次未执行:%s)", summary), false
default: // "ask"
// Text mode: privately DM the owner and return immediately — the owner's
// "同意/拒绝" reply is captured asynchronously by handleOwnerDecision
// (blocking here would deadlock the per-conversation worker that must also
// process that reply). The requester (this conversation) sees nothing.
if o.textMode {
return o.handleReplyText(ctx, req)
}
return o.handleReplyCard(ctx, req, convID, reply)
}
}
// autoApproveAndExecute runs an owner's own request without a second
// confirmation, while still recording the full lifecycle (Decide by the owner →
// execute) so the on-disk approvals log audits it like any other action. It
// replies into the conversation the owner asked in (the inbound webhook is still
// fresh — the owner just messaged). Used for both card and text mode.
func (o *approvalOrchestrator) autoApproveAndExecute(ctx context.Context, req *ApprovalRequest, convID string, reply approvalReplier) (string, bool) {
decided, _ := o.gate.Decide(req.ID, true, o.ownerUserID)
if decided == nil {
decided = req
}
fmt.Fprintf(os.Stderr, "[connect][approval][audit] 主人自助操作,自动执行 approvalId=%s owner=%s: %s\n",
decided.ID, o.ownerUserID, decided.Summary)
out, execErr := o.execute(ctx, decided)
if execErr != nil {
// Do not lose it: hold for retry and tell the owner to recover. Most
// likely the connector's dws login is not the bot owner, so an
// owner-scoped action can't run yet.
o.gate.markDeferred(decided.ID, execErr.Error())
o.recordAudit(ctx, decided.ID)
o.notifyOwnerDeferred(ctx, decided, execErr)
if reply != nil {
_ = reply(ctx, convID, "收到,但现在没能直接完成(已记下,稍后会补做)。")
}
return "", true
}
o.gate.markExecuted(decided.ID)
o.recordAudit(ctx, decided.ID)
if reply != nil {
_ = reply(ctx, convID, "已为你完成:"+decided.Summary+"\n"+out)
}
return "", true
}
// notifyOwnerDeferred privately tells the owner that an action could not run now
// and is being held, with the likely cause and how to recover (log dws in as the
// bot owner, then reply "重试"). Best-effort.
func (o *approvalOrchestrator) notifyOwnerDeferred(ctx context.Context, req *ApprovalRequest, execErr error) {
if o.notifier == nil {
return
}
who := strings.TrimSpace(req.Requester)
if who == "" || who == o.ownerUserID {
who = "你"
}
msg := fmt.Sprintf("⚠️ %s 请求执行:%s\n但我现在没能以你的身份完成(很可能这台连接器的 dws 没有登录成你本人的账号)。\n"+
"已先记下,不会丢。把 dws 登录成机器人主人账号后会自动补做;想立即补做可回复「重试」。\n(错误:%s)",
who, req.Summary, truncateRunes(execErr.Error(), 120))
_ = o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, msg)
}
// handleReplyText privately DMs the OWNER the approval request and hands control
// back to the connector (handled=true). The requester sees nothing — the
// approval happens only between the owner and the bot. It never blocks: the
// owner's decision arrives later as an inbound message routed through
// handleOwnerDecision.
func (o *approvalOrchestrator) handleReplyText(ctx context.Context, req *ApprovalRequest) (string, bool) {
who := strings.TrimSpace(req.Requester)
if who == "" {
who = "有人"
}
prompt := fmt.Sprintf("🔔 %s 请求执行一个操作,需要你确认:\n%s\n回复「同意」执行,或「拒绝」取消。", who, req.Summary)
if err := o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, prompt); err != nil {
// Cannot reach the owner: the action does not run. Do NOT leak the
// approval to the requester — text mode's whole point is privacy — so
// just log and swallow (handled), leaving the request Pending on disk.
fmt.Fprintf(os.Stderr, "[connect][approval] 私聊主人 %s 失败,本次未执行: %v\n", o.ownerUserID, err)
return "", true
}
fmt.Fprintf(os.Stderr, "[connect][approval] 已私聊主人 %s 待确认 approvalId=%s requester=%s: %s\n",
o.ownerUserID, req.ID, req.Requester, req.Summary)
return "", true
}
// handleOwnerDecision intercepts an inbound message that is the OWNER replying
// "同意/拒绝" (in their own 1:1 chat with the bot) to the pending request. It
// decides, executes-or-declines, privately acks the owner, and sends the
// outcome to the original requester. Returns true when it consumed the message
// (so the connector skips forwarding it to the agent). A non-owner sender, a
// non-decision message, or no pending request all return false (ordinary
// message). Only active in text mode.
func (o *approvalOrchestrator) handleOwnerDecision(ctx context.Context, senderStaffID, text string) bool {
if o == nil || !o.textMode || !o.enabled() {
return false
}
if senderStaffID == "" || senderStaffID != o.ownerUserID {
return false
}
// "重试/恢复": the owner has recovered — flush the deferred backlog.
if isRetryWord(text) {
return o.flushDeferred(ctx)
}
approve, ok := parseDecisionWord(text)
if !ok {
return false
}
req := o.gate.latestPending()
if req == nil {
return false
}
decided, deciding := o.gate.Decide(req.ID, approve, senderStaffID)
if !deciding {
// Already decided (e.g. a double reply): consume the keyword, do not
// re-execute.
return decided != nil
}
// "remember" policy: cache this decision for the action kind so the next
// same-verb request reuses it without asking again.
o.rememberDecision(decided.Verb, approve)
if !decided.approved() {
o.recordAudit(ctx, decided.ID)
_ = o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, "好的,已拒绝,未执行。")
o.notifyRequester(ctx, decided, "你的请求未获主人批准,本次未执行。")
return true
}
out, execErr := o.execute(ctx, decided)
if execErr != nil {
// Approved but could not run now → hold for retry, tell the owner how to
// recover. The requester is NOT told it failed (their task is not lost).
o.gate.markDeferred(decided.ID, execErr.Error())
o.recordAudit(ctx, decided.ID)
o.notifyOwnerDeferred(ctx, decided, execErr)
return true
}
o.gate.markExecuted(decided.ID)
o.recordAudit(ctx, decided.ID)
_ = o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, "已同意并执行完成:"+decided.Summary)
o.notifyRequester(ctx, decided, "已为你完成:"+decided.Summary+"\n"+out)
return true
}
// flushDeferred replays the deferred backlog after the owner recovers. Each
// request is re-executed; on success it is marked executed and the original
// requester gets the outcome, on failure it stays deferred (still not lost).
// The owner gets a summary. Returns true (the "重试" message is always consumed).
func (o *approvalOrchestrator) flushDeferred(ctx context.Context) bool {
pending := o.gate.allDeferred()
if len(pending) == 0 {
_ = o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, "当前没有积压的请求。")
return true
}
done, stuck := o.flushDeferredOnce(ctx, pending)
// Manual "重试" always reports back (the owner asked), naming what was done.
var b strings.Builder
fmt.Fprintf(&b, "已补做 %d 个积压请求", len(done))
if len(done) > 0 {
b.WriteString(":\n")
for i, s := range done {
fmt.Fprintf(&b, "%d. %s\n", i+1, s)
}
} else {
b.WriteString("。")
}
if stuck > 0 {
fmt.Fprintf(&b, "仍有 %d 个未成功(身份可能还没对上,确认 dws 登录后再回复「重试」)。", stuck)
}
_ = o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, strings.TrimRight(b.String(), "\n"))
return true
}
// flushDeferredOnce re-executes each given deferred request once. Successful
// ones are marked executed and their requester is notified; failed ones stay
// deferred. Returns the completed summaries and the still-stuck count. Shared by
// the manual "重试" path and the background auto-retry.
func (o *approvalOrchestrator) flushDeferredOnce(ctx context.Context, pending []*ApprovalRequest) (done []string, stuck int) {
for _, req := range pending {
out, execErr := o.execute(ctx, req)
if execErr != nil {
o.gate.markDeferred(req.ID, execErr.Error())
o.recordAudit(ctx, req.ID)
stuck++
continue
}
o.gate.markExecuted(req.ID)
o.recordAudit(ctx, req.ID)
o.notifyRequester(ctx, req, "(已恢复)已为你完成:"+req.Summary+"\n"+out)
done = append(done, req.Summary)
}
return done, stuck
}
// autoFlushDeferred is the background-retry pass: it replays the backlog and
// messages the owner ONLY when something actually completed (so a periodic tick
// while the identity is still wrong stays silent — no spam). The requester is
// still notified per completed item inside flushDeferredOnce.
func (o *approvalOrchestrator) autoFlushDeferred(ctx context.Context) {
pending := o.gate.allDeferred()
if len(pending) == 0 {
return
}
done, _ := o.flushDeferredOnce(ctx, pending)
if len(done) == 0 {
return
}
var b strings.Builder
fmt.Fprintf(&b, "(已自动恢复)补做了 %d 个积压请求:\n", len(done))
for i, s := range done {
fmt.Fprintf(&b, "%d. %s\n", i+1, s)
}
_ = o.notifier.sendOTOText(ctx, []string{o.ownerUserID}, strings.TrimRight(b.String(), "\n"))
}
// startAutoRetry runs autoFlushDeferred on an interval until ctx is cancelled,
// so a deferred backlog drains by itself once the owner's identity comes back —
// no manual "重试" needed. A no-op when there is no notifier (card mode) or a
// non-positive interval.
func (o *approvalOrchestrator) startAutoRetry(ctx context.Context, interval time.Duration) {
if o == nil || o.notifier == nil || interval <= 0 {
return
}
go func() {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
o.autoFlushDeferred(ctx)
}
}
}()
}
// notifyRequester sends the outcome to the original requester, unless they are
// the owner themselves (who already got the owner-side ack — no need to double
// message). Best-effort.
func (o *approvalOrchestrator) notifyRequester(ctx context.Context, req *ApprovalRequest, text string) {
who := strings.TrimSpace(req.Requester)
if who == "" || who == o.ownerUserID {
return
}
_ = o.notifier.sendOTOText(ctx, []string{who}, text)
}
// handleReplyCard runs the interactive-card flow: deliver the [Approve]/[Reject]
// card to the owner, block for the decision, then execute-or-decline and report
// the outcome into the conversation.
func (o *approvalOrchestrator) handleReplyCard(ctx context.Context, req *ApprovalRequest, convID string, reply approvalReplier) (string, bool) {
outTrackID, err := o.sender.SendApprovalCard(ctx, o.ownerUserID, req)
if err != nil {
fmt.Fprintf(os.Stderr, "[connect][approval] 确认卡片投放失败: %v\n", err)
// Cannot ask the owner → tell the requester the gate could not engage,
// rather than silently executing or silently dropping.
return "(需要主人确认,但确认卡片发送失败,本次未执行)", false
}
o.gate.setOutTrackID(req.ID, outTrackID)
fmt.Fprintf(os.Stderr, "[connect][approval] 已向主人 %s 发送确认卡片 approvalId=%s outTrackId=%s: %s\n",
o.ownerUserID, req.ID, outTrackID, req.Summary)
// Block for the owner's decision off the connector's per-conversation
// worker is fine: the worker already serializes one conversation, and the
// gate persists so a restart mid-wait loses only the in-memory block.
decided, gotDecision := o.gate.Await(ctx, req.ID, o.awaitWindow)
if !gotDecision || decided == nil {
_ = reply(ctx, convID, "(等待主人确认超时,本次未执行)")
return "", true
}
if !decided.approved() {
o.recordAudit(ctx, decided.ID)
_ = o.sender.UpdateApprovalCard(ctx, decided.OutTrackID, "已拒绝:未执行。")
_ = reply(ctx, convID, "主人暂时没批准。")
return "", true
}
// Approved → the orchestrator runs the planned command directly (no agent
// round-trip), then reports the outcome to the group and the card.
out, execErr := o.execute(ctx, decided)
if execErr != nil {
o.gate.markFailed(decided.ID, execErr.Error())
o.recordAudit(ctx, decided.ID)
_ = o.sender.UpdateApprovalCard(ctx, decided.OutTrackID, "已同意,但执行失败:"+execErr.Error())
_ = reply(ctx, convID, "主人已同意,但执行失败:"+execErr.Error())
return "", true
}
o.gate.markExecuted(decided.ID)
o.recordAudit(ctx, decided.ID)
_ = o.sender.UpdateApprovalCard(ctx, decided.OutTrackID, "已同意并执行完成。")
_ = reply(ctx, convID, "主人已同意,已执行:"+decided.Summary+"\n"+out)
return "", true
}
// execute runs the request's planned action via the runner and returns a short
// human-readable result line. It is the only place the gate touches the
// executor, so adding a new approvable verb is a matter of toPlannedAction +
// the runner already supporting that tool.
func (o *approvalOrchestrator) execute(ctx context.Context, req *ApprovalRequest) (string, error) {
if o.runner == nil {
return "", fmt.Errorf("no runner configured")
}
inv := executor.NewHelperInvocation(req.Action.LegacyPath, req.Action.Product, req.Action.Tool, req.Action.Params)
res, err := o.runner.Run(ctx, inv)
if err != nil {
return "", err
}
if !res.Invocation.Implemented {
// The helper override was not wired at runtime (e.g. dry-run / discovery
// gap): surface it rather than claim success.
return "(动作已受理,但运行时未实际执行——请检查命令是否在当前环境可用)", nil
}
return "(待办已创建)", nil
}
// handleCardCallback maps a button tap to gate.Decide. It pulls the approval id
// and decision from the action params (primary association), falling back to the
// card instance id (OutTrackId) when the params are absent. Returns a card
// response that flips the buttons to a decided state. Safe to call repeatedly:
// a second tap after a decision is a no-op (Decide is idempotent).
func (o *approvalOrchestrator) handleCardCallback(ctx context.Context, req *card.CardRequest) (*card.CardResponse, error) {
if o == nil || o.gate == nil || req == nil {
return &card.CardResponse{}, nil
}
id, approve, ok := decodeCardAction(req)
if !ok {
fmt.Fprintf(os.Stderr, "[connect][approval] 卡片回调无法解析动作 outTrackId=%s\n", req.OutTrackId)
return &card.CardResponse{}, nil
}
if id == "" {
// No approval id in the params: associate by the card instance id.
if found := o.gate.findByOutTrackID(req.OutTrackId); found != nil {
id = found.ID
}
}
if id == "" {
fmt.Fprintf(os.Stderr, "[connect][approval] 卡片回调无法关联审批 outTrackId=%s\n", req.OutTrackId)
return &card.CardResponse{}, nil
}
decided, deciding := o.gate.Decide(id, approve, strings.TrimSpace(req.UserId))
verb := "同意"
if !approve {
verb = "拒绝"
}
if deciding {
fmt.Fprintf(os.Stderr, "[connect][approval] 主人 %s 点了[%s] approvalId=%s\n", req.UserId, verb, id)
} else if decided != nil {
fmt.Fprintf(os.Stderr, "[connect][approval] 审批 %s 已是终态(%s),忽略重复点击\n", id, decided.State)
}
// Echo the decision back into the card's private data so the renderer can
// show a decided state. Best-effort; the gate state is the source of truth.
return &card.CardResponse{
UserPrivateData: &card.CardDataDto{
CardParamMap: map[string]string{"dwsDecision": verb},
},
}, nil
}
// decodeCardAction extracts (approvalId, approve, ok) from a card callback. It
// prefers the explicit decision param, then the tapped action id, so the card
// can carry the decision either way. ok is false when neither identifies a
// decision (a non-approval card, or a malformed payload).
func decodeCardAction(req *card.CardRequest) (id string, approve bool, ok bool) {
id = strings.TrimSpace(req.GetActionString(approvalParamID))
decision := strings.TrimSpace(req.GetActionString(approvalParamDecision))
switch decision {
case approvalDecisionApprove:
return id, true, true
case approvalDecisionReject:
return id, false, true
}
// Fall back to which button was pressed (its action id).
for _, a := range req.CardActionData.CardPrivateData.ActionIdList {
switch strings.TrimSpace(a) {
case approvalActionApprove:
return id, true, true
case approvalActionReject:
return id, false, true
}
}
return id, false, false
}
// ---- Real (HTTP) card sender ----
// dingtalkApprovalCardSender delivers the interactive approval card via the
// DingTalk card API, reusing aiCardClient for auth + the create/deliver/update
// HTTP plumbing. The card template must define two buttons whose action params
// the connector fills in (approval id + decision); see the docstring on
// SendApprovalCard for the contract.
type dingtalkApprovalCardSender struct {
cli *aiCardClient
templateID string
}
// newDingtalkApprovalCardSender builds the real sender. An empty templateID
// returns nil: without an interactive-card template the connector cannot render
// buttons, so the caller must keep the gate disabled rather than deliver a card
// the owner cannot act on.
func newDingtalkApprovalCardSender(clientID, clientSecret, templateID string) approvalCardSender {
templateID = strings.TrimSpace(templateID)
if templateID == "" {
return nil
}
return &dingtalkApprovalCardSender{
cli: newAICardClient(clientID, clientSecret, templateID),
templateID: templateID,
}
}
// SendApprovalCard creates an interactive card instance and delivers it to the
// owner's 1:1 chat with the bot. The approval id and per-button decision are
// passed in cardData.cardParamMap so the template's [Approve]/[Reject] buttons
// echo them back as action params on tap (see decodeCardAction). Best-effort
// result-check via callChecked surfaces a per-target deliver failure that the
// card API hides inside an HTTP 200.
func (s *dingtalkApprovalCardSender) SendApprovalCard(ctx context.Context, ownerUserID string, req *ApprovalRequest) (string, error) {
outTrackID := "dws_approval_" + req.ID
create := map[string]any{
"cardTemplateId": s.templateID,
"outTrackId": outTrackID,
"cardData": map[string]any{
"cardParamMap": map[string]any{
"title": "需要你确认",
"summary": req.Summary,
"requester": req.Requester,
approvalParamID: req.ID,
"approveDecision": approvalDecisionApprove,
"rejectDecision": approvalDecisionReject,
"approveActionId": approvalActionApprove,
"rejectActionId": approvalActionReject,
"config": `{"autoLayout":true}`,
},
},
"callbackType": "STREAM",
"imRobotOpenSpaceModel": map[string]any{"supportForward": true},
}
if err := s.cli.call(ctx, http.MethodPost, "/v1.0/card/instances", create); err != nil {
return "", err
}
deliver := map[string]any{
"outTrackId": outTrackID,
"userIdType": 1,
"openSpaceId": "dtv1.card//IM_ROBOT." + ownerUserID,
"imRobotOpenDeliverModel": map[string]any{
"spaceType": "IM_ROBOT",
"robotCode": s.cli.clientID,
},
}
if err := s.cli.callChecked(ctx, http.MethodPost, "/v1.0/card/instances/deliver", deliver); err != nil {
return "", err
}
return outTrackID, nil
}
// UpdateApprovalCard rewrites the card's result line after a decision. It is
// best-effort: a stuck card is bad UX but must never fail the gate flow, so
// callers ignore the error.
func (s *dingtalkApprovalCardSender) UpdateApprovalCard(ctx context.Context, outTrackID, text string) error {
return s.cli.call(ctx, http.MethodPut, "/v1.0/card/instances", map[string]any{
"outTrackId": outTrackID,
"cardData": map[string]any{"cardParamMap": map[string]any{"result": text, "summary": text}},
"cardUpdateOptions": map[string]any{"updateCardDataByKey": true},
})
}
@@ -0,0 +1,863 @@
// 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"
"strings"
"sync"
"testing"
"time"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/card"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
)
// ---- fakes (no network, no real runner) ----
type fakeCardSender struct {
mu sync.Mutex
sent []*ApprovalRequest
updates []string
failSend bool
lastTrack string
}
func (f *fakeCardSender) SendApprovalCard(_ context.Context, _ string, req *ApprovalRequest) (string, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.failSend {
return "", context.DeadlineExceeded
}
f.sent = append(f.sent, req)
f.lastTrack = "track-" + req.ID
return f.lastTrack, nil
}
func (f *fakeCardSender) UpdateApprovalCard(_ context.Context, _, text string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.updates = append(f.updates, text)
return nil
}
// fakeRunner records the invocations it is asked to run and reports them as
// implemented (so the orchestrator treats them as executed).
type fakeRunner struct {
mu sync.Mutex
runs []executor.Invocation
fail bool // when true, Run returns an error (simulates identity not ready)
}
func (r *fakeRunner) Run(_ context.Context, inv executor.Invocation) (executor.Result, error) {
r.mu.Lock()
defer r.mu.Unlock()
r.runs = append(r.runs, inv)
if r.fail {
return executor.Result{}, context.DeadlineExceeded
}
inv.Implemented = true
return executor.Result{Invocation: inv}, nil
}
func (r *fakeRunner) setFail(v bool) { r.mu.Lock(); defer r.mu.Unlock(); r.fail = v }
func (r *fakeRunner) count() int { r.mu.Lock(); defer r.mu.Unlock(); return len(r.runs) }
// fakeNotifier records the proactive 1:1 messages text-mode approval sends to
// the owner and the requester.
type fakeNotifier struct {
mu sync.Mutex
sent []sentMsg
}
type sentMsg struct {
to []string
text string
}
func (n *fakeNotifier) sendOTOText(_ context.Context, userIDs []string, text string) error {
n.mu.Lock()
defer n.mu.Unlock()
n.sent = append(n.sent, sentMsg{to: append([]string(nil), userIDs...), text: text})
return nil
}
// toUser reports whether any recorded message was sent to userID.
func (n *fakeNotifier) toUser(userID string) bool {
n.mu.Lock()
defer n.mu.Unlock()
for _, m := range n.sent {
for _, u := range m.to {
if u == userID {
return true
}
}
}
return false
}
func (n *fakeNotifier) count() int { n.mu.Lock(); defer n.mu.Unlock(); return len(n.sent) }
// cardClickReq builds a card callback as DingTalk delivers it: the tapped
// button's action id plus its private params (approval id + decision).
func cardClickReq(outTrackID, approvalID, decision, actionID, userID string) *card.CardRequest {
return &card.CardRequest{
OutTrackId: outTrackID,
UserId: userID,
CardActionData: card.PrivateCardActionData{
CardPrivateData: card.CardPrivateData{
ActionIdList: []string{actionID},
Params: map[string]any{
approvalParamID: approvalID,
approvalParamDecision: decision,
},
},
},
}
}
// TestDecodeCardAction verifies the action parser pulls the approval id and the
// approve/reject decision from a button tap, via params and via the action id
// fallback.
func TestDecodeCardAction(t *testing.T) {
approve := cardClickReq("t1", "appr-1", approvalDecisionApprove, approvalActionApprove, "owner")
id, ok2, ok := decodeCardAction(approve)
if !ok || !ok2 || id != "appr-1" {
t.Fatalf("approve decode: id=%q approve=%v ok=%v", id, ok2, ok)
}
reject := cardClickReq("t2", "appr-2", approvalDecisionReject, approvalActionReject, "owner")
id, ok2, ok = decodeCardAction(reject)
if !ok || ok2 || id != "appr-2" {
t.Fatalf("reject decode: id=%q approve=%v ok=%v", id, ok2, ok)
}
// Decision param missing → fall back to the tapped action id.
fallback := &card.CardRequest{
OutTrackId: "t3",
CardActionData: card.PrivateCardActionData{
CardPrivateData: card.CardPrivateData{
ActionIdList: []string{approvalActionApprove},
Params: map[string]any{approvalParamID: "appr-3"},
},
},
}
id, ok2, ok = decodeCardAction(fallback)
if !ok || !ok2 || id != "appr-3" {
t.Fatalf("fallback decode: id=%q approve=%v ok=%v", id, ok2, ok)
}
// A non-approval card → not ok.
if _, _, ok := decodeCardAction(&card.CardRequest{OutTrackId: "x"}); ok {
t.Fatal("non-approval card should not decode as a decision")
}
}
// TestHandleCardCallback_DrivesDecide verifies a button callback flips the gate
// state and that an approval id missing from params is recovered by outTrackId.
func TestHandleCardCallback_DrivesDecide(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("c1")
o := newApprovalOrchestrator(gate, &fakeCardSender{}, &fakeRunner{}, "owner")
app := gate.Submit(ApprovalRequest{Summary: "x"})
gate.setOutTrackID(app.ID, "track-x")
// Callback carries no approval id in params → associate by outTrackId.
req := &card.CardRequest{
OutTrackId: "track-x",
UserId: "owner",
CardActionData: card.PrivateCardActionData{
CardPrivateData: card.CardPrivateData{ActionIdList: []string{approvalActionApprove}},
},
}
if _, err := o.handleCardCallback(context.Background(), req); err != nil {
t.Fatalf("callback err: %v", err)
}
if got := gate.Get(app.ID); !got.approved() {
t.Fatalf("state = %s, want approved after approve tap", got.State)
}
}
// TestHandleReply_RejectDoesNotExecute is the reject-path guarantee: a rejected
// approval must NOT run the planned command.
func TestHandleReply_RejectDoesNotExecute(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("c2")
sender := &fakeCardSender{}
runner := &fakeRunner{}
o := newApprovalOrchestrator(gate, sender, runner, "owner")
o.awaitWindow = time.Second
var replies []string
var rmu sync.Mutex
reply := func(_ context.Context, _, text string) error {
rmu.Lock()
replies = append(replies, text)
rmu.Unlock()
return nil
}
// The owner rejects shortly after the card is sent.
go func() {
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
sender.mu.Lock()
n := len(sender.sent)
var id string
if n > 0 {
id = sender.sent[0].ID
}
sender.mu.Unlock()
if id != "" {
gate.Decide(id, false, "owner")
return
}
time.Sleep(5 * time.Millisecond)
}
}()
agentReply := `好的。[[ACTION:todo.create title="交方案"]]`
out, handled := o.handleReply(context.Background(), "requester", "conv-1", agentReply, reply)
if !handled {
t.Fatal("an action reply must be handled by the gate")
}
if out != "" {
t.Fatalf("handled reply should return empty connector reply, got %q", out)
}
if runner.count() != 0 {
t.Fatalf("reject path must NOT execute, runner ran %d times", runner.count())
}
if gate.Get(gate.list()[0].ID).State != approvalRejected {
t.Fatal("request should be rejected")
}
rmu.Lock()
joined := strings.Join(replies, " | ")
rmu.Unlock()
if !strings.Contains(joined, "没批准") {
t.Fatalf("reject reply not posted: %q", joined)
}
}
// TestToPlannedAction_Actions covers the action verbs the twin can execute:
// each maps to the right product/tool, and missing required args degrade to
// "not an action" (ok=false) so a malformed marker never submits a no-op.
func TestToPlannedAction_Actions(t *testing.T) {
cases := []struct {
name string
act detectedAction
wantOK bool
wantProduct string
wantTool string
}{
{"todo", detectedAction{Verb: "todo.create", Args: map[string]string{"title": "交方案"}}, true, "todo", "create_personal_todo"},
{"calendar", detectedAction{Verb: "calendar.create", Args: map[string]string{"title": "评审会", "start": "2026-06-20T10:00:00+08:00", "end": "2026-06-20T11:00:00+08:00"}}, true, "calendar", "create_calendar_event"},
{"calendar missing time", detectedAction{Verb: "calendar.create", Args: map[string]string{"title": "评审会"}}, false, "", ""},
{"doc", detectedAction{Verb: "doc.create", Args: map[string]string{"name": "周报"}}, true, "doc", "create_document"},
{"doc missing name", detectedAction{Verb: "doc.create", Args: map[string]string{}}, false, "", ""},
{"unknown verb", detectedAction{Verb: "drive.delete", Args: map[string]string{}}, false, "", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
pa, summary, ok := toPlannedAction(tc.act, "owner")
if ok != tc.wantOK {
t.Fatalf("ok=%v want %v", ok, tc.wantOK)
}
if !ok {
return
}
if pa.Product != tc.wantProduct || pa.Tool != tc.wantTool {
t.Fatalf("got %s/%s want %s/%s", pa.Product, pa.Tool, tc.wantProduct, tc.wantTool)
}
if summary == "" {
t.Fatal("summary should not be empty for a valid action")
}
// Every twin action is write-class → must be gated.
if classifyPlannedAction(pa) != CmdClassWrite {
t.Fatalf("%s should classify as write (gated), got %s", tc.name, classifyPlannedAction(pa))
}
})
}
}
// TestClassifyPlannedAction verifies the gate's read/write bridge: it classifies
// on the human command path first and falls back to product + RPC tool name.
func TestClassifyPlannedAction(t *testing.T) {
cases := []struct {
name string
pa plannedAction
want CmdClass
}{
{
name: "write via legacy path",
pa: plannedAction{Product: "todo", Tool: "create_personal_todo", LegacyPath: "todo task create"},
want: CmdClassWrite,
},
{
name: "read via legacy path",
pa: plannedAction{Product: "todo", Tool: "list_personal_todo", LegacyPath: "todo task list"},
want: CmdClassRead,
},
{
name: "empty legacy path falls back to product+tool",
pa: plannedAction{Product: "todo", Tool: "create_personal_todo"},
want: CmdClassWrite,
},
{
name: "unrecognised path falls back to tool verb",
pa: plannedAction{Product: "todo", Tool: "delete_personal_todo", LegacyPath: "todo xyz123"},
want: CmdClassWrite,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := classifyPlannedAction(tc.pa); got != tc.want {
t.Fatalf("classifyPlannedAction(%+v) = %s, want %s", tc.pa, got, tc.want)
}
})
}
}
// TestHandleReply_ReadClassBypassesGate proves the "写类才拦" wiring: when the
// planned command classifies as read-only, the gate does not engage — no card is
// sent, nothing runs, and the cleaned reply goes out normally (handled=false).
// We force the todo.create path to read-class via an override so the test drives
// the real handleReply → classifyPlannedAction path end to end.
func TestHandleReply_ReadClassBypassesGate(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
SetCmdClassOverride("todo task create", CmdClassRead)
defer SetCmdClassOverride("todo task create", CmdClassUnknown)
gate := newApprovalGate("c3")
sender := &fakeCardSender{}
runner := &fakeRunner{}
o := newApprovalOrchestrator(gate, sender, runner, "owner")
reply := func(_ context.Context, _, _ string) error { return nil }
agentReply := `好的,已为你查到。[[ACTION:todo.create title="交方案"]]`
out, handled := o.handleReply(context.Background(), "requester", "conv-1", agentReply, reply)
if handled {
t.Fatal("a read-class action must NOT be handled by the gate")
}
if !strings.Contains(out, "已为你查到") || strings.Contains(out, "[[ACTION") {
t.Fatalf("read-class reply should be the cleaned text without the marker, got %q", out)
}
sender.mu.Lock()
nSent := len(sender.sent)
sender.mu.Unlock()
if nSent != 0 {
t.Fatalf("read-class action must not send a confirmation card, sent %d", nSent)
}
if runner.count() != 0 {
t.Fatalf("read-class action must not execute, runner ran %d times", runner.count())
}
if len(gate.list()) != 0 {
t.Fatalf("read-class action must not create an approval request, got %d", len(gate.list()))
}
}
// TestParseDecisionWord checks whole-message decision parsing: a bare keyword
// decides, anything else (including a keyword embedded in a sentence) does not.
func TestParseDecisionWord(t *testing.T) {
cases := []struct {
in string
wantApprove bool
wantOk bool
}{
{"同意", true, true},
{" 同意 ", true, true},
{"通过", true, true},
{"Yes", true, true},
{"OK", true, true},
{"拒绝", false, true},
{"no", false, true},
{"不同意", false, true},
{"同意他的看法", false, false}, // embedded, not a bare decision
{"帮我创建个待办", false, false},
{"", false, false},
}
for _, tc := range cases {
gotApprove, gotOk := parseDecisionWord(tc.in)
if gotOk != tc.wantOk || (tc.wantOk && gotApprove != tc.wantApprove) {
t.Fatalf("parseDecisionWord(%q) = (%v,%v), want (%v,%v)", tc.in, gotApprove, gotOk, tc.wantApprove, tc.wantOk)
}
}
}
// TestPendingForConv finds the pending request for a conversation and stops
// returning it once decided.
func TestPendingForConv(t *testing.T) {
gate := newApprovalGate("") // in-memory
a := gate.Submit(ApprovalRequest{ConvID: "c1", Summary: "a"})
gate.Submit(ApprovalRequest{ConvID: "c2", Summary: "b"})
if got := gate.pendingForConv("c1"); got == nil || got.ID != a.ID {
t.Fatalf("pendingForConv(c1) = %v, want request %s", got, a.ID)
}
if got := gate.pendingForConv("none"); got != nil {
t.Fatalf("pendingForConv(none) = %v, want nil", got)
}
gate.Decide(a.ID, true, "owner")
if got := gate.pendingForConv("c1"); got != nil {
t.Fatalf("decided request must not be pending, got %v", got)
}
}
// TestHandleReply_TextMode_OwnerApproves is the private text-approval happy
// path: an action privately DMs the OWNER (the requester sees nothing, no
// execution yet); a non-owner "同意" is ignored; the owner's "同意" — sent from
// their own chat, NOT the request conversation — decides and executes.
func TestHandleReply_TextMode_OwnerApproves(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ct1")
runner := &fakeRunner{}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
// A group requester (not the owner) asks for an action.
out, handled := o.handleReply(context.Background(), "requester", "conv-group", `好的。[[ACTION:todo.create title="交方案"]]`, nil)
if !handled || out != "" {
t.Fatalf("text-mode action: handled=%v out=%q, want handled with empty out (requester sees nothing)", handled, out)
}
if runner.count() != 0 {
t.Fatalf("must not execute before the owner decides, ran %d", runner.count())
}
if len(gate.list()) != 1 {
t.Fatalf("expected one pending request, got %d", len(gate.list()))
}
// The approval prompt went privately to the OWNER, never to the requester.
if !notifier.toUser("owner") {
t.Fatalf("approval prompt was not DMed to the owner: %+v", notifier.sent)
}
if notifier.toUser("requester") {
t.Fatal("the requester must NOT be notified of the approval")
}
// A non-owner saying 同意 must not decide or execute.
if o.handleOwnerDecision(context.Background(), "intruder", "同意") {
t.Fatal("non-owner must not be able to approve")
}
if runner.count() != 0 {
t.Fatalf("non-owner approval must not execute, ran %d", runner.count())
}
// The owner saying 同意 decides and executes; the requester then gets the
// outcome.
if !o.handleOwnerDecision(context.Background(), "owner", "同意") {
t.Fatal("owner approval must be consumed")
}
if runner.count() != 1 {
t.Fatalf("owner approval must execute exactly once, ran %d", runner.count())
}
if gate.list()[0].State != approvalExecuted {
t.Fatalf("request state = %s, want executed", gate.list()[0].State)
}
if !notifier.toUser("requester") {
t.Fatal("the requester should get the final outcome after execution")
}
}
// TestHandleReply_TextMode_OwnerSelfAutoApproves: when the requester IS the
// owner, the action runs immediately with NO confirmation round-trip, but is
// still recorded (auto_approved=true, decided-by owner, executed) for audit.
func TestHandleReply_TextMode_OwnerSelfAutoApproves(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctself")
runner := &fakeRunner{}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
var replies []string
reply := func(_ context.Context, _, text string) error { replies = append(replies, text); return nil }
// The OWNER asks for the action themselves.
out, handled := o.handleReply(context.Background(), "owner", "conv-owner", `好。[[ACTION:todo.create title="自己的待办"]]`, reply)
if !handled || out != "" {
t.Fatalf("owner self-request: handled=%v out=%q", handled, out)
}
// Executed immediately — no second confirmation asked.
if runner.count() != 1 {
t.Fatalf("owner self-request must execute immediately, ran %d", runner.count())
}
if notifier.count() != 0 {
t.Fatalf("owner self-request must NOT send an approval DM, sent %d", notifier.count())
}
// Still recorded for audit: auto_approved + executed + decided by owner.
rec := gate.list()[0]
if !rec.AutoApproved || rec.State != approvalExecuted || rec.DecidedBy != "owner" {
t.Fatalf("audit record wrong: autoApproved=%v state=%s decidedBy=%s", rec.AutoApproved, rec.State, rec.DecidedBy)
}
if !strings.Contains(strings.Join(replies, "|"), "已为你完成") {
t.Fatalf("owner should get the result, replies=%v", replies)
}
}
// fakeAudit records the requests handed to the audit sink.
type fakeAudit struct {
mu sync.Mutex
recs []*ApprovalRequest
}
func (a *fakeAudit) record(_ context.Context, req *ApprovalRequest) {
a.mu.Lock()
defer a.mu.Unlock()
cp := *req
a.recs = append(a.recs, &cp)
}
func (a *fakeAudit) count() int { a.mu.Lock(); defer a.mu.Unlock(); return len(a.recs) }
// TestAudit_RecordsTerminalOutcomes verifies the audit sink gets one terminal
// record per action: an auto-executed owner request, and an approved request.
func TestAudit_RecordsTerminalOutcomes(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("cta")
audit := &fakeAudit{}
o := newTextApprovalOrchestrator(gate, &fakeRunner{}, "owner", &fakeNotifier{})
o.audit = audit
reply := func(_ context.Context, _, _ string) error { return nil }
// Owner self-request → auto-executed → audited once, as executed.
o.handleReply(context.Background(), "owner", "conv-o", `[[ACTION:todo.create title="自己"]]`, reply)
if audit.count() != 1 {
t.Fatalf("auto-exec must produce one audit record, got %d", audit.count())
}
if audit.recs[0].State != approvalExecuted || !audit.recs[0].AutoApproved {
t.Fatalf("auto audit record: state=%s auto=%v", audit.recs[0].State, audit.recs[0].AutoApproved)
}
// Someone else's request, approved by the owner → audited as executed.
o.handleReply(context.Background(), "requester", "conv-g", `[[ACTION:todo.create title="别人"]]`, reply)
if audit.count() != 1 {
t.Fatal("a pending (not yet decided) request must not be audited yet")
}
o.handleOwnerDecision(context.Background(), "owner", "同意")
if audit.count() != 2 {
t.Fatalf("owner approval must produce a second audit record, got %d", audit.count())
}
if audit.recs[1].State != approvalExecuted || audit.recs[1].DecidedBy != "owner" {
t.Fatalf("approved audit record: state=%s decidedBy=%s", audit.recs[1].State, audit.recs[1].DecidedBy)
}
}
// TestDeferredExecution_HoldsAndRetries is the graceful-degradation path: when
// execution fails (identity not ready), the request is DEFERRED (not lost, not
// failed), the owner is privately notified; after the owner recovers and replies
// "重试", the backlog is replayed, executes, and the requester gets the result.
func TestDeferredExecution_HoldsAndRetries(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctdef")
runner := &fakeRunner{fail: true} // identity not ready → execution fails
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
// A non-owner request, approved by the owner, but execution fails → deferred.
o.handleReply(context.Background(), "requester", "conv-g", `[[ACTION:todo.create title="待恢复"]]`, nil)
if !o.handleOwnerDecision(context.Background(), "owner", "同意") {
t.Fatal("owner approval must be consumed")
}
rec := gate.list()[0]
if rec.State != approvalDeferred {
t.Fatalf("failed execution must DEFER (not fail), got state=%s", rec.State)
}
// Owner was told to recover; requester was NOT told it failed (task not lost).
if !notifier.toUser("owner") {
t.Fatal("owner should be notified of the deferred action")
}
if notifier.toUser("requester") {
t.Fatal("requester must NOT be told it failed — their task is held, not lost")
}
// A bare non-retry word from the owner should pass through (not consumed).
if o.handleOwnerDecision(context.Background(), "owner", "在吗") {
t.Fatal("ordinary owner message must not be consumed")
}
// Owner recovers (identity now works) and replies "重试" → backlog flushes.
runner.setFail(false)
if !o.handleOwnerDecision(context.Background(), "owner", "重试") {
t.Fatal("retry word must be consumed")
}
if gate.list()[0].State != approvalExecuted {
t.Fatalf("after retry the deferred request must execute, got %s", gate.list()[0].State)
}
if !notifier.toUser("requester") {
t.Fatal("requester should get the outcome after the backlog is flushed")
}
}
// TestConfirmPolicy_Auto: a non-owner request runs without asking under "auto".
func TestConfirmPolicy_Auto(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctauto2")
runner := &fakeRunner{}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
o.confirmPolicy = "auto"
_, handled := o.handleReply(context.Background(), "someone", "c1", `[[ACTION:todo.create title="x"]]`, func(_ context.Context, _, _ string) error { return nil })
if !handled {
t.Fatal("auto policy should handle (run) the action")
}
if runner.count() != 1 {
t.Fatalf("auto policy must execute without asking, ran %d", runner.count())
}
if gate.list()[0].State != approvalExecuted {
t.Fatalf("state=%s want executed", gate.list()[0].State)
}
}
// TestConfirmPolicy_Manual: a non-owner request asks the owner (default).
func TestConfirmPolicy_Manual(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctman")
runner := &fakeRunner{}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier) // no policy = manual
o.handleReply(context.Background(), "someone", "c1", `[[ACTION:todo.create title="x"]]`, nil)
if runner.count() != 0 {
t.Fatal("manual policy must NOT execute before the owner decides")
}
if gate.list()[0].State != approvalPending {
t.Fatalf("state=%s want pending (awaiting owner)", gate.list()[0].State)
}
if !notifier.toUser("owner") {
t.Fatal("manual policy should DM the owner for approval")
}
}
// TestConfirmPolicy_Remember: ask once per verb, then reuse the decision.
func TestConfirmPolicy_Remember(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctrem")
runner := &fakeRunner{}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
o.confirmPolicy = "remember"
// First todo.create from a non-owner → asks (pending).
o.handleReply(context.Background(), "someone", "c1", `[[ACTION:todo.create title="第一次"]]`, nil)
if gate.latestPending() == nil {
t.Fatal("first request should ask the owner")
}
// Owner approves → remembered, executes.
o.handleOwnerDecision(context.Background(), "owner", "同意")
if runner.count() != 1 {
t.Fatalf("approved request should execute, ran %d", runner.count())
}
// Second todo.create → reused decision, auto-runs (no new pending).
_, handled := o.handleReply(context.Background(), "someone", "c2", `[[ACTION:todo.create title="第二次"]]`, func(_ context.Context, _, _ string) error { return nil })
if !handled || runner.count() != 2 {
t.Fatalf("remembered approve should auto-run the 2nd request, handled=%v ran=%d", handled, runner.count())
}
}
// TestScopeEnforcement: an action outside the role's allowlist is refused up
// front (the requester is told, nothing reaches the gate); an in-scope action
// proceeds; an empty allowlist allows everything.
func TestScopeEnforcement(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctscope")
runner := &fakeRunner{}
o := newTextApprovalOrchestrator(gate, runner, "owner", &fakeNotifier{})
o.allowedScopes = []string{"todo"} // HR-style: only todo
// doc.create is out of scope → refused, NOT gated, requester told.
out, handled := o.handleReply(context.Background(), "requester", "c1", `[[ACTION:doc.create name="周报"]]`, nil)
if handled {
t.Fatal("out-of-scope action must not be handled by the gate")
}
if !strings.Contains(out, "没有") || !strings.Contains(out, "doc") {
t.Fatalf("requester should be told it's out of scope, got %q", out)
}
if len(gate.list()) != 0 {
t.Fatal("out-of-scope action must not create an approval request")
}
// todo.create is in scope → proceeds (owner self-request auto-executes).
o.handleReply(context.Background(), "owner", "c2", `[[ACTION:todo.create title="排期"]]`, func(_ context.Context, _, _ string) error { return nil })
if len(gate.list()) != 1 {
t.Fatalf("in-scope action should be processed, got %d requests", len(gate.list()))
}
// scopeAllows: empty allowlist = allow all.
o.allowedScopes = nil
if !o.scopeAllows("anything") {
t.Fatal("empty allowlist must allow all products")
}
}
// TestAutoFlushDeferred verifies the background retry: silent while the identity
// is still wrong (no spam), and it drains + notifies once execution works.
func TestAutoFlushDeferred(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctauto")
runner := &fakeRunner{fail: true}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
// Defer one (identity not ready).
o.handleReply(context.Background(), "owner", "conv-o", `[[ACTION:todo.create title="自动恢复"]]`, func(_ context.Context, _, _ string) error { return nil })
deferNotices := notifier.count() // the deferred DM
if gate.list()[0].State != approvalDeferred {
t.Fatalf("want deferred, got %s", gate.list()[0].State)
}
// Auto-retry while still failing → stays deferred, NO new owner message.
o.autoFlushDeferred(context.Background())
if gate.list()[0].State != approvalDeferred {
t.Fatal("should still be deferred while identity is wrong")
}
if notifier.count() != deferNotices {
t.Fatalf("auto-retry must stay silent when nothing completes (sent %d, was %d)", notifier.count(), deferNotices)
}
// Identity recovers → auto-retry drains it and notifies once.
runner.setFail(false)
o.autoFlushDeferred(context.Background())
if gate.list()[0].State != approvalExecuted {
t.Fatalf("auto-retry should execute once identity is back, got %s", gate.list()[0].State)
}
notifier.mu.Lock()
last := notifier.sent[len(notifier.sent)-1].text
notifier.mu.Unlock()
if !strings.Contains(last, "已自动恢复") || !strings.Contains(last, "自动恢复") {
t.Fatalf("owner should get an auto-recovery notice, got %q", last)
}
}
// TestIsTransientSheetErr distinguishes retryable throttles from permanent errors.
func TestIsTransientSheetErr(t *testing.T) {
for _, e := range []string{"system error: THREADPOOL_BUSY", "server busy", "request timeout", "HTTP 429 too many requests"} {
if !isTransientSheetErr(fmt.Errorf("%s", e)) {
t.Fatalf("%q should be transient", e)
}
}
for _, e := range []string{"invalid nodeId", "permission denied", "not found"} {
if isTransientSheetErr(fmt.Errorf("%s", e)) {
t.Fatalf("%q should NOT be transient", e)
}
}
if isTransientSheetErr(nil) {
t.Fatal("nil is not transient")
}
}
// TestFlushDeferred_ReportsCompletedItems verifies the owner gets a per-item
// completion list (not just a count) when the backlog is flushed.
func TestFlushDeferred_ReportsCompletedItems(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ctflush")
runner := &fakeRunner{fail: true}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
o.handleReply(context.Background(), "owner", "conv-o", `[[ACTION:todo.create title="我的待办"]]`, func(_ context.Context, _, _ string) error { return nil })
if gate.list()[0].State != approvalDeferred {
t.Fatalf("want deferred, got %s", gate.list()[0].State)
}
runner.setFail(false)
o.handleOwnerDecision(context.Background(), "owner", "重试")
notifier.mu.Lock()
var last string
if len(notifier.sent) > 0 {
last = notifier.sent[len(notifier.sent)-1].text
}
notifier.mu.Unlock()
if !strings.Contains(last, "已补做 1 个") || !strings.Contains(last, "创建待办:我的待办") {
t.Fatalf("flush summary should list the completed item, got %q", last)
}
}
// TestIsRetryWord checks whole-message retry-keyword matching.
func TestIsRetryWord(t *testing.T) {
for _, w := range []string{"重试", " 恢复 ", "retry", "继续"} {
if !isRetryWord(w) {
t.Fatalf("%q should be a retry word", w)
}
}
for _, w := range []string{"重试一下他的方案", "", "你好"} {
if isRetryWord(w) {
t.Fatalf("%q should NOT be a retry word", w)
}
}
}
// TestHandleReply_TextMode_OwnerRejects: the owner's "拒绝" declines without
// executing.
func TestHandleReply_TextMode_OwnerRejects(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ct2")
runner := &fakeRunner{}
notifier := &fakeNotifier{}
o := newTextApprovalOrchestrator(gate, runner, "owner", notifier)
o.handleReply(context.Background(), "requester", "conv-group", `[[ACTION:todo.create title="x"]]`, nil)
if !o.handleOwnerDecision(context.Background(), "owner", "拒绝") {
t.Fatal("owner rejection must be consumed")
}
if runner.count() != 0 {
t.Fatalf("rejection must NOT execute, ran %d", runner.count())
}
if gate.list()[0].State != approvalRejected {
t.Fatalf("state = %s, want rejected", gate.list()[0].State)
}
}
// TestHandleOwnerDecision_NotADecision: an ordinary owner message (not a bare
// keyword) is not consumed, so it still reaches the agent.
func TestHandleOwnerDecision_NotADecision(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("ct3")
o := newTextApprovalOrchestrator(gate, &fakeRunner{}, "owner", &fakeNotifier{})
gate.Submit(ApprovalRequest{ConvID: "conv-1", Summary: "x", State: approvalPending})
if o.handleOwnerDecision(context.Background(), "owner", "顺便帮我查下天气") {
t.Fatal("a non-decision owner message must pass through to the agent")
}
}
// TestLatestPending returns the newest pending request across conversations.
func TestLatestPending(t *testing.T) {
gate := newApprovalGate("")
gate.Submit(ApprovalRequest{ConvID: "c1", Summary: "old", CreatedAt: time.Unix(100, 0)})
newer := gate.Submit(ApprovalRequest{ConvID: "c2", Summary: "new", CreatedAt: time.Unix(200, 0)})
if got := gate.latestPending(); got == nil || got.ID != newer.ID {
t.Fatalf("latestPending = %v, want newest %s", got, newer.ID)
}
gate.Decide(newer.ID, true, "owner")
if got := gate.latestPending(); got == nil || got.Summary != "old" {
t.Fatalf("after deciding newest, latestPending should fall back to the older pending, got %v", got)
}
}
// list is a tiny test helper to enumerate the gate's requests.
func (g *approvalGate) list() []*ApprovalRequest {
g.mu.Lock()
defer g.mu.Unlock()
out := make([]*ApprovalRequest, 0, len(g.reqs))
for _, r := range g.reqs {
cp := *r
out = append(out, &cp)
}
return out
}
@@ -0,0 +1,129 @@
// 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"
"strings"
"sync"
"testing"
"time"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/card"
)
// TestApprovalGate_EndToEndApprove exercises the whole vertical slice with no
// network: an agent reply carrying a todo.create marker → Submit → approval card
// → owner taps [Approve] via a card callback → the planned todo.create runs on
// the (fake) runner → the group is told it was executed.
//
// It mirrors exactly what runStreamConnector wires together, but with the card
// sender and runner faked, so the orchestration logic is verified end to end.
func TestApprovalGate_EndToEndApprove(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
gate := newApprovalGate("e2e-client")
sender := &fakeCardSender{}
runner := &fakeRunner{}
o := newApprovalOrchestrator(gate, sender, runner, "owner-007")
o.awaitWindow = 2 * time.Second
var replies []string
var rmu sync.Mutex
groupReply := func(_ context.Context, _, text string) error {
rmu.Lock()
replies = append(replies, text)
rmu.Unlock()
return nil
}
// Simulate the owner tapping [Approve] once the card has been delivered, via
// the exact card-callback path the Stream router would invoke.
go func() {
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
sender.mu.Lock()
track := sender.lastTrack
sender.mu.Unlock()
if track != "" {
_, _ = o.handleCardCallback(context.Background(), &card.CardRequest{
OutTrackId: track,
UserId: "owner-007",
CardActionData: card.PrivateCardActionData{
CardPrivateData: card.CardPrivateData{
ActionIdList: []string{approvalActionApprove},
Params: map[string]any{
approvalParamDecision: approvalDecisionApprove,
},
},
},
})
return
}
time.Sleep(5 * time.Millisecond)
}
}()
// This is the agent reply for: 群里有人 @机器人 "帮我建个待办:明天下班前交方案".
agentReply := `收到,我来帮你建这个待办。[[ACTION:todo.create title="明天下班前交方案" due="2026-06-14T18:00:00+08:00"]]`
out, handled := o.handleReply(context.Background(), "requester-zhang", "group-conv-9", agentReply, groupReply)
if !handled {
t.Fatal("action reply must be handled by the gate")
}
if out != "" {
t.Fatalf("handled reply returns empty connector reply, got %q", out)
}
// The planned command ran exactly once, and it was todo.create.
if runner.count() != 1 {
t.Fatalf("expected exactly 1 execution, got %d", runner.count())
}
runner.mu.Lock()
inv := runner.runs[0]
runner.mu.Unlock()
if inv.CanonicalProduct != "todo" || inv.Tool != "create_personal_todo" {
t.Fatalf("executed wrong command: %s.%s", inv.CanonicalProduct, inv.Tool)
}
vo, _ := inv.Params["PersonalTodoCreateVO"].(map[string]any)
if vo == nil || vo["subject"] != "明天下班前交方案" {
t.Fatalf("todo subject wrong: %+v", vo)
}
// State machine reached Executed.
final := gate.list()[0]
if final.State != approvalExecuted {
t.Fatalf("final state = %s, want executed", final.State)
}
// The owner saw [Approve]/[Reject] (the card was delivered), and the group
// got the executed-confirmation reply.
if len(sender.sent) != 1 {
t.Fatalf("expected 1 card delivered, got %d", len(sender.sent))
}
rmu.Lock()
joined := strings.Join(replies, " | ")
rmu.Unlock()
if !strings.Contains(joined, "已同意") || !strings.Contains(joined, "已执行") {
t.Fatalf("group not told of execution: %q", joined)
}
t.Logf("E2E approve chain OK:\n"+
" card delivered to owner: %v\n"+
" approval state: %s\n"+
" command executed: %s.%s (subject=%q)\n"+
" group replies: %s",
sender.sent[0].Summary, final.State, inv.CanonicalProduct, inv.Tool, vo["subject"], joined)
}
+206
View File
@@ -0,0 +1,206 @@
// 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"
"testing"
"time"
)
// TestApprovalGate_SubmitPending verifies Submit lands a request in Pending with
// a generated id and timestamp.
func TestApprovalGate_SubmitPending(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
g := newApprovalGate("client-A")
req := g.Submit(ApprovalRequest{Requester: "u1", ConvID: "cid", Summary: "do thing"})
if req.ID == "" {
t.Fatal("Submit should assign an ID")
}
if req.State != approvalPending {
t.Fatalf("state = %s, want pending", req.State)
}
if req.CreatedAt.IsZero() {
t.Fatal("CreatedAt should be set")
}
if got := g.Get(req.ID); got == nil || got.State != approvalPending {
t.Fatalf("Get returned %+v, want pending", got)
}
}
// TestApprovalGate_DecideApproveReject covers both decision branches and the
// idempotency of a second decision.
func TestApprovalGate_DecideApproveReject(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
g := newApprovalGate("client-B")
app := g.Submit(ApprovalRequest{Summary: "approve me"})
decided, deciding := g.Decide(app.ID, true, "owner")
if !deciding || decided.State != approvalApproved || decided.DecidedBy != "owner" {
t.Fatalf("approve decision = %+v deciding=%v", decided, deciding)
}
// Second decision is a no-op.
if _, again := g.Decide(app.ID, false, "owner"); again {
t.Fatal("second Decide must not be the deciding call")
}
if g.Get(app.ID).State != approvalApproved {
t.Fatal("state must stay approved after a redundant reject")
}
rej := g.Submit(ApprovalRequest{Summary: "reject me"})
d2, _ := g.Decide(rej.ID, false, "owner")
if d2.State != approvalRejected {
t.Fatalf("reject decision = %s, want rejected", d2.State)
}
// Unknown id.
if _, ok := g.Decide("nope", true, "owner"); ok {
t.Fatal("deciding unknown id should report false")
}
}
// TestApprovalGate_AwaitWakesOnDecide verifies Await blocks until a decision and
// returns the decided snapshot.
func TestApprovalGate_AwaitWakesOnDecide(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
g := newApprovalGate("client-C")
app := g.Submit(ApprovalRequest{Summary: "wait for me"})
go func() {
time.Sleep(20 * time.Millisecond)
g.Decide(app.ID, true, "owner")
}()
decided, got := g.Await(context.Background(), app.ID, time.Second)
if !got || decided == nil || !decided.approved() {
t.Fatalf("Await = %+v got=%v, want approved", decided, got)
}
}
// TestApprovalGate_AwaitTimeout verifies a timeout leaves the request Pending and
// reports no decision.
func TestApprovalGate_AwaitTimeout(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
g := newApprovalGate("client-D")
app := g.Submit(ApprovalRequest{Summary: "nobody decides"})
decided, got := g.Await(context.Background(), app.ID, 10*time.Millisecond)
if got {
t.Fatal("Await should report no decision on timeout")
}
if decided.State != approvalPending {
t.Fatalf("state = %s, want pending after timeout", decided.State)
}
}
// TestApprovalGate_PersistAndRecover verifies a Pending request written by one
// gate is recovered by a fresh gate over the same config dir (restart survival).
func TestApprovalGate_PersistAndRecover(t *testing.T) {
dir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", dir)
g1 := newApprovalGate("client-E")
app := g1.Submit(ApprovalRequest{Requester: "u9", Summary: "survive restart",
Action: plannedAction{Product: "todo", Tool: "create_personal_todo"}})
g1.setOutTrackID(app.ID, "card-123")
// Fresh gate, same dir → must recover the request and its outTrackId.
g2 := newApprovalGate("client-E")
got := g2.Get(app.ID)
if got == nil {
t.Fatal("request not recovered from disk")
}
if got.State != approvalPending || got.Summary != "survive restart" {
t.Fatalf("recovered = %+v", got)
}
if got.OutTrackID != "card-123" {
t.Fatalf("recovered outTrackId = %q, want card-123", got.OutTrackID)
}
if byTrack := g2.findByOutTrackID("card-123"); byTrack == nil || byTrack.ID != app.ID {
t.Fatal("findByOutTrackID failed after recovery")
}
}
// TestApprovalGate_NoPersistWhenEmptyClient verifies an empty clientId keeps the
// gate in memory only (no disk writes, mirroring the session store).
func TestApprovalGate_NoPersistWhenEmptyClient(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
g := newApprovalGate("")
if g.approvalDir() != "" {
t.Fatal("empty clientId must disable persistence")
}
app := g.Submit(ApprovalRequest{Summary: "memory only"})
if g.Get(app.ID) == nil {
t.Fatal("in-memory request should still be retrievable")
}
}
// TestParseActionMarker covers the simplified execution-class detection: a
// marker is extracted with its args and stripped from the human-facing reply,
// while plain Q&A is left untouched.
func TestParseActionMarker(t *testing.T) {
reply := `好的,我来帮你建。[[ACTION:todo.create title="交方案" due="2026-06-14T18:00:00+08:00"]]`
act, cleaned, found := parseActionMarker(reply)
if !found {
t.Fatal("marker should be detected")
}
if act.Verb != "todo.create" {
t.Fatalf("verb = %s", act.Verb)
}
if act.Args["title"] != "交方案" || act.Args["due"] != "2026-06-14T18:00:00+08:00" {
t.Fatalf("args = %+v", act.Args)
}
if cleaned != "好的,我来帮你建。" {
t.Fatalf("cleaned = %q", cleaned)
}
if _, _, f := parseActionMarker("这是一个普通问题的回答,没有动作。"); f {
t.Fatal("plain reply must not match")
}
}
// TestToPlannedAction verifies the marker → command mapping, including the
// reject of a malformed (titleless) action.
func TestToPlannedAction(t *testing.T) {
pa, summary, ok := toPlannedAction(detectedAction{
Verb: "todo.create",
Args: map[string]string{"title": "交方案", "due": "2026-06-14T18:00:00+08:00"},
}, "owner-1")
if !ok {
t.Fatal("valid todo.create should map")
}
if pa.Product != "todo" || pa.Tool != "create_personal_todo" {
t.Fatalf("planned = %+v", pa)
}
vo, _ := pa.Params["PersonalTodoCreateVO"].(map[string]any)
if vo == nil || vo["subject"] != "交方案" {
t.Fatalf("vo = %+v", vo)
}
if _, hasDue := vo["dueTime"]; !hasDue {
t.Fatal("due should be parsed into dueTime")
}
execs, _ := vo["executorIds"].([]string)
if len(execs) != 1 || execs[0] != "owner-1" {
t.Fatalf("executors = %+v, want [owner-1]", execs)
}
if summary == "" {
t.Fatal("summary should be non-empty")
}
if _, _, ok := toPlannedAction(detectedAction{Verb: "todo.create", Args: map[string]string{}}, "o"); ok {
t.Fatal("titleless action must be rejected")
}
if _, _, ok := toPlannedAction(detectedAction{Verb: "unknown.verb"}, "o"); ok {
t.Fatal("unknown verb must be rejected")
}
}
+578
View File
@@ -0,0 +1,578 @@
// 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 (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
)
// AI-card reply support for the stream-bridge channels: instead of a plain
// one-shot text message, the bot answers with a DingTalk AI card that shows a
// "Thinking" state while the local agent runs and flips to done with the
// final content — the same UX the hermes official pipeline provides.
//
// The experience combines the two verified official implementations:
// - the "🤔Thinking/🥳Done" chip on the user's message is a text emotion
// (message reaction), ported from the hermes gateway adapter;
// - the card itself uses the openclaw connector's public template and
// payload contract (msgContent + flowStatus state machine), because card
// templates are app-scoped: hermes' own template (c629162a-...) renders
// "内容加载失败" for any other app — confirmed by A/B on the same robot.
//
// Call order: create instance → deliver → flowStatus INPUTING → streaming
// frames (throttled, isFull) → finalize frame → flowStatus FINISHED.
const (
// defaultAICardTemplateID is the public AI-card streaming template the
// openclaw connector ships with (messaging/card.ts) — a best-effort
// default. Card templates are APP-SCOPED: the reliable production setup is
// registering an AI-card template under YOUR app in the DingTalk developer
// console (the hermes docs prescribe exactly this) and passing its ID via
// --card-template / DWS_CARD_TEMPLATE. Using another app's template (e.g.
// hermes' c629162a-...) renders "内容加载失败" — confirmed by live A/B on
// the same robot.
defaultAICardTemplateID = "02fcf2f4-5e02-4a85-b672-46d1f715543e.schema"
// aiCardMaxContent mirrors hermes' MAX_MESSAGE_LENGTH truncation.
aiCardMaxContent = 20000
// flowStatus states of the AI-card template (openclaw AICardStatus).
aiCardFlowInputing = "2"
aiCardFlowFinished = "3"
aiCardFlowFailed = "5"
)
// dingtalkCardAPIBase is a var so tests can point it at a httptest server.
var dingtalkCardAPIBase = "https://api.dingtalk.com"
// aiCardClient creates and finalizes AI cards using the robot's own
// credentials (clientId/clientSecret → app access token, cached ~2h).
type aiCardClient struct {
clientID string
clientSecret string
templateID string
httpClient *http.Client
mu sync.Mutex
token string
tokenExp time.Time
}
// newAICardClient builds the reply-UX client. With an empty templateID the
// client does emotions only (Thinking/Done chips) and no cards — mirroring
// hermes, where cards are an opt-in enabled by configuring a template ID and
// replies stay plain text otherwise. This avoids the silent-failure trap:
// card APIs all succeed even when the client cannot render the template.
func newAICardClient(clientID, clientSecret, templateID string) *aiCardClient {
templateID = strings.TrimSpace(templateID)
return &aiCardClient{
clientID: clientID,
clientSecret: clientSecret,
templateID: templateID,
httpClient: &http.Client{Timeout: 15 * time.Second},
}
}
// hasTemplate reports whether card replies are enabled (a template is
// configured); without one the client is used for emotions only.
func (c *aiCardClient) hasTemplate() bool { return c.templateID != "" }
// aiCardInstance is one delivered card, identified by its outTrackId.
type aiCardInstance struct {
outTrackID string
// inputing marks that the INPUTING flow state was already set (once per
// card, before the first streaming frame).
inputing bool
// lastFrame timestamps the last non-final streaming frame for the
// per-card throttle (the streaming endpoint 403s on <~500ms updates;
// hermes uses 800ms).
lastFrame time.Time
}
// accessToken returns a cached app access token, refreshing 5 minutes early.
func (c *aiCardClient) accessToken(ctx context.Context) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.token != "" && time.Now().Before(c.tokenExp.Add(-5*time.Minute)) {
return c.token, nil
}
body, err := json.Marshal(map[string]string{
"appKey": c.clientID,
"appSecret": c.clientSecret,
})
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
dingtalkCardAPIBase+"/v1.0/oauth2/accessToken", bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 400 {
return "", fmt.Errorf("accessToken HTTP %d: %s", resp.StatusCode, truncateRunes(string(raw), 200))
}
var parsed struct {
AccessToken string `json:"accessToken"`
ExpireIn int64 `json:"expireIn"`
}
if err := json.Unmarshal(raw, &parsed); err != nil || parsed.AccessToken == "" {
return "", fmt.Errorf("accessToken parse failed: %s", truncateRunes(string(raw), 200))
}
c.token = parsed.AccessToken
expire := parsed.ExpireIn
if expire <= 0 {
expire = 7200
}
c.tokenExp = time.Now().Add(time.Duration(expire) * time.Second)
return c.token, nil
}
// call performs one authenticated card-API request and fails on non-2xx.
func (c *aiCardClient) call(ctx context.Context, method, path string, payload map[string]any) error {
_, err := c.callRaw(ctx, method, path, payload)
return err
}
func (c *aiCardClient) callRaw(ctx context.Context, method, path string, payload map[string]any) (string, error) {
token, err := c.accessToken(ctx)
if err != nil {
return "", err
}
body, err := json.Marshal(payload)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, method, dingtalkCardAPIBase+path, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-acs-dingtalk-access-token", token)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 400 {
return "", fmt.Errorf("%s %s HTTP %d: %s", method, path, resp.StatusCode, truncateRunes(string(raw), 300))
}
// Surface every response body in the connector log: the card APIs report
// business-level failures inside a 200, and a silently dropped frame is
// otherwise indistinguishable from the client-side "内容加载失败".
fmt.Fprintf(os.Stderr, "[connect][card][api] %s %s -> %d %s\n", method, path, resp.StatusCode, truncateRunes(string(raw), 200))
return string(raw), nil
}
// sendOTOText sends a plain-text 1:1 (robot → person) message to each userId,
// using the robot batch one-to-one send API. It is how the connector reaches a
// specific person (e.g. the digital-twin owner) proactively, outside the
// ephemeral inbound sessionWebhook — the webhook can only reply into the
// conversation a message arrived on, and may be stale by the time an owner
// decides. Auth reuses the app access token (the bot's own clientId/secret), so
// the message is sent as the bot in its own org.
func (c *aiCardClient) sendOTOText(ctx context.Context, userIDs []string, text string) error {
if len(userIDs) == 0 {
return nil
}
param, err := json.Marshal(map[string]string{"content": text})
if err != nil {
return err
}
return c.call(ctx, http.MethodPost, "/v1.0/robot/oToMessages/batchSend", map[string]any{
"robotCode": c.clientID,
"userIds": userIDs,
"msgKey": "sampleText",
"msgParam": string(param),
})
}
// createAndDeliver creates an AI-card instance and delivers it into the
// conversation the message came from. With empty content the template
// renders the "Thinking" state while the agent runs. Group messages deliver
// to IM_GROUP (with robotCode), 1:1 to IM_ROBOT (spaceType only) — exactly
// the hermes deliver shapes.
func (c *aiCardClient) createAndDeliver(ctx context.Context, data *chatbot.BotCallbackDataModel) (*aiCardInstance, error) {
outTrackID := "dws_" + uuid.NewString()
create := map[string]any{
"cardTemplateId": c.templateID,
"outTrackId": outTrackID,
"cardData": map[string]any{
"cardParamMap": map[string]any{"config": `{"autoLayout":true}`},
},
"callbackType": "STREAM",
"imGroupOpenSpaceModel": map[string]any{"supportForward": true},
"imRobotOpenSpaceModel": map[string]any{"supportForward": true},
}
if err := c.call(ctx, http.MethodPost, "/v1.0/card/instances", create); err != nil {
return nil, err
}
deliver := map[string]any{
"outTrackId": outTrackID,
"userIdType": 1,
}
if data.ConversationType == "2" { // group chat
deliver["openSpaceId"] = "dtv1.card//IM_GROUP." + data.ConversationId
deliver["imGroupOpenDeliverModel"] = map[string]any{"robotCode": c.clientID}
} else { // 1:1 chat with the robot
if data.SenderStaffId == "" {
return nil, fmt.Errorf("missing senderStaffId for 1:1 card delivery")
}
deliver["openSpaceId"] = "dtv1.card//IM_ROBOT." + data.SenderStaffId
deliver["imRobotOpenDeliverModel"] = map[string]any{
"spaceType": "IM_ROBOT",
"robotCode": c.clientID,
"extension": map[string]any{"dynamicSummary": "true"},
}
}
if err := c.callChecked(ctx, http.MethodPost, "/v1.0/card/instances/deliver", deliver); err != nil {
return nil, err
}
return &aiCardInstance{outTrackID: outTrackID}, nil
}
// callChecked is call() plus a business-level result check: the deliver API
// reports per-target failures INSIDE a HTTP 200 (e.g. {"result":[{"success":
// false,"errorMsg":"spaceId is illegal"}],"success":true}) — observed live.
func (c *aiCardClient) callChecked(ctx context.Context, method, path string, payload map[string]any) error {
raw, err := c.callRaw(ctx, method, path, payload)
if err != nil {
return err
}
if strings.Contains(raw, `"success":false`) {
return fmt.Errorf("%s %s business failure: %s", method, path, truncateRunes(raw, 300))
}
return nil
}
// streamingUpdate sends one full content frame to the card.
func (c *aiCardClient) streamingUpdate(ctx context.Context, card *aiCardInstance, content string, finalize, isError bool) error {
if r := []rune(content); len(r) > aiCardMaxContent {
content = string(r[:aiCardMaxContent])
}
return c.call(ctx, http.MethodPut, "/v1.0/card/streaming", map[string]any{
"outTrackId": card.outTrackID,
"guid": uuid.NewString(),
"key": "msgContent",
"content": content,
"isFull": true,
"isFinalize": finalize,
"isError": isError,
})
}
// aiCardFrameGap spaces the deliver → content → finalize frames. Delivering
// and finalizing back-to-back races the client's card fetch and intermittently
// renders "内容加载失败" (the very failure that killed the #407 card attempt);
// a short gap lets the client subscribe before the closing frame lands.
var aiCardFrameGap = 500 * time.Millisecond
// cardContentParams is the cardParamMap contract of the openclaw template.
func cardContentParams(flowStatus, content string) map[string]any {
return map[string]any{
"flowStatus": flowStatus,
"msgContent": content,
"staticMsgContent": "",
"sys_full_json_obj": `{"order":["msgContent"]}`,
"config": `{"autoLayout":true}`,
}
}
// setFlowStatus updates the card instance's flow state (openclaw contract:
// INPUTING before streaming, FINISHED after the finalize frame).
func (c *aiCardClient) setFlowStatus(ctx context.Context, card *aiCardInstance, flowStatus, content string, byKey bool) error {
payload := map[string]any{
"outTrackId": card.outTrackID,
"cardData": map[string]any{"cardParamMap": cardContentParams(flowStatus, content)},
}
if byKey {
payload["cardUpdateOptions"] = map[string]any{"updateCardDataByKey": true}
}
return c.call(ctx, http.MethodPut, "/v1.0/card/instances", payload)
}
// aiCardFrameThrottle is the minimum spacing between non-final streaming
// frames per card (hermes uses 800ms; the endpoint 403s on rapid updates).
var aiCardFrameThrottle = 800 * time.Millisecond
// streamFrame pushes one full-content frame into the card, switching the card
// to INPUTING before the first frame. Non-final frames are throttled per
// card — a skipped frame is fine because every frame carries the full text so
// far (isFull). The final frame always goes out.
func (c *aiCardClient) streamFrame(ctx context.Context, card *aiCardInstance, content string, final bool) error {
normalized := normalizeForCard(content)
if !card.inputing {
if err := c.setFlowStatus(ctx, card, aiCardFlowInputing, normalized, false); err != nil {
return err
}
card.inputing = true
card.lastFrame = time.Now()
}
if !final {
if time.Since(card.lastFrame) < aiCardFrameThrottle {
return nil // skip; a later frame re-sends the full text
}
}
if err := c.streamingUpdate(ctx, card, normalized, final, false); err != nil {
return err
}
card.lastFrame = time.Now()
return nil
}
// finish closes the card: the finalized streaming frame plus the FINISHED
// flow state. A failure leaves the card spinning, so callers must treat an
// error as "fall back to a plain webhook reply" (after markFailed).
func (c *aiCardClient) finish(ctx context.Context, card *aiCardInstance, content string) error {
normalized := normalizeForCard(content)
if err := c.streamFrame(ctx, card, content, true); err != nil {
return err
}
if err := sleepCtx(ctx, aiCardFrameGap); err != nil {
return err
}
return c.setFlowStatus(ctx, card, aiCardFlowFinished, normalized, true)
}
// finalize is the one-shot path for channels without incremental output:
// INPUTING → final frame → FINISHED in one call.
func (c *aiCardClient) finalize(ctx context.Context, card *aiCardInstance, content string) error {
if err := sleepCtx(ctx, aiCardFrameGap); err != nil {
return err
}
return c.finish(ctx, card, content)
}
// repair re-pushes the finalize frame once, a few seconds after the reply.
// hermes streams many frames so a client that misses one recovers on the
// next; our burst of two frames has no such retry, and a missed fetch shows
// "内容加载失败" until a new frame arrives. Best-effort by design.
func (c *aiCardClient) repair(ctx context.Context, card *aiCardInstance, content string) {
if err := sleepCtx(ctx, aiCardRepairDelay); err != nil {
return
}
_ = c.setFlowStatus(ctx, card, aiCardFlowFinished, normalizeForCard(content), true)
}
// aiCardRepairDelay is how long after finalize the repair frame goes out.
var aiCardRepairDelay = 3 * time.Second
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// markFailed best-effort closes a stuck card in the error state so the
// Thinking chip does not spin forever when finalize failed and the reply
// went out as a plain message instead. Errors are ignored by design.
func (c *aiCardClient) markFailed(ctx context.Context, card *aiCardInstance) {
_ = c.setFlowStatus(ctx, card, aiCardFlowFailed, "", true)
}
// ---- Message reactions (the "🤔Thinking" chip) ----
//
// The status chip attached to the user's message is NOT a card: it is a text
// emotion (message reaction) — hermes fires "🤔Thinking" on receive and swaps
// it for "🥳Done" when the reply lands (gateway/platforms/dingtalk.py,
// _send_emotion / _fire_done_reaction). During thinking there is no card at
// all; the card only appears with the final content.
const (
emotionThinking = "🤔Thinking"
emotionDone = "🥳Done"
)
// sendEmotion adds (or recalls) a text reaction on the user's message.
// Failures are logged by callers at most — the reaction is decoration, never
// worth failing the reply over. Payload contract per the robot_1_0 SDK:
// POST /v1.0/robot/emotion/reply | /v1.0/robot/emotion/recall.
func (c *aiCardClient) sendEmotion(ctx context.Context, conversationID, msgID, name string, recall bool) error {
if conversationID == "" || msgID == "" {
return fmt.Errorf("emotion needs openConversationId and openMsgId")
}
path := "/v1.0/robot/emotion/reply"
if recall {
path = "/v1.0/robot/emotion/recall"
}
return c.call(ctx, http.MethodPost, path, map[string]any{
"robotCode": c.clientID,
"openConversationId": conversationID,
"openMsgId": msgID,
"emotionType": 2,
"emotionName": name,
"textEmotion": map[string]any{
"emotionId": "2659900",
"emotionName": name,
"text": name,
"backgroundId": "im_bg_1",
},
})
}
// markThinking fires the "🤔Thinking" chip on the user's message.
func (c *aiCardClient) markThinking(ctx context.Context, conversationID, msgID string) error {
return c.sendEmotion(ctx, conversationID, msgID, emotionThinking, false)
}
// swapThinkingToDone replaces the chip with "🥳Done" after the reply landed.
// Best-effort by design (mirrors hermes' fire-and-forget swap).
func (c *aiCardClient) swapThinkingToDone(ctx context.Context, conversationID, msgID string) {
_ = c.sendEmotion(ctx, conversationID, msgID, emotionThinking, true)
_ = c.sendEmotion(ctx, conversationID, msgID, emotionDone, false)
}
// ---- Markdown normalization for the AI-card renderer ----
//
// Ported from openclaw's normalizeForCard (messaging/card.ts): the 02fcf2f4
// template renders <br> as visual line breaks in plain text, needs real \n
// inside code fences and before Markdown block syntax, and a blank line
// before tables.
var (
cardTableDividerRe = regexp.MustCompile(`^\s*\|?\s*:?-+:?\s*(\|?\s*:?-+:?\s*)+\|?\s*$`)
cardTableRowRe = regexp.MustCompile(`^\s*\|?.*\|.*\|?\s*$`)
cardBlockStartRe = regexp.MustCompile(`^(\s{0,3}(?:[-*+]|\d+[.)])[ ])|(\s{0,3}\|)|(\s{0,3}#{1,6}\s)|(\s{0,3}(?:[-*_])\s*(?:[-*_])\s*(?:[-*_]))`)
cardFenceRe = regexp.MustCompile("^\\s{0,3}```")
cardQuoteRe = regexp.MustCompile(`^\s{0,3}>\s?`)
)
func normalizeCardLineEndings(text string) string {
text = strings.ReplaceAll(text, "\r\n", "\n")
return strings.ReplaceAll(text, "\r", "\n")
}
// ensureCardTableBlankLines inserts a blank line before a table header that
// directly follows non-table text, which the card renderer requires.
func ensureCardTableBlankLines(text string) string {
lines := strings.Split(normalizeCardLineEndings(text), "\n")
out := make([]string, 0, len(lines))
isDivider := func(line string) bool {
return strings.Contains(line, "|") && cardTableDividerRe.MatchString(line)
}
for i, line := range lines {
next := ""
if i+1 < len(lines) {
next = lines[i+1]
}
if cardTableRowRe.MatchString(line) && isDivider(next) && i > 0 &&
strings.TrimSpace(lines[i-1]) != "" && !cardTableRowRe.MatchString(lines[i-1]) {
out = append(out, "")
}
out = append(out, line)
}
return strings.Join(out, "\n")
}
// fixCardNewlines converts single \n to <br> for plain text while keeping
// real newlines inside code fences and before Markdown block syntax, and
// merges consecutive quote lines with <br> (lazy continuation).
func fixCardNewlines(text string) string {
normalized := normalizeCardLineEndings(text)
var merged []string
var pendingQuote []string
inCode := false
flushQuote := func() {
if len(pendingQuote) > 0 {
merged = append(merged, strings.Join(pendingQuote, "<br>"))
pendingQuote = nil
}
}
for _, line := range strings.Split(normalized, "\n") {
isFence := cardFenceRe.MatchString(line)
if inCode {
flushQuote()
merged = append(merged, line)
if isFence {
inCode = false
}
continue
}
if isFence {
flushQuote()
merged = append(merged, line)
inCode = true
continue
}
if cardQuoteRe.MatchString(line) {
if len(pendingQuote) == 0 {
pendingQuote = append(pendingQuote, line)
} else {
pendingQuote = append(pendingQuote, cardQuoteRe.ReplaceAllString(line, ""))
}
} else {
flushQuote()
merged = append(merged, line)
}
}
flushQuote()
inCode = false
var b strings.Builder
for i, line := range merged {
nextInCode := inCode
if cardFenceRe.MatchString(line) {
nextInCode = !inCode
}
if i < len(merged)-1 {
next := merged[i+1]
keepNewline := nextInCode || line == "" || next == "" ||
cardFenceRe.MatchString(next) || cardBlockStartRe.MatchString(next)
b.WriteString(line)
if keepNewline {
b.WriteString("\n")
} else {
b.WriteString("<br>")
}
} else {
b.WriteString(line)
}
inCode = nextInCode
}
return b.String()
}
// normalizeForCard prepares agent output for the AI-card renderer.
func normalizeForCard(content string) string {
return fixCardNewlines(ensureCardTableBlankLines(content))
}
+298
View File
@@ -0,0 +1,298 @@
// 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"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
)
// cardAPIRecorder fakes the DingTalk card endpoints and records every call.
type cardAPIRecorder struct {
mu sync.Mutex
calls []string // "METHOD path"
bodies []map[string]any // parsed request bodies, same order
tokens int // accessToken request count
fail map[string]int // "METHOD path" -> HTTP status to return
}
func newCardAPIServer(t *testing.T) (*cardAPIRecorder, *httptest.Server) {
t.Helper()
rec := &cardAPIRecorder{fail: map[string]int{}}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var body map[string]any
_ = json.Unmarshal(raw, &body)
key := r.Method + " " + r.URL.Path
rec.mu.Lock()
if r.URL.Path == "/v1.0/oauth2/accessToken" {
rec.tokens++
} else {
rec.calls = append(rec.calls, key)
rec.bodies = append(rec.bodies, body)
}
status := rec.fail[key]
rec.mu.Unlock()
if status != 0 {
w.WriteHeader(status)
_, _ = w.Write([]byte(`{"code":"boom"}`))
return
}
if r.URL.Path == "/v1.0/oauth2/accessToken" {
_, _ = w.Write([]byte(`{"accessToken":"tok-1","expireIn":7200}`))
return
}
_, _ = w.Write([]byte(`{"success":true}`))
}))
t.Cleanup(srv.Close)
return rec, srv
}
func withCardAPIBase(t *testing.T, base string) {
t.Helper()
old := dingtalkCardAPIBase
dingtalkCardAPIBase = base
oldGap, oldRepair := aiCardFrameGap, aiCardRepairDelay
aiCardFrameGap, aiCardRepairDelay = 0, 0
t.Cleanup(func() {
dingtalkCardAPIBase = old
aiCardFrameGap, aiCardRepairDelay = oldGap, oldRepair
})
}
func groupCallback() *chatbot.BotCallbackDataModel {
return &chatbot.BotCallbackDataModel{
ConversationId: "cid-group-1",
ConversationType: "2",
SenderStaffId: "staff-1",
}
}
// TestAICardCreateFinalizeSequence verifies the hermes-contract happy path:
// create (empty content = Thinking) → deliver → ONE finalized streaming frame.
func TestAICardCreateFinalizeSequence(t *testing.T) {
rec, srv := newCardAPIServer(t)
withCardAPIBase(t, srv.URL)
c := newAICardClient("ding-client", "ding-secret", defaultAICardTemplateID)
card, err := c.createAndDeliver(context.Background(), groupCallback())
if err != nil {
t.Fatalf("createAndDeliver: %v", err)
}
if !strings.HasPrefix(card.outTrackID, "dws_") {
t.Fatalf("outTrackID = %q, want dws_ prefix", card.outTrackID)
}
if err := c.finalize(context.Background(), card, "你好,**答案是 42**"); err != nil {
t.Fatalf("finalize: %v", err)
}
wantSeq := []string{
"POST /v1.0/card/instances",
"POST /v1.0/card/instances/deliver",
"PUT /v1.0/card/instances", // INPUTING + content
"PUT /v1.0/card/streaming", // finalize frame
"PUT /v1.0/card/instances", // FINISHED
}
if strings.Join(rec.calls, ",") != strings.Join(wantSeq, ",") {
t.Fatalf("call sequence = %v, want %v", rec.calls, wantSeq)
}
if rec.tokens != 1 {
t.Fatalf("token requests = %d, want 1 (cached)", rec.tokens)
}
// create: hermes template + empty "content" param (renders Thinking)
create := rec.bodies[0]
if create["cardTemplateId"] != defaultAICardTemplateID || create["callbackType"] != "STREAM" {
t.Fatalf("create payload wrong: %v", create)
}
pm := create["cardData"].(map[string]any)["cardParamMap"].(map[string]any)
if _, ok := pm["config"]; !ok {
t.Fatalf("create cardParamMap = %v, want config key (openclaw contract)", pm)
}
// deliver: group space + robotCode
deliver := rec.bodies[1]
if deliver["openSpaceId"] != "dtv1.card//IM_GROUP.cid-group-1" {
t.Fatalf("deliver openSpaceId = %v", deliver["openSpaceId"])
}
if deliver["imGroupOpenDeliverModel"].(map[string]any)["robotCode"] != "ding-client" {
t.Fatalf("deliver robotCode missing: %v", deliver)
}
// INPUTING then FINISHED flowStatus around a finalized streaming frame
statusOf := func(b map[string]any) string {
pm := b["cardData"].(map[string]any)["cardParamMap"].(map[string]any)
v, _ := pm["flowStatus"].(string)
return v
}
if statusOf(rec.bodies[2]) != aiCardFlowInputing {
t.Fatalf("flowStatus[2] = %v, want INPUTING", statusOf(rec.bodies[2]))
}
stream := rec.bodies[3]
if stream["key"] != "msgContent" || stream["isFinalize"] != true || stream["isError"] != false {
t.Fatalf("finalize frame wrong: %v", stream)
}
if statusOf(rec.bodies[4]) != aiCardFlowFinished {
t.Fatalf("flowStatus[4] = %v, want FINISHED", statusOf(rec.bodies[4]))
}
}
// TestAICardDeliverOneToOne checks 1:1 messages deliver into the IM_ROBOT
// space with the hermes shape (spaceType only, no robotCode).
func TestAICardDeliverOneToOne(t *testing.T) {
rec, srv := newCardAPIServer(t)
withCardAPIBase(t, srv.URL)
c := newAICardClient("ding-client", "ding-secret", defaultAICardTemplateID)
data := &chatbot.BotCallbackDataModel{ConversationType: "1", SenderStaffId: "staff-9"}
if _, err := c.createAndDeliver(context.Background(), data); err != nil {
t.Fatalf("createAndDeliver: %v", err)
}
deliver := rec.bodies[1]
if deliver["openSpaceId"] != "dtv1.card//IM_ROBOT.staff-9" {
t.Fatalf("deliver openSpaceId = %v, want IM_ROBOT.staff-9", deliver["openSpaceId"])
}
model := deliver["imRobotOpenDeliverModel"].(map[string]any)
if model["spaceType"] != "IM_ROBOT" || model["robotCode"] != "ding-client" {
t.Fatalf("imRobotOpenDeliverModel = %v", model)
}
}
// TestAICardCreateFailure checks errors surface so callers fall back to plain
// replies (never silently lost), and that missing staffId in 1:1 is rejected.
func TestAICardCreateFailure(t *testing.T) {
rec, srv := newCardAPIServer(t)
withCardAPIBase(t, srv.URL)
rec.fail["POST /v1.0/card/instances"] = 500
c := newAICardClient("ding-client", "ding-secret", defaultAICardTemplateID)
if _, err := c.createAndDeliver(context.Background(), groupCallback()); err == nil {
t.Fatal("want error when card create fails")
}
rec.fail = map[string]int{}
if _, err := c.createAndDeliver(context.Background(),
&chatbot.BotCallbackDataModel{ConversationType: "1"}); err == nil {
t.Fatal("want error for 1:1 without senderStaffId")
}
}
// TestAICardMarkFailed checks the stuck-Thinking remedy: a finalized error
// frame, errors swallowed.
func TestAICardMarkFailed(t *testing.T) {
rec, srv := newCardAPIServer(t)
withCardAPIBase(t, srv.URL)
c := newAICardClient("ding-client", "ding-secret", defaultAICardTemplateID)
c.markFailed(context.Background(), &aiCardInstance{outTrackID: "dws_x"})
last := rec.bodies[len(rec.bodies)-1]
pm := last["cardData"].(map[string]any)["cardParamMap"].(map[string]any)
if pm["flowStatus"] != aiCardFlowFailed {
t.Fatalf("markFailed frame wrong: %v", last)
}
}
// TestRobotConnectReplyCardFlag checks the flag default and dry-run surface.
func TestRobotConnectReplyCardFlag(t *testing.T) {
for _, tc := range []struct {
name string
args []string
want string
}{
{"default: no template -> text + emotions", nil, "thinking/done表态"},
{"template configured -> ai-card", []string{"--card-template", "tpl-1.schema"}, `"replyStyle": "ai-card"`},
{"public alias -> ai-card", []string{"--card-template", "public"}, `"replyStyle": "ai-card"`},
{"explicit off", []string{"--reply-card=false"}, `"replyStyle": "text/markdown"`},
} {
t.Run(tc.name, func(t *testing.T) {
root := newDevAppTestRoot(&captureRunner{})
var out strings.Builder
root.SetOut(&out)
root.SetErr(&out)
args := append([]string{"dev", "connect",
"--channel", "claudecode",
"--robot-client-id", "a", "--robot-client-secret", "b", "--dry-run"}, tc.args...)
root.SetArgs(args)
if err := root.Execute(); err != nil {
t.Fatalf("Execute: %v\n%s", err, out.String())
}
if !strings.Contains(out.String(), tc.want) {
t.Fatalf("missing %q in:\n%s", tc.want, out.String())
}
})
}
}
// TestAICardEmotions covers the Thinking chip contract: reply on receive,
// recall+Done on completion (POST /v1.0/robot/emotion/*).
func TestAICardEmotions(t *testing.T) {
rec, srv := newCardAPIServer(t)
withCardAPIBase(t, srv.URL)
c := newAICardClient("ding-client", "ding-secret", defaultAICardTemplateID)
if err := c.markThinking(context.Background(), "cid-1", "msg-1"); err != nil {
t.Fatalf("markThinking: %v", err)
}
c.swapThinkingToDone(context.Background(), "cid-1", "msg-1")
wantSeq := []string{
"POST /v1.0/robot/emotion/reply", // Thinking
"POST /v1.0/robot/emotion/recall", // Thinking recalled
"POST /v1.0/robot/emotion/reply", // Done
}
if strings.Join(rec.calls, ",") != strings.Join(wantSeq, ",") {
t.Fatalf("call sequence = %v, want %v", rec.calls, wantSeq)
}
first := rec.bodies[0]
if first["emotionName"] != "🤔Thinking" || first["openMsgId"] != "msg-1" ||
first["robotCode"] != "ding-client" {
t.Fatalf("thinking payload wrong: %v", first)
}
te := first["textEmotion"].(map[string]any)
if te["emotionId"] != "2659900" || te["backgroundId"] != "im_bg_1" || te["text"] != "🤔Thinking" {
t.Fatalf("textEmotion wrong: %v", te)
}
if rec.bodies[2]["emotionName"] != "🥳Done" {
t.Fatalf("done payload wrong: %v", rec.bodies[2])
}
// Missing ids must error (e.g. payloads without MsgId).
if err := c.markThinking(context.Background(), "", "msg-1"); err == nil {
t.Fatal("want error for missing conversation id")
}
}
// TestAICardCustomTemplate checks --card-template plumbs through to create.
func TestAICardCustomTemplate(t *testing.T) {
rec, srv := newCardAPIServer(t)
withCardAPIBase(t, srv.URL)
c := newAICardClient("ding-client", "ding-secret", "my-own-template.schema")
if _, err := c.createAndDeliver(context.Background(), groupCallback()); err != nil {
t.Fatalf("createAndDeliver: %v", err)
}
if rec.bodies[0]["cardTemplateId"] != "my-own-template.schema" {
t.Fatalf("cardTemplateId = %v, want custom template", rec.bodies[0]["cardTemplateId"])
}
}
+290
View File
@@ -0,0 +1,290 @@
// 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 "strings"
// CmdClass describes whether a dws command is read-only or mutating. It is the
// signal a connector confirmation gate consumes to decide whether a robot may
// run a command directly (read-only) or must first ask the principal to
// approve it (write / mutating).
//
// SAFETY CONTRACT: callers MUST treat CmdClassUnknown conservatively, i.e. as
// if it were CmdClassWrite (require confirmation). The classifier deliberately
// returns Unknown rather than silently coercing it to Write so that the
// confirmation gate keeps full information and can, for example, log/telemeter
// "unclassified" commands separately. Never auto-allow an Unknown command.
type CmdClass int
const (
// CmdClassUnknown means the leaf verb was not recognised by the
// heuristics or any override. Callers must default to requiring
// confirmation (treat as write) for safety.
CmdClassUnknown CmdClass = iota
// CmdClassRead is a read-only / non-mutating command that may be run
// without principal confirmation.
CmdClassRead
// CmdClassWrite is a mutating / state-changing command that must be
// confirmed by the principal before it runs.
CmdClassWrite
)
// String renders the class as a stable lowercase token, handy for logs and
// telemetry.
func (c CmdClass) String() string {
switch c {
case CmdClassRead:
return "read"
case CmdClassWrite:
return "write"
default:
return "unknown"
}
}
// readVerbs and writeVerbs are calibrated against the verbs that real dws
// cobra commands expose (scanned from `Use:` definitions across the repo, e.g.
// todo task create/list/get/update/delete/done, attendance get, approval
// submit, chat send / recall, drive upload / download / mkdir / chmod, doc
// export, contact search, etc). They are NOT invented: every entry below has
// at least one real command using it (or a "<verb>-by-..." / "batch-<verb>"
// compound that normalises to it).
var (
readVerbs = map[string]struct{}{
"list": {},
"get": {},
"search": {},
"read": {},
"view": {},
"query": {},
"show": {},
"detail": {},
"details": {},
"status": {},
"download": {},
"export": {},
"fetch": {},
"info": {},
"find": {},
"stats": {},
"stat": {},
"summary": {},
"check": {},
"inspect": {},
"doctor": {},
"version": {},
"whoami": {},
"ls": {},
"cat": {},
"describe": {},
"diff": {},
"preview": {},
}
writeVerbs = map[string]struct{}{
"create": {},
"update": {},
"delete": {},
"submit": {},
"send": {},
"done": {},
"cancel": {},
"offline": {},
"online": {},
"enable": {},
"disable": {},
"remove": {},
"add": {},
"set": {},
"unset": {},
"approve": {},
"reject": {},
"write": {},
"upload": {},
"move": {},
"mv": {},
"copy": {},
"cp": {},
"rename": {},
"reply": {},
"recall": {},
"publish": {},
"insert": {},
"import": {},
"install": {},
"uninstall": {},
"mkdir": {},
"share": {},
"unshare": {},
"commit": {},
"reset": {},
"stop": {},
"start": {},
"restart": {},
"hide": {},
"unhide": {},
"finalize": {},
"execute": {},
"run": {},
"exec": {},
"chmod": {},
"rm": {},
"clean": {},
"clear": {},
"refresh": {},
"recover": {},
"recovery": {},
"login": {},
"logout": {},
"register": {},
"connect": {},
"disconnect": {},
"upgrade": {},
"setup": {},
"generate": {},
"batch": {},
"apply": {},
"patch": {},
"put": {},
"post": {},
"sync": {},
"link": {},
"unlink": {},
"grant": {},
"revoke": {},
"assign": {},
"close": {},
"open": {},
"archive": {},
"restore": {},
"finish": {},
}
)
// defaultClassOverrides is the package-level override table. It is intentionally
// empty by default: heuristics are expected to cover the common case, and the
// override table exists only to correct individual misclassifications without
// touching the heuristic verb tables. Mutate it via SetCmdClassOverride.
//
// Keys may be either a single verb ("download") or a full space-joined command
// path ("doc export"); both are matched case-insensitively. A full-path key
// wins over a single-verb key when both are present.
var defaultClassOverrides = map[string]CmdClass{}
// SetCmdClassOverride registers a process-wide classification override for the
// given key. The key may be a single verb or a space-joined command path; it is
// normalised to lowercase. Passing CmdClassUnknown removes the override.
func SetCmdClassOverride(key string, class CmdClass) {
key = strings.ToLower(strings.TrimSpace(key))
if key == "" {
return
}
if class == CmdClassUnknown {
delete(defaultClassOverrides, key)
return
}
defaultClassOverrides[key] = class
}
// ClassifyDwsCommand classifies a dws command given its path segments (e.g.
// "todo", "task", "create"). It consults the package-level override table and
// then the read/write verb heuristics, scanning segments right-to-left so the
// leaf action verb dominates a container/noun segment.
//
// Remember the SAFETY CONTRACT on CmdClass: a CmdClassUnknown result MUST be
// treated as write (require confirmation) by the caller.
func ClassifyDwsCommand(parts ...string) CmdClass {
return ClassifyDwsCommandWith(defaultClassOverrides, parts...)
}
// ClassifyDwsCommandWith is like ClassifyDwsCommand but lets the caller supply
// an explicit override table (e.g. a per-tenant or per-request map) instead of
// the package-level one. A nil overrides map is allowed and means "no
// overrides". Override lookups always win over the heuristics.
func ClassifyDwsCommandWith(overrides map[string]CmdClass, parts ...string) CmdClass {
norm := normalizeParts(parts)
if len(norm) == 0 {
return CmdClassUnknown
}
// 1. Full-path override (most specific) wins.
if overrides != nil {
fullKey := strings.Join(norm, " ")
if c, ok := overrides[fullKey]; ok {
return c
}
}
// 2. Walk segments right-to-left: the leaf action verb is the most
// meaningful, but a leaf may be a noun/placeholder (e.g. an id) that
// we do not recognise, so fall back toward the root.
for i := len(norm) - 1; i >= 0; i-- {
seg := norm[i]
if overrides != nil {
if c, ok := overrides[seg]; ok {
return c
}
}
if c, ok := classifyVerb(seg); ok {
return c
}
}
return CmdClassUnknown
}
// classifyVerb classifies a single segment, handling compound verbs such as
// "send-by-bot", "list-forms", "batch-update" or "create_inline" by also
// trying the token before the first separator. Returns (class, true) when the
// segment maps to a known verb.
func classifyVerb(seg string) (CmdClass, bool) {
candidates := verbCandidates(seg)
for _, v := range candidates {
if _, ok := readVerbs[v]; ok {
return CmdClassRead, true
}
if _, ok := writeVerbs[v]; ok {
return CmdClassWrite, true
}
}
return CmdClassUnknown, false
}
// verbCandidates expands a segment into the tokens worth checking against the
// verb tables, in priority order: the whole segment first, then the leading
// token before the first '-' or '_' separator (so "batch-update" tries
// "update"-as-prefix... no: it tries "batch" first which is itself a write
// verb; and "send-by-bot" tries "send"). This handles both "<verb>-<qualifier>"
// and "<verb>_<qualifier>" compounds where the action sits at the front.
func verbCandidates(seg string) []string {
out := []string{seg}
if i := strings.IndexAny(seg, "-_"); i > 0 {
out = append(out, seg[:i])
}
return out
}
// normalizeParts lowercases, trims and drops empty/whitespace segments so that
// callers can pass raw argv-style slices without pre-cleaning them.
func normalizeParts(parts []string) []string {
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.ToLower(strings.TrimSpace(p))
if p == "" {
continue
}
out = append(out, p)
}
return out
}
+176
View File
@@ -0,0 +1,176 @@
// 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 "testing"
func TestClassifyDwsCommandReadVerbs(t *testing.T) {
readLeaves := []string{
"list", "get", "search", "read", "view", "query", "show",
"detail", "status", "download", "export", "fetch", "info",
"find", "summary",
}
for _, v := range readLeaves {
if got := ClassifyDwsCommand("todo", "task", v); got != CmdClassRead {
t.Errorf("verb %q: got %v, want CmdClassRead", v, got)
}
}
}
func TestClassifyDwsCommandWriteVerbs(t *testing.T) {
writeLeaves := []string{
"create", "update", "delete", "submit", "send", "done",
"cancel", "offline", "enable", "disable", "remove", "add",
"set", "approve", "reject", "write", "upload", "move", "copy",
}
for _, v := range writeLeaves {
if got := ClassifyDwsCommand("approval", "instance", v); got != CmdClassWrite {
t.Errorf("verb %q: got %v, want CmdClassWrite", v, got)
}
}
}
func TestClassifyDwsCommandUnknown(t *testing.T) {
cases := [][]string{
{},
{"todo"}, // container only, no action verb
{"todo", "task"}, // still only containers
{"frobnicate"}, // nonsense verb
{"todo", "task", "wibble"}, // unknown leaf, no known ancestor
{" ", ""}, // all empty after trim
}
for _, c := range cases {
if got := ClassifyDwsCommand(c...); got != CmdClassUnknown {
t.Errorf("parts %v: got %v, want CmdClassUnknown", c, got)
}
}
}
func TestClassifyDwsCommandRealSamples(t *testing.T) {
cases := []struct {
parts []string
want CmdClass
}{
// Real dws command paths sampled from the repo's cobra Use: defs.
{[]string{"todo", "task", "create"}, CmdClassWrite},
{[]string{"todo", "task", "list"}, CmdClassRead},
{[]string{"todo", "task", "get"}, CmdClassRead},
{[]string{"todo", "task", "update"}, CmdClassWrite},
{[]string{"todo", "task", "delete"}, CmdClassWrite},
{[]string{"todo", "task", "done"}, CmdClassWrite},
{[]string{"approval", "instance", "submit"}, CmdClassWrite},
{[]string{"attendance", "get"}, CmdClassRead},
{[]string{"chat", "message", "send"}, CmdClassWrite},
{[]string{"chat", "message", "list"}, CmdClassRead},
{[]string{"drive", "file", "download"}, CmdClassRead},
{[]string{"drive", "file", "upload"}, CmdClassWrite},
{[]string{"drive", "dir", "mkdir"}, CmdClassWrite},
{[]string{"doc", "export"}, CmdClassRead},
{[]string{"contact", "user", "search"}, CmdClassRead},
{[]string{"report", "status"}, CmdClassRead},
}
for _, c := range cases {
if got := ClassifyDwsCommand(c.parts...); got != c.want {
t.Errorf("cmd %v: got %v, want %v", c.parts, got, c.want)
}
}
}
func TestClassifyDwsCommandCompoundVerbs(t *testing.T) {
cases := []struct {
parts []string
want CmdClass
}{
// Compound leaf verbs that exist in the repo.
{[]string{"chat", "send-by-bot"}, CmdClassWrite},
{[]string{"chat", "send-by-webhook"}, CmdClassWrite},
{[]string{"chat", "recall-by-bot"}, CmdClassWrite},
{[]string{"aitable", "form", "list-forms"}, CmdClassRead},
{[]string{"wiki", "space", "list-spaces"}, CmdClassRead},
{[]string{"record", "batch-update"}, CmdClassWrite},
{[]string{"group", "add-bot"}, CmdClassWrite},
{[]string{"group", "remove-bot"}, CmdClassWrite},
}
for _, c := range cases {
if got := ClassifyDwsCommand(c.parts...); got != c.want {
t.Errorf("compound %v: got %v, want %v", c.parts, got, c.want)
}
}
}
func TestClassifyDwsCommandLeafFallbackToAncestor(t *testing.T) {
// When the true leaf is a placeholder/id segment we don't recognise,
// classification falls back to the nearest known ancestor verb.
if got := ClassifyDwsCommand("todo", "task", "get", "abc123"); got != CmdClassRead {
t.Errorf("trailing id segment: got %v, want CmdClassRead", got)
}
if got := ClassifyDwsCommand("todo", "task", "create", "xyz"); got != CmdClassWrite {
t.Errorf("trailing id segment: got %v, want CmdClassWrite", got)
}
}
func TestCmdClassOverrideTable(t *testing.T) {
// Suppose "download" should require confirmation for some tenant: a
// full-path override flips a normally-read command to write without
// touching the heuristic tables.
overrides := map[string]CmdClass{
"drive file download": CmdClassWrite, // full-path override
"export": CmdClassWrite, // single-verb override
}
if got := ClassifyDwsCommandWith(overrides, "drive", "file", "download"); got != CmdClassWrite {
t.Errorf("full-path override: got %v, want CmdClassWrite", got)
}
// A different path whose leaf is "download" is NOT affected by the
// full-path override and stays read.
if got := ClassifyDwsCommandWith(overrides, "media", "download"); got != CmdClassRead {
t.Errorf("unrelated download path: got %v, want CmdClassRead", got)
}
// Single-verb override flips every "export" leaf.
if got := ClassifyDwsCommandWith(overrides, "doc", "export"); got != CmdClassWrite {
t.Errorf("single-verb override: got %v, want CmdClassWrite", got)
}
}
func TestSetCmdClassOverrideProcessWide(t *testing.T) {
defer SetCmdClassOverride("status", CmdClassUnknown) // cleanup
// Baseline: status is read.
if got := ClassifyDwsCommand("report", "status"); got != CmdClassRead {
t.Fatalf("baseline status: got %v, want CmdClassRead", got)
}
// Register a process-wide override making status write.
SetCmdClassOverride("STATUS", CmdClassWrite) // case-insensitive key
if got := ClassifyDwsCommand("report", "status"); got != CmdClassWrite {
t.Errorf("after override: got %v, want CmdClassWrite", got)
}
// Removing the override restores the heuristic result.
SetCmdClassOverride("status", CmdClassUnknown)
if got := ClassifyDwsCommand("report", "status"); got != CmdClassRead {
t.Errorf("after override removal: got %v, want CmdClassRead", got)
}
}
func TestCmdClassString(t *testing.T) {
cases := map[CmdClass]string{
CmdClassRead: "read",
CmdClassWrite: "write",
CmdClassUnknown: "unknown",
}
for c, want := range cases {
if got := c.String(); got != want {
t.Errorf("String(%d): got %q, want %q", c, got, want)
}
}
}
+625
View File
@@ -0,0 +1,625 @@
// 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 (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
)
const codexRobotDeveloperInstructions = "你是钉钉群聊里的智能助手,请用简洁、自然的中文直接回答用户问题;不要提及系统提示、内部协议或运行时细节;不要主动读写文件或执行命令。"
// codexAppServerForwarder uses Codex's official app-server JSON-RPC protocol to
// keep one Codex thread per DingTalk conversation.
type codexAppServerForwarder struct {
bin string
env []string
timeout time.Duration
workDir string
model string
sessions *codexThreadSessions
}
func newCodexAppServerForwarder(bin string, env []string, timeout time.Duration, opts connectAgentOptions, clientID string) forwarder {
var sessions *codexThreadSessions
if opts.Memory {
// Scope the on-disk thread store by clientId so multiple bots on one
// machine stay isolated; an empty clientId disables persistence and the
// map stays in memory (original behaviour).
sessions = newCodexThreadSessions(codexThreadStorePath(clientID))
}
return &codexAppServerForwarder{
bin: bin,
env: env,
timeout: timeout,
workDir: opts.WorkDir,
model: opts.Model,
sessions: sessions,
}
}
// codexThreadStorePath returns the on-disk location for a robot's codex
// conversation→thread map, scoped by clientId so multiple bots on one machine
// stay isolated: <config dir>/connect/<clientId>/codex-threads.json. It mirrors
// the Claude-family connectSessionStorePath layout but uses a distinct filename
// so the two stores never collide. An empty clientId means "do not persist"
// (in-memory only). The clientId is sanitized with the same rule as the connect
// lock file so it is always filesystem-safe.
func codexThreadStorePath(clientID string) string {
if clientID == "" {
return ""
}
return filepath.Join(config.DefaultConfigDir(), "connect", sanitizeLockID(clientID), "codex-threads.json")
}
// resetSession drops the conversation's Codex thread so the next message starts
// a fresh one. Implements sessionResetter for the built-in /new and /clear
// commands. A no-op when per-conversation memory is disabled.
func (f *codexAppServerForwarder) resetSession(convID string) {
if f.sessions != nil {
f.sessions.reset(convID)
}
}
func (f *codexAppServerForwarder) canStream() bool { return true }
func (f *codexAppServerForwarder) label() string {
memo := "stateless"
if f.sessions != nil {
memo = "thread-memory"
}
return fmt.Sprintf("codex-app-server:%s (%s)", f.bin, memo)
}
func (f *codexAppServerForwarder) forward(ctx context.Context, convID, text string) (string, error) {
return f.forwardStream(ctx, convID, text, nil)
}
func (f *codexAppServerForwarder) forwardStream(ctx context.Context, convID, text string, onDelta func(string)) (string, error) {
return f.forwardAppServer(ctx, convID, text, onDelta)
}
func (f *codexAppServerForwarder) forwardAppServer(ctx context.Context, convID, text string, onDelta func(string)) (string, error) {
ctx, cancel := context.WithTimeout(ctx, f.timeout)
defer cancel()
var state *codexThreadState
if f.sessions != nil {
state = f.sessions.state(convID)
state.mu.Lock()
defer state.mu.Unlock()
}
cli, err := newCodexAppServerClient(ctx, f.bin, f.env, f.cwd())
if err != nil {
return "", err
}
defer cli.close()
if err := cli.initialize(ctx); err != nil {
return "", err
}
_ = state // held only for its per-conversation turn lock (see above)
threadID := ""
if f.sessions != nil {
threadID = f.sessions.threadID(convID)
}
if threadID != "" {
resumed, err := cli.resumeThread(ctx, f.threadParams(threadID))
if err != nil {
fmt.Fprintf(os.Stderr, "[connect][codex] resume thread %s 失败,重建会话: %v\n", threadID, err)
threadID = ""
f.sessions.setThreadID(convID, "")
} else {
threadID = resumed
}
}
if threadID == "" {
started, err := cli.startThread(ctx, f.threadParams(""))
if err != nil {
return "", err
}
threadID = started
if f.sessions != nil {
f.sessions.setThreadID(convID, threadID)
}
}
reply, err := cli.runTurn(ctx, threadID, text, onDelta)
if err != nil {
return "", err
}
return reply, nil
}
func (f *codexAppServerForwarder) cwd() string {
if f.workDir == "" {
return connectWorkDir()
}
if abs, err := filepath.Abs(f.workDir); err == nil {
return abs
}
return f.workDir
}
func (f *codexAppServerForwarder) threadParams(threadID string) map[string]any {
params := map[string]any{
"approvalPolicy": "never",
"cwd": f.cwd(),
"developerInstructions": codexRobotDeveloperInstructions,
"sandbox": "read-only",
}
if f.model != "" {
params["model"] = f.model
}
if threadID != "" {
params["threadId"] = threadID
}
return params
}
// codexThreadSessions maps a DingTalk conversation to its Codex thread so
// multi-turn context survives within a conversation. The convID→threadID map
// (threads, guarded by mu) is the authoritative store and is persisted to disk
// so the context also survives a connector restart — the codex equivalent of
// the Claude-family convSessions store. An empty path keeps it in memory only
// (persistence disabled), preserving the original behaviour exactly.
//
// states holds a per-conversation lock that serializes turns within one
// conversation; it carries no thread identity of its own.
type codexThreadSessions struct {
mu sync.Mutex
states map[string]*codexThreadState // per-conversation turn lock
threads map[string]string // convID→threadID, persisted
path string // on-disk store; empty disables persistence
}
// codexThreadState is a per-conversation turn lock. Holding it for the duration
// of a turn keeps two messages in the same conversation from interleaving their
// app-server calls; thread identity lives in codexThreadSessions.threads.
type codexThreadState struct {
mu sync.Mutex
}
// newCodexThreadSessions builds the session map, restoring any persisted
// convID→threadID entries from path. A missing or corrupt file degrades to an
// empty map (see loadConvSessionMap) — it never panics or blocks startup. An
// empty path means in-memory only.
func newCodexThreadSessions(path string) *codexThreadSessions {
return &codexThreadSessions{
states: make(map[string]*codexThreadState),
threads: loadConvSessionMap(path),
path: path,
}
}
// codexConvKey normalizes a conversation ID into a stable, non-empty map key.
func codexConvKey(convID string) string {
key := strings.TrimSpace(convID)
if key == "" {
key = "_default"
}
return key
}
// state returns the per-conversation turn lock, minting one on first sight.
func (s *codexThreadSessions) state(convID string) *codexThreadState {
key := codexConvKey(convID)
s.mu.Lock()
defer s.mu.Unlock()
if st, ok := s.states[key]; ok {
return st
}
st := &codexThreadState{}
s.states[key] = st
return st
}
// threadID returns the Codex thread bound to a conversation, or "" if none.
func (s *codexThreadSessions) threadID(convID string) string {
key := codexConvKey(convID)
s.mu.Lock()
defer s.mu.Unlock()
return s.threads[key]
}
// setThreadID binds a conversation to a Codex thread and persists the snapshot.
// A "" threadID forgets the binding (same as reset). Persistence is best-effort:
// a failed save only logs a warning and never blocks message handling.
func (s *codexThreadSessions) setThreadID(convID, threadID string) {
key := codexConvKey(convID)
s.mu.Lock()
if threadID == "" {
delete(s.threads, key)
} else {
s.threads[key] = threadID
}
snapshot := make(map[string]string, len(s.threads))
for k, v := range s.threads {
snapshot[k] = v
}
path := s.path
s.mu.Unlock()
saveConvSessionMap(path, snapshot)
}
// reset forgets a conversation's thread so the next message starts a fresh one.
// The removal is persisted so a restart does not resurrect the dropped thread.
func (s *codexThreadSessions) reset(convID string) {
s.setThreadID(convID, "")
}
type codexAppServerClient struct {
cmd *exec.Cmd
stdin io.WriteCloser
msgs chan codexRPCMessage
readErr chan error
done chan struct{}
closeOnce sync.Once
stderr *lockedBuffer
nextID int
}
type lockedBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *lockedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *lockedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
type codexRPCMessage struct {
ID *int `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *codexRPCError `json:"error,omitempty"`
}
type codexRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func newCodexAppServerClient(ctx context.Context, bin string, env []string, cwd string) (*codexAppServerClient, error) {
cmd := exec.CommandContext(ctx, bin, "app-server", "--stdio")
cmd.Dir = cwd
if len(env) > 0 {
cmd.Env = append(os.Environ(), env...)
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr := &lockedBuffer{}
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return nil, err
}
cli := &codexAppServerClient{
cmd: cmd,
stdin: stdin,
msgs: make(chan codexRPCMessage, 64),
readErr: make(chan error, 1),
done: make(chan struct{}),
stderr: stderr,
nextID: 1,
}
go cli.readLoop(stdout)
return cli, nil
}
func (c *codexAppServerClient) readLoop(stdout io.Reader) {
scanner := bufio.NewScanner(stdout)
scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
var msg codexRPCMessage
if err := json.Unmarshal([]byte(line), &msg); err != nil {
c.reportReadErr(fmt.Errorf("parse app-server JSONL: %w", err))
close(c.msgs)
return
}
select {
case c.msgs <- msg:
case <-c.done:
return
}
}
if err := scanner.Err(); err != nil {
c.reportReadErr(err)
} else {
c.reportReadErr(io.EOF)
}
close(c.msgs)
}
func (c *codexAppServerClient) close() {
c.closeOnce.Do(func() {
close(c.done)
_ = c.stdin.Close()
if c.cmd.Process != nil {
_ = c.cmd.Process.Kill()
}
_ = c.cmd.Wait()
})
}
func (c *codexAppServerClient) reportReadErr(err error) {
select {
case c.readErr <- err:
case <-c.done:
}
}
func (c *codexAppServerClient) initialize(ctx context.Context) error {
id := c.requestID()
if err := c.send(map[string]any{
"id": id,
"method": "initialize",
"params": map[string]any{
"capabilities": map[string]any{"experimentalApi": true},
"clientInfo": map[string]any{
"name": "dws-devapp-robot-connect",
"title": "DWS DevApp Robot Connect",
"version": "0.1.0",
},
},
}); err != nil {
return err
}
if _, err := c.waitResponse(ctx, id); err != nil {
return err
}
return c.send(map[string]any{"method": "initialized", "params": map[string]any{}})
}
func (c *codexAppServerClient) startThread(ctx context.Context, params map[string]any) (string, error) {
id := c.requestID()
if err := c.send(map[string]any{"id": id, "method": "thread/start", "params": params}); err != nil {
return "", err
}
return codexThreadIDFromResult(c.waitResponse(ctx, id))
}
func (c *codexAppServerClient) resumeThread(ctx context.Context, params map[string]any) (string, error) {
id := c.requestID()
if err := c.send(map[string]any{"id": id, "method": "thread/resume", "params": params}); err != nil {
return "", err
}
return codexThreadIDFromResult(c.waitResponse(ctx, id))
}
func (c *codexAppServerClient) runTurn(ctx context.Context, threadID, text string, onDelta func(string)) (string, error) {
id := c.requestID()
if err := c.send(map[string]any{
"id": id,
"method": "turn/start",
"params": map[string]any{
"input": []map[string]string{{"type": "text", "text": text}},
"threadId": threadID,
},
}); err != nil {
return "", err
}
var acc strings.Builder
for {
msg, err := c.next(ctx)
if err != nil {
return "", c.withStderr("app-server stream ended before turn/completed", err)
}
if msg.ID != nil && msg.Method != "" {
c.rejectServerRequest(*msg.ID, msg.Method)
continue
}
if msg.ID != nil && *msg.ID == id && msg.Error != nil {
return "", fmt.Errorf("turn/start: %s", msg.Error.Message)
}
switch msg.Method {
case "item/agentMessage/delta":
var p struct {
Delta string `json:"delta"`
ThreadID string `json:"threadId"`
}
if json.Unmarshal(msg.Params, &p) == nil && p.ThreadID == threadID && p.Delta != "" {
acc.WriteString(p.Delta)
if onDelta != nil {
onDelta(acc.String())
}
}
case "turn/completed":
final, status, errMsg, ok := codexTurnCompletedText(msg.Params, threadID)
if !ok {
continue
}
if status == "failed" {
if errMsg == "" {
errMsg = "turn failed"
}
return "", fmt.Errorf("%s", errMsg)
}
if final == "" {
final = strings.TrimSpace(acc.String())
}
if final == "" {
return "", fmt.Errorf("turn completed without agent message")
}
return final, nil
case "error":
return "", fmt.Errorf("app-server error notification: %s", truncateRunes(string(msg.Params), 300))
}
}
}
func (c *codexAppServerClient) requestID() int {
id := c.nextID
c.nextID++
return id
}
func (c *codexAppServerClient) send(v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
_, err = fmt.Fprintln(c.stdin, string(b))
return err
}
func (c *codexAppServerClient) waitResponse(ctx context.Context, id int) (json.RawMessage, error) {
for {
msg, err := c.next(ctx)
if err != nil {
return nil, c.withStderr("app-server exited before response", err)
}
if msg.ID != nil && msg.Method != "" {
c.rejectServerRequest(*msg.ID, msg.Method)
continue
}
if msg.ID == nil || *msg.ID != id {
continue
}
if msg.Error != nil {
return nil, fmt.Errorf("%s", msg.Error.Message)
}
return msg.Result, nil
}
}
func (c *codexAppServerClient) next(ctx context.Context) (codexRPCMessage, error) {
// The read loop reports EOF before closing msgs, so when the process
// exits right after its last frame both channels are ready and select
// would pick one at random — drain buffered frames (e.g. the final
// turn/completed) before honoring a read error.
select {
case msg, ok := <-c.msgs:
if !ok {
return codexRPCMessage{}, io.EOF
}
return msg, nil
default:
}
select {
case msg, ok := <-c.msgs:
if !ok {
return codexRPCMessage{}, io.EOF
}
return msg, nil
case err := <-c.readErr:
return codexRPCMessage{}, err
case <-c.done:
return codexRPCMessage{}, io.EOF
case <-ctx.Done():
return codexRPCMessage{}, ctx.Err()
}
}
func (c *codexAppServerClient) rejectServerRequest(id int, method string) {
_ = c.send(map[string]any{
"id": id,
"error": map[string]any{
"code": -32000,
"message": "DWS robot connect does not support interactive Codex app-server request: " + method,
},
})
}
func (c *codexAppServerClient) withStderr(prefix string, err error) error {
stderr := strings.TrimSpace(c.stderr.String())
if stderr == "" {
return fmt.Errorf("%s: %w", prefix, err)
}
return fmt.Errorf("%s: %w: %s", prefix, err, truncateRunes(stderr, 300))
}
func codexThreadIDFromResult(result json.RawMessage, err error) (string, error) {
if err != nil {
return "", err
}
var r struct {
Thread struct {
ID string `json:"id"`
} `json:"thread"`
}
if err := json.Unmarshal(result, &r); err != nil {
return "", err
}
if r.Thread.ID == "" {
return "", fmt.Errorf("app-server response missing thread.id")
}
return r.Thread.ID, nil
}
func codexTurnCompletedText(params json.RawMessage, wantThreadID string) (final, status, errMsg string, ok bool) {
var p struct {
ThreadID string `json:"threadId"`
Turn struct {
Status string `json:"status"`
Error *struct {
Message string `json:"message"`
AdditionalDetails string `json:"additionalDetails"`
} `json:"error"`
Items []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"items"`
} `json:"turn"`
}
if err := json.Unmarshal(params, &p); err != nil || p.ThreadID != wantThreadID {
return "", "", "", false
}
for i := len(p.Turn.Items) - 1; i >= 0; i-- {
if p.Turn.Items[i].Type == "agentMessage" && strings.TrimSpace(p.Turn.Items[i].Text) != "" {
final = strings.TrimSpace(p.Turn.Items[i].Text)
break
}
}
if p.Turn.Error != nil {
errMsg = strings.TrimSpace(p.Turn.Error.Message)
if p.Turn.Error.AdditionalDetails != "" {
errMsg = strings.TrimSpace(errMsg + ": " + p.Turn.Error.AdditionalDetails)
}
}
return final, p.Turn.Status, errMsg, true
}
@@ -0,0 +1,271 @@
// 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"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func writeShellExecutable(t *testing.T, dir, name, body string) string {
t.Helper()
path := filepath.Join(dir, name)
if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0o755); err != nil {
t.Fatalf("write stub %s: %v", name, err)
}
return path
}
func TestForwarderForChannelCodexPrefersAppServer(t *testing.T) {
clearChannelEnv(t)
t.Setenv("DWS_CONNECT_NO_INSTALL", "1")
stub := t.TempDir()
writeShellExecutable(t, stub, "codex", "exit 0\n")
t.Setenv("PATH", stub)
fwd, err := forwarderForChannel("codex", "", connectAgentOptions{Memory: true})
if err != nil {
t.Fatalf("codex forwarder: %v", err)
}
cf, ok := fwd.(*codexAppServerForwarder)
if !ok {
t.Fatalf("codex should prefer app-server forwarder, got %T", fwd)
}
if cf.sessions == nil {
t.Fatal("codex app-server should keep per-conversation thread memory by default")
}
t.Setenv("DWS_CODEX_APP_SERVER", "0")
fwd, err = forwarderForChannel("codex", "", connectAgentOptions{Memory: true})
if err != nil {
t.Fatalf("codex forwarder with deprecated app-server env: %v", err)
}
if _, ok := fwd.(*codexAppServerForwarder); !ok {
t.Fatalf("DWS_CODEX_APP_SERVER=0 should be ignored and keep app-server, got %T", fwd)
}
}
func TestCodexConnectPlanIgnoresAppServerEnv(t *testing.T) {
clearChannelEnv(t)
plan := buildConnectPlan("codex", "cid", "")
if got := plan["method"]; got != "stream-bridge-codex-app-server" {
t.Fatalf("default codex plan method = %v", got)
}
payload := connectAgentOptionsPayload("codex", connectAgentOptions{Memory: true})
if got := payload["memory"]; got != "per-conversation-app-server" {
t.Fatalf("default codex memory = %v", got)
}
t.Setenv("DWS_CODEX_APP_SERVER", "0")
plan = buildConnectPlan("codex", "cid", "")
if got := plan["method"]; got != "stream-bridge-codex-app-server" {
t.Fatalf("deprecated app-server env should be ignored, method = %v", got)
}
payload = connectAgentOptionsPayload("codex", connectAgentOptions{Memory: true})
if got := payload["memory"]; got != "per-conversation-app-server" {
t.Fatalf("deprecated app-server env should keep codex memory, got %v", got)
}
}
func TestCodexConnectPlanIgnoresAgentCmdOverride(t *testing.T) {
clearChannelEnv(t)
t.Setenv("DWS_AGENT_CMD", "my-codex exec")
plan := buildConnectPlan("codex", "cid", "")
if got := plan["method"]; got != "stream-bridge-codex-app-server" {
t.Fatalf("codex should ignore DWS_AGENT_CMD and keep app-server plan, method = %v", got)
}
payload := connectAgentOptionsPayload("codex", connectAgentOptions{Memory: true})
if got := payload["memory"]; got != "per-conversation-app-server" {
t.Fatalf("codex should ignore DWS_AGENT_CMD and keep app-server memory, got %v", got)
}
}
func TestCodexAppServerForwarderStreamsAndRemembersThread(t *testing.T) {
dir := t.TempDir()
logPath := filepath.Join(dir, "requests.log")
codex := writeShellExecutable(t, dir, "codex", `
while IFS= read -r line; do
printf '%s\n' "$line" >> "$CODEX_STUB_LOG"
case "$line" in
*\"method\":\"initialize\"*) printf '%s\n' '{"id":1,"result":{}}' ;;
*\"method\":\"thread/start\"*) printf '%s\n' '{"id":2,"result":{"thread":{"id":"thr_stub"}}}' ;;
*\"method\":\"thread/resume\"*) printf '%s\n' '{"id":2,"result":{"thread":{"id":"thr_stub"}}}' ;;
*\"method\":\"turn/start\"*)
printf '%s\n' '{"method":"item/agentMessage/delta","params":{"threadId":"thr_stub","turnId":"turn_stub","itemId":"item_1","delta":"你"}}'
printf '%s\n' '{"method":"item/agentMessage/delta","params":{"threadId":"thr_stub","turnId":"turn_stub","itemId":"item_1","delta":"好"}}'
printf '%s\n' '{"method":"turn/completed","params":{"threadId":"thr_stub","turn":{"id":"turn_stub","status":"completed","items":[{"id":"item_1","type":"agentMessage","text":"你好"}]}}}'
exit 0
;;
esac
done
`)
fwd := &codexAppServerForwarder{
bin: codex,
env: []string{"CODEX_STUB_LOG=" + logPath},
timeout: 5 * time.Second,
workDir: dir,
sessions: newCodexThreadSessions(""),
}
var deltas []string
reply, err := fwd.forwardStream(context.Background(), "conv-1", "第一问", func(s string) {
deltas = append(deltas, s)
})
if err != nil {
t.Fatalf("first forward: %v", err)
}
if reply != "你好" {
t.Fatalf("first reply = %q, want 你好", reply)
}
if strings.Join(deltas, "|") != "你|你好" {
t.Fatalf("deltas = %v, want [你 你好]", deltas)
}
if _, err := fwd.forwardStream(context.Background(), "conv-1", "第二问", nil); err != nil {
t.Fatalf("second forward: %v", err)
}
logBytes, err := os.ReadFile(logPath)
if err != nil {
t.Fatal(err)
}
log := string(logBytes)
if strings.Count(log, `"method":"thread/start"`) != 1 {
t.Fatalf("expected one thread/start, log:\n%s", log)
}
if strings.Count(log, `"method":"thread/resume"`) != 1 {
t.Fatalf("expected one thread/resume, log:\n%s", log)
}
}
func TestCodexAppServerForwarderReturnsAppServerError(t *testing.T) {
dir := t.TempDir()
codex := writeShellExecutable(t, dir, "codex", `
while IFS= read -r line; do
case "$line" in
*\"method\":\"initialize\"*)
printf '%s\n' '{"id":1,"error":{"code":123,"message":"app-server-broken"}}'
exit 0
;;
esac
done
`)
fwd := &codexAppServerForwarder{
bin: codex,
timeout: 10 * time.Second,
workDir: dir,
}
reply, err := fwd.forward(context.Background(), "conv-1", "hello")
if err == nil {
t.Fatal("forward should return the app-server error instead of falling back to exec")
}
if reply != "" {
t.Fatalf("reply = %q, want empty reply on app-server error", reply)
}
if !strings.Contains(err.Error(), "app-server-broken") {
t.Fatalf("error = %v, want app-server-broken", err)
}
}
func TestCodexAppServerReadLoopStopsWhenClosedWithFullQueue(t *testing.T) {
reader, writer := io.Pipe()
c := &codexAppServerClient{
msgs: make(chan codexRPCMessage, 1),
readErr: make(chan error, 1),
done: make(chan struct{}),
}
loopDone := make(chan struct{})
go func() {
defer close(loopDone)
c.readLoop(reader)
}()
writerDone := make(chan struct{})
go func() {
defer close(writerDone)
for i := 0; i < 200; i++ {
if _, err := fmt.Fprintf(writer, `{"method":"event/%d","params":{}}`+"\n", i); err != nil {
return
}
}
}()
deadline := time.Now().Add(time.Second)
for len(c.msgs) == 0 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if len(c.msgs) == 0 {
t.Fatal("readLoop did not enqueue the first message")
}
close(c.done)
_ = reader.Close()
_ = writer.Close()
select {
case <-loopDone:
case <-time.After(time.Second):
t.Fatal("readLoop did not stop after client close")
}
select {
case <-writerDone:
case <-time.After(time.Second):
t.Fatal("writer stayed blocked after pipe close")
}
}
func TestLockedBufferConcurrentReadWrite(t *testing.T) {
var b lockedBuffer
stop := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-stop:
return
default:
_, _ = b.Write([]byte("stderr\n"))
}
}
}()
for i := 0; i < 1000; i++ {
_ = b.String()
}
close(stop)
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("writer did not stop")
}
}
func TestCodexTurnCompletedText(t *testing.T) {
final, status, errMsg, ok := codexTurnCompletedText([]byte(`{"threadId":"thr","turn":{"status":"completed","items":[{"type":"agentMessage","text":"早"},{"type":"agentMessage","text":"最终"}]}}`), "thr")
if !ok || status != "completed" || final != "最终" || errMsg != "" {
t.Fatalf("completed = (%q,%q,%q,%v)", final, status, errMsg, ok)
}
_, status, errMsg, ok = codexTurnCompletedText([]byte(`{"threadId":"thr","turn":{"status":"failed","error":{"message":"boom","additionalDetails":"detail"},"items":[]}}`), "thr")
if !ok || status != "failed" || errMsg != "boom: detail" {
t.Fatalf("failed = (%q,%q,%v)", status, errMsg, ok)
}
}
@@ -0,0 +1,68 @@
// 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 (
"path/filepath"
"testing"
)
// TestCodexThreadSessionsPersist verifies that a codex conversation's thread
// survives a connector restart: a second store opened on the same path restores
// the convID→threadID mapping, and a reset is persisted too.
func TestCodexThreadSessionsPersist(t *testing.T) {
path := filepath.Join(t.TempDir(), "codex-threads.json")
s := newCodexThreadSessions(path)
if got := s.threadID("conv-1"); got != "" {
t.Fatalf("fresh store threadID = %q, want empty", got)
}
s.setThreadID("conv-1", "thr_a")
s.setThreadID("conv-2", "thr_b")
// Simulate a restart: a new store on the same path must restore both.
restarted := newCodexThreadSessions(path)
if got := restarted.threadID("conv-1"); got != "thr_a" {
t.Errorf("after restart conv-1 = %q, want thr_a", got)
}
if got := restarted.threadID("conv-2"); got != "thr_b" {
t.Errorf("after restart conv-2 = %q, want thr_b", got)
}
// Reset is persisted: the dropped thread must not resurrect on restart.
restarted.reset("conv-1")
again := newCodexThreadSessions(path)
if got := again.threadID("conv-1"); got != "" {
t.Errorf("after reset+restart conv-1 = %q, want empty", got)
}
if got := again.threadID("conv-2"); got != "thr_b" {
t.Errorf("after reset+restart conv-2 = %q, want thr_b (untouched)", got)
}
}
// TestCodexThreadSessionsInMemory verifies that an empty path keeps the store
// purely in memory: it still works within the process but writes nothing to
// disk, preserving the pre-persistence behaviour.
func TestCodexThreadSessionsInMemory(t *testing.T) {
s := newCodexThreadSessions("")
s.setThreadID("conv-1", "thr_a")
if got := s.threadID("conv-1"); got != "thr_a" {
t.Errorf("in-memory conv-1 = %q, want thr_a", got)
}
// A separate in-memory store shares no state (nothing was persisted).
other := newCodexThreadSessions("")
if got := other.threadID("conv-1"); got != "" {
t.Errorf("separate in-memory store conv-1 = %q, want empty", got)
}
}
+68
View File
@@ -0,0 +1,68 @@
// 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 "strings"
// connectControlAction is a built-in slash command a user can type in the chat
// to control the connector's per-conversation session, instead of a message
// that gets forwarded to the agent. Modelled on codex / OpenClaw connect's
// preset commands: the set is fixed (never dynamically extended) so the bot's
// behaviour stays predictable.
type connectControlAction struct {
// name is the canonical action ("new" | "clear"). Both reset the current
// conversation's session today (the next message starts fresh with no prior
// context), but they stay distinct actions so the ack wording can differ and
// a future channel can diverge their behaviour.
name string
// ack is the user-facing confirmation sent back into the chat (Chinese, for
// DingTalk users). It is never forwarded to the agent.
ack string
}
// resetsSession reports whether this action should drop the conversation's
// agent session. Both built-in commands do today; kept as a predicate so adding
// a non-resetting command later does not require touching the call site.
func (a connectControlAction) resetsSession() bool {
return a.name == "new" || a.name == "clear"
}
// connectControlCommands maps the recognised slash tokens to their action. The
// map is the single source of truth for "which commands exist" — both the
// parser and any help text should read from it. "/new", "/start" and "/reset"
// are aliases for opening a fresh session; "/clear" wipes the current one.
var connectControlCommands = map[string]connectControlAction{
"/new": {name: "new", ack: "🆕 已为你开启新会话,之前的上下文不再带入。"},
"/start": {name: "new", ack: "🆕 已为你开启新会话,之前的上下文不再带入。"},
"/reset": {name: "new", ack: "🆕 已为你开启新会话,之前的上下文不再带入。"},
"/clear": {name: "clear", ack: "🧹 已清空当前对话的上下文,我们从头开始。"},
}
// parseConnectControlCommand recognises a built-in slash command. It only
// matches when the WHOLE trimmed message is exactly one known token (case
// insensitive), so a normal question that merely starts with a slash — e.g.
// "/new 这个功能怎么实现?" — is forwarded to the agent untouched rather than
// silently swallowed as a command. Returns (action, true) on a match.
func parseConnectControlCommand(text string) (connectControlAction, bool) {
token := strings.ToLower(strings.TrimSpace(text))
if token == "" || !strings.HasPrefix(token, "/") {
return connectControlAction{}, false
}
// A command is a bare token: reject anything carrying arguments/whitespace.
if strings.ContainsAny(token, " \t\n") {
return connectControlAction{}, false
}
action, ok := connectControlCommands[token]
return action, ok
}
+67
View File
@@ -0,0 +1,67 @@
// 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 "testing"
func TestParseConnectControlCommand(t *testing.T) {
cases := []struct {
in string
wantName string // "" means no match
}{
// Recognised commands and their aliases.
{"/new", "new"},
{"/start", "new"},
{"/reset", "new"},
{"/clear", "clear"},
// Case-insensitive and trimmed.
{"/NEW", "new"},
{" /Clear ", "clear"},
{"/New\n", "new"},
// A normal question that merely starts with a slash is NOT a command —
// it must be forwarded to the agent, not swallowed.
{"/new 这个功能怎么实现?", ""},
{"/clear the cache please", ""},
{"/new x", ""},
// Non-commands.
{"", ""},
{" ", ""},
{"你好", ""},
{"new", ""}, // missing slash
{"/unknown", ""}, // unknown token
{"/", ""},
}
for _, c := range cases {
got, ok := parseConnectControlCommand(c.in)
if c.wantName == "" {
if ok {
t.Errorf("parseConnectControlCommand(%q) = (%+v, true), want no match", c.in, got)
}
continue
}
if !ok {
t.Errorf("parseConnectControlCommand(%q) = no match, want name %q", c.in, c.wantName)
continue
}
if got.name != c.wantName {
t.Errorf("parseConnectControlCommand(%q).name = %q, want %q", c.in, got.name, c.wantName)
}
if got.ack == "" {
t.Errorf("parseConnectControlCommand(%q).ack is empty, want a user-facing confirmation", c.in)
}
if !got.resetsSession() {
t.Errorf("parseConnectControlCommand(%q).resetsSession() = false, want true", c.in)
}
}
}
+536
View File
@@ -0,0 +1,536 @@
// 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"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/logging"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/spf13/cobra"
)
// connect_daemon turns the foreground `robot connect` connector into a 7x24
// background service. Three responsibilities live here and nowhere else (the
// forwarding/session/knowledge logic in devapp_connect.go and connect_stream.go
// is untouched):
//
// 1. detach: `connect --daemon` re-execs dws in supervisor mode in a new
// session (POSIX setsid), prints pid + log path, and exits.
// 2. supervise: the supervisor process runs the real connector as a worker
// child and restarts it with exponential backoff when it crashes.
// 3. status/stop: read the daemon pid file, probe liveness (reusing
// processAlive from connect_lock.go), and signal a graceful stop.
//
// Two hidden internal flags select the mode of a re-exec:
//
// --daemon-supervise : run the supervisor loop (set by the --daemon parent)
// --daemon-worker : run a single foreground connector (set by the supervisor)
const (
daemonSuperviseFlag = "daemon-supervise"
daemonWorkerFlag = "daemon-worker"
daemonFlag = "daemon"
)
// daemonState is the JSON persisted to the daemon pid file. It records the
// supervisor pid plus enough context for `status` to report without re-deriving
// it (start time for uptime, log path, the dir key it was filed under).
type daemonState struct {
Pid int `json:"pid"`
StartUnix int64 `json:"startUnix"`
LogPath string `json:"logPath"`
DirKey string `json:"dirKey"`
ClientID string `json:"clientId,omitempty"`
}
// connectDaemonDirOverride lets tests redirect the per-client daemon directory
// away from the real ~/.dws tree. Empty means use config.DefaultConfigDir.
var connectDaemonDirOverride string
// daemonDirKey derives a filesystem-safe directory key identifying a connector.
// Priority: clientId (the robot's AppKey, the natural identity) > unifiedAppID.
// Reuses sanitizeLockID (connect_lock.go) so the key matches the lock naming
// convention. Returns "" when neither is available.
func daemonDirKey(clientID, unifiedAppID string) string {
if v := strings.TrimSpace(clientID); v != "" {
return sanitizeLockID(v)
}
if v := strings.TrimSpace(unifiedAppID); v != "" {
return "app-" + sanitizeLockID(v)
}
return ""
}
// connectDaemonDir returns <configDir>/connect/<dirKey>, creating it. This holds
// daemon.pid and daemon.log for one connector.
func connectDaemonDir(dirKey string) (string, error) {
base := connectDaemonDirOverride
if base == "" {
base = config.DefaultConfigDir()
}
dir := filepath.Join(base, "connect", dirKey)
if err := os.MkdirAll(dir, config.DirPerm); err != nil {
return "", err
}
return dir, nil
}
func daemonPidPath(dir string) string { return filepath.Join(dir, "daemon.pid") }
func daemonLogPath(dir string) string { return filepath.Join(dir, "daemon.log") }
// writeDaemonState atomically persists the daemon pid file (write temp + rename)
// so a reader never sees a half-written file.
func writeDaemonState(dir string, st daemonState) error {
data, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
tmp := daemonPidPath(dir) + ".tmp"
if err := os.WriteFile(tmp, data, config.FilePerm); err != nil {
return err
}
return os.Rename(tmp, daemonPidPath(dir))
}
// readDaemonState loads the daemon pid file. A missing file yields (nil, nil) so
// callers can treat "not running" distinctly from a real I/O error.
func readDaemonState(dir string) (*daemonState, error) {
data, err := os.ReadFile(daemonPidPath(dir))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var st daemonState
if err := json.Unmarshal(data, &st); err != nil {
return nil, fmt.Errorf("daemon pid file %s is corrupt: %w", daemonPidPath(dir), err)
}
return &st, nil
}
// backoffDelay computes the restart delay for the Nth consecutive worker
// failure: base * 2^(n-1) capped at cap. Pure and unit-tested. n<=0 returns 0
// (first start is immediate). Caller resets n when a worker stays healthy.
func backoffDelay(consecutiveFailures int, base, maxDelay time.Duration) time.Duration {
if consecutiveFailures <= 0 {
return 0
}
d := base
for i := 1; i < consecutiveFailures; i++ {
d *= 2
if d >= maxDelay {
return maxDelay
}
}
if d > maxDelay {
return maxDelay
}
return d
}
const (
daemonBackoffBase = time.Second
daemonBackoffCap = 60 * time.Second
// daemonMaxFastFailures is the consecutive fast-failure ceiling: after this
// many crashes that each happened within daemonHealthyAfter, the supervisor
// gives up rather than spin forever (e.g. bad credentials).
daemonMaxFastFailures = 10
// daemonHealthyAfter is how long a worker must run before the supervisor
// considers it healthy and resets the failure counter.
daemonHealthyAfter = 60 * time.Second
// daemonStopTimeout bounds the graceful wait in `stop` before SIGKILL.
daemonStopTimeout = 10 * time.Second
)
// buildWorkerArgs rewrites the supervisor's own argv into a worker argv: it
// strips the daemon-control flags (--daemon / --daemon-supervise) and appends
// --daemon-worker, preserving every other flag (credentials, channel, knowledge,
// etc.) so the worker connects exactly as the foreground command would. Pure for
// unit testing.
func buildWorkerArgs(args []string) []string {
out := make([]string, 0, len(args)+1)
for _, a := range args {
switch {
case a == "--"+daemonFlag, a == "--"+daemonSuperviseFlag, a == "--"+daemonWorkerFlag:
continue
case strings.HasPrefix(a, "--"+daemonFlag+"="),
strings.HasPrefix(a, "--"+daemonSuperviseFlag+"="),
strings.HasPrefix(a, "--"+daemonWorkerFlag+"="):
continue
}
out = append(out, a)
}
out = append(out, "--"+daemonWorkerFlag)
return out
}
// startDaemon implements `connect --daemon`: it re-execs dws in supervisor mode
// detached from the terminal, writes nothing itself to the worker log (the
// supervisor does), prints the pid + log path, and returns so the parent exits.
func startDaemon(cmd *cobra.Command, dirKey, clientID string) error {
if !daemonDetachSupported {
return apperrors.NewValidation("--daemon is not supported on this OS; run the foreground connector under a service manager instead")
}
dir, err := connectDaemonDir(dirKey)
if err != nil {
return apperrors.NewInternal("create daemon dir: " + err.Error())
}
// Refuse to start a second supervisor for the same connector. The Stream
// single-instance lock would also catch this at the worker layer, but a
// pre-flight check gives a clearer message and avoids an orphaned supervisor.
if st, _ := readDaemonState(dir); st != nil && st.Pid > 0 && processAlive(st.Pid) {
return apperrors.NewValidation(fmt.Sprintf("a connect daemon is already running for %s (pid %d); use `robot connect status`/`stop`", dirKey, st.Pid))
}
exe, err := os.Executable()
if err != nil {
return apperrors.NewInternal("resolve executable: " + err.Error())
}
superviseArgs := buildSuperviseArgs(os.Args[1:])
logPath := daemonLogPath(dir)
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, config.FilePerm)
if err != nil {
return apperrors.NewInternal("open daemon log: " + err.Error())
}
defer logFile.Close()
child := exec.Command(exe, superviseArgs...)
child.Stdout = logFile
child.Stderr = logFile
child.Stdin = nil
// Pass the resolved dir key + clientId through the environment so the
// supervisor files its pid under the same key the parent computed (rather
// than re-deriving and risking a mismatch).
child.Env = append(os.Environ(),
"DWS_CONNECT_DAEMON_DIRKEY="+dirKey,
"DWS_CONNECT_DAEMON_CLIENTID="+clientID,
)
if connectDaemonDirOverride != "" {
child.Env = append(child.Env, "DWS_CONNECT_DAEMON_DIR="+connectDaemonDirOverride)
}
applyDetach(child)
if err := child.Start(); err != nil {
return apperrors.NewInternal("start daemon: " + err.Error())
}
// Release the child so the parent can exit without leaving a zombie.
pid := child.Process.Pid
_ = child.Process.Release()
writeConnectDaemonStarted(cmd.OutOrStdout(), pid, logPath, clientID, dirKey)
return nil
}
func writeConnectDaemonStarted(w io.Writer, pid int, logPath, clientID, dirKey string) {
fmt.Fprintf(w, "connect daemon started (pid %d)\n", pid)
fmt.Fprintf(w, " logs: %s\n", logPath)
fmt.Fprintf(w, " status: dws devapp robot connect status%s\n", statusHintArgs(clientID, dirKey))
fmt.Fprintf(w, " stop: dws devapp robot connect stop%s\n", statusHintArgs(clientID, dirKey))
fmt.Fprint(w, connectLocalDebugNotice())
}
// buildSuperviseArgs rewrites argv to run the supervisor: strip --daemon, append
// --daemon-supervise. Pure for testing.
func buildSuperviseArgs(args []string) []string {
out := make([]string, 0, len(args)+1)
for _, a := range args {
if a == "--"+daemonFlag || strings.HasPrefix(a, "--"+daemonFlag+"=") {
continue
}
out = append(out, a)
}
out = append(out, "--"+daemonSuperviseFlag)
return out
}
func statusHintArgs(clientID, dirKey string) string {
if strings.TrimSpace(clientID) != "" {
return " --robot-client-id " + clientID
}
if strings.HasPrefix(dirKey, "app-") {
return " --unified-app-id " + strings.TrimPrefix(dirKey, "app-")
}
return ""
}
// runSupervisor is the entry point when dws is started with --daemon-supervise.
// It writes the daemon pid file, then loops launching the worker child and
// restarting it with backoff until told to stop (SIGTERM/SIGINT) or it exhausts
// the fast-failure budget. On stop it forwards the signal to the worker, waits,
// and removes its pid file.
func runSupervisor(cmd *cobra.Command) error {
dirKey := strings.TrimSpace(os.Getenv("DWS_CONNECT_DAEMON_DIRKEY"))
if dirKey == "" {
return apperrors.NewInternal("supervisor started without DWS_CONNECT_DAEMON_DIRKEY")
}
if v := strings.TrimSpace(os.Getenv("DWS_CONNECT_DAEMON_DIR")); v != "" {
connectDaemonDirOverride = v
}
clientID := strings.TrimSpace(os.Getenv("DWS_CONNECT_DAEMON_CLIENTID"))
dir, err := connectDaemonDir(dirKey)
if err != nil {
return apperrors.NewInternal("create daemon dir: " + err.Error())
}
st := daemonState{
Pid: os.Getpid(),
StartUnix: time.Now().Unix(),
LogPath: daemonLogPath(dir),
DirKey: dirKey,
ClientID: clientID,
}
if err := writeDaemonState(dir, st); err != nil {
return apperrors.NewInternal("write daemon pid file: " + err.Error())
}
defer os.Remove(daemonPidPath(dir))
// Route worker stdout/stderr through the shared size-rotating writer
// (logging.NewRotatingFile) so a long-running connector's logs don't grow
// unbounded. The detached parent already redirected our own fds to the same
// daemon.log; from here we append through the rotator. Fall back to stderr if
// the rotator can't be opened.
var out io.Writer = cmd.ErrOrStderr()
if rot, rerr := logging.NewRotatingFile(daemonLogPath(dir)); rerr == nil {
defer rot.Close()
out = rot
}
// The supervisor reacts to SIGTERM/SIGINT itself (cmd.Context from root is
// already wired to these). We use an independent NotifyContext so cancelling
// it stops the loop and lets us forward the signal to the worker explicitly.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
workerArgs := buildWorkerArgs(os.Args[1:])
exe, err := os.Executable()
if err != nil {
return apperrors.NewInternal("resolve executable: " + err.Error())
}
failures := 0
for {
if delay := backoffDelay(failures, daemonBackoffBase, daemonBackoffCap); delay > 0 {
fmt.Fprintf(out, "[daemon] restarting worker in %s (consecutive failures: %d)\n", delay, failures)
select {
case <-ctx.Done():
return nil
case <-time.After(delay):
}
}
if ctx.Err() != nil {
return nil
}
started := time.Now()
worker := exec.Command(exe, workerArgs...)
worker.Stdout = out
worker.Stderr = out
worker.Env = os.Environ()
if err := worker.Start(); err != nil {
fmt.Fprintf(out, "[daemon] failed to start worker: %v\n", err)
failures++
if failures >= daemonMaxFastFailures {
return apperrors.NewInternal("daemon worker failed to start too many times; giving up")
}
continue
}
fmt.Fprintf(out, "[daemon] worker started (pid %d)\n", worker.Process.Pid)
waitErr := superviseWait(ctx, worker)
ran := time.Since(started)
if ctx.Err() != nil {
// We were asked to stop; the worker has been (or is being) signalled.
fmt.Fprintln(out, "[daemon] stop requested, worker shut down; exiting supervisor")
return nil
}
if ran >= daemonHealthyAfter {
failures = 0
} else {
failures++
}
fmt.Fprintf(out, "[daemon] worker exited after %s (err=%v); consecutive failures: %d\n", ran.Round(time.Second), waitErr, failures)
if failures >= daemonMaxFastFailures {
return apperrors.NewInternal(fmt.Sprintf("daemon worker crashed %d times in a row; giving up (check %s)", failures, daemonLogPath(dir)))
}
}
}
// superviseWait waits for the worker to exit, but if the supervisor's ctx is
// cancelled first it forwards SIGTERM to the worker for a graceful shutdown
// (releasing the Stream single-instance lock) and then waits.
func superviseWait(ctx context.Context, worker *exec.Cmd) error {
done := make(chan error, 1)
go func() { done <- worker.Wait() }()
select {
case err := <-done:
return err
case <-ctx.Done():
_ = worker.Process.Signal(syscall.SIGTERM)
select {
case err := <-done:
return err
case <-time.After(daemonStopTimeout):
_ = worker.Process.Kill()
return <-done
}
}
}
// daemonStatus reports the state of the connector daemon to w.
func daemonStatus(w io.Writer, dirKey string) error {
dir, err := connectDaemonDir(dirKey)
if err != nil {
return apperrors.NewInternal("resolve daemon dir: " + err.Error())
}
st, err := readDaemonState(dir)
if err != nil {
return apperrors.NewInternal(err.Error())
}
if st == nil {
fmt.Fprintf(w, "connect daemon: not running (no pid file under %s)\n", dir)
return nil
}
if st.Pid <= 0 || !processAlive(st.Pid) {
fmt.Fprintf(w, "connect daemon: not running (stale pid file for pid %d at %s)\n", st.Pid, daemonPidPath(dir))
return nil
}
uptime := time.Since(time.Unix(st.StartUnix, 0)).Round(time.Second)
fmt.Fprintf(w, "connect daemon: running\n")
fmt.Fprintf(w, " pid: %d\n", st.Pid)
fmt.Fprintf(w, " uptime: %s\n", uptime)
fmt.Fprintf(w, " logs: %s\n", st.LogPath)
if st.ClientID != "" {
fmt.Fprintf(w, " client: %s\n", st.ClientID)
}
return nil
}
// daemonStop gracefully stops the connector daemon: SIGTERM the supervisor (it
// forwards to the worker, which releases the lock and Stream connection), poll
// until it exits, escalate to SIGKILL on timeout, and clean up the pid file.
func daemonStop(w io.Writer, dirKey string) error {
dir, err := connectDaemonDir(dirKey)
if err != nil {
return apperrors.NewInternal("resolve daemon dir: " + err.Error())
}
st, err := readDaemonState(dir)
if err != nil {
return apperrors.NewInternal(err.Error())
}
if st == nil || st.Pid <= 0 {
fmt.Fprintf(w, "connect daemon: not running (nothing to stop)\n")
return nil
}
if !processAlive(st.Pid) {
_ = os.Remove(daemonPidPath(dir))
fmt.Fprintf(w, "connect daemon: was not running (cleaned up stale pid file for pid %d)\n", st.Pid)
return nil
}
proc, err := os.FindProcess(st.Pid)
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("find daemon process %d: %v", st.Pid, err))
}
if err := proc.Signal(syscall.SIGTERM); err != nil {
return apperrors.NewInternal(fmt.Sprintf("signal daemon %d: %v", st.Pid, err))
}
fmt.Fprintf(w, "sent SIGTERM to connect daemon (pid %d), waiting for graceful stop...\n", st.Pid)
deadline := time.Now().Add(daemonStopTimeout)
for time.Now().Before(deadline) {
if !processAlive(st.Pid) {
_ = os.Remove(daemonPidPath(dir))
fmt.Fprintf(w, "connect daemon stopped (pid %d)\n", st.Pid)
return nil
}
time.Sleep(200 * time.Millisecond)
}
// Graceful window elapsed; force kill.
_ = proc.Signal(syscall.SIGKILL)
time.Sleep(200 * time.Millisecond)
_ = os.Remove(daemonPidPath(dir))
fmt.Fprintf(w, "connect daemon did not stop in %s; sent SIGKILL (pid %d)\n", daemonStopTimeout, st.Pid)
return nil
}
// newDevAppRobotConnectStatusCommand implements `dws devapp robot connect
// status`: report whether a background connector daemon is running for the
// robot identified by --robot-client-id (or --unified-app-id).
func newDevAppRobotConnectStatusCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "查看后台连接器守护进程状态(pid、运行时长、日志路径)",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
dirKey, err := connectDaemonDirKeyFromFlags(cmd)
if err != nil {
return err
}
return daemonStatus(cmd.OutOrStdout(), dirKey)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("robot-client-id", "", "机器人 clientId(定位守护进程)")
cmd.Flags().String("unified-app-id", "", "统一应用 ID(当未用 clientId 起守护进程时定位)")
return cmd
}
// newDevAppRobotConnectStopCommand implements `dws devapp robot connect stop`:
// gracefully stop the background connector daemon (SIGTERM, escalate to SIGKILL
// on timeout) and clean up its pid file.
func newDevAppRobotConnectStopCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "stop",
Short: "优雅停止后台连接器守护进程(释放单实例锁与 Stream 连接)",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
dirKey, err := connectDaemonDirKeyFromFlags(cmd)
if err != nil {
return err
}
return daemonStop(cmd.OutOrStdout(), dirKey)
},
}
preferLegacyLeaf(cmd)
cmd.Flags().String("robot-client-id", "", "机器人 clientId(定位守护进程)")
cmd.Flags().String("unified-app-id", "", "统一应用 ID(当未用 clientId 起守护进程时定位)")
return cmd
}
// connectDaemonDirKeyFromFlags resolves the daemon directory key from the
// status/stop flags, requiring at least one identifier.
func connectDaemonDirKeyFromFlags(cmd *cobra.Command) (string, error) {
clientID := devAppStringFlag(cmd, "robot-client-id")
unifiedAppID := devAppStringFlag(cmd, "unified-app-id")
dirKey := daemonDirKey(clientID, unifiedAppID)
if dirKey == "" {
return "", apperrors.NewValidation("需要 --robot-client-id 或 --unified-app-id 以定位守护进程")
}
return dirKey, nil
}
+241
View File
@@ -0,0 +1,241 @@
// 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 (
"bytes"
"os"
"strings"
"testing"
"time"
)
func TestBackoffDelay(t *testing.T) {
base := time.Second
cap := 60 * time.Second
cases := []struct {
failures int
want time.Duration
}{
{0, 0},
{-1, 0},
{1, time.Second},
{2, 2 * time.Second},
{3, 4 * time.Second},
{4, 8 * time.Second},
{5, 16 * time.Second},
{6, 32 * time.Second},
{7, cap}, // 64s capped to 60s
{8, cap},
{100, cap},
}
for _, c := range cases {
if got := backoffDelay(c.failures, base, cap); got != c.want {
t.Errorf("backoffDelay(%d) = %v, want %v", c.failures, got, c.want)
}
}
}
func TestDaemonDirKey(t *testing.T) {
cases := []struct {
clientID string
unifiedAppID string
want string
}{
{"clientABC", "", "clientABC"},
{"client/with:bad*chars", "", "client_with_bad_chars"},
{"", "app-123", "app-app-123"},
{"", "u/n.id", "app-u_n_id"},
{" ", " ", ""},
{"cid", "uid", "cid"}, // clientID wins
}
for _, c := range cases {
if got := daemonDirKey(c.clientID, c.unifiedAppID); got != c.want {
t.Errorf("daemonDirKey(%q,%q) = %q, want %q", c.clientID, c.unifiedAppID, got, c.want)
}
}
}
func TestBuildWorkerArgs(t *testing.T) {
in := []string{"devapp", "robot", "connect", "--daemon", "--robot-client-id", "abc", "--channel=claudecode"}
got := buildWorkerArgs(in)
joined := strings.Join(got, " ")
if strings.Contains(joined, "--daemon ") || strings.HasSuffix(joined, "--daemon") {
// only the appended --daemon-worker may contain "daemon"
}
if !strings.HasSuffix(joined, "--daemon-worker") {
t.Errorf("worker args must end with --daemon-worker, got %q", joined)
}
for _, a := range got[:len(got)-1] {
if a == "--daemon" || a == "--daemon-supervise" || a == "--daemon-worker" {
t.Errorf("daemon-control flag leaked into worker args: %q", a)
}
}
if !strings.Contains(joined, "--robot-client-id abc") || !strings.Contains(joined, "--channel=claudecode") {
t.Errorf("credential/channel flags must be preserved, got %q", joined)
}
}
func TestBuildSuperviseArgs(t *testing.T) {
in := []string{"devapp", "robot", "connect", "--daemon", "--robot-client-id", "abc"}
got := buildSuperviseArgs(in)
joined := strings.Join(got, " ")
if !strings.HasSuffix(joined, "--daemon-supervise") {
t.Errorf("supervise args must end with --daemon-supervise, got %q", joined)
}
if strings.Contains(joined, " --daemon ") || strings.Contains(joined, " --daemon\b") {
t.Errorf("--daemon should be stripped, got %q", joined)
}
for _, a := range got[:len(got)-1] {
if a == "--daemon" {
t.Errorf("--daemon leaked into supervise args: %q", a)
}
}
}
func TestWriteConnectDaemonStartedIncludesLocalDebugNotice(t *testing.T) {
var buf bytes.Buffer
writeConnectDaemonStarted(&buf, 1234, "/tmp/daemon.log", "cid", "cid")
out := buf.String()
for _, want := range []string{"connect daemon started", "/tmp/daemon.log", "本地调试", "不代表线上发布完成", "不会提交版本发布"} {
if !strings.Contains(out, want) {
t.Fatalf("daemon started output missing %q:\n%s", want, out)
}
}
}
func TestDaemonStateRoundTrip(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
dir, err := connectDaemonDir("roundtrip")
if err != nil {
t.Fatalf("connectDaemonDir: %v", err)
}
// No file yet → nil, nil.
if st, err := readDaemonState(dir); err != nil || st != nil {
t.Fatalf("expected (nil,nil) for missing pid file, got (%v,%v)", st, err)
}
want := daemonState{Pid: 4242, StartUnix: time.Now().Unix(), LogPath: "/x/y.log", DirKey: "roundtrip", ClientID: "cid"}
if err := writeDaemonState(dir, want); err != nil {
t.Fatalf("writeDaemonState: %v", err)
}
got, err := readDaemonState(dir)
if err != nil || got == nil {
t.Fatalf("readDaemonState: (%v,%v)", got, err)
}
if got.Pid != want.Pid || got.DirKey != want.DirKey || got.ClientID != want.ClientID || got.LogPath != want.LogPath {
t.Errorf("round trip mismatch: got %+v want %+v", *got, want)
}
}
func TestReadDaemonStateCorrupt(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
dir, _ := connectDaemonDir("corrupt")
if err := os.WriteFile(daemonPidPath(dir), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := readDaemonState(dir); err == nil {
t.Error("expected error for corrupt pid file")
}
}
func TestDaemonStatusNotRunning(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
var buf bytes.Buffer
if err := daemonStatus(&buf, "nope"); err != nil {
t.Fatalf("daemonStatus: %v", err)
}
if !strings.Contains(buf.String(), "not running") {
t.Errorf("expected 'not running', got %q", buf.String())
}
}
func TestDaemonStatusStalePid(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
dir, _ := connectDaemonDir("stale")
// pid that is essentially certain to be dead.
writeDaemonState(dir, daemonState{Pid: deadPid(t), StartUnix: time.Now().Unix(), LogPath: "/l", DirKey: "stale"})
var buf bytes.Buffer
if err := daemonStatus(&buf, "stale"); err != nil {
t.Fatalf("daemonStatus: %v", err)
}
if !strings.Contains(buf.String(), "stale pid file") {
t.Errorf("expected stale pid report, got %q", buf.String())
}
}
func TestDaemonStatusRunning(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
dir, _ := connectDaemonDir("live")
// Use our own pid: guaranteed alive.
writeDaemonState(dir, daemonState{Pid: os.Getpid(), StartUnix: time.Now().Add(-90 * time.Second).Unix(), LogPath: "/l.log", DirKey: "live", ClientID: "cidX"})
var buf bytes.Buffer
if err := daemonStatus(&buf, "live"); err != nil {
t.Fatalf("daemonStatus: %v", err)
}
out := buf.String()
for _, want := range []string{"running", "pid:", "uptime:", "/l.log", "cidX"} {
if !strings.Contains(out, want) {
t.Errorf("status output missing %q; got %q", want, out)
}
}
}
func TestDaemonStopNotRunning(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
var buf bytes.Buffer
if err := daemonStop(&buf, "ghost"); err != nil {
t.Fatalf("daemonStop: %v", err)
}
if !strings.Contains(buf.String(), "not running") {
t.Errorf("expected 'not running', got %q", buf.String())
}
}
func TestDaemonStopStaleCleansPidFile(t *testing.T) {
connectDaemonDirOverride = t.TempDir()
t.Cleanup(func() { connectDaemonDirOverride = "" })
dir, _ := connectDaemonDir("stalestop")
writeDaemonState(dir, daemonState{Pid: deadPid(t), StartUnix: time.Now().Unix(), DirKey: "stalestop"})
var buf bytes.Buffer
if err := daemonStop(&buf, "stalestop"); err != nil {
t.Fatalf("daemonStop: %v", err)
}
if _, err := os.Stat(daemonPidPath(dir)); !os.IsNotExist(err) {
t.Errorf("stale pid file should be removed, stat err=%v", err)
}
if !strings.Contains(buf.String(), "stale") {
t.Errorf("expected stale cleanup message, got %q", buf.String())
}
}
// deadPid returns a pid that is not alive. It spawns `true`, waits for it to
// exit, and returns its pid — guaranteed reaped and gone.
func deadPid(t *testing.T) int {
t.Helper()
// A very high pid is almost never live; combine with a sanity probe.
for _, candidate := range []int{999999, 524287, 99999} {
if !processAlive(candidate) {
return candidate
}
}
t.Skip("could not find a guaranteed-dead pid on this host")
return 0
}
+38
View File
@@ -0,0 +1,38 @@
// 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.
//go:build !windows
package helpers
import (
"os/exec"
"syscall"
)
// daemonDetachSupported reports whether the current OS can detach a daemon.
const daemonDetachSupported = true
// detachSysProcAttr returns the SysProcAttr that detaches a child from the
// controlling terminal: Setsid starts a new session so the child survives the
// parent shell closing (no SIGHUP) and has no controlling tty. Used for the
// `connect --daemon` re-exec. Unix-only; Windows uses the stub.
func detachSysProcAttr() *syscall.SysProcAttr {
return &syscall.SysProcAttr{Setsid: true}
}
// applyDetach configures cmd so it runs in its own session, detached from the
// terminal.
func applyDetach(cmd *exec.Cmd) {
cmd.SysProcAttr = detachSysProcAttr()
}
@@ -0,0 +1,27 @@
// 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.
//go:build windows
package helpers
import "os/exec"
// daemonDetachSupported is false on Windows: the daemon uses POSIX setsid +
// signal-based stop, which has no direct equivalent here. `connect --daemon`
// errors out on Windows and users should run the foreground connector under a
// Windows service wrapper instead.
const daemonDetachSupported = false
// applyDetach is a no-op on Windows; daemon mode is rejected earlier.
func applyDetach(_ *exec.Cmd) {}

Some files were not shown because too many files have changed in this diff Show More