* feat(pat): A-core minimum viable loop for host-owned PAT
Enables third-party agents to integrate PAT via the smallest possible
contract surface. The flow a host needs to ship end-to-end:
1. Export DINGTALK_DWS_AGENTCODE in the spawned shell.
2. Run any `dws ...` business command.
3. On PAT hit, CLI exits with code 4 and writes a single-line stderr
JSON following docs/pat/contract.md §2.
4. Host parses the JSON and invokes `dws pat chmod <scope>...
--agentCode ... --grant-type ...` to grant.
5. Host replays the original command.
This PR intentionally ships ONLY the chmod path plus the host-owned
switch; the async flow (apply / status / scopes + authRequestId
registry + PAT_SCOPE_AUTH_REQUIRED active-request branch) lands in a
follow-up stacked PR (A-ext).
Scope of A-core:
- Host-owned PAT trigger: auth.HostOwnsPATFlow() keyed exclusively on
DINGTALK_DWS_AGENTCODE (DINGTALK_AGENT / DWS_CHANNEL / claw-type do
NOT participate).
- claw-type: hard-wired to "openClaw" in pkg/edition/default.go
MergeHeaders hook, matching historical main behavior and decoupled
from DINGTALK_AGENT.
- dws pat chmod: factory-built (newChmodCommand) so the PAT subcommand
tree has no shared package-level caller.
- stderr JSON classifier: internal/errors/pat.go covers PAT_NO_PERMISSION
/ PAT_LOW_RISK / PAT_MEDIUM_RISK / PAT_HIGH_RISK / PAT_SCOPE_*
selectors and fills data.hostControl for host consumption.
- Env contract: DINGTALK_SESSION_ID / DINGTALK_TRACE_ID /
DINGTALK_MESSAGE_ID carry HTTP trace headers (Chain B);
DWS_SESSION_ID (+ REWIND_SESSION_ID alias) is the lone fallback for
`dws pat chmod --session-id` (Chain A). The two chains are
independent; aliases do not cross-pollinate.
- Docs: docs/pat/{README,contract,host-integration}.md + refreshed
docs/architecture.md "PAT Architecture" chapter + docs/reference.md
PAT section. error-catalog.md folded into contract.md §6.
- Tests: host-owned signal, stderr contract, classifier, chmod factory,
retry / poll loop for the CLI-owned chmod path.
Compatibility: no breaking changes on main. All non-PAT commands are
untouched.
Follow-up PRs (in order):
- codex/pat-ext : dws pat apply / status / scopes + AsyncRegistry.
- codex/pat-oss-refactor (aka PR B) : oauth_helpers / secure_store
refactors split out per code review.
Made-with: Cursor
* fix(pat): unify host-owned stderr contract
* revert: drop PAT docs and changelog from pat core PR
* fix(pat): pin behavior auth endpoint
* fix(pat): recognize legacy tool miss
* fix(pat): fallback on gateway diagnostics
* fix(pat): treat authorization uri as opaque
* fix(pat): accept result envelope in device-flow polling
* feat(pat): add browser policy and poll compatibility
* fix(pat): keep CLI and host PAT contracts separate
* test(pat): isolate opaque uri retry env
* fix(pat): harden PAT result routing
* fix(pat): harden host-owned flow and runtime fallback
* fix(pat): preserve chmod failure on empty grant result
* refactor(pat): drop dead doc anchors, dedupe stderr injection helpers
Address two reviewer findings on top of the PAT-core series.
Fix:
- chmod: resolveSessionIDFromEnv silently selects DWS_SESSION_ID; drop
the slog.Warn that emitted both raw session ids into stderr /
~/.dws/logs.
- Remove every docs/pat/contract.md / error-catalog.md /
host-integration.md anchor from comments, help, and tests; those
files were never added by this branch. Comments are now self-contained
or point to docs/reference.md where applicable.
Refactor:
- internal/errors/pat.go: extract lookupCodeIn so getPATErrorCode and
getDWSGatewayErrorCode share one traversal; have ClassifyPatAuthCheck
delegate to getPATErrorCode instead of repeating the enum walk.
- internal/errors/pat.go + internal/app/pat_auth_retry.go: extract
ApplyHostMutations as the single injection point for data.hostControl
+ data.openBrowser; cleanPATJSON and enrichPATErrorForHostControl now
share it so the two stderr-JSON write paths cannot drift.
- internal/app/pat_auth_retry.go: drop buildPATScopeHostJSON and
buildHostControlState dead 1-line wrappers.
- internal/pat/chmod.go: drop unused patApply/Status/Scopes constants;
derive legacyToolArgs from toolArgs by clone + scopes->scope rename so
the two payloads stay in lock-step on every other field.
Net 15 files, +176 / -193. Verification:
env -u DINGTALK_DWS_AGENTCODE go test \
./internal/errors ./internal/auth ./internal/pat ./test/unit
env -u DINGTALK_DWS_AGENTCODE go test ./internal/app \
-run 'Test(IsPat|ExtractPat|PrintPat|PollPat|HandlePat|RetryWithPat|EnrichPAT|BuildPAT|DirectRuntime|ResolveIdentityHeaders)'
env -u DINGTALK_DWS_AGENTCODE go test -race \
./internal/pat ./internal/errors ./test/unit
env -u DINGTALK_DWS_AGENTCODE go test -race ./internal/app \
-run 'Test(HandlePat|RetryWithPat|EnrichPAT|BuildPAT|ResolveIdentityHeaders|DirectRuntime)'
go vet ./... && go build ./...
All green.
Made-with: Cursor
---------
Co-authored-by: shangguanxuan.sgx <shangguanxuan.sgx@alibaba-inc.com>
226 lines
6.4 KiB
Go
226 lines
6.4 KiB
Go
// 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 errors
|
|
|
|
import (
|
|
stderrors "errors"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestExitCodeByCategory(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
cases := []struct {
|
|
err error
|
|
want int
|
|
}{
|
|
{err: NewAPI("api"), want: 1},
|
|
{err: NewAuth("auth"), want: 2},
|
|
{err: NewValidation("validation"), want: 3},
|
|
{err: NewDiscovery("discovery"), want: 6},
|
|
{err: NewInternal("internal"), want: 5},
|
|
{err: stderrors.New("plain"), want: 5},
|
|
}
|
|
|
|
for _, tc := range cases {
|
|
if got := ExitCode(tc.err); got != tc.want {
|
|
t.Fatalf("ExitCode(%v) = %d, want %d", tc.err, got, tc.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPrintJSON(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
if err := PrintJSON(&b, NewValidation(
|
|
"bad flag",
|
|
WithReason("missing_required_flag"),
|
|
WithHint("Pass the required flag and retry."),
|
|
WithRetryable(true),
|
|
WithActions("dws schema doc.create_document", "retry command"),
|
|
WithSnapshot("/tmp/dws-recovery/snapshot.json"),
|
|
)); err != nil {
|
|
t.Fatalf("PrintJSON() error = %v", err)
|
|
}
|
|
|
|
got := b.String()
|
|
if !strings.Contains(got, "\"category\": \"validation\"") {
|
|
t.Fatalf("expected validation category in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "\"message\": \"bad flag\"") {
|
|
t.Fatalf("expected error message in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "\"reason\": \"missing_required_flag\"") {
|
|
t.Fatalf("expected reason in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "\"retryable\": true") {
|
|
t.Fatalf("expected retryable in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "\"hint\": \"Pass the required flag and retry.\"") {
|
|
t.Fatalf("expected hint in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "\"snapshot_path\": \"/tmp/dws-recovery/snapshot.json\"") {
|
|
t.Fatalf("expected snapshot path in output, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintHuman(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
if err := PrintHumanAt(&b, NewValidation(
|
|
"bad flag",
|
|
WithReason("missing_required_flag"),
|
|
WithOperation("calendar.list"),
|
|
WithServerKey("calendar"),
|
|
WithHint("Pass the required flag and retry."),
|
|
WithRetryable(true),
|
|
WithActions("retry command"),
|
|
WithSnapshot("/tmp/dws-recovery/snapshot.json"),
|
|
), VerbosityVerbose); err != nil {
|
|
t.Fatalf("PrintHuman() error = %v", err)
|
|
}
|
|
|
|
got := b.String()
|
|
if !strings.Contains(got, "Error: [VALIDATION] bad flag") {
|
|
t.Fatalf("expected formatted header in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Reason: missing_required_flag") {
|
|
t.Fatalf("expected reason in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Hint: Pass the required flag and retry.") {
|
|
t.Fatalf("expected hint in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Action: retry command") {
|
|
t.Fatalf("expected action in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Snapshot: /tmp/dws-recovery/snapshot.json") {
|
|
t.Fatalf("expected snapshot in verbose output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Retryable: true") {
|
|
t.Fatalf("expected retryable marker in output, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintHuman_NormalMode(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
PrintHuman(&b, NewValidation(
|
|
"bad flag",
|
|
WithHint("fix it"),
|
|
WithRetryable(true),
|
|
WithActions("retry"),
|
|
WithServerDiag(ServerDiagnostics{TraceID: "trace-abc", ServerErrorCode: "PARAM_ERROR"}),
|
|
))
|
|
|
|
got := b.String()
|
|
if !strings.Contains(got, "Error: [VALIDATION] bad flag") {
|
|
t.Fatalf("expected header, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Trace ID: trace-abc") {
|
|
t.Fatalf("expected trace id in normal output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "Server Code: PARAM_ERROR") {
|
|
t.Fatalf("expected server code in normal output, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintJSONIncludesServerDiag(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
if err := PrintJSON(&b, NewAPI(
|
|
"server error",
|
|
WithServerDiag(ServerDiagnostics{
|
|
TraceID: "trace-xyz",
|
|
ServerErrorCode: "TIMEOUT_ERROR",
|
|
TechnicalDetail: "deadline exceeded",
|
|
}),
|
|
)); err != nil {
|
|
t.Fatalf("PrintJSON() error = %v", err)
|
|
}
|
|
|
|
got := b.String()
|
|
if !strings.Contains(got, `"trace_id": "trace-xyz"`) {
|
|
t.Fatalf("expected trace_id in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, `"server_error_code": "TIMEOUT_ERROR"`) {
|
|
t.Fatalf("expected server_error_code in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, `"technical_detail": "deadline exceeded"`) {
|
|
t.Fatalf("expected technical_detail in output, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintJSONIncludesRPCCodeAndData(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
if err := PrintJSON(&b, NewAPI(
|
|
"JSON-RPC tools/call failed with code -32602: invalid arguments",
|
|
WithReason("tools_call_jsonrpc_invalid_params"),
|
|
WithRPCCode(-32602),
|
|
WithRPCData([]byte(`{"field":"base_id","error":"required"}`)),
|
|
)); err != nil {
|
|
t.Fatalf("PrintJSON() error = %v", err)
|
|
}
|
|
|
|
got := b.String()
|
|
if !strings.Contains(got, `"rpc_code": -32602`) {
|
|
t.Fatalf("expected rpc_code in output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, `"field"`) || !strings.Contains(got, `"base_id"`) {
|
|
t.Fatalf("expected rpc_data content in output, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintHumanIncludesRPCCode_Debug(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
if err := PrintHumanAt(&b, NewValidation(
|
|
"invalid params",
|
|
WithRPCCode(-32602),
|
|
WithRPCData([]byte(`"missing field"`)),
|
|
), VerbosityDebug); err != nil {
|
|
t.Fatalf("PrintHuman() error = %v", err)
|
|
}
|
|
|
|
got := b.String()
|
|
if !strings.Contains(got, "RPC Code: -32602") {
|
|
t.Fatalf("expected RPC Code in debug output, got %q", got)
|
|
}
|
|
if !strings.Contains(got, "RPC Data:") {
|
|
t.Fatalf("expected RPC Data in debug output, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintHumanHidesRPCCode_Normal(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var b strings.Builder
|
|
PrintHuman(&b, NewValidation(
|
|
"invalid params",
|
|
WithRPCCode(-32602),
|
|
))
|
|
|
|
got := b.String()
|
|
if strings.Contains(got, "RPC Code:") {
|
|
t.Fatalf("normal mode should not show RPC Code, got %q", got)
|
|
}
|
|
}
|