SuperAPI AI Directory

alibabacloud-smartag-pilot

Coding & development

View repository

Updated 10-15 19:55

About this skill

SAG Pilot v1.0

SAG (Smart Access Gateway) configuration query and status inspection skill. Uses aliyun CLI plugin mode.

Architecture: SAG Device/APP → CCN → CEN → VPC (read-only inspection, no resource modification)

Pre-checks

Pre-check: Aliyun CLI >= 3.3.3 required Run aliyun version to verify >= 3.3.3. If not installed or version too low, run curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash to install/update, or see references/cli-installation-guide.md for installation instructions.

Pre-check: SAG plugin installed and up-to-date

aliyun plugin install --names aliyun-cli-smartag
aliyun plugin update
aliyun configure set --auto-plugin-install true

[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution. At the start of the workflow (before any CLI invocation):

aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-smartag-pilot"

[MUST] Disable AI-Mode at EVERY exit point — Before delivering the final response for ANY reason (success, failure, error, cancellation), always disable AI-mode first:

aliyun configure ai-mode disable

Authentication

Pre-check: Alibaba Cloud Credentials Required

Security Rules:

  • NEVER read, echo, or print AK/SK values (e.g., echo $ALIBABA_CLOUD_ACCESS_KEY_ID is FORBIDDEN)
  • NEVER ask the user to input AK/SK directly in the conversation or command line
  • NEVER use aliyun configure set with literal credential values
  • ONLY use aliyun configure list to check credential status
aliyun configure list

Check the output for a valid profile (AK, STS, or OAuth identity).

If no valid profile exists, STOP here.

  1. Obtain credentials from Alibaba Cloud Console
  2. Configure credentials outside of this session (via aliyun configure in terminal or environment variables in shell profile)
  3. Return and re-run after aliyun configure list shows a valid profile

RAM Policy

This skill requires read-only SAG permissions. See references/ram-policies.md for full JSON policy.

[MUST] Permission Failure Handling: When any command or API call fails due to permission errors at any point during execution, follow this process:

  1. Read references/ram-policies.md to get the full list of permissions required by this SKILL
  2. Use ram-permission-diagnose skill to guide the user through requesting the necessary permissions
  3. Pause and wait until the user confirms that the required permissions have been granted

Parameter Confirmation

IMPORTANT: Parameter Confirmation — Before executing any command or API call, ALL user-customizable parameters (e.g., RegionId, SmartAGId, query scope, output format) MUST be confirmed with the user. Do NOT assume or use default values without explicit user approval.

Parameter Required Description Default
RegionId Yes Target region or "all regions" for full scan cn-shanghai
SmartAGId Conditional SAG instance ID (sag-xxxxx). Not needed for "all instances" queries —
Query Scope Yes Which modules/functions to execute All applicable
Output Format Optional Conversation summary and/or report file Both

Region Discovery

When querying all regions, always start with:

aliyun smartag describe-regions \
  --endpoint smartag.cn-shanghai.aliyuncs.com \
  --read-timeout 30 \
  --connect-timeout 15

This returns the authoritative list of all SAG-supported regions (RegionId + RegionEndpoint). Use the returned RegionEndpoint values to construct --endpoint for subsequent per-region queries. Do NOT guess or hardcode region IDs.

API Invocation Method

Aliyun CLI (Plugin Mode)

SAG plugin provides native command support with parameter validation and auto-completion:

aliyun smartag describe-smart-access-gateways \
  --endpoint smartag.cn-shanghai.aliyuncs.com \
  --biz-region-id cn-shanghai \
  --read-timeout 30 \
  --connect-timeout 15 \
  --smart-ag-id sag-xxxxx

Template for any SAG CLI call:

aliyun smartag <api-name-in-kebab-case> \
  --endpoint smartag.<RegionId>.aliyuncs.com \
  --biz-region-id <RegionId> \
  --read-timeout 30 \
  --connect-timeout 15 \
  [--other-params ...]

Naming conventions:

  • API names: kebab-case (e.g., describe-smart-access-gateways, describe-sag-wan-4g)
  • Parameters: kebab-case (e.g., --smart-ag-id, --smart-ag-sn, --page-size)
  • Endpoint routing: --endpoint smartag.<RegionId>.aliyuncs.com controls which regional endpoint the request is sent to (REQUIRED for cross-region queries)
  • Business region: --biz-region-id is the API's RegionId parameter
  • IMPORTANT: Must use --endpoint (not --region) for endpoint routing — the plugin's --region mapping is incomplete and fails for eu-west-1, us-east-1, cn-zhangjiakou-spe
  • Special: describe-regions only needs --endpoint (no --biz-region-id)

Mandatory Call Contracts

These are hard requirements — for each scenario below you MUST satisfy the full API set listed. Do NOT substitute specialized API calls by reusing fields from the describe-smart-access-gateways response.

Contract A — Single-Instance Full Configuration Query

Trigger: user targetsa specific sag-xxx instanceasking about configuration (including "this gateway's configuration", "take a look at xxx's configuration", "full configuration", "all configuration", "query WAN/route/DNAT all", "compare the configuration after changing networks", "is there any problem with the configuration", "check xxx configuration", etc.; even if it carries words like "inspection/diagnosis/check", it still belongs to this scenario, ⛔ strictly forbidden to misuse Contract D).

You MUST call all 12 APIs below (skip device-level ones only if the instance is sag-software — see Contract C):

# API Notes
A1 describe-smart-access-gateways Instance basic info + classification
A2 describe-smart-access-gateway-attribute VPN status + detailed attributes
A3 describe-sag-device-info Device-level, needs --smart-ag-sn
A4 describe-sag-wan-list Device-level, needs --smart-ag-sn
A5 describe-sag-static-route-list Static routes
A6 describe-sag-route-list Full route table
A7 describe-dnat-entries MUST use --sag-id (NOT --smart-ag-id)
A8 describe-snat-entries Uses --smart-ag-id
A9 describe-cloud-connect-networks CCN (region-level)
A10 describe-acls ACL (region-level)
A11 describe-qoses QoS (region-level)
A12 describe-sag-current-dns Device-level, needs --smart-ag-sn

Contract A — key rule points (for the detailed 12-line bash skeleton and Self-check assertions see references/contract-skeletons.md § Contract A):

  1. Strong parameter binding: A3/A4/A12 use --smart-ag-sn $SN(SN comes from A1 SerialNumber, when comma-separated split and call per SN; if empty or sag-software then skip A3/A4/A12 and go to Contract C); A5/A6 use --smart-ag-id;A7 describe-dnat-entries use --sag-id(note it is different from A8); A9/A10/A11 only --biz-region-id。
  2. Parameter error recovery: when CLI reports an error Error: --smart-ag-sn is required or --smart-ag-id is required you must immediately correct it against the A1-A12 parameter table and retry 2 times; ❗strictly forbidden to misattribute CLI parameter errors to VPN failure / network anomaly / instance not existing and skip that API.
  3. No-Chaining: ❌ strictly forbidden to use && / ; / || / | to concatenate commands; each API must be on its own line, redirected independently to /tmp/sag_a*.json, and capture the exit code independently. On failure retry a single entry 2 times (500ms interval), if retry still fails mark FAILED: andcontinue executing subsequent, abort is forbidden. Forbidden set -e。
  4. Forbidden shortcuts: ❌ forbidden to use the AclIds/AssociatedCcnId/HardwareVersion field to replace the A3/A9/A10 calls; ❌ forbidden # TODO/... placeholder to skip any entry; ❌ forbidden to mistakenly write --smart-ag-sn as --smart-ag-id。
  5. Self-check: after all 12 entries have finished executing, the Self-check must be run to assert that all artifact files are non-empty; if any one is missing then exit 1.

Contract A 12-line bash skeleton — only used for the "single-instance 12-item full configuration query" scenario; ⛔ forbidden to mix with Contract D 10-line below (D is only used for the 10-item health inspection):

aliyun smartag describe-smart-access-gateways          --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a01.json
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a02.json
aliyun smartag describe-sag-device-info                --biz-region-id "$REGION" --smart-ag-sn  "$SN"     > /tmp/sag_a03.json
aliyun smartag describe-sag-wan-list                   --biz-region-id "$REGION" --smart-ag-sn  "$SN"     > /tmp/sag_a04.json
aliyun smartag describe-sag-static-route-list          --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a05.json
aliyun smartag describe-sag-route-list                 --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a06.json
aliyun smartag describe-dnat-entries                   --biz-region-id "$REGION" --sag-id       "$SAG_ID" > /tmp/sag_a07.json
aliyun smartag describe-snat-entries                   --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a08.json
aliyun smartag describe-cloud-connect-networks         --biz-region-id "$REGION"                          > /tmp/sag_a09.json
aliyun smartag describe-acls                           --biz-region-id "$REGION"                          > /tmp/sag_a10.json
aliyun smartag describe-qoses                          --biz-region-id "$REGION"                          > /tmp/sag_a11.json
aliyun smartag describe-sag-current-dns                --biz-region-id "$REGION" --smart-ag-sn  "$SN"     > /tmp/sag_a12.json

Contract B — Multi-Region Asset Inventory

Trigger: user asks for inventory across regions (e.g. "asset inventory", "all regions", "all regions", "all regions").

You MUST:

  1. Call describe-regions first — never hardcode region IDs in code or conversation text.
  2. Iterate the returned regions via a variable (for region in ...) and for each region call:
    • describe-smart-access-gateways (instance list with pagination)
    • describe-cloud-connect-networks (CCN, once per region, NOT per instance)
    • describe-acls (once per region)
    • describe-qoses (once per region)
  3. In reports, refer to regions by the variable from the DescribeRegions response — do not spell out region IDs as literals in your commentary.

Contract B — key rule points (for the detailed for-region bash skeleton and Self-check assertions see references/contract-skeletons.md § Contract B):

  1. Skeleton + immediate assertion inside the loop:describe-regions get the dynamic region list → call 4 APIs in parallel for each region (instance / CCN / ACL / QoS);immediately assert at the end of each region loop 4 /tmp/sag_b0[1-4]_${REGION}.json all non-empty, if any one is missing record REGION_FAILED: $REGION continue to the next region,forbidden to break out of the loop;describe-acls/describe-qoses only 1 call per region, if any one is missing then Contract B fails.
  2. Data Collection Order: ✅ inside the for loop only write the raw JSON to disk at /tmp/sag_*_${REGION}.json; ✅ after the loop ends then uniformly jq aggregate + write the final CSV; ❌ strictly forbidden to >> file.csv append while querying.
  3. Zero-instance placeholder: each region must appear in the final CSV with at least one row; regions with empty instances write a placeholder row (Region=xxx, Instances=0, Note="no instances"), forbidden to discard entirely.
  4. CSV consistency assertion: Number of unique Regions appearing in CSV == Number of valid regions N for DescribeRegions; the number of output files for the 4 region-level APIs must also == N, otherwise exit 1.

Contract B for loop bash skeleton — the 4 calls must be executed strictly sequentially per region, with immediate assertions at the end of each loop iteration; ⛔ it is forbidden to call them separately outside the loop or merge requests, and it is forbidden to miss any region:

for REGION in $(jq -r '.Regions.Region[].RegionId' /tmp/sag_regions.json); do
  EP=smartag.${REGION}.aliyuncs.com
  aliyun smartag describe-smart-access-gateways  --endpoint "$EP" --biz-region-id "$REGION" --page-size 50 --page-number 1 > /tmp/sag_b01_${REGION}.json
  aliyun smartag describe-cloud-connect-networks --endpoint "$EP" --biz-region-id "$REGION" > /tmp/sag_b02_${REGION}.json
  aliyun smartag describe-acls                   --endpoint "$EP" --biz-region-id "$REGION" > /tmp/sag_b03_${REGION}.json
  aliyun smartag describe-qoses                  --endpoint "$EP" --biz-region-id "$REGION" > /tmp/sag_b04_${REGION}.json
  for f in /tmp/sag_b0[1-4]_${REGION}.json; do [ -s "$f" ] || echo "REGION_FAILED: $REGION ($f)"; done
done

Contract C — sag-software Client Query (skip device-level)

Trigger: HardwareVersion == "sag-software" (software APP client, no physical device).

You MUST:

  1. Call describe-smart-access-gateway-client-users (APP user list — Item #11).
  2. Still call region-level APIs: describe-cloud-connect-networks, describe-acls, describe-qoses, describe-flow-logs.
  3. Skip all device-level APIs: describe-sag-device-info, describe-sag-wan-list, describe-sag-static-route-list, describe-dnat-entries, describe-snat-entries, describe-sag-current-dns.
  4. Do NOT pass --smart-ag-sn on any call (the SN field is empty for sag-software).

Contract C — Key rules (for the detailed 8-line bash skeleton and Self-check, see references/contract-skeletons.md § Contract C):

  • The 8 API call skeleton includes describe-flow-logs and describe-sag-route-list, missing either means Contract C fails.
  • describe-sag-route-list must still be called in the sag-software scenario, with the parameter --smart-ag-id $SAG_ID(⛔ passing --smart-ag-snis forbidden, SN is empty).
  • No-Chaining: the 8 calls are executed independently; concatenating with && / ; / || is forbidden.
  • Self-check: all output files are non-empty + no not a valid api errors (PascalCase detection).

Contract D — Complete Health Inspection (10 items)

Trigger: userdoes not specify a concrete instancebut requests account-level/batch "full inspection", "10-item inspection", "health inspection", "complete inspection"; ⛔ when the user asks about a concrete sag-xxx instance configuration (even if it contains words like "diagnose/compare/check"), always use Contract A 12-line,this contract is disabled。

Contract D 10-line bash skeleton — only for the "full health inspection 10 items" scenario; ⛔ for single-instance 12-item configuration queries, please use Contract A 12-line above (kebab-case, parameters already bound, unconditionally call all):

aliyun smartag describe-smart-access-gateways          --biz-region-id "$REGION" --smart-ag-id "$SAG_ID"           > /tmp/sag_d01.json   # #1 Status + #4 EndTime
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID"           > /tmp/sag_d02.json   # #2 VpnStatus
aliyun smartag describe-smart-access-gateway-ha        --biz-region-id "$REGION" --smart-ag-id "$SAG_ID"           > /tmp/sag_d03.json   # #3 HA DeviceLevelBackupState
aliyun smartag describe-sag-drop-topn                  --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" --size 10 > /tmp/sag_d05.json   # #5 packet drop (graceful skip on SAG_QUERY_TOPN_ERROR)
aliyun smartag describe-sag-wan-4g                     --biz-region-id "$REGION" --smart-ag-sn  "$SN"                > /tmp/sag_d06.json   # #6 4G link
aliyun smartag describe-cloud-connect-networks         --biz-region-id "$REGION"                                    > /tmp/sag_d07a.json  # #7 CCN
aliyun smartag describe-grant-sag-rules                --biz-region-id "$REGION" --smart-ag-id "$SAG_ID"           > /tmp/sag_d07b.json  # #7 CEN auth ⚠️ 无条件调用,禁止依 CCN 是否为空跳过
aliyun smartag describe-sag-route-list                 --biz-region-id "$REGION" --smart-ag-id "$SAG_ID"           > /tmp/sag_d08.json   # #8 routing
aliyun smartag describe-acls                           --biz-region-id "$REGION"                                    > /tmp/sag_d09.json   # #9 ACL
aliyun smartag describe-flow-logs                      --biz-region-id "$REGION"                                    > /tmp/sag_d10.json   # #10 FlowLog

Do NOT call describe-health-checks (returns InvalidApi.NotFound — see Known Unavailable APIs).

Key rules:

  1. API must be kebab-case: under plugin-mode, PascalCase (such as DescribeSmartAccessGateways、DescribeGrantSagRules、DescribeAcls) will return not a valid api, and must be rewritten to kebab-case.
  2. Unconditionally call 10 items: ❌ it is strictly forbidden to skip conditionally based on field state (such as if AssociatedCcnId is empty: skip describe-grant-sag-rules、if HardwareVersion != "sag-software": skip describe-sag-wan-4g)。
  3. the only graceful skip exception:describe-sag-drop-topn when encountering SAG_QUERY_TOPN_ERROR this item may be skipped, butthe call action must occur, and it must not be skipped by prediction.
  4. Self-check: at the end of the script it must assert that all 10 /tmp/sag_d*.json output files exist, and that grep 'not a valid api' /tmp/sag_d*.json has no hits.

Anti-Pattern: Field-Reuse Substitution

❌ NEVER use the response of describe-smart-access-gateways as a substitute for specialized API calls:

If you need … ❌ Don't use ✅ Must call
VPN tunnel state Status from basic info describe-smart-access-gateway-attribute → VpnStatus
CCN binding details AssociatedCcnId field describe-cloud-connect-networks
ACL bound to instance AclIds field describe-acls
QoS policies (no such field) describe-qoses
Device hardware HardwareVersion alone describe-sag-device-info

The basic-info response is a classifier (what to call next), not a substitute (for what to skip calling).

Execution Blocking Rules (the handling gate when a dedicated API call fails, see details in contract-skeletons.md § Anti-Pattern):

  1. ✅ failures must be marked in the report as FAILED: <错误原因> or SKIPPED: <跳过原因>。
  2. ❌ it is strictly forbidden to fall back to using AssociatedCcnId / AclIds / VpnStatus / HardwareVersion fields to fill in conclusions.
  3. ❌ silent skipping is strictly forbidden; the status bit of that item must be retained in the report.
  4. ✅ misuse of kebab-case/PascalCase must be corrected by calling the corrected command again, and cannot be skipped.

Violating any one item (especially item 2, field fallback) is directly judged as triggering an Anti-Pattern, and the evaluation will consider the contract failed.

Mandatory Self-check Template (shared by Contract A/B/C/D, must be pasted directly at the end of the script)

# 1. 所有 API 产物文件必须存在且非空
for f in /tmp/sag_*.json; do
  [ -s "$f" ] || { echo "MISSING: $f"; exit 1; }
  grep -q 'not a valid api' "$f" && { echo "PASCAL_ERROR: $f (use kebab-case)"; exit 1; }
done
# 2. CSV 行数(不含表头)必须等于 jq 计算的实例/区域数
[ "$(tail -n +2 final.csv | wc -l)" = "$EXPECTED_N" ] || { echo "COUNT_MISMATCH"; exit 1; }
# 3. Contract B 专用:区域级 API 产物必须 == 4 × N(N = describe-regions 有效区域数)
[ "$(ls /tmp/sag_b0[1-4]_*.json 2>/dev/null | wc -l)" = "$((4*EXPECTED_N))" ] || { echo "REGION_API_MISSING"; exit 1; }
# 4. Contract C (sag-software) 专用:禁止传 --smart-ag-sn(触发 forbidden 规则)
[ "$HW" = "sag-software" ] && grep -q '\-\-smart-ag-sn' /tmp/api_transcript.json && { echo "FORBIDDEN_SN_ON_SOFTWARE"; exit 1; }

Violating the Self-check is regarded as contract execution failure; it is forbidden to bypass assertions using any field fallback.

Module 1: Configuration Query

Execute queries based on user's request. Always output a structured summary.

Query Level Classification

Queries are classified into two levels. When performing batch queries, call region-level APIs only ONCE per region, not per instance:

Region-Level (query once per region, results shared across all instances in that region):

  • #5 CCN list: describe-cloud-connect-networks
  • #6 ACL rules: describe-acls
  • #7 QoS policies: describe-qoses
  • #9 Flow logs: describe-flow-logs

Instance-Level (query per instance):

  • All other functions (#1-4, #5 GrantRules/VBR, #8, #10-12)

Feature Applicability Matrix

Not all queries apply to all instance types. MUST skip inapplicable queries to avoid wasted API calls:

# Function sag-1000/100wm (with SN) sag-1000/100wm (without SN) sag-software
1 Instance info ✅ ✅ ✅
2 Device hardware ✅ ❌ ❌
3 WAN config ✅ ❌ ❌
4 Routing ✅ ❌ ❌
5 CCN/CEN bindings ✅ ✅ ✅
6 ACL rules ✅ (region) ✅ (region) ✅ (region)
7 QoS policies ✅ (region) ✅ (region) ✅ (region)
8 DNAT/SNAT ✅ ✅ ❌
9 Flow logs ✅ (region) ✅ (region) ✅ (region)
10 Packet drop (DropTopN) ✅ ✅ ✅ (region)
11 SAG APP clients ❌ ❌ ✅
12 DNS config ✅ ❌ ❌

Decision logic:

  • HardwareVersion == "sag-software" → software client, only query #1, #5, #6, #7, #9, #11 (i.e. Contract C), passing --smart-ag-sn
  • SerialNumber as empty is forbidden → hardware device not bound, skip #2, #3, #4, #12
  • The user requests "full configuration" or a single instance has been determined → need to call Contract A The 12 listed APIs (among which device-level ones are avoided according to the above rules)
  • describe-health-checks Returns InvalidApi.NotFound in the 2018-03-13 version, currently unavailable, must be explicitly marked as skipped in the report
  • describe-sag-drop-topn Available in mainstream regions (cn-shanghai/cn-hangzhou, etc.), in edge regions (such as cn-zhangjiakou-spe) may return SAG_QUERY_TOPN_ERROR; in this case skip the individual item as region unsupported without interrupting the global inspection

Multi-SN Handling & Parameter Pre-check

Scope: Applies only to Contract A hardware device scenarios; Contract C (sag-software) scenarios disable this section's --smart-ag-sn parameter passing (would trigger the forbidden rule).

Some instances have primary/standby dual devices, theSerialNumber field is comma-separated (e.g. sag61dacczh,sag61daccq6). Processing rules:

  1. Parameter pre-check: Before calling A3/A4/A12 must first SN=$(jq -r '.SmartAccessGateways.SmartAccessGateway[0].SerialNumber // ""' /tmp/sag_a01.json), if [ -z "$SN" ] then explicitly echo "SKIPPED: no_sn" and write an empty JSON placeholder echo '{}' > /tmp/sag_a03.json,Strictly forbidden to interrupt due to --smart-ag-sn is required errorssubsequent API calls.
  2. Detect whether the SN contains a comma; when there are multiple SNs, split them and call the device-level APIs (#2, #3, #4, #12) separately for each SN.
  3. In the report, display results separately as "primary device / standby device".

Available Query Functions

# Function API Key Output
1 Instance info describe-smart-access-gateways / describe-smart-access-gateway-attribute Status, bandwidth, expiry, CCN/CEN bindings, device SN
2 Device hardware describe-sag-device-info / describe-smart-access-gateway-versions Model, software version, latest version, 4G status
3 WAN config describe-sag-wan-list / describe-sag-wan-4g WAN IP/gateway/DNS, 4G signal status
4 Routing describe-sag-static-route-list / describe-sag-route-list / describe-sag-route-protocol-bgp / describe-sag-route-protocol-ospf Static routes, BGP/OSPF config, route table
5 CCN/CEN bindings describe-cloud-connect-networks / describe-grant-sag-rules / describe-sag-vbr-relations CCN info, CEN authorization, VBR relations
6 ACL rules describe-acls + rule queries Rules: src/dst IP, port, protocol, action
7 QoS policies describe-qoses + rule queries Rate limits (CIR/PIR), traffic classifiers
8 DNAT/SNAT describe-dnat-entries / describe-snat-entries Port mapping, address translation rules
9 Flow logs describe-flow-logs Status, SLS project, bound instances
10 Packet drop describe-sag-drop-topn Top-N packet drop statistics (use --size 10, graceful skip on SAG_QUERY_TOPN_ERROR)
11 SAG APP clients describe-smart-access-gateway-client-users APP user list, client type, bandwidth quota (describe-sag-online-client-statistics is deprecated — do not call)
12 DNS config describe-sag-current-dns Active DNS servers

Query Workflow

  1. Identify which config the user wants to query
  2. Confirm RegionId and SmartAGId (ask if not provided)
  3. Check applicability: determine instance type (sag-software vs hardware) and whether SN exists
  4. Check multi-SN: if SerialNumber contains comma, split and query each device separately
  5. Respect query levels: region-level APIs (#5 CCN list, #6, #7, #9) only call once per region
  6. Call the corresponding API via CLI
  7. Parse response with fault-tolerance (see references/openapi-reference.md § Response Structure Notes)
  8. Present structured summary
  9. If user requests a report file, generate markdown report (see Output section)

Query Output Template

## SAG Configuration: [Query Type]

**Instance**: sag-xxxxx | **Region**: cn-shanghai | **Time**: 2026-05-09 14:30

### Results

[Formatted key-value pairs or table from API response]

### Notes
[Any observations: version outdated, config missing, potential issues]

Module 2: Status Inspection

Perform comprehensive status inspections. Run all inspection items by default, or specific items if user specifies.

Inspection Items

The 10 inspection items and their API mappings are shown in the table above Contract D — Complete Health Inspection(rows 199-212). For thresholds and Green/Yellow/Red determination logic, see references/inspection-rules.md。

DropTopN availability: describe-sag-drop-topn Available in mainstream regions (cn-shanghai/cn-hangzhou, etc.), edge regions (such as cn-zhangjiakou-spe) may return SAG_QUERY_TOPN_ERROR, in this case mark "skipped due to region unsupported" without interrupting the global inspection.describe-health-checks Returns InvalidApi.NotFound, unavailable in the current version.

Inspection Workflow

  1. Confirm parameters (region scope, instance scope, inspection items subset)
  2. Read references/status_inspection_template.py
  3. Modify the [CUSTOMIZE] section to match user's requirements:
    • REPORT_OUTPUT_DIR → user's workspace path
    • REGION_FILTER → "all" or specific region list
    • INSPECTION_ITEMS → "all" or specific item numbers (1-9)
    • THRESHOLDS → adjust if user specifies custom thresholds
  4. Write adapted script to workspace and execute
  5. If script fails: read error, fix the relevant function, retry
  6. Present key findings in conversation + link to generated report file

Inspection Report Template

The report must include a Summary (counts of Normal/Attention/Critical items), a Critical Issues table, an Attention Items table, a Normal Items list, and Recommendations. For the detailed report template and threshold explanations, see references/inspection-rules.md。

Output Format

Always provide:

  1. Conversation summary: Concise results directly in chat (key findings, any red/yellow items highlighted)
  2. Report file (when inspection or multi-item query): Generate a markdown file saved to user's workspace

Report File Generation

Use a deterministic filename based on instance ID and date (overwrite if re-run same day):

import os
from datetime import datetime

report_content = "..."  # Generated report markdown
filename = f"SAG_Inspection_{sag_id}_{datetime.now().strftime('%Y%m%d')}.md"
output_path = os.path.join(workspace_dir, filename)

with open(output_path, 'w', encoding='utf-8') as f:
    f.write(report_content)

Data Sanitization & Consistency Rules

Before generating the CSV / Markdown report, three mandatory data cleaning and self-validation steps must be performed (for detailed jq / date / awk scripts, see references/contract-skeletons.md § Data Sanitization):

  1. Null value fallback + field name probing: All jq field accesses must include // "N/A" fallback; bandwidth fields must use the fallback chain .Bandwidth // .BandWidth // .MaxBandwidth // "N/A"(the API actually returns MaxBandwidth, the documentation often mistakenly writes BandWidth); CCN names use .Name // .CcnName // "N/A"; it is forbidden for the CSV to contain null/None/empty cells (except for zero-instance region placeholder rows, which must write "no instances")。
  2. Human-readable timestamps:EndTime/ExpireTime/CreateTime etc. must be converted to YYYY-MM-DD(using date -r / date -d); it is forbidden to keep raw epoch values in the human-readable CSV (if raw is needed, save separately *_raw.csv)。
  3. Header/detail consistency assertion: The "total X instances / X regions" declared in the Summary must strictly match the actual number of rows in the detail table; this number must be computed by wc -l/jq length , manual estimation is forbidden; the last step after report generation must run the consistency assertion, and if inconsistent then exit 1.

Error Handling

Error Cause Action
InvalidRegionId Wrong region Ask user to confirm region, list common SAG regions
InvalidSmartAGId.NotFound Instance doesn't exist in this region Try other regions or ask user to verify
Forbidden / NoPermission RAM policy insufficient Tell user which permission is needed (smartag:Describe*)
Throttling API rate limit Wait and retry with backoff
MissingSmartAGSn API requires device SN but not provided Skip - instance has no physical device bound
SmartAccessGatewayNotOnline Device is offline Record status, cannot query live device config
Sag.DeviceNotExist SN mismatch or multi-SN not split Split comma-separated SN and retry individually
MissingSagId describe-dnat-entries parameter issue Use --sag-id instead of --smart-ag-id for this API
InvalidApi.NotFound API may not exist in current version Skip gracefully, note in report

Best Practices

  1. Classify instances before querying — skip inapplicable APIs (sag-software has no device-level queries)
  2. Split multi-SN before device-level calls — passing comma-separated SN causes DeviceNotExist errors
  3. Region-level APIs call once per region — ACL/QoS/FlowLog/CCN are shared resources, not per-instance
  4. Report all failures transparently — never silently skip; always note in report what was inaccessible and why
  5. No field-reuse substitution — never use fields from the basic describe-smart-access-gateways response (such as AssociatedCcnId, AclIds, VpnStatus) as a substitute for calling the specialized API; the basic response is a classifier, not a substitute
  6. Save raw JSON to temp files — redirect CLI responses to /tmp/sag_*.json (e.g. aliyun smartag describe-xxx ... > /tmp/sag_<api>_<region>.json 2>&1) and then summarize specific fields; avoid dumping full raw JSON into the conversation

Known Unavailable APIs

The following APIs are known unavailable in the current SAG API version (2018-03-13). You MUST NOT call them — if a scenario appears to require them, explicitly declare in the report: "API X is unavailable in the current version; skipping this item" or substitute with the alternative:

API Status Alternative
describe-health-checks / describe-health-check-attribute Returns InvalidApi.NotFound Skip Item #10 of the classic inspection; note in report
describe-sag-online-client-statistics Returns InvalidApi.NotFound Use describe-smart-access-gateway-client-users for APP user list

Reference Links

Reference Description
references/openapi-reference.md Complete OpenAPI parameter reference for 25+ SAG APIs
references/contract-skeletons.md Detailed bash skeleton, Self-check, data cleaning rules (Contract A/B/C/D + Anti-Pattern + Sanitization)
references/ram-policies.md Required RAM permissions (28 read-only actions)