{"id":"062e59a1-76d1-4808-b3c6-7e885f377355","entityType":"agent","slug":"clawhub-sdk-team-alibabacloud-sls-query","name":"Alibabacloud Sls Query","canonicalUrl":"https://www.xpersona.co/agent/clawhub-sdk-team-alibabacloud-sls-query","canonicalPath":"/agent/clawhub-sdk-team-alibabacloud-sls-query","generatedAt":"2026-10-11T07:41:11.818Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:02:31.758Z","emptyReason":null},"description":"Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index...","descriptionLabel":"Source description","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.2K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s173swjet2yrebzqrp6hjkvmy583mxef:alibabacloud-sls-query","sourceUrl":"https://clawhub.ai/sdk-team/alibabacloud-sls-query","homepage":"https://clawhub.ai/sdk-team/skills/alibabacloud-sls-query","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/sdk-team/alibabacloud-sls-query","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/sdk-team/skills/alibabacloud-sls-query","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":61,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Alibabacloud Sls Query technical dossier on Xpersona with agent coverage, OPENCLEW support, and live trust metadata."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:02:31.758Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:02:31.758Z","emptyReason":null},"stars":null,"forks":null,"downloads":1166,"packageName":null,"latestVersion":"0.0.2","tractionLabel":"1.2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:02:31.743Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T04:02:31.758Z","lastCrawledAt":"2026-10-11T04:02:31.743Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T04:02:31.743Z","lastVerifiedAt":null,"highlights":[{"version":"0.0.2","createdAt":"2026-06-29T02:00:04.266Z","changelog":"alibabacloud-sls-query v0.0.2 - Added explicit per-session random user-agent format requirement for all aliyun API commands, enhancing observability and traceability. - Updated prerequisite steps: removed AI mode instructions; clarified plugin update and user-agent requirements. - Improved documentation across references and guides for more concise, accurate workflow and permission setup. - Removed unused or obsolete files (e.g., skill-card.md). - Expanded details for session/user-agent usage and security policy adherence.","fileCount":62,"zipByteSize":85597},{"version":"0.0.1","createdAt":"2026-04-24T07:57:27.614Z","changelog":"- Minor update to skill trigger phrases: replaced \"SLS 排障\" with \"analyze sls logs\" in the trigger list. - No functional changes to workflow, requirements, or usage instructions.","fileCount":62,"zipByteSize":84331},{"version":"0.0.1-beta.2","createdAt":"2026-04-24T03:59:52.389Z","changelog":"- Adds detailed guidance for handling user-provided time ranges in log queries, including relative time, absolute time, and timezone normalization. - Expands instructions in \"Step 4: Resolve the Time Range\" with specific input patterns and parsing choices. - Structure and workflow for query building remain unchanged. - No code or feature changes beyond documentation.","fileCount":61,"zipByteSize":82780},{"version":"0.0.1-beta.1","createdAt":"2026-04-24T01:59:17.291Z","changelog":"Alibaba Cloud SLS log query & analysis skill - initial release. - Enables users to write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL statements using the aliyun CLI. - Provides detailed workflow: checking index config, selecting query mode, building query statements, and handling time ranges. - Incorporates security rules for credential handling; includes permission requirements and troubleshooting steps. - Step-by-step guidance for choosing query mode (index, SQL, SQL scan, SPL) based on index config and user needs. - Reference links and permission handling guidance included for enhanced reliability.","fileCount":61,"zipByteSize":82376}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s173swjet2yrebzqrp6hjkvmy583mxef:alibabacloud-sls-query","setupComplexity":"low","setupSteps":["Install using `clawhub skill install s173swjet2yrebzqrp6hjkvmy583mxef:alibabacloud-sls-query` in an isolated environment before connecting it to live workloads.","No published capability contract is available yet, so validate auth and request/response behavior manually.","Review the upstream CLAWHUB listing at https://clawhub.ai/sdk-team/alibabacloud-sls-query before using production credentials."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T07:41:11.814Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-sdk-team-alibabacloud-sls-query/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:02:31.758Z","emptyReason":null},"readme":"Skill: Alibabacloud Sls Query\n\nOwner: sdk-team\n\nSummary: Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index...\n\nTags: latest:0.0.2\n\nVersion history:\n\nv0.0.2 | 2026-06-29T02:00:04.266Z | auto\n\nalibabacloud-sls-query v0.0.2\n\n- Added explicit per-session random user-agent format requirement for all aliyun API commands, enhancing observability and traceability.\n- Updated prerequisite steps: removed AI mode instructions; clarified plugin update and user-agent requirements.\n- Improved documentation across references and guides for more concise, accurate workflow and permission setup.\n- Removed unused or obsolete files (e.g., skill-card.md).\n- Expanded details for session/user-agent usage and security policy adherence.\n\nv0.0.1 | 2026-04-24T07:57:27.614Z | auto\n\n- Minor update to skill trigger phrases: replaced \"SLS 排障\" with \"analyze sls logs\" in the trigger list.\n- No functional changes to workflow, requirements, or usage instructions.\n\nv0.0.1-beta.2 | 2026-04-24T03:59:52.389Z | auto\n\n- Adds detailed guidance for handling user-provided time ranges in log queries, including relative time, absolute time, and timezone normalization.\n- Expands instructions in \"Step 4: Resolve the Time Range\" with specific input patterns and parsing choices.\n- Structure and workflow for query building remain unchanged.\n- No code or feature changes beyond documentation.\n\nv0.0.1-beta.1 | 2026-04-24T01:59:17.291Z | auto\n\nAlibaba Cloud SLS log query & analysis skill - initial release.\n\n- Enables users to write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL statements using the aliyun CLI.\n- Provides detailed workflow: checking index config, selecting query mode, building query statements, and handling time ranges.\n- Incorporates security rules for credential handling; includes permission requirements and troubleshooting steps.\n- Step-by-step guidance for choosing query mode (index, SQL, SQL scan, SPL) based on index config and user needs.\n- Reference links and permission handling guidance included for enhanced reliability.\n\nArchive index:\n\nArchive v0.0.2: 62 files, 85597 bytes\n\nFiles: references/acceptance-criteria.md (4680b), references/cli-installation-guide.md (10666b), references/functions-guide.md (2297b), references/functions/aggregate.yaml (1352b), references/functions/approximate.yaml (1936b), references/functions/array.yaml (5124b), references/functions/binary.yaml (2184b), references/functions/bitwise.yaml (1682b), references/functions/color.yaml (1359b), references/functions/comparison.yaml (2378b), references/functions/conditional.yaml (1523b), references/functions/conversion.yaml (1430b), references/functions/datetime.yaml (1920b), references/functions/encoding.yaml (969b), references/functions/geo.yaml (1121b), references/functions/geospatial.yaml (2262b), references/functions/hash.yaml (693b), references/functions/hyperloglog.yaml (1313b), references/functions/ip_geo.yaml (935b), references/functions/json.yaml (901b), references/functions/lambda.yaml (3130b), references/functions/map.yaml (3609b), references/functions/math.yaml (1566b), references/functions/mobile.yaml (1107b), references/functions/operators.yaml (2310b), references/functions/overview.yaml (8152b), references/functions/README.md (3654b), references/functions/regex.yaml (1477b), references/functions/statistical.yaml (2182b), references/functions/string.yaml (3145b), references/functions/type_conversion.yaml (917b), references/functions/url.yaml (1093b), references/functions/window_funnel.yaml (2007b), references/functions/window.yaml (3045b), references/query_analysis/indexConfig.yaml (6471b), references/query_analysis/indexSearch.yaml (12221b), references/query_analysis/overview.yaml (5997b), references/query_analysis/sql.yaml (9043b), references/query-analysis.md (5186b), references/ram-policies.md (3281b), references/regions.md (3352b), references/related-apis.md (6189b), references/spl-guide.md (3368b), references/spl/extend.yaml (628b), references/spl/json_string_process.yaml (3407b), references/spl/limit.yaml (750b), references/spl/overview.yaml (9758b), references/spl/pack-fields.yaml (1420b), references/spl/parse-csv.yaml (479b), references/spl/parse-json.yaml (1011b), references/spl/parse-kv.yaml (468b), references/spl/parse-regexp.yaml (629b), references/spl/project-away.yaml (412b), references/spl/project-rename.yaml (413b), references/spl/project.yaml (574b), references/spl/sort.yaml (763b), references/spl/stats.yaml (1245b), references/spl/where.yaml (611b), references/troubleshooting.md (2685b), skill-card.md (3886b), SKILL.md (17440b), _meta.json (141b)\n\nFile v0.0.2:SKILL.md\n\n---\nname: alibabacloud-sls-query\ndescription: |\n  Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL scan/pipeline statements through the aliyun CLI.\n  Triggers: \"SLS 查询\", \"SLS 分析\", \"日志查询\", \"日志分析\", \"log query\", \"analyze sls logs\", \"aliyun log query\".\n---\n\n# Alibaba Cloud SLS Query & Analysis\n\n## Scenario Description\n\nUse this skill when the user wants to:\n\n- Explain, rewrite, optimize or execute an existing query\n- Translate a natural-language requirement into an SLS **index query**, **SQL**, or **SPL** statement\n\n---\n\n## Prerequisites\n\n### Install Aliyun CLI\n\nRun `aliyun version` to verify if version >= `3.3.8`. If not installed or outdated, follow the doc [references/cli-installation-guide.md](references/cli-installation-guide.md) to install or update.\n\n### Update Plugins\n\n```bash\naliyun plugin update\n```\n\n### Check Alibaba Cloud credentials configured\n\nRun `aliyun configure list` to check if credentials configured.\nIf no valid profile is shown, **STOP** here and ask the user to run `aliyun configure` outside of this session.\n\n**Security rules:**\n\n- **NEVER** read, echo, or print AK/SK values\n- **NEVER** ask the user to paste AK/SK into the conversation\n- **ONLY** use `aliyun configure list` to check credential status\n\n---\n\n## RAM Permission Requirements\n\n| API | CLI | Action | Purpose |\n|-----|-----|--------|---------|\n| GetLogsV2 | `get-logs-v2` | `log:GetLogStoreLogs` | Run query / SQL / SPL and read results |\n| GetIndex  | `get-index`   | `log:GetIndex`        | Read index config to verify prerequisites |\n\nFor the minimum and complete RAM policy JSON, see [references/ram-policies.md](references/ram-policies.md).\n\n> **Permission failure handling:** If a call returns `Unauthorized` permission error, stop and surface [references/ram-policies.md](references/ram-policies.md) to the user. Do **not** retry with a different account without explicit user confirmation.\n\n---\n\n## Observability (MUST follow for every aliyun api command)\n\nUpon loading this skill, generate a random session ID (32-char lowercase hex string) once for the entire session. Use it as `{session-id}` below.\n\n**Rule:** Every `aliyun` CLI command that calls a cloud API **MUST** include the `--user-agent` flag. Local utility commands (e.g. `configure`, `plugin`, `version`) do not support this flag and should be excluded.\n\n```\n--user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query/{session-id}\"\n```\n\nExample (assuming session-id is `a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6`):\n\n```bash\naliyun sls get-logs-v2 --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 --query '*' \\\n  --user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6\"\n```\n\nDo not skip, alter the format, or omit `--user-agent` on any `aliyun` API command invocation.\n\n---\n\n## Core Workflow\n\n1. Read index configuration (GetIndex)\n2. Pick query mode\n3. Build statement\n4. Resolve time range\n5. Execute query\n6. Extract data from response\n7. Present CLI command and results\n\n### Step 1: Read the Index Configuration (Mandatory)\n\nAlways call `get-index` first — the index config decides which query modes are available in Step 2.\n\n```bash\naliyun sls get-index \\\n  --project <project> --logstore <logstore>\n```\n\nTwo sections in the response drive every later decision:\n\n| Section | Meaning |\n|---------|---------|\n| `line`  | **Full-text index** — absence means full-text search is disabled |\n| `keys`  | **Field indexes** — map of field → `{ type, doc_value, token, caseSensitive, chn, ... }`. `doc_value: true` means statistics are enabled on that field |\n\nIf the call returns `IndexConfigNotExist` (HTTP 404), or the response has neither `line` nor `keys` populated, the Logstore has no index at all — stop immediately and tell the user they must create an index before any query / SQL / SPL can run.\n\n- **The response can be large** — extract only the fields relevant to the current query. Cache per `logstore` and reuse within the session.\n\nFor field types, tokenization, and how `get-index` maps to capabilities, see [references/related-apis.md](references/related-apis.md) and [references/query-analysis.md](references/query-analysis.md).\n\n---\n\n### Step 2: Pick the Query Mode (Critical)\n\nThe query statement takes one of the following forms:\n\n| Priority | Mode | Statement Form | Use when | Requires |\n|----------|------|----------------|----------|----------|\n| 1 | **Index search** | `<index-search>` | Filtering raw logs; return time-ordered and paginated logs | Full-text (`line`) or any field index (`keys.<field>`) |\n| 2 | **SQL** | `<index-search> \\| <SQL>` | Aggregation, `GROUP BY`, sort, window, top-N, projection, and other analytical operations | Target field has `keys.<field>` with `doc_value: true` |\n| 3 | **SQL scan** | `<index-search> \\| <SQL scan>` | User requested | None |\n| 4 | **SPL** | `<index-search> \\| <SPL>` | User requested | None |\n\n**Selection rule:**\n\n- Always prefer **Index search** for fastest speed.\n- Use **Index search + SQL** when the user needs analytical operations or field projection rather than full raw-log retrieval, such as aggregation, `GROUP BY`, sorting, window analysis, top-N, or returning only the required fields/columns.\n- Do **not** proactively choose **SQL scan** or **SPL**; use them only when the user explicitly requests.\n\nFor the full decision guide, see [references/query-analysis.md](references/query-analysis.md).\n\n---\n\n### Step 3: Write the Statement\n\n#### 3.1 Build the index-search segment first (left of `|`)\n\nCollect every filter that can be expressed in index-search syntax and place it before the first `|`. Use `*` if no filter applies.\n\n```text\n* and \"payment failed\" and status: \"500\" and not path: \"/healthz\"\n```\n\n- `*` matches all; `\"...\"` is full-text (needs full-text index).\n- `key: \"value\"` is a field filter (needs field index).\n- Combine with `and` / `or` / `not`; group with parentheses.\n- `key: *` means field exists. Range (`>`, `>=`, `[a, b]`) works only on `long` / `double`.\n\nIf the requirement can be fully answered without aggregation or row-level processing, stop here — this is already a complete index search. For full index-search syntax, see [references/query-analysis.md](references/query-analysis.md).\n\n#### 3.2 Append SQL — for aggregation / analytics\n\n```sql\nstatus: 500 | SELECT date_trunc('minute', __time__) AS minute,\n                    count(*) AS errors\n              FROM log\n              GROUP BY minute\n              ORDER BY minute\n```\n\n- Read [references/query-analysis.md](references/query-analysis.md) for Query & SQL rules\n- Table name is `log` (recommended to omit).\n- SQL respects the indexed field type from `get-index` — a `long` / `double` field can be compared directly (`status >= 500`). Cast only when a field is indexed as `text` but numeric semantics are needed (`try_cast` to suppress errors).\n- Read [references/functions-guide.md](references/functions-guide.md) for unusual Function selection (aggregate, JSON, regex, datetime, IP geo …)\n\n#### 3.3 Append SPL — for row-level processing / flexible filtering\n\n```spl\nstatus: 500 and service: payment\n| where try_cast(latency as BIGINT) > 1000\n| extend latency_ms = try_cast(latency as BIGINT)\n| project service, latency_ms, message\n```\n\nFor SPL syntax, pipeline commands, and field-handling rules, read [references/spl-guide.md](references/spl-guide.md).\n\n#### 3.4 Append SQL scan — fallback when the target field has no index / statistics\n\nSyntax follows regular SQL (see 3.2), with one difference: **every field is `varchar`**, so always `cast()` / `try_cast()` before numeric comparison or arithmetic. See [references/query-analysis.md](references/query-analysis.md) for scan semantics.\n\n```sql\n* | set session mode=scan; SELECT api, count(1) AS pv FROM log GROUP BY api\n```\n\n---\n\n### Step 4: Resolve the Time Range\n\nGenerate `--from` / `--to` as **Unix timestamps in seconds** before building the CLI command. `--from` is inclusive and `--to` is exclusive.\n\nChoose one of three input patterns:\n\n1. **Relative time** — user says \"recent / last N minutes|hours|days\".\n2. **Natural-language absolute time without timezone** — normalize to `YYYY-MM-DD HH:MM:SS`, then parse using the machine's local timezone.\n3. **Absolute time with explicit timezone** — parse using the customer-provided timezone or UTC offset.\n\n**1. Relative time**\n\n```bash\n# recent 15 minutes\nFROM=$(($(date +%s) - 900))\nTO=$(date +%s)\n```\n\n**2. Natural-language absolute time without timezone**\n\nIf the user gives a date/time but no timezone, use the machine's local timezone. First normalize natural language such as `2026年3月13日12点` to `2026-03-13 12:00:00`, then parse it as local time.\n\n```bash\n# Example: 2026年3月13日12点 -> 2026-03-13 12:00:00\n\n# Linux (GNU date): local timezone\nFROM=$(date -d \"2026-03-13 12:00:00\" +%s)\n\n# macOS (BSD date): local timezone\nFROM=$(date -j -f \"%Y-%m-%d %H:%M:%S\" \"2026-03-13 12:00:00\" +%s)\n```\n\nFor a time range such as \"2026年3月13日12点到13点\", compute both endpoints the same way. For a single point-in-time request, infer a practical window from the user's intent; if unclear, ask for the range before executing.\n\n**3. Absolute time with explicit timezone**\n\nTo convert a local date/time to a Unix timestamp: parse the input as UTC with `date -u`, then **subtract** the timezone's UTC offset in seconds.\n\nFormula: `unix_ts = date_utc_parse(input) − (UTC_offset_hours × 3600)`\n\n```bash\n# Example: 2025-01-15 10:30:00 Beijing Time (UTC+8)\n# Beijing is UTC+8, so subtract 8 × 3600 = 28800\n\n# Linux (GNU date)\nFROM=$(( $(date -u -d \"2025-01-15 10:30:00\" +%s) - 28800 ))\n\n# macOS (BSD date)\nFROM=$(( $(date -u -j -f \"%Y-%m-%d %H:%M:%S\" \"2025-01-15 10:30:00\" +%s) - 28800 ))\n```\n\n```bash\n# Example: 2025-01-15 10:30:00 New York Time (UTC-5)\n# New York is UTC-5, so subtract -5 × 3600 = subtract -18000 = add 18000\n\n# Linux (GNU date)\nFROM=$(( $(date -u -d \"2025-01-15 10:30:00\" +%s) + 18000 ))\n\n# macOS (BSD date)\nFROM=$(( $(date -u -j -f \"%Y-%m-%d %H:%M:%S\" \"2025-01-15 10:30:00\" +%s) + 18000 ))\n```\n\nCommon UTC offsets (value to subtract):\n\n| Timezone         | UTC offset hours | Seconds to subtract |\n|------------------|------------------|---------------------|\n| Beijing (UTC+8)  | +8               | `28800`             |\n| Tokyo (UTC+9)    | +9               | `32400`             |\n| London (UTC)     | 0                | `0`                 |\n| New York (UTC-5) | -5               | `-18000`            |\n\n---\n\n### Step 5: Execute via `get-logs-v2`\n\nUse `aliyun sls get-logs-v2` to execute queries. Run `aliyun help sls get-logs-v2` to see CLI parameter usage; read [references/related-apis.md](references/related-apis.md) for detailed API parameter descriptions.\n\n**Required CLI flags:**\n\n- `--project`: SLS project name\n- `--logstore`: Logstore name within the project\n- `--from`: Start of time range, **Unix timestamp in seconds** (inclusive)\n- `--to`: End of time range, **Unix timestamp in seconds** (exclusive)\n- `--query`: Statement built in Step 3\n\nPagination works differently depending on whether the statement has a `|`:\n\n#### 5.1 Index-search only — paginate with `--offset` / `--line`\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 \\\n  --query '* and \"payment failed\" and status: \"500\"' \\\n  --line 100 --offset 0 --reverse true\n```\n\n- Pagination: `--line` is page size (`1–100`, required); `--offset` is the start row (optional, default `0`).\n- Ordering: `--reverse true` returns newest first; default `false` is oldest first.\n\n#### 5.2 With SQL — paginate with `LIMIT` inside the statement\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 \\\n  --query 'status: \"500\" | SELECT request_uri, count(*) AS cnt FROM log GROUP BY request_uri ORDER BY cnt DESC LIMIT 20'\n```\n\n- SQL default result cap is **100 rows**. To get more results or paginate:\n  - `LIMIT count` — raise the cap (e.g., `LIMIT 500` returns up to 500 rows)\n  - `LIMIT offset, count` — paginate (e.g., `LIMIT 20, 20` for rows 21–40; `LIMIT 40, 20` for rows 41–60). Max offset+count is 1000000.\n  - **Do not** use `LIMIT count OFFSET offset` syntax — it is **not supported**. Always use `LIMIT offset, count`.\n- Ordering: use `ORDER BY <field> DESC/ASC` to sort.\n\n**Result completeness check:** every response contains `meta.progress`. If it is `Incomplete`, **re-issue the same request** until it returns `Complete`.\n\n---\n\n### Step 6: Extract Data from the Response\n\n`get-logs-v2` returns:\n\n```json\n{\n  \"meta\": { \"progress\": \"Complete\", \"count\": 10, ... },\n  \"data\": [ { \"field1\": \"value1\", ... }, ... ]\n}\n```\n\n| Field | Meaning |\n|-------|---------|\n| `meta.progress` | `Complete` or `Incomplete` (see Step 5) |\n| `meta.count` | Number of rows returned |\n| `data` | Array of log entries or aggregation rows; may contain `__time__` (Unix seconds, string) |\n\nUse `jq` (preferred) or `--cli-query` (JMESPath) to extract the fields the user needs:\n\n| Extract | `jq` | `--cli-query` (JMESPath) |\n|---------|------|--------------------------|\n| Data rows | `\\| jq '.data'` | `--cli-query 'data'` |\n| Progress | `\\| jq '.meta.progress'` | `--cli-query 'meta.progress'` |\n| Row count | `\\| jq '.meta.count'` | `--cli-query 'meta.count'` |\n| Specific fields | `\\| jq '.data[] \\| {LogStore, read_mb}'` | `--cli-query 'data[].{LogStore: LogStore, read_mb: read_mb}'` |\n\n---\n\n### Step 7: Present the CLI Command and Results\n\n**CLI command** — always show the full, copy-paste-ready `aliyun sls get-logs-v2 ...` command. Redact any AK/SK. If the query was not executed (write / explain scenario), present the command the user should run.\n\n**Results** — when a query was executed, use Step 6 to extract `data` and format according to the user's request (table, list, summary, etc.). Append one sentence explaining the query mode choice.\n\n---\n\n## Global Rules\n\n- **Always prefer Index search for fastest raw-log retrieval, and use Index search + SQL for analysis or field projection.**\n- **When the user only needs specific fields, use `SELECT` to project them** rather than fetching full raw logs — this reduces network overhead. Requires `doc_value: true` on the target fields (confirmed in Step 1).\n- **Do not** hard-code `__time__` filters — pass time range via `--from` / `--to`.\n- **Deprecated API**: never call `get-logs`; always use `get-logs-v2`.\n\n---\n\n## Troubleshooting\n\nWhen the user reports \"no data\", \"wrong result\", or a CLI error, walk through the checklist in this exact order:\n\n1. **Time range** — wrong `--from`/`--to`? Milliseconds instead of seconds? Recent writes still indexing?\n2. **Index configuration** — field index missing? Full-text index off? Target field not in `keys`?\n3. **Field type / statistics** — range query on a `text` field? SQL on a field without `doc_value`?\n4. **Syntax** — mixed SQL and SPL? Leading `*` in fuzzy match? SPL string escaping?\n5. **Mode choice** — scanning when an index-based query would do? Aggregating in SPL instead of SQL?\n6. **Completeness** — `meta.progress = Incomplete`, caller did not retry (see Step 5).\n7. **ProjectNotExist** — region or endpoint is wrong. Use cross-region discovery to locate the project automatically, or ask the user to confirm the region. **Before calling `get-project --cross-region true`, you MUST read the Cross-Region Discovery section in [references/regions.md](references/regions.md)** — this API is only available via `cn-zhangjiakou.log.aliyuncs.com` endpoint.\n8. **Network failure** (timeout, connection refused) — try switching to internal endpoint. See [references/regions.md](references/regions.md).\n\nFor the full catalog of failure modes and error codes, see [references/troubleshooting.md](references/troubleshooting.md) and the `Common Errors` table in [references/related-apis.md](references/related-apis.md).\n\n---\n\n## Reference Documents\n\n| Document | Description |\n|----------|-------------|\n| [references/query-analysis.md](references/query-analysis.md) | Mode decision, index-search / SQL rules, scan semantics |\n| [references/spl-guide.md](references/spl-guide.md) | SPL pipeline syntax, common commands, field handling |\n| [references/functions-guide.md](references/functions-guide.md) | Function categories, SQL/SPL differences, templates |\n| [references/troubleshooting.md](references/troubleshooting.md) | \"No data / wrong result / error\" playbook |\n| [references/related-apis.md](references/related-apis.md) | `GetLogsV2` and `GetIndex` API & CLI reference |\n| [references/ram-policies.md](references/ram-policies.md) | Minimum and complete RAM policies |\n| [references/cli-installation-guide.md](references/cli-installation-guide.md) | Aliyun CLI install, auth modes, profiles |\n| [references/regions.md](references/regions.md) | Region / endpoint configuration, internal endpoint, cross-region discovery (`get-project --cross-region true`, **only cn-zhangjiakou**) |\n| [references/acceptance-criteria.md](references/acceptance-criteria.md) | CLI invocation acceptance tests |\n| `references/query_analysis/*.yaml` · `references/spl/*.yaml` · `references/functions/*.yaml` | Source-of-truth YAMLs bundled with this skill |\n\nFile v0.0.2:references/functions/README.md\n\n# SLS Function Reference\n\nThis directory contains all functions supported by SLS SQL and SPL analysis statements, organized by category.\n\n## Directory Structure\n\n| File | Category | Description | Supported In |\n|------|----------|-------------|--------------|\n| `aggregate.yaml` | Aggregate Functions | count, sum, avg, max, min and other statistical functions | SQL |\n| `string.yaml` | String Functions | Text concatenation, substring, case conversion, find & replace | SQL + SPL |\n| `regex.yaml` | Regex Functions | Regex match, extract, replace | SQL + SPL |\n| `datetime.yaml` | Date/Time Functions | Time formatting, parsing, truncation, conversion | SQL + SPL |\n| `type_conversion.yaml` | Type Conversion Functions | cast, try_cast type conversion | SQL + SPL |\n| `conditional.yaml` | Conditional Functions | if, case, coalesce conditional logic | SQL + SPL |\n| `json.yaml` | JSON Functions | JSON data extraction and parsing | SQL + SPL |\n| `math.yaml` | Math Functions | Numeric calculations, rounding, exponentiation | SQL + SPL |\n| `url.yaml` | URL Functions | URL parsing and parameter extraction | SQL + SPL |\n| `ip_geo.yaml` | IP Geolocation Functions | IP to province, city, country, coordinates | SPL only |\n| `encoding.yaml` | Encoding/Decoding Functions | URL, Base64 encoding and decoding | SQL + SPL |\n| `hash.yaml` | Hash Functions | MD5, SHA1, SHA256 hash computation | SQL + SPL |\n\n## Usage\n\n### 1. Finding Functions\n\n- **By category**: Select the corresponding file from the table above\n- **By name**: Search for the specific function in the relevant YAML file\n- **By scenario**: Refer to `overview.yaml` for common scenario examples\n\n### 2. Function Details\n\nEach YAML file contains the following structure:\n\n```yaml\nfunctions:\n  - name: function_name\n    syntax: function_syntax\n    description: what_it_does\n    examples:\n      sql: SQL example\n      spl: SPL example\n    note: caveats (optional)\n```\n\n### 3. Important Notes\n\n#### Type Conversion\n- Fields default to VARCHAR type\n- Always use `cast()` or `try_cast()` before numeric comparison or arithmetic\n- Pay special attention to type conversion in SPL\n\nExample:\n```sql\n-- Correct\n* | SELECT * WHERE cast(status as BIGINT) >= 500\n\n-- Wrong\n* | SELECT * WHERE status >= 500\n```\n\n#### SQL vs SPL\n- **SQL**: uses SELECT, WHERE, GROUP BY syntax\n- **SPL**: uses extend, where, stats syntax\n- **Aggregate functions** are primarily used in SQL\n- **IP geo functions** are SPL only\n\n#### Regular Expressions\n- SPL uses the RE2 regex engine\n- Not supported: back-references (\\1), lookaround (?<=...), etc.\n- No double-escaping needed: `\\d` is written as `\\d`\n\n## Quick Examples\n\n### Statistical Analysis\n```sql\n-- Count by status code\n* | SELECT status, count(*) AS pv GROUP BY status ORDER BY pv DESC\n```\n\n### Time Grouping\n```sql\n-- Hourly aggregation\n* | SELECT date_trunc('hour', __time__) AS hour, count(*) AS pv GROUP BY hour\n```\n\n### Regex Extraction\n```sql\n-- Extract error codes\n* | SELECT regexp_extract(message, 'code:(\\d+)', 1) AS error_code, count(*) GROUP BY error_code\n```\n\n### JSON Parsing\n```sql\n-- Extract JSON fields\n* | SELECT json_extract_scalar(payload, '$.user.name') AS user, count(*) GROUP BY user\n```\n\n### IP Geo Analysis (SPL)\n```spl\n# Count by province\n* | extend province = ip_to_province(client_ip) | stats pv = count(*) by province\n```\n\n## Related Documents\n\n- [Function Index](./overview.yaml) - Function category index and usage guide\n- [SQL Query Syntax](../query_analysis/sql.yaml) - Complete SQL query syntax\n- [SPL Basic Syntax](../spl/overview.yaml) - SPL query basics\n- [Index Search](../query_analysis/indexSearch.yaml) - Keyword search syntax\n\nFile v0.0.2:_meta.json\n\n{\n  \"ownerId\": \"kn74p5w8ywv6prh40g0s82gmqh83nw54\",\n  \"slug\": \"alibabacloud-sls-query\",\n  \"version\": \"0.0.2\",\n  \"publishedAt\": 1782698404266\n}\n\nFile v0.0.2:references/acceptance-criteria.md\n\n# Acceptance Criteria: sls-query-analysis\n\n**Scenario**: SLS Log Query & Analysis\n**Purpose**: Skill testing acceptance criteria\n\n---\n\n## Correct CLI Invocation Patterns\n\n### 1. Command Format — verify product and API name\n\n#### CORRECT\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* and status: \"500\"' \\\n  --line 100\n```\n\n#### INCORRECT — Wrong product name\n\n```bash\naliyun log get-logs-v2 --project my-project --logstore my-logstore\n```\n\n**Why**: Product name is `sls`, not `log`, `logservice`, `aliyunlog`, or `aliyun-sls`.\n\n### 2. Parameter Format\n\n#### CORRECT — Kebab-case CLI sub-command and flags\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* | select count(*) as total from log' \\\n  --line 100 \\\n  --offset 0 \\\n  --reverse true\n```\n\n#### INCORRECT — PascalCase sub-command or flags\n\n```bash\n# Sub-command in PascalCase\naliyun sls GetLogsV2 --project my-project --logstore my-logstore\naliyun sls GetIndex  --project my-project --logstore my-logstore\n\n# Flags in PascalCase\naliyun sls get-logs-v2 --Project my-project --Logstore my-logstore --From 1740000000 --To 1740003600\n```\n\n**Why**: The SLS plugin uses **kebab-case** for both sub-commands (`get-logs-v2`, `get-index`) and flags (`--project`, `--logstore`, `--from`, `--to`, `--query`).\n\n#### INCORRECT — Using `--region-id` instead of `--region`\n\n```bash\naliyun sls get-logs-v2 --region-id cn-hangzhou --project p --logstore l --from 1 --to 2\n```\n\n**Why**: The CLI global flag is `--region`, not `--region-id`.\n\n#### INCORRECT — JSON `--params` string (old SDK pattern)\n\n```bash\naliyun sls get-logs-v2 --params '{\"Project\":\"my-project\",\"Logstore\":\"my-logstore\",\"From\":\"1740000000\",\"To\":\"1740003600\"}'\n```\n\n**Why**: The CLI takes individual flags, not a JSON `--params` blob.\n\n### 3. Authentication — never expose credentials\n\n#### CORRECT — Verify credential profile via default credential chain\n\n```bash\naliyun configure list\n```\n\n#### INCORRECT — Passing AK/SK directly in the command\n\n```bash\naliyun sls get-logs-v2 \\\n  --access-key-id LTAI5tXXXX \\\n  --access-key-secret 8dXXXX \\\n  --project p --logstore l --from 1740000000 --to 1740003600\n```\n\n**Why**: Credentials must come from the configured profile, environment variables, STS, or RAM role — never be typed into the command line.\n\n#### INCORRECT — Reading or printing raw credentials\n\n```bash\naliyun configure get           # FORBIDDEN: may expose credential details\ncat ~/.aliyun/config.json      # FORBIDDEN: may expose credential details\n```\n\n#### INCORRECT — Any command that prints environment credentials\n\n```bash\necho $ALIBABA_CLOUD_ACCESS_KEY_ID       # FORBIDDEN: example of secret output\nprintenv | grep -i credential           # FORBIDDEN: may reveal secrets\nenv | grep -i access_key                # FORBIDDEN: may reveal secrets\n```\n\n### 4. API Names — verify exact sub-command\n\n#### CORRECT\n\n```\nget-logs-v2      # OpenAPI Action: GetLogsV2\nget-index        # OpenAPI Action: GetIndex\n```\n\n#### INCORRECT\n\n```\nGetLogsV2          # PascalCase is the Action name, not the CLI sub-command\nGetIndex           # PascalCase is the Action name, not the CLI sub-command\ngetLogsV2          # Wrong casing\nget_logs_v2        # Wrong separator (snake_case)\ngetlogsv2          # Missing separators\nget-logs           # Deprecated — use get-logs-v2\nget-logs-2         # Wrong suffix (v2, not 2)\ndescribe-index     # Wrong verb — SLS uses get-, not describe-\nget-log-index      # Not a real sub-command — use get-index\n```\n\n### 5. Region Parameter\n\n#### CORRECT\n\n```bash\n--region cn-hangzhou\n--region cn-shanghai\n--region ap-southeast-1\n--region us-west-1\n```\n\n#### INCORRECT\n\n```bash\n--region hangzhou       # Missing country prefix\n--region cn-hangzhou-1  # Not a real region ID\n```\n\n**Why**: Only valid Alibaba Cloud region IDs are accepted (e.g., `cn-hangzhou`, `ap-southeast-1`). The project is region-scoped — a region mismatch returns `ProjectNotExist`.\n\n### 6. Time Parameters\n\n#### CORRECT — Unix timestamp in seconds\n\n```bash\n--from 1711324800 --to 1711411200\n```\n\n#### INCORRECT — Millisecond timestamps\n\n```bash\n--from 1711324800000 --to 1711411200000\n```\n\n**Why**: `--from` / `--to` are Unix **seconds**, not milliseconds.\n\n#### INCORRECT — Date or ISO strings\n\n```bash\n--from \"2024-03-25\"             --to \"2024-03-26\"\n--from \"2024-03-25T00:00:00Z\"   --to \"2024-03-26T00:00:00Z\"\n```\n\n**Why**: Only integer seconds are accepted; date strings must be converted first (e.g., `date -d \"2024-03-25 00:00:00 UTC\" +%s`).\n\nFile v0.0.2:references/cli-installation-guide.md\n\n# Aliyun CLI Installation & Configuration Guide\n\nComplete guide for installing and configuring Aliyun CLI.\n\n> **Aliyun CLI 3.3.8+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.8 or later for full plugin ecosystem coverage.\n\n## Installation\n\n### macOS or linux\n\n```bash\n/bin/bash -c \"$(curl -fsSL https://aliyuncli.alicdn.com/install.sh)\"\n\n# Verify\naliyun version\n```\n\n### Windows\n\n**Using Binary**\n\n1. Download from: <https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip>\n2. Extract the ZIP file\n3. Add the directory to your PATH environment variable\n4. Open new Command Prompt or PowerShell\n5. Verify: `aliyun version`\n\n**Using PowerShell**\n\n```powershell\n# Download\nInvoke-WebRequest -Uri \"https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip\" -OutFile \"aliyun-cli.zip\"\n\n# Extract\nExpand-Archive -Path aliyun-cli.zip -DestinationPath C:\\aliyun-cli\n\n# Add to PATH (requires admin privileges)\n$env:Path += \";C:\\aliyun-cli\"\n[Environment]::SetEnvironmentVariable(\"Path\", $env:Path, [System.EnvironmentVariableTarget]::Machine)\n\n# Verify\naliyun version\n```\n\n## Configuration\n\n### Quick Start\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id <your-access-key-id> \\\n  --access-key-secret <your-access-key-secret> \\\n  --region cn-hangzhou\n```\n\nAll `aliyun configure` commands support non-interactive flags, which is the recommended approach —\nit works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.\n\n**Where to Get Access Keys**\n\n1. Log in to Aliyun Console: <https://ram.console.aliyun.com/>\n2. Navigate to: AccessKey Management\n3. Create a new AccessKey pair\n4. Save the secret immediately — it's only shown once\n\n### Configuration Modes\n\nAliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.\n\n#### 1. AK Mode (Access Key)\n\nMost common mode for personal accounts and scripts.\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nConfiguration is stored in `~/.aliyun/config.json`:\n\n```json\n{\n  \"current\": \"default\",\n  \"profiles\": [\n    {\n      \"name\": \"default\",\n      \"mode\": \"AK\",\n      \"access_key_id\": \"LTAI5tXXXXXXXX\",\n      \"access_key_secret\": \"8dXXXXXXXXXXXXXXXXXXXXXXXX\",\n      \"region_id\": \"cn-hangzhou\",\n      \"output_format\": \"json\",\n      \"language\": \"en\"\n    }\n  ]\n}\n```\n\n#### 2. StsToken Mode (Temporary Credentials)\n\nFor short-lived access (tokens expire in 1-12 hours).\n\n```bash\naliyun configure set \\\n  --mode StsToken \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --sts-token v1.0:XXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.\n\n#### 3. RamRoleArn Mode (Assume RAM Role)\n\nAssume a RAM role for elevated or cross-account access.\n\n```bash\naliyun configure set \\\n  --mode RamRoleArn \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --ram-role-arn acs:ram::123456789012:role/AdminRole \\\n  --role-session-name my-session \\\n  --region cn-hangzhou\n```\n\nUse cases: cross-account resource access, temporary elevated privileges, role-based access control.\n\n#### 4. EcsRamRole Mode (ECS Instance RAM Role)\n\nUse the RAM role attached to an ECS instance — no credentials needed.\n\n```bash\naliyun configure set \\\n  --mode EcsRamRole \\\n  --ram-role-name MyEcsRole \\\n  --region cn-hangzhou\n```\n\nRequirements: must be running on an ECS instance with a RAM role attached.\n\nUse cases: scripts and automation running on ECS instances.\n\n#### 5. RsaKeyPair Mode (RSA Key Pair)\n\nUse RSA key pair for authentication (generate key pair in Aliyun Console first).\n\n```bash\naliyun configure set \\\n  --mode RsaKeyPair \\\n  --private-key /path/to/private-key.pem \\\n  --key-pair-name my-key-pair \\\n  --region cn-hangzhou\n```\n\n#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)\n\nCombine ECS instance role with RAM role assumption for cross-account access from ECS.\n\n```bash\naliyun configure set \\\n  --mode RamRoleArnWithEcs \\\n  --ram-role-name MyEcsRole \\\n  --ram-role-arn acs:ram::123456789012:role/TargetRole \\\n  --role-session-name my-session \\\n  --region cn-hangzhou\n```\n\n### Environment Variables\n\n**Highest priority** - overrides config file\n\n**Access Key Mode**\n\n```bash\nexport ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id\nexport ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret\nexport ALIBABA_CLOUD_REGION_ID=cn-hangzhou\n```\n\n**STS Token Mode**\n\n```bash\nexport ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id\nexport ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret\nexport ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token\nexport ALIBABA_CLOUD_REGION_ID=cn-hangzhou\n```\n\n**ECS RAM Role Mode**\n\n```bash\nexport ALIBABA_CLOUD_ECS_METADATA=role_name\n```\n\n**Use Case**:\n\n- CI/CD pipelines\n- Docker containers\n- Temporary credential override\n\n### Managing Multiple Profiles\n\n**Create Named Profiles**\n\n```bash\naliyun configure set --profile projectA \\\n  --mode AK \\\n  --access-key-id LTAI5tAAAAAAAA \\\n  --access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \\\n  --region cn-hangzhou\n\naliyun configure set --profile projectB \\\n  --mode AK \\\n  --access-key-id LTAI5tBBBBBBBB \\\n  --access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \\\n  --region cn-shanghai\n```\n\n**Use Specific Profile**\n\n```bash\naliyun ecs describe-instances --profile projectA\n\nexport ALIBABA_CLOUD_PROFILE=projectA\naliyun ecs describe-instances   # Uses projectA\n```\n\n**List and Switch Profiles**\n\n```bash\naliyun configure list                      # List all profiles\naliyun configure set --current projectA    # Switch default profile\n```\n\n### Credential Priority\n\nCredentials are loaded in this order (first found wins):\n\n1. **Command-line flag**: `--profile <name>`\n2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`\n3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.\n4. **Configuration file**: `~/.aliyun/config.json` (current profile)\n5. **ECS Instance RAM Role**: If running on ECS with attached role\n\n## Verification\n\n### Test Authentication\n\n```bash\n# Basic test - list regions\naliyun ecs describe-regions\n\n# Expected output: JSON array of regions\n```\n\n**If successful**, you'll see:\n\n```json\n{\n  \"Regions\": {\n    \"Region\": [\n      {\n        \"RegionId\": \"cn-hangzhou\",\n        \"RegionEndpoint\": \"ecs.cn-hangzhou.aliyuncs.com\",\n        \"LocalName\": \"华东 1（杭州）\"\n      },\n      ...\n    ]\n  },\n  \"RequestId\": \"...\"\n}\n```\n\n**If failed**, you'll see error messages:\n\n- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID\n- `SignatureDoesNotMatch` - Wrong Access Key Secret\n- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)\n- `Forbidden.RAM` - Insufficient permissions\n\n### Debug Configuration\n\n```bash\n# Show current configuration\naliyun configure get\n\n# Test with debug logging\naliyun ecs describe-regions --log-level=debug\n\n# Check credential provider\naliyun configure get mode\n```\n\n## Security Best Practices\n\n### 1. Use RAM Users (Not Root Account)\n\n❌ **Don't**: Use Aliyun root account credentials\n✅ **Do**: Create RAM users with specific permissions\n\n```bash\n# Create RAM user in console\n# Attach only necessary policies\n# Use RAM user's access keys\n```\n\n### 2. Principle of Least Privilege\n\nGrant only the minimum permissions needed:\n\n```bash\n# Example: Read-only ECS access\n# Attach policy: AliyunECSReadOnlyAccess\n```\n\n### 3. Rotate Access Keys Regularly\n\n```bash\n# Create new access key in RAM Console, then update configuration\naliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET\n# Delete old access key from console\n```\n\n### 4. Use STS Tokens for Temporary Access\n\n```bash\naliyun configure set --mode StsToken \\\n  --access-key-id XXXX --access-key-secret XXXX \\\n  --sts-token XXXX --region cn-hangzhou\n```\n\n### 5. Use ECS RAM Roles When Possible\n\n```bash\naliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou\n```\n\n### 6. Never Commit Credentials\n\n```bash\n# Add to .gitignore\necho \"~/.aliyun/config.json\" >> .gitignore\n\n# Use environment variables in CI/CD instead\n```\n\n### 7. Secure Config File\n\n```bash\n# Restrict permissions\nchmod 600 ~/.aliyun/config.json\n```\n\n## Troubleshooting\n\n### Issue: Command Not Found\n\n```bash\n# Check installation\nwhich aliyun\n\n# Check PATH\necho $PATH\n\n# Reinstall or add to PATH\n```\n\n### Issue: Authentication Failed\n\n```bash\n# Verify configuration\naliyun configure get\n\n# Test with debug\naliyun ecs describe-regions --log-level=debug\n\n# Check credentials in console\n# Verify access key is active\n```\n\n### Issue: Permission Denied\n\n```bash\n# Error: Forbidden.RAM\n\n# Check RAM user permissions\n# Attach necessary policies in RAM console\n# Example: AliyunECSFullAccess for ECS operations\n```\n\n### Issue: STS Token Expired\n\n```bash\n# Error: InvalidSecurityToken.Expired\n\n# Reconfigure with new token\naliyun configure set --mode StsToken \\\n  --access-key-id XXXX --access-key-secret XXXX \\\n  --sts-token NEW_TOKEN --region cn-hangzhou\n```\n\n### Issue: Wrong Region\n\n```bash\n# Some resources may not exist in the specified region\n\n# Check available regions\naliyun ecs describe-regions\n\n# Update default region\naliyun configure set region cn-shanghai\n```\n\n## Advanced Configuration\n\n### Custom Endpoint\n\n```bash\n# Use custom or private endpoint\nexport ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com\n```\n\n### Proxy Settings\n\n```bash\n# HTTP proxy\nexport HTTP_PROXY=http://proxy.example.com:8080\nexport HTTPS_PROXY=http://proxy.example.com:8080\n\n# No proxy for specific domains\nexport NO_PROXY=localhost,127.0.0.1,.aliyuncs.com\n```\n\n### Timeout Settings\n\n```bash\n# Connection timeout (default: 10s)\nexport ALIBABA_CLOUD_CONNECT_TIMEOUT=30\n\n# Read timeout (default: 10s)\nexport ALIBABA_CLOUD_READ_TIMEOUT=30\n```\n\n## Next Steps\n\nAfter installation and configuration:\n\n1. **Install plugins** for services you need (v3.3.1+ supports all published product plugins):\n\n   ```bash\n   aliyun plugin install --names ecs vpc rds\n\n   # List all available plugins\n   aliyun plugin list-remote\n   ```\n\n2. **Explore commands**:\n\n   ```bash\n   aliyun sls --help\n   aliyun fc --help\n   ```\n\n3. **Read documentation**:\n   - [Command Syntax Guide](./command-syntax.md)\n   - [Global Flags Reference](./global-flags.md)\n   - [Common Scenarios](./common-scenarios.md)\n\n## References\n\n- Official Documentation: <https://help.aliyun.com/zh/cli/>\n- RAM Console: <https://ram.console.aliyun.com/>\n- Access Key Management: <https://ram.console.aliyun.com/manage/ak>\n- Plugin Repository: <https://github.com/aliyun/aliyun-cli>\n\nFile v0.0.2:references/functions-guide.md\n\n# Function Selection Guide\n\nChoose a function category by scenario, then read the corresponding YAML in this skill.\n\n## High-Frequency Categories\n\n- Aggregation: `./functions/aggregate.yaml`\n- String processing: `./functions/string.yaml`\n- Regex matching: `./functions/regex.yaml`\n- Date/time handling: `./functions/datetime.yaml`\n- Type conversion: `./functions/type_conversion.yaml`\n- Conditional logic: `./functions/conditional.yaml`\n- JSON extraction: `./functions/json.yaml`\n- Math operations: `./functions/math.yaml`\n- URL parsing: `./functions/url.yaml`\n- Array / Map: `./functions/array.yaml`, `./functions/map.yaml`\n- Window analysis: `./functions/window.yaml`\n- Funnel analysis: `./functions/window_funnel.yaml`\n- Lambda expressions: `./functions/lambda.yaml`\n\n## Language Differences\n\n- **SQL + SPL both support**: string, regex, datetime, type conversion, conditional, JSON, math, URL, encoding, hash, array, Map, and most other basic functions\n- **SQL only**: window functions, bitwise operations, geospatial functions, HyperLogLog, statistical functions, funnel functions\n- **SPL only**: `ip_to_province`, `ip_to_city`, `ip_to_country`, `ip_to_geo`\n\n## Key Reminders\n\n- Always `cast()` or `try_cast()` before numeric comparison\n- Use `try_cast()` to avoid entire-row failures on conversion errors\n- Prefer `date_trunc()` or `date_format()` for time-based grouping\n- Prefer `json_extract()` / `json_extract_scalar()` for JSON fields\n- For SPL escape handling, prefer `ascii_escape`, `ascii_unescape`, `unicode_unescape`\n- SPL and SQL function capabilities are not always identical — when in doubt, consult the corresponding function YAML\n\n## Common Templates\n\n### Type Conversion\n```sql\n* | SELECT count(*) FROM log WHERE cast(status as BIGINT) >= 500\n```\n\n```spl\n* | where try_cast(status as BIGINT) >= 500\n```\n\n### JSON Extraction\n```sql\n* | SELECT json_extract_scalar(payload, '$.user.id') AS user_id, count(*) FROM log GROUP BY user_id\n```\n\n### Regex Extraction\n```sql\n* | SELECT regexp_extract(message, 'code:(\\d+)', 1) AS code, count(*) FROM log GROUP BY code\n```\n\n### SPL Geo Analysis\n```spl\n* | extend province = ip_to_province(client_ip) | stats pv = count(*) by province\n```\n\n## Source YAMLs\n\n- `./functions/overview.yaml`\n- `./functions/README.md`\n- `./functions/*.yaml`\n\nFile v0.0.2:references/functions/aggregate.yaml\n\ncategory: aggregate_functions\nname: 聚合函数\ndescription: 对数据进行汇总计算，通常与GROUP BY配合使用\n\nsupport: \n  sql: true\n  spl: false\n\nfunctions:\n  - name: count\n    syntax: \"count(*) 或 count(x)\"\n    description: 统计日志条数\n    example: \"* | SELECT count(*) AS pv\"\n    note: \"count(*) 统计所有，count(x) 统计x非NULL的数量\"\n  \n  - name: sum\n    syntax: \"sum(x)\"\n    description: 计算总和\n    example: \"* | SELECT sum(cast(response_size as BIGINT)) AS total_size\"\n  \n  - name: avg\n    syntax: \"avg(x)\"\n    description: 计算平均值\n    example: \"* | SELECT avg(cast(request_time as DOUBLE)) AS avg_time\"\n  \n  - name: max\n    syntax: \"max(x)\"\n    description: 返回最大值\n    example: \"* | SELECT max(cast(response_time as BIGINT)) AS max_time\"\n  \n  - name: min\n    syntax: \"min(x)\"\n    description: 返回最小值\n    example: \"* | SELECT min(cast(response_time as BIGINT)) AS min_time\"\n  \n  - name: count_if\n    syntax: \"count_if(condition)\"\n    description: 统计满足条件的日志数\n    example: \"* | SELECT count_if(cast(status as BIGINT) >= 500) AS error_count\"\n  \n  - name: arbitrary\n    syntax: \"arbitrary(x)\"\n    description: 返回任意一个非空值\n    example: \"* | SELECT status, arbitrary(request_time) GROUP BY status\"\n    note: 用于GROUP BY时获取非分组字段的值\n\nFile v0.0.2:references/functions/approximate.yaml\n\ncategory: approximate_functions\nname: 估算函数\ndescription: 基于数据预测或填充缺失值的近似计算\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: approx_distinct\n    syntax: \"approx_distinct(x)\"\n    description: 估算唯一值的个数，使用HyperLogLog算法\n    returns: 近似计数\n    example: \"* | SELECT approx_distinct(client_ip) AS uv\"\n    note: 比count(distinct x)更快，但是近似值\n  \n  - name: approx_percentile\n    syntax: \"approx_percentile(x, percentage)\"\n    description: 计算近似百分位数\n    params:\n      - x: 列名\n      - percentage: 百分位，取值0~1\n    example: \"* | SELECT approx_percentile(cast(request_time as double), 0.99) AS p99\"\n  \n  - name: approx_percentile (with array)\n    syntax: \"approx_percentile(x, array[p1, p2,...])\"\n    description: 同时计算多个百分位数\n    example: \"* | SELECT approx_percentile(cast(request_time as double), array[0.5, 0.95, 0.99]) AS percentiles\"\n  \n  - name: numeric_histogram\n    syntax: \"numeric_histogram(bucket_count, x)\"\n    description: 按照bucket数量统计x列的近似直方图\n    params:\n      - bucket_count: 桶的数量\n      - x: 数值列\n    returns: Map类型，键为桶的代表值，值为该桶的近似计数\n    example: \"* | SELECT numeric_histogram(10, cast(request_time as double))\"\n  \n  - name: numeric_histogram_u\n    syntax: \"numeric_histogram_u(bucket_count, x)\"\n    description: 按照bucket数量统计x列的近似直方图，返回多行格式\n    example: \"* | SELECT numeric_histogram_u(10, cast(request_time as double))\"\n\nuse_cases:\n  - 快速估算UV（独立访客）\n  - 计算性能指标的P50、P95、P99\n  - 生成数值分布直方图\n  - 大数据量下的快速统计\n\nimportant_notes:\n  - 估算函数牺牲精度换取性能\n  - approx_distinct使用HyperLogLog算法，标准误差约2.3%\n  - approx_percentile误差在1%以内\n  - 适用于大数据量场景\n\nFile v0.0.2:references/functions/array.yaml\n\ncategory: array_functions\nname: 数组函数和运算符\ndescription: 对数组进行增删改查、遍历和转换操作\n\nsupport:\n  sql: true\n  spl: partial\n\nfunctions:\n  - name: array_distinct\n    syntax: \"array_distinct(x)\"\n    description: 删除数组中重复的元素\n    examples:\n      sql: \"* | SELECT array_distinct(cast(json_parse(number) as array(bigint)))\"\n      spl: \"* | extend unique_arr = array_distinct(arr_field)\"\n  \n  - name: array_intersect\n    syntax: \"array_intersect(x, y)\"\n    description: 计算两个数组的交集\n    examples:\n      sql: \"* | SELECT array_intersect(array[1,2,3,4,5], array[1,3,5,7])\"\n      spl: \"* | extend intersection = array_intersect(arr1, arr2)\"\n  \n  - name: array_union\n    syntax: \"array_union(x, y)\"\n    description: 计算两个数组的并集\n    examples:\n      sql: \"* | SELECT array_union(array[1,2,3,4,5], array[1,3,5,7])\"\n    note: 仅支持SQL\n  \n  - name: array_except\n    syntax: \"array_except(x, y)\"\n    description: 计算两个数组的差集\n    examples:\n      sql: \"* | SELECT array_except(array[1,2,3,4,5], array[1,3,5,7])\"\n      spl: \"* | extend diff = array_except(arr1, arr2)\"\n  \n  - name: array_join\n    syntax: \"array_join(x, delimiter [, null_replacement])\"\n    description: 使用指定连接符将数组元素拼接为字符串\n    params:\n      - x: 数组\n      - delimiter: 连接符\n      - null_replacement: 可选，用于替换null元素的字符串\n    examples:\n      sql: \"* | SELECT array_join(array[null,'Log','Service'], ' ', 'Alicloud')\"\n      spl: \"* | extend joined = array_join(arr_field, ',')\"\n    note: 返回结果最大1KB，超出会被截断\n  \n  - name: array_max\n    syntax: \"array_max(x)\"\n    description: 获取数组中的最大值\n    examples:\n      sql: \"* | SELECT array_max(try_cast(json_parse(number) as array(bigint))) AS max_number\"\n  \n  - name: array_min\n    syntax: \"array_min(x)\"\n    description: 获取数组中的最小值\n    examples:\n      sql: \"* | SELECT array_min(try_cast(json_parse(number) as array(bigint))) AS min_number\"\n  \n  - name: array_position\n    syntax: \"array_position(x, element)\"\n    description: 获取指定元素的下标（从1开始），不存在返回0\n    examples:\n      sql: \"* | SELECT array_position(array[49,45,47], 45)\"\n  \n  - name: array_remove\n    syntax: \"array_remove(x, element)\"\n    description: 删除数组中指定的元素\n    examples:\n      sql: \"* | SELECT array_remove(array[49,45,47], 45)\"\n  \n  - name: array_sort\n    syntax: \"array_sort(x)\"\n    description: 对数组元素进行升序排序，null元素排在最后\n    examples:\n      sql: \"* | SELECT array_sort(array['b','d',null,'c','a'])\"\n  \n  - name: cardinality\n    syntax: \"cardinality(x)\"\n    description: 计算数组中元素的个数\n    examples:\n      sql: \"* | SELECT cardinality(cast(json_parse(number) as array(bigint)))\"\n  \n  - name: contains\n    syntax: \"contains(x, element)\"\n    description: 判断数组中是否包含指定元素\n    returns: boolean类型\n    examples:\n      sql: \"* | SELECT contains(cast(json_parse(region) as array(varchar)), 'cn-beijing')\"\n  \n  - name: reverse\n    syntax: \"reverse(x)\"\n    description: 对数组中的元素进行反向排列\n    examples:\n      sql: \"* | SELECT reverse(array[1,2,3,4,5])\"\n      spl: \"* | extend reversed = reverse(arr_field)\"\n  \n  - name: slice\n    syntax: \"slice(x, start, length)\"\n    description: 获取数组的子集\n    params:\n      - start: 索引开始位置（负数从末尾开始，正数从头部开始）\n      - length: 子集元素个数\n    examples:\n      sql: \"* | SELECT slice(array[1,2,4,5,6,7,7], 3, 2)\"\n  \n  - name: filter\n    syntax: \"filter(x, lambda_expression)\"\n    description: 结合Lambda表达式过滤数组元素\n    examples:\n      sql: \"* | SELECT filter(array[5,-6,null,7], x -> x > 0)\"\n      spl: \"* | extend filtered = filter(arr_field, x -> x > 0)\"\n  \n  - name: transform\n    syntax: \"transform(x, lambda_expression)\"\n    description: 将Lambda表达式应用到数组的每个元素\n    examples:\n      sql: \"* | SELECT transform(array[5,6], x -> x + 1)\"\n      spl: \"* | extend transformed = transform(arr_field, x -> x * 2)\"\n  \n  - name: reduce\n    syntax: \"reduce(x, lambda_expression)\"\n    description: 根据Lambda表达式对数组元素进行累加计算\n    examples:\n      sql: \"* | SELECT reduce(array[5,20,50], 0, (s, x) -> s + x, s -> s)\"\n  \n  - name: sequence\n    syntax: \"sequence(x, y [, step])\"\n    description: 返回起始值范围内连续递增的数组\n    params:\n      - x: 起始值\n      - y: 结束值\n      - step: 可选，递增间隔（默认为1）\n    examples:\n      sql: \"* | SELECT sequence(0, 10, 2)\"\n      spl: \"* | extend seq = sequence(1, 100)\"\n  \n  - name: zip\n    syntax: \"zip(x, y...)\"\n    description: 将多个数组合并为二维数组\n    examples:\n      sql: \"* | SELECT zip(array[1,2,3], array['1b',null,'3b'], array[1,2,3])\"\n\nimportant_notes:\n  - 数组下标从1开始\n  - array_join返回结果最大1KB\n  - 使用Lambda表达式可以实现复杂的数组处理逻辑\n  - 配合cast和json_parse处理JSON格式的数组字段\n\nFile v0.0.2:references/functions/binary.yaml\n\ncategory: binary_functions\nname: 二进制函数\ndescription: 处理二进制类型的数据，进行编码和解码\n\nsupport:\n  sql: true\n  spl: partial\n\nfunctions:\n  - name: from_base64\n    syntax: \"from_base64(x)\"\n    description: 对Base64编码的字符串进行解码\n    returns: varbinary类型\n    example: \"* | SELECT from_base64('aGVsbG8=')\"\n  \n  - name: to_base64\n    syntax: \"to_base64(x)\"\n    description: 将二进制数据编码为Base64字符串\n    returns: varchar类型\n    example: \"* | SELECT to_base64(cast('hello' as varbinary))\"\n  \n  - name: from_hex\n    syntax: \"from_hex(x)\"\n    description: 将十六进制字符串转换为二进制\n    example: \"* | SELECT from_hex('68656C6C6F')\"\n  \n  - name: to_hex\n    syntax: \"to_hex(x)\"\n    description: 将二进制数据转换为十六进制字符串\n    example: \"* | SELECT to_hex(cast('hello' as varbinary))\"\n  \n  - name: from_big_endian_64\n    syntax: \"from_big_endian_64(x)\"\n    description: 将大端序的8字节二进制转为bigint\n    example: \"* | SELECT from_big_endian_64(from_hex('0000000000000001'))\"\n  \n  - name: to_big_endian_64\n    syntax: \"to_big_endian_64(x)\"\n    description: 将bigint转为大端序的8字节二进制\n    example: \"* | SELECT to_big_endian_64(1)\"\n  \n  - name: md5\n    syntax: \"md5(x)\"\n    description: 计算MD5哈希值，返回二进制\n    example: \"* | SELECT to_hex(md5(cast('hello' as varbinary)))\"\n  \n  - name: sha1\n    syntax: \"sha1(x)\"\n    description: 计算SHA1哈希值，返回二进制\n    example: \"* | SELECT to_hex(sha1(cast('hello' as varbinary)))\"\n  \n  - name: sha256\n    syntax: \"sha256(x)\"\n    description: 计算SHA256哈希值，返回二进制\n    example: \"* | SELECT to_hex(sha256(cast('hello' as varbinary)))\"\n  \n  - name: sha512\n    syntax: \"sha512(x)\"\n    description: 计算SHA512哈希值，返回二进制\n    example: \"* | SELECT to_hex(sha512(cast('hello' as varbinary)))\"\n\nuse_cases:\n  - Base64编解码\n  - 哈希值计算\n  - 二进制数据处理\n  - 数据校验\n\nimportant_notes:\n  - 配合to_hex可以将二进制结果转为可读的十六进制\n  - 哈希函数返回二进制，通常需要to_hex转换\n  - 注意cast类型转换\n\nFile v0.0.2:references/functions/bitwise.yaml\n\ncategory: bitwise_functions\nname: 位运算函数\ndescription: 直接操作二进制位的运算函数\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: bit_count\n    syntax: \"bit_count(x, bits)\"\n    description: 统计二进制表示中1的个数\n    params:\n      - x: bigint类型的数值\n      - bits: 位数（32或64）\n    example: \"* | SELECT bit_count(5, 64)\"\n  \n  - name: bitwise_and\n    syntax: \"bitwise_and(x, y)\"\n    description: 按位与运算\n    example: \"* | SELECT bitwise_and(5, 3)\"\n  \n  - name: bitwise_or\n    syntax: \"bitwise_or(x, y)\"\n    description: 按位或运算\n    example: \"* | SELECT bitwise_or(5, 3)\"\n  \n  - name: bitwise_xor\n    syntax: \"bitwise_xor(x, y)\"\n    description: 按位异或运算\n    example: \"* | SELECT bitwise_xor(5, 3)\"\n  \n  - name: bitwise_not\n    syntax: \"bitwise_not(x)\"\n    description: 按位取反运算\n    example: \"* | SELECT bitwise_not(5)\"\n  \n  - name: bitwise_left_shift\n    syntax: \"bitwise_left_shift(x, n)\"\n    description: 按位左移n位\n    example: \"* | SELECT bitwise_left_shift(5, 2)\"\n  \n  - name: bitwise_right_shift\n    syntax: \"bitwise_right_shift(x, n)\"\n    description: 按位右移n位\n    example: \"* | SELECT bitwise_right_shift(5, 1)\"\n  \n  - name: bitwise_right_shift_arithmetic\n    syntax: \"bitwise_right_shift_arithmetic(x, n)\"\n    description: 算术右移n位（保留符号位）\n    example: \"* | SELECT bitwise_right_shift_arithmetic(-8, 2)\"\n\nuse_cases:\n  - 权限位掩码操作\n  - 标志位检查\n  - 位图运算\n  - 低级别数据处理\n\nimportant_notes:\n  - 所有位运算函数参数必须为bigint类型\n  - 需要先cast转换为bigint\n  - 位运算结果也是bigint类型\n\nFile v0.0.2:references/functions/color.yaml\n\ncategory: color_functions\nname: 颜色函数\ndescription: 颜色表示与转换，用于可视化展示\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: bar\n    syntax: \"bar(x, width [, low, high])\"\n    description: 生成ASCII条形图\n    params:\n      - x: 数值\n      - width: 条形图宽度\n      - low: 最小值（可选）\n      - high: 最大值（可选）\n    example: \"* | SELECT request_time, bar(cast(request_time as double), 20) as bar\"\n  \n  - name: color\n    syntax: \"color(string [, color])\"\n    description: 为字符串添加颜色标记（ANSI颜色码）\n    params:\n      - string: 要着色的字符串\n      - color: 颜色名称（可选）\n    example: \"* | SELECT color('ERROR', 'red')\"\n  \n  - name: render\n    syntax: \"render(x, color)\"\n    description: 使用指定颜色渲染布尔值\n    example: \"* | SELECT render(cast(status as bigint) >= 400, 'red')\"\n  \n  - name: rgb\n    syntax: \"rgb(red, green, blue)\"\n    description: 根据RGB值创建颜色\n    params:\n      - red: 红色分量(0-255)\n      - green: 绿色分量(0-255)\n      - blue: 蓝色分量(0-255)\n    example: \"* | SELECT rgb(255, 0, 0)\"\n\nuse_cases:\n  - 控制台输出美化\n  - 日志级别着色\n  - 可视化标记\n  - ASCII图表\n\nimportant_notes:\n  - 主要用于控制台输出\n  - 支持标准ANSI颜色\n  - 在Web界面可能不显示颜色\n\nArchive v0.0.1: 62 files, 84331 bytes\n\nFiles: references/acceptance-criteria.md (4680b), references/cli-installation-guide.md (11649b), references/functions-guide.md (2128b), references/functions/aggregate.yaml (1352b), references/functions/approximate.yaml (1936b), references/functions/array.yaml (5124b), references/functions/binary.yaml (2184b), references/functions/bitwise.yaml (1682b), references/functions/color.yaml (1359b), references/functions/comparison.yaml (2378b), references/functions/conditional.yaml (1523b), references/functions/conversion.yaml (1430b), references/functions/datetime.yaml (1920b), references/functions/encoding.yaml (969b), references/functions/geo.yaml (1121b), references/functions/geospatial.yaml (2262b), references/functions/hash.yaml (693b), references/functions/hyperloglog.yaml (1313b), references/functions/ip_geo.yaml (935b), references/functions/json.yaml (901b), references/functions/lambda.yaml (3130b), references/functions/map.yaml (3609b), references/functions/math.yaml (1566b), references/functions/mobile.yaml (1107b), references/functions/operators.yaml (2310b), references/functions/overview.yaml (8152b), references/functions/README.md (3383b), references/functions/regex.yaml (1477b), references/functions/statistical.yaml (2182b), references/functions/string.yaml (3145b), references/functions/type_conversion.yaml (917b), references/functions/url.yaml (1093b), references/functions/window_funnel.yaml (2007b), references/functions/window.yaml (3045b), references/query_analysis/indexConfig.yaml (6471b), references/query_analysis/indexSearch.yaml (12221b), references/query_analysis/overview.yaml (5997b), references/query_analysis/sql.yaml (9043b), references/query-analysis.md (4818b), references/ram-policies.md (3079b), references/regions.md (1303b), references/related-apis.md (5846b), references/spl-guide.md (3097b), references/spl/extend.yaml (628b), references/spl/json_string_process.yaml (3407b), references/spl/limit.yaml (750b), references/spl/overview.yaml (9758b), references/spl/pack-fields.yaml (1420b), references/spl/parse-csv.yaml (479b), references/spl/parse-json.yaml (1011b), references/spl/parse-kv.yaml (468b), references/spl/parse-regexp.yaml (629b), references/spl/project-away.yaml (412b), references/spl/project-rename.yaml (413b), references/spl/project.yaml (574b), references/spl/sort.yaml (763b), references/spl/stats.yaml (1245b), references/spl/where.yaml (611b), references/troubleshooting.md (1651b), skill-card.md (3184b), SKILL.md (16583b), _meta.json (141b)\n\nFile v0.0.1:SKILL.md\n\n---\nname: alibabacloud-sls-query\ndescription: |\n  Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL scan/pipeline statements through the aliyun CLI.\n  Triggers: \"SLS 查询\", \"SLS 分析\", \"日志查询\", \"日志分析\", \"log query\", \"analyze sls logs\", \"aliyun log query\".\n---\n\n# Alibaba Cloud SLS Query & Analysis\n\n## Scenario Description\n\nUse this skill when the user wants to:\n\n- Explain, rewrite, optimize or execute an existing query\n- Translate a natural-language requirement into an SLS **index query**, **SQL**, or **SPL** statement\n\n---\n\n## Prerequisites\n\n### Install Aliyun CLI\n\nRun `aliyun version` to verify if version >= `3.3.8`. If not installed or outdated, follow the doc [references/cli-installation-guide.md](references/cli-installation-guide.md) to install or update.\n\n### Ensure AI Mode Enabled\n\nBefore executing any CLI commands, enable AI-Mode, set User-Agent, and update plugins:\n\n```bash\naliyun configure ai-mode enable\naliyun configure ai-mode set-user-agent --user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query\"\naliyun plugin update\n```\n\n### Check Alibaba Cloud credentials configured\n\nRun `aliyun configure list` to check if credentials configured.\nIf no valid profile is shown, **STOP** here and ask the user to run `aliyun configure` outside of this session.\n\n**Security rules:**\n\n- **NEVER** read, echo, or print AK/SK values\n- **NEVER** ask the user to paste AK/SK into the conversation\n- **ONLY** use `aliyun configure list` to check credential status\n\n---\n\n## RAM Permission Requirements\n\n| API | CLI | Action | Purpose |\n|-----|-----|--------|---------|\n| GetLogsV2 | `get-logs-v2` | `log:GetLogStoreLogs` | Run query / SQL / SPL and read results |\n| GetIndex  | `get-index`   | `log:GetIndex`        | Read index config to verify prerequisites |\n\nFor the minimum and complete RAM policy JSON, see [references/ram-policies.md](references/ram-policies.md).\n\n> **Permission failure handling:** If a call returns `Unauthorized` permission error, stop and surface [references/ram-policies.md](references/ram-policies.md) to the user. Do **not** retry with a different account without explicit user confirmation.\n\n---\n\n## Core Workflow\n\n1. Read index configuration (GetIndex)\n2. Pick query mode\n3. Build statement\n4. Resolve time range\n5. Execute query\n6. Extract data from response\n7. Present CLI command and results\n\n### Step 1: Read the Index Configuration (Mandatory)\n\nAlways call `get-index` first — the index config decides which query modes are available in Step 2.\n\n```bash\naliyun sls get-index \\\n  --project <project> --logstore <logstore>\n```\n\nTwo sections in the response drive every later decision:\n\n| Section | Meaning |\n|---------|---------|\n| `line`  | **Full-text index** — absence means full-text search is disabled |\n| `keys`  | **Field indexes** — map of field → `{ type, doc_value, token, caseSensitive, chn, ... }`. `doc_value: true` means statistics are enabled on that field |\n\nIf the call returns `IndexConfigNotExist` (HTTP 404), or the response has neither `line` nor `keys` populated, the Logstore has no index at all — stop immediately and tell the user they must create an index before any query / SQL / SPL can run.\n\n- **The response can be large** — extract only the fields relevant to the current query. Cache per `logstore` and reuse within the session.\n\nFor field types, tokenization, and how `get-index` maps to capabilities, see [references/related-apis.md](references/related-apis.md) and [references/query-analysis.md](references/query-analysis.md).\n\n---\n\n### Step 2: Pick the Query Mode (Critical)\n\nThe query statement takes one of the following forms:\n\n| Priority | Mode | Statement Form | Use when | Requires |\n|----------|------|----------------|----------|----------|\n| 1 | **Index search** | `<index-search>` | Filtering raw logs; return time-ordered and paginated logs | Full-text (`line`) or any field index (`keys.<field>`) |\n| 2 | **SQL** | `<index-search> \\| <SQL>` | Aggregation, `GROUP BY`, sort, window, top-N, projection, and other analytical operations | Target field has `keys.<field>` with `doc_value: true` |\n| 3 | **SQL scan** | `<index-search> \\| <SQL scan>` | User requested | None |\n| 4 | **SPL** | `<index-search> \\| <SPL>` | User requested | None |\n\n**Selection rule:**\n\n- Always prefer **Index search** for fastest speed.\n- Use **Index search + SQL** when the user needs analytical operations or field projection rather than full raw-log retrieval, such as aggregation, `GROUP BY`, sorting, window analysis, top-N, or returning only the required fields/columns.\n- Do **not** proactively choose **SQL scan** or **SPL**; use them only when the user explicitly requests.\n\nFor the full decision guide, see [references/query-analysis.md](references/query-analysis.md).\n\n---\n\n### Step 3: Write the Statement\n\n#### 3.1 Build the index-search segment first (left of `|`)\n\nCollect every filter that can be expressed in index-search syntax and place it before the first `|`. Use `*` if no filter applies.\n\n```text\n* and \"payment failed\" and status: \"500\" and not path: \"/healthz\"\n```\n\n- `*` matches all; `\"...\"` is full-text (needs full-text index).\n- `key: \"value\"` is a field filter (needs field index).\n- Combine with `and` / `or` / `not`; group with parentheses.\n- `key: *` means field exists. Range (`>`, `>=`, `[a, b]`) works only on `long` / `double`.\n\nIf the requirement can be fully answered without aggregation or row-level processing, stop here — this is already a complete index search. For full index-search syntax, see [references/query-analysis.md](references/query-analysis.md).\n\n#### 3.2 Append SQL — for aggregation / analytics\n\n```sql\nstatus: 500 | SELECT date_trunc('minute', __time__) AS minute,\n                    count(*) AS errors\n              FROM log\n              GROUP BY minute\n              ORDER BY minute\n```\n\n- Read [references/query-analysis.md](references/query-analysis.md) for Query & SQL rules\n- Table name is `log` (recommended to omit).\n- SQL respects the indexed field type from `get-index` — a `long` / `double` field can be compared directly (`status >= 500`). Cast only when a field is indexed as `text` but numeric semantics are needed (`try_cast` to suppress errors).\n- Read [references/functions-guide.md](references/functions-guide.md) for unusual Function selection (aggregate, JSON, regex, datetime, IP geo …)\n\n#### 3.3 Append SPL — for row-level processing / flexible filtering\n\n```spl\nstatus: 500 and service: payment\n| where try_cast(latency as BIGINT) > 1000\n| extend latency_ms = try_cast(latency as BIGINT)\n| project service, latency_ms, message\n```\n\nFor SPL syntax, pipeline commands, and field-handling rules, read [references/spl-guide.md](references/spl-guide.md).\n\n#### 3.4 Append SQL scan — fallback when the target field has no index / statistics\n\nSyntax follows regular SQL (see 3.2), with one difference: **every field is `varchar`**, so always `cast()` / `try_cast()` before numeric comparison or arithmetic. See [references/query-analysis.md](references/query-analysis.md) for scan semantics.\n\n```sql\n* | set session mode=scan; SELECT api, count(1) AS pv FROM log GROUP BY api\n```\n\n---\n\n### Step 4: Resolve the Time Range\n\nGenerate `--from` / `--to` as **Unix timestamps in seconds** before building the CLI command. `--from` is inclusive and `--to` is exclusive.\n\nChoose one of three input patterns:\n\n1. **Relative time** — user says \"recent / last N minutes|hours|days\".\n2. **Natural-language absolute time without timezone** — normalize to `YYYY-MM-DD HH:MM:SS`, then parse using the machine's local timezone.\n3. **Absolute time with explicit timezone** — parse using the customer-provided timezone or UTC offset.\n\n**1. Relative time**\n\n```bash\n# recent 15 minutes\nFROM=$(($(date +%s) - 900))\nTO=$(date +%s)\n```\n\n**2. Natural-language absolute time without timezone**\n\nIf the user gives a date/time but no timezone, use the machine's local timezone. First normalize natural language such as `2026年3月13日12点` to `2026-03-13 12:00:00`, then parse it as local time.\n\n```bash\n# Example: 2026年3月13日12点 -> 2026-03-13 12:00:00\n\n# Linux (GNU date): local timezone\nFROM=$(date -d \"2026-03-13 12:00:00\" +%s)\n\n# macOS (BSD date): local timezone\nFROM=$(date -j -f \"%Y-%m-%d %H:%M:%S\" \"2026-03-13 12:00:00\" +%s)\n```\n\nFor a time range such as \"2026年3月13日12点到13点\", compute both endpoints the same way. For a single point-in-time request, infer a practical window from the user's intent; if unclear, ask for the range before executing.\n\n**3. Absolute time with explicit timezone**\n\nTo convert a local date/time to a Unix timestamp: parse the input as UTC with `date -u`, then **subtract** the timezone's UTC offset in seconds.\n\nFormula: `unix_ts = date_utc_parse(input) − (UTC_offset_hours × 3600)`\n\n```bash\n# Example: 2025-01-15 10:30:00 Beijing Time (UTC+8)\n# Beijing is UTC+8, so subtract 8 × 3600 = 28800\n\n# Linux (GNU date)\nFROM=$(( $(date -u -d \"2025-01-15 10:30:00\" +%s) - 28800 ))\n\n# macOS (BSD date)\nFROM=$(( $(date -u -j -f \"%Y-%m-%d %H:%M:%S\" \"2025-01-15 10:30:00\" +%s) - 28800 ))\n```\n\n```bash\n# Example: 2025-01-15 10:30:00 New York Time (UTC-5)\n# New York is UTC-5, so subtract -5 × 3600 = subtract -18000 = add 18000\n\n# Linux (GNU date)\nFROM=$(( $(date -u -d \"2025-01-15 10:30:00\" +%s) + 18000 ))\n\n# macOS (BSD date)\nFROM=$(( $(date -u -j -f \"%Y-%m-%d %H:%M:%S\" \"2025-01-15 10:30:00\" +%s) + 18000 ))\n```\n\nCommon UTC offsets (value to subtract):\n\n| Timezone         | UTC offset hours | Seconds to subtract |\n|------------------|------------------|---------------------|\n| Beijing (UTC+8)  | +8               | `28800`             |\n| Tokyo (UTC+9)    | +9               | `32400`             |\n| London (UTC)     | 0                | `0`                 |\n| New York (UTC-5) | -5               | `-18000`            |\n\n---\n\n### Step 5: Execute via `get-logs-v2`\n\nUse `aliyun sls get-logs-v2` to execute queries. Run `aliyun help sls get-logs-v2` to see CLI parameter usage; read [references/related-apis.md](references/related-apis.md) for detailed API parameter descriptions.\n\n**Required CLI flags:**\n\n- `--project`: SLS project name\n- `--logstore`: Logstore name within the project\n- `--from`: Start of time range, **Unix timestamp in seconds** (inclusive)\n- `--to`: End of time range, **Unix timestamp in seconds** (exclusive)\n- `--query`: Statement built in Step 3\n\nPagination works differently depending on whether the statement has a `|`:\n\n#### 5.1 Index-search only — paginate with `--offset` / `--line`\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 \\\n  --query '* and \"payment failed\" and status: \"500\"' \\\n  --line 100 --offset 0 --reverse true\n```\n\n- Pagination: `--line` is page size (`1–100`, required); `--offset` is the start row (optional, default `0`).\n- Ordering: `--reverse true` returns newest first; default `false` is oldest first.\n\n#### 5.2 With SQL — paginate with `LIMIT` inside the statement\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 \\\n  --query 'status: \"500\" | SELECT request_uri, count(*) AS cnt FROM log GROUP BY request_uri ORDER BY cnt DESC LIMIT 20'\n```\n\n- SQL default result cap is **100 rows**. To get more results or paginate:\n  - `LIMIT count` — raise the cap (e.g., `LIMIT 500` returns up to 500 rows)\n  - `LIMIT offset, count` — paginate (e.g., `LIMIT 20, 20` for rows 21–40; `LIMIT 40, 20` for rows 41–60). Max offset+count is 1000000.\n  - **Do not** use `LIMIT count OFFSET offset` syntax — it is **not supported**. Always use `LIMIT offset, count`.\n- Ordering: use `ORDER BY <field> DESC/ASC` to sort.\n\n**Result completeness check:** every response contains `meta.progress`. If it is `Incomplete`, **re-issue the same request** until it returns `Complete`.\n\n---\n\n### Step 6: Extract Data from the Response\n\n`get-logs-v2` returns:\n\n```json\n{\n  \"meta\": { \"progress\": \"Complete\", \"count\": 10, ... },\n  \"data\": [ { \"field1\": \"value1\", ... }, ... ]\n}\n```\n\n| Field | Meaning |\n|-------|---------|\n| `meta.progress` | `Complete` or `Incomplete` (see Step 5) |\n| `meta.count` | Number of rows returned |\n| `data` | Array of log entries or aggregation rows; may contain `__time__` (Unix seconds, string) |\n\nUse `jq` (preferred) or `--cli-query` (JMESPath) to extract the fields the user needs:\n\n| Extract | `jq` | `--cli-query` (JMESPath) |\n|---------|------|--------------------------|\n| Data rows | `\\| jq '.data'` | `--cli-query 'data'` |\n| Progress | `\\| jq '.meta.progress'` | `--cli-query 'meta.progress'` |\n| Row count | `\\| jq '.meta.count'` | `--cli-query 'meta.count'` |\n| Specific fields | `\\| jq '.data[] \\| {LogStore, read_mb}'` | `--cli-query 'data[].{LogStore: LogStore, read_mb: read_mb}'` |\n\n---\n\n### Step 7: Present the CLI Command and Results\n\n**CLI command** — always show the full, copy-paste-ready `aliyun sls get-logs-v2 ...` command. Redact any AK/SK. If the query was not executed (write / explain scenario), present the command the user should run.\n\n**Results** — when a query was executed, use Step 6 to extract `data` and format according to the user's request (table, list, summary, etc.). Append one sentence explaining the query mode choice.\n\n---\n\n## Cleanup\n\n**Whether operations succeed or fail, you MUST disable AI-Mode before ending the session:**\n\n```bash\naliyun configure ai-mode disable\n```\n\n---\n\n## Global Rules\n\n- **Always prefer Index search for fastest raw-log retrieval, and use Index search + SQL for analysis or field projection.**\n- **When the user only needs specific fields, use `SELECT` to project them** rather than fetching full raw logs — this reduces network overhead. Requires `doc_value: true` on the target fields (confirmed in Step 1).\n- **Do not** hard-code `__time__` filters — pass time range via `--from` / `--to`.\n- **Deprecated API**: never call `get-logs`; always use `get-logs-v2`.\n\n---\n\n## Troubleshooting\n\nWhen the user reports \"no data\", \"wrong result\", or a CLI error, walk through the checklist in this exact order:\n\n1. **Time range** — wrong `--from`/`--to`? Milliseconds instead of seconds? Recent writes still indexing?\n2. **Index configuration** — field index missing? Full-text index off? Target field not in `keys`?\n3. **Field type / statistics** — range query on a `text` field? SQL on a field without `doc_value`?\n4. **Syntax** — mixed SQL and SPL? Leading `*` in fuzzy match? SPL string escaping?\n5. **Mode choice** — scanning when an index-based query would do? Aggregating in SPL instead of SQL?\n6. **Completeness** — `meta.progress = Incomplete`, caller did not retry (see Step 5).\n7. **ProjectNotExist** — region or endpoint is wrong. See [references/regions.md](references/regions.md).\n8. **Network failure** (timeout, connection refused) — try switching to internal endpoint. See [references/regions.md](references/regions.md).\n\nFor the full catalog of failure modes and error codes, see [references/troubleshooting.md](references/troubleshooting.md) and the `Common Errors` table in [references/related-apis.md](references/related-apis.md).\n\n---\n\n## Reference Documents\n\n| Document | Description |\n|----------|-------------|\n| [references/query-analysis.md](references/query-analysis.md) | Mode decision, index-search / SQL rules, scan semantics |\n| [references/spl-guide.md](references/spl-guide.md) | SPL pipeline syntax, common commands, field handling |\n| [references/functions-guide.md](references/functions-guide.md) | Function categories, SQL/SPL differences, templates |\n| [references/troubleshooting.md](references/troubleshooting.md) | \"No data / wrong result / error\" playbook |\n| [references/related-apis.md](references/related-apis.md) | `GetLogsV2` and `GetIndex` API & CLI reference |\n| [references/ram-policies.md](references/ram-policies.md) | Minimum and complete RAM policies |\n| [references/cli-installation-guide.md](references/cli-installation-guide.md) | Aliyun CLI install, auth modes, profiles |\n| [references/regions.md](references/regions.md) | Region / endpoint configuration, internal endpoint, ProjectNotExist troubleshooting |\n| [references/acceptance-criteria.md](references/acceptance-criteria.md) | CLI invocation acceptance tests |\n| `references/query_analysis/*.yaml` · `references/spl/*.yaml` · `references/functions/*.yaml` | Source-of-truth YAMLs bundled with this skill |\n\nFile v0.0.1:references/functions/README.md\n\n# SLS 函数参考文档\n\n本目录包含 SLS SQL 和 SPL 分析语句支持的所有函数，按功能分类。\n\n## 目录结构\n\n| 文件 | 类别 | 描述 | 支持 |\n|------|------|------|------|\n| `aggregate.yaml` | 聚合函数 | count、sum、avg、max、min 等统计函数 | SQL |\n| `string.yaml` | 字符串函数 | 文本拼接、截取、大小写转换、查找替换 | SQL + SPL |\n| `regex.yaml` | 正则表达式函数 | 正则匹配、提取、替换 | SQL + SPL |\n| `datetime.yaml` | 日期时间函数 | 时间格式化、解析、截断、转换 | SQL + SPL |\n| `type_conversion.yaml` | 类型转换函数 | cast、try_cast 类型转换 | SQL + SPL |\n| `conditional.yaml` | 条件函数 | if、case、coalesce 条件判断 | SQL + SPL |\n| `json.yaml` | JSON函数 | JSON 数据提取和解析 | SQL + SPL |\n| `math.yaml` | 数学函数 | 数值计算、取整、幂运算 | SQL + SPL |\n| `url.yaml` | URL函数 | URL 解析和参数提取 | SQL + SPL |\n| `ip_geo.yaml` | IP地理位置函数 | IP 转省份、城市、国家、经纬度 | 仅SPL |\n| `encoding.yaml` | 编码解码函数 | URL、Base64 编码解码 | SQL + SPL |\n| `hash.yaml` | 哈希函数 | MD5、SHA1、SHA256 哈希计算 | SQL + SPL |\n\n## 使用说明\n\n### 1. 查找函数\n\n- **按功能查找**：根据上表选择对应的分类文件\n- **按名称查找**：在对应分类的 YAML 文件中查找具体函数\n- **按场景查找**：参考 `overview.yaml` 中的常见场景示例\n\n### 2. 查看函数详情\n\n每个 YAML 文件包含以下信息：\n\n```yaml\nfunctions:\n  - name: 函数名\n    syntax: 函数语法\n    description: 功能描述\n    examples:\n      sql: SQL 示例\n      spl: SPL 示例\n    note: 注意事项（可选）\n```\n\n### 3. 重要提示\n\n#### 类型转换\n- 字段默认为 VARCHAR 类型\n- 数值比较和运算前必须使用 `cast()` 或 `try_cast()` 转换\n- SPL 中尤其需要注意类型转换\n\n示例：\n```sql\n-- ✅ 正确\n* | SELECT * WHERE cast(status as BIGINT) >= 500\n\n-- ❌ 错误\n* | SELECT * WHERE status >= 500\n```\n\n#### SQL vs SPL\n- **SQL**：使用 SELECT、WHERE、GROUP BY 语法\n- **SPL**：使用 extend、where、stats 语法\n- **聚合函数**主要用于 SQL\n- **IP地理函数**仅用于 SPL\n\n#### 正则表达式\n- SPL 使用 RE2 正则引擎\n- 不支持：后向引用(\\1)、环视(?<=...)等\n- 反斜杠不需要双重转义：`\\d` 直接写 `\\d`\n\n## 快速示例\n\n### 统计分析\n```sql\n-- 按状态码统计\n* | SELECT status, count(*) AS pv GROUP BY status ORDER BY pv DESC\n```\n\n### 时间分组\n```sql\n-- 按小时统计\n* | SELECT date_trunc('hour', __time__) AS hour, count(*) AS pv GROUP BY hour\n```\n\n### 正则提取\n```sql\n-- 提取错误码\n* | SELECT regexp_extract(message, 'code:(\\d+)', 1) AS error_code, count(*) GROUP BY error_code\n```\n\n### JSON 解析\n```sql\n-- 提取 JSON 字段\n* | SELECT json_extract_scalar(payload, '$.user.name') AS user, count(*) GROUP BY user\n```\n\n### IP 地理分析（SPL）\n```spl\n# 按省份统计\n* | extend province = ip_to_province(client_ip) | stats pv = count(*) by province\n```\n\n## 相关文档\n\n- [函数索引](./overview.yaml) - 函数分类索引和使用指南\n- [SQL 查询语法](../query_analysis/sql.yaml) - SQL 查询完整语法\n- [SPL 基础语法](../spl/overview.yaml) - SPL 查询基础\n- [索引查询](../query_analysis/indexSearch.yaml) - 关键字搜索语法\n\nFile v0.0.1:_meta.json\n\n{\n  \"ownerId\": \"kn74p5w8ywv6prh40g0s82gmqh83nw54\",\n  \"slug\": \"alibabacloud-sls-query\",\n  \"version\": \"0.0.1\",\n  \"publishedAt\": 1777017447614\n}\n\nFile v0.0.1:references/acceptance-criteria.md\n\n# Acceptance Criteria: sls-query-analysis\n\n**Scenario**: SLS Log Query & Analysis\n**Purpose**: Skill testing acceptance criteria\n\n---\n\n## Correct CLI Invocation Patterns\n\n### 1. Command Format — verify product and API name\n\n#### CORRECT\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* and status: \"500\"' \\\n  --line 100\n```\n\n#### INCORRECT — Wrong product name\n\n```bash\naliyun log get-logs-v2 --project my-project --logstore my-logstore\n```\n\n**Why**: Product name is `sls`, not `log`, `logservice`, `aliyunlog`, or `aliyun-sls`.\n\n### 2. Parameter Format\n\n#### CORRECT — Kebab-case CLI sub-command and flags\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* | select count(*) as total from log' \\\n  --line 100 \\\n  --offset 0 \\\n  --reverse true\n```\n\n#### INCORRECT — PascalCase sub-command or flags\n\n```bash\n# Sub-command in PascalCase\naliyun sls GetLogsV2 --project my-project --logstore my-logstore\naliyun sls GetIndex  --project my-project --logstore my-logstore\n\n# Flags in PascalCase\naliyun sls get-logs-v2 --Project my-project --Logstore my-logstore --From 1740000000 --To 1740003600\n```\n\n**Why**: The SLS plugin uses **kebab-case** for both sub-commands (`get-logs-v2`, `get-index`) and flags (`--project`, `--logstore`, `--from`, `--to`, `--query`).\n\n#### INCORRECT — Using `--region-id` instead of `--region`\n\n```bash\naliyun sls get-logs-v2 --region-id cn-hangzhou --project p --logstore l --from 1 --to 2\n```\n\n**Why**: The CLI global flag is `--region`, not `--region-id`.\n\n#### INCORRECT — JSON `--params` string (old SDK pattern)\n\n```bash\naliyun sls get-logs-v2 --params '{\"Project\":\"my-project\",\"Logstore\":\"my-logstore\",\"From\":\"1740000000\",\"To\":\"1740003600\"}'\n```\n\n**Why**: The CLI takes individual flags, not a JSON `--params` blob.\n\n### 3. Authentication — never expose credentials\n\n#### CORRECT — Verify credential profile via default credential chain\n\n```bash\naliyun configure list\n```\n\n#### INCORRECT — Passing AK/SK directly in the command\n\n```bash\naliyun sls get-logs-v2 \\\n  --access-key-id LTAI5tXXXX \\\n  --access-key-secret 8dXXXX \\\n  --project p --logstore l --from 1740000000 --to 1740003600\n```\n\n**Why**: Credentials must come from the configured profile, environment variables, STS, or RAM role — never be typed into the command line.\n\n#### INCORRECT — Reading or printing raw credentials\n\n```bash\naliyun configure get           # FORBIDDEN: may expose credential details\ncat ~/.aliyun/config.json      # FORBIDDEN: may expose credential details\n```\n\n#### INCORRECT — Any command that prints environment credentials\n\n```bash\necho $ALIBABA_CLOUD_ACCESS_KEY_ID       # FORBIDDEN: example of secret output\nprintenv | grep -i credential           # FORBIDDEN: may reveal secrets\nenv | grep -i access_key                # FORBIDDEN: may reveal secrets\n```\n\n### 4. API Names — verify exact sub-command\n\n#### CORRECT\n\n```\nget-logs-v2      # OpenAPI Action: GetLogsV2\nget-index        # OpenAPI Action: GetIndex\n```\n\n#### INCORRECT\n\n```\nGetLogsV2          # PascalCase is the Action name, not the CLI sub-command\nGetIndex           # PascalCase is the Action name, not the CLI sub-command\ngetLogsV2          # Wrong casing\nget_logs_v2        # Wrong separator (snake_case)\ngetlogsv2          # Missing separators\nget-logs           # Deprecated — use get-logs-v2\nget-logs-2         # Wrong suffix (v2, not 2)\ndescribe-index     # Wrong verb — SLS uses get-, not describe-\nget-log-index      # Not a real sub-command — use get-index\n```\n\n### 5. Region Parameter\n\n#### CORRECT\n\n```bash\n--region cn-hangzhou\n--region cn-shanghai\n--region ap-southeast-1\n--region us-west-1\n```\n\n#### INCORRECT\n\n```bash\n--region hangzhou       # Missing country prefix\n--region cn-hangzhou-1  # Not a real region ID\n```\n\n**Why**: Only valid Alibaba Cloud region IDs are accepted (e.g., `cn-hangzhou`, `ap-southeast-1`). The project is region-scoped — a region mismatch returns `ProjectNotExist`.\n\n### 6. Time Parameters\n\n#### CORRECT — Unix timestamp in seconds\n\n```bash\n--from 1711324800 --to 1711411200\n```\n\n#### INCORRECT — Millisecond timestamps\n\n```bash\n--from 1711324800000 --to 1711411200000\n```\n\n**Why**: `--from` / `--to` are Unix **seconds**, not milliseconds.\n\n#### INCORRECT — Date or ISO strings\n\n```bash\n--from \"2024-03-25\"             --to \"2024-03-26\"\n--from \"2024-03-25T00:00:00Z\"   --to \"2024-03-26T00:00:00Z\"\n```\n\n**Why**: Only integer seconds are accepted; date strings must be converted first (e.g., `date -d \"2024-03-25 00:00:00 UTC\" +%s`).\n\nFile v0.0.1:references/cli-installation-guide.md\n\n# Aliyun CLI Installation & Configuration Guide\n\nComplete guide for installing and configuring Aliyun CLI.\n\n> **Aliyun CLI 3.3.8+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.8 or later for full plugin ecosystem coverage.\n\n## Installation\n\n### macOS\n\n**Using Homebrew (Recommended)**\n\n```bash\nbrew install aliyun-cli\n# Upgrade to latest\nbrew upgrade aliyun-cli\n\n# Verify version (>= 3.3.8)\naliyun version\n```\n\n**Using Binary**\n\n```bash\n# Download\nwget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz\n\n# Extract\ntar -xzf aliyun-cli-macosx-latest-amd64.tgz\n\n# Move to PATH\nsudo mv aliyun /usr/local/bin/\n\n# Verify\naliyun version\n```\n\n### Linux\n\n**Debian/Ubuntu**\n\n```bash\n# Download\nwget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz\n\n# Extract and install\ntar -xzf aliyun-cli-linux-latest-amd64.tgz\nsudo mv aliyun /usr/local/bin/\n\n# Verify\naliyun version\n```\n\n**CentOS/RHEL**\n\n```bash\n# Download\nwget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz\n\n# Extract and install\ntar -xzf aliyun-cli-linux-latest-amd64.tgz\nsudo mv aliyun /usr/local/bin/\n\n# Verify\naliyun version\n```\n\n**ARM64 Architecture**\n\n```bash\n# Download ARM64 version\nwget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz\n\n# Extract and install\ntar -xzf aliyun-cli-linux-latest-arm64.tgz\nsudo mv aliyun /usr/local/bin/\n```\n\n### Windows\n\n**Using Binary**\n\n1. Download from: <https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip>\n2. Extract the ZIP file\n3. Add the directory to your PATH environment variable\n4. Open new Command Prompt or PowerShell\n5. Verify: `aliyun version`\n\n**Using PowerShell**\n\n```powershell\n# Download\nInvoke-WebRequest -Uri \"https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip\" -OutFile \"aliyun-cli.zip\"\n\n# Extract\nExpand-Archive -Path aliyun-cli.zip -DestinationPath C:\\aliyun-cli\n\n# Add to PATH (requires admin privileges)\n$env:Path += \";C:\\aliyun-cli\"\n[Environment]::SetEnvironmentVariable(\"Path\", $env:Path, [System.EnvironmentVariableTarget]::Machine)\n\n# Verify\naliyun version\n```\n\n## Configuration\n\n### Quick Start\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id <your-access-key-id> \\\n  --access-key-secret <your-access-key-secret> \\\n  --region cn-hangzhou\n```\n\nAll `aliyun configure` commands support non-interactive flags, which is the recommended approach —\nit works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.\n\n**Where to Get Access Keys**\n\n1. Log in to Aliyun Console: <https://ram.console.aliyun.com/>\n2. Navigate to: AccessKey Management\n3. Create a new AccessKey pair\n4. Save the secret immediately — it's only shown once\n\n### Configuration Modes\n\nAliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.\n\n#### 1. AK Mode (Access Key)\n\nMost common mode for personal accounts and scripts.\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nConfiguration is stored in `~/.aliyun/config.json`:\n\n```json\n{\n  \"current\": \"default\",\n  \"profiles\": [\n    {\n      \"name\": \"default\",\n      \"mode\": \"AK\",\n      \"access_key_id\": \"LTAI5tXXXXXXXX\",\n      \"access_key_secret\": \"8dXXXXXXXXXXXXXXXXXXXXXXXX\",\n      \"region_id\": \"cn-hangzhou\",\n      \"output_format\": \"json\",\n      \"language\": \"en\"\n    }\n  ]\n}\n```\n\n#### 2. StsToken Mode (Temporary Credentials)\n\nFor short-lived access (tokens expire in 1-12 hours).\n\n```bash\naliyun configure set \\\n  --mode StsToken \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --sts-token v1.0:XXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.\n\n#### 3. RamRoleArn Mode (Assume RAM Role)\n\nAssume a RAM role for elevated or cross-account access.\n\n```bash\naliyun configure set \\\n  --mode RamRoleArn \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --ram-role-arn acs:ram::123456789012:role/AdminRole \\\n  --role-session-name my-session \\\n  --region cn-hangzhou\n```\n\nUse cases: cross-account resource access, temporary elevated privileges, role-based access control.\n\n#### 4. EcsRamRole Mode (ECS Instance RAM Role)\n\nUse the RAM role attached to an ECS instance — no credentials needed.\n\n```bash\naliyun configure set \\\n  --mode EcsRamRole \\\n  --ram-role-name MyEcsRole \\\n  --region cn-hangzhou\n```\n\nRequirements: must be running on an ECS instance with a RAM role attached.\n\nUse cases: scripts and automation running on ECS instances.\n\n#### 5. RsaKeyPair Mode (RSA Key Pair)\n\nUse RSA key pair for authentication (generate key pair in Aliyun Console first).\n\n```bash\naliyun configure set \\\n  --mode RsaKeyPair \\\n  --private-key /path/to/private-key.pem \\\n  --key-pair-name my-key-pair \\\n  --region cn-hangzhou\n```\n\n#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)\n\nCombine ECS instance role with RAM role assumption for cross-account access from ECS.\n\n```bash\naliyun configure set \\\n  --mode RamRoleArnWithEcs \\\n  --ram-role-name MyEcsRole \\\n  --ram-role-arn acs:ram::123456789012:role/TargetRole \\\n  --role-session-name my-session \\\n  --region cn-hangzhou\n```\n\n### Environment Variables\n\n**Highest priority** - overrides config file\n\n**Access Key Mode**\n\n```bash\nexport ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id\nexport ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret\nexport ALIBABA_CLOUD_REGION_ID=cn-hangzhou\n```\n\n**STS Token Mode**\n\n```bash\nexport ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id\nexport ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret\nexport ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token\nexport ALIBABA_CLOUD_REGION_ID=cn-hangzhou\n```\n\n**ECS RAM Role Mode**\n\n```bash\nexport ALIBABA_CLOUD_ECS_METADATA=role_name\n```\n\n**Use Case**:\n\n- CI/CD pipelines\n- Docker containers\n- Temporary credential override\n\n### Managing Multiple Profiles\n\n**Create Named Profiles**\n\n```bash\naliyun configure set --profile projectA \\\n  --mode AK \\\n  --access-key-id LTAI5tAAAAAAAA \\\n  --access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \\\n  --region cn-hangzhou\n\naliyun configure set --profile projectB \\\n  --mode AK \\\n  --access-key-id LTAI5tBBBBBBBB \\\n  --access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \\\n  --region cn-shanghai\n```\n\n**Use Specific Profile**\n\n```bash\naliyun ecs describe-instances --profile projectA\n\nexport ALIBABA_CLOUD_PROFILE=projectA\naliyun ecs describe-instances   # Uses projectA\n```\n\n**List and Switch Profiles**\n\n```bash\naliyun configure list                      # List all profiles\naliyun configure set --current projectA    # Switch default profile\n```\n\n### Credential Priority\n\nCredentials are loaded in this order (first found wins):\n\n1. **Command-line flag**: `--profile <name>`\n2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`\n3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.\n4. **Configuration file**: `~/.aliyun/config.json` (current profile)\n5. **ECS Instance RAM Role**: If running on ECS with attached role\n\n## Verification\n\n### Test Authentication\n\n```bash\n# Basic test - list regions\naliyun ecs describe-regions\n\n# Expected output: JSON array of regions\n```\n\n**If successful**, you'll see:\n\n```json\n{\n  \"Regions\": {\n    \"Region\": [\n      {\n        \"RegionId\": \"cn-hangzhou\",\n        \"RegionEndpoint\": \"ecs.cn-hangzhou.aliyuncs.com\",\n        \"LocalName\": \"华东 1（杭州）\"\n      },\n      ...\n    ]\n  },\n  \"RequestId\": \"...\"\n}\n```\n\n**If failed**, you'll see error messages:\n\n- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID\n- `SignatureDoesNotMatch` - Wrong Access Key Secret\n- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)\n- `Forbidden.RAM` - Insufficient permissions\n\n### Debug Configuration\n\n```bash\n# Show current configuration\naliyun configure get\n\n# Test with debug logging\naliyun ecs describe-regions --log-level=debug\n\n# Check credential provider\naliyun configure get mode\n```\n\n## Security Best Practices\n\n### 1. Use RAM Users (Not Root Account)\n\n❌ **Don't**: Use Aliyun root account credentials\n✅ **Do**: Create RAM users with specific permissions\n\n```bash\n# Create RAM user in console\n# Attach only necessary policies\n# Use RAM user's access keys\n```\n\n### 2. Principle of Least Privilege\n\nGrant only the minimum permissions needed:\n\n```bash\n# Example: Read-only ECS access\n# Attach policy: AliyunECSReadOnlyAccess\n```\n\n### 3. Rotate Access Keys Regularly\n\n```bash\n# Create new access key in RAM Console, then update configuration\naliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET\n# Delete old access key from console\n```\n\n### 4. Use STS Tokens for Temporary Access\n\n```bash\naliyun configure set --mode StsToken \\\n  --access-key-id XXXX --access-key-secret XXXX \\\n  --sts-token XXXX --region cn-hangzhou\n```\n\n### 5. Use ECS RAM Roles When Possible\n\n```bash\naliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou\n```\n\n### 6. Never Commit Credentials\n\n```bash\n# Add to .gitignore\necho \"~/.aliyun/config.json\" >> .gitignore\n\n# Use environment variables in CI/CD instead\n```\n\n### 7. Secure Config File\n\n```bash\n# Restrict permissions\nchmod 600 ~/.aliyun/config.json\n```\n\n## Troubleshooting\n\n### Issue: Command Not Found\n\n```bash\n# Check installation\nwhich aliyun\n\n# Check PATH\necho $PATH\n\n# Reinstall or add to PATH\n```\n\n### Issue: Authentication Failed\n\n```bash\n# Verify configuration\naliyun configure get\n\n# Test with debug\naliyun ecs describe-regions --log-level=debug\n\n# Check credentials in console\n# Verify access key is active\n```\n\n### Issue: Permission Denied\n\n```bash\n# Error: Forbidden.RAM\n\n# Check RAM user permissions\n# Attach necessary policies in RAM console\n# Example: AliyunECSFullAccess for ECS operations\n```\n\n### Issue: STS Token Expired\n\n```bash\n# Error: InvalidSecurityToken.Expired\n\n# Reconfigure with new token\naliyun configure set --mode StsToken \\\n  --access-key-id XXXX --access-key-secret XXXX \\\n  --sts-token NEW_TOKEN --region cn-hangzhou\n```\n\n### Issue: Wrong Region\n\n```bash\n# Some resources may not exist in the specified region\n\n# Check available regions\naliyun ecs describe-regions\n\n# Update default region\naliyun configure set region cn-shanghai\n```\n\n## Advanced Configuration\n\n### Custom Endpoint\n\n```bash\n# Use custom or private endpoint\nexport ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com\n```\n\n### Proxy Settings\n\n```bash\n# HTTP proxy\nexport HTTP_PROXY=http://proxy.example.com:8080\nexport HTTPS_PROXY=http://proxy.example.com:8080\n\n# No proxy for specific domains\nexport NO_PROXY=localhost,127.0.0.1,.aliyuncs.com\n```\n\n### Timeout Settings\n\n```bash\n# Connection timeout (default: 10s)\nexport ALIBABA_CLOUD_CONNECT_TIMEOUT=30\n\n# Read timeout (default: 10s)\nexport ALIBABA_CLOUD_READ_TIMEOUT=30\n```\n\n## Next Steps\n\nAfter installation and configuration:\n\n1. **Install plugins** for services you need (v3.3.1+ supports all published product plugins):\n\n   ```bash\n   aliyun plugin install --names ecs vpc rds\n\n   # List all available plugins\n   aliyun plugin list-remote\n   ```\n\n2. **Explore commands**:\n\n   ```bash\n   aliyun sls --help\n   aliyun fc --help\n   ```\n\n3. **Read documentation**:\n   - [Command Syntax Guide](./command-syntax.md)\n   - [Global Flags Reference](./global-flags.md)\n   - [Common Scenarios](./common-scenarios.md)\n\n## References\n\n- Official Documentation: <https://help.aliyun.com/zh/cli/>\n- RAM Console: <https://ram.console.aliyun.com/>\n- Access Key Management: <https://ram.console.aliyun.com/manage/ak>\n- Plugin Repository: <https://github.com/aliyun/aliyun-cli>\n\nFile v0.0.1:references/functions-guide.md\n\n# 函数选型指南\n\n先按场景选函数分类，再回读 skill 内部的对应 YAML。\n\n## 高频分类\n\n- 数据统计：`./functions/aggregate.yaml`\n- 字符串处理：`./functions/string.yaml`\n- 正则匹配：`./functions/regex.yaml`\n- 时间处理：`./functions/datetime.yaml`\n- 类型转换：`./functions/type_conversion.yaml`\n- 条件判断：`./functions/conditional.yaml`\n- JSON 提取：`./functions/json.yaml`\n- 数值计算：`./functions/math.yaml`\n- URL 解析：`./functions/url.yaml`\n- 数组 / Map：`./functions/array.yaml`、`./functions/map.yaml`\n- 窗口分析：`./functions/window.yaml`\n- 漏斗分析：`./functions/window_funnel.yaml`\n- Lambda 表达式：`./functions/lambda.yaml`\n\n## 语言差异\n\n- SQL + SPL 都支持：字符串、正则、时间、类型转换、条件、JSON、数学、URL、编码、哈希、数组、Map 等大部分基础函数\n- 仅 SQL：窗口函数、位运算、空间函数、HyperLogLog、统计函数、漏斗函数等\n- 仅 SPL：`ip_to_province`、`ip_to_city`、`ip_to_country`、`ip_to_geo`\n\n## 高频提醒\n\n- 数值比较前必须先 `cast()` 或 `try_cast()`\n- 想避免转换失败时整条报错，用 `try_cast()`\n- 时间分组优先 `date_trunc()` 或 `date_format()`\n- JSON 字段优先 `json_extract()` / `json_extract_scalar()`\n- SPL 做转义相关处理，优先看 `ascii_escape`、`ascii_unescape`、`unicode_unescape`\n- SPL 中某些函数能力和 SQL 不完全对齐，拿不准时回读对应函数 YAML\n\n## 常见模板\n\n### 类型转换\n```sql\n* | SELECT count(*) FROM log WHERE cast(status as BIGINT) >= 500\n```\n\n```spl\n* | where try_cast(status as BIGINT) >= 500\n```\n\n### JSON 提取\n```sql\n* | SELECT json_extract_scalar(payload, '$.user.id') AS user_id, count(*) FROM log GROUP BY user_id\n```\n\n### 正则提取\n```sql\n* | SELECT regexp_extract(message, 'code:(\\d+)', 1) AS code, count(*) FROM log GROUP BY code\n```\n\n### SPL 地域分析\n```spl\n* | extend province = ip_to_province(client_ip) | stats pv = count(*) by province\n```\n\n## 本地源文档\n\n- `./functions/overview.yaml`\n- `./functions/README.md`\n- `./functions/*.yaml`\n\nFile v0.0.1:references/functions/aggregate.yaml\n\ncategory: aggregate_functions\nname: 聚合函数\ndescription: 对数据进行汇总计算，通常与GROUP BY配合使用\n\nsupport: \n  sql: true\n  spl: false\n\nfunctions:\n  - name: count\n    syntax: \"count(*) 或 count(x)\"\n    description: 统计日志条数\n    example: \"* | SELECT count(*) AS pv\"\n    note: \"count(*) 统计所有，count(x) 统计x非NULL的数量\"\n  \n  - name: sum\n    syntax: \"sum(x)\"\n    description: 计算总和\n    example: \"* | SELECT sum(cast(response_size as BIGINT)) AS total_size\"\n  \n  - name: avg\n    syntax: \"avg(x)\"\n    description: 计算平均值\n    example: \"* | SELECT avg(cast(request_time as DOUBLE)) AS avg_time\"\n  \n  - name: max\n    syntax: \"max(x)\"\n    description: 返回最大值\n    example: \"* | SELECT max(cast(response_time as BIGINT)) AS max_time\"\n  \n  - name: min\n    syntax: \"min(x)\"\n    description: 返回最小值\n    example: \"* | SELECT min(cast(response_time as BIGINT)) AS min_time\"\n  \n  - name: count_if\n    syntax: \"count_if(condition)\"\n    description: 统计满足条件的日志数\n    example: \"* | SELECT count_if(cast(status as BIGINT) >= 500) AS error_count\"\n  \n  - name: arbitrary\n    syntax: \"arbitrary(x)\"\n    description: 返回任意一个非空值\n    example: \"* | SELECT status, arbitrary(request_time) GROUP BY status\"\n    note: 用于GROUP BY时获取非分组字段的值\n\nFile v0.0.1:references/functions/approximate.yaml\n\ncategory: approximate_functions\nname: 估算函数\ndescription: 基于数据预测或填充缺失值的近似计算\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: approx_distinct\n    syntax: \"approx_distinct(x)\"\n    description: 估算唯一值的个数，使用HyperLogLog算法\n    returns: 近似计数\n    example: \"* | SELECT approx_distinct(client_ip) AS uv\"\n    note: 比count(distinct x)更快，但是近似值\n  \n  - name: approx_percentile\n    syntax: \"approx_percentile(x, percentage)\"\n    description: 计算近似百分位数\n    params:\n      - x: 列名\n      - percentage: 百分位，取值0~1\n    example: \"* | SELECT approx_percentile(cast(request_time as double), 0.99) AS p99\"\n  \n  - name: approx_percentile (with array)\n    syntax: \"approx_percentile(x, array[p1, p2,...])\"\n    description: 同时计算多个百分位数\n    example: \"* | SELECT approx_percentile(cast(request_time as double), array[0.5, 0.95, 0.99]) AS percentiles\"\n  \n  - name: numeric_histogram\n    syntax: \"numeric_histogram(bucket_count, x)\"\n    description: 按照bucket数量统计x列的近似直方图\n    params:\n      - bucket_count: 桶的数量\n      - x: 数值列\n    returns: Map类型，键为桶的代表值，值为该桶的近似计数\n    example: \"* | SELECT numeric_histogram(10, cast(request_time as double))\"\n  \n  - name: numeric_histogram_u\n    syntax: \"numeric_histogram_u(bucket_count, x)\"\n    description: 按照bucket数量统计x列的近似直方图，返回多行格式\n    example: \"* | SELECT numeric_histogram_u(10, cast(request_time as double))\"\n\nuse_cases:\n  - 快速估算UV（独立访客）\n  - 计算性能指标的P50、P95、P99\n  - 生成数值分布直方图\n  - 大数据量下的快速统计\n\nimportant_notes:\n  - 估算函数牺牲精度换取性能\n  - approx_distinct使用HyperLogLog算法，标准误差约2.3%\n  - approx_percentile误差在1%以内\n  - 适用于大数据量场景\n\nFile v0.0.1:references/functions/array.yaml\n\ncategory: array_functions\nname: 数组函数和运算符\ndescription: 对数组进行增删改查、遍历和转换操作\n\nsupport:\n  sql: true\n  spl: partial\n\nfunctions:\n  - name: array_distinct\n    syntax: \"array_distinct(x)\"\n    description: 删除数组中重复的元素\n    examples:\n      sql: \"* | SELECT array_distinct(cast(json_parse(number) as array(bigint)))\"\n      spl: \"* | extend unique_arr = array_distinct(arr_field)\"\n  \n  - name: array_intersect\n    syntax: \"array_intersect(x, y)\"\n    description: 计算两个数组的交集\n    examples:\n      sql: \"* | SELECT array_intersect(array[1,2,3,4,5], array[1,3,5,7])\"\n      spl: \"* | extend intersection = array_intersect(arr1, arr2)\"\n  \n  - name: array_union\n    syntax: \"array_union(x, y)\"\n    description: 计算两个数组的并集\n    examples:\n      sql: \"* | SELECT array_union(array[1,2,3,4,5], array[1,3,5,7])\"\n    note: 仅支持SQL\n  \n  - name: array_except\n    syntax: \"array_except(x, y)\"\n    description: 计算两个数组的差集\n    examples:\n      sql: \"* | SELECT array_except(array[1,2,3,4,5], array[1,3,5,7])\"\n      spl: \"* | extend diff = array_except(arr1, arr2)\"\n  \n  - name: array_join\n    syntax: \"array_join(x, delimiter [, null_replacement])\"\n    description: 使用指定连接符将数组元素拼接为字符串\n    params:\n      - x: 数组\n      - delimiter: 连接符\n      - null_replacement: 可选，用于替换null元素的字符串\n    examples:\n      sql: \"* | SELECT array_join(array[null,'Log','Service'], ' ', 'Alicloud')\"\n      spl: \"* | extend joined = array_join(arr_field, ',')\"\n    note: 返回结果最大1KB，超出会被截断\n  \n  - name: array_max\n    syntax: \"array_max(x)\"\n    description: 获取数组中的最大值\n    examples:\n      sql: \"* | SELECT array_max(try_cast(json_parse(number) as array(bigint))) AS max_number\"\n  \n  - name: array_min\n    syntax: \"array_min(x)\"\n    description: 获取数组中的最小值\n    examples:\n      sql: \"* | SELECT array_min(try_cast(json_parse(number) as array(bigint))) AS min_number\"\n  \n  - name: array_position\n    syntax: \"array_position(x, element)\"\n    description: 获取指定元素的下标（从1开始），不存在返回0\n    examples:\n      sql: \"* | SELECT array_position(array[49,45,47], 45)\"\n  \n  - name: array_remove\n    syntax: \"array_remove(x, element)\"\n    description: 删除数组中指定的元素\n    examples:\n      sql: \"* | SELECT array_remove(array[49,45,47], 45)\"\n  \n  - name: array_sort\n    syntax: \"array_sort(x)\"\n    description: 对数组元素进行升序排序，null元素排在最后\n    examples:\n      sql: \"* | SELECT array_sort(array['b','d',null,'c','a'])\"\n  \n  - name: cardinality\n    syntax: \"cardinality(x)\"\n    description: 计算数组中元素的个数\n    examples:\n      sql: \"* | SELECT cardinality(cast(json_parse(number) as array(bigint)))\"\n  \n  - name: contains\n    syntax: \"contains(x, element)\"\n    description: 判断数组中是否包含指定元素\n    returns: boolean类型\n    examples:\n      sql: \"* | SELECT contains(cast(json_parse(region) as array(varchar)), 'cn-beijing')\"\n  \n  - name: reverse\n    syntax: \"reverse(x)\"\n    description: 对数组中的元素进行反向排列\n    examples:\n      sql: \"* | SELECT reverse(array[1,2,3,4,5])\"\n      spl: \"* | extend reversed = reverse(arr_field)\"\n  \n  - name: slice\n    syntax: \"slice(x, start, length)\"\n    description: 获取数组的子集\n    params:\n      - start: 索引开始位置（负数从末尾开始，正数从头部开始）\n      - length: 子集元素个数\n    examples:\n      sql: \"* | SELECT slice(array[1,2,4,5,6,7,7], 3, 2)\"\n  \n  - name: filter\n    syntax: \"filter(x, lambda_expression)\"\n    description: 结合Lambda表达式过滤数组元素\n    examples:\n      sql: \"* | SELECT filter(array[5,-6,null,7], x -> x > 0)\"\n      spl: \"* | extend filtered = filter(arr_field, x -> x > 0)\"\n  \n  - name: transform\n    syntax: \"transform(x, lambda_expression)\"\n    description: 将Lambda表达式应用到数组的每个元素\n    examples:\n      sql: \"* | SELECT transform(array[5,6], x -> x + 1)\"\n      spl: \"* | extend transformed = transform(arr_field, x -> x * 2)\"\n  \n  - name: reduce\n    syntax: \"reduce(x, lambda_expression)\"\n    description: 根据Lambda表达式对数组元素进行累加计算\n    examples:\n      sql: \"* | SELECT reduce(array[5,20,50], 0, (s, x) -> s + x, s -> s)\"\n  \n  - name: sequence\n    syntax: \"sequence(x, y [, step])\"\n    description: 返回起始值范围内连续递增的数组\n    params:\n      - x: 起始值\n      - y: 结束值\n      - step: 可选，递增间隔（默认为1）\n    examples:\n      sql: \"* | SELECT sequence(0, 10, 2)\"\n      spl: \"* | extend seq = sequence(1, 100)\"\n  \n  - name: zip\n    syntax: \"zip(x, y...)\"\n    description: 将多个数组合并为二维数组\n    examples:\n      sql: \"* | SELECT zip(array[1,2,3], array['1b',null,'3b'], array[1,2,3])\"\n\nimportant_notes:\n  - 数组下标从1开始\n  - array_join返回结果最大1KB\n  - 使用Lambda表达式可以实现复杂的数组处理逻辑\n  - 配合cast和json_parse处理JSON格式的数组字段\n\nFile v0.0.1:references/functions/binary.yaml\n\ncategory: binary_functions\nname: 二进制函数\ndescription: 处理二进制类型的数据，进行编码和解码\n\nsupport:\n  sql: true\n  spl: partial\n\nfunctions:\n  - name: from_base64\n    syntax: \"from_base64(x)\"\n    description: 对Base64编码的字符串进行解码\n    returns: varbinary类型\n    example: \"* | SELECT from_base64('aGVsbG8=')\"\n  \n  - name: to_base64\n    syntax: \"to_base64(x)\"\n    description: 将二进制数据编码为Base64字符串\n    returns: varchar类型\n    example: \"* | SELECT to_base64(cast('hello' as varbinary))\"\n  \n  - name: from_hex\n    syntax: \"from_hex(x)\"\n    description: 将十六进制字符串转换为二进制\n    example: \"* | SELECT from_hex('68656C6C6F')\"\n  \n  - name: to_hex\n    syntax: \"to_hex(x)\"\n    description: 将二进制数据转换为十六进制字符串\n    example: \"* | SELECT to_hex(cast('hello' as varbinary))\"\n  \n  - name: from_big_endian_64\n    syntax: \"from_big_endian_64(x)\"\n    description: 将大端序的8字节二进制转为bigint\n    example: \"* | SELECT from_big_endian_64(from_hex('0000000000000001'))\"\n  \n  - name: to_big_endian_64\n    syntax: \"to_big_endian_64(x)\"\n    description: 将bigint转为大端序的8字节二进制\n    example: \"* | SELECT to_big_endian_64(1)\"\n  \n  - name: md5\n    syntax: \"md5(x)\"\n    description: 计算MD5哈希值，返回二进制\n    example: \"* | SELECT to_hex(md5(cast('hello' as varbinary)))\"\n  \n  - name: sha1\n    syntax: \"sha1(x)\"\n    description: 计算SHA1哈希值，返回二进制\n    example: \"* | SELECT to_hex(sha1(cast('hello' as varbinary)))\"\n  \n  - name: sha256\n    syntax: \"sha256(x)\"\n    description: 计算SHA256哈希值，返回二进制\n    example: \"* | SELECT to_hex(sha256(cast('hello' as varbinary)))\"\n  \n  - name: sha512\n    syntax: \"sha512(x)\"\n    description: 计算SHA512哈希值，返回二进制\n    example: \"* | SELECT to_hex(sha512(cast('hello' as varbinary)))\"\n\nuse_cases:\n  - Base64编解码\n  - 哈希值计算\n  - 二进制数据处理\n  - 数据校验\n\nimportant_notes:\n  - 配合to_hex可以将二进制结果转为可读的十六进制\n  - 哈希函数返回二进制，通常需要to_hex转换\n  - 注意cast类型转换\n\nFile v0.0.1:references/functions/bitwise.yaml\n\ncategory: bitwise_functions\nname: 位运算函数\ndescription: 直接操作二进制位的运算函数\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: bit_count\n    syntax: \"bit_count(x, bits)\"\n    description: 统计二进制表示中1的个数\n    params:\n      - x: bigint类型的数值\n      - bits: 位数（32或64）\n    example: \"* | SELECT bit_count(5, 64)\"\n  \n  - name: bitwise_and\n    syntax: \"bitwise_and(x, y)\"\n    description: 按位与运算\n    example: \"* | SELECT bitwise_and(5, 3)\"\n  \n  - name: bitwise_or\n    syntax: \"bitwise_or(x, y)\"\n    description: 按位或运算\n    example: \"* | SELECT bitwise_or(5, 3)\"\n  \n  - name: bitwise_xor\n    syntax: \"bitwise_xor(x, y)\"\n    description: 按位异或运算\n    example: \"* | SELECT bitwise_xor(5, 3)\"\n  \n  - name: bitwise_not\n    syntax: \"bitwise_not(x)\"\n    description: 按位取反运算\n    example: \"* | SELECT bitwise_not(5)\"\n  \n  - name: bitwise_left_shift\n    syntax: \"bitwise_left_shift(x, n)\"\n    description: 按位左移n位\n    example: \"* | SELECT bitwise_left_shift(5, 2)\"\n  \n  - name: bitwise_right_shift\n    syntax: \"bitwise_right_shift(x, n)\"\n    description: 按位右移n位\n    example: \"* | SELECT bitwise_right_shift(5, 1)\"\n  \n  - name: bitwise_right_shift_arithmetic\n    syntax: \"bitwise_right_shift_arithmetic(x, n)\"\n    description: 算术右移n位（保留符号位）\n    example: \"* | SELECT bitwise_right_shift_arithmetic(-8, 2)\"\n\nuse_cases:\n  - 权限位掩码操作\n  - 标志位检查\n  - 位图运算\n  - 低级别数据处理\n\nimportant_notes:\n  - 所有位运算函数参数必须为bigint类型\n  - 需要先cast转换为bigint\n  - 位运算结果也是bigint类型\n\nFile v0.0.1:references/functions/color.yaml\n\ncategory: color_functions\nname: 颜色函数\ndescription: 颜色表示与转换，用于可视化展示\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: bar\n    syntax: \"bar(x, width [, low, high])\"\n    description: 生成ASCII条形图\n    params:\n      - x: 数值\n      - width: 条形图宽度\n      - low: 最小值（可选）\n      - high: 最大值（可选）\n    example: \"* | SELECT request_time, bar(cast(request_time as double), 20) as bar\"\n  \n  - name: color\n    syntax: \"color(string [, color])\"\n    description: 为字符串添加颜色标记（ANSI颜色码）\n    params:\n      - string: 要着色的字符串\n      - color: 颜色名称（可选）\n    example: \"* | SELECT color('ERROR', 'red')\"\n  \n  - name: render\n    syntax: \"render(x, color)\"\n    description: 使用指定颜色渲染布尔值\n    example: \"* | SELECT render(cast(status as bigint) >= 400, 'red')\"\n  \n  - name: rgb\n    syntax: \"rgb(red, green, blue)\"\n    description: 根据RGB值创建颜色\n    params:\n      - red: 红色分量(0-255)\n      - green: 绿色分量(0-255)\n      - blue: 蓝色分量(0-255)\n    example: \"* | SELECT rgb(255, 0, 0)\"\n\nuse_cases:\n  - 控制台输出美化\n  - 日志级别着色\n  - 可视化标记\n  - ASCII图表\n\nimportant_notes:\n  - 主要用于控制台输出\n  - 支持标准ANSI颜色\n  - 在Web界面可能不显示颜色\n\nArchive v0.0.1-beta.2: 61 files, 82780 bytes\n\nFiles: references/acceptance-criteria.md (4680b), references/cli-installation-guide.md (11649b), references/functions-guide.md (2128b), references/functions/aggregate.yaml (1352b), references/functions/approximate.yaml (1936b), references/functions/array.yaml (5124b), references/functions/binary.yaml (2184b), references/functions/bitwise.yaml (1682b), references/functions/color.yaml (1359b), references/functions/comparison.yaml (2378b), references/functions/conditional.yaml (1523b), references/functions/conversion.yaml (1430b), references/functions/datetime.yaml (1920b), references/functions/encoding.yaml (969b), references/functions/geo.yaml (1121b), references/functions/geospatial.yaml (2262b), references/functions/hash.yaml (693b), references/functions/hyperloglog.yaml (1313b), references/functions/ip_geo.yaml (935b), references/functions/json.yaml (901b), references/functions/lambda.yaml (3130b), references/functions/map.yaml (3609b), references/functions/math.yaml (1566b), references/functions/mobile.yaml (1107b), references/functions/operators.yaml (2310b), references/functions/overview.yaml (8152b), references/functions/README.md (3383b), references/functions/regex.yaml (1477b), references/functions/statistical.yaml (2182b), references/functions/string.yaml (3145b), references/functions/type_conversion.yaml (917b), references/functions/url.yaml (1093b), references/functions/window_funnel.yaml (2007b), references/functions/window.yaml (3045b), references/query_analysis/indexConfig.yaml (6471b), references/query_analysis/indexSearch.yaml (12221b), references/query_analysis/overview.yaml (5997b), references/query_analysis/sql.yaml (9043b), references/query-analysis.md (4818b), references/ram-policies.md (3079b), references/regions.md (1303b), references/related-apis.md (5846b), references/spl-guide.md (3097b), references/spl/extend.yaml (628b), references/spl/json_string_process.yaml (3407b), references/spl/limit.yaml (750b), references/spl/overview.yaml (9758b), references/spl/pack-fields.yaml (1420b), references/spl/parse-csv.yaml (479b), references/spl/parse-json.yaml (1011b), references/spl/parse-kv.yaml (468b), references/spl/parse-regexp.yaml (629b), references/spl/project-away.yaml (412b), references/spl/project-rename.yaml (413b), references/spl/project.yaml (574b), references/spl/sort.yaml (763b), references/spl/stats.yaml (1245b), references/spl/where.yaml (611b), references/troubleshooting.md (1651b), SKILL.md (16593b), _meta.json (148b)\n\nFile v0.0.1-beta.2:SKILL.md\n\n---\nname: alibabacloud-sls-query\ndescription: |\n  Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL scan/pipeline statements through the aliyun CLI.\n  Triggers: \"SLS 查询\", \"SLS 分析\", \"日志查询\", \"日志分析\", \"SLS 排障\", \"log query\", \"analyze logs\", \"aliyun log query\".\n---\n\n# Alibaba Cloud SLS Query & Analysis\n\n## Scenario Description\n\nUse this skill when the user wants to:\n\n- Explain, rewrite, optimize or execute an existing query\n- Translate a natural-language requirement into an SLS **index query**, **SQL**, or **SPL** statement\n\n---\n\n## Prerequisites\n\n### Install Aliyun CLI\n\nRun `aliyun version` to verify if version >= `3.3.8`. If not installed or outdated, follow the doc [references/cli-installation-guide.md](references/cli-installation-guide.md) to install or update.\n\n### Ensure AI Mode Enabled\n\nBefore executing any CLI commands, enable AI-Mode, set User-Agent, and update plugins:\n\n```bash\naliyun configure ai-mode enable\naliyun configure ai-mode set-user-agent --user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query\"\naliyun plugin update\n```\n\n### Check Alibaba Cloud credentials configured\n\nRun `aliyun configure list` to check if credentials configured.\nIf no valid profile is shown, **STOP** here and ask the user to run `aliyun configure` outside of this session.\n\n**Security rules:**\n\n- **NEVER** read, echo, or print AK/SK values\n- **NEVER** ask the user to paste AK/SK into the conversation\n- **ONLY** use `aliyun configure list` to check credential status\n\n---\n\n## RAM Permission Requirements\n\n| API | CLI | Action | Purpose |\n|-----|-----|--------|---------|\n| GetLogsV2 | `get-logs-v2` | `log:GetLogStoreLogs` | Run query / SQL / SPL and read results |\n| GetIndex  | `get-index`   | `log:GetIndex`        | Read index config to verify prerequisites |\n\nFor the minimum and complete RAM policy JSON, see [references/ram-policies.md](references/ram-policies.md).\n\n> **Permission failure handling:** If a call returns `Unauthorized` permission error, stop and surface [references/ram-policies.md](references/ram-policies.md) to the user. Do **not** retry with a different account without explicit user confirmation.\n\n---\n\n## Core Workflow\n\n1. Read index configuration (GetIndex)\n2. Pick query mode\n3. Build statement\n4. Resolve time range\n5. Execute query\n6. Extract data from response\n7. Present CLI command and results\n\n### Step 1: Read the Index Configuration (Mandatory)\n\nAlways call `get-index` first — the index config decides which query modes are available in Step 2.\n\n```bash\naliyun sls get-index \\\n  --project <project> --logstore <logstore>\n```\n\nTwo sections in the response drive every later decision:\n\n| Section | Meaning |\n|---------|---------|\n| `line`  | **Full-text index** — absence means full-text search is disabled |\n| `keys`  | **Field indexes** — map of field → `{ type, doc_value, token, caseSensitive, chn, ... }`. `doc_value: true` means statistics are enabled on that field |\n\nIf the call returns `IndexConfigNotExist` (HTTP 404), or the response has neither `line` nor `keys` populated, the Logstore has no index at all — stop immediately and tell the user they must create an index before any query / SQL / SPL can run.\n\n- **The response can be large** — extract only the fields relevant to the current query. Cache per `logstore` and reuse within the session.\n\nFor field types, tokenization, and how `get-index` maps to capabilities, see [references/related-apis.md](references/related-apis.md) and [references/query-analysis.md](references/query-analysis.md).\n\n---\n\n### Step 2: Pick the Query Mode (Critical)\n\nThe query statement takes one of the following forms:\n\n| Priority | Mode | Statement Form | Use when | Requires |\n|----------|------|----------------|----------|----------|\n| 1 | **Index search** | `<index-search>` | Filtering raw logs; return time-ordered and paginated logs | Full-text (`line`) or any field index (`keys.<field>`) |\n| 2 | **SQL** | `<index-search> \\| <SQL>` | Aggregation, `GROUP BY`, sort, window, top-N, projection, and other analytical operations | Target field has `keys.<field>` with `doc_value: true` |\n| 3 | **SQL scan** | `<index-search> \\| <SQL scan>` | User requested | None |\n| 4 | **SPL** | `<index-search> \\| <SPL>` | User requested | None |\n\n**Selection rule:**\n\n- Always prefer **Index search** for fastest speed.\n- Use **Index search + SQL** when the user needs analytical operations or field projection rather than full raw-log retrieval, such as aggregation, `GROUP BY`, sorting, window analysis, top-N, or returning only the required fields/columns.\n- Do **not** proactively choose **SQL scan** or **SPL**; use them only when the user explicitly requests.\n\nFor the full decision guide, see [references/query-analysis.md](references/query-analysis.md).\n\n---\n\n### Step 3: Write the Statement\n\n#### 3.1 Build the index-search segment first (left of `|`)\n\nCollect every filter that can be expressed in index-search syntax and place it before the first `|`. Use `*` if no filter applies.\n\n```text\n* and \"payment failed\" and status: \"500\" and not path: \"/healthz\"\n```\n\n- `*` matches all; `\"...\"` is full-text (needs full-text index).\n- `key: \"value\"` is a field filter (needs field index).\n- Combine with `and` / `or` / `not`; group with parentheses.\n- `key: *` means field exists. Range (`>`, `>=`, `[a, b]`) works only on `long` / `double`.\n\nIf the requirement can be fully answered without aggregation or row-level processing, stop here — this is already a complete index search. For full index-search syntax, see [references/query-analysis.md](references/query-analysis.md).\n\n#### 3.2 Append SQL — for aggregation / analytics\n\n```sql\nstatus: 500 | SELECT date_trunc('minute', __time__) AS minute,\n                    count(*) AS errors\n              FROM log\n              GROUP BY minute\n              ORDER BY minute\n```\n\n- Read [references/query-analysis.md](references/query-analysis.md) for Query & SQL rules\n- Table name is `log` (recommended to omit).\n- SQL respects the indexed field type from `get-index` — a `long` / `double` field can be compared directly (`status >= 500`). Cast only when a field is indexed as `text` but numeric semantics are needed (`try_cast` to suppress errors).\n- Read [references/functions-guide.md](references/functions-guide.md) for unusual Function selection (aggregate, JSON, regex, datetime, IP geo …)\n\n#### 3.3 Append SPL — for row-level processing / flexible filtering\n\n```spl\nstatus: 500 and service: payment\n| where try_cast(latency as BIGINT) > 1000\n| extend latency_ms = try_cast(latency as BIGINT)\n| project service, latency_ms, message\n```\n\nFor SPL syntax, pipeline commands, and field-handling rules, read [references/spl-guide.md](references/spl-guide.md).\n\n#### 3.4 Append SQL scan — fallback when the target field has no index / statistics\n\nSyntax follows regular SQL (see 3.2), with one difference: **every field is `varchar`**, so always `cast()` / `try_cast()` before numeric comparison or arithmetic. See [references/query-analysis.md](references/query-analysis.md) for scan semantics.\n\n```sql\n* | set session mode=scan; SELECT api, count(1) AS pv FROM log GROUP BY api\n```\n\n---\n\n### Step 4: Resolve the Time Range\n\nGenerate `--from` / `--to` as **Unix timestamps in seconds** before building the CLI command. `--from` is inclusive and `--to` is exclusive.\n\nChoose one of three input patterns:\n\n1. **Relative time** — user says \"recent / last N minutes|hours|days\".\n2. **Natural-language absolute time without timezone** — normalize to `YYYY-MM-DD HH:MM:SS`, then parse using the machine's local timezone.\n3. **Absolute time with explicit timezone** — parse using the customer-provided timezone or UTC offset.\n\n**1. Relative time**\n\n```bash\n# recent 15 minutes\nFROM=$(($(date +%s) - 900))\nTO=$(date +%s)\n```\n\n**2. Natural-language absolute time without timezone**\n\nIf the user gives a date/time but no timezone, use the machine's local timezone. First normalize natural language such as `2026年3月13日12点` to `2026-03-13 12:00:00`, then parse it as local time.\n\n```bash\n# Example: 2026年3月13日12点 -> 2026-03-13 12:00:00\n\n# Linux (GNU date): local timezone\nFROM=$(date -d \"2026-03-13 12:00:00\" +%s)\n\n# macOS (BSD date): local timezone\nFROM=$(date -j -f \"%Y-%m-%d %H:%M:%S\" \"2026-03-13 12:00:00\" +%s)\n```\n\nFor a time range such as \"2026年3月13日12点到13点\", compute both endpoints the same way. For a single point-in-time request, infer a practical window from the user's intent; if unclear, ask for the range before executing.\n\n**3. Absolute time with explicit timezone**\n\nTo convert a local date/time to a Unix timestamp: parse the input as UTC with `date -u`, then **subtract** the timezone's UTC offset in seconds.\n\nFormula: `unix_ts = date_utc_parse(input) − (UTC_offset_hours × 3600)`\n\n```bash\n# Example: 2025-01-15 10:30:00 Beijing Time (UTC+8)\n# Beijing is UTC+8, so subtract 8 × 3600 = 28800\n\n# Linux (GNU date)\nFROM=$(( $(date -u -d \"2025-01-15 10:30:00\" +%s) - 28800 ))\n\n# macOS (BSD date)\nFROM=$(( $(date -u -j -f \"%Y-%m-%d %H:%M:%S\" \"2025-01-15 10:30:00\" +%s) - 28800 ))\n```\n\n```bash\n# Example: 2025-01-15 10:30:00 New York Time (UTC-5)\n# New York is UTC-5, so subtract -5 × 3600 = subtract -18000 = add 18000\n\n# Linux (GNU date)\nFROM=$(( $(date -u -d \"2025-01-15 10:30:00\" +%s) + 18000 ))\n\n# macOS (BSD date)\nFROM=$(( $(date -u -j -f \"%Y-%m-%d %H:%M:%S\" \"2025-01-15 10:30:00\" +%s) + 18000 ))\n```\n\nCommon UTC offsets (value to subtract):\n\n| Timezone         | UTC offset hours | Seconds to subtract |\n|------------------|------------------|---------------------|\n| Beijing (UTC+8)  | +8               | `28800`             |\n| Tokyo (UTC+9)    | +9               | `32400`             |\n| London (UTC)     | 0                | `0`                 |\n| New York (UTC-5) | -5               | `-18000`            |\n\n---\n\n### Step 5: Execute via `get-logs-v2`\n\nUse `aliyun sls get-logs-v2` to execute queries. Run `aliyun help sls get-logs-v2` to see CLI parameter usage; read [references/related-apis.md](references/related-apis.md) for detailed API parameter descriptions.\n\n**Required CLI flags:**\n\n- `--project`: SLS project name\n- `--logstore`: Logstore name within the project\n- `--from`: Start of time range, **Unix timestamp in seconds** (inclusive)\n- `--to`: End of time range, **Unix timestamp in seconds** (exclusive)\n- `--query`: Statement built in Step 3\n\nPagination works differently depending on whether the statement has a `|`:\n\n#### 5.1 Index-search only — paginate with `--offset` / `--line`\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 \\\n  --query '* and \"payment failed\" and status: \"500\"' \\\n  --line 100 --offset 0 --reverse true\n```\n\n- Pagination: `--line` is page size (`1–100`, required); `--offset` is the start row (optional, default `0`).\n- Ordering: `--reverse true` returns newest first; default `false` is oldest first.\n\n#### 5.2 With SQL — paginate with `LIMIT` inside the statement\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 \\\n  --query 'status: \"500\" | SELECT request_uri, count(*) AS cnt FROM log GROUP BY request_uri ORDER BY cnt DESC LIMIT 20'\n```\n\n- SQL default result cap is **100 rows**. To get more results or paginate:\n  - `LIMIT count` — raise the cap (e.g., `LIMIT 500` returns up to 500 rows)\n  - `LIMIT offset, count` — paginate (e.g., `LIMIT 20, 20` for rows 21–40; `LIMIT 40, 20` for rows 41–60). Max offset+count is 1000000.\n  - **Do not** use `LIMIT count OFFSET offset` syntax — it is **not supported**. Always use `LIMIT offset, count`.\n- Ordering: use `ORDER BY <field> DESC/ASC` to sort.\n\n**Result completeness check:** every response contains `meta.progress`. If it is `Incomplete`, **re-issue the same request** until it returns `Complete`.\n\n---\n\n### Step 6: Extract Data from the Response\n\n`get-logs-v2` returns:\n\n```json\n{\n  \"meta\": { \"progress\": \"Complete\", \"count\": 10, ... },\n  \"data\": [ { \"field1\": \"value1\", ... }, ... ]\n}\n```\n\n| Field | Meaning |\n|-------|---------|\n| `meta.progress` | `Complete` or `Incomplete` (see Step 5) |\n| `meta.count` | Number of rows returned |\n| `data` | Array of log entries or aggregation rows; may contain `__time__` (Unix seconds, string) |\n\nUse `jq` (preferred) or `--cli-query` (JMESPath) to extract the fields the user needs:\n\n| Extract | `jq` | `--cli-query` (JMESPath) |\n|---------|------|--------------------------|\n| Data rows | `\\| jq '.data'` | `--cli-query 'data'` |\n| Progress | `\\| jq '.meta.progress'` | `--cli-query 'meta.progress'` |\n| Row count | `\\| jq '.meta.count'` | `--cli-query 'meta.count'` |\n| Specific fields | `\\| jq '.data[] \\| {LogStore, read_mb}'` | `--cli-query 'data[].{LogStore: LogStore, read_mb: read_mb}'` |\n\n---\n\n### Step 7: Present the CLI Command and Results\n\n**CLI command** — always show the full, copy-paste-ready `aliyun sls get-logs-v2 ...` command. Redact any AK/SK. If the query was not executed (write / explain scenario), present the command the user should run.\n\n**Results** — when a query was executed, use Step 6 to extract `data` and format according to the user's request (table, list, summary, etc.). Append one sentence explaining the query mode choice.\n\n---\n\n## Cleanup\n\n**Whether operations succeed or fail, you MUST disable AI-Mode before ending the session:**\n\n```bash\naliyun configure ai-mode disable\n```\n\n---\n\n## Global Rules\n\n- **Always prefer Index search for fastest raw-log retrieval, and use Index search + SQL for analysis or field projection.**\n- **When the user only needs specific fields, use `SELECT` to project them** rather than fetching full raw logs — this reduces network overhead. Requires `doc_value: true` on the target fields (confirmed in Step 1).\n- **Do not** hard-code `__time__` filters — pass time range via `--from` / `--to`.\n- **Deprecated API**: never call `get-logs`; always use `get-logs-v2`.\n\n---\n\n## Troubleshooting\n\nWhen the user reports \"no data\", \"wrong result\", or a CLI error, walk through the checklist in this exact order:\n\n1. **Time range** — wrong `--from`/`--to`? Milliseconds instead of seconds? Recent writes still indexing?\n2. **Index configuration** — field index missing? Full-text index off? Target field not in `keys`?\n3. **Field type / statistics** — range query on a `text` field? SQL on a field without `doc_value`?\n4. **Syntax** — mixed SQL and SPL? Leading `*` in fuzzy match? SPL string escaping?\n5. **Mode choice** — scanning when an index-based query would do? Aggregating in SPL instead of SQL?\n6. **Completeness** — `meta.progress = Incomplete`, caller did not retry (see Step 5).\n7. **ProjectNotExist** — region or endpoint is wrong. See [references/regions.md](references/regions.md).\n8. **Network failure** (timeout, connection refused) — try switching to internal endpoint. See [references/regions.md](references/regions.md).\n\nFor the full catalog of failure modes and error codes, see [references/troubleshooting.md](references/troubleshooting.md) and the `Common Errors` table in [references/related-apis.md](references/related-apis.md).\n\n---\n\n## Reference Documents\n\n| Document | Description |\n|----------|-------------|\n| [references/query-analysis.md](references/query-analysis.md) | Mode decision, index-search / SQL rules, scan semantics |\n| [references/spl-guide.md](references/spl-guide.md) | SPL pipeline syntax, common commands, field handling |\n| [references/functions-guide.md](references/functions-guide.md) | Function categories, SQL/SPL differences, templates |\n| [references/troubleshooting.md](references/troubleshooting.md) | \"No data / wrong result / error\" playbook |\n| [references/related-apis.md](references/related-apis.md) | `GetLogsV2` and `GetIndex` API & CLI reference |\n| [references/ram-policies.md](references/ram-policies.md) | Minimum and complete RAM policies |\n| [references/cli-installation-guide.md](references/cli-installation-guide.md) | Aliyun CLI install, auth modes, profiles |\n| [references/regions.md](references/regions.md) | Region / endpoint configuration, internal endpoint, ProjectNotExist troubleshooting |\n| [references/acceptance-criteria.md](references/acceptance-criteria.md) | CLI invocation acceptance tests |\n| `references/query_analysis/*.yaml` · `references/spl/*.yaml` · `references/functions/*.yaml` | Source-of-truth YAMLs bundled with this skill |\n\nFile v0.0.1-beta.2:references/functions/README.md\n\n# SLS 函数参考文档\n\n本目录包含 SLS SQL 和 SPL 分析语句支持的所有函数，按功能分类。\n\n## 目录结构\n\n| 文件 | 类别 | 描述 | 支持 |\n|------|------|------|------|\n| `aggregate.yaml` | 聚合函数 | count、sum、avg、max、min 等统计函数 | SQL |\n| `string.yaml` | 字符串函数 | 文本拼接、截取、大小写转换、查找替换 | SQL + SPL |\n| `regex.yaml` | 正则表达式函数 | 正则匹配、提取、替换 | SQL + SPL |\n| `datetime.yaml` | 日期时间函数 | 时间格式化、解析、截断、转换 | SQL + SPL |\n| `type_conversion.yaml` | 类型转换函数 | cast、try_cast 类型转换 | SQL + SPL |\n| `conditional.yaml` | 条件函数 | if、case、coalesce 条件判断 | SQL + SPL |\n| `json.yaml` | JSON函数 | JSON 数据提取和解析 | SQL + SPL |\n| `math.yaml` | 数学函数 | 数值计算、取整、幂运算 | SQL + SPL |\n| `url.yaml` | URL函数 | URL 解析和参数提取 | SQL + SPL |\n| `ip_geo.yaml` | IP地理位置函数 | IP 转省份、城市、国家、经纬度 | 仅SPL |\n| `encoding.yaml` | 编码解码函数 | URL、Base64 编码解码 | SQL + SPL |\n| `hash.yaml` | 哈希函数 | MD5、SHA1、SHA256 哈希计算 | SQL + SPL |\n\n## 使用说明\n\n### 1. 查找函数\n\n- **按功能查找**：根据上表选择对应的分类文件\n- **按名称查找**：在对应分类的 YAML 文件中查找具体函数\n- **按场景查找**：参考 `overview.yaml` 中的常见场景示例\n\n### 2. 查看函数详情\n\n每个 YAML 文件包含以下信息：\n\n```yaml\nfunctions:\n  - name: 函数名\n    syntax: 函数语法\n    description: 功能描述\n    examples:\n      sql: SQL 示例\n      spl: SPL 示例\n    note: 注意事项（可选）\n```\n\n### 3. 重要提示\n\n#### 类型转换\n- 字段默认为 VARCHAR 类型\n- 数值比较和运算前必须使用 `cast()` 或 `try_cast()` 转换\n- SPL 中尤其需要注意类型转换\n\n示例：\n```sql\n-- ✅ 正确\n* | SELECT * WHERE cast(status as BIGINT) >= 500\n\n-- ❌ 错误\n* | SELECT * WHERE status >= 500\n```\n\n#### SQL vs SPL\n- **SQL**：使用 SELECT、WHERE、GROUP BY 语法\n- **SPL**：使用 extend、where、stats 语法\n- **聚合函数**主要用于 SQL\n- **IP地理函数**仅用于 SPL\n\n#### 正则表达式\n- SPL 使用 RE2 正则引擎\n- 不支持：后向引用(\\1)、环视(?<=...)等\n- 反斜杠不需要双重转义：`\\d` 直接写 `\\d`\n\n## 快速示例\n\n### 统计分析\n```sql\n-- 按状态码统计\n* | SELECT status, count(*) AS pv GROUP BY status ORDER BY pv DESC\n```\n\n### 时间分组\n```sql\n-- 按小时统计\n* | SELECT date_trunc('hour', __time__) AS hour, count(*) AS pv GROUP BY hour\n```\n\n### 正则提取\n```sql\n-- 提取错误码\n* | SELECT regexp_extract(message, 'code:(\\d+)', 1) AS error_code, count(*) GROUP BY error_code\n```\n\n### JSON 解析\n```sql\n-- 提取 JSON 字段\n* | SELECT json_extract_scalar(payload, '$.user.name') AS user, count(*) GROUP BY user\n```\n\n### IP 地理分析（SPL）\n```spl\n# 按省份统计\n* | extend province = ip_to_province(client_ip) | stats pv = count(*) by province\n```\n\n## 相关文档\n\n- [函数索引](./overview.yaml) - 函数分类索引和使用指南\n- [SQL 查询语法](../query_analysis/sql.yaml) - SQL 查询完整语法\n- [SPL 基础语法](../spl/overview.yaml) - SPL 查询基础\n- [索引查询](../query_analysis/indexSearch.yaml) - 关键字搜索语法\n\nFile v0.0.1-beta.2:_meta.json\n\n{\n  \"ownerId\": \"kn74p5w8ywv6prh40g0s82gmqh83nw54\",\n  \"slug\": \"alibabacloud-sls-query\",\n  \"version\": \"0.0.1-beta.2\",\n  \"publishedAt\": 1777003192389\n}\n\nFile v0.0.1-beta.2:references/acceptance-criteria.md\n\n# Acceptance Criteria: sls-query-analysis\n\n**Scenario**: SLS Log Query & Analysis\n**Purpose**: Skill testing acceptance criteria\n\n---\n\n## Correct CLI Invocation Patterns\n\n### 1. Command Format — verify product and API name\n\n#### CORRECT\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* and status: \"500\"' \\\n  --line 100\n```\n\n#### INCORRECT — Wrong product name\n\n```bash\naliyun log get-logs-v2 --project my-project --logstore my-logstore\n```\n\n**Why**: Product name is `sls`, not `log`, `logservice`, `aliyunlog`, or `aliyun-sls`.\n\n### 2. Parameter Format\n\n#### CORRECT — Kebab-case CLI sub-command and flags\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* | select count(*) as total from log' \\\n  --line 100 \\\n  --offset 0 \\\n  --reverse true\n```\n\n#### INCORRECT — PascalCase sub-command or flags\n\n```bash\n# Sub-command in PascalCase\naliyun sls GetLogsV2 --project my-project --logstore my-logstore\naliyun sls GetIndex  --project my-project --logstore my-logstore\n\n# Flags in PascalCase\naliyun sls get-logs-v2 --Project my-project --Logstore my-logstore --From 1740000000 --To 1740003600\n```\n\n**Why**: The SLS plugin uses **kebab-case** for both sub-commands (`get-logs-v2`, `get-index`) and flags (`--project`, `--logstore`, `--from`, `--to`, `--query`).\n\n#### INCORRECT — Using `--region-id` instead of `--region`\n\n```bash\naliyun sls get-logs-v2 --region-id cn-hangzhou --project p --logstore l --from 1 --to 2\n```\n\n**Why**: The CLI global flag is `--region`, not `--region-id`.\n\n#### INCORRECT — JSON `--params` string (old SDK pattern)\n\n```bash\naliyun sls get-logs-v2 --params '{\"Project\":\"my-project\",\"Logstore\":\"my-logstore\",\"From\":\"1740000000\",\"To\":\"1740003600\"}'\n```\n\n**Why**: The CLI takes individual flags, not a JSON `--params` blob.\n\n### 3. Authentication — never expose credentials\n\n#### CORRECT — Verify credential profile via default credential chain\n\n```bash\naliyun configure list\n```\n\n#### INCORRECT — Passing AK/SK directly in the command\n\n```bash\naliyun sls get-logs-v2 \\\n  --access-key-id LTAI5tXXXX \\\n  --access-key-secret 8dXXXX \\\n  --project p --logstore l --from 1740000000 --to 1740003600\n```\n\n**Why**: Credentials must come from the configured profile, environment variables, STS, or RAM role — never be typed into the command line.\n\n#### INCORRECT — Reading or printing raw credentials\n\n```bash\naliyun configure get           # FORBIDDEN: may expose credential details\ncat ~/.aliyun/config.json      # FORBIDDEN: may expose credential details\n```\n\n#### INCORRECT — Any command that prints environment credentials\n\n```bash\necho $ALIBABA_CLOUD_ACCESS_KEY_ID       # FORBIDDEN: example of secret output\nprintenv | grep -i credential           # FORBIDDEN: may reveal secrets\nenv | grep -i access_key                # FORBIDDEN: may reveal secrets\n```\n\n### 4. API Names — verify exact sub-command\n\n#### CORRECT\n\n```\nget-logs-v2      # OpenAPI Action: GetLogsV2\nget-index        # OpenAPI Action: GetIndex\n```\n\n#### INCORRECT\n\n```\nGetLogsV2          # PascalCase is the Action name, not the CLI sub-command\nGetIndex           # PascalCase is the Action name, not the CLI sub-command\ngetLogsV2          # Wrong casing\nget_logs_v2        # Wrong separator (snake_case)\ngetlogsv2          # Missing separators\nget-logs           # Deprecated — use get-logs-v2\nget-logs-2         # Wrong suffix (v2, not 2)\ndescribe-index     # Wrong verb — SLS uses get-, not describe-\nget-log-index      # Not a real sub-command — use get-index\n```\n\n### 5. Region Parameter\n\n#### CORRECT\n\n```bash\n--region cn-hangzhou\n--region cn-shanghai\n--region ap-southeast-1\n--region us-west-1\n```\n\n#### INCORRECT\n\n```bash\n--region hangzhou       # Missing country prefix\n--region cn-hangzhou-1  # Not a real region ID\n```\n\n**Why**: Only valid Alibaba Cloud region IDs are accepted (e.g., `cn-hangzhou`, `ap-southeast-1`). The project is region-scoped — a region mismatch returns `ProjectNotExist`.\n\n### 6. Time Parameters\n\n#### CORRECT — Unix timestamp in seconds\n\n```bash\n--from 1711324800 --to 1711411200\n```\n\n#### INCORRECT — Millisecond timestamps\n\n```bash\n--from 1711324800000 --to 1711411200000\n```\n\n**Why**: `--from` / `--to` are Unix **seconds**, not milliseconds.\n\n#### INCORRECT — Date or ISO strings\n\n```bash\n--from \"2024-03-25\"             --to \"2024-03-26\"\n--from \"2024-03-25T00:00:00Z\"   --to \"2024-03-26T00:00:00Z\"\n```\n\n**Why**: Only integer seconds are accepted; date strings must be converted first (e.g., `date -d \"2024-03-25 00:00:00 UTC\" +%s`).\n\nFile v0.0.1-beta.2:references/cli-installation-guide.md\n\n# Aliyun CLI Installation & Configuration Guide\n\nComplete guide for installing and configuring Aliyun CLI.\n\n> **Aliyun CLI 3.3.8+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.8 or later for full plugin ecosystem coverage.\n\n## Installation\n\n### macOS\n\n**Using Homebrew (Recommended)**\n\n```bash\nbrew install aliyun-cli\n# Upgrade to latest\nbrew upgrade aliyun-cli\n\n# Verify version (>= 3.3.8)\naliyun version\n```\n\n**Using Binary**\n\n```bash\n# Download\nwget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz\n\n# Extract\ntar -xzf aliyun-cli-macosx-latest-amd64.tgz\n\n# Move to PATH\nsudo mv aliyun /usr/local/bin/\n\n# Verify\naliyun version\n```\n\n### Linux\n\n**Debian/Ubuntu**\n\n```bash\n# Download\nwget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz\n\n# Extract and install\ntar -xzf aliyun-cli-linux-latest-amd64.tgz\nsudo mv aliyun /usr/local/bin/\n\n# Verify\naliyun version\n```\n\n**CentOS/RHEL**\n\n```bash\n# Download\nwget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz\n\n# Extract and install\ntar -xzf aliyun-cli-linux-latest-amd64.tgz\nsudo mv aliyun /usr/local/bin/\n\n# Verify\naliyun version\n```\n\n**ARM64 Architecture**\n\n```bash\n# Download ARM64 version\nwget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz\n\n# Extract and install\ntar -xzf aliyun-cli-linux-latest-arm64.tgz\nsudo mv aliyun /usr/local/bin/\n```\n\n### Windows\n\n**Using Binary**\n\n1. Download from: <https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip>\n2. Extract the ZIP file\n3. Add the directory to your PATH environment variable\n4. Open new Command Prompt or PowerShell\n5. Verify: `aliyun version`\n\n**Using PowerShell**\n\n```powershell\n# Download\nInvoke-WebRequest -Uri \"https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip\" -OutFile \"aliyun-cli.zip\"\n\n# Extract\nExpand-Archive -Path aliyun-cli.zip -DestinationPath C:\\aliyun-cli\n\n# Add to PATH (requires admin privileges)\n$env:Path += \";C:\\aliyun-cli\"\n[Environment]::SetEnvironmentVariable(\"Path\", $env:Path, [System.EnvironmentVariableTarget]::Machine)\n\n# Verify\naliyun version\n```\n\n## Configuration\n\n### Quick Start\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id <your-access-key-id> \\\n  --access-key-secret <your-access-key-secret> \\\n  --region cn-hangzhou\n```\n\nAll `aliyun configure` commands support non-interactive flags, which is the recommended approach —\nit works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.\n\n**Where to Get Access Keys**\n\n1. Log in to Aliyun Console: <https://ram.console.aliyun.com/>\n2. Navigate to: AccessKey Management\n3. Create a new AccessKey pair\n4. Save the secret immediately — it's only shown once\n\n### Configuration Modes\n\nAliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.\n\n#### 1. AK Mode (Access Key)\n\nMost common mode for personal accounts and scripts.\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nConfiguration is stored in `~/.aliyun/config.json`:\n\n```json\n{\n  \"current\": \"default\",\n  \"profiles\": [\n    {\n      \"name\": \"default\",\n      \"mode\": \"AK\",\n      \"access_key_id\": \"LTAI5tXXXXXXXX\",\n      \"access_key_secret\": \"8dXXXXXXXXXXXXXXXXXXXXXXXX\",\n      \"region_id\": \"cn-hangzhou\",\n      \"output_format\": \"json\",\n      \"language\": \"en\"\n    }\n  ]\n}\n```\n\n#### 2. StsToken Mode (Temporary Credentials)\n\nFor short-lived access (tokens expire in 1-12 hours).\n\n```bash\naliyun configure set \\\n  --mode StsToken \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --sts-token v1.0:XXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.\n\n#### 3. RamRoleArn Mode (Assume RAM Role)\n\nAssume a RAM role for elevated or cross-account access.\n\n```bash\naliyun configure set \\\n  --mode RamRoleArn \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --ram-role-arn acs:ram::123456789012:role/AdminRole \\\n  --role-session-name my-session \\\n  --region cn-hangzhou\n```\n\nUse cases: cross-account resource access, temporary elevated privileges, role-based access control.\n\n#### 4. EcsRamRole Mode (ECS Instance RAM Role)\n\nUse the RAM role attached to an ECS instance — no credentials needed.\n\n```bash\naliyun configure set \\\n  --mode EcsRamRole \\\n  --ram-role-name MyEcsRole \\\n  --region cn-hangzhou\n```\n\nRequirements: must be running on an ECS instance with a RAM role attached.\n\nUse cases: scripts and automation running on ECS instances.\n\n#### 5. RsaKeyPair Mode (RSA Key Pair)\n\nUse RSA key pair for authentication (generate key pair in Aliyun Console first).\n\n```bash\naliyun configure set \\\n  --mode RsaKeyPair \\\n  --private-key /path/to/private-key.pem \\\n  --key-pair-name my-key-pair \\\n  --region cn-hangzhou\n```\n\n#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)\n\nCombine ECS instance role with RAM role assumption for cross-account access from ECS.\n\n```bash\naliyun configure set \\\n  --mode RamRoleArnWithEcs \\\n  --ram-role-name MyEcsRole \\\n  --ram-role-arn acs:ram::123456789012:role/TargetRole \\\n  --role-session-name my-session \\\n  --region cn-hangzhou\n```\n\n### Environment Variables\n\n**Highest priority** - overrides config file\n\n**Access Key Mode**\n\n```bash\nexport ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id\nexport ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret\nexport ALIBABA_CLOUD_REGION_ID=cn-hangzhou\n```\n\n**STS Token Mode**\n\n```bash\nexport ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id\nexport ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret\nexport ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token\nexport ALIBABA_CLOUD_REGION_ID=cn-hangzhou\n```\n\n**ECS RAM Role Mode**\n\n```bash\nexport ALIBABA_CLOUD_ECS_METADATA=role_name\n```\n\n**Use Case**:\n\n- CI/CD pipelines\n- Docker containers\n- Temporary credential override\n\n### Managing Multiple Profiles\n\n**Create Named Profiles**\n\n```bash\naliyun configure set --profile projectA \\\n  --mode AK \\\n  --access-key-id LTAI5tAAAAAAAA \\\n  --access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \\\n  --region cn-hangzhou\n\naliyun configure set --profile projectB \\\n  --mode AK \\\n  --access-key-id LTAI5tBBBBBBBB \\\n  --access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \\\n  --region cn-shanghai\n```\n\n**Use Specific Profile**\n\n```bash\naliyun ecs describe-instances --profile projectA\n\nexport ALIBABA_CLOUD_PROFILE=projectA\naliyun ecs describe-instances   # Uses projectA\n```\n\n**List and Switch Profiles**\n\n```bash\naliyun configure list                      # List all profiles\naliyun configure set --current projectA    # Switch default profile\n```\n\n### Credential Priority\n\nCredentials are loaded in this order (first found wins):\n\n1. **Command-line flag**: `--profile <name>`\n2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`\n3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.\n4. **Configuration file**: `~/.aliyun/config.json` (current profile)\n5. **ECS Instance RAM Role**: If running on ECS with attached role\n\n## Verification\n\n### Test Authentication\n\n```bash\n# Basic test - list regions\naliyun ecs describe-regions\n\n# Expected output: JSON array of regions\n```\n\n**If successful**, you'll see:\n\n```json\n{\n  \"Regions\": {\n    \"Region\": [\n      {\n        \"RegionId\": \"cn-hangzhou\",\n        \"RegionEndpoint\": \"ecs.cn-hangzhou.aliyuncs.com\",\n        \"LocalName\": \"华东 1（杭州）\"\n      },\n      ...\n    ]\n  },\n  \"RequestId\": \"...\"\n}\n```\n\n**If failed**, you'll see error messages:\n\n- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID\n- `SignatureDoesNotMatch` - Wrong Access Key Secret\n- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)\n- `Forbidden.RAM` - Insufficient permissions\n\n### Debug Configuration\n\n```bash\n# Show current configuration\naliyun configure get\n\n# Test with debug logging\naliyun ecs describe-regions --log-level=debug\n\n# Check credential provider\naliyun configure get mode\n```\n\n## Security Best Practices\n\n### 1. Use RAM Users (Not Root Account)\n\n❌ **Don't**: Use Aliyun root account credentials\n✅ **Do**: Create RAM users with specific permissions\n\n```bash\n# Create RAM user in console\n# Attach only necessary policies\n# Use RAM user's access keys\n```\n\n### 2. Principle of Least Privilege\n\nGrant only the minimum permissions needed:\n\n```bash\n# Example: Read-only ECS access\n# Attach policy: AliyunECSReadOnlyAccess\n```\n\n### 3. Rotate Access Keys Regularly\n\n```bash\n# Create new access key in RAM Console, then update configuration\naliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET\n# Delete old access key from console\n```\n\n### 4. Use STS Tokens for Temporary Access\n\n```bash\naliyun configure set --mode StsToken \\\n  --access-key-id XXXX --access-key-secret XXXX \\\n  --sts-token XXXX --region cn-hangzhou\n```\n\n### 5. Use ECS RAM Roles When Possible\n\n```bash\naliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou\n```\n\n### 6. Never Commit Credentials\n\n```bash\n# Add to .gitignore\necho \"~/.aliyun/config.json\" >> .gitignore\n\n# Use environment variables in CI/CD instead\n```\n\n### 7. Secure Config File\n\n```bash\n# Restrict permissions\nchmod 600 ~/.aliyun/config.json\n```\n\n## Troubleshooting\n\n### Issue: Command Not Found\n\n```bash\n# Check installation\nwhich aliyun\n\n# Check PATH\necho $PATH\n\n# Reinstall or add to PATH\n```\n\n### Issue: Authentication Failed\n\n```bash\n# Verify configuration\naliyun configure get\n\n# Test with debug\naliyun ecs describe-regions --log-level=debug\n\n# Check credentials in console\n# Verify access key is active\n```\n\n### Issue: Permission Denied\n\n```bash\n# Error: Forbidden.RAM\n\n# Check RAM user permissions\n# Attach necessary policies in RAM console\n# Example: AliyunECSFullAccess for ECS operations\n```\n\n### Issue: STS Token Expired\n\n```bash\n# Error: InvalidSecurityToken.Expired\n\n# Reconfigure with new token\naliyun configure set --mode StsToken \\\n  --access-key-id XXXX --access-key-secret XXXX \\\n  --sts-token NEW_TOKEN --region cn-hangzhou\n```\n\n### Issue: Wrong Region\n\n```bash\n# Some resources may not exist in the specified region\n\n# Check available regions\naliyun ecs describe-regions\n\n# Update default region\naliyun configure set region cn-shanghai\n```\n\n## Advanced Configuration\n\n### Custom Endpoint\n\n```bash\n# Use custom or private endpoint\nexport ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com\n```\n\n### Proxy Settings\n\n```bash\n# HTTP proxy\nexport HTTP_PROXY=http://proxy.example.com:8080\nexport HTTPS_PROXY=http://proxy.example.com:8080\n\n# No proxy for specific domains\nexport NO_PROXY=localhost,127.0.0.1,.aliyuncs.com\n```\n\n### Timeout Settings\n\n```bash\n# Connection timeout (default: 10s)\nexport ALIBABA_CLOUD_CONNECT_TIMEOUT=30\n\n# Read timeout (default: 10s)\nexport ALIBABA_CLOUD_READ_TIMEOUT=30\n```\n\n## Next Steps\n\nAfter installation and configuration:\n\n1. **Install plugins** for services you need (v3.3.1+ supports all published product plugins):\n\n   ```bash\n   aliyun plugin install --names ecs vpc rds\n\n   # List all available plugins\n   aliyun plugin list-remote\n   ```\n\n2. **Explore commands**:\n\n   ```bash\n   aliyun sls --help\n   aliyun fc --help\n   ```\n\n3. **Read documentation**:\n   - [Command Syntax Guide](./command-syntax.md)\n   - [Global Flags Reference](./global-flags.md)\n   - [Common Scenarios](./common-scenarios.md)\n\n## References\n\n- Official Documentation: <https://help.aliyun.com/zh/cli/>\n- RAM Console: <https://ram.console.aliyun.com/>\n- Access Key Management: <https://ram.console.aliyun.com/manage/ak>\n- Plugin Repository: <https://github.com/aliyun/aliyun-cli>\n\nFile v0.0.1-beta.2:references/functions-guide.md\n\n# 函数选型指南\n\n先按场景选函数分类，再回读 skill 内部的对应 YAML。\n\n## 高频分类\n\n- 数据统计：`./functions/aggregate.yaml`\n- 字符串处理：`./functions/string.yaml`\n- 正则匹配：`./functions/regex.yaml`\n- 时间处理：`./functions/datetime.yaml`\n- 类型转换：`./functions/type_conversion.yaml`\n- 条件判断：`./functions/conditional.yaml`\n- JSON 提取：`./functions/json.yaml`\n- 数值计算：`./functions/math.yaml`\n- URL 解析：`./functions/url.yaml`\n- 数组 / Map：`./functions/array.yaml`、`./functions/map.yaml`\n- 窗口分析：`./functions/window.yaml`\n- 漏斗分析：`./functions/window_funnel.yaml`\n- Lambda 表达式：`./functions/lambda.yaml`\n\n## 语言差异\n\n- SQL + SPL 都支持：字符串、正则、时间、类型转换、条件、JSON、数学、URL、编码、哈希、数组、Map 等大部分基础函数\n- 仅 SQL：窗口函数、位运算、空间函数、HyperLogLog、统计函数、漏斗函数等\n- 仅 SPL：`ip_to_province`、`ip_to_city`、`ip_to_country`、`ip_to_geo`\n\n## 高频提醒\n\n- 数值比较前必须先 `cast()` 或 `try_cast()`\n- 想避免转换失败时整条报错，用 `try_cast()`\n- 时间分组优先 `date_trunc()` 或 `date_format()`\n- JSON 字段优先 `json_extract()` / `json_extract_scalar()`\n- SPL 做转义相关处理，优先看 `ascii_escape`、`ascii_unescape`、`unicode_unescape`\n- SPL 中某些函数能力和 SQL 不完全对齐，拿不准时回读对应函数 YAML\n\n## 常见模板\n\n### 类型转换\n```sql\n* | SELECT count(*) FROM log WHERE cast(status as BIGINT) >= 500\n```\n\n```spl\n* | where try_cast(status as BIGINT) >= 500\n```\n\n### JSON 提取\n```sql\n* | SELECT json_extract_scalar(payload, '$.user.id') AS user_id, count(*) FROM log GROUP BY user_id\n```\n\n### 正则提取\n```sql\n* | SELECT regexp_extract(message, 'code:(\\d+)', 1) AS code, count(*) FROM log GROUP BY code\n```\n\n### SPL 地域分析\n```spl\n* | extend province = ip_to_province(client_ip) | stats pv = count(*) by province\n```\n\n## 本地源文档\n\n- `./functions/overview.yaml`\n- `./functions/README.md`\n- `./functions/*.yaml`\n\nFile v0.0.1-beta.2:references/functions/aggregate.yaml\n\ncategory: aggregate_functions\nname: 聚合函数\ndescription: 对数据进行汇总计算，通常与GROUP BY配合使用\n\nsupport: \n  sql: true\n  spl: false\n\nfunctions:\n  - name: count\n    syntax: \"count(*) 或 count(x)\"\n    description: 统计日志条数\n    example: \"* | SELECT count(*) AS pv\"\n    note: \"count(*) 统计所有，count(x) 统计x非NULL的数量\"\n  \n  - name: sum\n    syntax: \"sum(x)\"\n    description: 计算总和\n    example: \"* | SELECT sum(cast(response_size as BIGINT)) AS total_size\"\n  \n  - name: avg\n    syntax: \"avg(x)\"\n    description: 计算平均值\n    example: \"* | SELECT avg(cast(request_time as DOUBLE)) AS avg_time\"\n  \n  - name: max\n    syntax: \"max(x)\"\n    description: 返回最大值\n    example: \"* | SELECT max(cast(response_time as BIGINT)) AS max_time\"\n  \n  - name: min\n    syntax: \"min(x)\"\n    description: 返回最小值\n    example: \"* | SELECT min(cast(response_time as BIGINT)) AS min_time\"\n  \n  - name: count_if\n    syntax: \"count_if(condition)\"\n    description: 统计满足条件的日志数\n    example: \"* | SELECT count_if(cast(status as BIGINT) >= 500) AS error_count\"\n  \n  - name: arbitrary\n    syntax: \"arbitrary(x)\"\n    description: 返回任意一个非空值\n    example: \"* | SELECT status, arbitrary(request_time) GROUP BY status\"\n    note: 用于GROUP BY时获取非分组字段的值\n\nFile v0.0.1-beta.2:references/functions/approximate.yaml\n\ncategory: approximate_functions\nname: 估算函数\ndescription: 基于数据预测或填充缺失值的近似计算\n\nsupport:\n  sql: true\n  spl: false\n\nfunctions:\n  - name: approx_distinct\n    syntax: \"approx_distinct(x)\"\n    description: 估算唯一值的个数，使用HyperLogLog算法\n    returns: 近似计数\n    example: \"* | SELECT approx_distinct(client_ip) AS uv\"\n    note: 比count(distinct x)更快，但是近似值\n  \n  - name: approx_percentile\n    syntax: \"approx_percentile(x, percentage)\"\n    description: 计算近似百分位数\n    params:\n      - x: 列名\n      - percentage: 百分位，取值0~1\n    example: \"* | SELECT approx_percentile(cast(request_time as double), 0.99) AS p99\"\n  \n  - name: approx_percentile (with array)\n    syntax: \"approx_percentile(x, array[p1, p2,...])\"\n    description: 同时计算多个百分位数\n    example: \"* | SELECT approx_percentile(cast(request_time as double), array[0.5, 0.95, 0.99]) AS percentiles\"\n  \n  - name: numeric_histogram\n    syntax: \"numeric_histogram(bucket_count, x)\"\n    description: 按照bucket数量统计x列的近似直方图\n    params:\n      - bucket_count: 桶的数量\n      - x: 数值列\n    returns: Map类型，键为桶的代表值，值为该桶的近似计数\n    example: \"* | SELECT numeric_histogram(10, cast(request_time as double))\"\n  \n  - name: numeric_histogram_u\n    syntax: \"numeric_histogram_u(bucket_count, x)\"\n    description: 按照bucket数量统计x列的近似直方图，返回多行格式\n    example: \"* | SELECT numeric_histogram_u(10, cast(request_time as double))\"\n\nuse_cases:\n  - 快速估算UV（独立访客）\n  - 计算性能指标的P50、P95、P99\n  - 生成数值分布直方图\n  - 大数据量下的快速统计\n\nimportant_notes:\n  - 估算函数牺牲精度换取性能\n  - approx_distinct使用HyperLogLog算法，标准误差约2.3%\n  - approx_percentile误差在1%以内\n  - 适用于大数据量场景\n\nFile v0.0.1-beta.2:references/functions/array.yaml\n\ncategory: array_functions\nname: 数组函数和运算符\ndescription: 对数组进行增删改查、遍历和转换操作\n\nsupport:\n  sql: true\n  spl: partial\n\nfunctions:\n  - name: array_distinct\n    syntax: \"array_distinct(x)\"\n    description: 删除数组中重复的元素\n    examples:\n      sql: \"* | SELECT array_distinct(cast(json_parse(number) as array(bigint)))\"\n      spl: \"* | extend unique_arr = array_distinct(arr_field)\"\n  \n  - name: array_intersect\n    syntax: \"array_intersect(x, y)\"\n    description: 计算两个数组的交集\n    examples:\n      sql: \"* | SELECT array_intersect(array[1,2,3,4,5], array[1,3,5,7])\"\n      spl: \"* | extend intersection = array_intersect(arr1, arr2)\"\n  \n  - name: array_union\n    syntax: \"array_union(x, y)\"\n    description: 计算两个数组的并集\n    examples:\n      sql: \"* | SELECT array_union(array[1,2,3,4,5], array[1,3,5,7])\"\n    note: 仅支持SQL\n  \n  - name: array_except\n    syntax: \"array_except(x, y)\"\n    description: 计算两个数组的差集\n    examples:\n      sql: \"* | SELECT array_except(array[1,2,3,4,5], array[1,3,5,7])\"\n      spl: \"* | extend diff = array_except(arr1, arr2)\"\n  \n  - name: array_join\n    syntax: \"array_join(x, delimiter [, null_replacement])\"\n    description: 使用指定连接符将数组元素拼接为字符串\n    params:\n      - x: 数组\n      - delimiter: 连接符\n      - null_replacement: 可选，用于替换null元素的字符串\n    examples:\n      sql: \"* | SELECT array_join(array[null,'Log','Service'], ' ', 'Alicloud')\"\n      spl: \"* | extend joined = array_join(arr_field, ',')\"\n    note: 返回结果最大1KB，超出会被截断\n  \n  - name: array_max\n    syntax: \"array_max(x)\"\n    description: 获取数组中的最大值\n    examples:\n      sql: \"* | SELECT array_max(try_cast(json_parse(number) as array(bigint))) AS max_number\"\n  \n  - name: array_min\n    syntax: \"array_min(x)\"\n    description: 获取数组中的最小值\n    examples:\n      sql: \"* | SELECT array_min(try_cast(json_parse(number) as array(bigint))) AS min_number\"\n  \n  - name: array_position\n    syntax: \"array_position(x, element)\"\n    description: 获取指定元素的下标（从1开始），不存在返回0\n    examples:\n      sql: \"* | SELECT array_position(array[49,45,47], 45)\"\n  \n  - name: array_remove\n    syntax: \"array_remove(x, element)\"\n    description: 删除数组中指定的元素\n    examples:\n      sql: \"* | SELECT array_remove(array[49,45,47], 45)\"\n  \n  - name: array_sort\n    syntax: \"array_sort(x)\"\n    description: 对数组元素进行升序排序，null元素排在最后\n    examples:\n      sql: \"* | SELECT array_sort(array['b','d',null,'c','a'])\"\n  \n  - name: cardinality\n    syntax: \"cardinality(x)\"\n    description: 计算数组中元素的个数\n    examples:\n      sql: \"* | SELECT cardinality(cast(json_parse(number) as array(bigint)))\"\n\n\nArchive v0.0.1-beta.1: 61 files, 82376 bytes\n\nFiles: references/acceptance-criteria.md (4680b), references/cli-installation-guide.md (11649b), references/functions-guide.md (2128b), references/functions/aggregate.yaml (1352b), references/functions/approximate.yaml (1936b), references/functions/array.yaml (5124b), references/functions/binary.yaml (2184b), references/functions/bitwise.yaml (1682b), references/functions/color.yaml (1359b), references/functions/comparison.yaml (2378b), references/functions/conditional.yaml (1523b), references/functions/conversion.yaml (1430b), references/functions/datetime.yaml (1920b), references/functions/encoding.yaml (969b), references/functions/geo.yaml (1121b), references/functions/geospatial.yaml (2262b), references/functions/hash.yaml (693b), references/functions/hyperloglog.yaml (1313b), references/functions/ip_geo.yaml (935b), references/functions/json.yaml (901b), references/functions/lambda.yaml (3130b), references/functions/map.yaml (3609b), references/functions/math.yaml (1566b), references/functions/mobile.yaml (1107b), references/functions/operators.yaml (2310b), references/functions/overview.yaml (8152b), references/functions/README.md (3383b), references/functions/regex.yaml (1477b), references/functions/statistical.yaml (2182b), references/functions/string.yaml (3145b), references/functions/type_conversion.yaml (917b), references/functions/url.yaml (1093b), references/functions/window_funnel.yaml (2007b), references/functions/window.yaml (3045b), references/query_analysis/indexConfig.yaml (6471b), references/query_analysis/indexSearch.yaml (12221b), references/query_analysis/overview.yaml (5997b), references/query_analysis/sql.yaml (9043b), references/query-analysis.md (4818b), references/ram-policies.md (3079b), references/regions.md (1303b), references/related-apis.md (5846b), references/spl-guide.md (3097b), references/spl/extend.yaml (628b), references/spl/json_string_process.yaml (3407b), references/spl/limit.yaml (750b), references/spl/overview.yaml (9758b), references/spl/pack-fields.yaml (1420b), references/spl/parse-csv.yaml (479b), references/spl/parse-json.yaml (1011b), references/spl/parse-kv.yaml (468b), references/spl/parse-regexp.yaml (629b), references/spl/project-away.yaml (412b), references/spl/project-rename.yaml (413b), references/spl/project.yaml (574b), references/spl/sort.yaml (763b), references/spl/stats.yaml (1245b), references/spl/where.yaml (611b), references/troubleshooting.md (1651b), SKILL.md (15480b), _meta.json (148b)","readmeExcerpt":"Skill: Alibabacloud Sls Query Owner: sdk-team Summary: Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index... Tags: latest:0.0.2 Version history: v0.0.2 | 2026-06-29T02:00:04.266Z | auto alibabacloud-sls-query v0.0.2 - Added explicit per-session random user-agent format requirement for all aliyun API commands, enh","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"aliyun plugin update"},{"language":"text","snippet":"--user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query/{session-id}\""},{"language":"bash","snippet":"aliyun sls get-logs-v2 --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 --query '*' \\\n  --user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6\""},{"language":"bash","snippet":"aliyun sls get-index \\\n  --project <project> --logstore <logstore>"},{"language":"text","snippet":"* and \"payment failed\" and status: \"500\" and not path: \"/healthz\""},{"language":"sql","snippet":"status: 500 | SELECT date_trunc('minute', __time__) AS minute,\n                    count(*) AS errors\n              FROM log\n              GROUP BY minute\n              ORDER BY minute"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: alibabacloud-sls-query\ndescription: |\n  Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL scan/pipeline statements through the aliyun CLI.\n  Triggers: \"SLS 查询\", \"SLS 分析\", \"日志查询\", \"日志分析\", \"log query\", \"analyze sls logs\", \"aliyun log query\".\n---\n\n# Alibaba Cloud SLS Query & Analysis\n\n## Scenario Description\n\nUse this skill when the user wants to:\n\n- Explain, rewrite, optimize or execute an existing query\n- Translate a natural-language requirement into an SLS **index query**, **SQL**, or **SPL** statement\n\n---\n\n## Prerequisites\n\n### Install Aliyun CLI\n\nRun `aliyun version` to verify if version >= `3.3.8`. If not installed or outdated, follow the doc [references/cli-installation-guide.md](references/cli-installation-guide.md) to install or update.\n\n### Update Plugins\n\n```bash\naliyun plugin update\n```\n\n### Check Alibaba Cloud credentials configured\n\nRun `aliyun configure list` to check if credentials configured.\nIf no valid profile is shown, **STOP** here and ask the user to run `aliyun configure` outside of this session.\n\n**Security rules:**\n\n- **NEVER** read, echo, or print AK/SK values\n- **NEVER** ask the user to paste AK/SK into the conversation\n- **ONLY** use `aliyun configure list` to check credential status\n\n---\n\n## RAM Permission Requirements\n\n| API | CLI | Action | Purpose |\n|-----|-----|--------|---------|\n| GetLogsV2 | `get-logs-v2` | `log:GetLogStoreLogs` | Run query / SQL / SPL and read results |\n| GetIndex  | `get-index`   | `log:GetIndex`        | Read index config to verify prerequisites |\n\nFor the minimum and complete RAM policy JSON, see [references/ram-policies.md](references/ram-policies.md).\n\n> **Permission failure handling:** If a call returns `Unauthorized` permission error, stop and surface [references/ram-policies.md](references/ram-policies.md) to the user. Do **not** retry with a different account without explicit user confirmation.\n\n---\n\n## Observability (MUST follow for every aliyun api command)\n\nUpon loading this skill, generate a random session ID (32-char lowercase hex string) once for the entire session. Use it as `{session-id}` below.\n\n**Rule:** Every `aliyun` CLI command that calls a cloud API **MUST** include the `--user-agent` flag. Local utility commands (e.g. `configure`, `plugin`, `version`) do not support this flag and should be excluded.\n\n```\n--user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query/{session-id}\"\n```\n\nExample (assuming session-id is `a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6`):\n\n```bash\naliyun sls get-logs-v2 --project my-project --logstore my-logstore \\\n  --from 1740000000 --to 1740003600 --query '*' \\\n  --user-agent \"AlibabaCloud-Agent-Skills/alibabacloud-sls-query/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6\"\n```\n\nDo not skip, alter the format, or omit `--user-agent` on any `aliyun` API command invocation.\n\n---\n\n## Core Workflow\n\n1. Read index configuration (Ge"},{"path":"references/functions/README.md","content":"# SLS Function Reference\n\nThis directory contains all functions supported by SLS SQL and SPL analysis statements, organized by category.\n\n## Directory Structure\n\n| File | Category | Description | Supported In |\n|------|----------|-------------|--------------|\n| `aggregate.yaml` | Aggregate Functions | count, sum, avg, max, min and other statistical functions | SQL |\n| `string.yaml` | String Functions | Text concatenation, substring, case conversion, find & replace | SQL + SPL |\n| `regex.yaml` | Regex Functions | Regex match, extract, replace | SQL + SPL |\n| `datetime.yaml` | Date/Time Functions | Time formatting, parsing, truncation, conversion | SQL + SPL |\n| `type_conversion.yaml` | Type Conversion Functions | cast, try_cast type conversion | SQL + SPL |\n| `conditional.yaml` | Conditional Functions | if, case, coalesce conditional logic | SQL + SPL |\n| `json.yaml` | JSON Functions | JSON data extraction and parsing | SQL + SPL |\n| `math.yaml` | Math Functions | Numeric calculations, rounding, exponentiation | SQL + SPL |\n| `url.yaml` | URL Functions | URL parsing and parameter extraction | SQL + SPL |\n| `ip_geo.yaml` | IP Geolocation Functions | IP to province, city, country, coordinates | SPL only |\n| `encoding.yaml` | Encoding/Decoding Functions | URL, Base64 encoding and decoding | SQL + SPL |\n| `hash.yaml` | Hash Functions | MD5, SHA1, SHA256 hash computation | SQL + SPL |\n\n## Usage\n\n### 1. Finding Functions\n\n- **By category**: Select the corresponding file from the table above\n- **By name**: Search for the specific function in the relevant YAML file\n- **By scenario**: Refer to `overview.yaml` for common scenario examples\n\n### 2. Function Details\n\nEach YAML file contains the following structure:\n\n```yaml\nfunctions:\n  - name: function_name\n    syntax: function_syntax\n    description: what_it_does\n    examples:\n      sql: SQL example\n      spl: SPL example\n    note: caveats (optional)\n```\n\n### 3. Important Notes\n\n#### Type Conversion\n- Fields default to VARCHAR type\n- Always use `cast()` or `try_cast()` before numeric comparison or arithmetic\n- Pay special attention to type conversion in SPL\n\nExample:\n```sql\n-- Correct\n* | SELECT * WHERE cast(status as BIGINT) >= 500\n\n-- Wrong\n* | SELECT * WHERE status >= 500\n```\n\n#### SQL vs SPL\n- **SQL**: uses SELECT, WHERE, GROUP BY syntax\n- **SPL**: uses extend, where, stats syntax\n- **Aggregate functions** are primarily used in SQL\n- **IP geo functions** are SPL only\n\n#### Regular Expressions\n- SPL uses the RE2 regex engine\n- Not supported: back-references (\\1), lookaround (?<=...), etc.\n- No double-escaping needed: `\\d` is written as `\\d`\n\n## Quick Examples\n\n### Statistical Analysis\n```sql\n-- Count by status code\n* | SELECT status, count(*) AS pv GROUP BY status ORDER BY pv DESC\n```\n\n### Time Grouping\n```sql\n-- Hourly aggregation\n* | SELECT date_trunc('hour', __time__) AS hour, count(*) AS pv GROUP BY hour\n```\n\n### Regex Extraction\n```sql\n-- Extract error codes\n* | SELECT regexp_extract(message, 'code:("},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn74p5w8ywv6prh40g0s82gmqh83nw54\",\n  \"slug\": \"alibabacloud-sls-query\",\n  \"version\": \"0.0.2\",\n  \"publishedAt\": 1782698404266\n}"},{"path":"references/acceptance-criteria.md","content":"# Acceptance Criteria: sls-query-analysis\n\n**Scenario**: SLS Log Query & Analysis\n**Purpose**: Skill testing acceptance criteria\n\n---\n\n## Correct CLI Invocation Patterns\n\n### 1. Command Format — verify product and API name\n\n#### CORRECT\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* and status: \"500\"' \\\n  --line 100\n```\n\n#### INCORRECT — Wrong product name\n\n```bash\naliyun log get-logs-v2 --project my-project --logstore my-logstore\n```\n\n**Why**: Product name is `sls`, not `log`, `logservice`, `aliyunlog`, or `aliyun-sls`.\n\n### 2. Parameter Format\n\n#### CORRECT — Kebab-case CLI sub-command and flags\n\n```bash\naliyun sls get-logs-v2 \\\n  --project my-project \\\n  --logstore my-logstore \\\n  --from 1740000000 \\\n  --to 1740003600 \\\n  --query '* | select count(*) as total from log' \\\n  --line 100 \\\n  --offset 0 \\\n  --reverse true\n```\n\n#### INCORRECT — PascalCase sub-command or flags\n\n```bash\n# Sub-command in PascalCase\naliyun sls GetLogsV2 --project my-project --logstore my-logstore\naliyun sls GetIndex  --project my-project --logstore my-logstore\n\n# Flags in PascalCase\naliyun sls get-logs-v2 --Project my-project --Logstore my-logstore --From 1740000000 --To 1740003600\n```\n\n**Why**: The SLS plugin uses **kebab-case** for both sub-commands (`get-logs-v2`, `get-index`) and flags (`--project`, `--logstore`, `--from`, `--to`, `--query`).\n\n#### INCORRECT — Using `--region-id` instead of `--region`\n\n```bash\naliyun sls get-logs-v2 --region-id cn-hangzhou --project p --logstore l --from 1 --to 2\n```\n\n**Why**: The CLI global flag is `--region`, not `--region-id`.\n\n#### INCORRECT — JSON `--params` string (old SDK pattern)\n\n```bash\naliyun sls get-logs-v2 --params '{\"Project\":\"my-project\",\"Logstore\":\"my-logstore\",\"From\":\"1740000000\",\"To\":\"1740003600\"}'\n```\n\n**Why**: The CLI takes individual flags, not a JSON `--params` blob.\n\n### 3. Authentication — never expose credentials\n\n#### CORRECT — Verify credential profile via default credential chain\n\n```bash\naliyun configure list\n```\n\n#### INCORRECT — Passing AK/SK directly in the command\n\n```bash\naliyun sls get-logs-v2 \\\n  --access-key-id LTAI5tXXXX \\\n  --access-key-secret 8dXXXX \\\n  --project p --logstore l --from 1740000000 --to 1740003600\n```\n\n**Why**: Credentials must come from the configured profile, environment variables, STS, or RAM role — never be typed into the command line.\n\n#### INCORRECT — Reading or printing raw credentials\n\n```bash\naliyun configure get           # FORBIDDEN: may expose credential details\ncat ~/.aliyun/config.json      # FORBIDDEN: may expose credential details\n```\n\n#### INCORRECT — Any command that prints environment credentials\n\n```bash\necho $ALIBABA_CLOUD_ACCESS_KEY_ID       # FORBIDDEN: example of secret output\nprintenv | grep -i credential           # FORBIDDEN: may reveal secrets\nenv | grep -i access_key                # FORBIDDEN: may reveal secrets\n```\n\n### 4. API Names — verify exact sub-comma"},{"path":"references/cli-installation-guide.md","content":"# Aliyun CLI Installation & Configuration Guide\n\nComplete guide for installing and configuring Aliyun CLI.\n\n> **Aliyun CLI 3.3.8+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.8 or later for full plugin ecosystem coverage.\n\n## Installation\n\n### macOS or linux\n\n```bash\n/bin/bash -c \"$(curl -fsSL https://aliyuncli.alicdn.com/install.sh)\"\n\n# Verify\naliyun version\n```\n\n### Windows\n\n**Using Binary**\n\n1. Download from: <https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip>\n2. Extract the ZIP file\n3. Add the directory to your PATH environment variable\n4. Open new Command Prompt or PowerShell\n5. Verify: `aliyun version`\n\n**Using PowerShell**\n\n```powershell\n# Download\nInvoke-WebRequest -Uri \"https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip\" -OutFile \"aliyun-cli.zip\"\n\n# Extract\nExpand-Archive -Path aliyun-cli.zip -DestinationPath C:\\aliyun-cli\n\n# Add to PATH (requires admin privileges)\n$env:Path += \";C:\\aliyun-cli\"\n[Environment]::SetEnvironmentVariable(\"Path\", $env:Path, [System.EnvironmentVariableTarget]::Machine)\n\n# Verify\naliyun version\n```\n\n## Configuration\n\n### Quick Start\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id <your-access-key-id> \\\n  --access-key-secret <your-access-key-secret> \\\n  --region cn-hangzhou\n```\n\nAll `aliyun configure` commands support non-interactive flags, which is the recommended approach —\nit works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.\n\n**Where to Get Access Keys**\n\n1. Log in to Aliyun Console: <https://ram.console.aliyun.com/>\n2. Navigate to: AccessKey Management\n3. Create a new AccessKey pair\n4. Save the secret immediately — it's only shown once\n\n### Configuration Modes\n\nAliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.\n\n#### 1. AK Mode (Access Key)\n\nMost common mode for personal accounts and scripts.\n\n```bash\naliyun configure set \\\n  --mode AK \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nConfiguration is stored in `~/.aliyun/config.json`:\n\n```json\n{\n  \"current\": \"default\",\n  \"profiles\": [\n    {\n      \"name\": \"default\",\n      \"mode\": \"AK\",\n      \"access_key_id\": \"LTAI5tXXXXXXXX\",\n      \"access_key_secret\": \"8dXXXXXXXXXXXXXXXXXXXXXXXX\",\n      \"region_id\": \"cn-hangzhou\",\n      \"output_format\": \"json\",\n      \"language\": \"en\"\n    }\n  ]\n}\n```\n\n#### 2. StsToken Mode (Temporary Credentials)\n\nFor short-lived access (tokens expire in 1-12 hours).\n\n```bash\naliyun configure set \\\n  --mode StsToken \\\n  --access-key-id LTAI5tXXXXXXXX \\\n  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \\\n  --sts-token v1.0:XXXXXXXXXXXXXXXX \\\n  --region cn-hangzhou\n```\n\nUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.\n\n#### 3. RamRoleArn Mode (Assume RAM Role)\n\nAssume a RAM role for elevated or cross-account access.\n\n```bash\naliyun configure set \\\n  "}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":null,"editorialQuality":{"score":100,"threshold":65,"status":"thin","wordCount":1637,"uniquenessScore":43,"reasons":["uniqueness-below-45"]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T04:02:31.758Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T04:02:31.758Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T07:41:11.818Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}