Skip to content
Back to search

loongsuite-pilot

Local-first telemetry collector for AI coding agents — unified OpenTelemetry events for Claude Code, Codex, Cursor and more. Token usage, cost, traces and security audit, exported anywhere.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/alibaba/loongsuite-pilot with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/alibaba/loongsuite-pilot'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/alibaba--loongsuite-pilot/badge.svg)](/listings/alibaba--loongsuite-pilot)

HTML

<a href="/listings/alibaba--loongsuite-pilot"><img src="/api/listings/alibaba--loongsuite-pilot/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Prerequisites:

- Node.js 18 or later - `npm` - `curl` or `wget` - PowerShell 5.1 or later on Windows

Install from the public package on Linux or macOS:

curl -fsSL https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/installer.sh -o /tmp/loongsuite-pilot-installer.sh && bash /tmp/loongsuite-pilot-installer.sh install

Install from the public package on Windows:

$installer = "$env:TEMP\loongsuite-pilot-installer.ps1"
Invoke-WebRequest `
  -Uri "https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/installer.ps1" `
  -OutFile $installer
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installer install

Verify the service:

loongsuite-pilot status
loongsuite-pilot info

Local JSONL output is enabled by default under `~/.loongsuite-pilot/logs/output/` on Linux/macOS and `%USERPROFILE%\.loongsuite-pilot\logs\output\` on Windows.

For installer options, uninstall commands, and source builds, see [Installation](docs/installation.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 20 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: loongsuite-pilot-ops
  3. description: loongsuite-pilot-ops
  4. ---
  5. # loongsuite-pilot-ops
  6. ## Overview
  7. loongsuite-pilot-ops
  8. ## Quick Start
  9. ```bash
  10. # TODO: Add quick start commands
  11. ```
  12. ## Usage
  13. Please refer to the documentation for detailed usage instructions.
README.md · README · 315 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # LoongSuite Pilot
  2. ![LoongSuite](docs/_assets/img/loongsuite-logo.png)
  3. **Local telemetry collector for AI coding agents**
  4. [![CI](https://github.com/alibaba/loongsuite-pilot/actions/workflows/ci.yml/badge.svg)](https://github.com/alibaba/loongsuite-pilot/actions/workflows/ci.yml)
  5. [![Release](https://img.shields.io/github/v/release/alibaba/loongsuite-pilot)](https://github.com/alibaba/loongsuite-pilot/releases/latest)
  6. [![License](https://img.shields.io/github/license/alibaba/loongsuite-pilot)](LICENSE)
  7. [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22.13-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
  8. [![OpenTelemetry](https://img.shields.io/badge/OpenTelemetry-enabled-4F62AD)](https://opentelemetry.io/)
  9. **English** | [简体中文](README.zh-CN.md)
  10. [Overview](#overview) | [Quick Start](#quick-start) | [Documentation](#documentation) | [Community](#community) | [Contributing](#contributing)
  11. ---
  12. ## Overview
  13. LoongSuite Pilot is a local telemetry collector for AI coding agents. It discovers supported agents on a developer machine, installs the required hooks or plugins, normalizes activity into a shared GenAI event schema, and exports logs or traces to your chosen backends.
  14. <p align="center">
  15. <img src="docs/_assets/img/dashboard.png" alt="LoongSuite Pilot local dashboard" width="880">
  16. <br>
  17. <em>Built-in local dashboard — multi-agent token usage, sessions, requests, tools, models, providers, and repository activity at a glance.</em>
  18. </p>
  19. Development teams often use more than one AI coding agent, and each agent records activity in a different local format. Pilot gives teams one local collector that can discover those agents, collect their activity, normalize the data, and send it to destinations that are useful for analysis, audit, and observability.
  20. Pilot is designed to answer practical questions:
  21. - Which agents are being used?
  22. - What model, session, turn, and tool activity happened?
  23. - How much token usage is available from each agent?
  24. - Where should the data be exported: local files, SLS, HTTP, or traces?
  25. - How should sensitive prompts, tool arguments, and secrets be controlled before export?
  26. ## Highlights
  27. | Capability | What Pilot Does |
  28. | ------------------------ | ---------------------------------------------------------------------------------- |
  29. | Agent discovery | Detects supported agents from local paths and commands. |
  30. | Collection deployment | Installs hooks or plugins and reads local logs, sessions, or data files. |
  31. | Unified event schema | Normalizes agent-native events into a shared GenAI schema. |
  32. | Multi-destination output | Exports to JSONL, Alibaba Cloud SLS, HTTP, and OTLP trace backends. |
  33. | Privacy controls | Supports secret masking before output. |
  34. | Local operations | Provides service status, restart, rollback, and a built-in local dashboard. |
  35. ## Supported Agents
  36. | Agent | Integration | Trace Export | Log Export | Token Usage | Conversation / Tool Calls |
  37. | ------------- | ------------------------- | ------------ | ---------- | ----------- | ------------------------- |
  38. | Claude Code | Hook | Yes | Yes | Yes | Yes |
  39. | Codex | Hook | Yes | Yes | Yes | Yes |
  40. | GitHub Copilot CLI | Native plugin + transcript / native OTel | Yes | Yes | Yes (native OTel) | Yes |
  41. | Cursor | Hook | Yes | Yes | Yes | Yes |
  42. | Cursor CLI | Shared Cursor hook | Yes | Yes | Yes | Yes |
  43. | DeepSeek Harness | YAML patch plugin + local JSONL polling | Yes | Yes | Yes | Yes |
  44. | Grok Build | Hook + local session logs | Yes | Yes | Yes | Yes |
  45. | Hermes Agent | Native directory plugin | Yes | Yes | Yes | Yes |
  46. | Kiro CLI | Hook / session polling | Yes | Yes | No | Yes |
  47. | MiMo Code | Plugin injection | Yes | Yes | Yes | Yes |
  48. | OpenClaw | Plugin injection | Yes | Yes | Yes | Yes |
  49. | OpenCode | Plugin injection | Yes | Yes | Yes | Yes |
  50. | Pi Coding Agent | Extension injection | Yes | Yes | Yes | Yes |
  51. | Qoder | Hook | Yes | Yes | Yes | Yes |
  52. | Qoder CN | Hook | Yes | Yes | Yes | Yes |
  53. | Qoder for JetBrains | Detection-only | Yes | Yes | Yes | Yes |
  54. | Qoder CLI | Hook / session polling | Yes | Yes | Yes | Yes |
  55. | Qoder Work | Hook / local data polling | Yes | Yes | Yes | Yes |
  56. | Qoder Work CN | Hook / local data polling | Yes | Yes | Yes | Yes |
  57. | Qwen Code CLI | Hook | Yes | Yes | Yes | Yes |
  58. | Qwen Work CN | Hook / local data polling | Yes | Yes | Yes | Yes |
  59. | Wukong | CLI API polling | Yes | Yes | Yes | Yes |
  60. | WorkBuddy | Hook wakeup + local transcript watch/poll fallback | Yes | Yes | Yes | Yes |
  61. | [Doubao Work (macOS/Windows, experimental)](docs/doubao-work.md) | Read-only logs + execution metadata | Client turns, local tools + native sandbox executions | Metadata only | No | No |
  62. GitHub Copilot CLI automatic deployment supports Unix shells. Exact per-call token usage requires native OTel; transcript-only collection omits unavailable usage. Windows and subagents are not supported. See [telemetry details](docs/zh-CN/copilot-native-telemetry.md).
  63. OpenClaw integration supports 2026.3.8 or later with automatic version detection. Before 2026.5.12, model-call timing is inferred from legacy hooks; see [compatibility details](docs/agents.md#openclaw-compatibility-and-lifecycle).
  64. DeepSeek Harness (`dsh`) loads Pilot's observability plugin from its user-level
  65. `cordis.patch.yml`. The integration captures native LLM, reasoning, tool, token,
  66. and time-to-first-token events. See [Agent Configuration](docs/agents.md#deepseek-harness-collection-and-lifecycle)
  67. for activation, source-log, disable, and uninstall behavior.
  68. ### Documented Windows Agent Support
  69. The table above describes Pilot's general integration capabilities; it does not imply that every agent is supported on every operating system. The following agents are currently explicitly documented as supported on Windows:
  70. | Agent | Windows Integration | Trace Export | Log Export | Token Usage | Conversation / Tool Calls | Requirement |
  71. |-------|---------------------|--------------|------------|-------------|---------------------------|-------------|
  72. | Claude Code | Hook | Yes | Yes | Yes | Yes | — |
  73. | Cursor | Hook | Yes | Yes | Yes | Yes | — |
  74. | Qoder Work | Hook / local data source | Yes | Yes | No | Yes | User edition |
  75. | Qoder CLI | Hook | Yes | Yes | No | Yes | — |
  76. | Qoder IDE | Hook / local data source | Yes | Yes | Yes | Yes | Qoder 1.10.0 or later, User edition |
  77. | OpenCode | Plugin injection | Yes | Yes | Yes | Yes | — |
  78. | WorkBuddy | Hook wakeup + local transcript | Yes | Yes | Yes | Yes | WorkBuddy Desktop 5.3.5.0; Windows 11 installed-product E2E |
  79. Agents omitted from this Windows table do not currently have an explicit Windows support statement; omission does not necessarily mean that the agent cannot run on Windows. See the [Alibaba Cloud AI Coding Agent access guide](https://help.aliyun.com/zh/cms/cloudmonitor-2-0/ai-application-access-ai-coding-agent/) for the source support matrix and [Installation](docs/installation.md) for Windows prerequisites and setup.
  80. Agent definitions live in `agents.d/`. You can add new agents without changing the deployment framework; see [Agent Onboarding](docs/agent-onboarding.md).
  81. ## Quick Start
  82. Prerequisites:
  83. - Node.js that can load `node:sqlite` (22.13+, 23.4+, or newer). The installer downloads a managed Node.js 22.22 runtime on supported platforms; a system Node.js is accepted only when `require('node:sqlite')` succeeds. Node.js 18/20 and 22.0–22.12 / 23.0–23.3 are not enough.
  84. - `npm`
  85. - `curl` or `wget`
  86. - PowerShell 5.1 or later on Windows
  87. Install from the public package on Linux or macOS:
  88. ```bash
  89. curl -fsSL https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/installer.sh -o /tmp/loongsuite-pilot-installer.sh && bash /tmp/loongsuite-pilot-installer.sh install
  90. ```
  91. Install from the public package on Windows:
  92. ```powershell
  93. $installer = "$env:TEMP\loongsuite-pilot-installer.ps1"
  94. Invoke-WebRequest `
  95. -Uri "https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/installer.ps1" `
  96. -OutFile $installer
  97. powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installer install
  98. ```
  99. Verify the service:
  100. ```bash
  101. loongsuite-pilot status
  102. loongsuite-pilot info
  103. ```
  104. Local JSONL output is disabled by default. To write to `~/.loongsuite-pilot/logs/output/` on Linux/macOS or `%USERPROFILE%\.loongsuite-pilot\logs\output\` on Windows, set `"jsonl": { "enabled": true }` in `config.json`.
  105. For installer options, uninstall commands, and source builds, see [Installation](docs/installation.md).
  106. ## Configure Pilot
  107. Configuration is loaded in this order: environment variables, then `~/.loongsuite-pilot/config.json`, then built-in defaults.
  108. Start with the guide that matches what you want to change:
  109. | Task | Guide |
  110. | ------------------------------------------------ | ------------------------------------------------ |
  111. | Choose agents | [Agent Configuration](docs/agents.md) |
  112. | Write local JSONL logs | [Local JSONL Output](docs/local-jsonl-output.md) |
  113. | Report logs to SLS | [SLS Output](docs/sls-output.md) |
  114. | Report OTLP traces | [Trace Output](docs/trace-output.md) |
  115. | POST events to HTTP | [HTTP Output](docs/http-output.md) |
  116. | Mask secrets before output | [Data Masking](docs/masking.md) |
  117. | See global config loading and retention settings | [Configuration Guide](docs/configuration.md) |
  118. ### Upstream Trace Linking (optional)
  119. Link collected agent spans to an **upstream** trace so each turn's span tree reparents under the upstream span. Disabled by default, and fully fail-open (never affects normal collection/reporting).
  120. | Setting | Values | Default |
  121. | ------- | ------ | ------- |
  122. | `LOONGSUITE_PILOT_UPSTREAM_LINK` (env) · `upstreamLink.enabled` (config.json) | `true` / `1` to enable; unset, `false`, or `0` to disable | disabled |
  123. | `LOONGSUITE_PILOT_UPSTREAM_LINK_PROPAGATE_TO_TOOLS` (env) · `upstreamLink.propagateToTools` (config.json) | propagate trace context and optional resource attributes to supported CLI tool calls | disabled |
  124. | `LOONGSUITE_PILOT_UPSTREAM_LINK_PROPAGATE_TO_LLM` (env) · `upstreamLink.propagateToLlm` (config.json) | forward trace context to the LLM gateway as a `traceparent` request header (Claude Code) | disabled |
  125. | `LOONGSUITE_PILOT_UPSTREAM_LINK_GENERATE_TRACE_WHEN_MISSING` (env) · `upstreamLink.generateTraceWhenMissing` (config.json) | generate and propagate a per-turn local trace context when no valid upstream context is available | disabled |
  126. | `LOONGSUITE_PILOT_UPSTREAM_LINK_TTL_MS` (env) · `upstreamLink.ttlMs` (config.json) | cleanup TTL in ms for `acp-correlate` files | `86400000` (24h) |
  127. When enabled, the upstream `traceparent` reaches Pilot via one of two schemes and is stamped onto collected records (`trace_id` on the turn, `parent_span_id` on the user-input event):
  128. - **Correlation file** (per-turn): the caller writes `{sessionId, contentHash, contentPrefix, traceparent}` to `~/.loongsuite-pilot/acp-correlate/<sessionId>.jsonl` when it sends a prompt. Linking is protocol-agnostic, but requires a supported collector/plugin that emits the turn's user-input event. `sessionId` must match the native `gen_ai.session.id` Pilot collects, and the content hash or prefix must match that input. OpenClaw and Hermes require the collector fixes in [PR #508](https://github.com/alibaba/loongsuite-pilot/pull/508); Hermes also requires updating its deployed Pilot plugin and restarting Hermes. See the [per-turn setup and deployment requirements](docs/zh-CN/upstream-trace-correlation.md). ACP clients satisfy this naturally (the `session/new` id flows into collection), so ACP is the primary case.
  129. - **Environment** (`TRACEPARENT` on the agent process): applied to the session's first turn only when a supported Pilot hook calls `recordUpstreamContextOnce` to write a session record. The OpenClaw and Hermes plugins do not read `TRACEPARENT` directly. Use this scheme with a supported hook when the caller cannot obtain a per-turn `sessionId` up front.
  130. For Claude Code, enabling both `upstreamLink.enabled` and `propagateToTools` passes context into main-agent `Bash` calls. Pilot's `PreToolUse(Bash)` hook reserves the TOOL span id, prepends `TRACEPARENT` (and valid `TRACESTATE`, when present) to the Bash command, then reuses that id when the Stop hook builds the TOOL span. Optionally enable `generateTraceWhenMissing` so turns without upstream context generate and propagate a local trace. Set `LOONGSUITE_PILOT_RESOURCE_ATTRIBUTES` on the Claude Code process to have Pilot map it to standard `OTEL_RESOURCE_ATTRIBUTES` for the downstream CLI. Prefer `config.json` for the `upstreamLink` switches: environment variables affect only processes that inherit them, and `loongsuite-pilot restart` alone does not change an already-running Claude Code hook environment. The downstream CLI must extract Trace Context and configure its own exporter. This capability is fail-open and currently does not cover ACP-only downstream trace propagation, subagents, PowerShell, MCP tools, or non-Bash tools.
  131. Enabling both `upstreamLink.enabled` and `propagateToLlm` extends the same trace to the **LLM gateway**: Claude Code's fetch preload injects a `traceparent` header on outgoing `/v1/messages` requests, passing trace-id and flags through untouched and replacing parent-id with the span id of that physical request, so gateway-side spans nest under it. A retried call emits one LLM span per attempt, and each attempt advertises its own span id, so the gateway's spans nest under the attempt that actually issued them. A `traceparent` the caller already set is never overwritten, and the whole path is fail-open.
  132. ## Output Data
  133. | Backend | Use Case |
  134. | ---------- | ----------------------------------------------------------------------- |
  135. | JSONL | Local backup and easy inspection. Disabled by default; enable explicitly. |
  136. | SLS | Alibaba Cloud Log Service reporting. Supports WebTracking, AK, and API Key modes. |
  137. | HTTP | POST batches to a custom endpoint. |
  138. | OTLP Trace | Export GenAI activity as OpenTelemetry traces. |
  139. LoongSuite Pilot emits a normalized GenAI event schema across all supported agents. See [Output Event Schema](docs/output-event-schema.md) for event names, field definitions, provider values, finish reasons, and sensitivity notes for opt-in content fields.
  140. ## Operate Pilot
  141. Use the `loongsuite-pilot` command after installation:
  142. ```bash
  143. loongsuite-pilot start
  144. loongsuite-pilot stop
  145. loongsuite-pilot restart
  146. loongsuite-pilot status
  147. loongsuite-pilot info
  148. loongsuite-pilot token-usage
  149. loongsuite-pilot rollback
  150. ```
  151. The local dashboard is disabled by default. Run `loongsuite-pilot dashboard start`
  152. to enable it on port 8765, or `loongsuite-pilot dashboard start 9999` to choose a
  153. port. Run `loongsuite-pilot dashboard stop` to disable it. These commands restart
  154. a running collector; collection remains enabled. The page reads the collector-owned
  155. `logs/metrics-summary.json` file directly.
  156. On macOS, optionally run `loongsuite-pilot dashboard shortcut install` to create a
  157. Dashboard `.webloc` shortcut with a radar icon and add it to the Dock's files area.
  158. Normal installation and upgrades do not add shortcuts. It opens the configured
  159. URL in your default browser without starting or stopping Pilot. After changing
  160. the port, run the shortcut install command again. See [Dashboard shortcut](docs/installation.md#macos-dashboard-shortcut).
  161. macOS menu bar app:
  162. To disable automatic menu bar startup during installation, append `--enable-status-bar-app false` to the install command. This persists `enableStatusBarApp` in `config.json` before the collector starts. Omit the option to preserve the existing setting, or pass `true` to enable it. See the [installation guide](docs/installation.md#start-or-stop-the-macos-menu-bar-app).
  163. On macOS, Pilot runs a menu bar app after installation by default. It shows live token, session, request, and tool counts, plus per-agent and per-provider breakdowns, so you can keep an eye on activity without opening the dashboard.
  164. If you quit the menu bar app, reopen it without restarting collection:
  165. ```bash
  166. loongsuite-pilot menubar start
  167. ```
  168. Run this in your macOS desktop terminal without `sudo`. Pilot must already be running. The command persists `"enableStatusBarApp": true` in the active `config.json`; repeated calls reuse the running app.
  169. To close only the menu bar app, run `loongsuite-pilot menubar stop`. Collection keeps running, and stopping an already closed app succeeds. The command persists `"enableStatusBarApp": false`, so the next collector startup leaves it closed.
  170. <p align="center">
  171. <img src="docs/_assets/img/menubar.jpg" alt="LoongSuite Pilot macOS menu bar app" width="360">
  172. </p>
  173. The `LOONGSUITE_PILOT_ENABLE_STATUS_BAR_APP` environment variable still has higher priority than `config.json`. Unset a disabling value before `menubar start`; an enabling value can override the setting written by `menubar stop` on future Pilot starts.
  174. ## Documentation
  175. [User Manual](docs/README.md) - Complete guide to installing, configuring, operating, and extending Pilot
  176. [Installation Guide](docs/installation.md) - Install from package, verify service, uninstall, and run from source
  177. [Configuration Reference](docs/configuration.md) - Global config loading, runtime switches, retention, and links to output and privacy setup
  178. [Output Schema](docs/output-event-schema.md) - Normalized event names, fields, provider values, and finish reasons
  179. [Developer Guide](docs/agent-onboarding.md) - Add support for a new AI coding agent
  180. ## Development
  181. ```bash
  182. git clone https://github.com/alibaba/loongsuite-pilot.git
  183. cd loongsuite-pilot
  184. npm install
  185. npm run build
  186. node scripts/postinstall.js
  187. node dist/index.js
  188. ```
  189. For local development:
  190. ```bash
  191. npm install
  192. npm run build
  193. npm run typecheck
  194. npm test
  195. ```
  196. For packaging and service installation from a local build, see [Installation](docs/installation.md).
  197. ## Contributing
  198. Issues and pull requests are welcome. Before submitting a change, run the same core checks used by CI:
  199. ```bash
  200. npm ci
  201. npm run typecheck
  202. npm test
  203. npm run build
  204. ```
  205. To add support for another AI coding agent, start with the [Agent Onboarding Guide](docs/agent-onboarding.md). Report bugs and propose features through [GitHub Issues](https://github.com/alibaba/loongsuite-pilot/issues).
  206. ## Community
  207. We are looking forward to your feedback and suggestions. Scan the QR code below to join the LoongSuite Pilot DingTalk group.
  208. | LoongSuite Pilot SIG |
  209. |----|
  210. | <img src="docs/_assets/img/loongsuite-pilot-sig-dingtalk.jpg" height="150"> |
  211. ## LoongSuite Ecosystem
  212. | Project | Role |
  213. | ------- | ---- |
  214. | [LoongCollector](https://github.com/alibaba/loongcollector) | High-performance collector for logs, metrics, traces, events, and profiles. |
  215. | [LoongSuite Java](https://github.com/alibaba/loongsuite-java) | Shared GenAI telemetry utilities for Java instrumentation. |
  216. | [LoongSuite Go](https://github.com/alibaba/loongsuite-go) | Compile-time auto-instrumentation for Go applications. |
  217. | [LoongSuite Python](https://github.com/alibaba/loongsuite-python) | OpenTelemetry auto-instrumentation for Python and GenAI applications. |
  218. | [LoongSuite JS](https://github.com/alibaba/loongsuite-js) | OpenTelemetry integrations for JavaScript AI agents. |
  219. | [LoongSuite Pilot](https://github.com/alibaba/loongsuite-pilot) | Local telemetry collector for AI coding agents. |
  220. ## License
  221. Apache License 2.0 - see [LICENSE](LICENSE) for details.
deploy/installer-opensource.ps1 · Bundled script · 3,756 lines · 2 findings marked
  1. # installer-opensource.ps1 — Open-source installer for loongsuite-pilot (Windows)
  2. #
  3. # Install (first time):
  4. # irm https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/installer.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 4 on GitHub
  5. # .\installer-opensource.ps1 install `
  6. # -SlsEndpoint "https://cn-hangzhou.log.aliyuncs.com" `
  7. # -SlsProject "my-project" `
  8. # -SlsLogstore "my-logstore" `
  9. # -SlsAkId "your-ak-id" `
  10. # -SlsAkSecret "your-ak-secret"
  11. # .\installer-opensource.ps1 install `
  12. # -SlsEndpoint "https://cn-hangzhou.log.aliyuncs.com" `
  13. # -SlsProject "my-project" `
  14. # -SlsLogstore "my-logstore" `
  15. # -SlsApiKey "your-api-key" `
  16. # -MultimodalMode all
  17. #
  18. # Install a specific version:
  19. # .\installer-opensource.ps1 install -Version 1.2.0
  20. #
  21. # Optional Dashboard port (default: 8765; preserve existing port on reinstall):
  22. # .\installer-opensource.ps1 install -DashboardPort 9000
  23. #
  24. # Upgrade (preserve config, auto-rollback on failure):
  25. # .\installer-opensource.ps1 upgrade
  26. #
  27. # Uninstall:
  28. # .\installer-opensource.ps1 uninstall
  29. # .\installer-opensource.ps1 uninstall -Purge
  30. [CmdletBinding()]
  31. param(
  32. [Parameter(Position = 0)]
  33. [ValidateSet("install", "upgrade", "uninstall")]
  34. [string]$Command = "install",
  35. [string]$SlsEndpoint,
  36. [string]$SlsProject,
  37. [string]$SlsLogstore,
  38. [string]$SlsAkId,
  39. [string]$SlsAkSecret,
  40. [string]$SlsApiKey,
  41. [string]$PackageUrl,
  42. [string]$DataDir,
  43. [string]$DashboardPort,
  44. [string]$LogLevel,
  45. [Alias("user.id")]
  46. [string]$UserId,
  47. [string]$Lang,
  48. [string]$Version,
  49. [string[]]$ExcludeWorkspace,
  50. [string]$CollectLog,
  51. [string]$CollectTrace,
  52. [ValidateSet("true", "false")]
  53. [string]$EnableStatusBarApp,
  54. [string]$CmsLicenseKey,
  55. [string]$CmsEndpoint,
  56. [string]$CmsWorkspace,
  57. [string]$ServiceNamePrefix,
  58. [string]$Agents,
  59. [switch]$AllAgents,
  60. [AllowEmptyString()]
  61. [string]$MultimodalMode,
  62. [string]$MaskMode,
  63. [string]$MaskTypes,
  64. [string]$MaskReplacementMode,
  65. [string]$InterceptorMode,
  66. [string]$InterceptorTypes,
  67. [switch]$Purge,
  68. [switch]$PreferSystemNode
  69. )
  70. $ErrorActionPreference = "Stop"
  71. foreach ($excludedWorkspace in $ExcludeWorkspace) {
  72. if ($excludedWorkspace -notmatch '^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+)') {
  73. throw "-ExcludeWorkspace requires absolute local directories"
  74. }
  75. }
  76. # Wrap in try/catch: setting a static property on [Console] throws under Constrained
  77. # Language Mode (WDAC), and with $ErrorActionPreference=Stop that would abort the whole
  78. # script at load. Console encoding is cosmetic, so degrade silently.
  79. try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}
  80. # ============================================================
  81. # Constants
  82. # ============================================================
  83. $PACKAGE_NAME = "loongsuite-pilot"
  84. $DEFAULT_PILOT_DIR = Join-Path $env:USERPROFILE ".loongsuite-pilot"
  85. $CACHE_DIR = if ($env:LOONGSUITE_PILOT_CACHE_DIR) {
  86. $env:LOONGSUITE_PILOT_CACHE_DIR
  87. } else {
  88. $DEFAULT_PILOT_DIR
  89. }
  90. $PERMANENT_DIR = Join-Path $CACHE_DIR "package"
  91. $_OSS_BASE_URL = "https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot"
  92. # Managed Node.js runtime + prebuilt node_modules (downloaded from OSS at install time)
  93. if ($env:LOONGSUITE_PILOT_NODE_VERSION) { $script:NODE_VERSION = $env:LOONGSUITE_PILOT_NODE_VERSION } else { $script:NODE_VERSION = "22.22.2" }
  94. if ($env:LOONGSUITE_PILOT_NODE_DEPS_URL) { $script:NODE_DEPS_BASE = $env:LOONGSUITE_PILOT_NODE_DEPS_URL } else { $script:NODE_DEPS_BASE = "https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node" }
  95. if ($env:LOONGSUITE_PILOT_NODE_MODULES_URL) { $script:NODE_MODULES_BASE = $env:LOONGSUITE_PILOT_NODE_MODULES_URL } else { $script:NODE_MODULES_BASE = "https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node-modules" }
  96. # ============================================================
  97. # Defaults
  98. # ============================================================
  99. if (-not $DataDir) {
  100. $DataDir = if ($env:LOONGSUITE_PILOT_DATA_DIR) {
  101. $env:LOONGSUITE_PILOT_DATA_DIR
  102. } else {
  103. $DEFAULT_PILOT_DIR
  104. }
  105. }
  106. $env:LOONGSUITE_PILOT_DATA_DIR = $DataDir
  107. $env:LOONGSUITE_PILOT_CACHE_DIR = $CACHE_DIR
  108. $env:AGENT_DATA_COLLECTION_CONFIG = Join-Path $DataDir "config.json"
  109. if (-not $PackageUrl -and $env:LOONGSUITE_PILOT_PACKAGE_URL) {
  110. $PackageUrl = $env:LOONGSUITE_PILOT_PACKAGE_URL
  111. }
  112. # ============================================================
  113. # Validate install options
  114. # ============================================================
  115. if ($PSBoundParameters.Keys -contains 'EnableStatusBarApp' -and $Command -ne 'install') {
  116. Write-Error "-EnableStatusBarApp is only supported with install"
  117. exit 1
  118. }
  119. if ($PSBoundParameters.Keys -contains 'DashboardPort') {
  120. if ($DashboardPort -notmatch '\A[0-9]{1,5}\z' -or [int]$DashboardPort -lt 1 -or [int]$DashboardPort -gt 65535) {
  121. Write-Error "-DashboardPort must be an integer between 1 and 65535"
  122. exit 1
  123. }
  124. }
  125. if ($MaskMode) {
  126. if ($MaskMode -notin @("all", "none", "custom")) {
  127. Write-Error "Unknown mask mode: $MaskMode (use 'all', 'custom', or 'none')"
  128. exit 1
  129. }
  130. }
  131. if ($MaskMode -eq "custom" -and -not $MaskTypes) {
  132. Write-Error "--MaskTypes is required when -MaskMode custom"
  133. exit 1
  134. }
  135. if ($MaskTypes -and $MaskMode -ne "custom") {
  136. Write-Error "-MaskTypes can only be used with -MaskMode custom"
  137. exit 1
  138. }
  139. if ($MaskReplacementMode -and $MaskReplacementMode -notin @("placeholder", "preview")) {
  140. Write-Error "Unknown mask replacement mode: $MaskReplacementMode (use 'placeholder' or 'preview')"
  141. exit 1
  142. }
  143. if ($InterceptorMode) {
  144. if ($InterceptorMode -notin @("all", "none", "custom")) {
  145. Write-Error "Unknown interceptor mode: $InterceptorMode (use 'all', 'custom', or 'none')"
  146. exit 1
  147. }
  148. }
  149. if ($InterceptorMode -eq "custom" -and -not $InterceptorTypes) {
  150. Write-Error "--InterceptorTypes is required when -InterceptorMode custom"
  151. exit 1
  152. }
  153. if ($InterceptorTypes -and $InterceptorMode -ne "custom") {
  154. Write-Error "-InterceptorTypes can only be used with -InterceptorMode custom"
  155. exit 1
  156. }
  157. if ($SlsApiKey -and ($SlsAkId -or $SlsAkSecret)) {
  158. Write-Error "-SlsApiKey cannot be used with -SlsAkId or -SlsAkSecret"
  159. exit 1
  160. }
  161. if ($PSBoundParameters.Keys -contains 'MultimodalMode' -and -not $MultimodalMode) {
  162. Write-Error "-MultimodalMode requires 'none', 'input', 'output', or 'all'"
  163. exit 1
  164. }
  165. $script:MultimodalMode = $MultimodalMode
  166. # Keep in sync with MULTIMODAL_SUPPORTED_AGENT_IDS.
  167. $script:MultimodalSupportedAgents = "codex,qoder"
  168. if ($MultimodalMode) {
  169. if ($MultimodalMode -notin @("none", "input", "output", "all")) {
  170. Write-Error "Unknown multimodal mode: $MultimodalMode (use 'none', 'input', 'output', or 'all')"
  171. exit 1
  172. }
  173. }
  174. if ($MultimodalMode -and $Command -ne "install") {
  175. Write-Error "-MultimodalMode is only supported with install (got $Command)"
  176. exit 1
  177. }
  178. if ($MultimodalMode -and $MultimodalMode -ne "none") {
  179. if ($SlsEndpoint -notmatch '\S' -or $SlsProject -notmatch '\S' -or $SlsLogstore -notmatch '\S' -or $SlsApiKey -notmatch '\S') {
  180. Write-Error "-MultimodalMode $MultimodalMode requires -SlsEndpoint, -SlsProject, -SlsLogstore, and -SlsApiKey"
  181. exit 1
  182. }
  183. }
  184. # ============================================================
  185. # Resolve package URL
  186. # ============================================================
  187. if (-not $PackageUrl) {
  188. if ($Version) {
  189. $PackageUrl = "$_OSS_BASE_URL/$Version/$PACKAGE_NAME.zip"
  190. } else {
  191. $PackageUrl = "$_OSS_BASE_URL/latest/$PACKAGE_NAME.zip"
  192. }
  193. }
  194. # ============================================================
  195. # Language detection
  196. # ============================================================
  197. function Detect-Lang {
  198. if ($Lang) { return $Lang }
  199. if ($env:LOONGSUITE_PILOT_LANG) { return $env:LOONGSUITE_PILOT_LANG }
  200. # $PSUICulture is an automatic variable (no .NET static call), so it works under
  201. # Constrained Language Mode where [CultureInfo]::CurrentUICulture would throw.
  202. if ($PSUICulture -match "zh") { return "zh" }
  203. return "en"
  204. }
  205. $LANG_MODE = Detect-Lang
  206. function Msg {
  207. param([string]$zh, [string]$en)
  208. if ($LANG_MODE -eq "zh") { Write-Host $zh } else { Write-Host $en }
  209. }
  210. function Test-CanPrompt {
  211. # Each .NET call below throws under Constrained Language Mode (WDAC); guard every one
  212. # and default to non-interactive (the safe degrade — irm|iex installs are non-interactive).
  213. try {
  214. $processArgs = [Environment]::GetCommandLineArgs()
  215. if ($processArgs -contains "-NonInteractive") { return $false }
  216. } catch {}
  217. try {
  218. if ([Console]::IsInputRedirected) { return $false }
  219. } catch {}
  220. try {
  221. return [Environment]::UserInteractive -and $null -ne $Host.UI.RawUI
  222. } catch { return $false }
  223. }
  224. # ============================================================
  225. # Node.js resolution
  226. # ============================================================
  227. # node:sqlite is unflagged from 22.13 and 23.4. A major check accepts Node 20
  228. # and 22.12, whose require('node:sqlite') throws, so install succeeds and
  229. # SQLite collection does not. The require is the check.
  230. # Native stderr under EAP=Stop becomes a terminating error and hides $LASTEXITCODE.
  231. function Test-NodeSupportsSqlite {
  232. param([string]$bin)
  233. if (-not $bin -or -not (Test-Path -LiteralPath $bin)) { return $false }
  234. $prevEAP = $ErrorActionPreference
  235. $ErrorActionPreference = "Continue"
  236. $code = 1
  237. try {
  238. $sqliteProbe = & $bin -e "require('node:sqlite')" 2>&1
  239. $code = $LASTEXITCODE
  240. if ($null -eq $code) { $code = 1 }
  241. } catch {
  242. $code = 1
  243. } finally {
  244. $ErrorActionPreference = $prevEAP
  245. }
  246. return ($code -eq 0)
  247. }
  248. function Test-NodeSuitable {
  249. param([string]$bin)
  250. return (Test-NodeSupportsSqlite $bin)
  251. }
  252. function Resolve-Node {
  253. $candidates = @()
  254. # Existing installations pin the exact Node binary used for deployment.
  255. #
  256. # The pin file holds one absolute path to node.exe, and for a managed runtime that
  257. # path sits under the data dir -- i.e. under %USERPROFILE%, which can be non-ASCII.
  258. # 5.1 defaults both Get-Content and Set-Content to the ANSI codepage, so an
  259. # unqualified write stored "C:\Users\??.HOST\..." and every reader then failed
  260. # Test-NodeSuitable and silently fell back to whatever node.exe the candidate search
  261. # found first -- on a shared machine that was another account's nvm install.
  262. # -Encoding UTF8 always emits a BOM on 5.1 (there is no utf8NoBOM), and U+FEFF is not
  263. # whitespace, so .Trim() alone leaves it in the path: strip it explicitly first.
  264. foreach ($pinFile in @(
  265. (Join-Path $DataDir "node-bin"),
  266. (Join-Path $CACHE_DIR "node-bin")
  267. )) {
  268. if (-not (Test-Path -LiteralPath $pinFile)) { continue }
  269. $pinned = ([string](Get-Content -LiteralPath $pinFile -Raw -Encoding UTF8 -ErrorAction SilentlyContinue)).Trim([char]0xFEFF).Trim()
  270. if ($pinned) { $candidates += $pinned }
  271. }
  272. # nvm-windows. Both probes below must be non-fatal. NVM_HOME is often a *machine*
  273. # level variable pointing into another account's profile
  274. # (C:\Users\Administrator\AppData\Local\nvm was measured), and that directory's DACL
  275. # grants nothing to the current user: a bare Test-Path raises a PermissionDenied
  276. # UnauthorizedAccessException record, which the file header's
  277. # $ErrorActionPreference = "Stop" promotes to a terminating error. Resolve-Node is
  278. # called from uninstall before any cleanup runs, so one unreadable third-party node
  279. # manager aborted the entire uninstall and left config.json -- credentials included --
  280. # on disk even with -Purge. The Get-ChildItem calls were already guarded; these two
  281. # were not. -LiteralPath as well, because a version manager path may contain [ or ].
  282. $nvmHome = $env:NVM_HOME
  283. if ($nvmHome -and (Test-Path -LiteralPath $nvmHome -ErrorAction SilentlyContinue)) {
  284. $nvmDirs = Get-ChildItem $nvmHome -Directory -ErrorAction SilentlyContinue |
  285. Sort-Object Name -Descending
  286. foreach ($d in $nvmDirs) {
  287. $candidates += Join-Path $d.FullName "node.exe"
  288. }
  289. }
  290. # fnm -- same unreadable-directory hazard as the nvm branch above.
  291. $fnmDir = Join-Path $env:USERPROFILE ".fnm\node-versions"
  292. if (Test-Path -LiteralPath $fnmDir -ErrorAction SilentlyContinue) {
  293. $fnmDirs = Get-ChildItem $fnmDir -Directory -ErrorAction SilentlyContinue |
  294. Sort-Object Name -Descending
  295. foreach ($d in $fnmDirs) {
  296. $candidates += Join-Path $d.FullName "installation\node.exe"
  297. }
  298. }
  299. # Volta
  300. $voltaNode = Join-Path $env:USERPROFILE ".volta\bin\node.exe"
  301. $candidates += $voltaNode
  302. # Common install paths
  303. $candidates += "C:\Program Files\nodejs\node.exe"
  304. $candidates += "C:\Program Files (x86)\nodejs\node.exe"
  305. # PATH lookup
  306. $pathNode = Get-Command node -ErrorAction SilentlyContinue
  307. if ($pathNode) { $candidates += $pathNode.Source }
  308. foreach ($c in $candidates) {
  309. if (Test-NodeSuitable $c) {
  310. return $c
  311. }
  312. }
  313. return $null
  314. }
  315. # >>> managed-node-runtime >>>
  316. # Managed Node.js runtime + prebuilt node_modules, downloaded from OSS.
  317. function Get-ManagedNodePlatform {
  318. $archRaw = $env:PROCESSOR_ARCHITEW6432
  319. if (-not $archRaw) { $archRaw = $env:PROCESSOR_ARCHITECTURE }
  320. switch ($archRaw) {
  321. "AMD64" { return [pscustomobject]@{ Os = "win"; Arch = "x64" } }
  322. "ARM64" {
  323. Msg " ⚠️ 托管 Node.js 无 win-arm64 产物,回退系统 node + npm install" `
  324. " ⚠️ No win-arm64 managed Node.js artifact, falling back to system node + npm install"
  325. return $null
  326. }
  327. default {
  328. Msg " ⚠️ 托管 Node.js 不支持架构 $archRaw,回退系统 node + npm install" `
  329. " ⚠️ Managed Node.js does not support arch $archRaw, falling back to system node + npm install"
  330. return $null
  331. }
  332. }
  333. }
  334. # >>> pilot-short-path >>>
  335. # 8.3 short paths: why every delete and move below goes through a helper.
  336. #
  337. # Windows hands out %TEMP% in 8.3 short form whenever the profile name does not fit 8.3,
  338. # which a dot in an account name is often enough to do: C:\Users\zhang.wang becomes
  339. # C:\Users\ZHANG~1.WAN, the four characters after the dot being one too many for an 8.3
  340. # extension. %USERPROFILE% stays long, so a single install sees both forms. Reading such a
  341. # path works everywhere (Test-Path, Get-Item, Get-ChildItem, Get-Content, Set-Content,
  342. # Add-Content, New-Item, Out-File and Copy-Item all resolve it, and so does a Move-Item
  343. # destination), but Remove-Item, Move-Item, Rename-Item, Set-Location and Push-Location
  344. # fail with
  345. #
  346. # An object at the specified path C:\Users\ZHANG~1.WAN does not exist.
  347. #
  348. # naming the prefix their walk broke on rather than the path that was passed in.
  349. #
  350. # It is one guard in FileSystemProvider.NormalizeThePath, which is what the .NET stack
  351. # trace on the PSArgumentException names. That walk accumulates currentPath in the form you
  352. # typed it and, for each segment, compares the resolved item against it:
  353. #
  354. # if (fsinfo.FullName.Length < currentPath.Length)
  355. # throw NewArgumentException("path", ItemDoesNotExist, currentPath);
  356. # if (fsinfo.Name.Length >= childName.Length)
  357. # childName = fsinfo.Name; // "Expand the short file name"
  358. #
  359. # The guard is aimed at a child name of two or more dots, which .NET resolves to the parent
  360. # and so hands back shorter. An 8.3 name longer than the name it stands for is the other way
  361. # to make resolved shorter than typed, and the guard cannot tell the two apart -- note that
  362. # the very next line expands a short name only when doing so would not shorten it.
  363. #
  364. # So the trigger is not "a segment is in 8.3 form". Measured on 5.1.26100 over 13 profile
  365. # names and 7 nesting cases, it is a length comparison on every prefix:
  366. #
  367. # zhang.wang -> ZHANG~1.WAN 11 > 10 throws
  368. # abcd.wang -> ABCD~1.WAN 10 > 9 throws
  369. # ab.wang -> ABxxxx~1.WAN 12 > 7 throws (<=2 chars of base get a hash)
  370. # wang.zhang -> WANG~1.ZHA 10 = 10 works
  371. # zhangsan.wang -> ZHANGS~1.WAN 12 < 13 works
  372. # zhang.san -> no short name at all works
  373. #
  374. # It takes a short base with an over-long extension, which is why it looks rare in the
  375. # field. Depth is not irrelevant either: the first prefix whose typed length exceeds its
  376. # resolved length is the one that throws, so an earlier segment resolving much longer masks
  377. # a later offender (VERYLO~1\ZHANG~1.WAN is fine) while those same two segments in the other
  378. # order still throw (ZHANG~1.WAN\VERYLO~1 breaks on the first one). -LiteralPath behaves
  379. # identically to -Path, so quoting is not the fix, and neither is Convert-Path or
  380. # Resolve-Path -- both hand the short form straight back. Get-Item .FullName expands it.
  381. function Get-PilotLongPath {
  382. param([string]$Path)
  383. if (-not $Path) { return $Path }
  384. try {
  385. $item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
  386. if ($item.FullName) { return $item.FullName }
  387. } catch {
  388. # Not there, or not there yet -- a Move-Item destination is the common case. Only
  389. # an existing directory can carry a short name, so expanding the parent is enough.
  390. try {
  391. $parent = Split-Path -Parent $Path
  392. $leaf = Split-Path -Leaf $Path
  393. if ($parent -and $leaf) {
  394. $parentItem = Get-Item -LiteralPath $parent -Force -ErrorAction Stop
  395. if ($parentItem.FullName) { return (Join-Path $parentItem.FullName $leaf) }
  396. }
  397. } catch {}
  398. }
  399. return $Path
  400. }
  401. # Best-effort delete, for cleanup only. Every caller is a catch or a finally, where an
  402. # exception is not merely unhelpful but destructive, so this has to be incapable of
  403. # raising one: -ErrorAction SilentlyContinue covers the ordinary non-terminating half (a
  404. # file a virus scanner still holds open) and the catch covers everything else, the
  405. # binding failure above included. Deliberately returns nothing -- a caller that needs to
  406. # know whether the path is gone asks Test-Path.
  407. function Remove-PilotPathQuietly {
  408. param([string]$Path)
  409. if (-not $Path) { return }
  410. try {
  411. Remove-Item -LiteralPath (Get-PilotLongPath $Path) -Recurse -Force -ErrorAction SilentlyContinue
  412. } catch {}
  413. }
  414. # <<< pilot-short-path <<<
  415. # >>> pilot-ascii-temp >>>
  416. # Temp root guaranteed to be ASCII, for the two tar.exe staging dirs only.
  417. #
  418. # PowerShell hands native command arguments to CreateProcessW as UTF-16, but bsdtar
  419. # (%SystemRoot%\System32\tar.exe) enters through the ANSI CRT and converts them back
  420. # through the machine's ANSI codepage, so on an en-US box every character that page
  421. # cannot represent reaches tar as a literal "?": with $env:TEMP under a non-ASCII
  422. # %USERPROFILE% (e.g. C:\Users\<CJK name>\AppData\Local\Temp) both -f and -C pointed at
  423. # paths that do not exist and extraction failed with "Failed to open ...", which is what
  424. # stalled the install right after the download. Measured on that box: neither
  425. # [Console]::OutputEncoding = UTF8 nor `chcp 65001` changes it (they affect stdio
  426. # decoding, not argv conversion), and the 8.3 short name works but only where 8dot3
  427. # creation is still enabled, so it cannot be relied on.
  428. #
  429. # Callers keep the archive and the extraction dir inside this root and only then
  430. # Move-Item the result into the real (possibly non-ASCII) destination -- Move-Item is
  431. # pure Win32 and Unicode-safe. This root can be machine-wide (%SystemRoot%\Temp), so it
  432. # is for downloaded archives only: never stage credentials or config here, use $DataDir.
  433. #
  434. # The base resolution repeats Get-PilotTempRoot's fallback chain instead of calling it,
  435. # so this block stays byte-identical across the installers -- installer-opensource.ps1
  436. # has no Get-PilotTempRoot. Keep the two chains in sync. Environment variables only:
  437. # [System.IO.Path]::GetTempPath() is a static call on an off-list type and throws under
  438. # ConstrainedLanguage (WDAC / Device Guard).
  439. $script:PILOT_ASCII_TEMP_ROOT = ""
  440. function Get-PilotAsciiTempRoot {
  441. if ($script:PILOT_ASCII_TEMP_ROOT) { return $script:PILOT_ASCII_TEMP_ROOT }
  442. $root = "C:\Windows\Temp"
  443. if ($env:TEMP) { $root = $env:TEMP }
  444. elseif ($env:TMP) { $root = $env:TMP }
  445. elseif ($env:SystemRoot) { $root = (Join-Path $env:SystemRoot "Temp") }
  446. # 8.3 TEMP (ZHANG~1.WAN) is ASCII, so a charset check on $root used to
  447. # return it as-is and skip the long-name expand that Remove-Item /
  448. # Move-Item need. Expanding is still required -- but only keep the
  449. # expanded form when it is still ASCII. A CJK profile (short base +
  450. # over-long extension) hands out an ASCII 8.3 TEMP that Get-PilotLongPath
  451. # turns back into the long CJK path; tar.exe then fails with
  452. # "Failed to open 'C:\Users\??.HOST\...'". In that case keep $root as
  453. # the 8.3 form, try the machine-wide ASCII candidates below, and if
  454. # none of those are writable return the 8.3 so tar still has a path
  455. # it can open. Remove-Item / Move-Item callers wrap Get-PilotLongPath
  456. # themselves.
  457. $expanded = Get-PilotLongPath $root
  458. if ($expanded -notmatch '[^\x20-\x7E]') {
  459. $script:PILOT_ASCII_TEMP_ROOT = $expanded
  460. return $expanded
  461. }
  462. $candidates = @()
  463. if ($env:SystemRoot) { $candidates += (Join-Path $env:SystemRoot "Temp") }
  464. if ($env:SystemDrive) { $candidates += ($env:SystemDrive + "\loongsuite-pilot-tmp") }
  465. $candidates += "C:\Windows\Temp"
  466. foreach ($candidate in $candidates) {
  467. if ($candidate -match '[^\x20-\x7E]') { continue }
  468. # Probe by writing: %SystemRoot%\Temp grants Users write by default, but a
  469. # hardened host may not, and Test-Path cannot tell us that.
  470. try {
  471. if (-not (Test-Path -LiteralPath $candidate)) {
  472. New-Item -ItemType Directory -Path $candidate -Force -ErrorAction Stop | Out-Null
  473. }
  474. $probe = Join-Path $candidate ("pilot-w-" + $PID + ".tmp")
  475. Set-Content -LiteralPath $probe -Value "1" -ErrorAction Stop
  476. Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
  477. $script:PILOT_ASCII_TEMP_ROOT = $candidate
  478. return $candidate
  479. } catch {}
  480. }
  481. # Nothing writable: prefer the original ASCII 8.3 over the expanded CJK
  482. # long name. If $root itself is already CJK there is no ASCII option
  483. # left; return $expanded (same as $root) rather than failing here.
  484. if ($root -notmatch '[^\x20-\x7E]') {
  485. $script:PILOT_ASCII_TEMP_ROOT = $root
  486. return $root
  487. }
  488. $script:PILOT_ASCII_TEMP_ROOT = $expanded
  489. return $expanded
  490. }
  491. # Re-inherit the destination's ACL on a tree that was Move-Item'd out of the ASCII root.
  492. #
  493. # Move-Item is a rename, and a rename carries the source's ACEs along unchanged --
  494. # they keep their "inherited" flag but now describe a parent that no longer supplies
  495. # them, so the tree does not pick up the ACL of its new parent. Everything staged in
  496. # %SystemRoot%\Temp therefore lands in the profile with %SystemRoot%\Temp's permissions:
  497. # Users get (S,WD,AD,X), which is write and traverse but *not read*, and the read grant
  498. # comes from CREATOR OWNER. Run elevated -- an admin account, or "Run as administrator"
  499. # -- the owner of a new file is BUILTIN\Administrators, so CREATOR OWNER resolves to
  500. # Administrators and the moved tree ends up with no ACE for the user at all (measured:
  501. # node_modules\pino\package.json had exactly Administrators:(I)(F) and SYSTEM:(I)(F)).
  502. # The install then looks fine and the collector still cannot start, because the
  503. # scheduled task runs with a filtered token where Administrators is deny-only: node
  504. # cannot read the package.json it found and reports the confusing
  505. # ERR_MODULE_NOT_FOUND: Cannot find package 'pino' imported from ...\dist\index.js
  506. # in logs\last-startup-crash.json, while the same tree reads fine from an elevated
  507. # shell -- which is where anyone reproducing it by hand would look first.
  508. #
  509. # Copy-Item is not affected: a copy creates new files, which do inherit normally. Only
  510. # the Move-Item paths out of Get-PilotAsciiTempRoot need this.
  511. #
  512. # icacls, unlike tar.exe, handles a non-ASCII path correctly (verified against a CJK
  513. # profile: "Successfully processed 31950 files"), so the destination goes straight
  514. # through. Get-Acl / Set-Acl cannot express this: re-enabling inheritance needs
  515. # $acl.SetAccessRuleProtection(), a method call on an off-list type that CLM blocks.
  516. function Reset-PilotInheritedAcl {
  517. param([string]$Path)
  518. $script:PILOT_LAST_ACL_ERR = ""
  519. if (-not $Path -or -not (Test-Path -LiteralPath $Path)) {
  520. $script:PILOT_LAST_ACL_ERR = "path not found: $Path"
  521. return $false
  522. }
  523. # /T all descendants, /C keep going past a single failure, /Q stay quiet. Native
  524. # commands do not throw on a nonzero exit, so $LASTEXITCODE is the signal; the try
  525. # only covers icacls failing to launch, which $ErrorActionPreference = "Stop" would
  526. # otherwise turn into a terminating error.
  527. try {
  528. $aclOut = & icacls $Path /reset /T /C /Q 2>&1
  529. if ($LASTEXITCODE -eq 0) { return $true }
  530. $script:PILOT_LAST_ACL_ERR = "icacls (exit $LASTEXITCODE): $(($aclOut | Out-String).Trim())"
  531. return $false
  532. } catch {
  533. $script:PILOT_LAST_ACL_ERR = "icacls failed to run: $($_.Exception.Message)"
  534. return $false
  535. }
  536. }
  537. # <<< pilot-ascii-temp <<<
  538. # Extract a .tar.gz into $DestDir. Returns $true on success; on failure the last
  539. # error text is left in $script:PILOT_LAST_TAR_ERR for the caller to surface.
  540. #
  541. # Never invoke a bare `tar` on Windows. On a machine with Git for Windows
  542. # installed, PATH normally resolves `tar` to Git's bundled GNU tar (MSYS), and GNU
  543. # tar reads the colon in `-f C:\...\archive.tar.gz` as rsh host:path syntax: it
  544. # treats "C" as a remote host and dies with "Cannot connect to C: resolve failed"
  545. # (older builds hang instead). Windows' own bsdtar
  546. # (%SystemRoot%\System32\tar.exe, Win10 1803+ / Server 2019+) parses drive-letter
  547. # paths correctly, so try it first and only then fall back to PATH's tar with
  548. # --force-local, which is what makes GNU tar read the colon as part of a local
  549. # filename. Do not pass --force-local to bsdtar: it rejects the unknown flag and
  550. # exits immediately, which is why it is attached to the PATH candidate only.
  551. function Expand-PilotTarGz {
  552. param([string]$ArchivePath, [string]$DestDir)
  553. $script:PILOT_LAST_TAR_ERR = ""
  554. $exes = @()
  555. if ($env:SystemRoot) {
  556. # Inside a 32-bit PowerShell on 64-bit Windows, System32 is redirected to
  557. # SysWOW64, which ships no tar.exe; Sysnative reaches the real System32.
  558. foreach ($dir in @("System32", "Sysnative")) {
  559. $candidate = Join-Path $env:SystemRoot "$dir\tar.exe"
  560. if (Test-Path $candidate) { $exes += $candidate }
  561. }
  562. }
  563. # Everything from this index on is an unknown tar and needs --force-local.
  564. $nativeCount = $exes.Count
  565. # Require .Source: a `tar` that resolves to an alias or function has none, and
  566. # only an external binary can be invoked with an argument array. -notcontains
  567. # compares strings case-insensitively, so a PATH hit that is already the
  568. # System32 binary under different casing is not retried.
  569. $pathTar = Get-Command tar -ErrorAction SilentlyContinue
  570. if ($pathTar -and $pathTar.Source -and ($exes -notcontains $pathTar.Source)) {
  571. $exes += $pathTar.Source
  572. }
  573. if ($exes.Count -eq 0) {
  574. $script:PILOT_LAST_TAR_ERR = "tar not found (looked in %SystemRoot%\System32, Sysnative and PATH)"
  575. return $false
  576. }
  577. for ($i = 0; $i -lt $exes.Count; $i++) {
  578. $exe = $exes[$i]
  579. $tarArgs = @('-xzf', $ArchivePath, '-C', $DestDir)
  580. if ($i -ge $nativeCount) { $tarArgs = @('--force-local') + $tarArgs }
  581. # Naming the binary is the whole diagnostic: "Cannot connect to C: resolve
  582. # failed" only makes sense once you can see it came from Git's tar. Msg wraps
  583. # Write-Host, so this never lands in the return value.
  584. Msg " tar: $exe" " tar: $exe"
  585. # Native commands do not throw on a nonzero exit, so $LASTEXITCODE is the
  586. # only signal; the try only covers a binary that fails to launch at all,
  587. # which $ErrorActionPreference = "Stop" would otherwise make terminating.
  588. try {
  589. $tarOut = & $exe @tarArgs 2>&1
  590. if ($LASTEXITCODE -eq 0) { return $true }
  591. $script:PILOT_LAST_TAR_ERR = "$exe (exit $LASTEXITCODE): $(($tarOut | Out-String).Trim())"
  592. } catch {
  593. $script:PILOT_LAST_TAR_ERR = "$exe : $_"
  594. }
  595. Msg " ⚠️ tar 解包失败: $($script:PILOT_LAST_TAR_ERR)" `
  596. " ⚠️ tar failed: $($script:PILOT_LAST_TAR_ERR)"
  597. }
  598. return $false
  599. }
  600. function Invoke-ManagedNodeDownload {
  601. param([string]$Url, [string]$Dest)
  602. try {
  603. $prevProgress = $ProgressPreference
  604. $ProgressPreference = "SilentlyContinue"
  605. Invoke-WebRequest -Uri $Url -OutFile $Dest -UseBasicParsing -TimeoutSec 600
  606. $ProgressPreference = $prevProgress
  607. return $true
  608. } catch {
  609. return $false
  610. }
  611. }
  612. function Test-ManagedNodeChecksum {
  613. param([string]$Archive, [string]$ShasumsFile, [string]$Name)
  614. try {
  615. $expected = $null
  616. foreach ($line in (Get-Content $ShasumsFile)) {
  617. if ($line -match ("^([0-9a-fA-F]{64})\s+\*?" + [regex]::Escape($Name) + "\s*$")) {
  618. $expected = $Matches[1].ToLower()
  619. break
  620. }
  621. }
  622. if (-not $expected) {
  623. Msg " ❌ SHASUMS256.txt 中缺少 $Name 的校验和" " ❌ SHASUMS256.txt has no entry for $Name"
  624. return $false
  625. }
  626. $actual = (Get-FileHash -Algorithm SHA256 -Path $Archive).Hash.ToLower()
  627. if ($actual -ne $expected) {
  628. Msg " ❌ $Name sha256 校验失败 (expected $expected, got $actual)" " ❌ sha256 mismatch for $Name (expected $expected, got $actual)"
  629. return $false
  630. }
  631. return $true
  632. } catch {
  633. return $false
  634. }
  635. }
  636. function Resolve-ManagedNodeBin {
  637. param([string]$NodeDir)
  638. # Prefer the bin/ layout; official Node.js win zips put node.exe at the root.
  639. $binLayout = Join-Path $NodeDir "bin\node.exe"
  640. if (Test-Path $binLayout) { return $binLayout }
  641. $officialLayout = Join-Path $NodeDir "node.exe"
  642. if (Test-Path $officialLayout) { return $officialLayout }
  643. return $null
  644. }
  645. function Ensure-ManagedNode {
  646. $platform = Get-ManagedNodePlatform
  647. if (-not $platform) { return $null }
  648. $runtimeDir = Join-Path $DataDir "runtime"
  649. $archive = "node-v$($script:NODE_VERSION)-$($platform.Os)-$($platform.Arch).zip"
  650. $nodeDir = Join-Path $runtimeDir "node-v$($script:NODE_VERSION)-$($platform.Os)-$($platform.Arch)"
  651. $nodeBin = Resolve-ManagedNodeBin $nodeDir
  652. if ($nodeBin) {
  653. try {
  654. $v = (& $nodeBin --version 2>$null)
  655. if ($v -eq "v$($script:NODE_VERSION)") { return $nodeBin }
  656. } catch { }
  657. }
  658. $base = $script:NODE_DEPS_BASE.TrimEnd('/') + "/$($script:NODE_VERSION)"
  659. $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("pilot-managed-node-" + [guid]::NewGuid().ToString("N"))
  660. New-Item -ItemType Directory -Path $tmp -Force | Out-Null
  661. try {
  662. Msg "==> 下载托管 Node.js v$($script:NODE_VERSION) (win-x64)..." "==> Downloading managed Node.js v$($script:NODE_VERSION) (win-x64)..."
  663. $archivePath = Join-Path $tmp $archive
  664. $shasumsPath = Join-Path $tmp "SHASUMS256.txt"
  665. if (-not (Invoke-ManagedNodeDownload "$base/$archive" $archivePath)) { return $null }
  666. if (-not (Invoke-ManagedNodeDownload "$base/SHASUMS256.txt" $shasumsPath)) { return $null }
  667. if (-not (Test-ManagedNodeChecksum $archivePath $shasumsPath $archive)) { return $null }
  668. if (Test-Path $nodeDir) { Remove-Item -LiteralPath (Get-PilotLongPath $nodeDir) -Recurse -Force }
  669. if (-not (Test-Path $runtimeDir)) { New-Item -ItemType Directory -Path $runtimeDir -Force | Out-Null }
  670. Expand-Archive -Path $archivePath -DestinationPath $runtimeDir -Force
  671. $nodeBin = Resolve-ManagedNodeBin $nodeDir
  672. if (-not $nodeBin) {
  673. Msg " ❌ 解压产物中未找到 node.exe(bin\ 或根目录布局)" " ❌ No node.exe found in extracted archive (bin\ or root layout)"
  674. Remove-PilotPathQuietly $nodeDir
  675. return $null
  676. }
  677. return $nodeBin
  678. } catch {
  679. Remove-PilotPathQuietly $nodeDir
  680. return $null
  681. } finally {
  682. Remove-PilotPathQuietly $tmp
  683. }
  684. }
  685. function Ensure-NodeModules {
  686. param([string]$AppVersion = "latest")
  687. $platform = Get-ManagedNodePlatform
  688. if (-not $platform) { return $false }
  689. $modulesDir = Join-Path $script:PERMANENT_DIR "node_modules"
  690. $marker = Join-Path $modulesDir ".pilot-modules-version"
  691. $stamp = "$AppVersion $($platform.Os) $($platform.Arch)"
  692. if ((Test-Path $modulesDir) -and (Test-Path $marker)) {
  693. $existing = (Get-Content $marker -ErrorAction SilentlyContinue | Out-String).Trim()
  694. if ($existing -eq $stamp) { return $true }
  695. }
  696. $archive = "node-modules-$($platform.Os)-$($platform.Arch).tar.gz"
  697. $base = $script:NODE_MODULES_BASE.TrimEnd('/') + "/$AppVersion"
  698. # ASCII temp root: the archive is unpacked with tar.exe, which cannot see a
  699. # non-ASCII path (see Get-PilotAsciiTempRoot). Move-Item below lands it in the
  700. # real, possibly non-ASCII, install dir.
  701. $tmp = Join-Path (Get-PilotAsciiTempRoot) ("pilot-node-modules-" + [guid]::NewGuid().ToString("N"))
  702. New-Item -ItemType Directory -Path $tmp -Force | Out-Null
  703. try {
  704. Msg "==> 下载预编译 node_modules (win-x64, app v$AppVersion)..." "==> Downloading prebuilt node_modules (win-x64, app v$AppVersion)..."
  705. $archivePath = Join-Path $tmp $archive
  706. $shasumsPath = Join-Path $tmp "SHASUMS256.txt"
  707. if (-not (Invoke-ManagedNodeDownload "$base/$archive" $archivePath)) { return $false }
  708. if (-not (Invoke-ManagedNodeDownload "$base/SHASUMS256.txt" $shasumsPath)) { return $false }
  709. if (-not (Test-ManagedNodeChecksum $archivePath $shasumsPath $archive)) { return $false }
  710. $stage = Join-Path $tmp "stage"
  711. New-Item -ItemType Directory -Path $stage -Force | Out-Null
  712. # Expand-PilotTarGz already logged which tar ran and how it failed; name what
  713. # that cost so the "prebuilt node_modules unavailable, falling back to npm
  714. # install" notice below is not misread as "OSS has no artifact for this
  715. # version". A local tar conflict and a missing archive used to look identical.
  716. if (-not (Expand-PilotTarGz $archivePath $stage)) {
  717. Msg " ⚠️ 预编译 node_modules 解压失败" `
  718. " ⚠️ Failed to extract prebuilt node_modules"
  719. return $false
  720. }
  721. $stagedModules = Join-Path $stage "node_modules"
  722. if (-not (Test-Path $stagedModules)) {
  723. Msg " ⚠️ 预编译包中缺少 node_modules 目录" `
  724. " ⚠️ Extracted archive contains no node_modules directory"
  725. return $false
  726. }
  727. Set-Content -Path (Join-Path $stagedModules ".pilot-modules-version") -Value $stamp
  728. if (Test-Path $modulesDir) { Remove-Item -LiteralPath (Get-PilotLongPath $modulesDir) -Recurse -Force }
  729. # $stagedModules sits under the ASCII temp root, i.e. under whatever %TEMP%
  730. # gave us, and Move-Item cannot see an 8.3 segment either -- without this the
  731. # prebuilt tree silently lost every install on such a profile to npm install.
  732. Move-Item (Get-PilotLongPath $stagedModules) $modulesDir
  733. # The move brought the ASCII root's ACL with it, which can leave the tree
  734. # unreadable to the non-elevated scheduled task -- see Reset-PilotInheritedAcl.
  735. # If that cannot be repaired, throw the prebuilt tree away rather than deploy
  736. # dependencies the collector will not be able to read: returning $false falls
  737. # back to npm install, which creates node_modules in place and inherits normally.
  738. if (-not (Reset-PilotInheritedAcl $modulesDir)) {
  739. Msg " ⚠️ 预编译 node_modules 权限修复失败: $script:PILOT_LAST_ACL_ERR" `
  740. " ⚠️ Could not reset permissions on prebuilt node_modules: $script:PILOT_LAST_ACL_ERR"
  741. Remove-PilotPathQuietly $modulesDir
  742. return $false
  743. }
  744. return $true
  745. } catch {
  746. return $false
  747. } finally {
  748. Remove-PilotPathQuietly $tmp
  749. }
  750. }
  751. # <<< managed-node-runtime <<<
  752. # ============================================================
  753. # Check dependencies
  754. # ============================================================
  755. $script:NODE_BIN = ""
  756. $script:NPM_BIN = ""
  757. function Check-Deps {
  758. Msg "==> 检查依赖..." "==> Checking dependencies..."
  759. $script:NODE_BIN = ""
  760. if ($PreferSystemNode) {
  761. $script:NODE_BIN = Resolve-Node
  762. if (-not $script:NODE_BIN) {
  763. Msg " ⚠️ 系统 Node.js 不可用或无法加载 node:sqlite(需要 22.13+ 或 23.4+),改用托管运行时" `
  764. " ⚠️ System Node.js is missing or cannot load node:sqlite (need 22.13+ or 23.4+); using the managed runtime"
  765. $script:NODE_BIN = Ensure-ManagedNode
  766. }
  767. } else {
  768. $script:NODE_BIN = Ensure-ManagedNode
  769. if (-not $script:NODE_BIN) {
  770. Msg " ⚠️ 托管 Node.js 不可用(平台不支持或下载失败),回退系统 node" `
  771. " ⚠️ Managed Node.js unavailable (unsupported platform or download failed), falling back to system node"
  772. $script:NODE_BIN = Resolve-Node
  773. }
  774. }
  775. if (-not $script:NODE_BIN) {
  776. Msg "❌ 缺少可用的 Node.js:需要能加载 node:sqlite 的版本(22.13+ / 23.4+),或成功下载托管运行时" `
  777. "❌ No usable Node.js: node:sqlite must load (22.13+ / 23.4+), or the managed runtime must download"
  778. exit 1
  779. }
  780. if (-not (Test-NodeSupportsSqlite $script:NODE_BIN)) {
  781. $nodeVer = "unknown"
  782. $prevEAP = $ErrorActionPreference
  783. $ErrorActionPreference = "Continue"
  784. try {
  785. $verOut = & $script:NODE_BIN --version 2>&1
  786. $code = $LASTEXITCODE
  787. if ($code -eq 0 -and $verOut) { $nodeVer = "$verOut".Trim() }
  788. } catch {
  789. $nodeVer = "unknown"
  790. } finally {
  791. $ErrorActionPreference = $prevEAP
  792. }
  793. Msg "❌ 当前 Node.js 无法加载 node:sqlite($nodeVer)。需要 22.13+ 或 23.4+(无需 --experimental-sqlite),或托管运行时。" `
  794. "❌ This Node.js cannot load node:sqlite ($nodeVer). Need 22.13+ or 23.4+ (unflagged), or the managed runtime."
  795. exit 1
  796. }
  797. # Pin node binary path. -Encoding UTF8 is required, not cosmetic: the path can sit
  798. # under a non-ASCII %USERPROFILE% and the 5.1 default (ANSI) would store "??" there,
  799. # see the note on Resolve-Node.
  800. if (-not (Test-Path $CACHE_DIR)) { New-Item -ItemType Directory -Path $CACHE_DIR -Force | Out-Null }
  801. Set-Content -LiteralPath (Join-Path $CACHE_DIR "node-bin") -Value $script:NODE_BIN -Encoding UTF8
  802. # Hook entrypoints can always derive DataDir from their deployed location,
  803. # while GUI agents do not necessarily inherit the installer's CacheDir.
  804. if (-not (Test-Path $DataDir)) { New-Item -ItemType Directory -Path $DataDir -Force | Out-Null }
  805. Set-Content -LiteralPath (Join-Path $DataDir "node-bin") -Value $script:NODE_BIN -Encoding UTF8
  806. # Derive npm
  807. $npmPath = Join-Path (Split-Path $script:NODE_BIN) "npm.cmd"
  808. if (Test-Path $npmPath) {
  809. $script:NPM_BIN = $npmPath
  810. } else {
  811. $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
  812. if ($npmCmd) {
  813. $script:NPM_BIN = $npmCmd.Source
  814. } else {
  815. Msg "❌ 缺少依赖: npm,请先安装后重试" "❌ Missing dependency: npm — please install it first"
  816. exit 1
  817. }
  818. }
  819. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  820. $nodeVer = & $script:NODE_BIN --version
  821. $npmVer = & $script:NPM_BIN --version
  822. $ErrorActionPreference = $prevEAP
  823. Msg " ✅ node $nodeVer npm $npmVer" " ✅ node $nodeVer npm $npmVer"
  824. Msg " node pinned: $($script:NODE_BIN)" " node pinned: $($script:NODE_BIN)"
  825. Write-Host ""
  826. }
  827. # ============================================================
  828. # Download and extract package
  829. # ============================================================
  830. $script:INSTALL_SRC = ""
  831. function Download-AndExtract {
  832. $tmpDir = Join-Path $env:TEMP "loongsuite-pilot-install-$(Get-Random)"
  833. New-Item -ItemType Directory -Path $tmpDir -Force | Out-Null
  834. $script:TMP_DIR = $tmpDir
  835. $archivePath = Join-Path $tmpDir "package.zip"
  836. Msg "==> 下载安装包: $PackageUrl" "==> Downloading: $PackageUrl"
  837. try {
  838. if (Test-Path -LiteralPath $PackageUrl) {
  839. Copy-Item -LiteralPath $PackageUrl -Destination $archivePath -Force
  840. } elseif ($PackageUrl -match '^file://') {
  841. # Strip the file:// scheme with string ops instead of casting to [Uri], which is
  842. # forbidden under Constrained Language Mode (WDAC). Handles file:///C:/x and
  843. # file://C:/x; forward slashes are normalized to backslashes.
  844. $localPackagePath = ($PackageUrl -replace '^file:/{2,3}', '') -replace '/', '\'
  845. Copy-Item -LiteralPath $localPackagePath -Destination $archivePath -Force
  846. } else {
  847. # Best-effort TLS1.2 bump; setting this static property throws under Constrained
  848. # Language Mode (WDAC), so swallow it (modern Windows defaults to TLS1.2 anyway).
  849. try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {}
  850. Invoke-WebRequest -Uri $PackageUrl -OutFile $archivePath -UseBasicParsing
  851. }
  852. } catch {
  853. Msg "❌ 下载失败: $_" "❌ Download failed: $_"
  854. exit 1
  855. }
  856. Msg " ✅ 下载完成" " ✅ Downloaded"
  857. Write-Host ""
  858. Msg "==> 解压安装包..." "==> Extracting..."
  859. try {
  860. Expand-Archive -Path $archivePath -DestinationPath $tmpDir -Force
  861. } catch {
  862. Msg "❌ 解压失败: $_" "❌ Extraction failed: $_"
  863. exit 1
  864. }
  865. $pkgDir = Join-Path $tmpDir $PACKAGE_NAME
  866. if (Test-Path $pkgDir) {
  867. $script:INSTALL_SRC = $pkgDir
  868. } elseif (Test-Path (Join-Path $tmpDir "package.json")) {
  869. $script:INSTALL_SRC = $tmpDir
  870. } else {
  871. $found = Get-ChildItem $tmpDir -Recurse -Depth 2 -Filter "package.json" -ErrorAction SilentlyContinue | Select-Object -First 1
  872. if ($found) {
  873. $script:INSTALL_SRC = $found.DirectoryName
  874. } else {
  875. Msg "❌ 解压后未找到 package.json,安装包结构异常" "❌ package.json not found — unexpected package structure"
  876. exit 1
  877. }
  878. }
  879. Msg " ✅ 解压完成" " ✅ Extracted"
  880. Write-Host ""
  881. }
  882. # ============================================================
  883. # Agent probe
  884. # ============================================================
  885. $script:PROBE_RESULT = "[]"
  886. function Probe-Agents {
  887. Msg "==> 探测 AI Agent..." "==> Probing AI Agents..."
  888. $probeScript = Join-Path $script:INSTALL_SRC "dist\cli-probe.cjs"
  889. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  890. if (Test-Path $probeScript) {
  891. try {
  892. $raw = & $script:NODE_BIN $probeScript --installer --config-path (Join-Path $DataDir 'config.json') 2>$null
  893. if ($raw) {
  894. $script:PROBE_RESULT = if ($raw -is [array]) { $raw -join "" } else { $raw }
  895. }
  896. } catch {
  897. Msg " ⚠️ Agent 探测失败,将跳过选择" " ⚠️ Agent probe failed, skipping selection"
  898. $script:PROBE_RESULT = "[]"
  899. }
  900. }
  901. $count = $script:PROBE_RESULT | & $script:NODE_BIN -e "const r=JSON.parse(require('fs').readFileSync(0,'utf-8'));process.stdout.write(String(r.length))" 2>$null
  902. $ErrorActionPreference = $prevEAP
  903. if (-not $count) { $count = "0" }
  904. Msg " ✅ 探测到 ${count} 个 Agent 定义" " ✅ Found ${count} agent definitions"
  905. Write-Host ""
  906. }
  907. # ============================================================
  908. # Agent selection
  909. # ============================================================
  910. $script:SELECTED_AGENTS = $Agents
  911. $script:AGENT_SELECTION_EXPLICIT = if ($Agents) { '1' } else { '0' }
  912. function Select-Agents {
  913. # -AllAgents: collect every agent. Skip selection entirely and leave no gate
  914. # in config (other agent settings survive), so pilot auto-detects all
  915. # agents at runtime -- including ones installed after this run.
  916. if ($AllAgents) {
  917. if ($script:SELECTED_AGENTS) {
  918. Msg " ⚠️ -AllAgents 已启用,忽略 -Agents 指定的列表" `
  919. " ⚠️ -AllAgents is set; ignoring the -Agents list"
  920. $script:SELECTED_AGENTS = ""
  921. }
  922. Msg " 采集全部 Agent (不写入选择,由 pilot 运行时自动探测)" `
  923. " Collecting all agents (no selection written; pilot auto-detects at runtime)"
  924. Write-Host ""
  925. return
  926. }
  927. if ($script:SELECTED_AGENTS) {
  928. Msg " 使用指定的 Agent: $($script:SELECTED_AGENTS)" " Using specified agents: $($script:SELECTED_AGENTS)"
  929. Write-Host ""
  930. return
  931. }
  932. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  933. $agentCount = $script:PROBE_RESULT | & $script:NODE_BIN -e "const r=JSON.parse(require('fs').readFileSync(0,'utf-8'));process.stdout.write(String(r.length))" 2>$null
  934. $ErrorActionPreference = $prevEAP
  935. if (-not $agentCount -or $agentCount -eq "0") { return }
  936. # Non-interactive detection
  937. $isInteractive = Test-CanPrompt
  938. if (-not $isInteractive) {
  939. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  940. $script:SELECTED_AGENTS = $script:PROBE_RESULT | & $script:NODE_BIN -e @'
  941. const r = JSON.parse(require('fs').readFileSync(0,'utf-8'));
  942. const detected = r.filter(a => a.detected).map(a => a.id);
  943. process.stdout.write(detected.join(','));
  944. '@ 2>$null
  945. $ErrorActionPreference = $prevEAP
  946. Msg " (非交互模式) 自动选择已检测到的 Agent: $($script:SELECTED_AGENTS)" `
  947. " (non-interactive) Auto-selected detected agents: $($script:SELECTED_AGENTS)"
  948. Write-Host ""
  949. return
  950. }
  951. # Interactive menu
  952. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  953. $script:PROBE_RESULT | & $script:NODE_BIN -e @'
  954. const r = JSON.parse(require('fs').readFileSync(0,'utf-8'));
  955. const lang = process.argv[1];
  956. const defaults = [];
  957. for (let i = 0; i < r.length; i++) {
  958. const a = r[i];
  959. const status = lang === 'zh'
  960. ? (a.detected ? '已检测到: ' + a.reason : '未检测到' + (a.reason ? ': ' + a.reason : ''))
  961. : (a.detected ? 'detected: ' + a.reason : 'not detected' + (a.reason ? ': ' + a.reason : ''));
  962. console.log(' [' + (i+1) + '] ' + a.displayName.padEnd(16) + '(' + status + ')');
  963. if (a.detected) defaults.push(i+1);
  964. }
  965. console.log('');
  966. if (lang === 'zh') {
  967. console.log(' 默认选择已检测到的 Agent: ' + defaults.join(','));
  968. console.log(' 输入要启用的编号 (逗号分隔),直接回车使用默认:');
  969. } else {
  970. console.log(' Default selection (detected): ' + defaults.join(','));
  971. console.log(' Enter numbers to enable (comma-separated), press Enter for default:');
  972. }
  973. '@ $LANG_MODE
  974. $ErrorActionPreference = $prevEAP
  975. $rawSelection = Read-Host " >"
  976. $selectInput = if ($null -eq $rawSelection) { "" } else { $rawSelection.Trim() }
  977. $selectInput = $selectInput -replace '[,、;]', ','
  978. if ($selectInput) { $script:AGENT_SELECTION_EXPLICIT = '1' }
  979. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  980. $script:SELECTED_AGENTS = $script:PROBE_RESULT | & $script:NODE_BIN -e @'
  981. const r = JSON.parse(require('fs').readFileSync(0,'utf-8'));
  982. const input = (process.argv[1] || '').replace(/[,、;]/g, ',');
  983. let indices;
  984. if (!input.trim()) {
  985. indices = r.map((a, i) => a.detected ? i : -1).filter(i => i >= 0);
  986. } else {
  987. indices = [...new Set(input.trim().split(/[\s,]+/).map(Number).filter(n => n >= 1 && n <= r.length))].map(n => n - 1);
  988. }
  989. const ids = indices.sort((a,b) => a-b).map(i => r[i].id);
  990. process.stdout.write(ids.join(','));
  991. '@ $selectInput 2>$null
  992. $ErrorActionPreference = $prevEAP
  993. if ($script:SELECTED_AGENTS) {
  994. Msg " 已选择: $($script:SELECTED_AGENTS)" " Selected: $($script:SELECTED_AGENTS)"
  995. } else {
  996. Msg " 未选择任何 Agent" " No agents selected"
  997. }
  998. Write-Host ""
  999. }
  1000. # ============================================================
  1001. # Prompt for userId
  1002. # ============================================================
  1003. function Prompt-UserId {
  1004. if ($UserId) { return }
  1005. $configFile = Join-Path $DataDir "config.json"
  1006. $existingUid = ""
  1007. if (Test-Path $configFile) {
  1008. try {
  1009. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  1010. $existingUid = & $script:NODE_BIN -e @'
  1011. try { const c=JSON.parse(require('fs').readFileSync(process.argv[1],'utf-8')); process.stdout.write(c.userId||''); } catch {}
  1012. '@ $configFile 2>$null
  1013. $ErrorActionPreference = $prevEAP
  1014. } catch {}
  1015. }
  1016. # Reinstall preserves the existing identity without prompting. To change it,
  1017. # callers must pass -UserId explicitly; this keeps scripted installs fully
  1018. # non-interactive and avoids Read-Host failures in Windows PowerShell 5.1.
  1019. if ($existingUid) {
  1020. $script:UserId = $existingUid
  1021. return
  1022. }
  1023. $isInteractive = Test-CanPrompt
  1024. if (-not $isInteractive) {
  1025. return
  1026. }
  1027. Write-Host ""
  1028. if ($existingUid) {
  1029. Msg " 当前 userId: $existingUid" " Current userId: $existingUid"
  1030. Msg " 直接回车保留,或输入新值:" " Press Enter to keep, or type a new value:"
  1031. } else {
  1032. Msg " 请输入你的 userId(用于数据归属,可直接回车跳过):" `
  1033. " Enter your userId (for data attribution, press Enter to skip):"
  1034. }
  1035. $rawInput = Read-Host " >"
  1036. $input = if ($null -eq $rawInput) { "" } else { $rawInput.Trim() }
  1037. if ($input) {
  1038. $script:UserId = $input
  1039. } elseif ($existingUid) {
  1040. $script:UserId = $existingUid
  1041. }
  1042. }
  1043. # ============================================================
  1044. # Confirm config overwrite
  1045. # ============================================================
  1046. function Confirm-ConfigOverwrite {
  1047. $configFile = Join-Path $DataDir "config.json"
  1048. if (-not (Test-Path $configFile)) { return }
  1049. $slsModeForDiff = ""
  1050. if ($SlsApiKey) {
  1051. $slsModeForDiff = "apiKey"
  1052. } elseif ($SlsAkId -and $SlsAkSecret) {
  1053. $slsModeForDiff = "ak"
  1054. }
  1055. $jsonArg = @{
  1056. slsEndpoint = $SlsEndpoint
  1057. slsProject = $SlsProject
  1058. slsLogstore = $SlsLogstore
  1059. slsMode = $slsModeForDiff
  1060. cmsLicenseKey = $CmsLicenseKey
  1061. cmsEndpoint = $CmsEndpoint
  1062. cmsWorkspace = $CmsWorkspace
  1063. serviceNamePrefix = $ServiceNamePrefix
  1064. dashboardPort = $DashboardPort
  1065. maskMode = $MaskMode
  1066. maskTypes = $MaskTypes
  1067. maskReplacementMode = $MaskReplacementMode
  1068. interceptorMode = $InterceptorMode
  1069. interceptorTypes = $InterceptorTypes
  1070. multimodalMode = $script:MultimodalMode
  1071. } | ConvertTo-Json -Compress
  1072. $prevEAP = $ErrorActionPreference
  1073. try {
  1074. $ErrorActionPreference = "Continue"
  1075. $diffs = & $script:NODE_BIN -e @'
  1076. const fs = require('fs');
  1077. let old = {};
  1078. try { old = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8')); } catch { process.exit(0); }
  1079. const newVals = JSON.parse(process.argv[2]);
  1080. const normalizeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean).join(',');
  1081. const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
  1082. const parseTypeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean);
  1083. const uniqueTypes = list => [...new Set(list)];
  1084. const interceptorModeFinal = newVals.interceptorMode || (old.interceptor||{}).mode || '';
  1085. const interceptorTypesFinal = interceptorModeFinal === 'all'
  1086. ? INTERCEPTOR_TYPE_SET.slice()
  1087. : interceptorModeFinal === 'custom'
  1088. ? parseTypeCsv(newVals.interceptorMode ? newVals.interceptorTypes : ((old.interceptor||{}).types||[]).join(',')).filter(t => INTERCEPTOR_TYPE_SET.indexOf(t) !== -1)
  1089. : [];
  1090. const maskModeFinal = newVals.maskMode || (old.mask||{}).mode || '';
  1091. const maskTypesFinal = maskModeFinal === 'custom'
  1092. ? parseTypeCsv(newVals.maskMode ? newVals.maskTypes : ((old.mask||{}).types||[]).join(','))
  1093. : [];
  1094. const coveredMaskMode = interceptorTypesFinal.length && maskModeFinal !== 'all' ? 'custom' : maskModeFinal;
  1095. const coveredMaskTypes = coveredMaskMode === 'custom' ? uniqueTypes(maskTypesFinal.concat(interceptorTypesFinal)) : [];
  1096. const slsModeOf = sls => {
  1097. if (!sls) return '';
  1098. if (sls.mode) return sls.mode;
  1099. if (sls.apiKey) return 'apiKey';
  1100. if (sls.accessKeyId || sls.accessKeySecret) return 'ak';
  1101. return '';
  1102. };
  1103. const checks = [
  1104. { label: 'sls.endpoint', oldVal: (old.sls||{}).endpoint||'', newVal: newVals.slsEndpoint },
  1105. { label: 'sls.project', oldVal: (old.sls||{}).project||'', newVal: newVals.slsProject },
  1106. { label: 'sls.logstore', oldVal: (old.sls||{}).logstore||'', newVal: newVals.slsLogstore },
  1107. { label: 'sls.mode', oldVal: slsModeOf(old.sls), newVal: newVals.slsMode },
  1108. { label: 'cms.licenseKey', oldVal: (old.cms||{}).licenseKey||'', newVal: newVals.cmsLicenseKey },
  1109. { label: 'cms.endpoint', oldVal: (old.cms||{}).endpoint||'', newVal: newVals.cmsEndpoint },
  1110. { label: 'cms.workspace', oldVal: (old.cms||{}).workspace||'', newVal: newVals.cmsWorkspace },
  1111. { label: 'serviceNamePrefix', oldVal: old.serviceNamePrefix||'', newVal: newVals.serviceNamePrefix },
  1112. { label: 'dashboard.port', oldVal: (old.dashboard||{}).port||'', newVal: newVals.dashboardPort ? Number(newVals.dashboardPort) : '' },
  1113. { label: 'mask.mode', oldVal: (old.mask||{}).mode||'', newVal: coveredMaskMode },
  1114. { label: 'mask.types', oldVal: (old.mask||{}).mode === 'custom' && Array.isArray((old.mask||{}).types) ? normalizeCsv(old.mask.types.join(',')) : '', newVal: coveredMaskTypes.join(',') },
  1115. { label: 'mask.replacementMode', oldVal: (old.mask||{}).replacementMode||'', newVal: newVals.maskReplacementMode },
  1116. { label: 'interceptor.mode', oldVal: (old.interceptor||{}).mode||'', newVal: newVals.interceptorMode },
  1117. { label: 'interceptor.types', oldVal: Array.isArray((old.interceptor||{}).types) ? normalizeCsv(old.interceptor.types.join(',')) : '', newVal: normalizeCsv(newVals.interceptorTypes) },
  1118. { label: 'multimodal.storage.type', oldVal: (old.multimodal && old.multimodal.storage && old.multimodal.storage.type) || '', newVal: (newVals.multimodalMode && newVals.multimodalMode !== 'none' && newVals.slsEndpoint && newVals.slsProject && newVals.slsLogstore && newVals.slsMode === 'apiKey') ? 'sls' : '' },
  1119. ];
  1120. const changed = checks.filter(c => c.newVal && c.oldVal && c.newVal !== c.oldVal);
  1121. if (!changed.length) process.exit(0);
  1122. for (const c of changed) {
  1123. console.log(c.label + ': ' + c.oldVal + ' -> ' + c.newVal);
  1124. }
  1125. '@ $configFile $jsonArg 2>$null
  1126. } finally {
  1127. $ErrorActionPreference = $prevEAP
  1128. }
  1129. if (-not $diffs) { return }
  1130. Write-Host ""
  1131. Msg "⚠️ 以下配置将被覆盖:" "⚠️ The following config will be overwritten:"
  1132. $diffs | ForEach-Object { Write-Host " $_" }
  1133. $isInteractive = Test-CanPrompt
  1134. if ($isInteractive) {
  1135. Write-Host ""
  1136. Msg " 确认覆盖? (y/N):" " Confirm overwrite? (y/N):"
  1137. $answer = Read-Host " >"
  1138. if ($answer -notin @("y", "Y", "yes", "YES")) {
  1139. Msg "已取消安装" "Installation cancelled"
  1140. exit 0
  1141. }
  1142. } else {
  1143. Msg " (非交互模式) 继续覆盖" " (non-interactive) Proceeding with overwrite"
  1144. }
  1145. }
  1146. # ============================================================
  1147. # Deploy bootstrap scripts
  1148. # ============================================================
  1149. function Deploy-BootstrapScripts {
  1150. $srcDir = Join-Path $script:PERMANENT_DIR "scripts"
  1151. $bootDir = Join-Path $CACHE_DIR "bin"
  1152. if (-not (Test-Path $bootDir)) { New-Item -ItemType Directory -Path $bootDir -Force | Out-Null }
  1153. Copy-Item (Join-Path $srcDir "collector-daemon.js") $bootDir -Force
  1154. }
  1155. # ============================================================
  1156. # Deploy package to versions/ directory
  1157. # ============================================================
  1158. function Deploy-Package {
  1159. param([string]$src)
  1160. $cacheDir = $CACHE_DIR
  1161. $versionsDir = Join-Path $cacheDir "versions"
  1162. $currentFile = Join-Path $cacheDir "current"
  1163. $previousFile = Join-Path $cacheDir "previous"
  1164. $ver = ""; $commit = ""
  1165. $versionFile = Join-Path $src "VERSION"
  1166. if (Test-Path $versionFile) {
  1167. $content = Get-Content $versionFile
  1168. foreach ($line in $content) {
  1169. if ($line -match "^version=(.+)") { $ver = $Matches[1] }
  1170. if ($line -match "^git_commit=(.+)") { $commit = $Matches[1] }
  1171. }
  1172. }
  1173. $deployedDirName = ""
  1174. $oldDir = ""
  1175. if ($ver -and $commit) {
  1176. if (Test-Path $currentFile) {
  1177. $oldDir = (Get-Content $currentFile -ErrorAction SilentlyContinue).Trim()
  1178. }
  1179. $baseDirName = "${ver}_${commit}"
  1180. $deployedDirName = $baseDirName
  1181. $target = Join-Path $versionsDir $deployedDirName
  1182. if (Test-Path -LiteralPath $target) {
  1183. # Never overwrite a version directory in place. A collector may still
  1184. # have native modules loaded from it, especially when replacing an old
  1185. # S4U task that the current shell cannot terminate.
  1186. $suffix = "$(Get-Date -Format 'yyyyMMddHHmmss')_$(Get-Random -Minimum 1000 -Maximum 9999)"
  1187. $deployedDirName = "${baseDirName}_${suffix}"
  1188. $target = Join-Path $versionsDir $deployedDirName
  1189. }
  1190. Msg "==> 部署到 $target ..." "==> Deploying to $target ..."
  1191. if (-not (Test-Path $versionsDir)) { New-Item -ItemType Directory -Path $versionsDir -Force | Out-Null }
  1192. Copy-Item $src $target -Recurse
  1193. $script:PERMANENT_DIR = $target
  1194. } else {
  1195. Msg "==> 部署到 $($script:PERMANENT_DIR) ..." "==> Deploying to $($script:PERMANENT_DIR) ..."
  1196. $parentDir = Split-Path $script:PERMANENT_DIR
  1197. if (-not (Test-Path $parentDir)) { New-Item -ItemType Directory -Path $parentDir -Force | Out-Null }
  1198. if (Test-Path $script:PERMANENT_DIR) { Remove-Item $script:PERMANENT_DIR -Recurse -Force }
  1199. Copy-Item $src $script:PERMANENT_DIR -Recurse
  1200. }
  1201. Msg " ✅ 部署完成" " ✅ Deployed"
  1202. Write-Host ""
  1203. Msg "==> 安装依赖..." "==> Installing dependencies..."
  1204. $modulesVer = $ver
  1205. if (-not $modulesVer) { if ($Version) { $modulesVer = $Version } else { $modulesVer = "latest" } }
  1206. $modulesFromOss = Ensure-NodeModules $modulesVer
  1207. if (-not $modulesFromOss) {
  1208. Msg " ⚠️ 预编译 node_modules 不可用,回退 npm install" " ⚠️ Prebuilt node_modules unavailable, falling back to npm install"
  1209. $nodeDir = Split-Path $script:NODE_BIN
  1210. $savedPath = $env:PATH
  1211. if ($env:PATH -notlike "*$nodeDir*") { $env:PATH = "$nodeDir;$env:PATH" }
  1212. Push-Location $script:PERMANENT_DIR
  1213. try {
  1214. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  1215. & $script:NPM_BIN install --omit=dev --omit=optional 2>&1 | Select-Object -Last 1
  1216. $npmExit = $LASTEXITCODE
  1217. $ErrorActionPreference = $prevEAP
  1218. } finally {
  1219. Pop-Location
  1220. $env:PATH = $savedPath
  1221. }
  1222. if ($npmExit -ne 0) {
  1223. Msg "❌ 依赖安装失败 (exit=$npmExit),请检查 npm 日志" "❌ Dependencies installation failed (exit=$npmExit), check npm logs"
  1224. exit 1
  1225. }
  1226. }
  1227. # Only publish current/previous after the candidate is complete. This keeps
  1228. # the old version recoverable when dependency installation fails.
  1229. if ($deployedDirName) {
  1230. if ($oldDir -and $oldDir -ne $deployedDirName) {
  1231. Set-Content -Path $previousFile -Value $oldDir
  1232. }
  1233. Set-Content -Path $currentFile -Value $deployedDirName
  1234. }
  1235. Deploy-BootstrapScripts
  1236. if ($modulesFromOss) {
  1237. Msg " ✅ 依赖安装完成(预编译 node_modules)" " ✅ Dependencies installed (prebuilt node_modules)"
  1238. } else {
  1239. Msg " ✅ 依赖安装完成" " ✅ Dependencies installed"
  1240. }
  1241. Write-Host ""
  1242. # >>> pilot-postinstall-exit-check >>>
  1243. Msg "==> 部署 hook 脚本..." "==> Deploying hook scripts..."
  1244. $postinstallScript = Join-Path $script:PERMANENT_DIR "scripts\postinstall.js"
  1245. $postinstallExit = 0
  1246. $postinstallPartial = $false
  1247. # Empty means "nothing went wrong". The caller aborts on a non-empty value -- the policy
  1248. # lives at the call sites so this block stays byte-identical across the installers, same
  1249. # split as $script:PILOT_LAST_RESTART_ERR.
  1250. $script:PILOT_POSTINSTALL_ERR = ""
  1251. if (Test-Path $postinstallScript) {
  1252. # postinstall.js resolves its target as LOONGSUITE_PILOT_DATA_DIR, falling back to
  1253. # $env:USERPROFILE\.loongsuite-pilot. Unset, an install started with -DataDir would
  1254. # put hooks/skills/plugins in the default tree while its config lives elsewhere, and
  1255. # the collector would then find no hooks at all. Set for this child only and
  1256. # restored afterwards: the rest of the installer must keep seeing what it had.
  1257. $hadPostinstallDataDir = Test-Path Env:LOONGSUITE_PILOT_DATA_DIR
  1258. $priorPostinstallDataDir = if ($hadPostinstallDataDir) {
  1259. (Get-Item Env:LOONGSUITE_PILOT_DATA_DIR).Value
  1260. } else { $null }
  1261. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  1262. try {
  1263. $env:LOONGSUITE_PILOT_DATA_DIR = $DataDir
  1264. # Captured rather than streamed because the per-tree verdict is in the output and
  1265. # nowhere else (see below). 2>&1 because postinstall.js reports it on stderr.
  1266. $postinstallOut = & $script:NODE_BIN $postinstallScript 2>&1
  1267. $postinstallExit = $LASTEXITCODE
  1268. $postinstallOut | ForEach-Object { Write-Host $_ }
  1269. if (($postinstallOut | Out-String) -match "failed asset tree|Post-install failed") { $postinstallPartial = $true }
  1270. } finally {
  1271. $ErrorActionPreference = $prevEAP
  1272. if ($hadPostinstallDataDir) {
  1273. Set-Item Env:LOONGSUITE_PILOT_DATA_DIR -Value $priorPostinstallDataDir
  1274. } else {
  1275. Remove-Item Env:LOONGSUITE_PILOT_DATA_DIR -ErrorAction SilentlyContinue
  1276. }
  1277. }
  1278. }
  1279. # Never print the check mark for a postinstall that did not finish. That is exactly how
  1280. # the hooks/skills/plugins trees went missing on every Windows install without a word:
  1281. # fs.cpSync fail-fasts with 0xC0000409 on the bundled Node, killing the script before it
  1282. # copied anything, and this line printed "Hook scripts deployed" regardless.
  1283. #
  1284. # Three distinct outcomes, and the exit code only covers the first. postinstall.js
  1285. # deliberately exits 0 after a per-tree failure -- a non-zero exit would abort the npm
  1286. # install fallback above -- and announces it as "N failed asset tree(s)" instead; its
  1287. # top-level catch is the same story, printing "Post-install failed: <reason>" and still
  1288. # exiting 0. So a non-zero code means the process died outright, while the other two are
  1289. # legible only in the output. Keying the check mark off the exit code alone printed it over
  1290. # an install that had just reported a tree it could not copy.
  1291. #
  1292. # An install with no hooks/plugins is not an install: the collector finds nothing to load
  1293. # and every collection cycle fails on a plugin that was never written. The caller aborts
  1294. # (install) or rolls back (upgrade) on $script:PILOT_POSTINSTALL_ERR.
  1295. if ($postinstallExit -ne 0) {
  1296. $script:PILOT_POSTINSTALL_ERR = "postinstall.js (exit $postinstallExit)"
  1297. Msg " ❌ Hook 脚本部署失败 (exit=$postinstallExit),hooks/plugins 缺失" `
  1298. " ❌ Hook script deployment failed (exit=$postinstallExit); hooks/plugins are missing"
  1299. } elseif ($postinstallPartial) {
  1300. $script:PILOT_POSTINSTALL_ERR = "postinstall.js reported a failed asset tree"
  1301. Msg " ❌ Hook 脚本部分部署失败(见上方输出),hooks/plugins 缺失" `
  1302. " ❌ Some hook asset trees failed to deploy (see the output above); hooks/plugins are missing"
  1303. } else {
  1304. Msg " ✅ Hook 脚本已部署" " ✅ Hook scripts deployed"
  1305. }
  1306. # <<< pilot-postinstall-exit-check <<<
  1307. Write-Host ""
  1308. }
  1309. # ============================================================
  1310. # Migrate legacy layout
  1311. # ============================================================
  1312. function Migrate-LegacyLayout {
  1313. $cacheDir = $CACHE_DIR
  1314. $currentFile = Join-Path $cacheDir "current"
  1315. $legacyDir = Join-Path $cacheDir "package"
  1316. $versionsDir = Join-Path $cacheDir "versions"
  1317. if (Test-Path $currentFile) { return }
  1318. if (-not (Test-Path (Join-Path $legacyDir "dist\index.js"))) { return }
  1319. Msg "==> 迁移旧版本目录结构..." "==> Migrating legacy directory layout..."
  1320. $ver = "0.0.0"; $commit = "legacy"
  1321. $versionFile = Join-Path $legacyDir "VERSION"
  1322. if (Test-Path $versionFile) {
  1323. $content = Get-Content $versionFile
  1324. foreach ($line in $content) {
  1325. if ($line -match "^version=(.+)") { $ver = $Matches[1] }
  1326. if ($line -match "^git_commit=(.+)") { $commit = $Matches[1] }
  1327. }
  1328. }
  1329. $dirName = "${ver}_${commit}"
  1330. $target = Join-Path $versionsDir $dirName
  1331. if (-not (Test-Path $versionsDir)) { New-Item -ItemType Directory -Path $versionsDir -Force | Out-Null }
  1332. Copy-Item $legacyDir $target -Recurse
  1333. Set-Content -Path $currentFile -Value $dirName
  1334. $script:PERMANENT_DIR = $target
  1335. Msg " ✅ 已迁移到 $target" " ✅ Migrated to $target"
  1336. Write-Host ""
  1337. }
  1338. # ============================================================
  1339. # Write config.json
  1340. # ============================================================
  1341. function Write-Config {
  1342. $configFile = Join-Path $DataDir "config.json"
  1343. Msg "==> 写入配置文件 $configFile ..." "==> Writing config to $configFile ..."
  1344. if (-not (Test-Path $DataDir)) { New-Item -ItemType Directory -Path $DataDir -Force | Out-Null }
  1345. # Bundle all params as JSON to avoid PowerShell dropping empty-string args to native commands
  1346. $cfgArgs = [ordered]@{
  1347. configPath = $configFile
  1348. dataDir = $DataDir
  1349. dashboardPort = "$DashboardPort"
  1350. slsEndpoint = "$SlsEndpoint"
  1351. slsProject = "$SlsProject"
  1352. slsLogstore = "$SlsLogstore"
  1353. slsAkId = "$SlsAkId"
  1354. slsAkSecret = "$SlsAkSecret"
  1355. slsApiKey = "$SlsApiKey"
  1356. logLevel = "$LogLevel"
  1357. userId = "$($script:UserId)"
  1358. excludeWorkspaces = @($ExcludeWorkspace | Where-Object { $null -ne $_ })
  1359. collectLog = "$CollectLog"
  1360. collectTrace = "$CollectTrace"
  1361. enableStatusBarApp = "$EnableStatusBarApp"
  1362. cmsLicenseKey = "$CmsLicenseKey"
  1363. cmsEndpoint = "$CmsEndpoint"
  1364. cmsWorkspace = "$CmsWorkspace"
  1365. serviceNamePrefix = "$ServiceNamePrefix"
  1366. selectedAgents = "$($script:SELECTED_AGENTS)"
  1367. allAgentsMode = $(if ($AllAgents) { "1" } else { "" })
  1368. multimodalMode = "$($script:MultimodalMode)"
  1369. multimodalSupportedAgents = "$($script:MultimodalSupportedAgents)"
  1370. agentSelectionExplicit = "$($script:AGENT_SELECTION_EXPLICIT)"
  1371. maskMode = "$MaskMode"
  1372. maskTypes = "$MaskTypes"
  1373. maskReplacementMode = "$MaskReplacementMode"
  1374. interceptorMode = "$InterceptorMode"
  1375. interceptorTypes = "$InterceptorTypes"
  1376. probeResult = "$($script:PROBE_RESULT)"
  1377. }
  1378. $cfgJson = $cfgArgs | ConvertTo-Json -Compress
  1379. # Stage the JSON through a temp file rather than piping it to node's stdin. Under Windows
  1380. # PowerShell 5.1 a string piped to a native command is encoded with $OutputEncoding (default
  1381. # ASCII), so any non-ASCII value (Chinese serviceNamePrefix/userId, a Chinese username in the
  1382. # path, custom mask types...) would be mangled to "?" before node ever sees it. Set-Content
  1383. # -Encoding UTF8 is CLM-safe (no forbidden .NET calls) and encodes UTF-8 correctly regardless
  1384. # of $OutputEncoding; it prepends a BOM in PS5.1, which node strips below before JSON.parse.
  1385. $cfgTmp = Join-Path $env:TEMP ("lp-config-" + (Get-Random) + ".json")
  1386. Set-Content -LiteralPath $cfgTmp -Value $cfgJson -Encoding UTF8 -NoNewline
  1387. # Native node does not throw; read $LASTEXITCODE on the next line so a JSON
  1388. # or write failure cannot print "Config written" and keep installing.
  1389. $cfgExit = 1
  1390. $prevEAP = $ErrorActionPreference
  1391. try {
  1392. $ErrorActionPreference = "Continue"
  1393. & $script:NODE_BIN -e @'
  1394. const fs = require('fs');
  1395. let raw = fs.readFileSync(process.argv[1], 'utf-8');
  1396. if (raw.charCodeAt(0) === 0xFEFF) raw = raw.slice(1);
  1397. const opts = JSON.parse(raw);
  1398. let existing = {};
  1399. try { existing = JSON.parse(fs.readFileSync(opts.configPath, 'utf-8')); } catch {}
  1400. const config = {
  1401. ...existing,
  1402. enabled: true,
  1403. dataDir: opts.dataDir,
  1404. };
  1405. if (Array.isArray(opts.excludeWorkspaces) && opts.excludeWorkspaces.length > 0) {
  1406. if (opts.excludeWorkspaces.some(value => typeof value !== 'string' || !require('path').win32.isAbsolute(value))) {
  1407. throw new Error('-ExcludeWorkspace requires absolute local directories');
  1408. }
  1409. config.privacy = { ...config.privacy, excludeWorkspaces: opts.excludeWorkspaces };
  1410. }
  1411. if (!config.dashboard || typeof config.dashboard !== 'object' || Array.isArray(config.dashboard)) {
  1412. config.dashboard = {};
  1413. }
  1414. if (opts.dashboardPort) config.dashboard.port = Number(opts.dashboardPort);
  1415. if (config.dashboard.port === undefined) config.dashboard.port = 8765;
  1416. delete config.internal;
  1417. if (config.userId === undefined && config['user.id'] !== undefined) {
  1418. config.userId = config['user.id'];
  1419. }
  1420. delete config['user.id'];
  1421. if (opts.slsEndpoint || opts.slsProject || opts.slsLogstore || opts.slsApiKey) {
  1422. config.sls = config.sls || {};
  1423. delete config.sls.destinationOverride;
  1424. if (opts.slsEndpoint) config.sls.endpoint = opts.slsEndpoint;
  1425. if (opts.slsApiKey) {
  1426. config.sls.mode = 'apiKey';
  1427. config.sls.apiKey = opts.slsApiKey;
  1428. delete config.sls.accessKeyId;
  1429. delete config.sls.accessKeySecret;
  1430. } else if (opts.slsAkId && opts.slsAkSecret) {
  1431. config.sls.mode = 'ak';
  1432. config.sls.accessKeyId = opts.slsAkId;
  1433. config.sls.accessKeySecret = opts.slsAkSecret;
  1434. delete config.sls.apiKey;
  1435. } else if (opts.slsEndpoint || opts.slsProject || opts.slsLogstore) {
  1436. config.sls.mode = 'webtracking';
  1437. delete config.sls.apiKey;
  1438. delete config.sls.accessKeyId;
  1439. delete config.sls.accessKeySecret;
  1440. }
  1441. if (opts.slsProject && opts.slsLogstore) {
  1442. config.sls.project = opts.slsProject;
  1443. config.sls.logstore = opts.slsLogstore;
  1444. delete config.sls.endpoints;
  1445. }
  1446. }
  1447. if (opts.logLevel) config.logLevel = opts.logLevel;
  1448. if (opts.userId) { config.userId = opts.userId; delete config.identity; }
  1449. if (opts.collectLog) config.collectLog = opts.collectLog === 'true';
  1450. if (opts.collectTrace) config.collectTrace = opts.collectTrace === 'true';
  1451. if (opts.enableStatusBarApp) config.enableStatusBarApp = opts.enableStatusBarApp.toLowerCase() === 'true';
  1452. if (opts.cmsLicenseKey || opts.cmsEndpoint || opts.cmsWorkspace) {
  1453. config.cms = config.cms || {};
  1454. if (opts.cmsLicenseKey) config.cms.licenseKey = opts.cmsLicenseKey;
  1455. if (opts.cmsEndpoint) config.cms.endpoint = opts.cmsEndpoint;
  1456. if (opts.cmsWorkspace) config.cms.workspace = opts.cmsWorkspace;
  1457. }
  1458. if (opts.serviceNamePrefix) config.serviceNamePrefix = opts.serviceNamePrefix;
  1459. if (opts.maskMode) {
  1460. config.mask = config.mask || {};
  1461. config.mask.mode = opts.maskMode;
  1462. if (opts.maskMode === 'custom') {
  1463. config.mask.types = opts.maskTypes.split(',').map(t => t.trim()).filter(Boolean);
  1464. } else { delete config.mask.types; }
  1465. }
  1466. if (opts.maskReplacementMode) {
  1467. config.mask = config.mask || {};
  1468. config.mask.replacementMode = opts.maskReplacementMode;
  1469. }
  1470. if (opts.interceptorMode) {
  1471. config.interceptor = config.interceptor || {};
  1472. config.interceptor.mode = opts.interceptorMode;
  1473. if (opts.interceptorMode === 'custom') {
  1474. config.interceptor.types = opts.interceptorTypes.split(',').map(t => t.trim()).filter(Boolean);
  1475. } else { delete config.interceptor.types; }
  1476. }
  1477. const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
  1478. (function ensureMaskCoversInterceptor(config) {
  1479. const interceptor = config.interceptor || {};
  1480. const extra = interceptor.mode === 'all'
  1481. ? INTERCEPTOR_TYPE_SET.slice()
  1482. : interceptor.mode === 'custom' && Array.isArray(interceptor.types)
  1483. ? interceptor.types.filter(type => INTERCEPTOR_TYPE_SET.indexOf(type) !== -1)
  1484. : [];
  1485. if (extra.length === 0) return;
  1486. if ((config.mask || {}).mode === 'all') return;
  1487. const current = (config.mask || {}).mode === 'custom' && Array.isArray((config.mask || {}).types)
  1488. ? config.mask.types.filter(type => typeof type === 'string' && type.trim())
  1489. : [];
  1490. config.mask = config.mask && typeof config.mask === 'object' && !Array.isArray(config.mask)
  1491. ? config.mask
  1492. : {};
  1493. config.mask.mode = 'custom';
  1494. config.mask.types = [...new Set(current.concat(extra))];
  1495. })(config);
  1496. const allAgents = JSON.parse(opts.probeResult || '[]');
  1497. if (opts.allAgentsMode === '1') {
  1498. // Clear enable gates, not metadata such as a persisted OpenClaw entry.
  1499. for (const agent of Object.values(config.agents || {})) delete agent.enabled;
  1500. } else if (opts.selectedAgents) {
  1501. config.agents = config.agents || {};
  1502. const previousOpenclaw = config.agents.openclaw;
  1503. const selected = opts.selectedAgents.split(',').map(s => s.trim()).filter(Boolean);
  1504. for (const agent of allAgents) {
  1505. config.agents[agent.id] = config.agents[agent.id] || {};
  1506. // A transient discovery miss is not consent to uninstall a live plugin.
  1507. if (agent.id === 'openclaw' && !agent.detected && opts.agentSelectionExplicit !== '1'
  1508. && previousOpenclaw !== undefined) {
  1509. console.log('OpenClaw: detection unavailable; preserving previous enabled state and entry');
  1510. continue;
  1511. }
  1512. config.agents[agent.id].enabled = selected.includes(agent.id);
  1513. }
  1514. }
  1515. const openclaw = allAgents.find(agent => agent.id === 'openclaw');
  1516. if (openclaw && openclaw.detected && openclaw.openclawCliPath
  1517. && (opts.allAgentsMode === '1' || (config.agents && config.agents.openclaw && config.agents.openclaw.enabled !== false))) {
  1518. config.agents = config.agents || {};
  1519. config.agents.openclaw = config.agents.openclaw || {};
  1520. const previousEntry = config.agents.openclaw.cliPath;
  1521. if (typeof previousEntry === 'string' && previousEntry !== openclaw.openclawCliPath) {
  1522. console.log('OpenClaw: updating launch entry ' + JSON.stringify(previousEntry) + ' -> ' + JSON.stringify(openclaw.openclawCliPath));
  1523. }
  1524. config.agents.openclaw.cliPath = openclaw.openclawCliPath;
  1525. }
  1526. if (opts.multimodalMode) {
  1527. config.agents = config.agents || {};
  1528. const supported = String(opts.multimodalSupportedAgents || '').split(',').map(s => s.trim()).filter(Boolean);
  1529. const selected = new Set(String(opts.selectedAgents || '').split(',').map(s => s.trim()).filter(Boolean));
  1530. const allSupported = opts.allAgentsMode === '1' && opts.multimodalMode !== 'none';
  1531. for (const id of supported) {
  1532. if (allSupported) config.agents[id] = config.agents[id] || {};
  1533. else if (!config.agents[id]) continue;
  1534. if (opts.multimodalMode === 'none') {
  1535. delete config.agents[id].multimodal;
  1536. continue;
  1537. }
  1538. const prev = (config.agents[id].multimodal && typeof config.agents[id].multimodal === 'object')
  1539. ? config.agents[id].multimodal
  1540. : {};
  1541. config.agents[id].multimodal = { ...prev, uploadMode: (allSupported || selected.has(id)) ? opts.multimodalMode : 'none' };
  1542. }
  1543. }
  1544. if (opts.multimodalMode && opts.multimodalMode !== 'none' && opts.slsEndpoint && opts.slsProject && opts.slsLogstore && opts.slsApiKey) {
  1545. config.multimodal = {
  1546. storage: {
  1547. type: 'sls',
  1548. target: { endpoint: opts.slsEndpoint, project: opts.slsProject, logstore: opts.slsLogstore },
  1549. },
  1550. };
  1551. }
  1552. fs.writeFileSync(opts.configPath, JSON.stringify(config, null, 2) + '\n');
  1553. '@ $cfgTmp
  1554. $cfgExit = $LASTEXITCODE
  1555. } finally {
  1556. $ErrorActionPreference = $prevEAP
  1557. Remove-PilotPathQuietly $cfgTmp
  1558. }
  1559. if ($cfgExit -ne 0) {
  1560. Msg "❌ 配置写入失败 (exit=$cfgExit)" "❌ Failed to write config (exit=$cfgExit)"
  1561. exit 1
  1562. }
  1563. Msg " ✅ 配置已写入" " ✅ Config written"
  1564. Write-Host ""
  1565. }
  1566. # reg.exe removes overrides under CLM; the guarded .NET call notifies Explorer.
  1567. function Get-PilotRuntimeOverride {
  1568. param([string]$Name)
  1569. $prevEAP = $ErrorActionPreference
  1570. try {
  1571. $ErrorActionPreference = "Continue"
  1572. $regOut = reg.exe query "HKCU\Environment" /v $Name 2>$null
  1573. $regExitCode = $LASTEXITCODE
  1574. } finally {
  1575. $ErrorActionPreference = $prevEAP
  1576. }
  1577. if ($regExitCode -ne 0) { return "" }
  1578. foreach ($line in $regOut) {
  1579. if (($line -match '^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*)$') -and $Matches[1] -ieq $Name) {
  1580. return $Matches[2].Trim()
  1581. }
  1582. }
  1583. return ""
  1584. }
  1585. function Remove-PilotRuntimeOverride {
  1586. param([string]$Name)
  1587. reg.exe delete "HKCU\Environment" /v $Name /f 2>$null | Out-Null
  1588. if ($LASTEXITCODE -ne 0) { throw "Failed to remove $Name" }
  1589. try {
  1590. [Environment]::SetEnvironmentVariable($Name, $null, 'User')
  1591. return $true
  1592. } catch {
  1593. return $false
  1594. }
  1595. }
  1596. function Retire-PilotRuntimeOverride {
  1597. param([string]$Name, [string]$WrapperPath)
  1598. $current = Get-PilotRuntimeOverride -Name $Name
  1599. if (-not $current) { return }
  1600. # Pilot-owned only: a third-party override must survive untouched.
  1601. if (($current -ieq $WrapperPath) -or ($current -like '*loongsuite-pilot*')) {
  1602. $broadcasted = Remove-PilotRuntimeOverride -Name $Name
  1603. if (-not $broadcasted) { $script:RUNTIME_ENV_BROADCAST_FAILED = $true }
  1604. Msg " ✅ 已退役 $Name" " ✅ Retired $Name"
  1605. }
  1606. }
  1607. function Retire-QoderworkRuntimeOverrides {
  1608. $wrapperPath = Join-Path $DataDir "hooks\qoderwork-runtime-wrapper.mjs"
  1609. $script:RUNTIME_ENV_BROADCAST_FAILED = $false
  1610. Retire-PilotRuntimeOverride -Name 'QW_QODER_WORKER_RUNTIME_PATH' -WrapperPath $wrapperPath
  1611. Retire-PilotRuntimeOverride -Name 'QODER_WORKER_RUNTIME_PATH' -WrapperPath $wrapperPath
  1612. if ($script:RUNTIME_ENV_BROADCAST_FAILED) {
  1613. Msg " 环境变量已清理,但无法通知 Explorer;请注销并重新登录 Windows" `
  1614. " Environment overrides removed but Explorer could not be notified; sign out and back in"
  1615. } else {
  1616. Msg " 请完全退出并重新打开对应应用以生效" `
  1617. " Fully quit and restart the corresponding apps for changes to take effect"
  1618. }
  1619. Write-Host ""
  1620. }
  1621. # ============================================================
  1622. # Install loongsuite-pilot command (batch wrapper)
  1623. # ============================================================
  1624. function Install-Command {
  1625. Msg "==> 安装服务管理脚本..." "==> Installing service management script..."
  1626. $binDir = Join-Path $env:USERPROFILE ".local\bin"
  1627. if (-not (Test-Path $binDir)) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null }
  1628. # Copy the PowerShell service management script. Deploy it as loongsuite-pilot-service.ps1,
  1629. # NOT loongsuite-pilot.ps1: in PowerShell a bare `loongsuite-pilot` resolves an on-PATH .ps1
  1630. # (ExternalScript) BEFORE the .cmd shim, and a directly-run .ps1 obeys the session
  1631. # ExecutionPolicy (often Restricted) instead of the shim's -ExecutionPolicy Bypass. A
  1632. # non-colliding name keeps the .cmd the only match for the bare command name.
  1633. $ps1File = Join-Path $binDir "loongsuite-pilot-service.ps1"
  1634. $ps1Src = Join-Path $script:PERMANENT_DIR "scripts\loongsuite-pilot.ps1"
  1635. if (Test-Path $ps1Src) {
  1636. Copy-Item $ps1Src $ps1File -Force
  1637. }
  1638. # Remove any stale same-name script from older installs that would shadow the .cmd shim.
  1639. $legacyPs1 = Join-Path $binDir "loongsuite-pilot.ps1"
  1640. if (Test-Path $legacyPs1) { Remove-Item $legacyPs1 -Force -ErrorAction SilentlyContinue }
  1641. $layoutFile = Join-Path $binDir "loongsuite-pilot-layout.json"
  1642. $layout = [ordered]@{
  1643. dataDir = $DataDir
  1644. cacheDir = $CACHE_DIR
  1645. } | ConvertTo-Json
  1646. # loongsuite-pilot.ps1 reads this back with Get-Content -Encoding UTF8 | ConvertFrom-Json,
  1647. # which tolerates a BOM, so Set-Content is fine here (and CLM-safe, unlike WriteAllText).
  1648. Set-Content -LiteralPath $layoutFile -Value $layout -Encoding UTF8
  1649. # Create a .cmd shim that forwards to the PowerShell script
  1650. $cmdFile = Join-Path $binDir "loongsuite-pilot.cmd"
  1651. $cmdContent = @'
  1652. @echo off
  1653. powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0loongsuite-pilot-service.ps1" %*
  1654. '@
  1655. Set-Content -Path $cmdFile -Value $cmdContent -Encoding ASCII
  1656. Msg " ✅ 已安装: $cmdFile" " ✅ Installed: $cmdFile"
  1657. # Add to user PATH if not already there. The persistent write uses reg.exe (a native command,
  1658. # CLM-safe) rather than [Environment]::SetEnvironmentVariable (a .NET static call WDAC forbids)
  1659. # or Set-ItemProperty. Two hazards this avoids:
  1660. # 1. Set-ItemProperty writes plain REG_SZ by default, DOWNGRADING a REG_EXPAND_SZ Path.
  1661. # 2. Get-ItemProperty returns Path already EXPANDED; writing that back FREEZES
  1662. # %USERPROFILE%/%SystemRoot% tokens into literal paths.
  1663. # So we read the RAW (unexpanded) value and its type via `reg query`, then write it back with
  1664. # `reg add /t <type>` to preserve REG_EXPAND_SZ and the tokens. The presence check still uses
  1665. # the EXPANDED value so a bin dir already present via a %VAR% token is not added twice.
  1666. $expandedPath = (Get-ItemProperty -Path 'HKCU:\Environment' -Name Path -ErrorAction SilentlyContinue).Path
  1667. if ($expandedPath -notlike "*$binDir*") {
  1668. $pathType = 'REG_EXPAND_SZ'
  1669. $rawUserPath = ''
  1670. $regOut = reg query "HKCU\Environment" /v Path 2>$null
  1671. if ($LASTEXITCODE -eq 0) {
  1672. foreach ($line in $regOut) {
  1673. if ($line -match '^\s*Path\s+(REG_(?:EXPAND_)?SZ)\s+(.*)$') {
  1674. $pathType = $Matches[1]
  1675. $rawUserPath = $Matches[2]
  1676. break
  1677. }
  1678. }
  1679. }
  1680. # Never drop the existing PATH: if reg query yielded nothing usable, fall back to the
  1681. # expanded value (worst case re-freezes tokens, but preserves all entries).
  1682. if (-not $rawUserPath -and $expandedPath) { $rawUserPath = $expandedPath }
  1683. $newPath = if ($rawUserPath) { "$binDir;$rawUserPath" } else { $binDir }
  1684. reg add "HKCU\Environment" /v Path /t $pathType /d "$newPath" /f | Out-Null
  1685. # Best-effort broadcast so already-open Explorer-spawned terminals refresh their PATH
  1686. # without a re-login: [Environment]::SetEnvironmentVariable persists AND sends
  1687. # WM_SETTINGCHANGE. It is a .NET static call CLM forbids, so swallow failures — the reg add
  1688. # above already persisted the typed value. $newPath still carries raw %VAR% tokens, so on
  1689. # non-CLM hosts .NET also writes REG_EXPAND_SZ (no downgrade).
  1690. try { [Environment]::SetEnvironmentVariable('Path', $newPath, 'User') } catch {}
  1691. Msg " 已将 $binDir 添加到用户 PATH" " Added $binDir to user PATH"
  1692. $env:Path = "$binDir;$env:Path"
  1693. }
  1694. Write-Host ""
  1695. }
  1696. # ============================================================
  1697. # Version helpers
  1698. # ============================================================
  1699. function Get-InstalledVersion {
  1700. $cacheDir = $CACHE_DIR
  1701. $currentFile = Join-Path $cacheDir "current"
  1702. $versionsDir = Join-Path $cacheDir "versions"
  1703. if (Test-Path $currentFile) {
  1704. $dir = (Get-Content $currentFile -ErrorAction SilentlyContinue).Trim()
  1705. $vf = Join-Path $versionsDir "$dir\VERSION"
  1706. if ($dir -and (Test-Path $vf)) {
  1707. $content = Get-Content $vf
  1708. foreach ($line in $content) {
  1709. if ($line -match "^version=(.+)") { return $Matches[1] }
  1710. }
  1711. }
  1712. }
  1713. $vf = Join-Path $script:PERMANENT_DIR "VERSION"
  1714. if (Test-Path $vf) {
  1715. $content = Get-Content $vf
  1716. foreach ($line in $content) {
  1717. if ($line -match "^version=(.+)") { return $Matches[1] }
  1718. }
  1719. }
  1720. return ""
  1721. }
  1722. function Get-VersionFromDir {
  1723. param([string]$dir)
  1724. $vf = Join-Path $dir "VERSION"
  1725. if (Test-Path $vf) {
  1726. $content = Get-Content $vf
  1727. foreach ($line in $content) {
  1728. if ($line -match "^version=(.+)") { return $Matches[1] }
  1729. }
  1730. }
  1731. return ""
  1732. }
  1733. function Get-CommitFromDir {
  1734. param([string]$dir)
  1735. $vf = Join-Path $dir "VERSION"
  1736. if (Test-Path $vf) {
  1737. $content = Get-Content $vf
  1738. foreach ($line in $content) {
  1739. if ($line -match "^git_commit=(.+)") { return $Matches[1] }
  1740. }
  1741. }
  1742. return ""
  1743. }
  1744. function Show-VersionInfo {
  1745. param([string]$dir)
  1746. $vf = Join-Path $dir "VERSION"
  1747. if (Test-Path $vf) {
  1748. $v = ""; $c = ""; $t = ""
  1749. $content = Get-Content $vf
  1750. foreach ($line in $content) {
  1751. if ($line -match "^version=(.+)") { $v = $Matches[1] }
  1752. if ($line -match "^git_commit=(.+)") { $c = $Matches[1] }
  1753. if ($line -match "^build_time=(.+)") { $t = $Matches[1] }
  1754. }
  1755. return "v${v} (${c}, ${t})"
  1756. }
  1757. return "unknown"
  1758. }
  1759. # ============================================================
  1760. # Print summary
  1761. # ============================================================
  1762. function Print-Summary {
  1763. param([string]$action)
  1764. $configFile = Join-Path $DataDir "config.json"
  1765. Write-Host "============================================================"
  1766. $ver = Show-VersionInfo $script:PERMANENT_DIR
  1767. switch ($action) {
  1768. "install" { Msg "✅ 安装完成!版本: $ver" "✅ Installation complete! Version: $ver" }
  1769. "upgrade" { Msg "✅ 升级完成!版本: $ver" "✅ Upgrade complete! Version: $ver" }
  1770. }
  1771. Write-Host ""
  1772. Msg "配置文件: $configFile" "Config file: $configFile"
  1773. Msg "数据目录: $DataDir" "Data directory: $DataDir"
  1774. Msg "Hook 目录: $DataDir\hooks" "Hooks directory: $DataDir\hooks"
  1775. Write-Host ""
  1776. if ($SlsEndpoint) {
  1777. Msg "SLS 后端: $SlsEndpoint" "SLS backend: $SlsEndpoint"
  1778. if ($SlsProject) { Msg " 项目: $SlsProject" " Project: $SlsProject" }
  1779. if ($SlsLogstore) { Msg " 日志库: $SlsLogstore" " Logstore: $SlsLogstore" }
  1780. Write-Host ""
  1781. }
  1782. Msg "命令:" "Commands:"
  1783. Write-Host " loongsuite-pilot # 查看状态 / Status"
  1784. Write-Host " loongsuite-pilot info # 版本与配置 / Version & config"
  1785. Write-Host ""
  1786. Msg "提示: 请新开一个终端后再使用 loongsuite-pilot 命令 (WDAC/受限环境可能需注销重登)。" `
  1787. "Tip: open a NEW terminal before using the loongsuite-pilot command (a WDAC/locked-down environment may require signing out and back in)."
  1788. Write-Host "============================================================"
  1789. }
  1790. # >>> pilot-restart-stale-collector >>>
  1791. # Displace a collector that outlived Stop-PilotService and therefore still serves the
  1792. # PREVIOUS version dir. `start` is deliberately a no-op when a collector is already
  1793. # running, and on a re-install one usually is: Stop-PilotService only ends the current
  1794. # task instance, and Task Scheduler (or the updater's own collector watchdog) relaunches
  1795. # it within seconds -- while `current` still names the old version dir, because
  1796. # Deploy-Package writes the new one only after Ensure-NodeModules. collector-daemon.js
  1797. # resolves `current` exactly once at startup, so that survivor keeps running the old
  1798. # dist forever, while `status` reads `current` and confidently reports the NEW version.
  1799. # Nothing crashes and nothing logs: the install says "Service started" and the bytes the
  1800. # user just installed are simply never loaded. Measured on a re-install where the
  1801. # survivor started 30s before the new version dir even existed.
  1802. #
  1803. # This became silent only once re-installs stopped overwriting the live version dir (pinned
  1804. # by tests/unit/deploy/installer-version-dir-not-overwritten.test.mjs): while Deploy-Package still
  1805. # did Remove-Item on it, the same survivor died with ERR_MODULE_NOT_FOUND and got restarted
  1806. # onto the new version, so the bug announced itself. Keeping the old dir is right; this is
  1807. # the other half of it.
  1808. #
  1809. # restart-collector (not restart) is what the updater uses after deploying a version: it
  1810. # stops the collector unconditionally, kills orphans, then re-registers and starts it, and
  1811. # it leaves the updater alone. Skipped when $priorVersion is empty -- a fresh install has
  1812. # no survivor to displace, and `start` just launched the collector from the new `current`.
  1813. #
  1814. # Skipped again when `start` did not say "already running". That line (Cmd-Start, off
  1815. # Get-CollectorRuntime or the pid file) is the only evidence a survivor was there; without
  1816. # it `start` launched the collector itself, from the new `current`, and there is nothing
  1817. # stale to displace. The bounce is not free either: replacing a task the running principal
  1818. # cannot write to is denied, and because callers treat a failed displacement as a failed
  1819. # deploy, an unnecessary one can roll back an upgrade whose collector had come up correctly.
  1820. # Callers pass the captured start output, hence Out-String -- it arrives as lines. Passing
  1821. # nothing would silently turn this whole block back into a no-op, so every call site has to
  1822. # pass a variable it filled from `start`, pinned by
  1823. # tests/unit/deploy/installer-restart-stale-collector.test.mjs.
  1824. #
  1825. # $serviceEntry is whichever entry point the caller already resolved: the .ps1 needs
  1826. # powershell.exe -File, the .cmd wrapper is invoked directly. Branching here rather than at
  1827. # the call sites keeps this block byte-identical across the three installers.
  1828. #
  1829. # Returns $true when there is nothing to displace or the displacement succeeded, $false with
  1830. # the reason in $script:PILOT_LAST_RESTART_ERR otherwise. Native commands do not throw on a
  1831. # nonzero exit, so $LASTEXITCODE is the only signal there is -- and discarding it put the
  1832. # failure right back where this block came from. Cmd-RestartCollector exits 1 when the node
  1833. # runtime cannot be resolved, when the bootstrap entry is missing, and when the service
  1834. # manager refuses to restart a non-degraded install; in every one of those the survivor is
  1835. # still running the OLD version dir. Callers must not print success on a $false: `status`
  1836. # resolves `current`, which the survivor answers to exactly as well as the new collector
  1837. # would, so "is running" cannot tell the two apart. That is the entire bug.
  1838. function Restart-StaleCollector {
  1839. param([string]$serviceEntry, [string]$priorVersion, $startOutput = "")
  1840. $script:PILOT_LAST_RESTART_ERR = ""
  1841. if (-not $priorVersion) { return $true }
  1842. if (-not $serviceEntry) { return $true }
  1843. if (-not (Test-Path $serviceEntry)) { return $true }
  1844. if (($startOutput | Out-String) -notmatch "already running") { return $true }
  1845. # Locally forced to Continue: with 2>&1 in effect a caller left on Stop turns the first
  1846. # stderr line into a NativeCommandError, which would report a successful restart as a
  1847. # failure. restart-collector writes progress to stderr on purpose.
  1848. $prevEAP = $ErrorActionPreference
  1849. $ErrorActionPreference = "Continue"
  1850. try {
  1851. if ($serviceEntry -match '\.ps1$') {
  1852. $restartOut = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $serviceEntry restart-collector 2>&1
  1853. } else {
  1854. $restartOut = & $serviceEntry restart-collector 2>&1
  1855. }
  1856. if ($LASTEXITCODE -eq 0) { return $true }
  1857. $script:PILOT_LAST_RESTART_ERR = "restart-collector (exit $LASTEXITCODE): $(($restartOut | Out-String).Trim())"
  1858. return $false
  1859. } catch {
  1860. $script:PILOT_LAST_RESTART_ERR = "restart-collector failed to run: $($_.Exception.Message)"
  1861. return $false
  1862. } finally {
  1863. $ErrorActionPreference = $prevEAP
  1864. }
  1865. }
  1866. # <<< pilot-restart-stale-collector <<<
  1867. # ============================================================
  1868. # Stop service by PID file
  1869. # ============================================================
  1870. function Stop-PilotService {
  1871. $pidFile = Join-Path $DataDir "loongsuite-pilot.pid"
  1872. if (Test-Path $pidFile) {
  1873. $oldPid = (Get-Content $pidFile -ErrorAction SilentlyContinue).Trim()
  1874. if ($oldPid) {
  1875. $proc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
  1876. if ($proc) {
  1877. Msg "==> 停止运行中的服务 (PID $oldPid)..." "==> Stopping running service (PID $oldPid)..."
  1878. Stop-Process -Id $oldPid -Force -ErrorAction SilentlyContinue
  1879. $count = 0
  1880. while ($count -lt 10) {
  1881. $proc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
  1882. if (-not $proc) { break }
  1883. Start-Sleep -Seconds 1
  1884. $count++
  1885. }
  1886. Msg " ✅ 已停止" " ✅ Stopped"
  1887. Write-Host ""
  1888. }
  1889. }
  1890. Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
  1891. }
  1892. # Also try the loongsuite-pilot command (use .ps1 directly to avoid cmd.exe popup)
  1893. $ps1Path = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
  1894. if (Test-Path $ps1Path) {
  1895. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  1896. & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ps1Path stop 2>$null
  1897. $ErrorActionPreference = $prevEAP
  1898. }
  1899. }
  1900. # >>> pilot-hold-tasks-during-deploy >>>
  1901. # Stop-PilotService only ends the current task instance. The updater task has a
  1902. # repeating trigger every 5 minutes plus RestartCount, so it comes back while
  1903. # Deploy-Package is still filling a versions/ directory that neither current nor
  1904. # previous names. gcOldVersions then deletes that directory. Disable-ScheduledTask
  1905. # writes Enabled=false on the task definition and actually holds that relaunch;
  1906. # Stop-ScheduledTask does not.
  1907. #
  1908. # Callers Disable BEFORE Stop-PilotService. Disable does not kill a running
  1909. # instance, so Stop is still required, but Stop-Process -Force while the task
  1910. # is still Enabled can arm RestartCount (collector interval is 1 minute).
  1911. # Closing the definition first means a stop cannot be scheduled as a restart.
  1912. #
  1913. # Disable is a write, so it can fail with Access is denied: a -RunLevel Limited
  1914. # task grants its own principal only Read, Synchronize, and an elevated first
  1915. # install leaves the tasks owned by Administrators (same ACL that makes uninstall
  1916. # fail to delete them). A failed disable must not abort the install. Track only
  1917. # names we actually disabled so Enable cannot turn on a task we never held.
  1918. #
  1919. # Enable lives in finally and is idempotent. Start stays on the success path: a
  1920. # failed postinstall must not launch a collector whose hooks were never written.
  1921. # Keep this block byte-identical across every .ps1 installer that carries it.
  1922. $script:PILOT_HELD_TASK_NAMES = @()
  1923. function Get-PilotDeployTaskNames {
  1924. $tag = Get-PilotUserTag
  1925. @("LoongsuitePilot-$tag", "LoongsuitePilotUpdater-$tag")
  1926. }
  1927. function Disable-PilotScheduledTasksDuringDeploy {
  1928. $script:PILOT_HELD_TASK_NAMES = @()
  1929. $taskFolder = "\LoongsuitePilot\"
  1930. foreach ($taskName in (Get-PilotDeployTaskNames)) {
  1931. $task = Get-ScheduledTask -TaskName $taskName -TaskPath $taskFolder -ErrorAction SilentlyContinue
  1932. if (-not $task) { continue }
  1933. $enabled = $true
  1934. try { $enabled = [bool]$task.Settings.Enabled } catch { $enabled = $true }
  1935. if (-not $enabled) { continue }
  1936. try {
  1937. Disable-ScheduledTask -TaskName $taskName -TaskPath $taskFolder -ErrorAction Stop | Out-Null
  1938. $script:PILOT_HELD_TASK_NAMES += $taskName
  1939. } catch {
  1940. Msg " ⚠️ 无法禁用计划任务 ${taskName}: $($_.Exception.Message)" `
  1941. " ⚠️ Could not disable scheduled task ${taskName}: $($_.Exception.Message)"
  1942. }
  1943. }
  1944. if (@($script:PILOT_HELD_TASK_NAMES).Count -gt 0) {
  1945. Msg " 已禁用计划任务(部署期间): $($script:PILOT_HELD_TASK_NAMES -join ', ')" `
  1946. " Disabled scheduled tasks for the deploy: $($script:PILOT_HELD_TASK_NAMES -join ', ')"
  1947. }
  1948. }
  1949. function Enable-PilotScheduledTasksAfterDeploy {
  1950. $taskFolder = "\LoongsuitePilot\"
  1951. $stillHeld = @()
  1952. foreach ($taskName in @($script:PILOT_HELD_TASK_NAMES)) {
  1953. try {
  1954. Enable-ScheduledTask -TaskName $taskName -TaskPath $taskFolder -ErrorAction Stop | Out-Null
  1955. } catch {
  1956. Msg " ⚠️ 无法重新启用计划任务 ${taskName}: $($_.Exception.Message)" `
  1957. " ⚠️ Could not re-enable scheduled task ${taskName}: $($_.Exception.Message)"
  1958. # Keep the name so finally can retry. Wiping the list here would
  1959. # make a failed success-path Enable a no-op on the way out.
  1960. $stillHeld += $taskName
  1961. }
  1962. }
  1963. $script:PILOT_HELD_TASK_NAMES = @($stillHeld)
  1964. }
  1965. # <<< pilot-hold-tasks-during-deploy <<<
  1966. # ============================================================
  1967. # GC old versions
  1968. # ============================================================
  1969. function GC-OldVersions {
  1970. $cacheDir = $CACHE_DIR
  1971. $versionsDir = Join-Path $cacheDir "versions"
  1972. $currentFile = Join-Path $cacheDir "current"
  1973. $previousFile = Join-Path $cacheDir "previous"
  1974. if (-not (Test-Path $versionsDir)) { return }
  1975. $keepCurrent = ""; $keepPrevious = ""
  1976. if (Test-Path $currentFile) { $keepCurrent = (Get-Content $currentFile -ErrorAction SilentlyContinue).Trim() }
  1977. if (Test-Path $previousFile) { $keepPrevious = (Get-Content $previousFile -ErrorAction SilentlyContinue).Trim() }
  1978. Get-ChildItem $versionsDir -Directory -ErrorAction SilentlyContinue | ForEach-Object {
  1979. if ($_.Name -ne $keepCurrent -and $_.Name -ne $keepPrevious) {
  1980. Remove-Item $_.FullName -Recurse -Force
  1981. }
  1982. }
  1983. }
  1984. # ============================================================
  1985. # Remove hook configs
  1986. # ============================================================
  1987. function Remove-HookConfigs {
  1988. $HOOK_MARKER = ".loongsuite-pilot"
  1989. $configs = @(
  1990. (Join-Path $env:USERPROFILE ".cursor\hooks.json"),
  1991. (Join-Path $env:USERPROFILE ".qoder\settings.json"),
  1992. (Join-Path $env:USERPROFILE ".qoder-cn\settings.json"),
  1993. (Join-Path $env:USERPROFILE ".qoderwork\settings.json"),
  1994. (Join-Path $env:USERPROFILE ".qoderworkcn\settings.json"),
  1995. (Join-Path $env:USERPROFILE ".qwenworkcn\settings.json"),
  1996. (Join-Path $env:USERPROFILE ".claude\settings.json"),
  1997. (Join-Path $env:USERPROFILE ".kiro\agents\pilot-kiro.json"),
  1998. (Join-Path $env:USERPROFILE ".qwen\settings.json"),
  1999. (Join-Path $env:USERPROFILE ".workbuddy\settings.json")
  2000. )
  2001. foreach ($cfg in $configs) {
  2002. if (-not (Test-Path $cfg)) { continue }
  2003. $short = $cfg.Replace($env:USERPROFILE, "~")
  2004. # Same guard Remove-OpenClawPlugin and Remove-OtelPlugin already carry, and the
  2005. # reason uninstall may now reach this function without a Node: without it the
  2006. # call below runs as & "" against a hook config that then goes unreported.
  2007. if (-not $script:NODE_BIN) {
  2008. Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2009. continue
  2010. }
  2011. # Saved and restored around the try, not inside it: a throw from the native call
  2012. # (an install-dir node-bin pin that no longer exists, say) used to skip the
  2013. # restore and leave the whole rest of uninstall running at "Continue", where the
  2014. # later fail-fast checks stop failing fast.
  2015. $prevEAP = $ErrorActionPreference
  2016. $ErrorActionPreference = "Continue"
  2017. try {
  2018. & $script:NODE_BIN -e @'
  2019. const fs = require('fs');
  2020. const cfg = process.argv[1];
  2021. const marker = process.argv[2];
  2022. try {
  2023. const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
  2024. const hooks = data.hooks;
  2025. if (!hooks || typeof hooks !== 'object') process.exit(0);
  2026. let changed = false;
  2027. for (const [event, entries] of Object.entries(hooks)) {
  2028. if (!Array.isArray(entries)) continue;
  2029. const filtered = entries.filter(e => {
  2030. const cmd = e.command || '';
  2031. const nested = Array.isArray(e.hooks) ? e.hooks : [];
  2032. const hasMarker = cmd.includes(marker) || nested.some(h => (h.command || '').includes(marker));
  2033. if (hasMarker) changed = true;
  2034. return !hasMarker;
  2035. });
  2036. if (filtered.length === 0) { delete hooks[event]; changed = true; }
  2037. else hooks[event] = filtered;
  2038. }
  2039. if (Object.keys(hooks).length === 0) {
  2040. delete data.hooks;
  2041. changed = true;
  2042. }
  2043. if (changed) {
  2044. fs.writeFileSync(cfg, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2045. }
  2046. } catch(e) { process.stderr.write(e.message); process.exit(1); }
  2047. '@ $cfg $HOOK_MARKER 2>$null
  2048. Msg " ✅ 已清理: $short" " ✅ Cleaned: $short"
  2049. } catch {
  2050. Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)"
  2051. } finally {
  2052. $ErrorActionPreference = $prevEAP
  2053. }
  2054. }
  2055. }
  2056. # Grok Build's hook file is Pilot-owned, but still preserve any third-party
  2057. # entries that may have been added to it. Stable script-name matching also
  2058. # works when Pilot was installed with a custom data directory.
  2059. function Remove-GrokBuildHookConfig {
  2060. $grokHome = if ($env:GROK_HOME) { $env:GROK_HOME } else { Join-Path $env:USERPROFILE ".grok" }
  2061. $cfg = Join-Path $grokHome "hooks\loongsuite-pilot.json"
  2062. $stateFile = Join-Path $DataDir "deployed-agents.json"
  2063. if ($script:NODE_BIN -and (Test-Path -LiteralPath $stateFile)) {
  2064. $prevEAP = $ErrorActionPreference
  2065. try {
  2066. $ErrorActionPreference = "Continue"
  2067. $persisted = & $script:NODE_BIN -e @'
  2068. const fs = require("fs");
  2069. const path = require("path");
  2070. try {
  2071. const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  2072. const value = state?.["grok-build"]?.hookSettingsPath;
  2073. if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
  2074. } catch {}
  2075. '@ $stateFile 2>$null
  2076. } finally {
  2077. $ErrorActionPreference = $prevEAP
  2078. }
  2079. if ($persisted) { $cfg = [string]$persisted }
  2080. }
  2081. if (-not (Test-Path -LiteralPath $cfg)) { return }
  2082. if (-not $script:NODE_BIN) {
  2083. Msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (无 Node.js,请手动清理 Grok Build Pilot hook)" `
  2084. " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (Node.js unavailable; remove the Grok Build Pilot hook manually)"
  2085. return
  2086. }
  2087. $prevEAP = $ErrorActionPreference
  2088. $ErrorActionPreference = "Continue"
  2089. $result = & $script:NODE_BIN -e @'
  2090. const fs = require("fs");
  2091. const cfg = process.argv[1];
  2092. const owned = value => typeof value === "string"
  2093. && /(?:^|[\\/])grok-build-loongsuite-pilot-hook\.(?:sh|ps1)(?:"|\s|$)/i.test(value);
  2094. try {
  2095. const data = JSON.parse(fs.readFileSync(cfg, "utf8"));
  2096. const hooks = data && typeof data.hooks === "object" && data.hooks ? data.hooks : null;
  2097. if (!hooks) { process.stdout.write("nochange"); process.exit(0); }
  2098. let changed = false;
  2099. for (const [event, entries] of Object.entries(hooks)) {
  2100. if (!Array.isArray(entries)) continue;
  2101. const kept = [];
  2102. for (const entry of entries) {
  2103. if (owned(entry && entry.command)) { changed = true; continue; }
  2104. if (entry && Array.isArray(entry.hooks)) {
  2105. const nested = entry.hooks.filter(hook => !owned(hook && hook.command));
  2106. if (nested.length !== entry.hooks.length) changed = true;
  2107. if (entry.hooks.length > 0 && nested.length === 0) continue;
  2108. kept.push({ ...entry, hooks: nested });
  2109. } else {
  2110. kept.push(entry);
  2111. }
  2112. }
  2113. if (kept.length === 0) delete hooks[event];
  2114. else hooks[event] = kept;
  2115. }
  2116. if (!changed) { process.stdout.write("nochange"); process.exit(0); }
  2117. if (Object.keys(hooks).length === 0) delete data.hooks;
  2118. if (Object.keys(data).length === 0) {
  2119. fs.unlinkSync(cfg);
  2120. } else {
  2121. const tmp = `${cfg}.${process.pid}.tmp`;
  2122. fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
  2123. fs.renameSync(tmp, cfg);
  2124. }
  2125. process.stdout.write("cleaned");
  2126. } catch (error) {
  2127. process.stderr.write(error.message); process.exit(1);
  2128. }
  2129. '@ $cfg 2>$null
  2130. $exitCode = $LASTEXITCODE
  2131. $ErrorActionPreference = $prevEAP
  2132. $result = ([string]($result -join "")).Trim()
  2133. if ($exitCode -eq 0 -and $result -in @("cleaned", "nochange")) {
  2134. Msg " ✅ 已清理: ~/.grok/hooks/loongsuite-pilot.json" `
  2135. " ✅ Cleaned: ~/.grok/hooks/loongsuite-pilot.json"
  2136. } else {
  2137. Msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (需手动清理)" `
  2138. " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (manual cleanup needed)"
  2139. }
  2140. }
  2141. # ============================================================
  2142. # Remove plugin-inject specs (OpenCode)
  2143. # ============================================================
  2144. # OpenCode uses deployMode "plugin-inject": a spec is written into its own
  2145. # config file's plugin array, not a shared settings.json. Remove-HookConfigs
  2146. # does not cover it, so clean it here to avoid a dangling spec.
  2147. function Remove-OpenCodePlugin {
  2148. $configs = @(
  2149. (Join-Path $env:USERPROFILE ".config\opencode\opencode.jsonc"),
  2150. (Join-Path $env:USERPROFILE ".config\opencode\opencode.json"),
  2151. (Join-Path $env:USERPROFILE ".config\opencode\config.json")
  2152. )
  2153. foreach ($cfg in $configs) {
  2154. if (-not (Test-Path $cfg)) { continue }
  2155. $short = $cfg.Replace($env:USERPROFILE, "~")
  2156. if (-not $script:NODE_BIN) {
  2157. Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2158. continue
  2159. }
  2160. $result = & $script:NODE_BIN -e @'
  2161. const fs = require('fs');
  2162. const f = process.argv[1];
  2163. // Match legacy plugins/opencode/plugin.mjs only under this installation.
  2164. const normalize = value => {
  2165. if (typeof value !== 'string') return '';
  2166. let plain = value;
  2167. if (plain.startsWith('file://')) {
  2168. try {
  2169. const url = new URL(plain);
  2170. plain = decodeURIComponent(url.pathname);
  2171. if (plain[0] === '/' && plain[2] === ':') plain = plain.slice(1);
  2172. if (url.hostname && url.hostname !== 'localhost') {
  2173. if (process.platform !== 'win32') return '';
  2174. plain = '//' + url.hostname + plain;
  2175. }
  2176. } catch { return ''; }
  2177. }
  2178. plain = plain.split(String.fromCharCode(92)).join('/');
  2179. while (plain.endsWith('/')) plain = plain.slice(0, -1);
  2180. return process.platform === 'win32' ? plain.toLowerCase() : plain;
  2181. };
  2182. const dataDir = normalize(process.argv[2]);
  2183. const managed = dataDir ? dataDir + '/plugins/opencode' : null;
  2184. const isOurs = s => typeof s === 'string' && (
  2185. s === 'loongsuite-pilot-opencode' || s.startsWith('loongsuite-pilot-opencode@') ||
  2186. (managed !== null && (normalize(s) === managed || normalize(s) === managed + '/plugin.mjs'))
  2187. );
  2188. const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : (e?.package ?? ''));
  2189. const stripJsonc = src => src
  2190. .replace(/\/\*[\s\S]*?\*\//g, '')
  2191. .replace(/^\s*\/\/.*$/gm, '')
  2192. .replace(/[ \t]+\/\/.*$/gm, '');
  2193. try {
  2194. const raw = fs.readFileSync(f, 'utf-8');
  2195. let data, hadComments = false;
  2196. try { data = JSON.parse(raw); }
  2197. catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
  2198. let removed = 0;
  2199. for (const key of ['plugin', 'plugins']) {
  2200. if (!Array.isArray(data[key])) continue;
  2201. const before = data[key].length;
  2202. data[key] = data[key].filter(e => !isOurs(entryStr(e)));
  2203. removed += before - data[key].length;
  2204. }
  2205. if (!removed) { process.stdout.write('nochange'); process.exit(0); }
  2206. if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
  2207. fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2208. process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
  2209. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2210. '@ $cfg $DataDir 2>$null
  2211. switch ($result) {
  2212. "cleaned" { Msg " ✅ 已清理: $short" " ✅ Cleaned: $short" }
  2213. "cleaned-bak" { Msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" }
  2214. "nochange" { }
  2215. default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
  2216. }
  2217. }
  2218. }
  2219. function Remove-HermesPlugin {
  2220. $hermesHome = if ($env:HERMES_HOME) { $env:HERMES_HOME } else { Join-Path $env:USERPROFILE ".hermes" }
  2221. $pluginDir = Join-Path $hermesHome "plugins\loongsuite-pilot"
  2222. $stateFile = Join-Path $DataDir "deployed-agents.json"
  2223. if (Test-Path $stateFile) {
  2224. try {
  2225. $state = Get-Content $stateFile -Raw | ConvertFrom-Json
  2226. $recorded = $state.'hermes-agent'.targetDir
  2227. if ($recorded -and [System.IO.Path]::IsPathRooted([string]$recorded)) {
  2228. $pluginDir = [string]$recorded
  2229. }
  2230. } catch {
  2231. # Fall back to the current HERMES_HOME-derived path.
  2232. }
  2233. }
  2234. $marker = Join-Path $pluginDir ".loongsuite-pilot-managed.json"
  2235. if (-not (Test-Path $marker)) { return }
  2236. try {
  2237. $meta = Get-Content $marker -Raw | ConvertFrom-Json
  2238. if ($meta.owner -ne "loongsuite-pilot" -or $meta.agentId -ne "hermes-agent") {
  2239. Msg " ⚠️ 保留未受 Pilot 管理的 Hermes 插件: $pluginDir" `
  2240. " ⚠️ Preserved unmanaged Hermes plugin: $pluginDir"
  2241. return
  2242. }
  2243. $hermesCli = if ($env:HERMES_CLI) {
  2244. $env:HERMES_CLI
  2245. } else {
  2246. Join-Path $hermesHome "hermes-agent\venv\Scripts\hermes.exe"
  2247. }
  2248. if (-not (Test-Path $hermesCli)) {
  2249. $hermesCommand = Get-Command hermes -ErrorAction SilentlyContinue
  2250. if ($hermesCommand) { $hermesCli = $hermesCommand.Source }
  2251. }
  2252. if (Test-Path $hermesCli) {
  2253. & $hermesCli plugins disable loongsuite-pilot *> $null
  2254. }
  2255. Remove-Item $pluginDir -Recurse -Force
  2256. Msg " ✅ 已清理: $pluginDir" " ✅ Cleaned: $pluginDir"
  2257. } catch {
  2258. Msg " ⚠️ 跳过: $pluginDir (需手动清理)" `
  2259. " ⚠️ Skipped: $pluginDir (manual cleanup needed)"
  2260. }
  2261. }
  2262. # ============================================================
  2263. # Remove Pi Coding Agent extension injection
  2264. # ============================================================
  2265. function Remove-PiCodingAgentExtension {
  2266. $piAgentDir = if ($env:PI_CODING_AGENT_DIR) { $env:PI_CODING_AGENT_DIR } else { Join-Path $env:USERPROFILE ".pi\agent" }
  2267. $cfg = Join-Path $piAgentDir "settings.json"
  2268. $stateFile = Join-Path $DataDir "deployed-agents.json"
  2269. if ($script:NODE_BIN -and (Test-Path -LiteralPath $stateFile)) {
  2270. $prevEAP = $ErrorActionPreference
  2271. try {
  2272. $ErrorActionPreference = "Continue"
  2273. $persisted = & $script:NODE_BIN -e @'
  2274. const fs = require("fs");
  2275. const path = require("path");
  2276. try {
  2277. const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  2278. const value = state?.["pi-coding-agent"]?.pluginInjectConfigPath;
  2279. if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
  2280. } catch {}
  2281. '@ $stateFile 2>$null
  2282. } finally {
  2283. $ErrorActionPreference = $prevEAP
  2284. }
  2285. if ($persisted) { $cfg = [string]$persisted }
  2286. }
  2287. $short = $cfg.Replace($env:USERPROFILE, "~")
  2288. if (-not $script:NODE_BIN) {
  2289. Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2290. return
  2291. }
  2292. $result = & $script:NODE_BIN -e @'
  2293. const fs = require('fs');
  2294. const path = require('path');
  2295. const defaultConfig = process.argv[1];
  2296. const dataDir = process.argv[2];
  2297. const targets = [{ configPath: defaultConfig, markers: ['loongsuite-pilot-pi-coding-agent', 'plugins/pi-coding-agent/index.mjs'] }];
  2298. const resolveValue = value => typeof value === 'string'
  2299. ? value.replace(/^~(?=[\\/])/, process.env.USERPROFILE || '').replaceAll('$PILOT_DATA', dataDir)
  2300. : value;
  2301. const stripJsoncComments = text => {
  2302. let result = '';
  2303. let index = 0;
  2304. let inString = false;
  2305. let escape = false;
  2306. while (index < text.length) {
  2307. const ch = text[index];
  2308. if (inString) {
  2309. result += ch;
  2310. if (escape) escape = false;
  2311. else if (ch.charCodeAt(0) === 92) escape = true;
  2312. else if (ch === '"') inString = false;
  2313. index++;
  2314. continue;
  2315. }
  2316. if (ch === '"') {
  2317. inString = true;
  2318. result += ch;
  2319. index++;
  2320. continue;
  2321. }
  2322. if (ch === '/' && text[index + 1] === '/') {
  2323. index += 2;
  2324. while (index < text.length && text[index] !== '\n') index++;
  2325. continue;
  2326. }
  2327. if (ch === '/' && text[index + 1] === '*') {
  2328. index += 2;
  2329. while (index + 1 < text.length && !(text[index] === '*' && text[index + 1] === '/')) index++;
  2330. index += 2;
  2331. continue;
  2332. }
  2333. result += ch;
  2334. index++;
  2335. }
  2336. return result;
  2337. };
  2338. const comparable = value => typeof value === 'string'
  2339. ? value.split(String.fromCharCode(92)).join('/')
  2340. : '';
  2341. const localDir = path.join(dataDir, 'agents.d.local');
  2342. try {
  2343. for (const name of fs.existsSync(localDir) ? fs.readdirSync(localDir) : []) {
  2344. if (!name.endsWith('.json')) continue;
  2345. let def;
  2346. try { def = JSON.parse(fs.readFileSync(path.join(localDir, name), 'utf8')); } catch { continue; }
  2347. if (def?.piSdk?.schemaVersion !== 1 || !def?.pluginInject?.pluginId?.startsWith('loongsuite-pilot-pi-sdk-')) continue;
  2348. const spec = resolveValue(def.pluginInject.pluginSpec);
  2349. for (const configPath of def.pluginInject.configPaths || []) {
  2350. targets.push({
  2351. configPath: resolveValue(configPath),
  2352. markers: [def.pluginInject.pluginId, spec, 'plugins/pi-coding-agent/agents/'].filter(Boolean),
  2353. });
  2354. }
  2355. }
  2356. let cleaned = 0;
  2357. let skipped = 0;
  2358. for (const target of targets) {
  2359. if (!target.configPath || !fs.existsSync(target.configPath)) continue;
  2360. try {
  2361. const raw = fs.readFileSync(target.configPath, 'utf-8');
  2362. const data = JSON.parse(stripJsoncComments(raw));
  2363. if (!Array.isArray(data.extensions)) continue;
  2364. const before = data.extensions.length;
  2365. data.extensions = data.extensions.filter(entry => {
  2366. const value = comparable(entry);
  2367. return !target.markers.some(marker => value === comparable(marker) || value.includes(comparable(marker)));
  2368. });
  2369. if (data.extensions.length === before) continue;
  2370. if (raw !== JSON.stringify(data, null, 2) + '\n') {
  2371. try {
  2372. fs.copyFileSync(target.configPath, target.configPath + '.bak', fs.constants.COPYFILE_EXCL);
  2373. } catch (e) {
  2374. if (e?.code !== 'EEXIST') throw e;
  2375. }
  2376. }
  2377. fs.writeFileSync(target.configPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2378. cleaned++;
  2379. } catch {
  2380. skipped++;
  2381. }
  2382. }
  2383. process.stdout.write(cleaned > 0 ? (skipped > 0 ? 'partial' : 'cleaned') : (skipped > 0 ? 'skipped' : 'nochange'));
  2384. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2385. '@ $cfg $DATA_DIR 2>$null
  2386. switch ($result) {
  2387. "cleaned" { Msg " ✅ 已清理 Pi / PI SDK Agent 扩展配置" " ✅ Cleaned Pi / PI SDK Agent extension configs" }
  2388. "partial" { Msg " ⚠️ 已清理可读取的 Pi 配置,部分损坏配置需手动清理" `
  2389. " ⚠️ Cleaned readable Pi configs; some invalid configs need manual cleanup" }
  2390. "skipped" { Msg " ⚠️ Pi 配置损坏,需手动清理" " ⚠️ Invalid Pi configs skipped (manual cleanup needed)" }
  2391. "nochange" { }
  2392. default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
  2393. }
  2394. }
  2395. # ============================================================
  2396. # Remove plugin-inject specs (MiMo Code)
  2397. # ============================================================
  2398. # MiMo Code uses deployMode "plugin-inject": a spec is written into its own
  2399. # config file's plugin array. Same shape as Remove-OpenCodePlugin but for
  2400. # ~/.config/mimocode/mimocode.json[c]. Without this, the spec survives
  2401. # uninstall and points at a (possibly purged) plugin.mjs.
  2402. function Remove-MimoCodePlugin {
  2403. $configs = @(
  2404. (Join-Path $env:USERPROFILE ".config\mimocode\mimocode.jsonc"),
  2405. (Join-Path $env:USERPROFILE ".config\mimocode\mimocode.json")
  2406. )
  2407. foreach ($cfg in $configs) {
  2408. if (-not (Test-Path $cfg)) { continue }
  2409. $short = $cfg.Replace($env:USERPROFILE, "~")
  2410. if (-not $script:NODE_BIN) {
  2411. Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2412. continue
  2413. }
  2414. $result = & $script:NODE_BIN -e @'
  2415. const fs = require('fs');
  2416. const f = process.argv[1];
  2417. const isOurs = s => typeof s === 'string' && (s.includes('loongsuite-pilot-mimo-code') || s.includes('plugins/mimo-code/plugin.mjs'));
  2418. const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : '');
  2419. const stripJsonc = src => src
  2420. .replace(/\/\*[\s\S]*?\*\//g, '')
  2421. .replace(/^\s*\/\/.*$/gm, '')
  2422. .replace(/[ \t]+\/\/.*$/gm, '');
  2423. try {
  2424. const raw = fs.readFileSync(f, 'utf-8');
  2425. let data, hadComments = false;
  2426. try { data = JSON.parse(raw); }
  2427. catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
  2428. const key = Array.isArray(data.plugins) ? 'plugins' : (Array.isArray(data.plugin) ? 'plugin' : null);
  2429. if (!key) { process.stdout.write('nochange'); process.exit(0); }
  2430. const before = data[key].length;
  2431. data[key] = data[key].filter(e => !isOurs(entryStr(e)));
  2432. if (data[key].length === before) { process.stdout.write('nochange'); process.exit(0); }
  2433. if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
  2434. fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2435. process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
  2436. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2437. '@ $cfg 2>$null
  2438. switch ($result) {
  2439. "cleaned" { Msg " ✅ 已清理: $short" " ✅ Cleaned: $short" }
  2440. "cleaned-bak" { Msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" }
  2441. "nochange" { }
  2442. default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
  2443. }
  2444. }
  2445. }
  2446. # ============================================================
  2447. # Remove OpenClaw's nested plugin entry and load path.
  2448. # ============================================================
  2449. function Remove-OpenClawPlugin {
  2450. $stateDir = if ($env:OPENCLAW_STATE_DIR) {
  2451. $env:OPENCLAW_STATE_DIR
  2452. } else {
  2453. Join-Path $env:USERPROFILE ".openclaw"
  2454. }
  2455. $configs = @()
  2456. if ($env:OPENCLAW_CONFIG_PATH) { $configs += $env:OPENCLAW_CONFIG_PATH }
  2457. $configs += @(
  2458. (Join-Path $stateDir "openclaw.json"),
  2459. (Join-Path $stateDir "config.json"),
  2460. (Join-Path $env:USERPROFILE ".openclaw\openclaw.json"),
  2461. (Join-Path $env:USERPROFILE ".openclaw\config.json")
  2462. )
  2463. $managedPath = Join-Path $DataDir "plugins\openclaw"
  2464. $cleanupScript = @'
  2465. const fs = require('fs');
  2466. const f = process.env.PILOT_OC_CONFIG;
  2467. const managed = process.env.PILOT_OC_MANAGED.replaceAll('\\', '/');
  2468. const entryStr = value => typeof value === 'string'
  2469. ? value
  2470. : (Array.isArray(value) && typeof value[0] === 'string' ? value[0] : '');
  2471. const isOurs = value => {
  2472. const normalized = entryStr(value).replaceAll('\\', '/');
  2473. const plain = normalized.startsWith('file://') ? normalized.slice('file://'.length) : normalized;
  2474. return plain === managed ||
  2475. plain === managed + '/plugin.mjs' ||
  2476. normalized.includes('loongsuite-pilot-openclaw') ||
  2477. normalized.includes('plugins/openclaw/plugin.mjs') && plain.includes('.loongsuite-pilot/');
  2478. };
  2479. try {
  2480. const data = JSON.parse(fs.readFileSync(f, 'utf-8'));
  2481. let changed = false;
  2482. for (const key of ['plugin', 'plugins']) {
  2483. if (!Array.isArray(data[key])) continue;
  2484. const filtered = data[key].filter(value => !isOurs(value));
  2485. if (filtered.length !== data[key].length) { data[key] = filtered; changed = true; }
  2486. }
  2487. const plugins = data.plugins && typeof data.plugins === 'object' && !Array.isArray(data.plugins)
  2488. ? data.plugins
  2489. : null;
  2490. if (plugins) {
  2491. if (plugins.load && typeof plugins.load === 'object' && Array.isArray(plugins.load.paths)) {
  2492. const filtered = plugins.load.paths.filter(value => !isOurs(value));
  2493. if (filtered.length !== plugins.load.paths.length) { plugins.load.paths = filtered; changed = true; }
  2494. }
  2495. if (plugins.entries && typeof plugins.entries === 'object' && !Array.isArray(plugins.entries) &&
  2496. Object.prototype.hasOwnProperty.call(plugins.entries, 'loongsuite-pilot-openclaw')) {
  2497. delete plugins.entries['loongsuite-pilot-openclaw'];
  2498. changed = true;
  2499. }
  2500. }
  2501. if (!changed) { process.stdout.write('nochange'); process.exit(0); }
  2502. fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2503. process.stdout.write('cleaned');
  2504. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2505. '@
  2506. foreach ($cfg in ($configs | Select-Object -Unique)) {
  2507. if (-not (Test-Path $cfg)) { continue }
  2508. $short = $cfg.Replace($env:USERPROFILE, "~")
  2509. if (-not $script:NODE_BIN) {
  2510. Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2511. continue
  2512. }
  2513. $hadConfigEnv = Test-Path Env:PILOT_OC_CONFIG
  2514. $hadManagedEnv = Test-Path Env:PILOT_OC_MANAGED
  2515. $previousConfigEnv = $env:PILOT_OC_CONFIG
  2516. $previousManagedEnv = $env:PILOT_OC_MANAGED
  2517. try {
  2518. $env:PILOT_OC_CONFIG = $cfg
  2519. $env:PILOT_OC_MANAGED = $managedPath
  2520. $result = $cleanupScript | & $script:NODE_BIN 2>$null
  2521. if ($LASTEXITCODE -ne 0) { $result = "error" }
  2522. } finally {
  2523. if ($hadConfigEnv) { $env:PILOT_OC_CONFIG = $previousConfigEnv }
  2524. else { Remove-Item Env:PILOT_OC_CONFIG -ErrorAction SilentlyContinue }
  2525. if ($hadManagedEnv) { $env:PILOT_OC_MANAGED = $previousManagedEnv }
  2526. else { Remove-Item Env:PILOT_OC_MANAGED -ErrorAction SilentlyContinue }
  2527. }
  2528. switch ($result) {
  2529. "cleaned" { Msg " ✅ 已清理: $short" " ✅ Cleaned: $short" }
  2530. "nochange" { }
  2531. default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
  2532. }
  2533. }
  2534. }
  2535. # ============================================================
  2536. # Remove legacy Claude OTel plugin
  2537. # ============================================================
  2538. function Remove-OtelPlugin {
  2539. $OTEL_CLAUDE_DIR = Join-Path $env:USERPROFILE ".cache\opentelemetry.instrumentation.claude"
  2540. # Clean Claude settings.json hooks
  2541. $claudeSettings = Join-Path $env:USERPROFILE ".claude\settings.json"
  2542. if ((Test-Path $claudeSettings) -and $script:NODE_BIN) {
  2543. $content = Get-Content $claudeSettings -Raw -ErrorAction SilentlyContinue
  2544. if ($content -match "otel-claude-hook|hook-entry") {
  2545. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  2546. & $script:NODE_BIN -e @'
  2547. const fs = require('fs');
  2548. const f = process.argv[1];
  2549. const isOurs = c => c.includes('otel-claude-hook') || c.includes('hook-entry.sh');
  2550. try {
  2551. const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
  2552. if (d && d.hooks) {
  2553. for (const ev of Object.keys(d.hooks)) {
  2554. if (!Array.isArray(d.hooks[ev])) continue;
  2555. d.hooks[ev] = d.hooks[ev].map(m => {
  2556. if (!Array.isArray(m.hooks)) return m;
  2557. m.hooks = m.hooks.filter(h => !(h.command && isOurs(h.command)));
  2558. return m.hooks.length > 0 ? m : null;
  2559. }).filter(Boolean);
  2560. if (d.hooks[ev].length === 0) delete d.hooks[ev];
  2561. }
  2562. if (Object.keys(d.hooks).length === 0) delete d.hooks;
  2563. fs.writeFileSync(f, JSON.stringify(d, null, 2) + '\n');
  2564. }
  2565. } catch {}
  2566. '@ $claudeSettings 2>$null
  2567. $ErrorActionPreference = $prevEAP
  2568. Msg " ✅ settings.json hooks 已清理" " ✅ settings.json hooks cleaned"
  2569. }
  2570. }
  2571. # Remove plugin directories
  2572. foreach ($dir in @($OTEL_CLAUDE_DIR)) {
  2573. if (Test-Path $dir) {
  2574. if ($Purge) {
  2575. Remove-Item $dir -Recurse -Force
  2576. Msg " ✅ 插件目录已完全删除 (--Purge): $dir" " ✅ Plugin directory fully removed (-Purge): $dir"
  2577. } else {
  2578. Get-ChildItem $dir -ErrorAction SilentlyContinue |
  2579. Where-Object { $_.Name -ne "sessions" } |
  2580. ForEach-Object { Remove-Item $_.FullName -Recurse -Force }
  2581. Msg " ✅ 插件文件已删除(sessions/ 已保留)" " ✅ Plugin files removed (sessions/ preserved)"
  2582. }
  2583. }
  2584. }
  2585. }
  2586. function Start-PilotAndWait {
  2587. param(
  2588. [Parameter(Mandatory = $true)]
  2589. [string]$ScriptPath,
  2590. [string]$PriorVersion = "",
  2591. [int]$TimeoutSeconds = 30
  2592. )
  2593. if (-not (Test-Path -LiteralPath $ScriptPath)) { return $false }
  2594. $prevEAP = $ErrorActionPreference
  2595. $ErrorActionPreference = "Continue"
  2596. $startOutput = & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $ScriptPath start 2>&1
  2597. $startExit = $LASTEXITCODE
  2598. $startOutput | ForEach-Object { Write-Host $_ }
  2599. $staleOk = Restart-StaleCollector $ScriptPath $PriorVersion $startOutput
  2600. if (-not $staleOk) {
  2601. Write-Host " $script:PILOT_LAST_RESTART_ERR" -ForegroundColor Yellow
  2602. }
  2603. $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
  2604. do {
  2605. $statusOutput = & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $ScriptPath status 2>$null
  2606. if ($statusOutput -match "is running") {
  2607. $ErrorActionPreference = $prevEAP
  2608. # Deliberately $staleOk, not $true: a collector that outlived the deploy answers
  2609. # "is running" from the old version dir just as convincingly as the new one.
  2610. return $staleOk
  2611. }
  2612. Start-Sleep -Seconds 2
  2613. } while ((Get-Date) -lt $deadline)
  2614. $ErrorActionPreference = $prevEAP
  2615. if ($startExit -ne 0) {
  2616. Write-Host " start command exited with code $startExit" -ForegroundColor Yellow
  2617. }
  2618. return $false
  2619. }
  2620. # ============================================================
  2621. # CMD: install
  2622. # ============================================================
  2623. function Assert-SingleSlsConfig {
  2624. $configFile = Join-Path $DataDir "config.json"
  2625. if (-not (Test-Path -LiteralPath $configFile)) { return }
  2626. $prevEAP = $ErrorActionPreference
  2627. $configExit = 1
  2628. $global:LASTEXITCODE = 1
  2629. $nodeOut = $null
  2630. try {
  2631. $ErrorActionPreference = "Continue"
  2632. $nodeOut = & $script:NODE_BIN -e @'
  2633. const fs = require("fs");
  2634. try {
  2635. const config = JSON.parse(fs.readFileSync(process.argv[1], "utf8").replace(/^\uFEFF/, ""));
  2636. process.exit(Array.isArray(config?.sls) ? 12 : 0);
  2637. } catch { process.exit(13); }
  2638. '@ $configFile 2>&1
  2639. $configExit = $global:LASTEXITCODE
  2640. } finally {
  2641. $ErrorActionPreference = $prevEAP
  2642. }
  2643. if ($configExit -eq 12) {
  2644. Msg "❌ 配置包含多个 SLS flusher;安装器不支持修改,请手动编辑 config.json" `
  2645. "❌ Multiple SLS flushers found; the installer cannot modify them. Edit config.json manually."
  2646. exit 1
  2647. }
  2648. if ($configExit -ne 0) {
  2649. $detail = (($nodeOut | Out-String).Trim())
  2650. Msg "❌ 无法检查现有 config.json,请检查文件后重试`n$detail" `
  2651. "❌ Cannot inspect existing config.json; check the file and retry.`n$detail"
  2652. exit 1
  2653. }
  2654. }
  2655. function Cmd-Install {
  2656. Msg "==> 开始安装 $PACKAGE_NAME ..." "==> Installing $PACKAGE_NAME ..."
  2657. Write-Host ""
  2658. # Before anything is downloaded or registered, so Ctrl+C is still cheap.
  2659. Warn-ElevatedInstall
  2660. Check-Deps
  2661. Assert-SingleSlsConfig
  2662. Migrate-LegacyLayout
  2663. $curVer = Get-InstalledVersion
  2664. if ($curVer) {
  2665. Msg "⚠️ 检测到已安装版本 v${curVer},将执行重新安装" "⚠️ Existing installation v${curVer} detected, re-installing"
  2666. Write-Host ""
  2667. }
  2668. try {
  2669. Disable-PilotScheduledTasksDuringDeploy
  2670. Stop-PilotService
  2671. Download-AndExtract
  2672. Probe-Agents
  2673. Select-Agents
  2674. Prompt-UserId
  2675. Confirm-ConfigOverwrite
  2676. Deploy-Package $script:INSTALL_SRC
  2677. # Nothing downstream can repair this: postinstall.js is the only thing that fills
  2678. # $DataDir\{hooks,skills,plugins}, and a collector with no hooks collects nothing.
  2679. # Better to stop with the reason on screen than to finish and report success.
  2680. if ($script:PILOT_POSTINSTALL_ERR) {
  2681. Msg "❌ 安装中止:$script:PILOT_POSTINSTALL_ERR" `
  2682. "❌ Install aborted: $script:PILOT_POSTINSTALL_ERR"
  2683. Msg " 请检查上方输出后重试安装" " Check the output above and re-run the install"
  2684. exit 1
  2685. }
  2686. Write-Config
  2687. Install-Command
  2688. Retire-QoderworkRuntimeOverrides
  2689. Enable-PilotScheduledTasksAfterDeploy
  2690. Msg "==> 启动服务..." "==> Starting service..."
  2691. $ps1Path = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
  2692. $started = Start-PilotAndWait -ScriptPath $ps1Path -PriorVersion $curVer
  2693. if (-not $started) {
  2694. if ($curVer -and (Test-Path (Join-Path $CACHE_DIR "previous"))) {
  2695. Msg "⚠️ 新安装未产生运行心跳,正在恢复 previous 版本..." `
  2696. "⚠️ The new installation produced no runtime heartbeat; restoring the previous version..."
  2697. $prevEAP = $ErrorActionPreference
  2698. $ErrorActionPreference = "Continue"
  2699. & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $ps1Path rollback 2>$null
  2700. $ErrorActionPreference = $prevEAP
  2701. }
  2702. throw "Collector failed to produce a runtime heartbeat after installation."
  2703. }
  2704. Msg " ✅ 服务已启动" " ✅ Service started"
  2705. Write-Host ""
  2706. Print-Summary "install"
  2707. } finally {
  2708. Enable-PilotScheduledTasksAfterDeploy
  2709. Remove-PilotPathQuietly $script:TMP_DIR
  2710. }
  2711. }
  2712. # ============================================================
  2713. # CMD: upgrade
  2714. # ============================================================
  2715. function Cmd-Upgrade {
  2716. Msg "==> 开始升级 $PACKAGE_NAME ..." "==> Upgrading $PACKAGE_NAME ..."
  2717. Write-Host ""
  2718. Migrate-LegacyLayout
  2719. $oldVer = Get-InstalledVersion
  2720. if (-not $oldVer) {
  2721. Msg "❌ 未检测到已安装的 loongsuite-pilot,请先执行 install" `
  2722. "❌ No existing installation found. Please run install first."
  2723. exit 1
  2724. }
  2725. Msg " 当前版本: $oldVer" " Current version: $oldVer"
  2726. Write-Host ""
  2727. Check-Deps
  2728. try {
  2729. Download-AndExtract
  2730. $newVer = Get-VersionFromDir $script:INSTALL_SRC
  2731. $newCommit = Get-CommitFromDir $script:INSTALL_SRC
  2732. $oldCommit = Get-CommitFromDir $script:PERMANENT_DIR
  2733. if ($newVer -and $newVer -eq $oldVer -and $newCommit -eq $oldCommit) {
  2734. Msg "✅ 已是最新版本 v${newVer} (${newCommit}),无需升级" `
  2735. "✅ Already at latest version v${newVer} (${newCommit}), nothing to do"
  2736. exit 0
  2737. }
  2738. Msg " 新版本: ${newVer} (${newCommit})" " New version: ${newVer} (${newCommit})"
  2739. Write-Host ""
  2740. Msg "==> 停止服务..." "==> Stopping service..."
  2741. Disable-PilotScheduledTasksDuringDeploy
  2742. Stop-PilotService
  2743. Write-Host ""
  2744. Deploy-Package $script:INSTALL_SRC
  2745. Install-Command
  2746. Retire-QoderworkRuntimeOverrides
  2747. Enable-PilotScheduledTasksAfterDeploy
  2748. Msg "==> 启动新版本..." "==> Starting new version..."
  2749. $ps1Path = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
  2750. # A failed postinstall is a failed upgrade: no point starting the new version, and the
  2751. # rollback below is what keeps `current` on a version whose assets are known complete.
  2752. $started = $false
  2753. if ($script:PILOT_POSTINSTALL_ERR) {
  2754. Msg " ❌ Hook 脚本部署失败: $script:PILOT_POSTINSTALL_ERR" `
  2755. " ❌ Hook script deployment failed: $script:PILOT_POSTINSTALL_ERR"
  2756. } else {
  2757. $started = Start-PilotAndWait -ScriptPath $ps1Path -PriorVersion $oldVer
  2758. }
  2759. if ($started) {
  2760. Msg " ✅ 新版本启动成功" " ✅ New version started successfully"
  2761. Write-Host ""
  2762. GC-OldVersions
  2763. Print-Summary "upgrade"
  2764. }
  2765. if (-not $started) {
  2766. Write-Host ""
  2767. Msg "⚠️ 新版本启动失败,正在回滚..." "⚠️ New version failed to start, rolling back..."
  2768. if (Test-Path $ps1Path) {
  2769. $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
  2770. & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ps1Path stop 2>$null
  2771. & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ps1Path rollback 2>$null
  2772. $ErrorActionPreference = $prevEAP
  2773. }
  2774. Msg "❌ 升级失败,已回滚到 v${oldVer}" "❌ Upgrade failed, rolled back to v${oldVer}"
  2775. Msg " 请检查日志: loongsuite-pilot log" " Check logs: loongsuite-pilot log"
  2776. exit 1
  2777. }
  2778. } finally {
  2779. Enable-PilotScheduledTasksAfterDeploy
  2780. Remove-PilotPathQuietly $script:TMP_DIR
  2781. }
  2782. }
  2783. # Write UTF-8 *without BOM* in a way that works under Constrained Language Mode (WDAC),
  2784. # where [System.IO.File]::WriteAllText / New-Object UTF8Encoding are forbidden. We stage the
  2785. # content through a temp file (Set-Content prepends a BOM) and let node rewrite it BOM-free,
  2786. # because these files (.codex/hooks.json, config.toml) are read by node/Codex, which choke
  2787. # on a BOM. Falls back to Set-Content (with BOM) only if node is somehow unavailable.
  2788. function Write-FileUtf8NoBom {
  2789. param(
  2790. [Parameter(Mandatory = $true)][string]$Path,
  2791. [Parameter(Mandatory = $true)][string]$Content
  2792. )
  2793. if (-not $script:NODE_BIN) {
  2794. Set-Content -LiteralPath $Path -Value $Content -Encoding UTF8 -NoNewline
  2795. return
  2796. }
  2797. $tmp = Join-Path $env:TEMP ("lp-write-" + (Get-Random) + ".tmp")
  2798. Set-Content -LiteralPath $tmp -Value $Content -Encoding UTF8 -NoNewline
  2799. # Windows PowerShell 5.1 strips nested double quotes while marshalling a
  2800. # single-quoted -e argument to a native executable. Keep the JavaScript in a
  2801. # here-string and use JS single-quoted literals so node receives the quotes.
  2802. $rewriteScript = @'
  2803. const fs = require('fs');
  2804. let content = fs.readFileSync(process.argv[1], 'utf-8');
  2805. if (content.charCodeAt(0) === 0xFEFF) content = content.slice(1);
  2806. fs.writeFileSync(process.argv[2], content);
  2807. '@
  2808. $rewriteExit = 1
  2809. $prevEAP = $ErrorActionPreference
  2810. try {
  2811. $ErrorActionPreference = "Continue"
  2812. & $script:NODE_BIN -e $rewriteScript $tmp $Path
  2813. $rewriteExit = $LASTEXITCODE
  2814. } finally {
  2815. $ErrorActionPreference = $prevEAP
  2816. Remove-PilotPathQuietly $tmp
  2817. }
  2818. if ($rewriteExit -ne 0) { throw "Failed to write UTF-8 file: $Path" }
  2819. }
  2820. function Test-IsPilotCodexHookCommand {
  2821. param([object]$Command)
  2822. if ($null -eq $Command) { return $false }
  2823. return ([string]$Command) -match '(?i)(?:^|[\/\\"''\s])codex-loongsuite-pilot-hook\.(?:mjs|sh|ps1)(?:["''\s]|$)'
  2824. }
  2825. function Remove-CodexHookConfig {
  2826. $configPath = Join-Path $env:USERPROFILE ".codex\hooks.json"
  2827. if (-not (Test-Path -LiteralPath $configPath)) { return }
  2828. try {
  2829. # Get-Content -Encoding UTF8 handles both BOM and no-BOM files and is CLM-safe,
  2830. # unlike [System.IO.File]::ReadAllText.
  2831. $raw = Get-Content -LiteralPath $configPath -Raw -Encoding UTF8
  2832. $data = $raw | ConvertFrom-Json
  2833. if (-not $data.hooks -or
  2834. $null -eq $data.hooks.PSObject -or
  2835. $null -eq $data.hooks.PSObject.Properties) {
  2836. return
  2837. }
  2838. $changed = $false
  2839. $eventProperties = @(
  2840. $data.hooks.PSObject.Properties |
  2841. Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace($_.Name) }
  2842. )
  2843. if ($eventProperties.Count -eq 0) { return }
  2844. foreach ($eventProperty in $eventProperties) {
  2845. $eventName = $eventProperty.Name
  2846. $entries = @($eventProperty.Value)
  2847. $keptEntries = @()
  2848. foreach ($entry in $entries) {
  2849. # Preserve malformed or extension-owned null/scalar entries. They
  2850. # are not Pilot commands and uninstall must not fail on them.
  2851. if ($null -eq $entry -or $null -eq $entry.PSObject) {
  2852. $keptEntries += ,$entry
  2853. continue
  2854. }
  2855. $commandProperty = $entry.PSObject.Properties["command"]
  2856. $directCommand = if ($commandProperty) { $commandProperty.Value } else { $null }
  2857. if (Test-IsPilotCodexHookCommand $directCommand) {
  2858. $changed = $true
  2859. continue
  2860. }
  2861. $nestedProperty = $entry.PSObject.Properties["hooks"]
  2862. if ($nestedProperty -and $null -ne $nestedProperty.Value) {
  2863. $nestedHooks = @($nestedProperty.Value)
  2864. $keptNestedHooks = @(
  2865. $nestedHooks | Where-Object {
  2866. if ($null -eq $_ -or $null -eq $_.PSObject) {
  2867. return $true
  2868. }
  2869. $nestedCommandProperty = $_.PSObject.Properties["command"]
  2870. $nestedCommand = if ($nestedCommandProperty) {
  2871. $nestedCommandProperty.Value
  2872. } else {
  2873. $null
  2874. }
  2875. -not (Test-IsPilotCodexHookCommand $nestedCommand)
  2876. }
  2877. )
  2878. if ($keptNestedHooks.Count -ne $nestedHooks.Count) {
  2879. $changed = $true
  2880. $entry.hooks = @($keptNestedHooks)
  2881. }
  2882. if ($nestedHooks.Count -gt 0 -and $keptNestedHooks.Count -eq 0) {
  2883. continue
  2884. }
  2885. }
  2886. $keptEntries += ,$entry
  2887. }
  2888. if ($keptEntries.Count -eq 0) {
  2889. $data.hooks.PSObject.Properties.Remove($eventName)
  2890. } else {
  2891. $data.hooks.$eventName = @($keptEntries)
  2892. }
  2893. }
  2894. if ($changed) {
  2895. $updated = ($data | ConvertTo-Json -Depth 100) + "`r`n"
  2896. Write-FileUtf8NoBom -Path $configPath -Content $updated
  2897. }
  2898. # Do not report success until the resulting config is independently
  2899. # checked for both direct and nested Pilot commands.
  2900. $verifyData = (
  2901. Get-Content -LiteralPath $configPath -Raw -Encoding UTF8 |
  2902. ConvertFrom-Json
  2903. )
  2904. if ($verifyData.hooks) {
  2905. $verifyEventProperties = @(
  2906. $verifyData.hooks.PSObject.Properties |
  2907. Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace($_.Name) }
  2908. )
  2909. foreach ($eventProperty in $verifyEventProperties) {
  2910. foreach ($entry in @($eventProperty.Value)) {
  2911. if ($null -eq $entry -or $null -eq $entry.PSObject) { continue }
  2912. $commandProperty = $entry.PSObject.Properties["command"]
  2913. $directCommand = if ($commandProperty) { $commandProperty.Value } else { $null }
  2914. if (Test-IsPilotCodexHookCommand $directCommand) {
  2915. throw "Pilot Codex hook command is still present"
  2916. }
  2917. $nestedProperty = $entry.PSObject.Properties["hooks"]
  2918. $nestedHooks = if ($nestedProperty) { @($nestedProperty.Value) } else { @() }
  2919. foreach ($nestedHook in $nestedHooks) {
  2920. if ($null -eq $nestedHook -or $null -eq $nestedHook.PSObject) { continue }
  2921. $nestedCommandProperty = $nestedHook.PSObject.Properties["command"]
  2922. $nestedCommand = if ($nestedCommandProperty) {
  2923. $nestedCommandProperty.Value
  2924. } else {
  2925. $null
  2926. }
  2927. if (Test-IsPilotCodexHookCommand $nestedCommand) {
  2928. throw "Pilot Codex nested hook command is still present"
  2929. }
  2930. }
  2931. }
  2932. }
  2933. }
  2934. if ($changed) {
  2935. Msg " ✅ 已清理: ~\.codex\hooks.json" `
  2936. " ✅ Cleaned: ~\.codex\hooks.json"
  2937. }
  2938. } catch {
  2939. throw "Failed to clean Pilot hooks from $configPath`: $($_.Exception.Message)"
  2940. }
  2941. }
  2942. function Remove-OnePilotScheduledTask {
  2943. param(
  2944. [Parameter(Mandatory = $true)]
  2945. [string]$TaskName,
  2946. [Parameter(Mandatory = $true)]
  2947. [string]$TaskPath
  2948. )
  2949. $task = Get-ScheduledTask `
  2950. -TaskName $TaskName `
  2951. -TaskPath $TaskPath `
  2952. -ErrorAction SilentlyContinue
  2953. if (-not $task) { return }
  2954. if ($task.State -eq "Running") {
  2955. Stop-ScheduledTask `
  2956. -TaskName $TaskName `
  2957. -TaskPath $TaskPath `
  2958. -ErrorAction SilentlyContinue
  2959. }
  2960. $unregisterError = $null
  2961. try {
  2962. Unregister-ScheduledTask `
  2963. -TaskName $TaskName `
  2964. -TaskPath $TaskPath `
  2965. -Confirm:$false `
  2966. -ErrorAction Stop
  2967. } catch {
  2968. $unregisterError = $_.Exception.Message
  2969. $fullTaskName = "$($TaskPath.TrimEnd('\'))\$TaskName"
  2970. # Locally forced to Continue for the native call below. On Windows PowerShell 5.1
  2971. # a native command that writes stderr *while a 2> redirection is in effect*
  2972. # raises a NativeCommandError, and the file header's
  2973. # $ErrorActionPreference = "Stop" promotes that to a terminating error whose
  2974. # Message is nothing but the raw stderr line. schtasks.exe prints
  2975. # "ERROR: Access is denied." there on exactly the failure this branch exists to
  2976. # report, so the throw below -- the only place that tells the user why the task
  2977. # survived and what to do about it -- was unreachable: the user saw the bare
  2978. # stderr line and nothing else. Restored in finally so the rest of uninstall
  2979. # keeps failing fast. $schtasksExit starts at 1 so a schtasks.exe that cannot
  2980. # launch at all is treated as failure rather than inheriting a stale
  2981. # $LASTEXITCODE of 0.
  2982. $schtasksExit = 1
  2983. $schtasksOut = ""
  2984. $prevEAP = $ErrorActionPreference
  2985. $ErrorActionPreference = "Continue"
  2986. try {
  2987. $schtasksOut = & schtasks.exe /Delete /TN $fullTaskName /F 2>&1
  2988. $schtasksExit = $LASTEXITCODE
  2989. } finally {
  2990. $ErrorActionPreference = $prevEAP
  2991. }
  2992. if ($schtasksExit -ne 0) {
  2993. # Each element here is an ErrorRecord, not a string: at "Continue" the
  2994. # NativeCommandError still goes to the error stream and 2>&1 merges the record
  2995. # itself, so Out-String rendered the whole PowerShell error block -- source
  2996. # line, squiggle line, CategoryInfo, FullyQualifiedErrorId -- into the middle
  2997. # of the sentence below. Measured on a 5.1 box: schtasks.exe emits two records
  2998. # for one stderr line, the second one empty. .Exception.Message is a property
  2999. # get, so it stays CLM-safe, and it is the raw stderr text and nothing else.
  3000. $schtasksLines = @()
  3001. foreach ($schtasksLine in $schtasksOut) {
  3002. $lineText = ""
  3003. if ($schtasksLine.Exception) { $lineText = [string]$schtasksLine.Exception.Message }
  3004. else { $lineText = [string]$schtasksLine }
  3005. $lineText = $lineText.Trim()
  3006. if ($lineText) { $schtasksLines += $lineText }
  3007. }
  3008. $schtasksDetail = $schtasksLines -join " "
  3009. throw "Failed to remove scheduled task $fullTaskName (Unregister-ScheduledTask: $unregisterError; schtasks exit: $schtasksExit): $schtasksDetail. If that says access is denied, this instance's scheduled tasks are owned by BUILTIN\Administrators, which is what registering them from an elevated session produces -- uninstall itself does not need administrator rights. Re-run uninstall from an elevated PowerShell, or reinstall without elevation."
  3010. }
  3011. }
  3012. $remaining = Get-ScheduledTask `
  3013. -TaskName $TaskName `
  3014. -TaskPath $TaskPath `
  3015. -ErrorAction SilentlyContinue
  3016. if ($remaining) {
  3017. $fullTaskName = "$($TaskPath.TrimEnd('\'))\$TaskName"
  3018. throw "Scheduled task still exists after deletion: $fullTaskName"
  3019. }
  3020. }
  3021. # >>> pilot-account-identity >>>
  3022. # Windows account identity, DOMAIN\user, without whoami. On 5.1 a native command's
  3023. # stdout is decoded with [Console]::OutputEncoding -- the console codepage, 437 on an
  3024. # en-US box -- so `whoami` returns "host\??" for a non-ASCII account name: every
  3025. # character the codepage cannot represent arrives as a literal U+003F, measured on a
  3026. # C:\Users\<CJK name> profile. That corrupted string used to reach
  3027. # New-ScheduledTaskPrincipal -UserId, where Task Scheduler rejected the registration
  3028. # with "No mapping between account names and security IDs was done" (HRESULT
  3029. # 0x80131500), so such a user never got an autostart task at all; it also collapsed
  3030. # every non-ASCII account to the same "___" task-name tag.
  3031. #
  3032. # The environment variables carry the real UTF-16 string and are CLM-safe, unlike
  3033. # [Security.Principal.WindowsIdentity]::GetCurrent() (CLM: "Method invocation is
  3034. # supported only on core types") and unlike [Environment]::UserName. USERDOMAIN is not
  3035. # always an account domain: under some logon providers (OpenSSH sshd among them) it is
  3036. # the literal "WORKGROUP", which maps to no SID either, so fall back to the machine
  3037. # name -- which is also what whoami prints for a local account, keeping the tag below
  3038. # byte-identical for ASCII users who upgrade in place.
  3039. function Get-PilotAccountName {
  3040. $user = [string]$env:USERNAME
  3041. if (-not $user) { return "" }
  3042. $domain = [string]$env:USERDOMAIN
  3043. if ((-not $domain) -or ($domain -eq "WORKGROUP")) { $domain = [string]$env:COMPUTERNAME }
  3044. if ($domain) { return ($domain + "\" + $user) }
  3045. return $user
  3046. }
  3047. # Task names are per-user: multiple users can run on one machine, each with their
  3048. # own data dir under %USERPROFILE%. A global task name would collide -- the second
  3049. # user cannot delete or overwrite the first user's task (Access is denied), so it
  3050. # would fail with "already exists" and drop to the background fallback. The shared
  3051. # \LoongsuitePilot folder stays cross-user writable; only the task name is scoped.
  3052. # Tag from the full DOMAIN\user identity, not $env:USERNAME alone (bare SAM name):
  3053. # two same-named accounts from different domains (CORP\alice vs DEV\alice) would
  3054. # otherwise share one task name and re-introduce the cross-user "already exists"
  3055. # collision this scoping is meant to prevent. Task names live in the file system, so
  3056. # everything outside [A-Za-z0-9._-] becomes "_" -- which turns a non-ASCII account
  3057. # name into a row of underscores that two such users on one machine would fight over,
  3058. # hence the short deterministic digest appended in that case only. ASCII installs keep
  3059. # the exact tag they already have, so their registered tasks stay upgradeable in place.
  3060. function Get-PilotUserTag {
  3061. $name = (Get-PilotAccountName).ToLower()
  3062. $tag = $name -replace '[^A-Za-z0-9._-]', '_'
  3063. if ($name -match '[^\x20-\x7E]') {
  3064. $hash = 0
  3065. foreach ($ch in $name.ToCharArray()) { $hash = ($hash * 31 + [int]$ch) % 1000000007 }
  3066. $tag = $tag + "-" + $hash
  3067. }
  3068. return $tag
  3069. }
  3070. # <<< pilot-account-identity <<<
  3071. # >>> pilot-elevation-warning >>>
  3072. # "Run as administrator" is the reflex a lot of Windows users have for an installer, and
  3073. # here it quietly costs them the ability to uninstall. The scheduled tasks are registered
  3074. # with -RunLevel Limited into the shared \LoongsuitePilot folder, and the only reason a
  3075. # standard user can delete them again is that folder's inherited CREATOR OWNER :
  3076. # FullControl ACE. Under an elevated token CREATOR OWNER resolves to
  3077. # BUILTIN\Administrators, so the tasks come out owned by Administrators and the same
  3078. # account's ordinary session keeps only Read, Synchronize -- schtasks /Delete answers
  3079. # "ERROR: Access is denied." and uninstall cannot remove them. Same mechanism as the file
  3080. # ACLs that Reset-PilotInheritedAcl already repairs with icacls /reset; the task side has
  3081. # no equivalent yet, so for now all we can do is say so before the user commits.
  3082. #
  3083. # The probe is best-effort by construction: both the cast and GetCurrent() are "supported
  3084. # only on core types" under Constrained Language Mode, so under WDAC this throws and we
  3085. # report not-elevated. Losing the hint is acceptable; failing an install over a hint is
  3086. # not.
  3087. function Test-PilotElevated {
  3088. try {
  3089. $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
  3090. $principal = [Security.Principal.WindowsPrincipal]$identity
  3091. return [bool]$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
  3092. } catch {
  3093. return $false
  3094. }
  3095. }
  3096. function Warn-ElevatedInstall {
  3097. if (-not (Test-PilotElevated)) { return }
  3098. Msg "⚠️ 当前是提权(管理员)会话" "⚠️ This is an elevated (administrator) session"
  3099. Msg " 这样注册出来的计划任务归 BUILTIN\Administrators,本账号的普通会话之后删不掉" " Scheduled tasks registered from it are owned by BUILTIN\Administrators, and this account's ordinary sessions cannot delete them afterwards"
  3100. Msg " 继续安装的话,卸载(-Uninstall)也必须在提权会话里执行" " If you continue, uninstall (-Uninstall) will have to run elevated as well"
  3101. Msg " 想让普通会话自己就能卸载:Ctrl+C 退出,在非提权 PowerShell 里重新安装" " To keep uninstall working without elevation: press Ctrl+C and re-run the install from a non-elevated PowerShell"
  3102. Write-Host ""
  3103. }
  3104. # <<< pilot-elevation-warning <<<
  3105. function Remove-PilotScheduledTasks {
  3106. $taskFolder = "\LoongsuitePilot"
  3107. # Reconstruct the task names with the same helpers that registered them -- the tag
  3108. # must match byte for byte or uninstall silently leaves the tasks behind.
  3109. $currentIdentity = Get-PilotAccountName
  3110. $currentUser = $env:USERNAME
  3111. $userTag = Get-PilotUserTag
  3112. $currentUserTasks = @(
  3113. "LoongsuitePilot-$userTag",
  3114. "LoongsuitePilotUpdater-$userTag"
  3115. )
  3116. $legacyTasks = @("LoongsuitePilot", "LoongsuitePilotUpdater")
  3117. foreach ($taskName in @($currentUserTasks + $legacyTasks)) {
  3118. $isLegacy = $taskName -in $legacyTasks
  3119. $task = Get-ScheduledTask `
  3120. -TaskName $taskName `
  3121. -TaskPath "$taskFolder\" `
  3122. -ErrorAction SilentlyContinue
  3123. if ($isLegacy) {
  3124. if (-not $task) { continue }
  3125. $taskOwner = [string]$task.Principal.UserId
  3126. $isCurrentOwner = (
  3127. -not $taskOwner -or
  3128. $taskOwner -ieq $currentIdentity -or
  3129. $taskOwner -ieq $currentUser -or
  3130. $taskOwner.ToLower().EndsWith("\$currentUser".ToLower())
  3131. )
  3132. if (-not $isCurrentOwner) { continue }
  3133. }
  3134. Remove-OnePilotScheduledTask `
  3135. -TaskName $taskName `
  3136. -TaskPath "$taskFolder\"
  3137. }
  3138. }
  3139. function Assert-SafePilotDirectory {
  3140. param(
  3141. [Parameter(Mandatory = $true)]
  3142. [string]$Path,
  3143. [Parameter(Mandatory = $true)]
  3144. [string]$Purpose
  3145. )
  3146. # CLM-safe path normalization: Convert-Path resolves the absolute path without the
  3147. # forbidden [System.IO.Path]::GetFullPath; fall back to the raw path if it can't be
  3148. # resolved (e.g. it no longer exists). Split-Path -Qualifier gives the drive root ("C:").
  3149. $fullPath = $Path
  3150. try { $fullPath = (Convert-Path -LiteralPath $Path -ErrorAction Stop) } catch { $fullPath = $Path }
  3151. $fullPath = $fullPath.TrimEnd('\')
  3152. $rootPath = (Split-Path -Qualifier $fullPath -ErrorAction SilentlyContinue)
  3153. $profilePath = $env:USERPROFILE.TrimEnd('\')
  3154. if (-not $fullPath -or $fullPath -ieq $rootPath -or $fullPath -ieq "$rootPath\" -or $fullPath -ieq $profilePath) {
  3155. throw "Refusing to use unsafe $Purpose directory: $Path"
  3156. }
  3157. return $fullPath
  3158. }
  3159. function ConvertTo-ExtendedLengthPath {
  3160. param(
  3161. [Parameter(Mandatory = $true)]
  3162. [string]$Path
  3163. )
  3164. $fullPath = $Path
  3165. try { $fullPath = (Convert-Path -LiteralPath $Path -ErrorAction Stop) } catch { $fullPath = $Path }
  3166. if ($fullPath.StartsWith("\\?\")) { return $fullPath }
  3167. if ($fullPath.StartsWith("\\")) {
  3168. return "\\?\UNC\$($fullPath.Substring(2))"
  3169. }
  3170. return "\\?\$fullPath"
  3171. }
  3172. function Remove-PilotPath {
  3173. param(
  3174. [Parameter(Mandatory = $true)]
  3175. [string]$Path
  3176. )
  3177. if (-not (Test-Path -LiteralPath $Path)) { return }
  3178. $extendedPath = ConvertTo-ExtendedLengthPath -Path $Path
  3179. $lastError = $null
  3180. $isFullLanguage = $ExecutionContext.SessionState.LanguageMode -eq 'FullLanguage'
  3181. for ($attempt = 1; $attempt -le 3; $attempt++) {
  3182. try {
  3183. if ($isFullLanguage) {
  3184. # Fast path: .NET calls handle the \\?\ extended-length path (deep node_modules
  3185. # trees that exceed MAX_PATH). Available only under Full Language Mode.
  3186. if ([System.IO.Directory]::Exists($extendedPath)) {
  3187. [System.IO.Directory]::Delete($extendedPath, $true)
  3188. } elseif ([System.IO.File]::Exists($extendedPath)) {
  3189. [System.IO.File]::SetAttributes($extendedPath, [System.IO.FileAttributes]::Normal)
  3190. [System.IO.File]::Delete($extendedPath)
  3191. }
  3192. } else {
  3193. # Constrained Language Mode (WDAC): the .NET calls above are forbidden. Fall
  3194. # back to Remove-Item on the original path — covers all but pathological >260-char
  3195. # paths, which are rare and can be cleaned manually if they ever surface.
  3196. Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction Stop
  3197. }
  3198. return
  3199. } catch {
  3200. $lastError = $_
  3201. if ($attempt -lt 3) { Start-Sleep -Milliseconds (100 * $attempt) }
  3202. }
  3203. }
  3204. throw $lastError
  3205. }
  3206. function Remove-PilotInstallationFiles {
  3207. $cachePath = Assert-SafePilotDirectory -Path $CACHE_DIR -Purpose "cache"
  3208. $dataPath = Assert-SafePilotDirectory -Path $DataDir -Purpose "data"
  3209. $cachePrefix = $cachePath + '\'
  3210. $cacheContainsData = $dataPath.ToLower().StartsWith($cachePrefix.ToLower())
  3211. if ($cachePath -ine $dataPath -and -not $cacheContainsData) {
  3212. if (Test-Path -LiteralPath $cachePath) {
  3213. Remove-PilotPath -Path $cachePath
  3214. }
  3215. } else {
  3216. foreach ($relativePath in @(
  3217. "versions",
  3218. "bin",
  3219. "package",
  3220. "current",
  3221. "previous",
  3222. "node-bin"
  3223. )) {
  3224. $target = Join-Path $cachePath $relativePath
  3225. if (Test-Path -LiteralPath $target) {
  3226. Remove-PilotPath -Path $target
  3227. }
  3228. }
  3229. }
  3230. foreach ($relativePath in @("hooks", "skills", "plugins")) {
  3231. $target = Join-Path $dataPath $relativePath
  3232. if (Test-Path -LiteralPath $target) {
  3233. Remove-PilotPath -Path $target
  3234. }
  3235. }
  3236. }
  3237. # >>> dsh-unpatch-refusal >>>
  3238. # Would removing the plugin assets leave a reference behind? Only a patch file that still
  3239. # carries our managed block would, so that is the one question worth refusing over.
  3240. #
  3241. # Consulted only on the paths that would otherwise refuse to continue, never on the
  3242. # working path: this reads a file owned by a third-party tool, and an unreadable one must
  3243. # not be able to turn a healthy uninstall into a failing one. Unreadable is answered
  3244. # "still managed" on purpose -- we cannot prove nothing dangles, so we keep the
  3245. # conservative answer and let the caller refuse.
  3246. function Test-DshPatchStillManaged {
  3247. param([string]$PatchPath)
  3248. if (-not $PatchPath) { return $false }
  3249. if (-not (Test-Path -LiteralPath $PatchPath -ErrorAction SilentlyContinue)) { return $false }
  3250. try {
  3251. return [bool](Select-String -LiteralPath $PatchPath -SimpleMatch "# BEGIN PILOT-OBSERVABILITY-MANAGED" -Quiet)
  3252. } catch {
  3253. return $true
  3254. }
  3255. }
  3256. # <<< dsh-unpatch-refusal <<<
  3257. # ============================================================
  3258. # Remove the Pilot-owned DeepSeek Harness YAML patch before plugin assets.
  3259. # Unix and Windows both execute assets/plugins/dsh/cleanup.mjs.
  3260. # ============================================================
  3261. function Remove-DshYamlPatch {
  3262. $pluginDir = Join-Path $DataDir "plugins\dsh"
  3263. $cleanupScript = Join-Path $pluginDir "cleanup.mjs"
  3264. $dshHome = if ($env:DSH_HOME) { $env:DSH_HOME } else { Join-Path $env:USERPROFILE ".dsh" }
  3265. $patchPath = Join-Path $dshHome "cordis.patch.yml"
  3266. # DSH_HOME may differ between install and uninstall. Prefer the exact path
  3267. # persisted by DeploymentManager, with the current environment as a legacy fallback.
  3268. $stateFile = Join-Path $DataDir "deployed-agents.json"
  3269. if (Test-Path -LiteralPath $stateFile) {
  3270. try {
  3271. $state = Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json
  3272. $persistedPatch = $state.dsh.dshPatchPath
  3273. if ($persistedPatch -and ([string]$persistedPatch -match '^(?:[A-Za-z]:[\\/]|\\\\)')) {
  3274. $patchPath = [string]$persistedPatch
  3275. }
  3276. } catch {
  3277. # Preserve compatibility with missing or legacy state and use the fallback above.
  3278. }
  3279. }
  3280. if (-not (Test-Path -LiteralPath $cleanupScript)) {
  3281. if (Test-DshPatchStillManaged -PatchPath $patchPath) {
  3282. throw "DSH cleanup helper is missing; refusing to remove plugin assets still referenced by $patchPath"
  3283. }
  3284. return
  3285. }
  3286. if (-not $script:NODE_BIN) {
  3287. # Gated the same way as the branch above, which it was not. Resolve-Node returns
  3288. # $null when no candidate is suitable, so this throw has always been reachable,
  3289. # and uninstall now also arrives here after a failed Node probe instead of dying
  3290. # inside Resolve-Node itself. Refusing unconditionally aborted the entire
  3291. # uninstall -- Cmd-Uninstall calls this before every other cleanup step, and
  3292. # -Purge, the step that deletes config.json and the reporting credentials in it,
  3293. # is the last thing in the function -- on machines where DSH was never patched and
  3294. # there was nothing to protect. Refuse only when something would really dangle.
  3295. if (Test-DshPatchStillManaged -PatchPath $patchPath) {
  3296. throw "No usable Node.js; cannot safely remove the DSH YAML patch at $patchPath"
  3297. }
  3298. Msg " ⚠️ 跳过: 无可用 node,且 $patchPath 里没有 Pilot 托管块,无需 unpatch" `
  3299. " ⚠️ Skipped: no usable node, and $patchPath carries no Pilot-managed block, so there is nothing to unpatch"
  3300. return
  3301. }
  3302. & $script:NODE_BIN $cleanupScript --patch $patchPath --plugin-dir $pluginDir
  3303. if ($LASTEXITCODE -ne 0) {
  3304. throw "DSH YAML patch cleanup failed; Pilot assets were preserved"
  3305. }
  3306. Msg " ✅ 已清理 DSH YAML patch" " ✅ Cleaned DSH YAML patch"
  3307. }
  3308. # ============================================================
  3309. # CMD: uninstall
  3310. # ============================================================
  3311. function Remove-CopilotPlugin {
  3312. $copilotHome = Join-Path $env:USERPROFILE '.copilot'
  3313. if (-not (Test-Path -LiteralPath $copilotHome)) { return }
  3314. $helper = $null
  3315. $candidates = @((Join-Path $script:PERMANENT_DIR 'dist/copilot-cleanup.cjs'))
  3316. $currentFile = Join-Path $CACHE_DIR 'current'
  3317. if (Test-Path -LiteralPath $currentFile) {
  3318. $version = (Get-Content -LiteralPath $currentFile -Raw -Encoding UTF8).Trim()
  3319. $candidates = @((Join-Path $CACHE_DIR "versions/$version/dist/copilot-cleanup.cjs")) + $candidates
  3320. }
  3321. foreach ($candidate in $candidates) {
  3322. if (Test-Path -LiteralPath $candidate) { $helper = $candidate; break }
  3323. }
  3324. if (-not $script:NODE_BIN -or -not $helper) {
  3325. Write-Warning 'Copilot cleanup skipped: safe Node JSONC helper unavailable; config and plugin assets preserved'
  3326. return
  3327. }
  3328. $savedPreference = $ErrorActionPreference
  3329. try {
  3330. $ErrorActionPreference = 'Continue'
  3331. & $script:NODE_BIN $helper $copilotHome
  3332. $cleanupExit = $LASTEXITCODE
  3333. } finally { $ErrorActionPreference = $savedPreference }
  3334. if ($cleanupExit -ne 0) { Write-Warning 'Copilot cleanup incomplete; config and plugin assets preserved for retry' }
  3335. }
  3336. function Remove-CopilotOtelEnvironment {
  3337. # Best-effort legacy cleanup: Copilot automatic deployment is Unix-only.
  3338. # A profile access/CLM failure must not interrupt other agents or -Purge.
  3339. foreach ($relative in @('Documents/PowerShell/Microsoft.PowerShell_profile.ps1', 'Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1')) {
  3340. $tmp = $null
  3341. try {
  3342. $profilePath = Join-Path $env:USERPROFILE $relative
  3343. if (-not (Test-Path -LiteralPath $profilePath)) { continue }
  3344. $before = Get-Content -LiteralPath $profilePath -Raw -Encoding UTF8
  3345. $after = $before -replace '(?s)\r?\n?# >>> loongsuite-pilot copilot otel >>>.*?# <<< loongsuite-pilot copilot otel <<<\r?\n?', "`n"
  3346. if ($before -ne $after) {
  3347. $tmp = "$profilePath.pilot-$PID.tmp"
  3348. Set-Content -LiteralPath $tmp -Value $after -Encoding UTF8 -NoNewline
  3349. Move-Item -LiteralPath (Get-PilotLongPath $tmp) -Destination (Get-PilotLongPath $profilePath) -Force
  3350. }
  3351. } catch { Write-Warning "Copilot profile cleanup incomplete; continuing uninstall" }
  3352. finally { if ($tmp) { Remove-PilotPathQuietly $tmp } }
  3353. }
  3354. Remove-Item -LiteralPath (Join-Path $DATA_DIR 'state/copilot/otel-enabled') -Force -ErrorAction SilentlyContinue
  3355. }
  3356. function Cmd-Uninstall {
  3357. Msg "🗑️ 开始卸载 $PACKAGE_NAME ..." "🗑️ Uninstalling $PACKAGE_NAME ..."
  3358. Write-Host ""
  3359. Msg "==> 停止服务..." "==> Stopping service..."
  3360. Stop-PilotService
  3361. Msg " ✅ 服务已停止" " ✅ Service stopped"
  3362. Write-Host ""
  3363. Remove-PilotScheduledTasks
  3364. Msg " ✅ 已移除计划任务" " ✅ Removed scheduled tasks"
  3365. # Resolve the pinned runtime before installation files (including node-bin)
  3366. # are removed. JSON config cleanup must also work when Node is absent from PATH.
  3367. if (-not $script:NODE_BIN) {
  3368. try {
  3369. $script:NODE_BIN = Resolve-Node
  3370. } catch {
  3371. # Non-fatal on purpose. Resolve-Node probes third-party version-manager
  3372. # directories, and under the file header's $ErrorActionPreference = "Stop"
  3373. # any unexpected error record in there becomes terminating. Unguarded, that
  3374. # aborted Cmd-Uninstall right here -- before plugin cleanup, before the
  3375. # install directory was deleted, and before -Purge -- so config.json
  3376. # survived on disk with its credentials in it. Every step below that needs
  3377. # Node already checks $script:NODE_BIN and reports what it skipped.
  3378. $script:NODE_BIN = ""
  3379. Msg " ⚠️ 解析 Node 失败: $($_.Exception.Message)" `
  3380. " ⚠️ Resolving Node failed: $($_.Exception.Message)"
  3381. }
  3382. }
  3383. if (-not $script:NODE_BIN) {
  3384. Msg " ⚠️ 未解析到可用的 Node;依赖 Node 的清理步骤会逐项跳过并提示,其余步骤继续" `
  3385. " ⚠️ No usable Node resolved; each Node-dependent cleanup step will be skipped with a notice, the rest continues"
  3386. }
  3387. Msg "==> 清理 DSH YAML patch..." "==> Cleaning up DSH YAML patch..."
  3388. Remove-DshYamlPatch
  3389. Write-Host ""
  3390. # Read the persisted target before the default data/install directory is removed.
  3391. Msg "==> 清理 Hermes 插件..." "==> Cleaning up Hermes plugin..."
  3392. Remove-HermesPlugin
  3393. Write-Host ""
  3394. Msg "==> 清理 OpenClaw 插件配置..." "==> Cleaning up OpenClaw plugin config..."
  3395. Remove-OpenClawPlugin
  3396. Write-Host ""
  3397. # This cleanup executes Node.js. Run it before installation assets or a
  3398. # pinned runtime can disappear, matching the POSIX uninstall ordering.
  3399. Msg "==> 清理 Grok Build hook 配置..." "==> Cleaning up Grok Build hook config..."
  3400. Remove-GrokBuildHookConfig
  3401. try { Remove-CopilotOtelEnvironment } catch { Write-Warning "Copilot environment cleanup failed; continuing uninstall" }
  3402. try { Remove-CopilotPlugin } catch { Write-Warning "Copilot plugin cleanup failed; continuing uninstall" }
  3403. Write-Host ""
  3404. Msg "==> 清理 hook 配置..." "==> Cleaning up hook configs..."
  3405. Remove-HookConfigs
  3406. try {
  3407. Remove-CodexHookConfig
  3408. } catch {
  3409. Msg " ⚠️ Codex hook 清理失败,继续卸载: $($_.Exception.Message)" `
  3410. " ⚠️ Codex hook cleanup failed; continuing uninstall: $($_.Exception.Message)"
  3411. }
  3412. Write-Host ""
  3413. Msg "==> 清理 QoderWork 系列环境变量..." "==> Cleaning up QoderWork-family env vars..."
  3414. $wrapperPath = Join-Path $DataDir "hooks\qoderwork-runtime-wrapper.mjs"
  3415. $script:RUNTIME_ENV_BROADCAST_FAILED = $false
  3416. $runtimeEnvCleanupFailed = $false
  3417. foreach ($envName in @('QW_QODER_WORKER_RUNTIME_PATH', 'QODER_WORKER_RUNTIME_PATH')) {
  3418. try {
  3419. $currentRuntime = Get-PilotRuntimeOverride -Name $envName
  3420. if ($currentRuntime -and $currentRuntime -ieq $wrapperPath) {
  3421. $broadcasted = Remove-PilotRuntimeOverride -Name $envName
  3422. if (-not $broadcasted) { $script:RUNTIME_ENV_BROADCAST_FAILED = $true }
  3423. Msg " ✅ 已移除 $envName" " ✅ Removed $envName"
  3424. }
  3425. } catch {
  3426. $runtimeEnvCleanupFailed = $true
  3427. Msg " ⚠️ 清理 $envName 失败,已保留安装文件以便重试: $($_.Exception.Message)" `
  3428. " ⚠️ Failed to clean $envName; installation files will be preserved for retry: $($_.Exception.Message)"
  3429. }
  3430. }
  3431. if ($script:RUNTIME_ENV_BROADCAST_FAILED) {
  3432. Msg " ⚠️ 请注销并重新登录 Windows 以刷新 Explorer 环境" `
  3433. " ⚠️ Sign out and back in to refresh the Explorer environment"
  3434. }
  3435. Write-Host ""
  3436. Msg "==> 清理 Claude 旧插件..." "==> Cleaning up legacy Claude plugin..."
  3437. Remove-OtelPlugin
  3438. Write-Host ""
  3439. Msg "==> 清理 OpenCode 插件配置..." "==> Cleaning up OpenCode plugin config..."
  3440. Remove-OpenCodePlugin
  3441. Write-Host ""
  3442. Msg "==> 清理 Pi Coding Agent Extension 配置..." "==> Cleaning up Pi Coding Agent extension config..."
  3443. Remove-PiCodingAgentExtension
  3444. Write-Host ""
  3445. Msg "==> 清理 MiMo Code 插件配置..." "==> Cleaning up MiMo Code plugin config..."
  3446. Remove-MimoCodePlugin
  3447. Write-Host ""
  3448. if ($runtimeEnvCleanupFailed) {
  3449. throw "Runtime environment cleanup failed; installation files were preserved for retry"
  3450. }
  3451. # Keep the pinned node runtime and deployed helper assets available until
  3452. # every external config and runtime override has been cleaned. In
  3453. # particular, never leave a User env var pointing at a deleted wrapper.
  3454. Msg "==> 删除安装目录..." "==> Removing installation..."
  3455. Remove-PilotInstallationFiles
  3456. Msg " ✅ 已删除安装文件" " ✅ Removed installation files"
  3457. Msg "==> 删除 loongsuite-pilot 命令..." "==> Removing loongsuite-pilot command..."
  3458. $cmdFile = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot.cmd"
  3459. $ps1File = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
  3460. $legacyPs1File = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot.ps1"
  3461. $layoutFile = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-layout.json"
  3462. if (Test-Path $cmdFile) { Remove-Item $cmdFile -Force }
  3463. if (Test-Path $ps1File) { Remove-Item $ps1File -Force }
  3464. if (Test-Path $legacyPs1File) { Remove-Item $legacyPs1File -Force }
  3465. if (Test-Path $layoutFile) { Remove-Item $layoutFile -Force }
  3466. Msg " ✅ loongsuite-pilot 命令已删除" " ✅ loongsuite-pilot command removed"
  3467. Write-Host ""
  3468. if ($Purge) {
  3469. Msg "==> 删除数据目录 (-Purge)..." "==> Removing data directory (-Purge)..."
  3470. $safeDataDir = Assert-SafePilotDirectory -Path $DataDir -Purpose "data"
  3471. if (Test-Path -LiteralPath $safeDataDir) {
  3472. Remove-PilotPath -Path $safeDataDir
  3473. }
  3474. Msg " ✅ 已删除 $DataDir" " ✅ Removed $DataDir"
  3475. } else {
  3476. Msg "📁 数据目录已保留: $DataDir" "📁 Data directory preserved: $DataDir"
  3477. # Names the credentials rather than saying "config": this line is the only notice
  3478. # a user gets that an uninstall they consider finished left an SLS AccessKeySecret
  3479. # readable on disk, and "contains config and logs" does not read like that.
  3480. Msg " (包含配置和日志,其中 config.json 里有上报凭据;如需彻底删除请加 -Purge)" `
  3481. " (contains config and logs -- config.json holds reporting credentials; add -Purge to remove)"
  3482. }
  3483. Write-Host ""
  3484. Write-Host "============================================================"
  3485. Msg "✅ 卸载完成!" "✅ Uninstallation complete!"
  3486. Write-Host "============================================================"
  3487. }
  3488. # ============================================================
  3489. # Main dispatcher
  3490. # ============================================================
  3491. switch ($Command) {
  3492. "install" { Cmd-Install }
  3493. "upgrade" { Cmd-Upgrade }
  3494. "uninstall" { Cmd-Uninstall }
  3495. default {
  3496. Write-Host "Usage: .\installer-opensource.ps1 {install|upgrade|uninstall} [options]"
  3497. exit 1
  3498. }
  3499. }
deploy/installer-opensource.sh · Bundled script · 3,242 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # installer-opensource.sh — Open-source installer for loongsuite-pilot
  3. #
  4. # Install (first time):
  5. # curl -fsSL https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/installer.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 5 on GitHub
  6. # curl -fsSL <URL>/installer.sh | bash -s -- install \
  7. # --sls-endpoint "https://cn-hangzhou.log.aliyuncs.com" \
  8. # --sls-project "my-project" \
  9. # --sls-logstore "my-logstore" \
  10. # --sls-ak-id "your-ak-id" \
  11. # --sls-ak-secret "your-ak-secret"
  12. # curl -fsSL <URL>/installer.sh | bash -s -- install \
  13. # --sls-endpoint "https://cn-hangzhou.log.aliyuncs.com" \
  14. # --sls-project "my-project" \
  15. # --sls-logstore "my-logstore" \
  16. # --sls-api-key "your-api-key" \
  17. # --multimodal-mode all
  18. #
  19. # Install a specific version:
  20. # curl -fsSL <URL>/installer.sh | bash -s -- install --version 1.2.0
  21. #
  22. # Optional Dashboard port (default: 8765; preserve existing port on reinstall):
  23. # curl -fsSL <URL>/installer.sh | bash -s -- install --dashboard-port 9000
  24. #
  25. # Upgrade (preserve config, auto-rollback on failure):
  26. # curl -fsSL <URL>/installer.sh | bash -s -- upgrade
  27. #
  28. # Uninstall:
  29. # curl -fsSL <URL>/installer.sh | bash -s -- uninstall
  30. # curl -fsSL <URL>/installer.sh | bash -s -- uninstall --purge
  31. set -euo pipefail
  32. # ============================================================
  33. # Constants
  34. # ============================================================
  35. PACKAGE_NAME="loongsuite-pilot"
  36. PERMANENT_DIR="$HOME/.loongsuite-pilot/package"
  37. DEFAULT_DATA_DIR="$HOME/.loongsuite-pilot"
  38. # OSS download base URL
  39. _OSS_BASE_URL="https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot"
  40. # Managed Node.js runtime + prebuilt node_modules (downloaded from OSS at install time)
  41. NODE_VERSION="${LOONGSUITE_PILOT_NODE_VERSION:-22.22.2}"
  42. NODE_DEPS_BASE="${LOONGSUITE_PILOT_NODE_DEPS_URL:-https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node}"
  43. NODE_MODULES_BASE="${LOONGSUITE_PILOT_NODE_MODULES_URL:-https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node-modules}"
  44. # ============================================================
  45. # Parse sub-command
  46. # ============================================================
  47. COMMAND=""
  48. PACKAGE_URL="${LOONGSUITE_PILOT_PACKAGE_URL:-}"
  49. INSTALL_VERSION=""
  50. SLS_ENDPOINT=""
  51. SLS_PROJECT=""
  52. SLS_LOGSTORE=""
  53. SLS_AK_ID=""
  54. SLS_AK_SECRET=""
  55. SLS_API_KEY=""
  56. DATA_DIR="$DEFAULT_DATA_DIR"
  57. DASHBOARD_PORT=""
  58. DASHBOARD_PORT_SET=0
  59. LOG_LEVEL=""
  60. USER_ID=""
  61. COLLECT_LOG=""
  62. COLLECT_TRACE=""
  63. ENABLE_STATUS_BAR_APP=""
  64. CMS_LICENSE_KEY=""
  65. CMS_ENDPOINT=""
  66. CMS_WORKSPACE=""
  67. SERVICE_NAME_PREFIX=""
  68. SELECTED_AGENTS=""
  69. HOOK_INSTALL_SCOPE=""
  70. AGENT_SELECTION_EXPLICIT=0
  71. ALL_AGENTS=0
  72. MULTIMODAL_MODE=""
  73. MULTIMODAL_MODE_SET=0
  74. # Keep in sync with MULTIMODAL_SUPPORTED_AGENT_IDS.
  75. MULTIMODAL_SUPPORTED_AGENTS="codex,qoder"
  76. EXCLUDE_WORKSPACES=()
  77. MASK_MODE=""
  78. MASK_TYPES=""
  79. MASK_REPLACEMENT_MODE=""
  80. INTERCEPTOR_MODE=""
  81. INTERCEPTOR_TYPES=""
  82. HAS_SUDO=0
  83. PURGE=0
  84. PREFER_SYSTEM_NODE=0
  85. # First arg is sub-command (or option -> default to install)
  86. if [[ $# -gt 0 ]]; then
  87. case "$1" in
  88. install|upgrade|uninstall)
  89. COMMAND="$1"; shift ;;
  90. -*)
  91. COMMAND="install" ;;
  92. *)
  93. COMMAND="install" ;;
  94. esac
  95. else
  96. COMMAND="install"
  97. fi
  98. while [[ $# -gt 0 ]]; do
  99. case "$1" in
  100. --sls-endpoint) SLS_ENDPOINT="$2"; shift 2 ;;
  101. --sls-endpoint=*) SLS_ENDPOINT="${1#*=}"; shift ;;
  102. --sls-project) SLS_PROJECT="$2"; shift 2 ;;
  103. --sls-project=*) SLS_PROJECT="${1#*=}"; shift ;;
  104. --sls-logstore) SLS_LOGSTORE="$2"; shift 2 ;;
  105. --sls-logstore=*) SLS_LOGSTORE="${1#*=}"; shift ;;
  106. --sls-ak-id) SLS_AK_ID="$2"; shift 2 ;;
  107. --sls-ak-id=*) SLS_AK_ID="${1#*=}"; shift ;;
  108. --sls-ak-secret) SLS_AK_SECRET="$2"; shift 2 ;;
  109. --sls-ak-secret=*) SLS_AK_SECRET="${1#*=}"; shift ;;
  110. --sls-api-key) SLS_API_KEY="$2"; shift 2 ;;
  111. --sls-api-key=*) SLS_API_KEY="${1#*=}"; shift ;;
  112. --package-url) PACKAGE_URL="$2"; shift 2 ;;
  113. --package-url=*) PACKAGE_URL="${1#--package-url=}"; shift ;;
  114. --data-dir) DATA_DIR="$2"; shift 2 ;;
  115. --data-dir=*) DATA_DIR="${1#*=}"; shift ;;
  116. --dashboard-port)
  117. if [ "$#" -lt 2 ] || [[ "$2" == --* ]]; then
  118. echo "--dashboard-port requires an integer between 1 and 65535" >&2
  119. exit 1
  120. fi
  121. DASHBOARD_PORT="$2"; DASHBOARD_PORT_SET=1; shift 2 ;;
  122. --dashboard-port=*) DASHBOARD_PORT="${1#*=}"; DASHBOARD_PORT_SET=1; shift ;;
  123. --log-level) LOG_LEVEL="$2"; shift 2 ;;
  124. --log-level=*) LOG_LEVEL="${1#*=}"; shift ;;
  125. --userId|--user.id) USER_ID="$2"; shift 2 ;;
  126. --userId=*|--user.id=*) USER_ID="${1#*=}"; shift ;;
  127. --lang) export LOONGSUITE_PILOT_LANG="$2"; shift 2 ;;
  128. --lang=*) export LOONGSUITE_PILOT_LANG="${1#--lang=}"; shift ;;
  129. --version) INSTALL_VERSION="$2"; shift 2 ;;
  130. --version=*) INSTALL_VERSION="${1#*=}"; shift ;;
  131. --exclude-workspace)
  132. if [ "$#" -lt 2 ] || [[ "$2" != /* ]]; then
  133. echo "--exclude-workspace requires an absolute local directory" >&2
  134. exit 1
  135. fi
  136. EXCLUDE_WORKSPACES+=("$2"); shift 2 ;;
  137. --exclude-workspace=*)
  138. excluded_workspace="${1#*=}"
  139. if [[ "$excluded_workspace" != /* ]]; then
  140. echo "--exclude-workspace requires an absolute local directory" >&2
  141. exit 1
  142. fi
  143. EXCLUDE_WORKSPACES+=("$excluded_workspace"); shift ;;
  144. --collect-log) COLLECT_LOG="$2"; shift 2 ;;
  145. --collect-log=*) COLLECT_LOG="${1#*=}"; shift ;;
  146. --collect-trace) COLLECT_TRACE="$2"; shift 2 ;;
  147. --collect-trace=*) COLLECT_TRACE="${1#*=}"; shift ;;
  148. --enable-status-bar-app|--enable-status-bar-app=*)
  149. if [[ "$1" == *=* ]]; then
  150. ENABLE_STATUS_BAR_APP="${1#*=}"; shift
  151. else
  152. if [ "$#" -lt 2 ]; then
  153. echo "--enable-status-bar-app requires true or false" >&2
  154. exit 1
  155. fi
  156. ENABLE_STATUS_BAR_APP="$2"; shift 2
  157. fi
  158. case "$ENABLE_STATUS_BAR_APP" in
  159. true|false) ;;
  160. *) echo "--enable-status-bar-app requires true or false" >&2; exit 1 ;;
  161. esac ;;
  162. --cms-license-key) CMS_LICENSE_KEY="$2"; shift 2 ;;
  163. --cms-license-key=*) CMS_LICENSE_KEY="${1#*=}"; shift ;;
  164. --cms-endpoint) CMS_ENDPOINT="$2"; shift 2 ;;
  165. --cms-endpoint=*) CMS_ENDPOINT="${1#*=}"; shift ;;
  166. --cms-workspace) CMS_WORKSPACE="$2"; shift 2 ;;
  167. --cms-workspace=*) CMS_WORKSPACE="${1#*=}"; shift ;;
  168. --service-name-prefix) SERVICE_NAME_PREFIX="$2"; shift 2 ;;
  169. --service-name-prefix=*) SERVICE_NAME_PREFIX="${1#*=}"; shift ;;
  170. --agents) SELECTED_AGENTS="$2"; AGENT_SELECTION_EXPLICIT=1; shift 2 ;;
  171. --agents=*) SELECTED_AGENTS="${1#*=}"; AGENT_SELECTION_EXPLICIT=1; shift ;;
  172. --scope)
  173. [ "$#" -ge 2 ] || { echo "--scope requires user or system" >&2; exit 1; }
  174. HOOK_INSTALL_SCOPE="$2"; shift 2 ;;
  175. --scope=*) HOOK_INSTALL_SCOPE="${1#*=}"; shift ;;
  176. --all-agents) ALL_AGENTS=1; shift ;;
  177. --multimodal-mode) MULTIMODAL_MODE="${2-}"; MULTIMODAL_MODE_SET=1; shift 2 || shift ;;
  178. --multimodal-mode=*) MULTIMODAL_MODE="${1#*=}"; MULTIMODAL_MODE_SET=1; shift ;;
  179. --mask-mode) MASK_MODE="$2"; shift 2 ;;
  180. --mask-mode=*) MASK_MODE="${1#*=}"; shift ;;
  181. --mask-types) MASK_TYPES="$2"; shift 2 ;;
  182. --mask-types=*) MASK_TYPES="${1#*=}"; shift ;;
  183. --mask-replacement-mode) MASK_REPLACEMENT_MODE="$2"; shift 2 ;;
  184. --mask-replacement-mode=*) MASK_REPLACEMENT_MODE="${1#*=}"; shift ;;
  185. --interceptor-mode) INTERCEPTOR_MODE="$2"; shift 2 ;;
  186. --interceptor-mode=*) INTERCEPTOR_MODE="${1#*=}"; shift ;;
  187. --interceptor-types) INTERCEPTOR_TYPES="$2"; shift 2 ;;
  188. --interceptor-types=*) INTERCEPTOR_TYPES="${1#*=}"; shift ;;
  189. --purge) PURGE=1; shift ;;
  190. --prefer-system-node) PREFER_SYSTEM_NODE=1; shift ;;
  191. --prefer-system-node=*) PREFER_SYSTEM_NODE=1; shift ;;
  192. --system-service)
  193. echo "⚠️ --system-service is deprecated and ignored. Auto-detection is now the default." >&2
  194. shift ;;
  195. *)
  196. echo "Unknown option: $1" >&2
  197. exit 1 ;;
  198. esac
  199. done
  200. if [ -n "$HOOK_INSTALL_SCOPE" ]; then
  201. case "$HOOK_INSTALL_SCOPE" in
  202. user|system) ;;
  203. *) echo "--scope requires user or system" >&2; exit 1 ;;
  204. esac
  205. if [ "$COMMAND" != "install" ]; then
  206. echo "--scope is only supported with install; upgrades preserve recorded hook scope" >&2
  207. exit 1
  208. fi
  209. fi
  210. if [ -n "$ENABLE_STATUS_BAR_APP" ] && [ "$COMMAND" != "install" ]; then
  211. echo "--enable-status-bar-app is only supported with install" >&2
  212. exit 1
  213. fi
  214. if [ "$DASHBOARD_PORT_SET" -eq 1 ]; then
  215. if ! [[ "$DASHBOARD_PORT" =~ ^[0-9]{1,5}$ ]] || (( 10#$DASHBOARD_PORT < 1 || 10#$DASHBOARD_PORT > 65535 )); then
  216. echo "--dashboard-port must be an integer between 1 and 65535" >&2
  217. exit 1
  218. fi
  219. fi
  220. if [ -n "$MASK_MODE" ]; then
  221. case "$MASK_MODE" in
  222. all|none|custom) ;;
  223. *)
  224. echo "❌ Unknown mask mode: $MASK_MODE (use 'all', 'custom', or 'none')" >&2
  225. exit 1 ;;
  226. esac
  227. fi
  228. if [ "$MASK_MODE" = "custom" ] && [ -z "$MASK_TYPES" ]; then
  229. echo "❌ --mask-types is required when --mask-mode custom" >&2
  230. exit 1
  231. fi
  232. if [ -n "$MASK_TYPES" ] && [ "$MASK_MODE" != "custom" ]; then
  233. echo "❌ --mask-types can only be used with --mask-mode custom" >&2
  234. exit 1
  235. fi
  236. if [ -n "$MASK_REPLACEMENT_MODE" ] && [ "$MASK_REPLACEMENT_MODE" != "placeholder" ] && [ "$MASK_REPLACEMENT_MODE" != "preview" ]; then
  237. echo "❌ Unknown mask replacement mode: $MASK_REPLACEMENT_MODE (use 'placeholder' or 'preview')" >&2
  238. exit 1
  239. fi
  240. if [ -n "$INTERCEPTOR_MODE" ]; then
  241. case "$INTERCEPTOR_MODE" in
  242. all|none|custom) ;;
  243. *)
  244. echo "❌ Unknown interceptor mode: $INTERCEPTOR_MODE (use 'all', 'custom', or 'none')" >&2
  245. exit 1 ;;
  246. esac
  247. fi
  248. if [ "$INTERCEPTOR_MODE" = "custom" ] && [ -z "$INTERCEPTOR_TYPES" ]; then
  249. echo "❌ --interceptor-types is required when --interceptor-mode custom" >&2
  250. exit 1
  251. fi
  252. if [ -n "$INTERCEPTOR_TYPES" ] && [ "$INTERCEPTOR_MODE" != "custom" ]; then
  253. echo "❌ --interceptor-types can only be used with --interceptor-mode custom" >&2
  254. exit 1
  255. fi
  256. if [ -n "$SLS_API_KEY" ] && { [ -n "$SLS_AK_ID" ] || [ -n "$SLS_AK_SECRET" ]; }; then
  257. echo "❌ --sls-api-key cannot be used with --sls-ak-id or --sls-ak-secret" >&2
  258. exit 1
  259. fi
  260. if [ "$MULTIMODAL_MODE_SET" -eq 1 ]; then
  261. if [ -z "$MULTIMODAL_MODE" ]; then
  262. echo "❌ --multimodal-mode requires 'none', 'input', 'output', or 'all'" >&2
  263. exit 1
  264. fi
  265. case "$MULTIMODAL_MODE" in
  266. none|input|output|all) ;;
  267. *)
  268. echo "❌ Unknown multimodal mode: $MULTIMODAL_MODE (use 'none', 'input', 'output', or 'all')" >&2
  269. exit 1 ;;
  270. esac
  271. if [ "$COMMAND" != "install" ]; then
  272. echo "❌ --multimodal-mode is only supported with install (got $COMMAND)" >&2
  273. exit 1
  274. fi
  275. if [ "$MULTIMODAL_MODE" != "none" ]; then
  276. if [[ "$SLS_ENDPOINT" != *[![:space:]]* ]] || [[ "$SLS_PROJECT" != *[![:space:]]* ]] \
  277. || [[ "$SLS_LOGSTORE" != *[![:space:]]* ]] || [[ "$SLS_API_KEY" != *[![:space:]]* ]]; then
  278. echo "❌ --multimodal-mode $MULTIMODAL_MODE requires --sls-endpoint, --sls-project, --sls-logstore, and --sls-api-key" >&2
  279. exit 1
  280. fi
  281. fi
  282. fi
  283. # Validate current user and sudo access on Linux
  284. validate_install_user() {
  285. case "$(uname -s)" in
  286. Linux)
  287. local current_user
  288. current_user=$(whoami)
  289. if [ "$(id -u)" -eq 0 ]; then
  290. HAS_SUDO=1
  291. msg " ✅ 以 root 身份安装(自动使用系统级服务)" \
  292. " ✅ Installing as root (auto system-level service)"
  293. else
  294. msg " Install user: $current_user(服务类型将在启动时自动检测)" \
  295. " Install user: $current_user (service type auto-detected at start)"
  296. fi
  297. ;;
  298. esac
  299. }
  300. # Resolve PACKAGE_URL from OSS if not explicitly set
  301. if [ -z "$PACKAGE_URL" ]; then
  302. if [ -n "$INSTALL_VERSION" ]; then
  303. PACKAGE_URL="${_OSS_BASE_URL}/${INSTALL_VERSION}/${PACKAGE_NAME}.tar.gz"
  304. else
  305. PACKAGE_URL="${_OSS_BASE_URL}/latest/${PACKAGE_NAME}.tar.gz"
  306. fi
  307. fi
  308. # ============================================================
  309. # Language detection
  310. # ============================================================
  311. detect_lang() {
  312. if [ -n "${LOONGSUITE_PILOT_LANG:-}" ]; then echo "$LOONGSUITE_PILOT_LANG"; return; fi
  313. for v in "${LANGUAGE:-}" "${LC_ALL:-}" "${LC_MESSAGES:-}" "${LANG:-}"; do
  314. if echo "$v" | grep -qi "zh"; then echo "zh"; return; fi
  315. done
  316. if [ "$(uname)" = "Darwin" ]; then
  317. local al
  318. al=$(defaults read -g AppleLanguages 2>/dev/null | grep -i "zh" | head -1 || true)
  319. if [ -n "$al" ]; then echo "zh"; return; fi
  320. fi
  321. echo "en"
  322. }
  323. LANG_MODE=$(detect_lang)
  324. msg() { [ "$LANG_MODE" = "zh" ] && echo "$1" || echo "$2"; }
  325. # ============================================================
  326. # Common: check dependencies
  327. # ============================================================
  328. _resolve_realpath() {
  329. realpath "$1" 2>/dev/null || readlink -f "$1" 2>/dev/null || echo "$1"
  330. }
  331. _node_is_app_bundle() {
  332. local resolved
  333. resolved=$(_resolve_realpath "$1")
  334. case "$resolved" in
  335. /Applications/*.app/Contents/*|/System/Applications/*.app/Contents/*|"$HOME"/Applications/*.app/Contents/*)
  336. return 0
  337. ;;
  338. esac
  339. return 1
  340. }
  341. # node:sqlite is unflagged from 22.13 and 23.4. A major-version check accepts
  342. # Node 20 and 22.12, whose require('node:sqlite') throws, so install would
  343. # succeed and SQLite collection would not. The require is the check.
  344. _node_supports_sqlite() {
  345. "$1" -e "require('node:sqlite')" >/dev/null 2>&1
  346. }
  347. _node_is_suitable() {
  348. local bin="$1"
  349. [ -x "$bin" ] || return 1
  350. _node_is_app_bundle "$bin" && return 1
  351. _node_supports_sqlite "$bin" || return 1
  352. return 0
  353. }
  354. resolve_node() {
  355. local _candidates=()
  356. local _nvm_candidates=("$HOME/.nvm/versions/node"/*/bin/node)
  357. local i
  358. for (( i=${#_nvm_candidates[@]}-1; i>=0; i-- )); do
  359. _candidates+=("${_nvm_candidates[i]}")
  360. done
  361. _candidates+=(
  362. "$HOME/.volta/bin/node"
  363. "$HOME/.fnm/aliases/default/bin/node"
  364. /opt/homebrew/bin/node
  365. /usr/local/bin/node
  366. "$HOME/.local/bin/node"
  367. )
  368. if command -v node >/dev/null 2>&1; then
  369. _candidates+=("$(command -v node)")
  370. fi
  371. for candidate in "${_candidates[@]}"; do
  372. if _node_is_suitable "$candidate"; then
  373. _resolve_realpath "$candidate"
  374. return 0
  375. fi
  376. done
  377. return 1
  378. }
  379. # >>> managed-node-runtime >>>
  380. # Managed Node.js runtime + prebuilt node_modules, downloaded from OSS.
  381. # Everything here logs to stderr only: ensure_managed_node is captured via
  382. # $(...) and must print the node path — and nothing else — on stdout.
  383. _mn_msg() {
  384. if [ "${LANG_MODE:-en}" = "zh" ]; then echo "$1" >&2; else echo "$2" >&2; fi
  385. }
  386. managed_node_platform() {
  387. local os arch
  388. case "$(uname -s)" in
  389. Darwin) os="darwin" ;;
  390. Linux) os="linux" ;;
  391. MINGW*|MSYS*|CYGWIN*) os="win" ;;
  392. *)
  393. echo "managed node: unsupported platform $(uname -s)" >&2
  394. return 1 ;;
  395. esac
  396. case "$(uname -m)" in
  397. arm64|aarch64) arch="arm64" ;;
  398. x86_64|amd64) arch="x64" ;;
  399. *)
  400. echo "managed node: unsupported architecture $(uname -m)" >&2
  401. return 1 ;;
  402. esac
  403. if [ "$os" = "win" ] && [ "$arch" = "arm64" ]; then
  404. _mn_msg "managed node: win-arm64 无托管产物,回退系统 node + npm install" \
  405. "managed node: no win-arm64 artifact, falling back to system node + npm install"
  406. return 1
  407. fi
  408. if [ "$os" = "linux" ] && managed_node_is_musl; then
  409. _mn_msg "managed node: linux musl (Alpine) 无托管产物,回退系统 node + npm install" \
  410. "managed node: no linux-musl artifact, falling back to system node + npm install"
  411. return 1
  412. fi
  413. echo "$os $arch"
  414. }
  415. managed_node_is_musl() {
  416. ls /lib/ld-musl-* >/dev/null 2>&1 && return 0
  417. ldd --version 2>&1 | grep -qi musl && return 0
  418. return 1
  419. }
  420. managed_node_download() {
  421. # managed_node_download <url> <dest>
  422. # Bounded timeouts mirror the .ps1 installer (-TimeoutSec 600); without
  423. # them a stalled TCP connection hangs the installer indefinitely.
  424. if command -v curl >/dev/null 2>&1; then
  425. curl -fsSL --retry 2 --connect-timeout 20 --max-time 600 "$1" -o "$2"
  426. elif command -v wget >/dev/null 2>&1; then
  427. wget -q --tries=2 --timeout=20 "$1" -O "$2"
  428. else
  429. return 1
  430. fi
  431. }
  432. managed_node_sha256() {
  433. if command -v shasum >/dev/null 2>&1; then
  434. shasum -a 256 "$1" | awk '{print $1}'
  435. elif command -v sha256sum >/dev/null 2>&1; then
  436. sha256sum "$1" | awk '{print $1}'
  437. else
  438. echo "managed node: neither shasum nor sha256sum available" >&2
  439. return 1
  440. fi
  441. }
  442. managed_node_verify() {
  443. # managed_node_verify <archive> <shasums-file> <archive-basename>
  444. local expected actual
  445. # [*]? accepts sha256sum binary-mode lines ("<hash> *<name>"), matching
  446. # the .ps1 installer's Test-ManagedNodeChecksum.
  447. expected=$(grep -E "[[:space:]][*]?${3}\$" "$2" 2>/dev/null | awk '{print $1}' | head -1)
  448. if [ -z "$expected" ]; then
  449. echo "managed node: SHASUMS256.txt has no entry for $3" >&2
  450. return 1
  451. fi
  452. actual=$(managed_node_sha256 "$1") || return 1
  453. if [ "$expected" != "$actual" ]; then
  454. echo "managed node: sha256 mismatch for $3 (expected $expected, got $actual)" >&2
  455. return 1
  456. fi
  457. return 0
  458. }
  459. managed_node_bin() {
  460. # managed_node_bin <node-dir> <os>
  461. # Prefer the bin/ layout; official Node.js win zips put node.exe at the root.
  462. local bin="$1/bin/node"
  463. [ "$2" = "win" ] && bin="$1/bin/node.exe"
  464. if [ -x "$bin" ]; then
  465. echo "$bin"
  466. return 0
  467. fi
  468. if [ "$2" = "win" ] && [ -x "$1/node.exe" ]; then
  469. echo "$1/node.exe"
  470. return 0
  471. fi
  472. return 1
  473. }
  474. ensure_managed_node() {
  475. local runtime_dir="$DATA_DIR/runtime"
  476. local tuple os arch
  477. tuple=$(managed_node_platform) || return 1
  478. os="${tuple% *}"; arch="${tuple#* }"
  479. local ext="tar.gz"
  480. [ "$os" = "win" ] && ext="zip"
  481. local archive="node-v${NODE_VERSION}-${os}-${arch}.${ext}"
  482. local node_dir="$runtime_dir/node-v${NODE_VERSION}-${os}-${arch}"
  483. local node_bin=""
  484. node_bin=$(managed_node_bin "$node_dir" "$os") || node_bin=""
  485. if [ -n "$node_bin" ] && [ "$("$node_bin" --version 2>/dev/null)" = "v${NODE_VERSION}" ]; then
  486. echo "$node_bin"
  487. return 0
  488. fi
  489. local base="${NODE_DEPS_BASE%/}/${NODE_VERSION}"
  490. local tmp
  491. tmp=$(mktemp -d) || return 1
  492. _mn_msg "==> 下载托管 Node.js v${NODE_VERSION} (${os}-${arch})..." \
  493. "==> Downloading managed Node.js v${NODE_VERSION} (${os}-${arch})..."
  494. if ! managed_node_download "$base/$archive" "$tmp/$archive" \
  495. || ! managed_node_download "$base/SHASUMS256.txt" "$tmp/SHASUMS256.txt" \
  496. || ! managed_node_verify "$tmp/$archive" "$tmp/SHASUMS256.txt" "$archive"; then
  497. rm -rf "$tmp"
  498. return 1
  499. fi
  500. mkdir -p "$runtime_dir"
  501. rm -rf "$node_dir"
  502. if [ "$ext" = "zip" ]; then
  503. if ! command -v unzip >/dev/null 2>&1 || ! unzip -q "$tmp/$archive" -d "$runtime_dir"; then
  504. rm -rf "$tmp" "$node_dir"
  505. return 1
  506. fi
  507. else
  508. if ! { tar --warning=no-unknown-keyword -xzf "$tmp/$archive" -C "$runtime_dir" 2>/dev/null \
  509. || tar -xzf "$tmp/$archive" -C "$runtime_dir"; }; then
  510. rm -rf "$tmp" "$node_dir"
  511. return 1
  512. fi
  513. fi
  514. rm -rf "$tmp"
  515. node_bin=$(managed_node_bin "$node_dir" "$os") || node_bin=""
  516. if [ -z "$node_bin" ]; then
  517. echo "managed node: extracted archive has no usable node binary under $node_dir (bin/node or node.exe)" >&2
  518. rm -rf "$node_dir"
  519. return 1
  520. fi
  521. if [ "$os" = "darwin" ] && command -v xattr >/dev/null 2>&1; then
  522. xattr -dr com.apple.quarantine "$node_dir" 2>/dev/null || true
  523. fi
  524. echo "$node_bin"
  525. }
  526. ensure_node_modules() {
  527. # ensure_node_modules <app-version> (expects PERMANENT_DIR to point at the deployed version dir)
  528. local app_version="${1:-latest}"
  529. local tuple os arch
  530. tuple=$(managed_node_platform) || return 1
  531. os="${tuple% *}"; arch="${tuple#* }"
  532. local modules_dir="$PERMANENT_DIR/node_modules"
  533. local marker="$modules_dir/.pilot-modules-version"
  534. local stamp="${app_version} ${os} ${arch}"
  535. if [ -d "$modules_dir" ] && [ "$(cat "$marker" 2>/dev/null)" = "$stamp" ]; then
  536. return 0
  537. fi
  538. local archive="node-modules-${os}-${arch}.tar.gz"
  539. local base="${NODE_MODULES_BASE%/}/${app_version}"
  540. local tmp
  541. tmp=$(mktemp -d) || return 1
  542. _mn_msg "==> 下载预编译 node_modules (${os}-${arch}, app v${app_version})..." \
  543. "==> Downloading prebuilt node_modules (${os}-${arch}, app v${app_version})..."
  544. if ! managed_node_download "$base/$archive" "$tmp/$archive" \
  545. || ! managed_node_download "$base/SHASUMS256.txt" "$tmp/SHASUMS256.txt" \
  546. || ! managed_node_verify "$tmp/$archive" "$tmp/SHASUMS256.txt" "$archive"; then
  547. rm -rf "$tmp"
  548. return 1
  549. fi
  550. local stage="$tmp/stage"
  551. mkdir -p "$stage"
  552. if ! { tar --warning=no-unknown-keyword -xzf "$tmp/$archive" -C "$stage" 2>/dev/null \
  553. || tar -xzf "$tmp/$archive" -C "$stage"; }; then
  554. rm -rf "$tmp"
  555. return 1
  556. fi
  557. if [ ! -d "$stage/node_modules" ]; then
  558. rm -rf "$tmp"
  559. echo "managed node_modules: archive does not contain node_modules/" >&2
  560. return 1
  561. fi
  562. echo "$stamp" > "$stage/node_modules/.pilot-modules-version"
  563. rm -rf "$modules_dir"
  564. if ! mv "$stage/node_modules" "$modules_dir"; then
  565. rm -rf "$tmp"
  566. return 1
  567. fi
  568. rm -rf "$tmp"
  569. return 0
  570. }
  571. run_npm() {
  572. # npm shipped with the managed runtime is a symlink to npm-cli.js, whose
  573. # `#!/usr/bin/env node` shebang resolves node through PATH. The runtime's bin dir
  574. # is not on PATH, so calling "$NPM_BIN" directly dies with
  575. # "env: node: No such file or directory" on hosts without a system node — exactly
  576. # the hosts the managed runtime exists for. Mirrors the .ps1 npm fallback, which
  577. # already prepends the node dir.
  578. PATH="$(dirname "$NODE_BIN"):$PATH" "$NPM_BIN" "$@"
  579. }
  580. # <<< managed-node-runtime <<<
  581. check_deps() {
  582. msg "==> 检查依赖..." "==> Checking dependencies..."
  583. NODE_BIN=""
  584. if [ "${PREFER_SYSTEM_NODE:-0}" -eq 1 ]; then
  585. NODE_BIN=$(resolve_node) || NODE_BIN=""
  586. if [ -z "$NODE_BIN" ]; then
  587. msg " ⚠️ 系统 Node.js 不可用或无法加载 node:sqlite(需要 22.13+ 或 23.4+),改用托管运行时" \
  588. " ⚠️ System Node.js is missing or cannot load node:sqlite (need 22.13+ or 23.4+); using the managed runtime"
  589. NODE_BIN=$(ensure_managed_node) || NODE_BIN=""
  590. fi
  591. else
  592. NODE_BIN=$(ensure_managed_node) || NODE_BIN=""
  593. if [ -z "$NODE_BIN" ]; then
  594. msg " ⚠️ 托管 Node.js 不可用(平台不支持或下载失败),回退系统 node" \
  595. " ⚠️ Managed Node.js unavailable (unsupported platform or download failed), falling back to system node"
  596. NODE_BIN=$(resolve_node) || NODE_BIN=""
  597. fi
  598. fi
  599. if [ -z "$NODE_BIN" ]; then
  600. msg "❌ 缺少可用的 Node.js:需要能加载 node:sqlite 的版本(22.13+ / 23.4+),或成功下载托管运行时" \
  601. "❌ No usable Node.js: node:sqlite must load (22.13+ / 23.4+), or the managed runtime must download"
  602. exit 1
  603. fi
  604. if ! _node_supports_sqlite "$NODE_BIN"; then
  605. local node_ver
  606. node_ver="$("$NODE_BIN" --version 2>/dev/null || echo unknown)"
  607. msg "❌ 当前 Node.js 无法加载 node:sqlite(${node_ver})。需要 22.13+ 或 23.4+(无需 --experimental-sqlite),或托管运行时。" \
  608. "❌ This Node.js cannot load node:sqlite (${node_ver}). Need 22.13+ or 23.4+ (unflagged), or the managed runtime."
  609. exit 1
  610. fi
  611. # Pin the node binary path
  612. mkdir -p "$DATA_DIR" 2>/dev/null || true
  613. echo "$NODE_BIN" > "$DATA_DIR/node-bin"
  614. # Derive npm from the same installation
  615. NPM_BIN="$(dirname "$NODE_BIN")/npm"
  616. if [ ! -x "$NPM_BIN" ]; then
  617. if command -v npm &>/dev/null; then
  618. NPM_BIN=$(command -v npm)
  619. else
  620. msg "❌ 缺少依赖: npm,请先安装后重试" \
  621. "❌ Missing dependency: npm — please install it first"
  622. exit 1
  623. fi
  624. fi
  625. if [ "$(uname)" = "Darwin" ]; then
  626. local sys_arch; sys_arch=$(uname -m)
  627. local node_arch; node_arch=$("$NODE_BIN" -e "process.stdout.write(process.arch)")
  628. if [ "$sys_arch" = "arm64" ] && [ "$node_arch" = "x64" ]; then
  629. msg "⚠️ 架构不匹配: 系统为 arm64 (Apple Silicon),但 Node.js 为 x64 (Intel)" \
  630. "⚠️ Architecture mismatch: system is arm64 but Node.js is x64 (Intel)"
  631. msg " 原生模块可能无法正常加载,建议安装 arm64 版本的 Node.js" \
  632. " Native modules may fail to load. Please install arm64 Node.js"
  633. fi
  634. fi
  635. if ! command -v curl &>/dev/null && ! command -v wget &>/dev/null; then
  636. msg "❌ 需要 curl 或 wget,请先安装" \
  637. "❌ curl or wget is required — please install one first"
  638. exit 1
  639. fi
  640. msg " ✅ node $("$NODE_BIN" --version) npm $(run_npm --version)" \
  641. " ✅ node $("$NODE_BIN" --version) npm $(run_npm --version)"
  642. msg " node pinned: $NODE_BIN" " node pinned: $NODE_BIN"
  643. echo ""
  644. }
  645. # ============================================================
  646. # Common: download and extract package -> sets INSTALL_SRC
  647. # ============================================================
  648. download_and_extract() {
  649. TMP_DIR="$(mktemp -d)"
  650. # TMP_DIR cleanup is handled by the caller's trap
  651. msg "==> 下载安装包: $PACKAGE_URL" \
  652. "==> Downloading: $PACKAGE_URL"
  653. if command -v curl &>/dev/null; then
  654. curl -fsSL "$PACKAGE_URL" -o "$TMP_DIR/package.tar.gz"
  655. else
  656. wget -q "$PACKAGE_URL" -O "$TMP_DIR/package.tar.gz"
  657. fi
  658. msg " ✅ 下载完成" " ✅ Downloaded"
  659. echo ""
  660. msg "==> 解压安装包..." "==> Extracting..."
  661. if tar --warning=no-unknown-keyword -xzf "$TMP_DIR/package.tar.gz" -C "$TMP_DIR" 2>/dev/null; then
  662. :
  663. else
  664. tar -xzf "$TMP_DIR/package.tar.gz" -C "$TMP_DIR"
  665. fi
  666. if [ -d "$TMP_DIR/$PACKAGE_NAME" ]; then
  667. INSTALL_SRC="$TMP_DIR/$PACKAGE_NAME"
  668. elif [ -f "$TMP_DIR/package.json" ]; then
  669. INSTALL_SRC="$TMP_DIR"
  670. else
  671. INSTALL_SRC=$(find "$TMP_DIR" -name "package.json" -maxdepth 2 -exec dirname {} \; | head -1 || true)
  672. if [ -z "$INSTALL_SRC" ]; then
  673. msg "❌ 解压后未找到 package.json,安装包结构异常" \
  674. "❌ package.json not found — unexpected package structure"
  675. exit 1
  676. fi
  677. fi
  678. msg " ✅ 解压完成" " ✅ Extracted"
  679. echo ""
  680. }
  681. # ============================================================
  682. # Agent probe: detect available agents via Node.js CLI probe
  683. # ============================================================
  684. PROBE_RESULT="[]"
  685. probe_agents() {
  686. msg "==> 探测 AI Agent..." "==> Probing AI Agents..."
  687. PROBE_RESULT=$("$NODE_BIN" "$INSTALL_SRC/dist/cli-probe.cjs" --installer --config-path "$DATA_DIR/config.json" 2>/dev/null) || {
  688. msg " ⚠️ Agent 探测失败,将跳过选择" " ⚠️ Agent probe failed, skipping selection"
  689. PROBE_RESULT="[]"
  690. return 0
  691. }
  692. local count
  693. count=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "const r=JSON.parse(require('fs').readFileSync(0,'utf8'));process.stdout.write(String(r.length))" 2>/dev/null || echo "0")
  694. msg " ✅ 探测到 ${count} 个 Agent 定义" " ✅ Found ${count} agent definitions"
  695. echo ""
  696. }
  697. # ============================================================
  698. # Agent selection: interactive menu or --agents flag
  699. # ============================================================
  700. select_agents() {
  701. # --all-agents: collect every agent. Skip selection entirely and leave no
  702. # enabled gate in config (other agent settings survive), so pilot auto-detects
  703. # all agents at runtime — including ones installed after this run.
  704. if [ "$ALL_AGENTS" = "1" ]; then
  705. if [ -n "$SELECTED_AGENTS" ]; then
  706. msg " ⚠️ --all-agents 已启用,忽略 --agents 指定的列表" \
  707. " ⚠️ --all-agents is set; ignoring the --agents list"
  708. SELECTED_AGENTS=""
  709. fi
  710. msg " 采集全部 Agent (不写入选择,由 pilot 运行时自动探测)" \
  711. " Collecting all agents (no selection written; pilot auto-detects at runtime)"
  712. echo ""
  713. return 0
  714. fi
  715. if [ -n "$SELECTED_AGENTS" ]; then
  716. msg " 使用指定的 Agent: $SELECTED_AGENTS" " Using specified agents: $SELECTED_AGENTS"
  717. echo ""
  718. return 0
  719. fi
  720. local agent_count
  721. agent_count=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "const r=JSON.parse(require('fs').readFileSync(0,'utf8'));process.stdout.write(String(r.length))" 2>/dev/null || echo "0")
  722. if [ "$agent_count" = "0" ]; then
  723. return 0
  724. fi
  725. # Non-interactive: auto-select all detected agents
  726. if [ ! -t 0 ] || [ "$HOOK_INSTALL_SCOPE" = system ]; then
  727. SELECTED_AGENTS=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
  728. const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
  729. const detected = r.filter(a => a.detected).map(a => a.id);
  730. process.stdout.write(detected.join(','));
  731. " 2>/dev/null || true)
  732. msg " 自动选择已检测到的 Agent: $SELECTED_AGENTS" \
  733. " Auto-selected detected agents: $SELECTED_AGENTS"
  734. echo ""
  735. return 0
  736. fi
  737. # Interactive menu
  738. printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
  739. const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
  740. const lang = process.argv[1];
  741. const defaults = [];
  742. for (let i = 0; i < r.length; i++) {
  743. const a = r[i];
  744. const status = lang === 'zh'
  745. ? (a.detected ? '已检测到: ' + a.reason : '未检测到' + (a.reason ? ': ' + a.reason : ''))
  746. : (a.detected ? 'detected: ' + a.reason : 'not detected' + (a.reason ? ': ' + a.reason : ''));
  747. console.log(' [' + (i+1) + '] ' + a.displayName.padEnd(16) + '(' + status + ')');
  748. if (a.detected) defaults.push(i+1);
  749. }
  750. console.log('');
  751. if (lang === 'zh') {
  752. console.log(' 默认选择已检测到的 Agent: ' + defaults.join(','));
  753. console.log(' 输入要启用的编号 (逗号分隔),直接回车使用默认:');
  754. } else {
  755. console.log(' Default selection (detected): ' + defaults.join(','));
  756. console.log(' Enter numbers to enable (comma-separated), press Enter for default:');
  757. }
  758. " "$LANG_MODE"
  759. # Read user input (Node readline handles UTF-8 editing; normalize Chinese punctuation).
  760. # Prompt must go to stderr so it is visible and not captured by $().
  761. local select_input
  762. select_input=$("$NODE_BIN" -e "
  763. const readline = require('readline');
  764. const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
  765. rl.question(' > ', (answer) => {
  766. const normalized = answer.replace(/[,、;]/g, ',').trim();
  767. process.stdout.write(normalized);
  768. rl.close();
  769. });
  770. ") || {
  771. printf " > " >&2
  772. read -r select_input
  773. select_input=$(printf '%s' "$select_input" | sed 's/,/,/g; s/、/,/g; s/;/,/g')
  774. }
  775. # Compute final selection: empty input = detected agents, otherwise use exact input
  776. if [ -n "$select_input" ]; then AGENT_SELECTION_EXPLICIT=1; fi
  777. SELECTED_AGENTS=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
  778. const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
  779. const input = (process.argv[1] || '').replace(/[,、;]/g, ',');
  780. let indices;
  781. if (!input.trim()) {
  782. indices = r.map((a, i) => a.detected ? i : -1).filter(i => i >= 0);
  783. } else {
  784. indices = [...new Set(input.trim().split(/[\s,]+/).map(Number).filter(n => n >= 1 && n <= r.length))].map(n => n - 1);
  785. }
  786. const ids = indices.sort((a,b) => a-b).map(i => r[i].id);
  787. process.stdout.write(ids.join(','));
  788. " "$select_input" 2>/dev/null || true)
  789. if [ -n "$SELECTED_AGENTS" ]; then
  790. msg " 已选择: $SELECTED_AGENTS" " Selected: $SELECTED_AGENTS"
  791. else
  792. msg " 未选择任何 Agent" " No agents selected"
  793. fi
  794. echo ""
  795. }
  796. # ============================================================
  797. # Interactive: prompt for userId (skipped when --userId given or non-interactive)
  798. # ============================================================
  799. prompt_user_id() {
  800. if [ -n "$USER_ID" ]; then return 0; fi
  801. if [ ! -t 0 ]; then return 0; fi
  802. local existing_uid=""
  803. local config_file="$DATA_DIR/config.json"
  804. if [ -f "$config_file" ]; then
  805. existing_uid=$("$NODE_BIN" -e "
  806. try { const c=JSON.parse(require('fs').readFileSync(process.argv[1],'utf-8')); process.stdout.write(c.userId||''); } catch {}
  807. " -- "$config_file" 2>/dev/null || true)
  808. fi
  809. echo ""
  810. if [ -n "$existing_uid" ]; then
  811. msg " 当前 userId: $existing_uid" \
  812. " Current userId: $existing_uid"
  813. msg " 直接回车保留,或输入新值:" \
  814. " Press Enter to keep, or type a new value:"
  815. else
  816. msg " 请输入你的 userId(用于数据归属,可直接回车跳过):" \
  817. " Enter your userId (for data attribution, press Enter to skip):"
  818. fi
  819. printf " > "
  820. local input
  821. read -r input
  822. input=$(echo "$input" | tr -d '[:space:]')
  823. if [ -n "$input" ]; then
  824. USER_ID="$input"
  825. elif [ -n "$existing_uid" ]; then
  826. USER_ID="$existing_uid"
  827. fi
  828. }
  829. # ============================================================
  830. # Interactive: confirm config overwrite when key fields differ
  831. # ============================================================
  832. confirm_config_overwrite() {
  833. local config_file="$DATA_DIR/config.json"
  834. if [ ! -f "$config_file" ]; then return 0; fi
  835. local diffs
  836. diffs=$("$NODE_BIN" -e "
  837. const fs = require('fs');
  838. let old = {};
  839. try { old = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8')); } catch { process.exit(0); }
  840. const newVals = JSON.parse(process.argv[2]);
  841. const normalizeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean).join(',');
  842. const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
  843. const parseTypeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean);
  844. const uniqueTypes = list => [...new Set(list)];
  845. const interceptorModeFinal = newVals.interceptorMode || (old.interceptor||{}).mode || '';
  846. const interceptorTypesFinal = interceptorModeFinal === 'all'
  847. ? INTERCEPTOR_TYPE_SET.slice()
  848. : interceptorModeFinal === 'custom'
  849. ? parseTypeCsv(newVals.interceptorMode ? newVals.interceptorTypes : ((old.interceptor||{}).types||[]).join(',')).filter(t => INTERCEPTOR_TYPE_SET.indexOf(t) !== -1)
  850. : [];
  851. const maskModeFinal = newVals.maskMode || (old.mask||{}).mode || '';
  852. const maskTypesFinal = maskModeFinal === 'custom'
  853. ? parseTypeCsv(newVals.maskMode ? newVals.maskTypes : ((old.mask||{}).types||[]).join(','))
  854. : [];
  855. const coveredMaskMode = interceptorTypesFinal.length && maskModeFinal !== 'all' ? 'custom' : maskModeFinal;
  856. const coveredMaskTypes = coveredMaskMode === 'custom' ? uniqueTypes(maskTypesFinal.concat(interceptorTypesFinal)) : [];
  857. const slsModeOf = sls => {
  858. if (!sls) return '';
  859. if (sls.mode) return sls.mode;
  860. if (sls.apiKey) return 'apiKey';
  861. if (sls.accessKeyId || sls.accessKeySecret) return 'ak';
  862. return '';
  863. };
  864. const checks = [
  865. { label: 'sls.endpoint', oldVal: (old.sls||{}).endpoint||'', newVal: newVals.slsEndpoint },
  866. { label: 'sls.project', oldVal: (old.sls||{}).project||'', newVal: newVals.slsProject },
  867. { label: 'sls.logstore', oldVal: (old.sls||{}).logstore||'', newVal: newVals.slsLogstore },
  868. { label: 'sls.mode', oldVal: slsModeOf(old.sls), newVal: newVals.slsMode },
  869. { label: 'cms.licenseKey', oldVal: (old.cms||{}).licenseKey||'', newVal: newVals.cmsLicenseKey },
  870. { label: 'cms.endpoint', oldVal: (old.cms||{}).endpoint||'', newVal: newVals.cmsEndpoint },
  871. { label: 'cms.workspace', oldVal: (old.cms||{}).workspace||'', newVal: newVals.cmsWorkspace },
  872. { label: 'serviceNamePrefix', oldVal: old.serviceNamePrefix||'', newVal: newVals.serviceNamePrefix },
  873. { label: 'dashboard.port', oldVal: (old.dashboard||{}).port||'', newVal: newVals.dashboardPort ? Number(newVals.dashboardPort) : '' },
  874. { label: 'mask.mode', oldVal: (old.mask||{}).mode||'', newVal: coveredMaskMode },
  875. { label: 'mask.types', oldVal: (old.mask||{}).mode === 'custom' && Array.isArray((old.mask||{}).types) ? normalizeCsv(old.mask.types.join(',')) : '', newVal: coveredMaskTypes.join(',') },
  876. { label: 'mask.replacementMode', oldVal: (old.mask||{}).replacementMode||'', newVal: newVals.maskReplacementMode },
  877. { label: 'interceptor.mode', oldVal: (old.interceptor||{}).mode||'', newVal: newVals.interceptorMode },
  878. { label: 'interceptor.types', oldVal: Array.isArray((old.interceptor||{}).types) ? normalizeCsv(old.interceptor.types.join(',')) : '', newVal: normalizeCsv(newVals.interceptorTypes) },
  879. { label: 'multimodal.storage.type', oldVal: (old.multimodal && old.multimodal.storage && old.multimodal.storage.type) || '', newVal: (newVals.multimodalMode && newVals.multimodalMode !== 'none' && newVals.slsEndpoint && newVals.slsProject && newVals.slsLogstore && newVals.slsMode === 'apiKey') ? 'sls' : '' },
  880. ];
  881. const changed = checks.filter(c => c.newVal && c.oldVal && c.newVal !== c.oldVal);
  882. if (!changed.length) process.exit(0);
  883. for (const c of changed) {
  884. console.log(c.label + ': ' + c.oldVal + ' -> ' + c.newVal);
  885. }
  886. " -- "$config_file" "$(printf '{"slsEndpoint":"%s","slsProject":"%s","slsLogstore":"%s","slsMode":"%s","cmsLicenseKey":"%s","cmsEndpoint":"%s","cmsWorkspace":"%s","serviceNamePrefix":"%s","dashboardPort":"%s","maskMode":"%s","maskTypes":"%s","maskReplacementMode":"%s","interceptorMode":"%s","interceptorTypes":"%s","multimodalMode":"%s"}' \
  887. "$SLS_ENDPOINT" "$SLS_PROJECT" "$SLS_LOGSTORE" "$([ -n "$SLS_API_KEY" ] && echo "apiKey" || { [ -n "$SLS_AK_ID" ] && [ -n "$SLS_AK_SECRET" ] && echo "ak" || true; })" "$CMS_LICENSE_KEY" "$CMS_ENDPOINT" "$CMS_WORKSPACE" "$SERVICE_NAME_PREFIX" "$DASHBOARD_PORT" "$MASK_MODE" "$MASK_TYPES" "$MASK_REPLACEMENT_MODE" "$INTERCEPTOR_MODE" "$INTERCEPTOR_TYPES" "$MULTIMODAL_MODE")" 2>/dev/null || true)
  888. if [ -z "$diffs" ]; then return 0; fi
  889. echo ""
  890. msg "⚠️ 以下配置将被覆盖:" "⚠️ The following config will be overwritten:"
  891. echo "$diffs" | while IFS= read -r line; do
  892. echo " $line"
  893. done
  894. if [ -t 0 ]; then
  895. echo ""
  896. msg " 确认覆盖? (y/N):" " Confirm overwrite? (y/N):"
  897. printf " > "
  898. local answer
  899. read -r answer
  900. case "$answer" in
  901. y|Y|yes|YES) ;;
  902. *)
  903. msg "已取消安装" "Installation cancelled"
  904. exit 0
  905. ;;
  906. esac
  907. else
  908. msg " (非交互模式) 继续覆盖" \
  909. " (non-interactive) Proceeding with overwrite"
  910. fi
  911. }
  912. # ============================================================
  913. # Common: deploy bootstrap scripts from the current version
  914. # ============================================================
  915. deploy_bootstrap_scripts() {
  916. local src_dir="$PERMANENT_DIR/scripts"
  917. local boot_dir="$HOME/.loongsuite-pilot/bin"
  918. mkdir -p "$boot_dir"
  919. cp -f "$src_dir/collector-daemon.js" "$boot_dir/"
  920. [ -f "$src_dir/updater-daemon.js" ] && cp -f "$src_dir/updater-daemon.js" "$boot_dir/" || true
  921. }
  922. # ============================================================
  923. # Common: deploy package to versions/ directory
  924. # ============================================================
  925. deploy_package() {
  926. local src="$1"
  927. local cache_dir="$HOME/.loongsuite-pilot"
  928. local versions_dir="$cache_dir/versions"
  929. local current_file="$cache_dir/current"
  930. local previous_file="$cache_dir/previous"
  931. local ver="" commit=""
  932. if [ -f "$src/VERSION" ]; then
  933. ver=$(grep '^version=' "$src/VERSION" | cut -d= -f2)
  934. commit=$(grep '^git_commit=' "$src/VERSION" | cut -d= -f2)
  935. fi
  936. if [ -n "$ver" ] && [ -n "$commit" ]; then
  937. local dir_name="${ver}_${commit}"
  938. local target="$versions_dir/$dir_name"
  939. if [ -f "$current_file" ]; then
  940. local old_dir
  941. old_dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
  942. if [ -n "$old_dir" ] && [ "$old_dir" != "$dir_name" ]; then
  943. echo "$old_dir" > "$previous_file"
  944. fi
  945. fi
  946. msg "==> 部署到 $target ..." "==> Deploying to $target ..."
  947. mkdir -p "$versions_dir"
  948. rm -rf "$target"
  949. if ! cp -r "$src" "$target"; then
  950. msg " ❌ 文件部署失败" " ❌ File deployment failed"
  951. return 1
  952. fi
  953. PERMANENT_DIR="$target"
  954. else
  955. msg "==> 部署到 $PERMANENT_DIR ..." \
  956. "==> Deploying to $PERMANENT_DIR ..."
  957. mkdir -p "$(dirname "$PERMANENT_DIR")"
  958. rm -rf "$PERMANENT_DIR"
  959. if ! cp -r "$src" "$PERMANENT_DIR"; then
  960. msg " ❌ 文件部署失败" " ❌ File deployment failed"
  961. return 1
  962. fi
  963. fi
  964. msg " ✅ 部署完成" " ✅ Deployed"
  965. echo ""
  966. deploy_bootstrap_scripts
  967. msg "==> 安装依赖..." "==> Installing dependencies..."
  968. local modules_ver="${ver:-${INSTALL_VERSION:-latest}}"
  969. if ensure_node_modules "$modules_ver"; then
  970. msg " ✅ 依赖安装完成(预编译 node_modules)" " ✅ Dependencies installed (prebuilt node_modules)"
  971. else
  972. msg " ⚠️ 预编译 node_modules 不可用,回退 npm install" \
  973. " ⚠️ Prebuilt node_modules unavailable, falling back to npm install"
  974. if ! (cd "$PERMANENT_DIR" && run_npm install --production --no-optional 2>&1 | tail -1); then
  975. msg " ❌ 依赖安装失败" " ❌ Dependency installation failed"
  976. return 1
  977. fi
  978. msg " ✅ 依赖安装完成" " ✅ Dependencies installed"
  979. fi
  980. echo ""
  981. msg "==> 部署 hook 脚本..." "==> Deploying hook scripts..."
  982. if [ -f "$PERMANENT_DIR/scripts/postinstall.js" ]; then
  983. # postinstall.js falls back to $HOME/.loongsuite-pilot when this is unset, so
  984. # --data-dir would otherwise put hooks/skills/plugins in the default tree while
  985. # the config lives elsewhere.
  986. # Captured because two of the three failure modes are only in the output: a per-tree
  987. # failure and a thrown main() both exit 0 on purpose (a non-zero exit would abort the
  988. # npm install fallback above), announcing themselves as "N failed asset tree(s)" and
  989. # "Post-install failed: <reason>" instead. 2>&1 because both go to stderr.
  990. postinstall_exit=0
  991. postinstall_out="$(LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
  992. "$NODE_BIN" "$PERMANENT_DIR/scripts/postinstall.js" 2>&1)" || postinstall_exit=$?
  993. # `if`, not `[ -n ... ] && printf`: under set -e the latter aborts the function when
  994. # the output is empty.
  995. if [ -n "$postinstall_out" ]; then
  996. printf '%s\n' "$postinstall_out"
  997. fi
  998. if [ "$postinstall_exit" -ne 0 ]; then
  999. msg " ❌ Hook 脚本部署失败 (exit=$postinstall_exit),hooks/plugins 缺失" \
  1000. " ❌ Hook script deployment failed (exit=$postinstall_exit); hooks/plugins are missing"
  1001. return 1
  1002. fi
  1003. if printf '%s' "$postinstall_out" | grep -qE "failed asset tree|Post-install failed"; then
  1004. msg " ❌ Hook 脚本部分部署失败(见上方输出),hooks/plugins 缺失" \
  1005. " ❌ Some hook asset trees failed to deploy (see the output above); hooks/plugins are missing"
  1006. return 1
  1007. fi
  1008. msg " ✅ Hook 脚本已部署" " ✅ Hook scripts deployed"
  1009. msg " 如使用 Codex 桌面版,首次启动需在桌面端手动信任 hooks" \
  1010. " If using Codex desktop app, please manually trust hooks on first launch"
  1011. else
  1012. msg " ⚠️ postinstall.js 未找到,跳过 Hook 部署" \
  1013. " ⚠️ postinstall.js not found, skipping hook deployment"
  1014. fi
  1015. echo ""
  1016. # Write current pointer only after all deploy steps succeed
  1017. if [ -n "$ver" ] && [ -n "$commit" ]; then
  1018. echo "$dir_name" > "$current_file.tmp"
  1019. mv -f "$current_file.tmp" "$current_file"
  1020. fi
  1021. }
  1022. # ============================================================
  1023. # Migrate legacy single-directory layout to versions/ layout
  1024. # ============================================================
  1025. migrate_legacy_layout() {
  1026. local cache_dir="$HOME/.loongsuite-pilot"
  1027. local current_file="$cache_dir/current"
  1028. local legacy_dir="$cache_dir/package"
  1029. local versions_dir="$cache_dir/versions"
  1030. if [ -f "$current_file" ]; then
  1031. return 0
  1032. fi
  1033. if [ ! -d "$legacy_dir" ] || [ ! -f "$legacy_dir/dist/index.js" ]; then
  1034. return 0
  1035. fi
  1036. msg "==> 迁移旧版本目录结构..." "==> Migrating legacy directory layout..."
  1037. local ver="" commit=""
  1038. if [ -f "$legacy_dir/VERSION" ]; then
  1039. ver=$(grep '^version=' "$legacy_dir/VERSION" | cut -d= -f2)
  1040. commit=$(grep '^git_commit=' "$legacy_dir/VERSION" | cut -d= -f2)
  1041. fi
  1042. ver="${ver:-0.0.0}"
  1043. commit="${commit:-legacy}"
  1044. local dir_name="${ver}_${commit}"
  1045. local target="$versions_dir/$dir_name"
  1046. mkdir -p "$versions_dir"
  1047. cp -r "$legacy_dir" "$target"
  1048. echo "$dir_name" > "$current_file"
  1049. PERMANENT_DIR="$target"
  1050. msg " ✅ 已迁移到 $target" " ✅ Migrated to $target"
  1051. echo ""
  1052. }
  1053. # ============================================================
  1054. # Common: write / merge config.json
  1055. # ============================================================
  1056. write_config() {
  1057. local config_file="$DATA_DIR/config.json"
  1058. msg "==> 写入配置文件 $config_file ..." \
  1059. "==> Writing config to $config_file ..."
  1060. mkdir -p "$DATA_DIR"
  1061. local excluded_workspaces_json=""
  1062. if [ "${#EXCLUDE_WORKSPACES[@]}" -gt 0 ]; then
  1063. excluded_workspaces_json=$("$NODE_BIN" -e 'console.log(JSON.stringify(process.argv.slice(1)))' -- "${EXCLUDE_WORKSPACES[@]}")
  1064. fi
  1065. printf '%s' "$PROBE_RESULT" | \
  1066. LP_EXCLUDE_WORKSPACES="$excluded_workspaces_json" \
  1067. LP_SLS_API_KEY="$SLS_API_KEY" \
  1068. LP_SELECTED_AGENTS="$SELECTED_AGENTS" \
  1069. LP_AGENT_SELECTION_EXPLICIT="$AGENT_SELECTION_EXPLICIT" \
  1070. LP_MULTIMODAL_MODE="$MULTIMODAL_MODE" \
  1071. LP_MULTIMODAL_SUPPORTED_AGENTS="$MULTIMODAL_SUPPORTED_AGENTS" \
  1072. LP_DASHBOARD_PORT="$DASHBOARD_PORT" \
  1073. LP_ENABLE_STATUS_BAR_APP="$ENABLE_STATUS_BAR_APP" \
  1074. "$NODE_BIN" -e "
  1075. const fs = require('fs');
  1076. const path = '$config_file';
  1077. let existing = {};
  1078. try { existing = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
  1079. const config = {
  1080. ...existing,
  1081. enabled: true,
  1082. dataDir: '$DATA_DIR',
  1083. };
  1084. if (!config.dashboard || typeof config.dashboard !== 'object' || Array.isArray(config.dashboard)) {
  1085. config.dashboard = {};
  1086. }
  1087. if (process.env.LP_EXCLUDE_WORKSPACES) {
  1088. config.privacy = { ...config.privacy, excludeWorkspaces: JSON.parse(process.env.LP_EXCLUDE_WORKSPACES) };
  1089. }
  1090. const dashboardPort = process.env.LP_DASHBOARD_PORT || '';
  1091. const enableStatusBarApp = process.env.LP_ENABLE_STATUS_BAR_APP || '';
  1092. if (enableStatusBarApp) config.enableStatusBarApp = enableStatusBarApp === 'true';
  1093. if (dashboardPort) config.dashboard.port = Number(dashboardPort);
  1094. if (config.dashboard.port === undefined) config.dashboard.port = 8765;
  1095. delete config.internal;
  1096. if (config.userId === undefined && config['user.id'] !== undefined) {
  1097. config.userId = config['user.id'];
  1098. }
  1099. delete config['user.id'];
  1100. const slsEndpoint = '${SLS_ENDPOINT}';
  1101. const slsProject = '${SLS_PROJECT}';
  1102. const slsLogstore = '${SLS_LOGSTORE}';
  1103. const slsAkId = '${SLS_AK_ID}';
  1104. const slsAkSecret = '${SLS_AK_SECRET}';
  1105. const slsApiKey = process.env.LP_SLS_API_KEY || '';
  1106. const logLevel = '${LOG_LEVEL}';
  1107. const userId = '${USER_ID}';
  1108. if (slsEndpoint || slsProject || slsLogstore || slsApiKey) {
  1109. config.sls = config.sls || {};
  1110. delete config.sls.destinationOverride;
  1111. if (slsEndpoint) {
  1112. config.sls.endpoint = slsEndpoint;
  1113. }
  1114. if (slsApiKey) {
  1115. config.sls.mode = 'apiKey';
  1116. config.sls.apiKey = slsApiKey;
  1117. delete config.sls.accessKeyId;
  1118. delete config.sls.accessKeySecret;
  1119. } else if (slsAkId && slsAkSecret) {
  1120. config.sls.mode = 'ak';
  1121. config.sls.accessKeyId = slsAkId;
  1122. config.sls.accessKeySecret = slsAkSecret;
  1123. delete config.sls.apiKey;
  1124. } else if (slsEndpoint || slsProject || slsLogstore) {
  1125. config.sls.mode = 'webtracking';
  1126. delete config.sls.apiKey;
  1127. delete config.sls.accessKeyId;
  1128. delete config.sls.accessKeySecret;
  1129. }
  1130. if (slsProject && slsLogstore) {
  1131. config.sls.project = slsProject;
  1132. config.sls.logstore = slsLogstore;
  1133. delete config.sls.endpoints;
  1134. }
  1135. }
  1136. if (logLevel) {
  1137. config.logLevel = logLevel;
  1138. }
  1139. if (userId) {
  1140. config.userId = userId;
  1141. delete config.identity;
  1142. }
  1143. const collectLog = '${COLLECT_LOG}';
  1144. const collectTrace = '${COLLECT_TRACE}';
  1145. const cmsLicenseKey = '${CMS_LICENSE_KEY}';
  1146. const cmsEndpoint = '${CMS_ENDPOINT}';
  1147. const cmsWorkspace = '${CMS_WORKSPACE}';
  1148. const serviceNamePrefix = '${SERVICE_NAME_PREFIX}';
  1149. const selectedAgents = process.env.LP_SELECTED_AGENTS || '';
  1150. const allAgentsMode = '${ALL_AGENTS}';
  1151. const multimodalMode = process.env.LP_MULTIMODAL_MODE || '';
  1152. const maskMode = '${MASK_MODE}';
  1153. const maskTypes = '${MASK_TYPES}';
  1154. const maskReplacementMode = '${MASK_REPLACEMENT_MODE}';
  1155. const interceptorMode = '${INTERCEPTOR_MODE}';
  1156. const interceptorTypes = '${INTERCEPTOR_TYPES}';
  1157. if (collectLog) config.collectLog = collectLog === 'true';
  1158. if (collectTrace) config.collectTrace = collectTrace === 'true';
  1159. if (cmsLicenseKey || cmsEndpoint || cmsWorkspace) {
  1160. config.cms = config.cms || {};
  1161. if (cmsLicenseKey) config.cms.licenseKey = cmsLicenseKey;
  1162. if (cmsEndpoint) config.cms.endpoint = cmsEndpoint;
  1163. if (cmsWorkspace) config.cms.workspace = cmsWorkspace;
  1164. }
  1165. if (serviceNamePrefix) config.serviceNamePrefix = serviceNamePrefix;
  1166. if (maskMode) {
  1167. config.mask = config.mask || {};
  1168. config.mask.mode = maskMode;
  1169. if (maskMode === 'custom') {
  1170. config.mask.types = maskTypes
  1171. .split(',')
  1172. .map(type => type.trim())
  1173. .filter(Boolean);
  1174. } else {
  1175. delete config.mask.types;
  1176. }
  1177. }
  1178. if (maskReplacementMode) {
  1179. config.mask = config.mask || {};
  1180. config.mask.replacementMode = maskReplacementMode;
  1181. }
  1182. if (interceptorMode) {
  1183. config.interceptor = config.interceptor || {};
  1184. config.interceptor.mode = interceptorMode;
  1185. if (interceptorMode === 'custom') {
  1186. config.interceptor.types = interceptorTypes
  1187. .split(',')
  1188. .map(type => type.trim())
  1189. .filter(Boolean);
  1190. } else {
  1191. delete config.interceptor.types;
  1192. }
  1193. }
  1194. const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
  1195. (function ensureMaskCoversInterceptor(config) {
  1196. const interceptor = config.interceptor || {};
  1197. const extra = interceptor.mode === 'all'
  1198. ? INTERCEPTOR_TYPE_SET.slice()
  1199. : interceptor.mode === 'custom' && Array.isArray(interceptor.types)
  1200. ? interceptor.types.filter(type => INTERCEPTOR_TYPE_SET.indexOf(type) !== -1)
  1201. : [];
  1202. if (extra.length === 0) return;
  1203. if ((config.mask || {}).mode === 'all') return;
  1204. const current = (config.mask || {}).mode === 'custom' && Array.isArray((config.mask || {}).types)
  1205. ? config.mask.types.filter(type => typeof type === 'string' && type.trim())
  1206. : [];
  1207. config.mask = config.mask && typeof config.mask === 'object' && !Array.isArray(config.mask)
  1208. ? config.mask
  1209. : {};
  1210. config.mask.mode = 'custom';
  1211. config.mask.types = [...new Set(current.concat(extra))];
  1212. })(config);
  1213. const allAgents = JSON.parse(fs.readFileSync(0, 'utf8') || '[]');
  1214. if (allAgentsMode === '1') {
  1215. // Clear enable gates, not metadata such as a persisted OpenClaw entry.
  1216. for (const agent of Object.values(config.agents || {})) delete agent.enabled;
  1217. } else if (selectedAgents) {
  1218. config.agents = config.agents || {};
  1219. const previousOpenclaw = config.agents.openclaw;
  1220. const selected = selectedAgents.split(',').map(s => s.trim()).filter(Boolean);
  1221. for (const agent of allAgents) {
  1222. config.agents[agent.id] = config.agents[agent.id] || {};
  1223. // A transient discovery miss is not consent to uninstall a live plugin.
  1224. if (agent.id === 'openclaw' && !agent.detected && process.env.LP_AGENT_SELECTION_EXPLICIT !== '1'
  1225. && previousOpenclaw !== undefined) {
  1226. console.log('OpenClaw: detection unavailable; preserving previous enabled state and entry');
  1227. continue;
  1228. }
  1229. config.agents[agent.id].enabled = selected.includes(agent.id);
  1230. }
  1231. }
  1232. const openclaw = allAgents.find(agent => agent.id === 'openclaw');
  1233. if (openclaw && openclaw.detected && openclaw.openclawCliPath
  1234. && (allAgentsMode === '1' || (config.agents && config.agents.openclaw && config.agents.openclaw.enabled !== false))) {
  1235. config.agents = config.agents || {};
  1236. config.agents.openclaw = config.agents.openclaw || {};
  1237. const previousEntry = config.agents.openclaw.cliPath;
  1238. if (typeof previousEntry === 'string' && previousEntry !== openclaw.openclawCliPath) {
  1239. console.log('OpenClaw: updating launch entry ' + JSON.stringify(previousEntry) + ' -> ' + JSON.stringify(openclaw.openclawCliPath));
  1240. }
  1241. config.agents.openclaw.cliPath = openclaw.openclawCliPath;
  1242. }
  1243. if (multimodalMode) {
  1244. config.agents = config.agents || {};
  1245. const supported = (process.env.LP_MULTIMODAL_SUPPORTED_AGENTS || '').split(',').map(s => s.trim()).filter(Boolean);
  1246. const selected = new Set(selectedAgents.split(',').map(s => s.trim()).filter(Boolean));
  1247. const allSupported = allAgentsMode === '1' && multimodalMode !== 'none';
  1248. for (const id of supported) {
  1249. if (allSupported) config.agents[id] = config.agents[id] || {};
  1250. else if (!config.agents[id]) continue;
  1251. if (multimodalMode === 'none') {
  1252. delete config.agents[id].multimodal;
  1253. continue;
  1254. }
  1255. const prev = (config.agents[id].multimodal && typeof config.agents[id].multimodal === 'object')
  1256. ? config.agents[id].multimodal
  1257. : {};
  1258. config.agents[id].multimodal = { ...prev, uploadMode: (allSupported || selected.has(id)) ? multimodalMode : 'none' };
  1259. }
  1260. }
  1261. if (multimodalMode && multimodalMode !== 'none' && slsEndpoint && slsProject && slsLogstore && slsApiKey) {
  1262. config.multimodal = {
  1263. storage: {
  1264. type: 'sls',
  1265. target: { endpoint: slsEndpoint, project: slsProject, logstore: slsLogstore },
  1266. },
  1267. };
  1268. }
  1269. fs.writeFileSync(path, JSON.stringify(config, null, 2) + '\n');
  1270. "
  1271. msg " ✅ 配置已写入" " ✅ Config written"
  1272. echo ""
  1273. }
  1274. # ============================================================
  1275. # Common: install/update the loongsuite-pilot service management script
  1276. # ============================================================
  1277. install_loongsuite_pilot_command() {
  1278. msg "==> 安装服务管理脚本..." "==> Installing service management script..."
  1279. local global_bin_dir="$HOME/.local/bin"
  1280. mkdir -p "$global_bin_dir"
  1281. local loongsuite_pilot_cmd="$global_bin_dir/loongsuite-pilot"
  1282. cp -f "$PERMANENT_DIR/scripts/loongsuite-pilot.sh" "$loongsuite_pilot_cmd"
  1283. chmod +x "$loongsuite_pilot_cmd"
  1284. msg " ✅ 已安装: $loongsuite_pilot_cmd" " ✅ Installed: $loongsuite_pilot_cmd"
  1285. # If /usr/local/bin is writable (root), create a symlink for immediate PATH access
  1286. if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
  1287. ln -sf "$loongsuite_pilot_cmd" /usr/local/bin/loongsuite-pilot
  1288. msg " ✅ 已链接到 /usr/local/bin/loongsuite-pilot" " ✅ Linked to /usr/local/bin/loongsuite-pilot"
  1289. else
  1290. ensure_path_block() {
  1291. local file="$1"
  1292. if [ ! -f "$file" ]; then
  1293. touch "$file" 2>/dev/null || return 0
  1294. fi
  1295. if [ ! -w "$file" ]; then
  1296. msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
  1297. return 0
  1298. fi
  1299. if grep -q '\.local/bin' "$file" 2>/dev/null; then return 0; fi
  1300. # Ensure file ends with a newline before appending
  1301. [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
  1302. cat >> "$file" << 'PATHBLOCK'
  1303. # loongsuite-pilot: add ~/.local/bin to PATH
  1304. export PATH="$HOME/.local/bin:$PATH"
  1305. PATHBLOCK
  1306. msg " 已将 ~/.local/bin 添加到 PATH ($file)" \
  1307. " Added ~/.local/bin to PATH ($file)"
  1308. }
  1309. case "${SHELL:-/bin/bash}" in
  1310. */zsh)
  1311. ensure_path_block "$HOME/.zshrc" || true
  1312. ;;
  1313. */bash)
  1314. ensure_path_block "$HOME/.bashrc" || true
  1315. # Do not create ~/.bash_profile just to add PATH. On Debian/Ubuntu
  1316. # style accounts, its mere presence prevents bash login shells from
  1317. # reading ~/.profile, which often sources ~/.bashrc and user aliases.
  1318. if [ -f "$HOME/.bash_profile" ]; then
  1319. ensure_path_block "$HOME/.bash_profile" || true
  1320. elif [ -f "$HOME/.bash_login" ]; then
  1321. ensure_path_block "$HOME/.bash_login" || true
  1322. else
  1323. ensure_path_block "$HOME/.profile" || true
  1324. fi
  1325. ;;
  1326. *)
  1327. ensure_path_block "$HOME/.bashrc" || true
  1328. ;;
  1329. esac
  1330. fi
  1331. echo ""
  1332. # Ensure loongsuite-pilot is on PATH for the rest of this script
  1333. export PATH="$global_bin_dir:$PATH"
  1334. }
  1335. # ============================================================
  1336. # qodercli token intercept: inject/remove shell function
  1337. # ============================================================
  1338. _sed_inplace() {
  1339. if [[ "$(uname)" == "Darwin" ]]; then
  1340. sed -i '' "$@"
  1341. else
  1342. sed -i "$@"
  1343. fi
  1344. }
  1345. # Is `needle` present INSIDE the begin/end marker region of `file`?
  1346. # Signature checks must be scoped this way rather than grepping the whole rc
  1347. # file: the qodercli and qoderclicn blocks both name the same wrapper script, so
  1348. # a file-wide match lets one block vouch for the other and a stale block never
  1349. # gets migrated. Mirrors extractMarkerBlock() in src/core/hook-watchdog.ts.
  1350. _rc_block_contains() {
  1351. local file="$1" begin="$2" end="$3" needle="$4"
  1352. sed -n "/$begin/,/$end/p" "$file" 2>/dev/null | grep -qF "$needle"
  1353. }
  1354. inject_qodercli_token_intercept() {
  1355. # Not selected: clean up any stale block from a prior install, then bail.
  1356. if [ "$ALL_AGENTS" != "1" ] && ! echo "$SELECTED_AGENTS" | grep -q 'qoder'; then remove_qodercli_token_intercept; return 0; fi
  1357. if ! command -v qodercli >/dev/null 2>&1; then return 0; fi
  1358. local intercept_script="$DATA_DIR/hooks/qodercli-token-intercept.mjs"
  1359. local runtime_wrapper="$DATA_DIR/hooks/qodercli-runtime-wrapper.sh"
  1360. if [ ! -f "$intercept_script" ] || [ ! -f "$runtime_wrapper" ]; then return 0; fi
  1361. msg "==> 配置 qodercli token 采集..." "==> Configuring qodercli token intercept..."
  1362. _inject_to_rc() {
  1363. local file="$1"
  1364. if [ ! -f "$file" ]; then return 0; fi
  1365. if [ ! -w "$file" ]; then
  1366. msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
  1367. return 0
  1368. fi
  1369. # Migrate-or-skip: our block may already be present. If it is the current
  1370. # guard shape (signature line present) we're done; otherwise it is an
  1371. # older released bare-function block sharing the same marker — remove it
  1372. # so the new guarded block below replaces it (the old bare block
  1373. # parse-errors under a user alias, which is exactly what we're fixing).
  1374. if grep -q 'loongsuite-pilot BEGIN qodercli-intercept' "$file" 2>/dev/null; then
  1375. if _rc_block_contains "$file" \
  1376. 'loongsuite-pilot BEGIN qodercli-intercept' \
  1377. 'loongsuite-pilot END qodercli-intercept' \
  1378. 'qodercli-runtime-wrapper.sh'; then return 0; fi
  1379. _sed_inplace '/# loongsuite-pilot BEGIN qodercli-intercept/,/# loongsuite-pilot END qodercli-intercept/d' "$file"
  1380. fi
  1381. [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
  1382. # Double-quoted heredoc so $DATA_DIR expands at install time, honoring
  1383. # --data-dir overrides. $@ is escaped to defer expansion to runtime.
  1384. # The `if ! alias ... eval '...'` shape guards against clobbering a
  1385. # user's own qodercli alias/function AND avoids a parse error: a bare
  1386. # qodercli() token would fail to parse under an active alias (interactive
  1387. # shells expand aliases at parse time, before the guard runs), so the
  1388. # definition is deferred behind eval. Keep byte-identical to the
  1389. # watchdog's blockFn (src/core/hook-watchdog.ts).
  1390. cat >> "$file" << INTERCEPTBLOCK
  1391. # loongsuite-pilot BEGIN qodercli-intercept
  1392. if ! alias qodercli >/dev/null 2>&1 && ! typeset -f qodercli >/dev/null 2>&1; then
  1393. eval 'qodercli() { "$DATA_DIR/hooks/qodercli-runtime-wrapper.sh" "\$@"; }'
  1394. fi
  1395. # loongsuite-pilot END qodercli-intercept
  1396. INTERCEPTBLOCK
  1397. msg " ✅ 已写入 $file (请执行 source $file 或打开新终端)" \
  1398. " ✅ Written to $file (run: source $file or open a new terminal)"
  1399. }
  1400. case "${SHELL:-/bin/bash}" in
  1401. */zsh) _inject_to_rc "$HOME/.zshrc" ;;
  1402. */bash) _inject_to_rc "$HOME/.bashrc" ;;
  1403. *) _inject_to_rc "$HOME/.bashrc" ;;
  1404. esac
  1405. # If the user already defines their own `qodercli`, our guard skipped the
  1406. # wrapper (to avoid clobbering it), so collection won't run. Tell them how
  1407. # to opt in, since there is otherwise no signal explaining the silence.
  1408. if _rc_user_override_present qodercli \
  1409. 'loongsuite-pilot BEGIN qodercli-intercept' \
  1410. 'loongsuite-pilot END qodercli-intercept'; then
  1411. msg " ⚠️ 检测到你已自定义 qodercli(alias/function),为避免覆盖,采集未启用。" \
  1412. " ⚠️ Detected your own 'qodercli' (alias/function); collection is disabled to avoid clobbering it."
  1413. msg " 如需启用采集,请让你的定义调用: $runtime_wrapper" \
  1414. " To enable collection, have your definition call: $runtime_wrapper"
  1415. fi
  1416. echo ""
  1417. }
  1418. remove_qodercli_token_intercept() {
  1419. for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
  1420. if [ -f "$file" ] && grep -q 'loongsuite-pilot BEGIN qodercli-intercept' "$file" 2>/dev/null; then
  1421. _sed_inplace '/# loongsuite-pilot BEGIN qodercli-intercept/,/# loongsuite-pilot END qodercli-intercept/d' "$file"
  1422. msg " 已清理 qodercli token intercept ($file)" \
  1423. " Cleaned up qodercli token intercept ($file)"
  1424. fi
  1425. done
  1426. }
  1427. # The CN line gets its own function rather than sharing the one above: that
  1428. # block's exact bytes are part of a released idempotency contract (the watchdog
  1429. # greps for them), so it is left untouched. Only the marker and the flavor
  1430. # variable differ here — the wrapper and preload script are the same assets.
  1431. inject_qoderclicn_token_intercept() {
  1432. # Not selected: clean up any stale block from a prior install, then bail.
  1433. if [ "$ALL_AGENTS" != "1" ] && ! echo "$SELECTED_AGENTS" | grep -q 'qoder-cn'; then remove_qoderclicn_token_intercept; return 0; fi
  1434. if ! command -v qoderclicn >/dev/null 2>&1; then return 0; fi
  1435. local intercept_script="$DATA_DIR/hooks/qodercli-token-intercept.mjs"
  1436. local runtime_wrapper="$DATA_DIR/hooks/qodercli-runtime-wrapper.sh"
  1437. if [ ! -f "$intercept_script" ] || [ ! -f "$runtime_wrapper" ]; then return 0; fi
  1438. msg "==> 配置 qoderclicn token 采集..." "==> Configuring qoderclicn token intercept..."
  1439. _inject_cn_to_rc() {
  1440. local file="$1"
  1441. if [ ! -f "$file" ]; then return 0; fi
  1442. if [ ! -w "$file" ]; then
  1443. msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
  1444. return 0
  1445. fi
  1446. # Migrate-or-skip, same shape as the qodercli block: the signature is the
  1447. # flavor assignment, since the wrapper name cannot tell the two apart.
  1448. if grep -q 'loongsuite-pilot BEGIN qoderclicn-intercept' "$file" 2>/dev/null; then
  1449. if _rc_block_contains "$file" \
  1450. 'loongsuite-pilot BEGIN qoderclicn-intercept' \
  1451. 'loongsuite-pilot END qoderclicn-intercept' \
  1452. 'LOONGSUITE_QODERCLI_FLAVOR=qoderclicn'; then return 0; fi
  1453. _sed_inplace '/# loongsuite-pilot BEGIN qoderclicn-intercept/,/# loongsuite-pilot END qoderclicn-intercept/d' "$file"
  1454. fi
  1455. [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
  1456. # Double-quoted heredoc so $DATA_DIR expands at install time. $@ is
  1457. # escaped to defer expansion to runtime. Keep byte-identical to the
  1458. # watchdog's blockFn (src/core/hook-watchdog.ts, id qoderclicn-rc).
  1459. cat >> "$file" << INTERCEPTBLOCK
  1460. # loongsuite-pilot BEGIN qoderclicn-intercept
  1461. if ! alias qoderclicn >/dev/null 2>&1 && ! typeset -f qoderclicn >/dev/null 2>&1; then
  1462. eval 'qoderclicn() { LOONGSUITE_QODERCLI_FLAVOR=qoderclicn "$DATA_DIR/hooks/qodercli-runtime-wrapper.sh" "\$@"; }'
  1463. fi
  1464. # loongsuite-pilot END qoderclicn-intercept
  1465. INTERCEPTBLOCK
  1466. msg " ✅ 已写入 $file (请执行 source $file 或打开新终端)" \
  1467. " ✅ Written to $file (run: source $file or open a new terminal)"
  1468. }
  1469. case "${SHELL:-/bin/bash}" in
  1470. */zsh) _inject_cn_to_rc "$HOME/.zshrc" ;;
  1471. */bash) _inject_cn_to_rc "$HOME/.bashrc" ;;
  1472. *) _inject_cn_to_rc "$HOME/.bashrc" ;;
  1473. esac
  1474. if _rc_user_override_present qoderclicn \
  1475. 'loongsuite-pilot BEGIN qoderclicn-intercept' \
  1476. 'loongsuite-pilot END qoderclicn-intercept'; then
  1477. msg " ⚠️ 检测到你已自定义 qoderclicn(alias/function),为避免覆盖,采集未启用。" \
  1478. " ⚠️ Detected your own 'qoderclicn' (alias/function); collection is disabled to avoid clobbering it."
  1479. msg " 如需启用采集,请让你的定义调用: LOONGSUITE_QODERCLI_FLAVOR=qoderclicn $runtime_wrapper" \
  1480. " To enable collection, have your definition call: LOONGSUITE_QODERCLI_FLAVOR=qoderclicn $runtime_wrapper"
  1481. fi
  1482. echo ""
  1483. }
  1484. remove_qoderclicn_token_intercept() {
  1485. for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
  1486. if [ -f "$file" ] && grep -q 'loongsuite-pilot BEGIN qoderclicn-intercept' "$file" 2>/dev/null; then
  1487. _sed_inplace '/# loongsuite-pilot BEGIN qoderclicn-intercept/,/# loongsuite-pilot END qoderclicn-intercept/d' "$file"
  1488. msg " 已清理 qoderclicn token intercept ($file)" \
  1489. " Cleaned up qoderclicn token intercept ($file)"
  1490. fi
  1491. done
  1492. }
  1493. # Restore app defaults without requiring the old wrapper, app, or agent selection to exist.
  1494. retire_qoderwork_runtime_overrides() {
  1495. if [ "$(uname)" != "Darwin" ]; then return 0; fi
  1496. local plist_path
  1497. for plist_path in \
  1498. "$HOME/Library/LaunchAgents/com.loongsuite-pilot.qoderwork-env.plist" \
  1499. "$HOME/Library/LaunchAgents/com.loongsuite-pilot.qwenworkcn-env.plist"; do
  1500. if [ -f "$plist_path" ]; then
  1501. launchctl unload "$plist_path" 2>/dev/null || true
  1502. rm -f "$plist_path"
  1503. fi
  1504. done
  1505. local env_name current_runtime
  1506. for env_name in QW_QODER_WORKER_RUNTIME_PATH QODER_WORKER_RUNTIME_PATH; do
  1507. current_runtime=$(launchctl getenv "$env_name" 2>/dev/null || true)
  1508. if [ "$current_runtime" = "$DATA_DIR/hooks/qoderwork-runtime-wrapper.mjs" ] || printf '%s' "$current_runtime" | grep -q 'loongsuite-pilot'; then
  1509. launchctl unsetenv "$env_name"
  1510. msg " 已清理 $env_name" " Cleaned up $env_name"
  1511. fi
  1512. done
  1513. }
  1514. # ============================================================
  1515. # Claude Code fetch intercept: inject/remove shell function
  1516. #
  1517. # Why a shell wrapper instead of ~/.claude/settings.json env:
  1518. # Claude Code is a Bun-compiled binary. Bun reads BUN_OPTIONS at runtime
  1519. # startup (before any JS executes), so settings.json env values are too
  1520. # late — they only affect Claude Code's child processes, not the Bun
  1521. # preload of the main process. A shell wrapper that sets BUN_OPTIONS
  1522. # before invoking `claude` is the only reliable injection point.
  1523. #
  1524. # The wrapper prepends our preload but preserves any existing BUN_OPTIONS
  1525. # the user (or qodercli wrapper, or launchd setenv) may have set.
  1526. # ============================================================
  1527. # Detect a user-defined <cli> alias/function OUTSIDE our managed block.
  1528. # $1=cli name $2=BEGIN marker substring $3=END marker substring
  1529. # Returns 0 (true) when found. Our injected wrapper's `if ! alias ...` guard
  1530. # intentionally skips such users to avoid clobbering their setup — which means
  1531. # collection is silently off for them. This lets the installer surface a
  1532. # one-time, actionable hint at install time (rc is sourced too often to warn on
  1533. # every shell). Heuristic: scans common rc files with our block stripped; misses
  1534. # aliases defined in files those rc's source.
  1535. _rc_user_override_present() {
  1536. local cli="$1" begin="$2" end="$3" file
  1537. for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
  1538. [ -f "$file" ] || continue
  1539. if sed "/$begin/,/$end/d" "$file" 2>/dev/null \
  1540. | grep -Eq "^[[:space:]]*(alias[[:space:]]+$cli=|(function[[:space:]]+)?$cli[[:space:]]*\(\)|function[[:space:]]+$cli([[:space:]]|\{|\$))"; then
  1541. return 0
  1542. fi
  1543. done
  1544. return 1
  1545. }
  1546. inject_claude_code_fetch_intercept() {
  1547. # Not selected: clean up any stale block from a prior install, then bail.
  1548. if [ "$ALL_AGENTS" != "1" ] && ! echo "$SELECTED_AGENTS" | grep -q 'claude-code'; then remove_claude_code_fetch_intercept; return 0; fi
  1549. if ! command -v claude >/dev/null 2>&1; then return 0; fi
  1550. local intercept_script="$DATA_DIR/hooks/claude-code-fetch-intercept.mjs"
  1551. if [ ! -f "$intercept_script" ]; then return 0; fi
  1552. msg "==> 配置 claude-code fetch 拦截..." "==> Configuring claude-code fetch intercept..."
  1553. _inject_to_rc() {
  1554. local file="$1"
  1555. if [ ! -f "$file" ]; then return 0; fi
  1556. if [ ! -w "$file" ]; then
  1557. msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
  1558. return 0
  1559. fi
  1560. # Migrate-or-skip: our block may already be present. If it is the current
  1561. # guard shape (signature line present) we're done; otherwise it is an
  1562. # older released bare-function block sharing the same marker — remove it
  1563. # so the new guarded block below replaces it (the old bare block
  1564. # parse-errors under a user alias, which is exactly what we're fixing).
  1565. if grep -q 'loongsuite-pilot BEGIN claude-code-intercept' "$file" 2>/dev/null; then
  1566. if grep -qF 'if ! alias claude >/dev/null 2>&1' "$file"; then return 0; fi
  1567. _sed_inplace '/# loongsuite-pilot BEGIN claude-code-intercept/,/# loongsuite-pilot END claude-code-intercept/d' "$file"
  1568. fi
  1569. [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
  1570. # Double-quoted heredoc so $DATA_DIR expands at install time, honoring
  1571. # --data-dir overrides. Other refs (${BUN_OPTIONS}, $@) are escaped to
  1572. # defer expansion until the wrapper actually runs in the user's shell.
  1573. # The `if ! alias ... eval '...'` shape guards against clobbering a
  1574. # user's own claude alias/function (e.g. a proxy+flags alias) AND avoids
  1575. # a parse error: a bare claude() token would fail to parse under an
  1576. # active alias (interactive shells expand aliases at parse time, before
  1577. # the guard runs), so the definition is deferred behind eval. Keep
  1578. # byte-identical to the watchdog's blockFn (src/core/hook-watchdog.ts).
  1579. cat >> "$file" << INTERCEPTBLOCK
  1580. # loongsuite-pilot BEGIN claude-code-intercept
  1581. if ! alias claude >/dev/null 2>&1 && ! typeset -f claude >/dev/null 2>&1; then
  1582. eval 'claude() { BUN_OPTIONS="--preload=$DATA_DIR/hooks/claude-code-fetch-intercept.mjs \${BUN_OPTIONS}" command claude "\$@"; }'
  1583. fi
  1584. # loongsuite-pilot END claude-code-intercept
  1585. INTERCEPTBLOCK
  1586. msg " ✅ 已写入 $file (请执行 source $file 或打开新终端)" \
  1587. " ✅ Written to $file (run: source $file or open a new terminal)"
  1588. }
  1589. case "${SHELL:-/bin/bash}" in
  1590. */zsh) _inject_to_rc "$HOME/.zshrc" ;;
  1591. */bash) _inject_to_rc "$HOME/.bashrc" ;;
  1592. *) _inject_to_rc "$HOME/.bashrc" ;;
  1593. esac
  1594. # If the user already defines their own `claude`, our guard skipped the
  1595. # wrapper (to avoid clobbering it), so collection won't run. Tell them how
  1596. # to opt in, since there is otherwise no signal explaining the silence.
  1597. if _rc_user_override_present claude \
  1598. 'loongsuite-pilot BEGIN claude-code-intercept' \
  1599. 'loongsuite-pilot END claude-code-intercept'; then
  1600. msg " ⚠️ 检测到你已自定义 claude(alias/function),为避免覆盖,采集未启用。" \
  1601. " ⚠️ Detected your own 'claude' (alias/function); collection is disabled to avoid clobbering it."
  1602. msg " 如需启用采集,请在你的 claude 定义中加入: BUN_OPTIONS=\"--preload=$DATA_DIR/hooks/claude-code-fetch-intercept.mjs \${BUN_OPTIONS}\"" \
  1603. " To enable collection, add to your claude definition: BUN_OPTIONS=\"--preload=$DATA_DIR/hooks/claude-code-fetch-intercept.mjs \${BUN_OPTIONS}\""
  1604. fi
  1605. echo ""
  1606. }
  1607. # Remove only the Pilot-owned Copilot startup block. Native telemetry files are data.
  1608. remove_copilot_plugin() {
  1609. local copilot_home="$HOME/.copilot"
  1610. [ -d "$copilot_home" ] || return 0
  1611. local node_bin="${NODE_BIN:-}" helper="" version="" cache="$HOME/.loongsuite-pilot"
  1612. if [ ! -x "$node_bin" ] && [ -f "$cache/node-bin" ]; then
  1613. node_bin=$(tr -d '\r\n' < "$cache/node-bin")
  1614. fi
  1615. if [ ! -x "$node_bin" ]; then node_bin=$(command -v node) || node_bin=""; fi
  1616. if [ -f "$cache/current" ]; then version=$(tr -d '\r\n' < "$cache/current"); fi
  1617. local candidate
  1618. for candidate in "$cache/versions/$version/dist/copilot-cleanup.cjs" "${PERMANENT_DIR:-$cache/package}/dist/copilot-cleanup.cjs"; do
  1619. if [ -f "$candidate" ]; then helper="$candidate"; break; fi
  1620. done
  1621. if [ -z "$node_bin" ] || [ -z "$helper" ]; then
  1622. echo "Copilot cleanup skipped: safe Node JSONC helper unavailable; config and plugin assets preserved" >&2
  1623. return 0
  1624. fi
  1625. if ! "$node_bin" "$helper" "$copilot_home"; then
  1626. echo "Copilot cleanup incomplete; config and plugin assets preserved for retry" >&2
  1627. fi
  1628. }
  1629. remove_copilot_otel_environment() {
  1630. local file
  1631. for file in "$HOME/.bashrc" "$HOME/.zshrc"; do
  1632. [ -f "$file" ] || continue
  1633. local tmp="${file}.pilot-copilot-$$.tmp"
  1634. if sed '/^# >>> loongsuite-pilot copilot otel >>>$/,/^# <<< loongsuite-pilot copilot otel <<<$/{d;}' "$file" > "$tmp"; then
  1635. cat "$tmp" > "$file"
  1636. fi
  1637. rm -f "$tmp"
  1638. done
  1639. rm -f "$DATA_DIR/state/copilot/otel-enabled"
  1640. }
  1641. remove_claude_code_fetch_intercept() {
  1642. for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
  1643. if [ -f "$file" ] && grep -q 'loongsuite-pilot BEGIN claude-code-intercept' "$file" 2>/dev/null; then
  1644. _sed_inplace '/# loongsuite-pilot BEGIN claude-code-intercept/,/# loongsuite-pilot END claude-code-intercept/d' "$file"
  1645. msg " 已清理 claude-code fetch intercept ($file)" \
  1646. " Cleaned up claude-code fetch intercept ($file)"
  1647. fi
  1648. done
  1649. }
  1650. # ============================================================
  1651. # Common: read VERSION file fields
  1652. # ============================================================
  1653. get_installed_version() {
  1654. local cache_dir="$HOME/.loongsuite-pilot"
  1655. local current_file="$cache_dir/current"
  1656. local versions_dir="$cache_dir/versions"
  1657. if [ -f "$current_file" ]; then
  1658. local dir
  1659. dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
  1660. if [ -n "$dir" ] && [ -f "$versions_dir/$dir/VERSION" ]; then
  1661. grep '^version=' "$versions_dir/$dir/VERSION" | cut -d= -f2
  1662. return 0
  1663. fi
  1664. fi
  1665. local vf="$PERMANENT_DIR/VERSION"
  1666. if [ -f "$vf" ]; then
  1667. grep '^version=' "$vf" | cut -d= -f2
  1668. else
  1669. echo ""
  1670. fi
  1671. }
  1672. get_version_from_dir() {
  1673. local vf="$1/VERSION"
  1674. if [ -f "$vf" ]; then
  1675. grep '^version=' "$vf" | cut -d= -f2
  1676. else
  1677. echo ""
  1678. fi
  1679. }
  1680. get_commit_from_dir() {
  1681. local vf="$1/VERSION"
  1682. if [ -f "$vf" ]; then
  1683. grep '^git_commit=' "$vf" | cut -d= -f2
  1684. else
  1685. echo ""
  1686. fi
  1687. }
  1688. show_version_info() {
  1689. local dir="$1"
  1690. local vf="$dir/VERSION"
  1691. if [ -f "$vf" ]; then
  1692. local v; v=$(grep '^version=' "$vf" | cut -d= -f2)
  1693. local c; c=$(grep '^git_commit=' "$vf" | cut -d= -f2)
  1694. local t; t=$(grep '^build_time=' "$vf" | cut -d= -f2)
  1695. echo "v${v} (${c}, ${t})"
  1696. else
  1697. echo "unknown"
  1698. fi
  1699. }
  1700. # ============================================================
  1701. # Common: print summary
  1702. # ============================================================
  1703. # ============================================================
  1704. # Remove legacy Claude OTel plugin
  1705. # ============================================================
  1706. remove_otel_plugin() {
  1707. local OTEL_CLAUDE_DIR="$HOME/.cache/opentelemetry.instrumentation.claude"
  1708. # Prevent NODE_OPTIONS --require intercept.js from breaking node commands
  1709. # after the Claude plugin directory (and intercept.js) is deleted
  1710. unset NODE_OPTIONS 2>/dev/null || true
  1711. if [ -f "$OTEL_CLAUDE_DIR/package/scripts/uninstall.sh" ]; then
  1712. bash "$OTEL_CLAUDE_DIR/package/scripts/uninstall.sh" 2>/dev/null || true
  1713. msg " ✅ Claude Code 插件 hooks 和 alias 已清理" \
  1714. " ✅ Claude Code plugin hooks and alias cleaned"
  1715. else
  1716. for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.bash_profile"; do
  1717. [ -f "$rc" ] || continue
  1718. if grep -q "# BEGIN otel-claude-hook" "$rc" 2>/dev/null; then
  1719. sed -i.bak '/# BEGIN otel-claude-hook/,/# END otel-claude-hook/d' "$rc"
  1720. rm -f "${rc}.bak"
  1721. fi
  1722. if grep -q "# BEGIN otel-claude-hook-env" "$rc" 2>/dev/null; then
  1723. sed -i.bak '/# BEGIN otel-claude-hook-env/,/# END otel-claude-hook-env/d' "$rc"
  1724. rm -f "${rc}.bak"
  1725. fi
  1726. done
  1727. msg " ✅ claude alias 已清理" " ✅ claude alias cleaned"
  1728. # Clean settings.json hooks (fallback when uninstall.sh is unavailable)
  1729. local claude_settings="$HOME/.claude/settings.json"
  1730. if [ -f "$claude_settings" ] && grep -qE "otel-claude-hook|hook-entry\.sh" "$claude_settings" 2>/dev/null && command -v node &>/dev/null; then
  1731. node -e "
  1732. const fs = require('fs');
  1733. const f = process.argv[1];
  1734. const isOurs = c => c.includes('otel-claude-hook') || c.includes('hook-entry.sh');
  1735. try {
  1736. const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
  1737. if (d && d.hooks) {
  1738. for (const ev of Object.keys(d.hooks)) {
  1739. if (!Array.isArray(d.hooks[ev])) continue;
  1740. d.hooks[ev] = d.hooks[ev].map(m => {
  1741. if (!Array.isArray(m.hooks)) return m;
  1742. m.hooks = m.hooks.filter(h => !(h.command && isOurs(h.command)));
  1743. return m.hooks.length > 0 ? m : null;
  1744. }).filter(Boolean);
  1745. if (d.hooks[ev].length === 0) delete d.hooks[ev];
  1746. }
  1747. if (Object.keys(d.hooks).length === 0) delete d.hooks;
  1748. fs.writeFileSync(f, JSON.stringify(d, null, 2) + '\n');
  1749. }
  1750. } catch {}
  1751. " "$claude_settings" 2>/dev/null || true
  1752. msg " ✅ settings.json hooks 已清理" " ✅ settings.json hooks cleaned"
  1753. fi
  1754. fi
  1755. local otel_config="$HOME/.claude/otel-config.json"
  1756. if [ -f "$otel_config" ] && command -v node &>/dev/null; then
  1757. node -e "
  1758. const fs = require('fs');
  1759. try {
  1760. const cfg = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8'));
  1761. delete cfg.log_enabled;
  1762. delete cfg.log_dir;
  1763. delete cfg.log_filename_format;
  1764. fs.writeFileSync(process.argv[1], JSON.stringify(cfg, null, 2) + '\n');
  1765. } catch {}
  1766. " "$otel_config" 2>/dev/null || true
  1767. fi
  1768. if [ -d "$OTEL_CLAUDE_DIR" ]; then
  1769. if [ "$PURGE" -eq 1 ]; then
  1770. rm -rf "$OTEL_CLAUDE_DIR"
  1771. msg " ✅ 插件目录已完全删除 (--purge): $OTEL_CLAUDE_DIR" \
  1772. " ✅ Plugin directory fully removed (--purge): $OTEL_CLAUDE_DIR"
  1773. else
  1774. find "$OTEL_CLAUDE_DIR" -maxdepth 1 \
  1775. ! -name sessions \
  1776. ! -name "$(basename "$OTEL_CLAUDE_DIR")" \
  1777. -exec rm -rf {} + 2>/dev/null || true
  1778. msg " ✅ 插件文件已删除(sessions/ 已保留)" \
  1779. " ✅ Plugin files removed (sessions/ preserved)"
  1780. fi
  1781. fi
  1782. }
  1783. print_summary() {
  1784. local action="$1" # install / upgrade
  1785. local config_file="$DATA_DIR/config.json"
  1786. echo "============================================================"
  1787. local ver; ver=$(show_version_info "$PERMANENT_DIR")
  1788. case "$action" in
  1789. install)
  1790. msg "✅ 安装完成!版本: $ver" "✅ Installation complete! Version: $ver" ;;
  1791. upgrade)
  1792. msg "✅ 升级完成!版本: $ver" "✅ Upgrade complete! Version: $ver" ;;
  1793. esac
  1794. echo ""
  1795. msg "配置文件: $config_file" "Config file: $config_file"
  1796. msg "数据目录: $DATA_DIR" "Data directory: $DATA_DIR"
  1797. msg "Hook 目录: $DATA_DIR/hooks" "Hooks directory: $DATA_DIR/hooks"
  1798. echo ""
  1799. if [ -n "$SLS_ENDPOINT" ]; then
  1800. msg "SLS 后端: $SLS_ENDPOINT" "SLS backend: $SLS_ENDPOINT"
  1801. [ -n "$SLS_PROJECT" ] && msg " 项目: $SLS_PROJECT" " Project: $SLS_PROJECT"
  1802. [ -n "$SLS_LOGSTORE" ] && msg " 日志库: $SLS_LOGSTORE" " Logstore: $SLS_LOGSTORE"
  1803. echo ""
  1804. fi
  1805. msg "命令:" "Commands:"
  1806. echo " loongsuite-pilot status # 查看状态 / Status"
  1807. echo " loongsuite-pilot info # 版本与配置 / Version & config"
  1808. echo "============================================================"
  1809. }
  1810. # >>> pilot-stop-for-deploy >>>
  1811. # Overlay `install` used to SIGTERM only the collector pid file. The updater
  1812. # stayed up, and gcOldVersions() deletes any versions/<dir> that is not
  1813. # current/previous -- including the directory this deploy just copied, before
  1814. # current is published. installer-opensource.sh writes current after
  1815. # node_modules + postinstall, so that window is minutes. `loongsuite-pilot stop`
  1816. # unloads LaunchAgent / disables systemd (autostart_remove) so neither process
  1817. # comes back mid-deploy. That is the Unix counterpart of Disable-ScheduledTask.
  1818. #
  1819. # stop deletes the unit files. restore_pilot_after_deploy (EXIT trap) is the
  1820. # counterpart of Enable-ScheduledTask in finally: it re-registers autostart
  1821. # via start. Container installs must not start a daemon in the build layer.
  1822. #
  1823. # Fresh install has no CLI yet. Fall back to both pid files so a leftover
  1824. # collector or updater still goes down.
  1825. # All CLI after stop must go through run_pilot_cli so --data-dir matches.
  1826. PILOT_HELD_FOR_DEPLOY=0
  1827. resolve_pilot_cli() {
  1828. if command -v loongsuite-pilot &>/dev/null; then
  1829. command -v loongsuite-pilot
  1830. elif [ -f "$HOME/.local/bin/loongsuite-pilot" ]; then
  1831. printf '%s\n' "$HOME/.local/bin/loongsuite-pilot"
  1832. fi
  1833. }
  1834. run_pilot_cli() {
  1835. local cli
  1836. cli="$(resolve_pilot_cli)"
  1837. [ -n "$cli" ] || return 1
  1838. # deploy_package writes versions/current under $HOME/.loongsuite-pilot
  1839. # (the CLI cache default). Do not point CACHE_DIR at DATA_DIR.
  1840. LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
  1841. "$cli" "$@"
  1842. }
  1843. stop_one_pilot_pid_file() {
  1844. local pid_file="$1"
  1845. [ -f "$pid_file" ] || return 0
  1846. local old_pid
  1847. old_pid=$(cat "$pid_file")
  1848. if kill -0 "$old_pid" 2>/dev/null; then
  1849. kill "$old_pid" 2>/dev/null || true
  1850. local count=0
  1851. while kill -0 "$old_pid" 2>/dev/null && [ $count -lt 10 ]; do
  1852. sleep 1
  1853. count=$((count + 1))
  1854. done
  1855. if kill -0 "$old_pid" 2>/dev/null; then
  1856. kill -9 "$old_pid" 2>/dev/null || true
  1857. fi
  1858. rm -f "$pid_file"
  1859. else
  1860. rm -f "$pid_file"
  1861. fi
  1862. }
  1863. stop_pilot_for_deploy() {
  1864. PILOT_HELD_FOR_DEPLOY=0
  1865. local cli
  1866. cli="$(resolve_pilot_cli)"
  1867. if [ -z "$cli" ] && [ ! -f "$DATA_DIR/loongsuite-pilot.pid" ] && [ ! -f "$DATA_DIR/loongsuite-pilot-updater.pid" ]; then
  1868. return 0
  1869. fi
  1870. msg "==> 停止服务..." "==> Stopping service..."
  1871. if [ -n "$cli" ]; then
  1872. PILOT_HELD_FOR_DEPLOY=1
  1873. if ! run_pilot_cli stop; then
  1874. msg " ⚠️ 无法停止服务,覆盖安装期间 updater 可能仍会 GC" \
  1875. " ⚠️ Could not stop the service; updater may still GC during this overlay"
  1876. fi
  1877. fi
  1878. # Leftovers: no CLI on PATH, or an updater the CLI did not track.
  1879. stop_one_pilot_pid_file "$DATA_DIR/loongsuite-pilot.pid"
  1880. stop_one_pilot_pid_file "$DATA_DIR/loongsuite-pilot-updater.pid"
  1881. echo ""
  1882. }
  1883. restore_pilot_after_deploy() {
  1884. [ "${PILOT_HELD_FOR_DEPLOY:-0}" -eq 1 ] || return 0
  1885. [ "${INSTALL_MODE:-host}" = "container" ] && return 0
  1886. PILOT_HELD_FOR_DEPLOY=0
  1887. if ! run_pilot_cli start; then
  1888. msg " ⚠️ 无法恢复自启,请手动运行: loongsuite-pilot start" \
  1889. " ⚠️ Could not restore autostart, run manually: loongsuite-pilot start"
  1890. fi
  1891. }
  1892. # <<< pilot-stop-for-deploy <<<
  1893. # ============================================================
  1894. # CMD: install
  1895. # ============================================================
  1896. reject_multi_sls_config() {
  1897. local config_file="$DATA_DIR/config.json"
  1898. [ -f "$config_file" ] || return 0
  1899. local status
  1900. if "$NODE_BIN" -e '
  1901. const fs = require("fs");
  1902. try {
  1903. const config = JSON.parse(fs.readFileSync(process.argv[1], "utf8").replace(/^\uFEFF/, ""));
  1904. process.exit(Array.isArray(config?.sls) ? 12 : 0);
  1905. } catch { process.exit(13); }
  1906. ' "$config_file"; then
  1907. return 0
  1908. else
  1909. status=$?
  1910. fi
  1911. if [ "$status" -eq 12 ]; then
  1912. msg "❌ 配置包含多个 SLS flusher;安装器不支持修改,请手动编辑 config.json" \
  1913. "❌ Multiple SLS flushers found; the installer cannot modify them. Edit config.json manually." >&2
  1914. else
  1915. msg "❌ 无法检查现有 config.json,请检查文件后重试" \
  1916. "❌ Cannot inspect existing config.json; check the file and retry." >&2
  1917. fi
  1918. return 1
  1919. }
  1920. apply_installation_scope() {
  1921. [ -n "$HOOK_INSTALL_SCOPE" ] || return 0
  1922. local scope_args=(hook install --scope "$HOOK_INSTALL_SCOPE" --json)
  1923. if [ -n "$SELECTED_AGENTS" ]; then scope_args+=(--agents "$SELECTED_AGENTS"); fi
  1924. if ! run_pilot_cli "${scope_args[@]}"; then
  1925. # A partial registration can require recovery. Keep its runtime and
  1926. # leave the collector stopped instead of the EXIT trap starting it.
  1927. PILOT_HELD_FOR_DEPLOY=0
  1928. msg "❌ Hook 安装未完成;已保留运行文件,请修复后重试 hook install" \
  1929. "❌ Hook installation incomplete; runtime retained. Resolve the error and retry hook install." >&2
  1930. return 1
  1931. fi
  1932. }
  1933. cmd_install() {
  1934. msg "==> 开始安装 $PACKAGE_NAME ..." \
  1935. "==> Installing $PACKAGE_NAME ..."
  1936. echo ""
  1937. validate_install_user
  1938. check_deps
  1939. reject_multi_sls_config
  1940. # Migrate legacy layout if needed
  1941. migrate_legacy_layout
  1942. # Check if already installed
  1943. local cur_ver; cur_ver=$(get_installed_version)
  1944. if [ -n "$cur_ver" ]; then
  1945. msg "⚠️ 检测到已安装版本 v${cur_ver},将执行重新安装" \
  1946. "⚠️ Existing installation v${cur_ver} detected, re-installing"
  1947. echo ""
  1948. fi
  1949. # Stop collector AND updater, and unload launchd / disable systemd so GC
  1950. # cannot delete the in-flight versions dir. See stop_pilot_for_deploy.
  1951. # Arm restore before stop: autostart_remove is not reversible if we die
  1952. # between stop and trap.
  1953. trap 'restore_pilot_after_deploy; rm -rf "${TMP_DIR:-}"' EXIT
  1954. stop_pilot_for_deploy
  1955. download_and_extract
  1956. probe_agents
  1957. select_agents
  1958. prompt_user_id
  1959. confirm_config_overwrite
  1960. # set -e would end the install here anyway; saying why beats an exit code on its own.
  1961. if ! deploy_package "$INSTALL_SRC"; then
  1962. echo ""
  1963. msg "❌ 安装中止:hook 脚本部署失败,请检查上方输出后重试" \
  1964. "❌ Install aborted: hook script deployment failed; check the output above and retry"
  1965. exit 1
  1966. fi
  1967. write_config
  1968. install_loongsuite_pilot_command
  1969. retire_qoderwork_runtime_overrides
  1970. inject_qodercli_token_intercept
  1971. inject_qoderclicn_token_intercept
  1972. inject_claude_code_fetch_intercept
  1973. apply_installation_scope
  1974. msg "==> 启动服务..." "==> Starting service..."
  1975. if run_pilot_cli start; then
  1976. sleep 2
  1977. local _status_out
  1978. _status_out="$(run_pilot_cli status 2>/dev/null || true)"
  1979. if echo "$_status_out" | grep -q "is running"; then
  1980. PILOT_HELD_FOR_DEPLOY=0
  1981. msg " ✅ 服务已启动" " ✅ Service started"
  1982. else
  1983. msg " ⚠️ 服务可能尚未就绪,请检查: loongsuite-pilot status" \
  1984. " ⚠️ Service may not be ready. Check: loongsuite-pilot status"
  1985. fi
  1986. else
  1987. msg " ⚠️ 服务启动失败,请手动运行: loongsuite-pilot start" \
  1988. " ⚠️ Service failed to start, run manually: loongsuite-pilot start"
  1989. fi
  1990. echo ""
  1991. print_summary "install"
  1992. }
  1993. # ============================================================
  1994. # CMD: upgrade
  1995. # ============================================================
  1996. cmd_upgrade() {
  1997. msg "==> 开始升级 $PACKAGE_NAME ..." \
  1998. "==> Upgrading $PACKAGE_NAME ..."
  1999. echo ""
  2000. validate_install_user
  2001. # Migrate legacy layout if needed
  2002. migrate_legacy_layout
  2003. # Must have an existing installation
  2004. local old_ver; old_ver=$(get_installed_version)
  2005. if [ -z "$old_ver" ]; then
  2006. msg "❌ 未检测到已安装的 loongsuite-pilot,请先执行 install" \
  2007. "❌ No existing installation found. Please run install first."
  2008. exit 1
  2009. fi
  2010. msg " 当前版本: ${old_ver:-unknown}" " Current version: ${old_ver:-unknown}"
  2011. echo ""
  2012. check_deps
  2013. trap 'restore_pilot_after_deploy; rm -rf "${TMP_DIR:-}"' EXIT
  2014. download_and_extract
  2015. local new_ver; new_ver=$(get_version_from_dir "$INSTALL_SRC")
  2016. local new_commit; new_commit=$(get_commit_from_dir "$INSTALL_SRC")
  2017. local old_commit; old_commit=$(get_commit_from_dir "$PERMANENT_DIR")
  2018. if [ -n "$new_ver" ] && [ "$new_ver" = "$old_ver" ] && [ "$new_commit" = "$old_commit" ]; then
  2019. msg "✅ 已是最新版本 v${new_ver} (${new_commit}),无需升级" \
  2020. "✅ Already at latest version v${new_ver} (${new_commit}), nothing to do"
  2021. exit 0
  2022. fi
  2023. msg " 新版本: ${new_ver:-unknown} (${new_commit:-unknown})" \
  2024. " New version: ${new_ver:-unknown} (${new_commit:-unknown})"
  2025. echo ""
  2026. stop_pilot_for_deploy
  2027. # Deploy new version to versions/<ver>_<commit>/
  2028. # Old version stays untouched; deploy_package writes current/previous pointers
  2029. if ! deploy_package "$INSTALL_SRC"; then
  2030. echo ""
  2031. msg "⚠️ 部署失败,正在回滚到旧版本..." \
  2032. "⚠️ Deployment failed, rolling back to old version..."
  2033. local _rollback_ok=1
  2034. run_pilot_cli rollback 2>/dev/null || _rollback_ok=0
  2035. if [ "$_rollback_ok" -eq 1 ]; then
  2036. if run_pilot_cli start; then
  2037. PILOT_HELD_FOR_DEPLOY=0
  2038. else
  2039. _rollback_ok=0
  2040. fi
  2041. fi
  2042. if [ "$_rollback_ok" -eq 1 ]; then
  2043. msg "❌ 升级失败(部署/依赖安装出错),已回滚到 v${old_ver:-unknown} 并重启服务" \
  2044. "❌ Upgrade failed (deploy/dependency error), rolled back to v${old_ver:-unknown} and restarted"
  2045. else
  2046. msg "❌ 升级失败且自动回滚未成功,请手动恢复:" \
  2047. "❌ Upgrade failed and auto-rollback did not succeed. Manual recovery:"
  2048. msg " loongsuite-pilot rollback && loongsuite-pilot start" \
  2049. " loongsuite-pilot rollback && loongsuite-pilot start"
  2050. fi
  2051. exit 1
  2052. fi
  2053. install_loongsuite_pilot_command
  2054. retire_qoderwork_runtime_overrides
  2055. # Start the new version
  2056. msg "==> 启动新版本..." "==> Starting new version..."
  2057. if run_pilot_cli start; then
  2058. sleep 2
  2059. local _status_out
  2060. _status_out="$(run_pilot_cli status 2>/dev/null || true)"
  2061. if echo "$_status_out" | grep -q "is running"; then
  2062. PILOT_HELD_FOR_DEPLOY=0
  2063. msg " ✅ 新版本启动成功" " ✅ New version started successfully"
  2064. echo ""
  2065. # GC: remove old versions beyond current + previous
  2066. gc_old_versions
  2067. print_summary "upgrade"
  2068. return 0
  2069. fi
  2070. fi
  2071. # --- Rollback via version pointer ---
  2072. echo ""
  2073. msg "⚠️ 新版本启动失败,正在回滚..." \
  2074. "⚠️ New version failed to start, rolling back..."
  2075. run_pilot_cli stop 2>/dev/null || true
  2076. local _rb_ok=1
  2077. run_pilot_cli rollback 2>/dev/null || _rb_ok=0
  2078. if [ "$_rb_ok" -eq 1 ]; then
  2079. if run_pilot_cli start; then
  2080. PILOT_HELD_FOR_DEPLOY=0
  2081. msg "❌ 升级失败,已回滚到 v${old_ver:-unknown}" \
  2082. "❌ Upgrade failed, rolled back to v${old_ver:-unknown}"
  2083. msg " 请检查日志: loongsuite-pilot log" " Check logs: loongsuite-pilot log"
  2084. else
  2085. msg "❌ 升级失败,已回滚但未能重启服务" \
  2086. "❌ Upgrade failed, rolled back but could not restart"
  2087. msg " 请手动运行: loongsuite-pilot start" \
  2088. " Run manually: loongsuite-pilot start"
  2089. fi
  2090. else
  2091. msg "❌ 升级失败且回滚未成功,请手动恢复:" \
  2092. "❌ Upgrade failed and rollback did not succeed. Manual recovery:"
  2093. msg " loongsuite-pilot rollback && loongsuite-pilot start" \
  2094. " loongsuite-pilot rollback && loongsuite-pilot start"
  2095. fi
  2096. exit 1
  2097. }
  2098. # ============================================================
  2099. # GC: remove old version directories beyond current + previous
  2100. # ============================================================
  2101. gc_old_versions() {
  2102. local cache_dir="$HOME/.loongsuite-pilot"
  2103. local versions_dir="$cache_dir/versions"
  2104. local current_file="$cache_dir/current"
  2105. local previous_file="$cache_dir/previous"
  2106. [ -d "$versions_dir" ] || return 0
  2107. local keep_current="" keep_previous=""
  2108. if [ -f "$current_file" ]; then
  2109. keep_current=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
  2110. fi
  2111. if [ -f "$previous_file" ]; then
  2112. keep_previous=$(cat "$previous_file" 2>/dev/null | tr -d '[:space:]')
  2113. fi
  2114. for d in "$versions_dir"/*/; do
  2115. [ -d "$d" ] || continue
  2116. local name
  2117. name=$(basename "$d")
  2118. if [ "$name" = "$keep_current" ] || [ "$name" = "$keep_previous" ]; then
  2119. continue
  2120. fi
  2121. rm -rf "$d"
  2122. done
  2123. }
  2124. # ============================================================
  2125. # Remove hook entries injected into tool config files
  2126. # ============================================================
  2127. remove_hook_configs() {
  2128. local HOOK_MARKER=".loongsuite-pilot"
  2129. local configs=(
  2130. "$HOME/.cursor/hooks.json"
  2131. "$HOME/.qoder/settings.json"
  2132. "$HOME/.qoder-cn/settings.json"
  2133. "$HOME/.qoderwork/settings.json"
  2134. "$HOME/.qoderworkcn/settings.json"
  2135. "$HOME/.qwenworkcn/settings.json"
  2136. "$HOME/.claude/settings.json"
  2137. "$HOME/.codex/hooks.json"
  2138. "$HOME/.kiro/agents/pilot-kiro.json"
  2139. "$HOME/.qwen/settings.json"
  2140. "$HOME/.workbuddy/settings.json"
  2141. )
  2142. local _has_node=0
  2143. if command -v node &>/dev/null; then
  2144. _has_node=1
  2145. else
  2146. msg " ⚠️ 未找到 Node.js,含 hook 的配置文件将跳过自动清理" \
  2147. " ⚠️ Node.js not found, config files with hooks will skip auto-cleanup"
  2148. fi
  2149. for cfg in "${configs[@]}"; do
  2150. [ -f "$cfg" ] || continue
  2151. local short="${cfg/#$HOME/\~}"
  2152. local ok=0
  2153. if [ "$_has_node" -eq 1 ]; then
  2154. node -e "
  2155. const fs = require('fs');
  2156. const cfg = process.argv[1];
  2157. const marker = process.argv[2];
  2158. try {
  2159. const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
  2160. const hooks = data.hooks;
  2161. if (!hooks || typeof hooks !== 'object') process.exit(0);
  2162. let changed = false;
  2163. const isCodex = cfg.endsWith('/.codex/hooks.json');
  2164. const isPilotCodex = c => typeof c === 'string' && c.includes(marker)
  2165. && new RegExp('(^|[ /])codex-loongsuite-pilot-hook[.](sh|mjs|ps1)([^A-Za-z0-9_.-]|$)', 'i').test(c);
  2166. for (const [event, entries] of Object.entries(hooks)) {
  2167. if (!Array.isArray(entries)) continue;
  2168. const candidates = isCodex ? entries.flatMap(e => {
  2169. if (!e || typeof e !== 'object') return [e];
  2170. if (isPilotCodex(e.command)) { changed = true; return []; }
  2171. if (!Array.isArray(e.hooks)) return [e];
  2172. const nested = e.hooks.filter(h => !isPilotCodex(h && h.command));
  2173. if (nested.length === e.hooks.length) return [e];
  2174. changed = true;
  2175. return nested.length ? [{ ...e, hooks: nested }] : [];
  2176. }) : entries;
  2177. const filtered = isCodex ? candidates : candidates.filter(e => {
  2178. const cmd = e.command || '';
  2179. const nested = Array.isArray(e.hooks) ? e.hooks : [];
  2180. const hasMarker = cmd.includes(marker) || nested.some(h => (h.command || '').includes(marker));
  2181. if (hasMarker) changed = true;
  2182. return !hasMarker;
  2183. });
  2184. if (filtered.length === 0) { delete hooks[event]; changed = true; }
  2185. else hooks[event] = filtered;
  2186. }
  2187. if (changed) {
  2188. fs.writeFileSync(cfg, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2189. process.stdout.write('cleaned');
  2190. } else {
  2191. process.stdout.write('skip');
  2192. }
  2193. } catch(e) { process.stderr.write(e.message); process.exit(1); }
  2194. " "$cfg" "$HOOK_MARKER" && ok=1
  2195. else
  2196. # Node unavailable: skip auto-cleanup to avoid over-deletion
  2197. if grep -q "$HOOK_MARKER" "$cfg" 2>/dev/null; then
  2198. msg " ⚠️ 跳过: $short (无 Node.js,请手动删除含 $HOOK_MARKER 的 hook 条目)" \
  2199. " ⚠️ Skipped: $short (no Node.js, manually remove hook entries containing $HOOK_MARKER)"
  2200. else
  2201. ok=1
  2202. fi
  2203. fi
  2204. if [ "$ok" -eq 1 ]; then
  2205. msg " ✅ 已清理: $short" " ✅ Cleaned: $short"
  2206. else
  2207. msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)"
  2208. fi
  2209. done
  2210. }
  2211. # Grok Build uses a dedicated Pilot-owned hook file. Match the stable entry
  2212. # script name instead of the data-dir path so custom LOONGSUITE_PILOT_DATA_DIR
  2213. # installations uninstall correctly, while unrelated hooks in the file remain.
  2214. remove_native_system_hooks() {
  2215. [ -f "$DATA_DIR/deployed-agents.json" ] || return 0
  2216. local cache="${PILOT_CACHE_DIR:-$HOME/.loongsuite-pilot}"
  2217. local version="$(cat "$cache/current" 2>/dev/null || true)"
  2218. local node_bin="${NODE_BIN:-}"
  2219. if [ ! -x "$node_bin" ] && [ -f "$DATA_DIR/node-bin" ]; then
  2220. node_bin=$(tr -d '\r\n' < "$DATA_DIR/node-bin")
  2221. fi
  2222. if [ ! -x "$node_bin" ]; then node_bin=$(command -v node) || node_bin=""; fi
  2223. if [ -z "$node_bin" ]; then
  2224. echo "System hook cleanup requires Node.js; Pilot assets retained for retry" >&2
  2225. return 1
  2226. fi
  2227. local candidate
  2228. for candidate in "$DATA_DIR/dist/scope-cleanup.cjs" "$cache/versions/$version/dist/scope-cleanup.cjs" "${PERMANENT_DIR:-$cache/package}/dist/scope-cleanup.cjs"; do
  2229. if [ -f "$candidate" ]; then
  2230. if ! "$node_bin" "$candidate" "$DATA_DIR"; then
  2231. echo "System hook cleanup failed; uninstall stopped and Pilot assets retained for retry" >&2
  2232. return 1
  2233. fi
  2234. return 0
  2235. fi
  2236. done
  2237. # Refuse to delete assets while recorded system hooks still reference them.
  2238. "$node_bin" - "$DATA_DIR/deployed-agents.json" <<'NODE'
  2239. const fs = require('fs');
  2240. try {
  2241. const state = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
  2242. if (Object.values(state).some(r => r?.hookScope === 'system' || r?.hookPendingMigration)) {
  2243. throw new Error('System hook cleanup helper missing; retain Pilot assets and retry with the installed package');
  2244. }
  2245. } catch (error) {
  2246. if (error.code !== 'ENOENT') { console.error(error.message); process.exitCode = 1; }
  2247. }
  2248. NODE
  2249. }
  2250. remove_grok_build_hook_config() {
  2251. local grok_home="${GROK_HOME:-$HOME/.grok}"
  2252. local cfg="$grok_home/hooks/loongsuite-pilot.json"
  2253. local state_file="$DATA_DIR/deployed-agents.json"
  2254. if command -v node &>/dev/null && [ -f "$state_file" ]; then
  2255. local persisted
  2256. persisted=$(node -e '
  2257. const fs = require("fs");
  2258. const path = require("path");
  2259. try {
  2260. const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  2261. const value = state?.["grok-build"]?.hookSettingsPath;
  2262. if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
  2263. } catch {}
  2264. ' "$state_file")
  2265. if [ -n "$persisted" ]; then cfg="$persisted"; fi
  2266. fi
  2267. [ -f "$cfg" ] || return 0
  2268. if ! command -v node &>/dev/null; then
  2269. msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (无 Node.js,请手动清理 Grok Build Pilot hook)" \
  2270. " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (Node.js unavailable; remove the Grok Build Pilot hook manually)"
  2271. return 0
  2272. fi
  2273. local result
  2274. result="$(node -e '
  2275. const fs = require("fs");
  2276. const cfg = process.argv[1];
  2277. const owned = value => typeof value === "string"
  2278. && /(?:^|[\\/])grok-build-loongsuite-pilot-hook\.(?:sh|ps1)(?:"|\s|$)/i.test(value);
  2279. try {
  2280. const data = JSON.parse(fs.readFileSync(cfg, "utf8"));
  2281. const hooks = data && typeof data.hooks === "object" && data.hooks ? data.hooks : null;
  2282. if (!hooks) { process.stdout.write("nochange"); process.exit(0); }
  2283. let changed = false;
  2284. for (const [event, entries] of Object.entries(hooks)) {
  2285. if (!Array.isArray(entries)) continue;
  2286. const kept = [];
  2287. for (const entry of entries) {
  2288. if (owned(entry && entry.command)) { changed = true; continue; }
  2289. if (entry && Array.isArray(entry.hooks)) {
  2290. const nested = entry.hooks.filter(hook => !owned(hook && hook.command));
  2291. if (nested.length !== entry.hooks.length) changed = true;
  2292. if (entry.hooks.length > 0 && nested.length === 0) continue;
  2293. kept.push({ ...entry, hooks: nested });
  2294. } else {
  2295. kept.push(entry);
  2296. }
  2297. }
  2298. if (kept.length === 0) delete hooks[event];
  2299. else hooks[event] = kept;
  2300. }
  2301. if (!changed) { process.stdout.write("nochange"); process.exit(0); }
  2302. if (Object.keys(hooks).length === 0) delete data.hooks;
  2303. if (Object.keys(data).length === 0) {
  2304. fs.unlinkSync(cfg);
  2305. } else {
  2306. const tmp = `${cfg}.${process.pid}.tmp`;
  2307. fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
  2308. fs.renameSync(tmp, cfg);
  2309. }
  2310. process.stdout.write("cleaned");
  2311. } catch (error) {
  2312. process.stderr.write(error.message); process.exit(1);
  2313. }
  2314. ' "$cfg" 2>/dev/null || true)"
  2315. if [ "$result" = "cleaned" ] || [ "$result" = "nochange" ]; then
  2316. msg " ✅ 已清理: ~/.grok/hooks/loongsuite-pilot.json" \
  2317. " ✅ Cleaned: ~/.grok/hooks/loongsuite-pilot.json"
  2318. else
  2319. msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (需手动清理)" \
  2320. " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (manual cleanup needed)"
  2321. fi
  2322. }
  2323. # ============================================================
  2324. # Remove the Pilot-owned DeepSeek Harness YAML patch before plugin assets.
  2325. # The same helper is invoked by the PowerShell installer.
  2326. # ============================================================
  2327. remove_dsh_yaml_patch() {
  2328. local plugin_dir="$DATA_DIR/plugins/dsh"
  2329. local cleanup_script="$plugin_dir/cleanup.mjs"
  2330. local node_bin=""
  2331. for pin_file in "$DATA_DIR/node-bin" "$HOME/.loongsuite-pilot/node-bin"; do
  2332. if [ -f "$pin_file" ]; then
  2333. local pinned
  2334. pinned=$(tr -d '\r\n' < "$pin_file")
  2335. if _node_is_suitable "$pinned"; then node_bin="$pinned"; break; fi
  2336. fi
  2337. done
  2338. if [ -z "$node_bin" ]; then node_bin=$(resolve_node) || node_bin=""; fi
  2339. if [ -z "$node_bin" ]; then
  2340. msg " ❌ 无可用 Node.js,无法安全清理 DSH YAML patch" \
  2341. " ❌ No usable Node.js; cannot safely remove the DSH YAML patch"
  2342. return 1
  2343. fi
  2344. # DSH_HOME may differ between install and uninstall. Prefer the exact path
  2345. # recorded when Pilot deployed the block, then fall back for legacy state.
  2346. local dsh_home="${DSH_HOME:-$HOME/.dsh}"
  2347. local patch_path="$dsh_home/cordis.patch.yml"
  2348. local state_file="$DATA_DIR/deployed-agents.json"
  2349. if [ -f "$state_file" ]; then
  2350. local persisted_patch
  2351. persisted_patch=$("$node_bin" -e '
  2352. const fs = require("fs");
  2353. const path = require("path");
  2354. try {
  2355. const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  2356. const value = state?.dsh?.dshPatchPath;
  2357. if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
  2358. } catch {}
  2359. ' "$state_file")
  2360. if [ -n "$persisted_patch" ]; then patch_path="$persisted_patch"; fi
  2361. fi
  2362. if [ ! -f "$cleanup_script" ]; then
  2363. if [ -f "$patch_path" ] && grep -Fq '# BEGIN PILOT-OBSERVABILITY-MANAGED' "$patch_path"; then
  2364. msg " ❌ DSH 清理脚本缺失,拒绝删除仍被 YAML 引用的插件资产" \
  2365. " ❌ DSH cleanup helper is missing; refusing to remove plugin assets still referenced by YAML"
  2366. return 1
  2367. fi
  2368. return 0
  2369. fi
  2370. if ! "$node_bin" "$cleanup_script" --patch "$patch_path" --plugin-dir "$plugin_dir"; then
  2371. msg " ❌ DSH YAML patch 清理失败;卸载已停止,Pilot 资产保持不变" \
  2372. " ❌ DSH YAML patch cleanup failed; uninstall stopped and Pilot assets were preserved"
  2373. return 1
  2374. fi
  2375. msg " ✅ 已清理 DSH YAML patch" " ✅ Cleaned DSH YAML patch"
  2376. }
  2377. # ============================================================
  2378. # Remove plugin-inject specs (OpenCode)
  2379. # ============================================================
  2380. # OpenCode uses deployMode "plugin-inject": a spec is written into its own
  2381. # config file's plugin array, not a shared settings.json. remove_hook_configs
  2382. # does not cover it, so clean it here to avoid a dangling spec that points at
  2383. # the (possibly purged) data dir.
  2384. remove_opencode_plugin() {
  2385. local configs=(
  2386. "$HOME/.config/opencode/opencode.jsonc"
  2387. "$HOME/.config/opencode/opencode.json"
  2388. "$HOME/.config/opencode/config.json"
  2389. )
  2390. for cfg in "${configs[@]}"; do
  2391. [ -f "$cfg" ] || continue
  2392. local short="${cfg/#$HOME/\~}"
  2393. if ! command -v node &>/dev/null; then
  2394. msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2395. continue
  2396. fi
  2397. local result
  2398. result=$(node -e "
  2399. const fs = require('fs');
  2400. const f = process.argv[1];
  2401. // Match legacy plugins/opencode/plugin.mjs only under this installation.
  2402. const normalize = value => {
  2403. if (typeof value !== 'string') return '';
  2404. let plain = value;
  2405. if (plain.startsWith('file://')) {
  2406. try {
  2407. const url = new URL(plain);
  2408. plain = decodeURIComponent(url.pathname);
  2409. if (plain[0] === '/' && plain[2] === ':') plain = plain.slice(1);
  2410. if (url.hostname && url.hostname !== 'localhost') {
  2411. if (process.platform !== 'win32') return '';
  2412. plain = '//' + url.hostname + plain;
  2413. }
  2414. } catch { return ''; }
  2415. }
  2416. plain = plain.split(String.fromCharCode(92)).join('/');
  2417. while (plain.endsWith('/')) plain = plain.slice(0, -1);
  2418. return process.platform === 'win32' ? plain.toLowerCase() : plain;
  2419. };
  2420. const dataDir = normalize(process.argv[2]);
  2421. const managed = dataDir ? dataDir + '/plugins/opencode' : null;
  2422. const isOurs = s => typeof s === 'string' && (
  2423. s === 'loongsuite-pilot-opencode' || s.startsWith('loongsuite-pilot-opencode@') ||
  2424. (managed !== null && (normalize(s) === managed || normalize(s) === managed + '/plugin.mjs'))
  2425. );
  2426. const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : (e?.package ?? ''));
  2427. // JSONC fallback: strip block comments, whole-line // comments, and trailing
  2428. // // comments preceded by whitespace. URL values like file:/// are never
  2429. // touched because their slashes are not preceded by whitespace.
  2430. const stripJsonc = src => src
  2431. .replace(/\/\*[\s\S]*?\*\//g, '')
  2432. .replace(/^\s*\/\/.*\$/gm, '')
  2433. .replace(/[ \t]+\/\/.*\$/gm, '');
  2434. try {
  2435. const raw = fs.readFileSync(f, 'utf-8');
  2436. let data, hadComments = false;
  2437. try { data = JSON.parse(raw); }
  2438. catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
  2439. let removed = 0;
  2440. for (const key of ['plugin', 'plugins']) {
  2441. if (!Array.isArray(data[key])) continue;
  2442. const before = data[key].length;
  2443. data[key] = data[key].filter(e => !isOurs(entryStr(e)));
  2444. removed += before - data[key].length;
  2445. }
  2446. if (!removed) { process.stdout.write('nochange'); process.exit(0); }
  2447. if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
  2448. fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2449. process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
  2450. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2451. " "$cfg" "$DATA_DIR" 2>/dev/null) || result="error"
  2452. case "$result" in
  2453. cleaned)
  2454. msg " ✅ 已清理: $short" " ✅ Cleaned: $short" ;;
  2455. cleaned-bak)
  2456. msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" \
  2457. " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" ;;
  2458. nochange)
  2459. : ;;
  2460. *)
  2461. msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
  2462. esac
  2463. done
  2464. }
  2465. # Remove only the Hermes directory plugin owned by this Pilot installation.
  2466. remove_hermes_plugin() {
  2467. local hermes_home="${HERMES_HOME:-$HOME/.hermes}"
  2468. local default_plugin_dir="$hermes_home/plugins/loongsuite-pilot"
  2469. local state_file="$DATA_DIR/deployed-agents.json"
  2470. local plugin_dir="$default_plugin_dir"
  2471. if ! command -v node &>/dev/null; then
  2472. msg " ⚠️ 跳过: $plugin_dir (无 node,需手动清理)" \
  2473. " ⚠️ Skipped: $plugin_dir (node unavailable, manual cleanup needed)"
  2474. return 0
  2475. fi
  2476. plugin_dir=$(node -e "
  2477. const fs = require('fs');
  2478. const path = require('path');
  2479. const stateFile = process.argv[1];
  2480. let target = process.argv[2];
  2481. try {
  2482. const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
  2483. const recorded = state?.['hermes-agent']?.targetDir;
  2484. if (typeof recorded === 'string' && path.isAbsolute(recorded)) target = recorded;
  2485. } catch {}
  2486. process.stdout.write(target);
  2487. " "$state_file" "$default_plugin_dir" 2>/dev/null) || plugin_dir="$default_plugin_dir"
  2488. local marker="$plugin_dir/.loongsuite-pilot-managed.json"
  2489. [ -f "$marker" ] || return 0
  2490. local ownership
  2491. ownership=$(node -e "
  2492. const fs = require('fs');
  2493. const path = require('path');
  2494. const dir = process.argv[1];
  2495. const marker = path.join(dir, '.loongsuite-pilot-managed.json');
  2496. try {
  2497. const meta = JSON.parse(fs.readFileSync(marker, 'utf8'));
  2498. if (meta.owner !== 'loongsuite-pilot' || meta.agentId !== 'hermes-agent') {
  2499. process.stdout.write('unmanaged');
  2500. process.exit(0);
  2501. }
  2502. process.stdout.write('owned');
  2503. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2504. " "$plugin_dir" 2>/dev/null) || ownership="error"
  2505. if [ "$ownership" = "owned" ]; then
  2506. local hermes_cli="${HERMES_CLI:-$hermes_home/hermes-agent/venv/bin/hermes}"
  2507. if [ ! -x "$hermes_cli" ] && command -v hermes &>/dev/null; then
  2508. hermes_cli=$(command -v hermes)
  2509. fi
  2510. if [ -x "$hermes_cli" ]; then
  2511. "$hermes_cli" plugins disable loongsuite-pilot >/dev/null 2>&1 || true
  2512. fi
  2513. fi
  2514. local result="$ownership"
  2515. if [ "$ownership" = "owned" ]; then
  2516. result=$(node -e "
  2517. const fs = require('fs');
  2518. const path = require('path');
  2519. const dir = process.argv[1];
  2520. const marker = path.join(dir, '.loongsuite-pilot-managed.json');
  2521. try {
  2522. const meta = JSON.parse(fs.readFileSync(marker, 'utf8'));
  2523. if (meta.owner !== 'loongsuite-pilot' || meta.agentId !== 'hermes-agent') {
  2524. process.stdout.write('unmanaged');
  2525. process.exit(0);
  2526. }
  2527. fs.rmSync(dir, { recursive: true, force: true });
  2528. process.stdout.write('cleaned');
  2529. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2530. " "$plugin_dir" 2>/dev/null) || result="error"
  2531. fi
  2532. case "$result" in
  2533. cleaned)
  2534. msg " ✅ 已清理: $plugin_dir" " ✅ Cleaned: $plugin_dir" ;;
  2535. unmanaged)
  2536. msg " ⚠️ 保留未受 Pilot 管理的 Hermes 插件: $plugin_dir" \
  2537. " ⚠️ Preserved unmanaged Hermes plugin: $plugin_dir" ;;
  2538. *)
  2539. msg " ⚠️ 跳过: $plugin_dir (需手动清理)" \
  2540. " ⚠️ Skipped: $plugin_dir (manual cleanup needed)" ;;
  2541. esac
  2542. }
  2543. # ============================================================
  2544. # Remove Pi Coding Agent extension injection
  2545. # ============================================================
  2546. remove_pi_coding_agent_extension() {
  2547. local cfg="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}/settings.json"
  2548. local state_file="$DATA_DIR/deployed-agents.json"
  2549. if command -v node &>/dev/null && [ -f "$state_file" ]; then
  2550. local persisted
  2551. persisted=$(node -e '
  2552. const fs = require("fs");
  2553. const path = require("path");
  2554. try {
  2555. const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  2556. const value = state?.["pi-coding-agent"]?.pluginInjectConfigPath;
  2557. if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
  2558. } catch {}
  2559. ' "$state_file")
  2560. if [ -n "$persisted" ]; then cfg="$persisted"; fi
  2561. fi
  2562. local short="${cfg/#$HOME/\~}"
  2563. if ! command -v node &>/dev/null; then
  2564. msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2565. return 0
  2566. fi
  2567. local result
  2568. result=$(node -e "
  2569. const fs = require('fs');
  2570. const path = require('path');
  2571. const defaultConfig = process.argv[1];
  2572. const dataDir = process.argv[2];
  2573. const targets = [{ configPath: defaultConfig, markers: ['loongsuite-pilot-pi-coding-agent', 'plugins/pi-coding-agent/index.mjs'] }];
  2574. const resolveValue = value => typeof value === 'string'
  2575. ? value.replace(/^~(?=[\\/])/, process.env.HOME || '').replaceAll('\$PILOT_DATA', dataDir)
  2576. : value;
  2577. const stripJsoncComments = text => {
  2578. let result = '';
  2579. let index = 0;
  2580. let inString = false;
  2581. let escape = false;
  2582. while (index < text.length) {
  2583. const ch = text[index];
  2584. if (inString) {
  2585. result += ch;
  2586. if (escape) escape = false;
  2587. else if (ch.charCodeAt(0) === 92) escape = true;
  2588. else if (ch === '\"') inString = false;
  2589. index++;
  2590. continue;
  2591. }
  2592. if (ch === '\"') {
  2593. inString = true;
  2594. result += ch;
  2595. index++;
  2596. continue;
  2597. }
  2598. if (ch === '/' && text[index + 1] === '/') {
  2599. index += 2;
  2600. while (index < text.length && text[index] !== '\n') index++;
  2601. continue;
  2602. }
  2603. if (ch === '/' && text[index + 1] === '*') {
  2604. index += 2;
  2605. while (index + 1 < text.length && !(text[index] === '*' && text[index + 1] === '/')) index++;
  2606. index += 2;
  2607. continue;
  2608. }
  2609. result += ch;
  2610. index++;
  2611. }
  2612. return result;
  2613. };
  2614. const comparable = value => typeof value === 'string'
  2615. ? value.split(String.fromCharCode(92)).join('/')
  2616. : '';
  2617. const localDir = path.join(dataDir, 'agents.d.local');
  2618. try {
  2619. for (const name of fs.existsSync(localDir) ? fs.readdirSync(localDir) : []) {
  2620. if (!name.endsWith('.json')) continue;
  2621. let def;
  2622. try { def = JSON.parse(fs.readFileSync(path.join(localDir, name), 'utf8')); } catch { continue; }
  2623. if (def?.piSdk?.schemaVersion !== 1 || !def?.pluginInject?.pluginId?.startsWith('loongsuite-pilot-pi-sdk-')) continue;
  2624. const spec = resolveValue(def.pluginInject.pluginSpec);
  2625. for (const configPath of def.pluginInject.configPaths || []) {
  2626. targets.push({
  2627. configPath: resolveValue(configPath),
  2628. markers: [def.pluginInject.pluginId, spec, 'plugins/pi-coding-agent/agents/'].filter(Boolean),
  2629. });
  2630. }
  2631. }
  2632. let cleaned = 0;
  2633. let skipped = 0;
  2634. for (const target of targets) {
  2635. if (!target.configPath || !fs.existsSync(target.configPath)) continue;
  2636. try {
  2637. const raw = fs.readFileSync(target.configPath, 'utf-8');
  2638. const data = JSON.parse(stripJsoncComments(raw));
  2639. if (!Array.isArray(data.extensions)) continue;
  2640. const before = data.extensions.length;
  2641. data.extensions = data.extensions.filter(entry => {
  2642. const value = comparable(entry);
  2643. return !target.markers.some(marker => value === comparable(marker) || value.includes(comparable(marker)));
  2644. });
  2645. if (data.extensions.length === before) continue;
  2646. if (raw !== JSON.stringify(data, null, 2) + '\n') {
  2647. try {
  2648. fs.copyFileSync(target.configPath, target.configPath + '.bak', fs.constants.COPYFILE_EXCL);
  2649. } catch (e) {
  2650. if (e?.code !== 'EEXIST') throw e;
  2651. }
  2652. }
  2653. fs.writeFileSync(target.configPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2654. cleaned++;
  2655. } catch {
  2656. skipped++;
  2657. }
  2658. }
  2659. process.stdout.write(cleaned > 0 ? (skipped > 0 ? 'partial' : 'cleaned') : (skipped > 0 ? 'skipped' : 'nochange'));
  2660. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2661. " "$cfg" "$DATA_DIR" 2>/dev/null) || result="error"
  2662. case "$result" in
  2663. cleaned)
  2664. msg " ✅ 已清理 Pi / PI SDK Agent 扩展配置" " ✅ Cleaned Pi / PI SDK Agent extension configs" ;;
  2665. partial)
  2666. msg " ⚠️ 已清理可读取的 Pi 配置,部分损坏配置需手动清理" \
  2667. " ⚠️ Cleaned readable Pi configs; some invalid configs need manual cleanup" ;;
  2668. skipped)
  2669. msg " ⚠️ Pi 配置损坏,需手动清理" " ⚠️ Invalid Pi configs skipped (manual cleanup needed)" ;;
  2670. nochange)
  2671. : ;;
  2672. *)
  2673. msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
  2674. esac
  2675. }
  2676. # ============================================================
  2677. # MiMo Code also uses deployMode "plugin-inject": a spec is written into its
  2678. # own config file's plugin array. Same shape as remove_opencode_plugin but for
  2679. # ~/.config/mimocode/mimocode.json[c]. Without this, the spec survives
  2680. # uninstall and points at a (possibly purged) plugin.mjs, so the next MiMo
  2681. # Code launch loads a non-existent module.
  2682. # ============================================================
  2683. remove_mimocode_plugin() {
  2684. local configs=(
  2685. "$HOME/.config/mimocode/mimocode.jsonc"
  2686. "$HOME/.config/mimocode/mimocode.json"
  2687. )
  2688. for cfg in "${configs[@]}"; do
  2689. [ -f "$cfg" ] || continue
  2690. local short="${cfg/#$HOME/\~}"
  2691. if ! command -v node &>/dev/null; then
  2692. msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2693. continue
  2694. fi
  2695. local result
  2696. result=$(node -e "
  2697. const fs = require('fs');
  2698. const f = process.argv[1];
  2699. const isOurs = s => typeof s === 'string' && (s.includes('loongsuite-pilot-mimo-code') || s.includes('plugins/mimo-code/plugin.mjs'));
  2700. const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : '');
  2701. const stripJsonc = src => src
  2702. .replace(/\/\*[\s\S]*?\*\//g, '')
  2703. .replace(/^\s*\/\/.*\$/gm, '')
  2704. .replace(/[ \t]+\/\/.*\$/gm, '');
  2705. try {
  2706. const raw = fs.readFileSync(f, 'utf-8');
  2707. let data, hadComments = false;
  2708. try { data = JSON.parse(raw); }
  2709. catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
  2710. const key = Array.isArray(data.plugins) ? 'plugins' : (Array.isArray(data.plugin) ? 'plugin' : null);
  2711. if (!key) { process.stdout.write('nochange'); process.exit(0); }
  2712. const before = data[key].length;
  2713. data[key] = data[key].filter(e => !isOurs(entryStr(e)));
  2714. if (data[key].length === before) { process.stdout.write('nochange'); process.exit(0); }
  2715. if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
  2716. fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2717. process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
  2718. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2719. " "$cfg" 2>/dev/null) || result="error"
  2720. case "$result" in
  2721. cleaned)
  2722. msg " ✅ 已清理: $short" " ✅ Cleaned: $short" ;;
  2723. cleaned-bak)
  2724. msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" \
  2725. " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" ;;
  2726. nochange)
  2727. : ;;
  2728. *)
  2729. msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
  2730. esac
  2731. done
  2732. }
  2733. # ============================================================
  2734. # Remove OpenClaw's nested plugin entry and load path.
  2735. # ============================================================
  2736. # OpenClaw stores injected plugins under plugins.load.paths plus
  2737. # plugins.entries. The generic hook cleanup does not cover this shape, and
  2738. # leaving either value behind makes OpenClaw load a path that uninstall is
  2739. # about to remove. Only Pilot-owned values are removed; unrelated plugins and
  2740. # their configuration remain semantically unchanged.
  2741. remove_openclaw_plugin() {
  2742. local state_dir="${OPENCLAW_STATE_DIR:-$HOME/.openclaw}"
  2743. local managed_path="$DATA_DIR/plugins/openclaw"
  2744. local configs=()
  2745. [ -n "${OPENCLAW_CONFIG_PATH:-}" ] && configs+=("$OPENCLAW_CONFIG_PATH")
  2746. configs+=(
  2747. "$state_dir/openclaw.json"
  2748. "$state_dir/config.json"
  2749. "$HOME/.openclaw/openclaw.json"
  2750. "$HOME/.openclaw/config.json"
  2751. )
  2752. local seen="|"
  2753. for cfg in "${configs[@]}"; do
  2754. [ -f "$cfg" ] || continue
  2755. case "$seen" in *"|$cfg|"*) continue ;; esac
  2756. seen="${seen}${cfg}|"
  2757. local short="${cfg/#$HOME/\~}"
  2758. if ! command -v node &>/dev/null; then
  2759. msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
  2760. continue
  2761. fi
  2762. local result
  2763. result=$(PILOT_OC_CONFIG="$cfg" PILOT_OC_MANAGED="$managed_path" node 2>/dev/null <<'NODE'
  2764. const fs = require('fs');
  2765. const f = process.env.PILOT_OC_CONFIG;
  2766. const managed = process.env.PILOT_OC_MANAGED.replaceAll('\\', '/');
  2767. const entryStr = value => typeof value === 'string'
  2768. ? value
  2769. : (Array.isArray(value) && typeof value[0] === 'string' ? value[0] : '');
  2770. const isOurs = value => {
  2771. const normalized = entryStr(value).replaceAll('\\', '/');
  2772. const plain = normalized.startsWith('file://') ? normalized.slice('file://'.length) : normalized;
  2773. return plain === managed ||
  2774. plain === managed + '/plugin.mjs' ||
  2775. normalized.includes('loongsuite-pilot-openclaw') ||
  2776. normalized.includes('plugins/openclaw/plugin.mjs') && plain.includes('.loongsuite-pilot/');
  2777. };
  2778. try {
  2779. const data = JSON.parse(fs.readFileSync(f, 'utf-8'));
  2780. let changed = false;
  2781. for (const key of ['plugin', 'plugins']) {
  2782. if (!Array.isArray(data[key])) continue;
  2783. const filtered = data[key].filter(value => !isOurs(value));
  2784. if (filtered.length !== data[key].length) { data[key] = filtered; changed = true; }
  2785. }
  2786. const plugins = data.plugins && typeof data.plugins === 'object' && !Array.isArray(data.plugins)
  2787. ? data.plugins
  2788. : null;
  2789. if (plugins) {
  2790. if (plugins.load && typeof plugins.load === 'object' && Array.isArray(plugins.load.paths)) {
  2791. const filtered = plugins.load.paths.filter(value => !isOurs(value));
  2792. if (filtered.length !== plugins.load.paths.length) { plugins.load.paths = filtered; changed = true; }
  2793. }
  2794. if (plugins.entries && typeof plugins.entries === 'object' && !Array.isArray(plugins.entries) &&
  2795. Object.prototype.hasOwnProperty.call(plugins.entries, 'loongsuite-pilot-openclaw')) {
  2796. delete plugins.entries['loongsuite-pilot-openclaw'];
  2797. changed = true;
  2798. }
  2799. }
  2800. if (!changed) { process.stdout.write('nochange'); process.exit(0); }
  2801. fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
  2802. process.stdout.write('cleaned');
  2803. } catch (e) { process.stderr.write(e.message); process.exit(1); }
  2804. NODE
  2805. ) || result="error"
  2806. case "$result" in
  2807. cleaned)
  2808. msg " ✅ 已清理: $short" " ✅ Cleaned: $short" ;;
  2809. nochange)
  2810. : ;;
  2811. *)
  2812. msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
  2813. esac
  2814. done
  2815. }
  2816. # ============================================================
  2817. # CMD: uninstall
  2818. # ============================================================
  2819. cmd_uninstall() {
  2820. msg "🗑️ 开始卸载 $PACKAGE_NAME ..." \
  2821. "🗑️ Uninstalling $PACKAGE_NAME ..."
  2822. echo ""
  2823. # Stop service (also removes autostart)
  2824. msg "==> 停止服务..." "==> Stopping service..."
  2825. if command -v loongsuite-pilot &>/dev/null; then
  2826. loongsuite-pilot stop 2>/dev/null || true
  2827. elif [ -f "$HOME/.local/bin/loongsuite-pilot" ]; then
  2828. "$HOME/.local/bin/loongsuite-pilot" stop 2>/dev/null || true
  2829. else
  2830. local pid_file="$DATA_DIR/loongsuite-pilot.pid"
  2831. if [ -f "$pid_file" ]; then
  2832. local pid; pid=$(cat "$pid_file")
  2833. kill "$pid" 2>/dev/null || true
  2834. sleep 2
  2835. kill -9 "$pid" 2>/dev/null || true
  2836. rm -f "$pid_file"
  2837. fi
  2838. # Manual autostart cleanup when loongsuite-pilot is unavailable
  2839. case "$(uname -s)" in
  2840. Darwin)
  2841. local _plist="$HOME/Library/LaunchAgents/com.loongsuite-pilot.plist"
  2842. local _uplist="$HOME/Library/LaunchAgents/com.loongsuite-pilot.updater.plist"
  2843. for f in "$_uplist" "$_plist"; do
  2844. if [ -f "$f" ]; then
  2845. launchctl unload -w "$f" 2>/dev/null || true
  2846. rm -f "$f"
  2847. fi
  2848. done
  2849. ;;
  2850. Linux)
  2851. local _run_user
  2852. _run_user="$(whoami)"
  2853. # Clean up user-level systemd units
  2854. local _user_unit_dir="$HOME/.config/systemd/user"
  2855. if [ -f "$_user_unit_dir/loongsuite-pilot.service" ]; then
  2856. systemctl --user disable --now loongsuite-pilot.service &>/dev/null || true
  2857. systemctl --user disable --now loongsuite-pilot-updater.service &>/dev/null || true
  2858. rm -f "$_user_unit_dir/loongsuite-pilot.service"
  2859. rm -f "$_user_unit_dir/loongsuite-pilot-updater.service"
  2860. systemctl --user daemon-reload &>/dev/null || true
  2861. fi
  2862. # Clean up system-level systemd units
  2863. local _sys_unit="/etc/systemd/system/loongsuite-pilot-${_run_user}.service"
  2864. local _sys_uunit="/etc/systemd/system/loongsuite-pilot-updater-${_run_user}.service"
  2865. for f in "$_sys_uunit" "$_sys_unit"; do
  2866. if [ -f "$f" ]; then
  2867. sudo systemctl disable --now "$(basename "$f")" &>/dev/null || true
  2868. sudo rm -f "$f"
  2869. fi
  2870. done
  2871. sudo systemctl daemon-reload &>/dev/null || true
  2872. # Clean up init.d scripts
  2873. local _initd="/etc/init.d/loongsuite-pilot-${_run_user}"
  2874. local _initd_u="/etc/init.d/loongsuite-pilot-updater-${_run_user}"
  2875. for f in "$_initd_u" "$_initd"; do
  2876. if [ -f "$f" ]; then
  2877. sudo "$f" stop &>/dev/null || true
  2878. local _name; _name=$(basename "$f")
  2879. if command -v chkconfig &>/dev/null; then sudo chkconfig --del "$_name" &>/dev/null || true
  2880. elif command -v update-rc.d &>/dev/null; then sudo update-rc.d "$_name" remove &>/dev/null || true; fi
  2881. sudo rm -f "$f"
  2882. fi
  2883. done
  2884. ;;
  2885. esac
  2886. fi
  2887. msg " ✅ 服务已停止" " ✅ Service stopped"
  2888. echo ""
  2889. msg "==> 清理 DSH YAML patch..." "==> Cleaning up DSH YAML patch..."
  2890. if ! remove_dsh_yaml_patch; then
  2891. return 1
  2892. fi
  2893. echo ""
  2894. # Read the persisted target before the data/install directory is removed.
  2895. msg "==> 清理 Hermes 插件..." "==> Cleaning up Hermes plugin..."
  2896. remove_hermes_plugin
  2897. echo ""
  2898. msg "==> 清理 OpenClaw 插件配置..." "==> Cleaning up OpenClaw plugin config..."
  2899. remove_openclaw_plugin
  2900. echo ""
  2901. # Remove hook entries from tool configs BEFORE removing install dir
  2902. msg "==> 清理 hook 配置..." "==> Cleaning up hook configs..."
  2903. if ! remove_native_system_hooks; then
  2904. return 1
  2905. fi
  2906. remove_hook_configs
  2907. if ! remove_grok_build_hook_config; then
  2908. return 1
  2909. fi
  2910. remove_qodercli_token_intercept
  2911. remove_qoderclicn_token_intercept
  2912. retire_qoderwork_runtime_overrides
  2913. remove_claude_code_fetch_intercept
  2914. remove_copilot_otel_environment
  2915. remove_copilot_plugin
  2916. echo ""
  2917. # Remove OTel Claude plugin
  2918. msg "==> 清理 Claude 旧插件..." "==> Cleaning up legacy Claude plugin..."
  2919. remove_otel_plugin
  2920. echo ""
  2921. # Remove plugin-inject specs (OpenCode)
  2922. msg "==> 清理 OpenCode 插件配置..." "==> Cleaning up OpenCode plugin config..."
  2923. remove_opencode_plugin
  2924. echo ""
  2925. msg "==> 清理 Pi Coding Agent Extension 配置..." "==> Cleaning up Pi Coding Agent extension config..."
  2926. remove_pi_coding_agent_extension
  2927. echo ""
  2928. # Remove plugin-inject specs (MiMo Code)
  2929. msg "==> 清理 MiMo Code 插件配置..." "==> Cleaning up MiMo Code plugin config..."
  2930. remove_mimocode_plugin
  2931. echo ""
  2932. # Remove installation artifacts
  2933. msg "==> 删除安装目录..." "==> Removing installation..."
  2934. local _cache_dir="$HOME/.loongsuite-pilot"
  2935. rm -rf "${_cache_dir:?}/versions"
  2936. rm -rf "${_cache_dir:?}/bin"
  2937. rm -rf "${_cache_dir:?}/package"
  2938. rm -f "${_cache_dir:?}/current"
  2939. rm -f "${_cache_dir:?}/previous"
  2940. rm -f "${_cache_dir:?}/node-bin"
  2941. msg " ✅ 已删除安装文件" " ✅ Installation files removed"
  2942. # Remove loongsuite-pilot command
  2943. msg "==> 删除 loongsuite-pilot 命令..." "==> Removing loongsuite-pilot command..."
  2944. rm -f "$HOME/.local/bin/loongsuite-pilot"
  2945. rm -f /usr/local/bin/loongsuite-pilot 2>/dev/null || true
  2946. msg " ✅ loongsuite-pilot 命令已删除" " ✅ loongsuite-pilot command removed"
  2947. echo ""
  2948. # Data directory
  2949. if [ "$PURGE" -eq 1 ]; then
  2950. msg "==> 删除数据目录 (--purge)..." "==> Removing data directory (--purge)..."
  2951. rm -rf "$DATA_DIR"
  2952. msg " ✅ 已删除 $DATA_DIR" " ✅ Removed $DATA_DIR"
  2953. else
  2954. msg "📁 数据目录已保留: $DATA_DIR" \
  2955. "📁 Data directory preserved: $DATA_DIR"
  2956. msg " (包含配置和日志,如需彻底删除请加 --purge)" \
  2957. " (contains config and logs, add --purge to remove)"
  2958. fi
  2959. echo ""
  2960. echo "============================================================"
  2961. msg "✅ 卸载完成!" "✅ Uninstallation complete!"
  2962. echo "============================================================"
  2963. }
  2964. # ============================================================
  2965. # Main dispatcher
  2966. # ============================================================
  2967. case "$COMMAND" in
  2968. install) cmd_install ;;
  2969. upgrade) cmd_upgrade ;;
  2970. uninstall) cmd_uninstall ;;
  2971. *)
  2972. echo "Usage: $0 {install|upgrade|uninstall} [options]"
  2973. exit 1 ;;
  2974. esac
scripts/e2e/lib/agent-matrix.mjs · Bundled script · 359 lines · 2 findings marked
  1. import { Buffer } from 'node:buffer';
  2. import { readFileSync } from 'node:fs';
  3. import * as path from 'node:path';
  4. import { fileURLToPath } from 'node:url';
  5. import { shellSingleQuoteBash } from './propagate-sls-install.mjs';
  6. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  7. export function defaultAgentMatrixPath() {
  8. return path.join(__dirname, '..', 'agent-matrix.json');
  9. }
  10. export function loadAgentMatrix(env = process.env) {
  11. const p = env.E2E_AGENT_MATRIX_PATH?.trim() || defaultAgentMatrixPath();
  12. const raw = readFileSync(p, 'utf8');
  13. const j = JSON.parse(raw);
  14. if (!Array.isArray(j.agents)) throw new Error(`agent-matrix.json missing agents[] (${p})`);
  15. return { path: p, agents: j.agents };
  16. }
  17. /** 旧 glibc 主机(RHEL/CentOS/AliOS 7)profile 检测,影响默认 Cursor 安装策略。 */
  18. export function isE2eOldGlibcCursorHostProfile(env = process.env) {
  19. const p = (env.E2E_PROFILE ?? 'linux-8u').trim().toLowerCase();
  20. return p === 'linux-7u' || p === '7u' || p === 'alios7' || p === 'linux-alios7';
  21. }
  22. /** E2E_CURSOR_INSTALL_STRATEGY 显式优先;否则旧 glibc profile → watzon,其余 → official。 */
  23. export function resolveE2eCursorInstallStrategy(env = process.env) {
  24. const raw = env.E2E_CURSOR_INSTALL_STRATEGY?.trim();
  25. if (raw) return raw.toLowerCase() === 'watzon' ? 'watzon' : 'official';
  26. return isE2eOldGlibcCursorHostProfile(env) ? 'watzon' : 'official';
  27. }
  28. /**
  29. * cursor: official=cursor.com/install Agent CLI; watzon=AppImage 提取。E2E_CURSOR_ENSURE_INSTALL_SH 最优先。
  30. */
  31. export function resolveEnsureInstallSh(agent, env = process.env) {
  32. const bin = String(agent.binary ?? '').trim();
  33. if (bin === 'cursor') {
  34. if (env.E2E_CURSOR_ENSURE_INSTALL_SH?.trim()) {
  35. return env.E2E_CURSOR_ENSURE_INSTALL_SH.trim();
  36. }
  37. const strategy = resolveE2eCursorInstallStrategy(env);
  38. if (strategy === 'watzon') {
  39. const stripInstallPath = u => String(u).trim().replace(/\/install\.sh\/?$/i, '');
  40. const jsdelivrBase = env.E2E_CURSOR_JSDELIVR_BASE?.trim()
  41. ? env.E2E_CURSOR_JSDELIVR_BASE.trim()
  42. : env.E2E_CURSOR_INSTALL_SCRIPT_URL?.trim()
  43. ? stripInstallPath(env.E2E_CURSOR_INSTALL_SCRIPT_URL)
  44. : 'https://cdn.jsdelivr.net/gh/watzon/cursor-linux-installer@main';
  45. const rawBase = env.E2E_CURSOR_RAW_BASE?.trim()
  46. ? env.E2E_CURSOR_RAW_BASE.trim()
  47. : env.E2E_CURSOR_INSTALL_SCRIPT_URL_FALLBACK?.trim()
  48. ? stripInstallPath(env.E2E_CURSOR_INSTALL_SCRIPT_URL_FALLBACK)
  49. : 'https://raw.githubusercontent.com/watzon/cursor-linux-installer/main';
  50. const failMsg =
  51. "echo '[e2e-ensure] Cursor (watzon) failed — try E2E_CURSOR_INSTALL_STRATEGY=official or E2E_CURSOR_ENSURE_INSTALL_SH'";
  52. return (
  53. `( _d="$HOME/.cache/loongsuite-e2e-cursor-install"; mkdir -p "$_d" && cd "$_d" || exit 1; ` +
  54. `_b="${jsdelivrBase}"; _f="${rawBase}"; ` +
  55. `_dl() { o="$1"; a="$2"; b="$3"; curl -fsSL --connect-timeout 25 --max-time 120 --retry 2 --retry-delay 2 "$a" -o "$o" || curl -fsSL --connect-timeout 25 --max-time 120 --retry 2 --retry-delay 2 "$b" -o "$o"; }; ` +
  56. `_dl install.sh "$_b/install.sh" "$_f/install.sh" && _dl lib.sh "$_b/lib.sh" "$_f/lib.sh" && _dl cursor.sh "$_b/cursor.sh" "$_f/cursor.sh" && ` +
  57. `chmod +x install.sh cursor.sh && bash ./install.sh stable --extract ) || ${failMsg}`
  58. );
  59. }
  60. const failOfficial =
  61. "echo '[e2e-ensure] Cursor official installer failed — set E2E_CURSOR_ENSURE_INSTALL_SH or E2E_CURSOR_INSTALL_STRATEGY=watzon'";
  62. return (
  63. `( set +e; export NO_COLOR=1; mkdir -p "$HOME/.local/bin"; ` +
  64. `curl -fsSL --connect-timeout 25 --max-time 300 --retry 2 --retry-delay 2 https://cursor.com/install | bash ) ` +
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 70 on GitHub
  65. `|| ${failOfficial}`
  66. );
  67. }
  68. return String(agent.ensureInstallSh ?? '').trim();
  69. }
  70. function buildCodexEnsureInstallSh(bin, env) {
  71. if (bin !== 'codex') return null;
  72. const spec = env.E2E_CODEX_NPM_SPEC?.trim() || '@openai/codex';
  73. return `npm install -g ${shellSingleQuoteBash(spec)} || echo '[e2e-ensure] npm install codex failed'`;
  74. }
  75. function buildEnsureSummaryScript(matrix) {
  76. const lines = [
  77. 'echo "[e2e-ensure] summary:"',
  78. ];
  79. const seen = new Set();
  80. for (const a of matrix.agents ?? []) {
  81. const bin = String(a.binary ?? '').trim();
  82. if (!bin || seen.has(bin)) continue;
  83. seen.add(bin);
  84. const label = String(a.id ?? a.name ?? bin).replace(/'/g, `'\''`);
  85. if (bin === 'cursor') {
  86. lines.push(
  87. `if [ "$_e2e_cursor_incompat" -eq 1 ] && [ "\${_e2e_have_cf:-0}" -ne 1 ]; then`,
  88. ` echo "[e2e-ensure] ${label}: cursor incompatible (glibc too old; skipped)"`,
  89. `elif [ "\${_e2e_have_cf:-0}" -eq 1 ]; then`,
  90. ` echo "[e2e-ensure] ${label}: have cursor"`,
  91. `elif command -v agent >/dev/null 2>&1 || command -v cursor-agent >/dev/null 2>&1; then`,
  92. ` echo "[e2e-ensure] ${label}: have cursor (via agent/cursor-agent CLI)"`,
  93. `elif command -v cursor-installer >/dev/null 2>&1; then`,
  94. ` echo "[e2e-ensure] ${label}: have cursor (cursor-installer on PATH; run cursor-installer --update if needed)"`,
  95. `else`,
  96. ` echo "[e2e-ensure] ${label}: missing cursor"`,
  97. `fi`,
  98. );
  99. continue;
  100. }
  101. if (bin === 'qoder') {
  102. lines.push(
  103. `if command -v qoder >/dev/null 2>&1 || command -v qodercli >/dev/null 2>&1; then echo "[e2e-ensure] ${label}: have qoder/qodercli"; else echo "[e2e-ensure] ${label}: missing qoder/qodercli"; fi`,
  104. );
  105. continue;
  106. }
  107. const binEsc = bin.replace(/'/g, `'\''`);
  108. lines.push(
  109. `if command -v '${binEsc}' >/dev/null 2>&1; then echo "[e2e-ensure] ${label}: have ${binEsc}"; else echo "[e2e-ensure] ${label}: missing ${binEsc}"; fi`,
  110. );
  111. }
  112. return lines;
  113. }
  114. /** 生成远端 ensure 脚本:npm 安装缺失 CLI,cursor 改用 --version 真实探测。 */
  115. export function buildEnsureAgentClisScript(matrix, env = process.env) {
  116. const cursorStrat = resolveE2eCursorInstallStrategy(env);
  117. const cursorSkipIfIncompat = (env.E2E_CURSOR_SKIP_IF_INCOMPAT ?? '1').trim() === '0' ? '0' : '1';
  118. const lines = [
  119. 'set +euo pipefail',
  120. 'export PATH="$HOME/.local/bin:$PATH"',
  121. `_E2E_CURSOR_STRAT=${shellSingleQuoteBash(cursorStrat)}`,
  122. `export _E2E_CURSOR_SKIP_IF_INCOMPAT=${shellSingleQuoteBash(cursorSkipIfIncompat)}`,
  123. '_e2e_cursor_incompat=0',
  124. '# 探测二进制是否可运行:0=OK, 2=glibc 不兼容, 1=其他失败。',
  125. '_e2e_cursor_runnable() {',
  126. ' _b="$1"',
  127. ' [ -n "$_b" ] || return 1',
  128. ' if [ ! -x "$_b" ] && ! command -v "$_b" >/dev/null 2>&1; then return 1; fi',
  129. ' _out=$("$_b" --version </dev/null 2>&1); _rc=$?',
  130. ' if [ "$_rc" -eq 0 ]; then return 0; fi',
  131. ' case "$_out" in',
  132. ' *GLIBC_*|*"not found"*|*"No such file or directory"*|*"cannot execute"*) return 2;;',
  133. ' esac',
  134. ' return 1',
  135. '}',
  136. 'echo "[e2e-ensure] checking agent matrix CLIs (scripts/e2e/agent-matrix.json)"',
  137. ];
  138. const extra = env.E2E_EXTRA_ENSURE_BASH?.trim();
  139. if (extra) {
  140. if (extra.length > 10_000) {
  141. console.warn('[e2e] E2E_EXTRA_ENSURE_BASH exceeds 10 000 chars — verify no accidental injection');
  142. }
  143. lines.push('# E2E_EXTRA_ENSURE_BASH');
  144. lines.push(extra);
  145. }
  146. lines.push('if ! command -v npm >/dev/null 2>&1; then');
  147. lines.push(' echo "[e2e-ensure] npm not on PATH; skipping npm-based installs"');
  148. lines.push('else');
  149. lines.push(' _npfx="$(npm config get prefix 2>/dev/null || true)"');
  150. lines.push(' if [ -n "$_npfx" ] && [ -d "$_npfx/bin" ]; then export PATH="$_npfx/bin:$PATH"; fi');
  151. const forceCodex = env.E2E_CODEX_FORCE_ENSURE?.trim() === '1';
  152. const skipAgents = resolveProbeSkipAgents(env);
  153. for (const a of matrix.agents) {
  154. const bin = String(a.binary ?? '').trim();
  155. if (!bin) continue;
  156. if (skipAgents.has(bin.toLowerCase())) continue;
  157. const label = String(a.name ?? bin);
  158. let install = resolveEnsureInstallSh(a, env);
  159. const codexSh = buildCodexEnsureInstallSh(bin, env);
  160. if (codexSh) install = codexSh;
  161. lines.push(` echo "[e2e-ensure] binary: ${bin} (${label})"`);
  162. if (bin === 'cursor') {
  163. lines.push(' _e2e_have_cf=0');
  164. lines.push(' _e2e_cf_probe() {');
  165. lines.push(' _cand="$1"');
  166. lines.push(' [ -n "$_cand" ] || return 1');
  167. lines.push(' _e2e_cursor_runnable "$_cand"');
  168. lines.push(' _rrc=$?');
  169. lines.push(' if [ "$_rrc" -eq 0 ]; then _e2e_have_cf=1; return 0; fi');
  170. lines.push(' if [ "$_rrc" -eq 2 ]; then _e2e_cursor_incompat=1; fi');
  171. lines.push(' return 1');
  172. lines.push(' }');
  173. lines.push(' if [ "$_E2E_CURSOR_STRAT" = "watzon" ]; then');
  174. lines.push(
  175. ' for _cp in "$HOME/.local/share/cursor/cursor/usr/bin/cursor" "$HOME/.cursor/cursor/usr/bin/cursor" "$(command -v cursor 2>/dev/null)"; do',
  176. );
  177. lines.push(' [ "$_e2e_have_cf" -eq 1 ] && break');
  178. lines.push(' _e2e_cf_probe "$_cp" || true');
  179. lines.push(' done');
  180. lines.push(' else');
  181. lines.push(
  182. ' # official: legacy AppImage `cursor` on PATH does not count — need Cursor Agent CLI that actually runs.',
  183. );
  184. lines.push(
  185. ' for _cp in "$HOME/.local/bin/agent" "$HOME/.local/bin/cursor-agent" "$(command -v agent 2>/dev/null)" "$(command -v cursor-agent 2>/dev/null)"; do',
  186. );
  187. lines.push(' [ "$_e2e_have_cf" -eq 1 ] && break');
  188. lines.push(' _e2e_cf_probe "$_cp" || true');
  189. lines.push(' done');
  190. lines.push(
  191. ' if [ "$_e2e_have_cf" -eq 0 ] && [ -d "$HOME/.local/share/cursor-agent/versions" ]; then',
  192. );
  193. lines.push(
  194. ' for _vdir in "$HOME/.local/share/cursor-agent/versions"/*/cursor-agent; do',
  195. );
  196. lines.push(' [ "$_e2e_have_cf" -eq 1 ] && break');
  197. lines.push(' _e2e_cf_probe "$_vdir" || true');
  198. lines.push(' done');
  199. lines.push(' fi');
  200. lines.push(' fi');
  201. lines.push(' if [ "$_e2e_have_cf" -eq 1 ]; then');
  202. lines.push(
  203. ' echo "[e2e-ensure] ok: cursor family (strategy=$_E2E_CURSOR_STRAT; verified via --version)"',
  204. );
  205. lines.push(' elif [ "$_e2e_cursor_incompat" -eq 1 ]; then');
  206. lines.push(
  207. ' echo "[e2e-ensure] cursor present but incompatible with host glibc; leaving extract untouched (set E2E_CURSOR_SKIP_IF_INCOMPAT=0 to fail loudly in probe)"',
  208. );
  209. lines.push(' else');
  210. if (install) {
  211. lines.push(` echo "[e2e-ensure] installing ${label}..."`);
  212. lines.push(` ${install}`);
  213. } else {
  214. lines.push(
  215. ` echo "[e2e-ensure] no ensureInstallSh for ${label}; install ${bin} manually or append E2E_EXTRA_ENSURE_BASH"`,
  216. );
  217. }
  218. lines.push(' fi');
  219. continue;
  220. }
  221. if (bin === 'codex' && forceCodex) {
  222. lines.push(` echo "[e2e-ensure] E2E_CODEX_FORCE_ENSURE=1: reinstalling ${label}"`);
  223. if (install) {
  224. lines.push(` ${install}`);
  225. } else {
  226. lines.push(` echo "[e2e-ensure] no codex ensure command (internal error)"`);
  227. }
  228. continue;
  229. }
  230. lines.push(` if command -v ${bin} >/dev/null 2>&1; then`);
  231. lines.push(` echo "[e2e-ensure] ok: ${bin}"`);
  232. lines.push(` else`);
  233. if (install) {
  234. lines.push(` echo "[e2e-ensure] installing ${label}..."`);
  235. lines.push(` ${install}`);
  236. } else {
  237. lines.push(
  238. ` echo "[e2e-ensure] no ensureInstallSh for ${label}; install ${bin} manually or append E2E_EXTRA_ENSURE_BASH"`,
  239. );
  240. }
  241. lines.push(` fi`);
  242. }
  243. lines.push('fi');
  244. lines.push(
  245. 'if command -v cursor-installer >/dev/null 2>&1 && ! command -v cursor >/dev/null 2>&1; then',
  246. ' echo "[e2e-ensure] cursor-installer present but cursor shim missing; trying cursor-installer --extract --update stable"',
  247. ' cursor-installer --extract --update stable || echo "[e2e-ensure] cursor-installer --extract --update failed (non-fatal if extract already done)"',
  248. 'fi',
  249. '# official: always put Agent CLI first as `~/.local/bin/cursor` (PATH may still have legacy AppImage earlier)',
  250. 'if [ "$_E2E_CURSOR_STRAT" != "watzon" ] && command -v agent >/dev/null 2>&1; then',
  251. ' mkdir -p "$HOME/.local/bin"',
  252. ' ln -sf "$(command -v agent)" "$HOME/.local/bin/cursor" && echo "[e2e-ensure] official: ~/.local/bin/cursor -> agent (overrides legacy shim order)"',
  253. 'elif ! command -v cursor >/dev/null 2>&1 && command -v agent >/dev/null 2>&1; then',
  254. ' mkdir -p "$HOME/.local/bin"',
  255. ' ln -sf "$(command -v agent)" "$HOME/.local/bin/cursor" && echo "[e2e-ensure] linked ~/.local/bin/cursor -> agent (Agent CLI)"',
  256. 'fi',
  257. '# Always fix wrong-depth path .../cursor/cursor/cursor when extract exists (watzon / legacy)',
  258. '_e2e_cursor_bin=""',
  259. 'for _p in "$HOME/.local/share/cursor/cursor/usr/bin/cursor" "$HOME/.cursor/cursor/usr/bin/cursor"; do',
  260. ' if [ -x "$_p" ]; then',
  261. ' _e2e_cursor_runnable "$_p"',
  262. ' _prc=$?',
  263. ' if [ "$_prc" -eq 0 ]; then _e2e_cursor_bin="$_p"; break; fi',
  264. ' if [ "$_prc" -eq 2 ]; then _e2e_cursor_incompat=1; fi',
  265. ' fi',
  266. 'done',
  267. 'if [ -n "$_e2e_cursor_bin" ]; then',
  268. ' for _legacy_root in "$HOME/.local/share/cursor/cursor" "$HOME/.cursor/cursor"; do',
  269. ' if [ -d "$_legacy_root" ]; then',
  270. ' ln -sf "$_e2e_cursor_bin" "$_legacy_root/cursor" && echo "[e2e-ensure] compat symlink $_legacy_root/cursor -> $_e2e_cursor_bin"',
  271. ' fi',
  272. ' done',
  273. 'fi',
  274. 'if ! command -v cursor >/dev/null 2>&1; then',
  275. ' if [ -n "$_e2e_cursor_bin" ]; then',
  276. ' mkdir -p "$HOME/.local/bin"',
  277. ' ln -sf "$_e2e_cursor_bin" "$HOME/.local/bin/cursor" && echo "[e2e-ensure] linked ~/.local/bin/cursor -> $_e2e_cursor_bin"',
  278. ' elif [ "$_e2e_cursor_incompat" -eq 1 ]; then',
  279. ' echo "[e2e-ensure] skip cursor shim creation: extracted binary incompatible with host glibc"',
  280. ' elif ! command -v agent >/dev/null 2>&1; then',
  281. ' echo "[e2e-ensure] no cursor/agent on PATH and no extracted Cursor binary under ~/.local/share/cursor or ~/.cursor"',
  282. ' fi',
  283. 'fi',
  284. );
  285. lines.push(...buildEnsureSummaryScript(matrix));
  286. return `${lines.join('\n')}\n`;
  287. }
  288. /**
  289. * Parse E2E_PROBE_SKIP_AGENTS: comma-separated list of agent binary names to skip.
  290. * @param {NodeJS.ProcessEnv} [env]
  291. * @returns {Set<string>}
  292. */
  293. export function resolveProbeSkipAgents(env = process.env) {
  294. const raw = (env?.E2E_PROBE_SKIP_AGENTS ?? '').toString().trim();
  295. if (!raw) return new Set();
  296. return new Set(raw.split(',').map(s => s.trim().toLowerCase()).filter(Boolean));
  297. }
  298. /**
  299. * One isolated bash -s per agent (stdin from decoded pipe, not SSH session).
  300. * @param {{ agents: object[] }} matrix
  301. * @param {NodeJS.ProcessEnv} [env]
  302. */
  303. export function buildMatrixProbeScript(matrix, env = process.env) {
  304. const cursorSkipIfIncompat = (env.E2E_CURSOR_SKIP_IF_INCOMPAT ?? '1').trim() === '0' ? '0' : '1';
  305. const skipAgents = resolveProbeSkipAgents(env);
  306. const lines = [
  307. 'set +e -o pipefail',
  308. 'export PATH="$HOME/.local/bin:$PATH"',
  309. `export _E2E_CURSOR_SKIP_IF_INCOMPAT=${shellSingleQuoteBash(cursorSkipIfIncompat)}`,
  310. 'cd "$HOME" || true',
  311. 'echo "[e2e-probe] running one isolated bash per agent (order = agent-matrix.json)"',
  312. ];
  313. for (const a of matrix.agents) {
  314. const block = String(a.defaultProbeSh ?? '').trim();
  315. if (!block) continue;
  316. const bin = String(a.binary ?? '').trim();
  317. const label = String(a.name ?? bin ?? 'agent').replace(/'/g, `'\\''`);
  318. const binEsc = bin.replace(/'/g, `'\\''`);
  319. if (skipAgents.has(bin.toLowerCase())) {
  320. lines.push(`echo "[e2e-probe] >>> SKIP: ${label} (binary=${binEsc}) — E2E_PROBE_SKIP_AGENTS"`);
  321. continue;
  322. }
  323. const b64 = Buffer.from(`${block}\n`, 'utf8').toString('base64');
  324. lines.push(`echo "[e2e-probe] >>> start: ${label} (binary=${binEsc})"`);
  325. lines.push(`echo "[e2e-probe] command:"; printf '%s' '${b64}' | base64 -d | sed 's/^/ /'`);
  326. lines.push(`echo ""`);
  327. lines.push(
  328. `printf '%s' '${b64}' | base64 -d | bash --norc --noprofile -s; _st=$?; ` +
    • Note: Quoted as data in code: Decodes base64 and runs the result in a shell
    • Line 351 on GitHub
  329. `if [ "$_st" -eq 0 ]; then echo "[e2e-probe] <<< end: ${label} (exit 0)"; ` +
  330. `else echo "[e2e-probe] <<< end: ${label} (exit \${_st}, non-fatal)"; fi`,
  331. );
  332. }
  333. lines.push('echo "[e2e-probe] all matrix blocks finished"');
  334. return `${lines.join('\n')}\n`;
  335. }
scripts/e2e/lib/agent-probe-body.mjs · Bundled script · 46 lines · 1 finding marked
  1. /**
  2. * Build remote bash for agent probes. Uses optional `---` line separators: first segment runs as a
  3. * normal preamble (PATH, cd); each following segment runs in its own `bash -s` fed by base64 so
  4. * tools like Codex cannot consume the rest of the SSH-delivered script from inherited stdin.
  5. *
  6. * If there is no `---`, the entire command is executed via one base64-wrapped inner bash (still
  7. * avoids sharing the outer SSH stdin pipe with grandchildren in most setups).
  8. *
  9. * @param {string} probeCmd
  10. * @returns {string} full remote bash source (include set +e yourself inside probeCmd or rely on outer)
  11. */
  12. export function buildAgentProbeRemoteBody(probeCmd) {
  13. const raw = probeCmd.trim();
  14. if (!raw) return '';
  15. const parts = raw.split(/\r?\n---\r?\n/).map(p => p.trim()).filter(Boolean);
  16. if (parts.length === 1) {
  17. return [
  18. 'set +euo pipefail',
  19. 'echo "[e2e-probe] stdin-isolated inner bash (use lines containing only --- between agents for per-agent isolation)"',
  20. wrapInBase64Bash(parts[0]),
  21. ].join('\n');
  22. }
  23. const lines = [
  24. 'set +euo pipefail',
  25. 'echo "[e2e-probe] multi-block probe (' +
  26. String(parts.length - 1) +
  27. ' isolated segment(s) after preamble; divider = line --- only)"',
  28. wrapInBase64Bash(parts[0]),
  29. ];
  30. for (let i = 1; i < parts.length; i++) {
  31. lines.push(`echo "[e2e-probe] --- block ${i} ---"`);
  32. lines.push(wrapInBase64Bash(parts[i]));
  33. }
  34. return lines.join('\n');
  35. }
  36. /**
  37. * @param {string} bashSnippet
  38. * @returns {string} one remote statement
  39. */
  40. export function wrapInBase64Bash(bashSnippet) {
  41. const b64 = Buffer.from(`${bashSnippet}\n`, 'utf8').toString('base64');
  42. return `printf '%s' '${b64}' | base64 -d | bash --norc --noprofile -s`;
    • Note: Quoted as data in code: Decodes base64 and runs the result in a shell
    • Line 45 on GitHub
  43. }
scripts/e2e/lib/e2e-scenarios.mjs · Bundled script · 1,795 lines · 1 finding marked
  1. /**
  2. * Helper module to export E2E scenario script generators for testing.
  3. * This separates the test-exportable functions from the main entry script.
  4. */
  5. import {
  6. buildRemoteInstallSlsCliQuotedArgs,
  7. shouldPropagateSlsToRemoteInstall,
  8. shellSingleQuoteBash,
  9. } from './propagate-sls-install.mjs';
  10. import { normalizeE2eQoderPersonalAccessToken } from './qoder-pat.mjs';
  11. import {
  12. buildRemoteSecretExportsSh,
  13. buildRemoteCodexConfigSh,
  14. buildRemoteClaudeOnboardingSkipSh,
  15. buildRemoteClaudeProxyConfigSh,
  16. } from './remote-agent-config.mjs';
  17. import {
  18. loadAgentMatrix,
  19. buildEnsureAgentClisScript,
  20. buildMatrixProbeScript,
  21. } from './agent-matrix.mjs';
  22. import { buildAgentProbeRemoteBody } from './agent-probe-body.mjs';
  23. /**
  24. * Default installer URL shared by run-remote-e2e and the per-scenario script generators.
  25. * Points at the loongsuite-dev OSS bucket so pre-release artifacts are exercised.
  26. */
  27. export const DEFAULT_E2E_INSTALLER_URL =
  28. 'https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-dev/loongsuite-pilot/loongsuite-pilot-installer-inner.sh';
  29. /**
  30. * Reboot autostart verification script generator.
  31. * 默认自动 sudo reboot。关键技巧:用 `nohup ... &` + `disown` 让 reboot 后台触发,
  32. * 然后本地脚本主动 exit 0,避免 SSH 被强制断开时得到 "Connection reset by peer" 被误判为失败。
  33. * @param {string} installerUrl
  34. * @param {string} userId
  35. * @param {NodeJS.ProcessEnv} env
  36. */
  37. export function rebootAutostartScript(installerUrl, userId, env) {
  38. const u = installerUrl.replace(/'/g, `'\\''`);
  39. const id = userId.replace(/'/g, `'\\''`);
  40. const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
  41. const installTail = slsFlags ? ` ${slsFlags}` : '';
  42. return `
  43. set -euo pipefail
  44. INSTALLER_URL='${u}'
  45. USER_ID='${id}'
  46. # Step 1: Install pilot
  47. echo "=== Phase 1: Install loongsuite-pilot ==="
  48. curl -fsSL "$INSTALLER_URL" | bash -s -- install --user.id "$USER_ID"${installTail}
  49. command -v loongsuite-pilot >/dev/null
  50. echo "install: loongsuite-pilot on PATH"
  51. # Step 2: Verify service is running
  52. echo "=== Phase 2: Verify initial service status ==="
  53. loongsuite-pilot status
  54. # Check systemd (no sudo needed for is-active query) and launchd
  55. if systemctl --user is-active --quiet loongsuite-pilot.service 2>/dev/null; then
  56. echo "✓ autostart: systemd user unit is active"
  57. elif systemctl is-active --quiet loongsuite-pilot.service 2>/dev/null; then
  58. echo "✓ autostart: systemd system-level unit is active"
  59. elif command -v launchctl >/dev/null 2>&1 && launchctl list 2>/dev/null | grep -q loongsuite-pilot; then
  60. echo "✓ autostart: launchd job is loaded"
  61. elif pgrep -f 'loongsuite-pilot|collector-daemon|updater-daemon' >/dev/null; then
  62. echo "✓ autostart: process running (service manager unknown)"
  63. else
  64. echo "✗ WARNING: service not detected"
  65. fi
  66. # Step 3: Capture current version and diagnostics
  67. loongsuite-pilot info
  68. echo "=== Pre-reboot diagnostics ==="
  69. ps aux | grep -E 'loongsuite-pilot|node.*dist/index' | grep -v grep || true
  70. ls -la "$HOME/.loongsuite-pilot/current" 2>/dev/null || true
  71. # Step 4: Stop service cleanly before reboot
  72. echo "=== Phase 3: Stop service and prepare reboot ==="
  73. loongsuite-pilot stop || true
  74. sleep 2
  75. # Write marker file (proves this is the same machine after reboot)
  76. echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$HOME/.loongsuite-pilot/.e2e-reboot-marker"
  77. echo "✓ Marker written: $HOME/.loongsuite-pilot/.e2e-reboot-marker"
  78. # Step 5: Auto-reboot
  79. # Check sudo availability (passwordless required for non-interactive ssh pipe)
  80. if ! sudo -n true 2>/dev/null; then
  81. echo "❌ ERROR: passwordless sudo is required for auto-reboot"
  82. echo ""
  83. echo "Please configure passwordless sudo on the remote host:"
  84. echo " echo \"$USER ALL=(ALL) NOPASSWD: /sbin/reboot, /usr/sbin/reboot\" | sudo tee /etc/sudoers.d/loongsuite-pilot-e2e"
  85. exit 1
  86. fi
  87. echo "=== Phase 4: Triggering reboot (SSH will disconnect — this is EXPECTED) ==="
  88. echo "ℹ 'Connection reset by peer' / 'Broken pipe' is normal: remote sshd is killed during reboot."
  89. echo "ℹ The local runner treats this as SUCCESS for reboot-autostart scenario."
  90. # Key trick: schedule reboot asynchronously and exit immediately.
  91. # • nohup + & + disown — detach from current shell so SSH can close cleanly
  92. # • 'sleep 1' delay — gives the local side a chance to receive the final echoes
  93. # • redirect all output — prevents reboot daemon from holding stdout/stderr
  94. nohup bash -c 'sleep 1 && sudo reboot' >/dev/null 2>&1 &
  95. disown || true
  96. echo "✓ Reboot scheduled (will fire in ~1 second)"
  97. echo "✓ Phase 1 complete. After ~30s, run:"
  98. echo " export E2E_SCENARIO=post-reboot-verify"
  99. echo " npm run test:e2e:remote"
  100. # Proactively exit with 0 so that SSH disconnect during reboot doesn't surface as error
  101. exit 0
  102. `;
  103. }
  104. /**
  105. * Post-reboot verification script generator.
  106. */
  107. export function postRebootVerificationScript() {
  108. return `
  109. set -euo pipefail
  110. echo "=== Post-Reboot Verification ==="
  111. # Check marker file
  112. MARKER="$HOME/.loongsuite-pilot/.e2e-reboot-marker"
  113. if [ -f "$MARKER" ]; then
  114. echo "Reboot marker found (written at: $(cat "$MARKER"))"
  115. else
  116. echo "ERROR: Reboot marker not found — this may be a fresh machine"
  117. exit 1
  118. fi
  119. # Check if pilot command is available
  120. if ! command -v loongsuite-pilot >/dev/null; then
  121. echo "ERROR: loongsuite-pilot not on PATH after reboot"
  122. exit 1
  123. fi
  124. echo "✓ loongsuite-pilot on PATH"
  125. # Check service status
  126. if systemctl --user is-active --quiet loongsuite-pilot.service 2>/dev/null; then
  127. echo "✓ systemd user unit loongsuite-pilot.service is ACTIVE"
  128. systemctl --user status loongsuite-pilot.service --no-pager || true
  129. elif systemctl is-active --quiet loongsuite-pilot.service 2>/dev/null; then
  130. echo "✓ systemd system-level unit loongsuite-pilot.service is ACTIVE"
  131. systemctl status loongsuite-pilot.service --no-pager 2>/dev/null || true
  132. else
  133. echo "✗ systemd unit NOT active (checking alternatives...)"
  134. if pgrep -f 'loongsuite-pilot|node.*dist/index' >/dev/null; then
  135. echo "✓ loongsuite-pilot process found (via pgrep)"
  136. ps aux | grep -E 'loongsuite-pilot|node.*dist/index' | grep -v grep || true
  137. else
  138. echo "✗ No pilot process found"
  139. exit 1
  140. fi
  141. fi
  142. # Check updater daemon
  143. if systemctl --user is-active --quiet loongsuite-pilot-updater.service 2>/dev/null; then
  144. echo "✓ updater daemon is ACTIVE (user-level)"
  145. elif systemctl is-active --quiet loongsuite-pilot-updater.service 2>/dev/null; then
  146. echo "✓ updater daemon is ACTIVE (system-level)"
  147. else
  148. echo "⚠ updater daemon not detected via systemd (may still be running)"
  149. fi
  150. # Verify data integrity
  151. if [ -d "$HOME/.loongsuite-pilot" ]; then
  152. echo "✓ data directory exists"
  153. ls -la "$HOME/.loongsuite-pilot/" || true
  154. else
  155. echo "✗ data directory missing"
  156. exit 1
  157. fi
  158. # Quick version check
  159. loongsuite-pilot info
  160. echo "=== Post-reboot verification PASSED ==="
  161. `;
  162. }
  163. /**
  164. * Multi-account install script generator.
  165. */
  166. export function multiAccountInstallScript(installerUrl, userIds, env) {
  167. const u = installerUrl.replace(/'/g, `'\\''`);
  168. const ids = userIds.replace(/'/g, `'\\''`);
  169. const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
  170. const installTail = slsFlags ? ` ${slsFlags}` : '';
  171. return `
  172. set -euo pipefail
  173. INSTALLER_URL='${u}'
  174. USER_IDS='${ids}'
  175. echo "=== Multi-Account Install Test ==="
  176. echo "User IDs: $USER_IDS"
  177. # Parse comma-separated user IDs
  178. IFS=',' read -ra USERS <<< "$USER_IDS"
  179. for i in "\${!USERS[@]}"; do
  180. USER_ID="\${USERS[$i]}"
  181. USER_HOME=$(eval echo "~user\${i}")
  182. echo ""
  183. echo "--- Installing for user\${i} (ID: $USER_ID) ---"
  184. # Check if user exists, create if not
  185. if ! id "user\${i}" &>/dev/null; then
  186. echo "Creating user\${i}..."
  187. sudo useradd -m -s /bin/bash "user\${i}" || {
  188. echo "WARNING: Cannot create user\${i} (may need root), using current user with different config dir"
  189. USER_HOME="$HOME/.loongsuite-pilot-test-user\${i}"
  190. }
  191. fi
  192. # Install pilot for this user
  193. if id "user\${i}" &>/dev/null; then
  194. sudo -u "user\${i}" bash -c "
  195. set -euo pipefail
  196. export HOME=$(eval echo ~user\${i})
  197. curl -fsSL '${u}' | bash -s -- install --user.id '\${USER_ID}'${installTail}
  198. command -v loongsuite-pilot >/dev/null || echo 'WARNING: loongsuite-pilot not in PATH for user\${i}'
  199. test -d \"\$HOME/.loongsuite-pilot\" && echo '✓ data dir created' || echo '✗ data dir missing'
  200. "
  201. else
  202. # Fallback: install in isolated directory under current user
  203. mkdir -p "$USER_HOME"
  204. AGENT_DATA_COLLECTION_CONFIG="$USER_HOME/config.json" curl -fsSL "$INSTALLER_URL" | bash -s -- install --user.id "$USER_ID"${installTail}
  205. echo "✓ Installed for user\${i} (isolated mode in $USER_HOME)"
  206. fi
  207. done
  208. # Verify all installations
  209. echo ""
  210. echo "=== Verification ==="
  211. for i in "\${!USERS[@]}"; do
  212. if id "user\${i}" &>/dev/null; then
  213. sudo -u "user\${i}" bash -c "
  214. echo \"user\${i}: \$(loongsuite-pilot info 2>&1 || echo 'info command failed')\"
  215. test -f \"\$HOME/.loongsuite-pilot/config.json\" && echo \" ✓ config.json exists\" || echo \" ✗ config.json missing\"
  216. "
  217. else
  218. echo "user\${i}: (isolated mode)"
  219. test -f "$HOME/.loongsuite-pilot-test-user\${i}/config.json" && echo " ✓ config.json exists" || echo " ✗ config.json missing"
  220. fi
  221. done
  222. echo ""
  223. echo "=== Multi-account install test completed ==="
  224. `;
  225. }
  226. /**
  227. * Auto-upgrade test script generator.
  228. */
  229. export function autoUpgradeScript(installerUrl, userId, env) {
  230. const u = installerUrl.replace(/'/g, `'\\''`);
  231. const id = userId.replace(/'/g, `'\\''`);
  232. const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
  233. const installTail = slsFlags ? ` ${slsFlags}` : '';
  234. return `
  235. set -euo pipefail
  236. INSTALLER_URL='${u}'
  237. USER_ID='${id}'
  238. echo "=== Auto-Upgrade Test ==="
  239. # Phase 1: Initial install
  240. echo "--- Phase 1: Install pilot ---"
  241. curl -fsSL "$INSTALLER_URL" | bash -s -- install --user.id "$USER_ID"${installTail}
  242. command -v loongsuite-pilot >/dev/null
  243. echo "✓ Initial install successful"
  244. # Capture initial version
  245. INITIAL_VERSION=$(loongsuite-pilot info 2>&1 | head -1)
  246. INITIAL_COMMIT=$(cat "$HOME/.loongsuite-pilot/VERSION" | grep git_commit | cut -d'=' -f2)
  247. echo "Initial version: $INITIAL_VERSION"
  248. echo "Initial commit: $INITIAL_COMMIT"
  249. # Phase 2: Verify initial service running
  250. echo ""
  251. echo "--- Phase 2: Verify initial service ---"
  252. loongsuite-pilot status || true
  253. ps aux | grep -E 'loongsuite-pilot|node.*dist/index' | grep -v grep || true
  254. # Phase 3: Trigger upgrade
  255. echo ""
  256. echo "--- Phase 3: Trigger upgrade ---"
  257. echo "Running upgrade command..."
  258. curl -fsSL "$INSTALLER_URL" | bash -s -- upgrade
  259. # Wait for upgrade to complete
  260. echo "Waiting 10s for upgrade to stabilize..."
  261. sleep 10
  262. # Phase 4: Verify upgraded version
  263. echo ""
  264. echo "--- Phase 4: Verify upgraded version ---"
  265. if [ -f "$HOME/.loongsuite-pilot/VERSION" ]; then
  266. NEW_VERSION=$(loongsuite-pilot info 2>&1 | head -1)
  267. NEW_COMMIT=$(cat "$HOME/.loongsuite-pilot/VERSION" | grep git_commit | cut -d'=' -f2)
  268. echo "New version: $NEW_VERSION"
  269. echo "New commit: $NEW_COMMIT"
  270. if [ "$INITIAL_COMMIT" = "$NEW_COMMIT" ]; then
  271. echo "⚠ Version unchanged (may already be latest)"
  272. else
  273. echo "✓ Version changed from $INITIAL_COMMIT to $NEW_COMMIT"
  274. fi
  275. else
  276. echo "✗ VERSION file missing after upgrade"
  277. exit 1
  278. fi
  279. # Phase 5: Verify service restarted after upgrade
  280. echo ""
  281. echo "--- Phase 5: Verify service auto-restart ---"
  282. if systemctl --user is-active --quiet loongsuite-pilot.service 2>/dev/null; then
  283. echo "✓ systemd service is ACTIVE after upgrade (user-level)"
  284. systemctl --user status loongsuite-pilot.service --no-pager | head -10 || true
  285. elif systemctl is-active --quiet loongsuite-pilot.service 2>/dev/null; then
  286. echo "✓ systemd service is ACTIVE after upgrade (system-level)"
  287. systemctl status loongsuite-pilot.service --no-pager 2>/dev/null | head -10 || true
  288. else
  289. if pgrep -f 'loongsuite-pilot|node.*dist/index' >/dev/null; then
  290. echo "✓ pilot process found after upgrade"
  291. else
  292. echo "✗ pilot process NOT found after upgrade"
  293. exit 1
  294. fi
  295. fi
  296. # Phase 6: Verify data integrity
  297. echo ""
  298. echo "--- Phase 6: Verify data integrity ---"
  299. if [ -f "$HOME/.loongsuite-pilot/config.json" ]; then
  300. echo "✓ config.json preserved"
  301. cat "$HOME/.loongsuite-pilot/config.json" | grep -o '"userId":"[^"]*"' || true
  302. else
  303. echo "✗ config.json missing after upgrade"
  304. exit 1
  305. fi
  306. if [ -d "$HOME/.loongsuite-pilot/versions" ]; then
  307. echo "✓ versions directory exists (multi-version management)"
  308. ls -la "$HOME/.loongsuite-pilot/versions/" || true
  309. else
  310. echo "⚠ versions directory not found"
  311. fi
  312. echo ""
  313. echo "=== Auto-Upgrade Test PASSED ==="
  314. `;
  315. }
  316. /**
  317. * 解析 E2E_AGENT_VERSIONS_N,默认 3。
  318. * @param {NodeJS.ProcessEnv} env
  319. */
  320. export function resolveVersionMatrixN(env) {
  321. const raw = (env?.E2E_AGENT_VERSIONS_N ?? '3').toString().trim();
  322. const n = Number.parseInt(raw, 10);
  323. if (!Number.isFinite(n) || n <= 0) return 3;
  324. return Math.min(n, 20);
  325. }
  326. /**
  327. * 解析 E2E_AGENT_VERSIONS_FILTER(逗号分隔的 binary 或 id),空值表示不过滤。
  328. * @param {NodeJS.ProcessEnv} env
  329. */
  330. export function resolveVersionMatrixFilter(env) {
  331. const raw = (env?.E2E_AGENT_VERSIONS_FILTER ?? '').toString().trim();
  332. if (!raw) return null;
  333. return raw
  334. .split(',')
  335. .map(s => s.trim().toLowerCase())
  336. .filter(Boolean);
  337. }
  338. /**
  339. * 从 matrix 中筛选出支持版本矩阵的 agents(npmPackage 非空)。
  340. * @param {{agents: object[]}} matrix
  341. * @param {NodeJS.ProcessEnv} env
  342. */
  343. export function resolveVersionMatrixAgents(matrix, env = process.env) {
  344. const filter = resolveVersionMatrixFilter(env);
  345. const agents = (matrix?.agents ?? []).filter(a => {
  346. const pkg = typeof a.npmPackage === 'string' ? a.npmPackage.trim() : '';
  347. if (!pkg) return false;
  348. if (!filter) return true;
  349. const bin = String(a.binary ?? '').trim().toLowerCase();
  350. const id = String(a.id ?? '').trim().toLowerCase();
  351. return filter.includes(bin) || filter.includes(id);
  352. });
  353. return agents;
  354. }
  355. /**
  356. * Agent 鉴权 / 配置注入 prologue(复用 install-smoke 的处理):
  357. * - CODEX_OPENAI_API_KEY / ANTHROPIC_BASE_URL / ANTHROPIC_API_KEY / ANTHROPIC_MODEL / CURSOR_API_KEY
  358. * - 可选:~/.codex/config.toml、~/.claude.json(hasCompletedOnboarding)、~/.config/claude-code-proxy/config.json
  359. * - QODER_PERSONAL_ACCESS_TOKEN
  360. * 这些 export 的环境变量会被后续 `bash --norc --noprofile -s` 子 shell 继承(shell 进程默认继承环境变量)。
  361. * @param {NodeJS.ProcessEnv} env
  362. * @returns {string}
  363. */
  364. export function buildVersionMatrixPrologueSh(env = process.env) {
  365. const chunks = [];
  366. const secrets = buildRemoteSecretExportsSh(env);
  367. if (secrets) chunks.push(secrets.trimEnd());
  368. const codexCfg = buildRemoteCodexConfigSh(env);
  369. if (codexCfg) chunks.push(codexCfg.trimEnd());
  370. const claudeOnboard = buildRemoteClaudeOnboardingSkipSh(env);
  371. if (claudeOnboard) chunks.push(claudeOnboard.trimEnd());
  372. const claudeProxy = buildRemoteClaudeProxyConfigSh(env);
  373. if (claudeProxy) chunks.push(claudeProxy.trimEnd());
  374. const tok = normalizeE2eQoderPersonalAccessToken(env?.E2E_QODER_PERSONAL_ACCESS_TOKEN);
  375. if (tok) chunks.push(`export QODER_PERSONAL_ACCESS_TOKEN=${shellSingleQuoteBash(tok)}`);
  376. if (!chunks.length) return '';
  377. return `${chunks.join('\n')}\n`;
  378. }
  379. /**
  380. * version-matrix 场景可选的 loongsuite-pilot 安装前导(类似 install-smoke)。
  381. * 如果 env 里有 E2E_USER_ID(+ 可选 SLS flags),则在 Node 升级后、agent 循环前自动重装 pilot,保证 SLS 能看到数据。
  382. * @param {NodeJS.ProcessEnv} env
  383. */
  384. export function buildVersionMatrixInstallPreludeSh(env = process.env) {
  385. const userId = (env?.E2E_USER_ID ?? '').trim();
  386. if (!userId) return '';
  387. const installerUrl = (env?.E2E_INSTALLER_URL ?? DEFAULT_E2E_INSTALLER_URL).replace(/'/g, `'\\''`);
  388. const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
  389. const installTail = slsFlags ? ` ${slsFlags}` : '';
  390. const uid = userId.replace(/'/g, `'\\''`);
  391. return `
  392. # [version-matrix] 重装/刷新 pilot + SLS 配置(同 install-smoke),保证 SLS Logstore 能收到数据
  393. echo "[version-matrix] (re-)installing loongsuite-pilot with SLS flags ..."
  394. curl -fsSL '${installerUrl}' | bash -s -- install --user.id '${uid}'${installTail} || {
  395. echo "[version-matrix] WARN: pilot install failed (may already be installed) — continuing"
  396. }
  397. `;
  398. }
  399. /**
  400. * 生成远端 version-matrix 脚本:对每个支持版本矩阵的 agent,串行安装最近 N 个版本并执行 probe。
  401. * 当 E2E_USER_ID 存在时自动重装 pilot(带 SLS flags)以保证遥测数据可观测。
  402. * @param {{agents: object[]}} matrix
  403. * @param {NodeJS.ProcessEnv} env
  404. */
  405. export function versionMatrixScript(matrix, env = process.env) {
  406. const agents = resolveVersionMatrixAgents(matrix, env);
  407. const n = resolveVersionMatrixN(env);
  408. const requirePilot = (env?.E2E_VERSION_MATRIX_REQUIRE_PILOT ?? '1').toString().trim() !== '0';
  409. const restoreLatest = (env?.E2E_VERSION_MATRIX_RESTORE_LATEST ?? '1').toString().trim() !== '0';
  410. const prologue = buildVersionMatrixPrologueSh(env);
  411. const installPrelude = buildVersionMatrixInstallPreludeSh(env);
  412. if (agents.length === 0) {
  413. return `
  414. set +e
  415. ${prologue}echo "[version-matrix] no agents with npmPackage found (filter=\${E2E_AGENT_VERSIONS_FILTER:-})"
  416. exit 0
  417. `;
  418. }
  419. const perAgentBlocks = agents
  420. .map(a => {
  421. const pkg = a.npmPackage.replace(/'/g, `'\\''`);
  422. const bin = String(a.binary ?? '').replace(/'/g, `'\\''`);
  423. const label = String(a.name ?? a.binary ?? pkg).replace(/'/g, `'\\''`);
  424. const probe = (a.defaultProbeSh ?? '').toString();
  425. const probeB64 = Buffer.from(probe + '\n', 'utf8').toString('base64');
  426. return `
  427. echo ""
  428. echo "########################################"
  429. echo "# [version-matrix] agent=${label} (binary=${bin}, pkg=${pkg})"
  430. echo "########################################"
  431. _run_agent_matrix '${pkg}' '${bin}' '${label}' '${probeB64}'
  432. `;
  433. })
  434. .join('\n');
  435. return `
  436. set +e
  437. ${prologue}
  438. # prepend npm global bin to avoid stale PATH symlinks
  439. _NPM_PREFIX="$(npm config get prefix 2>/dev/null || true)"
  440. if [ -n "$_NPM_PREFIX" ] && [ -d "$_NPM_PREFIX/bin" ]; then
  441. export PATH="$_NPM_PREFIX/bin:$HOME/.local/bin:$PATH"
  442. else
  443. export PATH="$HOME/.local/bin:$PATH"
  444. fi
  445. echo "[version-matrix] mode=serial; versions_per_agent=${n}; filter=\${E2E_AGENT_VERSIONS_FILTER:-<none>}; npm_prefix=\${_NPM_PREFIX:-<unknown>}"
  446. # remove stale ~/.local/bin/<bin> -> qodercli symlinks left by old scripts
  447. _cleanup_stale_bin() {
  448. _b="$1"
  449. [ "$_b" = "qoder" ] && return 0
  450. _p="$HOME/.local/bin/$_b"
  451. if [ -L "$_p" ]; then
  452. _tgt="$(readlink "$_p" 2>/dev/null || true)"
  453. case "$_tgt" in
  454. *qodercli*|*@qoder-ai*) rm -f "$_p" && echo "[version-matrix] removed stale $_p -> $_tgt";;
  455. esac
  456. fi
  457. }
  458. if ! command -v npm >/dev/null 2>&1; then
  459. echo "[version-matrix] ERROR: npm not on PATH on remote. Install Node.js/npm first."
  460. exit 2
  461. fi
  462. if ! command -v node >/dev/null 2>&1; then
  463. echo "[version-matrix] ERROR: node not on PATH on remote."
  464. exit 2
  465. fi
  466. # auto-upgrade Node via nvm if below min (old Node may crash newer CLI bundles)
  467. _MIN_NODE_MAJOR="\${E2E_VERSION_MATRIX_MIN_NODE:-22}"
  468. _AUTO_UPGRADE_NODE="\${E2E_VERSION_MATRIX_AUTO_UPGRADE_NODE:-1}"
  469. _node_major() { node -v 2>/dev/null | sed -E 's/^v([0-9]+).*/\\1/'; }
  470. _cur_major="$(_node_major)"
  471. if [ -z "$_cur_major" ] || [ "$_cur_major" -lt "$_MIN_NODE_MAJOR" ] 2>/dev/null; then
  472. echo "[version-matrix] current node=v$_cur_major < required v$_MIN_NODE_MAJOR (to avoid bundle/runtime incompat on old Node)"
  473. if [ "$_AUTO_UPGRADE_NODE" != "1" ]; then
  474. echo "[version-matrix] ERROR: auto-upgrade disabled. Upgrade Node manually or set E2E_VERSION_MATRIX_AUTO_UPGRADE_NODE=1."
  475. exit 2
  476. fi
  477. _OLD_NPM_BIN="$(npm config get prefix 2>/dev/null)/bin"
  478. export NVM_DIR="\${NVM_DIR:-$HOME/.nvm}"
  479. if [ ! -s "$NVM_DIR/nvm.sh" ]; then
  480. echo "[version-matrix] installing nvm 0.39.7 to $NVM_DIR ..."
  481. if command -v curl >/dev/null 2>&1; then
  482. curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash >/tmp/.e2e-vm-nvm-install.log 2>&1 || {
  483. echo "[version-matrix] ERROR: nvm install failed (tail):"; tail -20 /tmp/.e2e-vm-nvm-install.log; exit 2;
  484. }
  485. elif command -v wget >/dev/null 2>&1; then
  486. wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash >/tmp/.e2e-vm-nvm-install.log 2>&1 || {
  487. echo "[version-matrix] ERROR: nvm install failed (tail):"; tail -20 /tmp/.e2e-vm-nvm-install.log; exit 2;
  488. }
  489. else
  490. echo "[version-matrix] ERROR: neither curl nor wget on PATH; cannot install nvm."; exit 2;
  491. fi
  492. fi
  493. # shellcheck disable=SC1090
  494. . "$NVM_DIR/nvm.sh" || { echo "[version-matrix] ERROR: cannot source $NVM_DIR/nvm.sh"; exit 2; }
  495. echo "[version-matrix] nvm install $_MIN_NODE_MAJOR ..."
  496. nvm install "$_MIN_NODE_MAJOR" >/tmp/.e2e-vm-nvm-node.log 2>&1 || {
  497. echo "[version-matrix] ERROR: nvm install $_MIN_NODE_MAJOR failed (tail):"; tail -30 /tmp/.e2e-vm-nvm-node.log; exit 2;
  498. }
  499. nvm use "$_MIN_NODE_MAJOR" >/dev/null 2>&1 || { echo "[version-matrix] ERROR: nvm use $_MIN_NODE_MAJOR failed"; exit 2; }
  500. nvm alias default "$_MIN_NODE_MAJOR" >/dev/null 2>&1 || true
  501. # old-glibc hosts (Linux 7U / CentOS 7): apply Aliyun patchelf if node -v fails
  502. _AUTO_PATCHELF="\${E2E_VERSION_MATRIX_AUTO_PATCHELF:-1}"
  503. _node_try="$(node -v 2>&1)"
  504. _node_try_st=$?
  505. if [ "$_node_try_st" -ne 0 ] || printf '%s' "$_node_try" | grep -qE 'GLIBC|GLIBCXX|CXXABI|not found|error while loading' 2>/dev/null; then
  506. echo "[version-matrix] node=v$_MIN_NODE_MAJOR has glibc/libstdc++ incompat on this host (Linux 7U / CentOS 7 pattern):"
  507. printf '%s\n' "$_node_try" | head -5 | sed 's/^/ /'
  508. if [ "$_AUTO_PATCHELF" != "1" ]; then
  509. echo "[version-matrix] ERROR: auto-patchelf disabled (E2E_VERSION_MATRIX_AUTO_PATCHELF=0). Apply patch manually."
  510. exit 2
  511. fi
  512. echo "[version-matrix] applying Aliyun patchelf_node_for_7u.sh ..."
  513. _patchelf_log="/tmp/.e2e-vm-patchelf.log"
  514. _patchelf_url="https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite/loongsuite-pilot/patchelf_node_for_7u.sh"
  515. if command -v curl >/dev/null 2>&1; then
  516. curl -fsSL "$_patchelf_url" | bash >"$_patchelf_log" 2>&1
  517. elif command -v wget >/dev/null 2>&1; then
  518. wget -qO- "$_patchelf_url" | bash >"$_patchelf_log" 2>&1
  519. else
  520. echo "[version-matrix] ERROR: neither curl nor wget on PATH; cannot fetch patchelf script."; exit 2;
  521. fi
  522. _patch_st=$?
  523. if [ "$_patch_st" -ne 0 ]; then
  524. echo "[version-matrix] ERROR: patchelf_node_for_7u.sh failed (rc=$_patch_st) tail:"
  525. tail -30 "$_patchelf_log" 2>/dev/null || true
  526. exit 2
  527. fi
  528. _node_try2="$(node -v 2>&1)"
  529. if [ $? -ne 0 ] || printf '%s' "$_node_try2" | grep -qE 'GLIBC|GLIBCXX|CXXABI|not found|error while loading' 2>/dev/null; then
  530. echo "[version-matrix] ERROR: node still broken after patchelf:"
  531. printf '%s\n' "$_node_try2" | head -10 | sed 's/^/ /'
  532. echo "[version-matrix] patchelf log tail:"; tail -20 "$_patchelf_log" 2>/dev/null || true
  533. exit 2
  534. fi
  535. echo "[version-matrix] patchelf succeeded; node=$_node_try2"
  536. fi
  537. echo "[version-matrix] switched to node=$(node -v 2>/dev/null) npm=$(npm -v 2>/dev/null)"
  538. _NPM_PREFIX="$(npm config get prefix 2>/dev/null || true)"
  539. if [ -n "$_NPM_PREFIX" ] && [ -d "$_NPM_PREFIX/bin" ]; then
  540. export PATH="$_NPM_PREFIX/bin:$HOME/.local/bin:$PATH"
  541. fi
  542. if [ -n "$_OLD_NPM_BIN" ] && [ -d "$_OLD_NPM_BIN" ] && [ "$_OLD_NPM_BIN" != "$_NPM_PREFIX/bin" ]; then
  543. case ":$PATH:" in *":$_OLD_NPM_BIN:"*) ;; *) export PATH="$PATH:$_OLD_NPM_BIN";; esac
  544. fi
  545. echo "[version-matrix] npm_prefix(updated)=\${_NPM_PREFIX:-<unknown>}"
  546. fi
  547. ${installPrelude}
  548. ${requirePilot ? `if ! command -v loongsuite-pilot >/dev/null 2>&1; then
  549. echo "[version-matrix] ERROR: loongsuite-pilot not installed. Run install-smoke first or set E2E_VERSION_MATRIX_REQUIRE_PILOT=0 to skip."
  550. exit 2
  551. fi
  552. loongsuite-pilot info 2>&1 | head -3 || true` : '# Pilot precheck skipped (E2E_VERSION_MATRIX_REQUIRE_PILOT=0)'}
  553. _latest_versions() {
  554. _pkg="$1"; _n="$2"
  555. npm view "$_pkg" versions --json 2>/dev/null | node -e "
  556. let raw='';
  557. process.stdin.on('data', c => raw += c);
  558. process.stdin.on('end', () => {
  559. try {
  560. const j = JSON.parse(raw);
  561. const arr = Array.isArray(j) ? j : [j];
  562. const PLAT = /-(win32|linux|darwin|freebsd|sunos|aix|android|musl|alpine|x64|arm64|arm|ia32|x86_64|aarch64|armv7l|ppc64|s390x)([.-][A-Za-z0-9_]+)*$/i;
  563. const filtered = arr.filter(v => typeof v === 'string' && !PLAT.test(v));
  564. const n = parseInt(process.argv[1], 10) || 3;
  565. const slice = filtered.slice(-n).reverse();
  566. for (const v of slice) process.stdout.write(v + '\\n');
  567. } catch (e) { process.exit(0); }
  568. });
  569. " "$_n"
  570. }
  571. _run_agent_matrix() {
  572. _pkg="$1"; _bin="$2"; _label="$3"; _probe_b64="$4"
  573. _cleanup_stale_bin "\${_bin}"
  574. echo "[version-matrix] querying npm: \${_pkg}"
  575. _versions="$(_latest_versions "\${_pkg}" "${n}")"
  576. if [ -z "\${_versions}" ]; then
  577. echo "[version-matrix] WARN: cannot fetch versions for \${_pkg} (network? package renamed?) — skipping"
  578. return 0
  579. fi
  580. echo "[version-matrix] \${_label} most recent versions (latest first):"
  581. echo "\${_versions}" | sed 's/^/ - /'
  582. npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
  583. for _v in \${_versions}; do
  584. echo ""
  585. echo ">>> [version-matrix] agent=\${_label} version=\${_v} >>>"
  586. _spec="\${_pkg}@\${_v}"
  587. if ! npm install -g "\${_spec}" >/tmp/.e2e-vm-install.log 2>&1; then
  588. echo "[version-matrix] install failed for \${_spec} (tail):"
  589. tail -20 /tmp/.e2e-vm-install.log || true
  590. echo "<<< [version-matrix] agent=\${_label} version=\${_v} SKIPPED <<<"
  591. continue
  592. fi
  593. _abs_bin=""
  594. if [ -n "$_NPM_PREFIX" ] && [ -x "$_NPM_PREFIX/bin/\${_bin}" ]; then
  595. _abs_bin="$_NPM_PREFIX/bin/\${_bin}"
  596. elif [ "\${_bin}" = "qoder" ] && [ -n "$_NPM_PREFIX" ] && [ -x "$_NPM_PREFIX/bin/qodercli" ]; then
  597. _abs_bin="$_NPM_PREFIX/bin/qodercli"
  598. mkdir -p "$HOME/.local/bin" && ln -sf "$_abs_bin" "$HOME/.local/bin/qoder" 2>/dev/null || true
  599. elif command -v "\${_bin}" >/dev/null 2>&1; then
  600. _abs_bin="$(command -v "\${_bin}")"
  601. elif [ "\${_bin}" = "qoder" ] && command -v qodercli >/dev/null 2>&1; then
  602. _abs_bin="$(command -v qodercli)"
  603. mkdir -p "$HOME/.local/bin" && ln -sf "$_abs_bin" "$HOME/.local/bin/qoder" 2>/dev/null || true
  604. fi
  605. if [ -z "$_abs_bin" ]; then
  606. echo "[version-matrix] WARN: \${_bin} not on PATH after install (likely platform-specific subpackage without top-level bin) — SKIPPED"
  607. echo "<<< [version-matrix] agent=\${_label} version=\${_v} SKIPPED <<<"
  608. npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
  609. continue
  610. fi
  611. echo "[version-matrix] resolved \${_bin} -> $_abs_bin"
  612. _ver_out="$("$_abs_bin" --version 2>&1)"
  613. _ver_st=$?
  614. printf '%s\n' "$_ver_out" | head -3
  615. if [ "$_ver_st" -ne 0 ] || printf '%s' "$_ver_out" | grep -qE 'SyntaxError|Invalid regular expression|ERR_UNSUPPORTED|Cannot find module' 2>/dev/null; then
  616. echo "[version-matrix] WARN: \${_bin} --version failed (rc=$_ver_st) — likely bundle/runtime incompatibility; SKIPPED probe for this version"
  617. _node_v="$(node -v 2>/dev/null || echo unknown)"
  618. echo "[version-matrix] node=$_node_v; consider newer Node (20+/22+) or newer CLI version"
  619. echo "<<< [version-matrix] agent=\${_label} version=\${_v} SKIPPED (incompat) <<<"
  620. npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
  621. continue
  622. fi
  623. # dedup codex [hooks.state."..."] to avoid duplicate-key warnings
  624. if [ "\${_bin}" = "codex" ] && [ -f "$HOME/.codex/config.toml" ]; then
  625. _cfg="$HOME/.codex/config.toml"
  626. awk '
  627. /^\\[hooks\\.state\\./ {
  628. if ($0 in seen) { skip = 1; next }
  629. seen[$0] = 1; skip = 0; print; next
  630. }
  631. /^\\[/ { skip = 0 }
  632. !skip { print }
  633. ' "$_cfg" > "$_cfg.vmtmp" && mv "$_cfg.vmtmp" "$_cfg" || rm -f "$_cfg.vmtmp"
  634. fi
  635. _probe_log="$(mktemp 2>/dev/null || echo "/tmp/.e2e-vm-probe-$$")"
  636. printf '%s' "\${_probe_b64}" | base64 -d | bash --norc --noprofile -s >"$_probe_log" 2>&1
  637. _st=$?
  638. _lines=$(wc -l < "$_probe_log" 2>/dev/null | tr -d ' ' || echo 0)
  639. _max=\${E2E_VERSION_MATRIX_PROBE_LOG_LINES:-40}
  640. if [ "$_lines" -gt "$_max" ]; then
  641. head -n "$_max" "$_probe_log"
  642. echo "[version-matrix] ... (probe output truncated at $_max/$_lines lines; E2E_VERSION_MATRIX_PROBE_LOG_LINES to override)"
  643. else
  644. cat "$_probe_log"
  645. fi
  646. rm -f "$_probe_log" 2>/dev/null || true
  647. if [ "\${_st}" -eq 0 ]; then
  648. echo "<<< [version-matrix] agent=\${_label} version=\${_v} probe exit 0 <<<"
  649. else
  650. echo "<<< [version-matrix] agent=\${_label} version=\${_v} probe exit \${_st} (non-fatal) <<<"
  651. fi
  652. npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
  653. done
  654. ${restoreLatest ? `echo "[version-matrix] restoring \${_pkg}@latest ..."
  655. npm install -g "\${_pkg}" >/tmp/.e2e-vm-restore.log 2>&1 || {
  656. echo "[version-matrix] WARN: restore latest failed (tail):"
  657. tail -10 /tmp/.e2e-vm-restore.log || true
  658. }` : '# restore latest disabled (E2E_VERSION_MATRIX_RESTORE_LATEST=0)'}
  659. }
  660. ${perAgentBlocks}
  661. echo ""
  662. echo "=== [version-matrix] all agents finished ==="
  663. echo "ℹ SLS 数据差异以运行时间段 + 上面的 '>>> agent=X version=Y >>>' 日志指示线人工对齐。"
  664. ${buildJsonlValidationSh(env)}
  665. exit 0
  666. `;
  667. }
  668. /**
  669. * 生成内嵌在远端 bash 中的 Node 校验器源码,校验 ~/.loongsuite-pilot/logs/output/*.jsonl
  670. * 是否满足 AgentActivityEntry (src/types/events.ts) 的必填字段 schema。
  671. * 独立导出便于单元测试。
  672. */
  673. export const JSONL_VALIDATOR_JS = `'use strict';
  674. const fs = require('fs');
  675. const path = require('path');
  676. const LOG_DIR = process.env._JV_LOG_DIR || (process.env.HOME + '/.loongsuite-pilot/logs/output');
  677. const SINCE_SECONDS = parseInt(process.env.E2E_JSONL_SINCE_SECONDS || '0', 10);
  678. const STRICT = (process.env.E2E_JSONL_STRICT || '0') === '1';
  679. const DEFAULT_AGENT_FILTER = 'claude-code,codex,qoder-cli,cursor-cli,qwen-code-cli,opencode';
  680. const _RAW_FILTER = process.env.E2E_JSONL_AGENT_FILTER;
  681. const _FILTER_SRC = (_RAW_FILTER === undefined || _RAW_FILTER === '') ? DEFAULT_AGENT_FILTER : _RAW_FILTER;
  682. const AGENT_FILTER = (_FILTER_SRC.trim().toLowerCase() === 'all' || _FILTER_SRC.trim() === '*')
  683. ? []
  684. : _FILTER_SRC.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
  685. const MAX_SAMPLES = parseInt(process.env.E2E_JSONL_MAX_SAMPLES || '3', 10);
  686. const COMMON_REQUIRED = [
  687. 'time_unix_nano', 'event.id', 'user.id', 'event.name',
  688. 'gen_ai.session.id', 'gen_ai.agent.type', 'gen_ai.provider.name',
  689. ];
  690. const EVENT_NAME_ENUM = new Set([
  691. 'gen_ai.agent.invoke', 'gen_ai.agent.result',
  692. 'llm.request', 'llm.response', 'tool.call', 'tool.result',
  693. 'gen_ai.model.request', 'gen_ai.model.response', 'gen_ai.tool.call', 'gen_ai.tool.result',
  694. 'gen_ai.agent.invoke', 'gen_ai.agent.result',
  695. 'skill.use', 'tool.approve', 'agent.input', 'other',
  696. ]);
  697. const CONDITIONAL_REQUIRED = {
  698. 'tool.call': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
  699. 'tool.result': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
  700. 'gen_ai.tool.call': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
  701. 'gen_ai.tool.result': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
  702. 'gen_ai.agent.invoke': ['gen_ai.agent.invocation.id'],
  703. 'gen_ai.agent.result': ['gen_ai.agent.invocation.id'],
  704. 'skill.use': ['gen_ai.skill.name'],
  705. };
  706. const COVERAGE_FIELDS = [
  707. ...COMMON_REQUIRED,
  708. 'trace_id', 'span_id', 'gen_ai.turn.id', 'gen_ai.step.id',
  709. 'gen_ai.agent.invocation.id', 'gen_ai.agent.parent.invocation.id',
  710. 'gen_ai.turn.start', 'gen_ai.turn.end',
  711. 'gen_ai.request.id', 'gen_ai.request.model',
  712. 'gen_ai.response.id', 'gen_ai.response.model', 'gen_ai.response.finish_reasons',
  713. 'gen_ai.input.messages_delta', 'gen_ai.output.messages',
  714. 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens', 'gen_ai.usage.total_tokens',
  715. 'gen_ai.tool.name', 'gen_ai.tool.call.id', 'gen_ai.tool.call.duration',
  716. 'tool.result.status', 'error.type',
  717. 'gen_ai.agent.id', 'gen_ai.agent.parent.id', 'gen_ai.agent.peer.id',
  718. 'gen_ai.agent.invocation.id', 'gen_ai.agent.parent.invocation.id',
  719. ];
  720. const NUMBER_FIELDS = [
  721. 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens',
  722. 'gen_ai.usage.cache_read.input_tokens', 'gen_ai.usage.cache_creation.input_tokens',
  723. 'gen_ai.usage.total_tokens', 'gen_ai.usage.input_cost',
  724. 'gen_ai.usage.output_cost', 'gen_ai.usage.cache_read.input_cost',
  725. 'gen_ai.usage.cache_creation.input_cost', 'gen_ai.usage.total_cost',
  726. ];
  727. const ARRAY_FIELDS = [
  728. 'gen_ai.response.finish_reasons', 'gen_ai.input.messages',
  729. 'gen_ai.input.messages_delta', 'gen_ai.output.messages',
  730. 'gen_ai.system_instructions', 'gen_ai.tool.definitions',
  731. ];
  732. const PLACEHOLDER_FIELDS = [
  733. 'gen_ai.provider.name', 'gen_ai.request.model', 'gen_ai.response.model',
  734. ];
  735. const PLACEHOLDERS = new Set(['unknown', 'n/a', 'na', 'none', 'null', 'undefined']);
  736. const TERMINAL_FINISH_REASONS = new Set(['stop', 'end_turn', 'cancelled', 'error']);
  737. function listJsonl(dir) {
  738. if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return [];
  739. return fs.readdirSync(dir)
  740. .filter(f => f.endsWith('.jsonl'))
  741. .map(f => path.join(dir, f));
  742. }
  743. function matchesAgentFilter(file) {
  744. if (!AGENT_FILTER.length) return true;
  745. const base = path.basename(file, '.jsonl').toLowerCase();
  746. return AGENT_FILTER.some(a => base.startsWith(a + '-') || base === a);
  747. }
  748. function withinWindow(entry) {
  749. if (!SINCE_SECONDS || SINCE_SECONDS <= 0) return true;
  750. const ns = entry && entry.time_unix_nano;
  751. if (!ns || typeof ns !== 'string') return true;
  752. const ms = Number(ns.slice(0, -6)) || 0;
  753. return (Date.now() - ms) <= SINCE_SECONDS * 1000;
  754. }
  755. function pct(num, total) {
  756. if (!total) return '0.0%';
  757. return ((num / total) * 100).toFixed(1) + '%';
  758. }
  759. function hasValue(value) {
  760. return value !== undefined && value !== null && value !== '';
  761. }
  762. function pairingEventName(value) {
  763. return ({
  764. 'gen_ai.model.request': 'llm.request',
  765. 'gen_ai.model.response': 'llm.response',
  766. 'gen_ai.tool.call': 'tool.call',
  767. 'gen_ai.tool.result': 'tool.result',
  768. })[value] || value;
  769. }
  770. function normalizedAgentType(value) {
  771. return String(value || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
  772. }
  773. function isTerminalTurnEntry(entry) {
  774. const agentType = normalizedAgentType(entry['gen_ai.agent.type']);
  775. if (entry['gen_ai.agent.scope'] === 'subagent' && agentType !== 'codex') return false;
  776. if (entry['gen_ai.turn.end'] === true) return true;
  777. // Codex status applies to every record; only the native marker closes a turn.
  778. if (agentType === 'codex') return false;
  779. if (agentType === 'openclaw') {
  780. return entry['agent.openclaw.hook'] === 'llm_output';
  781. }
  782. const reasons = entry['gen_ai.response.finish_reasons'];
  783. return Array.isArray(reasons) && reasons.some(reason => TERMINAL_FINISH_REASONS.has(reason));
  784. }
  785. function increment(target, key, amount = 1) {
  786. target[key] = (target[key] || 0) + amount;
  787. }
  788. function validTraceId(value) {
  789. return typeof value === 'string' && /^[0-9a-f]{32}$/i.test(value) && !/^0{32}$/.test(value);
  790. }
  791. function validSpanId(value) {
  792. return typeof value === 'string' && /^[0-9a-f]{16}$/i.test(value) && !/^0{16}$/.test(value);
  793. }
  794. const files = listJsonl(LOG_DIR).filter(matchesAgentFilter);
  795. if (!files.length) {
  796. console.log('[jsonl-validate] no .jsonl files in ' + LOG_DIR + (AGENT_FILTER.length ? ' (filter=' + AGENT_FILTER.join(',') + ')' : ''));
  797. console.log('[jsonl-validate] hint: run install-smoke + agent probe, or version-matrix with E2E_USER_ID first.');
  798. process.exit(STRICT ? 1 : 0);
  799. }
  800. let totalEntries = 0;
  801. let totalWindowed = 0;
  802. let hardIssueTotal = 0;
  803. const globalEventName = Object.create(null);
  804. const globalAgentType = Object.create(null);
  805. const globalProvider = Object.create(null);
  806. const issueCounts = Object.create(null);
  807. const issueSamples = [];
  808. const fileStats = new Map();
  809. const rows = [];
  810. const coverage = Object.create(null);
  811. function addIssue(file, category, fields = []) {
  812. hardIssueTotal++;
  813. increment(issueCounts, category);
  814. const stat = fileStats.get(file);
  815. if (stat) stat.issues++;
  816. if (issueSamples.length < MAX_SAMPLES) {
  817. issueSamples.push({ file, category, fields: [...new Set(fields)].sort() });
  818. }
  819. }
  820. function recordCoverage(eventName, entry) {
  821. const name = typeof eventName === 'string' && eventName ? eventName : '<missing>';
  822. if (!coverage[name]) coverage[name] = { count: 0, fields: Object.create(null) };
  823. coverage[name].count++;
  824. for (const field of COVERAGE_FIELDS) {
  825. if (hasValue(entry[field])) increment(coverage[name].fields, field);
  826. }
  827. }
  828. function validateTypes(file, entry) {
  829. const bad = [];
  830. if (hasValue(entry.time_unix_nano) && (typeof entry.time_unix_nano !== 'string' || !/^\\d+$/.test(entry.time_unix_nano))) bad.push('time_unix_nano');
  831. if (hasValue(entry.observed_time_unix_nano) && (typeof entry.observed_time_unix_nano !== 'string' || !/^\\d+$/.test(entry.observed_time_unix_nano))) bad.push('observed_time_unix_nano');
  832. for (const field of ['event.id', 'user.id', 'event.name', 'gen_ai.session.id', 'gen_ai.agent.type', 'gen_ai.provider.name']) {
  833. if (hasValue(entry[field]) && typeof entry[field] !== 'string') bad.push(field);
  834. }
  835. if (hasValue(entry.trace_id) && !validTraceId(entry.trace_id)) bad.push('trace_id');
  836. if (hasValue(entry.span_id) && !validSpanId(entry.span_id)) bad.push('span_id');
  837. if (hasValue(entry.parent_span_id) && !validSpanId(entry.parent_span_id)) bad.push('parent_span_id');
  838. for (const field of NUMBER_FIELDS) {
  839. if (hasValue(entry[field]) && (typeof entry[field] !== 'number' || !Number.isFinite(entry[field]) || entry[field] < 0)) bad.push(field);
  840. }
  841. if (hasValue(entry['gen_ai.tool.call.duration'])
  842. && (typeof entry['gen_ai.tool.call.duration'] !== 'number'
  843. || !Number.isFinite(entry['gen_ai.tool.call.duration'])
  844. || entry['gen_ai.tool.call.duration'] <= 0)) {
  845. bad.push('gen_ai.tool.call.duration');
  846. }
  847. for (const field of ARRAY_FIELDS) {
  848. if (hasValue(entry[field]) && !Array.isArray(entry[field])) bad.push(field);
  849. }
  850. for (const field of ['gen_ai.turn.start', 'gen_ai.turn.end']) {
  851. if (hasValue(entry[field]) && typeof entry[field] !== 'boolean') bad.push(field);
  852. }
  853. for (const field of ['gen_ai.tool.call.arguments', 'gen_ai.tool.call.result']) {
  854. const value = entry[field];
  855. if (typeof value === 'string' && /^[\\s]*[\\[{]/.test(value)) bad.push(field);
  856. }
  857. if (bad.length) addIssue(file, 'type_error', bad);
  858. }
  859. for (const file of files) {
  860. const base = path.basename(file);
  861. const stat = { entries: 0, windowed: 0, issues: 0, eventName: Object.create(null) };
  862. fileStats.set(base, stat);
  863. const raw = fs.readFileSync(file, 'utf8').split(/\\r?\\n/);
  864. for (const line of raw) {
  865. if (!line.trim()) continue;
  866. let entry;
  867. try {
  868. entry = JSON.parse(line);
  869. } catch (e) {
  870. stat.entries++;
  871. totalEntries++;
  872. addIssue(base, 'parse_error');
  873. continue;
  874. }
  875. stat.entries++;
  876. totalEntries++;
  877. if (!withinWindow(entry)) continue;
  878. stat.windowed++;
  879. totalWindowed++;
  880. const en = entry['event.name'];
  881. const conditional = CONDITIONAL_REQUIRED[en] || [];
  882. const miss = [...COMMON_REQUIRED, ...conditional].filter(k => !hasValue(entry[k]));
  883. const failedStatus = typeof entry['tool.result.status'] === 'string'
  884. && ['failure', 'failed', 'error'].includes(entry['tool.result.status'].toLowerCase());
  885. const finishReasons = Array.isArray(entry['gen_ai.response.finish_reasons'])
  886. ? entry['gen_ai.response.finish_reasons'] : [];
  887. if ((failedStatus || finishReasons.includes('error') || hasValue(entry['error.message']))
  888. && !hasValue(entry['error.type'])) {
  889. miss.push('error.type');
  890. }
  891. if (miss.length) {
  892. addIssue(base, 'missing_required', miss);
  893. }
  894. if (en !== undefined && !EVENT_NAME_ENUM.has(en)) addIssue(base, 'bad_event_name', ['event.name']);
  895. if (en) increment(stat.eventName, en);
  896. if (en) globalEventName[en] = (globalEventName[en] || 0) + 1;
  897. const at = entry['gen_ai.agent.type']; if (at) globalAgentType[at] = (globalAgentType[at] || 0) + 1;
  898. const pr = entry['gen_ai.provider.name']; if (pr) globalProvider[pr] = (globalProvider[pr] || 0) + 1;
  899. validateTypes(base, entry);
  900. recordCoverage(en, entry);
  901. rows.push({ file: base, entry });
  902. }
  903. }
  904. const seenEventIds = new Map();
  905. for (const row of rows) {
  906. const eventId = row.entry['event.id'];
  907. if (typeof eventId !== 'string' || !eventId) continue;
  908. if (seenEventIds.has(eventId)) addIssue(row.file, 'duplicate_event_id', ['event.id']);
  909. else seenEventIds.set(eventId, row);
  910. }
  911. const steps = new Map();
  912. for (const row of rows) {
  913. const entry = row.entry;
  914. const eventName = pairingEventName(entry['event.name']);
  915. if (eventName !== 'llm.request' && eventName !== 'llm.response') continue;
  916. if (!hasValue(entry['gen_ai.step.id'])) continue;
  917. const key = String(entry['gen_ai.session.id']) + '\\0' + String(entry['gen_ai.turn.id'] || '') + '\\0' + String(entry['gen_ai.step.id']);
  918. if (!steps.has(key)) steps.set(key, []);
  919. steps.get(key).push(row);
  920. }
  921. for (const stepRows of steps.values()) {
  922. const requests = stepRows.filter(row => pairingEventName(row.entry['event.name']) === 'llm.request');
  923. const responses = stepRows.filter(row => pairingEventName(row.entry['event.name']) === 'llm.response');
  924. if (requests.length !== 1 || responses.length !== 1) {
  925. addIssue(stepRows[0].file, 'model_pair_error', ['event.name', 'gen_ai.step.id']);
  926. }
  927. }
  928. const tools = new Map();
  929. for (const row of rows) {
  930. const entry = row.entry;
  931. const eventName = pairingEventName(entry['event.name']);
  932. if (eventName !== 'tool.call' && eventName !== 'tool.result') continue;
  933. const callId = entry['gen_ai.tool.call.id'];
  934. if (!hasValue(callId)) continue;
  935. const key = String(entry['gen_ai.session.id']) + '\\0' + String(callId);
  936. if (!tools.has(key)) tools.set(key, []);
  937. tools.get(key).push(row);
  938. }
  939. for (const toolRows of tools.values()) {
  940. const calls = toolRows.filter(row => pairingEventName(row.entry['event.name']) === 'tool.call');
  941. const results = toolRows.filter(row => pairingEventName(row.entry['event.name']) === 'tool.result');
  942. const names = new Set(toolRows.map(row => row.entry['gen_ai.tool.name']).filter(hasValue));
  943. if (calls.length !== 1 || results.length !== 1 || names.size !== 1) {
  944. addIssue(toolRows[0].file, 'tool_pair_error', ['event.name', 'gen_ai.tool.call.id', 'gen_ai.tool.name']);
  945. }
  946. }
  947. const turns = new Map();
  948. for (const row of rows) {
  949. const entry = row.entry;
  950. if (entry['event.name'] === 'gen_ai.agent.invoke' || entry['event.name'] === 'gen_ai.agent.result') continue;
  951. if (!hasValue(entry['gen_ai.turn.id'])) continue;
  952. if (entry['gen_ai.agent.scope'] === 'subagent'
  953. && normalizedAgentType(entry['gen_ai.agent.type']) !== 'codex') continue;
  954. if (entry['event.name'] === 'gen_ai.agent.invoke' || entry['event.name'] === 'gen_ai.agent.result') continue;
  955. const key = String(entry['gen_ai.agent.type']) + '\\0'
  956. + String(entry['gen_ai.session.id']) + '\\0' + String(entry['gen_ai.turn.id']);
  957. if (!turns.has(key)) turns.set(key, []);
  958. turns.get(key).push(row);
  959. }
  960. for (const turnRows of turns.values()) {
  961. const starts = turnRows.filter(row => row.entry['gen_ai.turn.start'] === true).length;
  962. const ends = turnRows.filter(row => row.entry['gen_ai.turn.end'] === true).length;
  963. const completed = turnRows.some(row => isTerminalTurnEntry(row.entry));
  964. if (starts !== 1 || ends !== (completed ? 1 : 0)) {
  965. addIssue(turnRows[0].file, 'turn_boundary_error', ['gen_ai.turn.start', 'gen_ai.turn.end']);
  966. }
  967. }
  968. let placeholderCount = 0;
  969. for (const row of rows) {
  970. for (const field of PLACEHOLDER_FIELDS) {
  971. const value = row.entry[field];
  972. if (typeof value === 'string' && PLACEHOLDERS.has(value.trim().toLowerCase())) placeholderCount++;
  973. }
  974. }
  975. if (SINCE_SECONDS > 0 && totalWindowed === 0) {
  976. addIssue(path.basename(files[0]), 'empty_window');
  977. }
  978. for (const [base, stat] of fileStats) {
  979. const tag = stat.issues ? 'FAIL' : 'OK';
  980. const summary = Object.entries(stat.eventName).map(([k, v]) => k + '=' + v).join(', ') || '<none>';
  981. console.log('[jsonl-validate] ' + tag + ' ' + base + ' entries=' + stat.entries + ' windowed=' + stat.windowed + ' issues=' + stat.issues + ' event.name{' + summary + '}');
  982. }
  983. console.log('');
  984. console.log('=== [jsonl-validate] summary ===');
  985. console.log(' files=' + files.length + ' entries=' + totalEntries + ' windowed=' + totalWindowed);
  986. for (const category of [
  987. 'missing_required', 'bad_event_name', 'parse_error', 'type_error',
  988. 'duplicate_event_id', 'model_pair_error', 'tool_pair_error', 'turn_boundary_error',
  989. 'empty_window',
  990. ]) {
  991. console.log(' ' + category + '=' + (issueCounts[category] || 0));
  992. }
  993. console.log(' suspicious_placeholders=' + placeholderCount + ' (reported, not a universal failure)');
  994. console.log(' event.name: ' + (Object.entries(globalEventName).map(([k, v]) => k + '=' + v).join(', ') || '<none>'));
  995. console.log(' gen_ai.agent.type: ' + (Object.entries(globalAgentType).map(([k, v]) => k + '=' + v).join(', ') || '<none>'));
  996. console.log(' gen_ai.provider.name: ' + (Object.entries(globalProvider).map(([k, v]) => k + '=' + v).join(', ') || '<none>'));
  997. console.log(' per-event field coverage:');
  998. for (const eventName of Object.keys(coverage).sort()) {
  999. const eventCoverage = coverage[eventName];
  1000. console.log(' ' + eventName + ' count=' + eventCoverage.count);
  1001. for (const field of COVERAGE_FIELDS) {
  1002. const count = eventCoverage.fields[field] || 0;
  1003. console.log(' ' + field + '=' + count + ' (' + pct(count, eventCoverage.count) + ')');
  1004. }
  1005. }
  1006. if (issueSamples.length) {
  1007. console.log(' issue samples (field names only, up to ' + MAX_SAMPLES + '):');
  1008. for (const sample of issueSamples) {
  1009. console.log(' - file=' + sample.file + ' category=' + sample.category + ' fields=[' + sample.fields.join(',') + ']');
  1010. }
  1011. }
  1012. if (hardIssueTotal > 0 && STRICT) {
  1013. console.error('[jsonl-validate] STRICT: failures detected → exit 1');
  1014. process.exit(1);
  1015. }
  1016. process.exit(0);
  1017. `;
  1018. /**
  1019. * 追加到 install-smoke (probe 之后) / version-matrix 末尾的 JSONL 字段校验 bash 片段。
  1020. * 校验 ~/.loongsuite-pilot/logs/output/*.jsonl 是否满足 AgentActivityEntry schema。
  1021. * 环境变量:
  1022. * E2E_JSONL_VALIDATE=0 禁用
  1023. * E2E_JSONL_STRICT=1 schema、类型、唯一性或关联错误时 exit 1
  1024. * E2E_JSONL_SINCE_SECONDS=600 仅统计最近 N 秒的条目
  1025. * E2E_JSONL_AGENT_FILTER=claude-code,codex,qoder-cli,cursor-cli,qwen-code-cli,opencode 仅校验 agent 前缀匹配的文件(默认);设为 all 或 * 关闭过滤
  1026. * E2E_JSONL_LOG_DIR=/path 覆盖默认 ~/.loongsuite-pilot/logs/output
  1027. * @param {NodeJS.ProcessEnv} env
  1028. * @returns {string}
  1029. */
  1030. export function buildJsonlValidationSh(env = process.env) {
  1031. if ((env?.E2E_JSONL_VALIDATE ?? '1').toString().trim() === '0') return '';
  1032. const b64 = Buffer.from(JSONL_VALIDATOR_JS, 'utf8').toString('base64');
  1033. return `
  1034. # === [jsonl-validate] AgentActivityEntry schema check (src/types/events.ts) ===
  1035. if ! command -v node >/dev/null 2>&1; then
  1036. echo "[jsonl-validate] WARN: node not on PATH — skipping schema check"
  1037. else
  1038. export _JV_LOG_DIR="\${E2E_JSONL_LOG_DIR:-$HOME/.loongsuite-pilot/logs/output}"
  1039. if [ ! -d "$_JV_LOG_DIR" ]; then
  1040. echo "[jsonl-validate] WARN: log dir not found: $_JV_LOG_DIR (pilot may not have flushed yet)"
  1041. else
  1042. echo ""
  1043. echo "=== [jsonl-validate] scanning $_JV_LOG_DIR ==="
  1044. printf '%s' '${b64}' | base64 -d | node -
  1045. _jv_st=$?
  1046. if [ "$_jv_st" -ne 0 ]; then
  1047. if [ "\${E2E_JSONL_STRICT:-0}" = "1" ]; then
  1048. echo "[jsonl-validate] STRICT mode: validation failed (exit $_jv_st)"
  1049. exit $_jv_st
  1050. else
  1051. echo "[jsonl-validate] validation returned non-zero ($_jv_st) — set E2E_JSONL_STRICT=1 to fail the job"
  1052. fi
  1053. fi
  1054. fi
  1055. fi
  1056. `;
  1057. }
  1058. // ──────────────────────────────────────────────────────────
  1059. // File Collection E2E validation
  1060. // ──────────────────────────────────────────────────────────
  1061. /**
  1062. * Build a bash script that creates a file-collection config + test log files,
  1063. * waits for pilot to pick them up, and verifies the pipeline processed them.
  1064. */
  1065. export function buildFileCollectionValidationSh() {
  1066. return `
  1067. set -euo pipefail
  1068. echo ""
  1069. echo "=== [file-collection-e2e] File Collection Pipeline Validation ==="
  1070. # Step 0: Enable file collection in pilot config and restart
  1071. echo "[file-collection-e2e] Step 0: Enabling fileCollection in config.json..."
  1072. PILOT_CONFIG="$HOME/.loongsuite-pilot/config.json"
  1073. echo "[file-collection-e2e] stopping pilot before config update..."
  1074. loongsuite-pilot stop 2>/dev/null || true
  1075. sleep 2
  1076. if [ -f "$PILOT_CONFIG" ]; then
  1077. node -e "
  1078. const fs = require('fs');
  1079. const cfg = JSON.parse(fs.readFileSync(process.argv[1], 'utf8'));
  1080. cfg.fileCollection = { enabled: true };
  1081. fs.writeFileSync(process.argv[1], JSON.stringify(cfg, null, 2));
  1082. " "$PILOT_CONFIG"
  1083. else
  1084. echo '{"fileCollection":{"enabled":true}}' > "$PILOT_CONFIG"
  1085. fi
  1086. echo "[file-collection-e2e] config updated: $(node -e "const c=require('$PILOT_CONFIG');console.log(JSON.stringify(c.fileCollection))" 2>/dev/null)"
  1087. echo "[file-collection-e2e] starting pilot with fileCollection.enabled..."
  1088. loongsuite-pilot start 2>/dev/null || true
  1089. sleep 5
  1090. FC_CONFIG_DIR="$HOME/.loongsuite-pilot/configs/local"
  1091. FC_STATE_DIR="$HOME/.loongsuite-pilot/state/pipeline"
  1092. FC_LEGACY_STATE_DIR="$HOME/.loongsuite-pilot/state/file-collection"
  1093. FC_SERVICE_LOG_GLOB="$HOME/.loongsuite-pilot/logs/loongsuite-pilot-service.log*"
  1094. FC_TEST_LOG_DIR="$HOME/.loongsuite-pilot/e2e-test-logs"
  1095. FC_CONFIG_NAME="e2e-file-test"
  1096. fc_state_file() {
  1097. if [ -f "$FC_STATE_DIR/$FC_CONFIG_NAME.json" ]; then echo "$FC_STATE_DIR/$FC_CONFIG_NAME.json"; return; fi
  1098. if [ -f "$FC_LEGACY_STATE_DIR/$FC_CONFIG_NAME.json" ]; then echo "$FC_LEGACY_STATE_DIR/$FC_CONFIG_NAME.json"; return; fi
  1099. echo "$FC_STATE_DIR/$FC_CONFIG_NAME.json"
  1100. }
  1101. # Step 1: Create test log directory and write test data
  1102. echo "[file-collection-e2e] Step 1: Creating test log files..."
  1103. mkdir -p "$FC_TEST_LOG_DIR"
  1104. for i in $(seq 1 20); do
  1105. echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] e2e-test-line-$i key=value idx=$i" >> "$FC_TEST_LOG_DIR/app.log"
  1106. done
  1107. echo "[file-collection-e2e] wrote 20 lines to $FC_TEST_LOG_DIR/app.log"
  1108. # Step 2: Create file-collection config using real SLS endpoint from E2E env
  1109. echo "[file-collection-e2e] Step 2: Creating file-collection config..."
  1110. mkdir -p "$FC_CONFIG_DIR"
  1111. # Read SLS config from pilot's config.json (written by installer with real E2E_SLS_* values)
  1112. FC_SLS_ENDPOINT=$(node -e "try{const c=require('$HOME/.loongsuite-pilot/config.json');const e=c.sls?.endpoint||'';console.log(e.replace(/^https?:\\/\\//,''))}catch{console.log('cn-hangzhou.log.aliyuncs.com')}" 2>/dev/null)
  1113. FC_SLS_PROJECT=$(node -e "try{const c=require('$HOME/.loongsuite-pilot/config.json');console.log(c.sls?.project||'e2e-test-project')}catch{console.log('e2e-test-project')}" 2>/dev/null)
  1114. FC_SLS_LOGSTORE=$(node -e "try{const c=require('$HOME/.loongsuite-pilot/config.json');console.log(c.sls?.logstore||'e2e-test-logstore')}catch{console.log('e2e-test-logstore')}" 2>/dev/null)
  1115. echo "[file-collection-e2e] using SLS: endpoint=$FC_SLS_ENDPOINT project=$FC_SLS_PROJECT logstore=$FC_SLS_LOGSTORE"
  1116. node -e "
  1117. const config = {
  1118. configName: 'e2e-file-test',
  1119. inputs: [{
  1120. Type: 'input_file',
  1121. FilePaths: [process.argv[1]],
  1122. FileEncoding: 'utf8',
  1123. MaxDirSearchDepth: 0
  1124. }],
  1125. flushers: [{
  1126. Type: 'flusher_sls',
  1127. Endpoint: process.argv[2],
  1128. Project: process.argv[3],
  1129. Logstore: process.argv[4],
  1130. TelemetryType: 'logs'
  1131. }]
  1132. };
  1133. require('fs').writeFileSync(process.argv[5], JSON.stringify(config, null, 2));
  1134. " "$FC_TEST_LOG_DIR/*.log" "$FC_SLS_ENDPOINT" "$FC_SLS_PROJECT" "$FC_SLS_LOGSTORE" "$FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
  1135. echo "[file-collection-e2e] config written: $FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
  1136. cat "$FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
  1137. # Step 3: Wait for pilot to detect the config and process files
  1138. # FileCollectionManager rescans every 60s; we also trigger via fs.watch.
  1139. echo "[file-collection-e2e] Step 3: Waiting for pilot to process config (up to 90s)..."
  1140. TIMEOUT=90
  1141. ELAPSED=0
  1142. while [ $ELAPSED -lt $TIMEOUT ]; do
  1143. if [ -f "$(fc_state_file)" ]; then
  1144. STATE_SIZE=$(wc -c < "$(fc_state_file)" | tr -d ' ')
  1145. if [ "$STATE_SIZE" -gt 2 ]; then
  1146. echo "[file-collection-e2e] state file detected after \${ELAPSED}s (size=\${STATE_SIZE}B)"
  1147. break
  1148. fi
  1149. fi
  1150. sleep 3
  1151. ELAPSED=$((ELAPSED + 3))
  1152. done
  1153. # Step 4: Validate results
  1154. echo "[file-collection-e2e] Step 4: Validating results..."
  1155. FC_FAIL=0
  1156. # Check state file exists and is non-empty
  1157. if [ -f "$(fc_state_file)" ]; then
  1158. STATE_CONTENT=$(cat "$(fc_state_file)")
  1159. STATE_SIZE=$(echo -n "$STATE_CONTENT" | wc -c | tr -d ' ')
  1160. if [ "$STATE_SIZE" -gt 2 ]; then
  1161. echo "[file-collection-e2e] OK: state file exists and has content (\${STATE_SIZE}B)"
  1162. # Check that offset was advanced (file was read)
  1163. if echo "$STATE_CONTENT" | grep -q '"lastOffset"'; then
  1164. echo "[file-collection-e2e] OK: state contains lastOffset (file was read)"
  1165. else
  1166. echo "[file-collection-e2e] WARN: state exists but no lastOffset found"
  1167. fi
  1168. if echo "$STATE_CONTENT" | grep -q '"inode"'; then
  1169. echo "[file-collection-e2e] OK: state contains inode (rotation tracking active)"
  1170. fi
  1171. else
  1172. echo "[file-collection-e2e] FAIL: state file exists but is empty/trivial"
  1173. FC_FAIL=1
  1174. fi
  1175. else
  1176. echo "[file-collection-e2e] FAIL: state file not found at $(fc_state_file)"
  1177. echo "[file-collection-e2e] pilot service log (last 20 lines with FileCollection):"
  1178. grep -iE "FileCollection|file-collection|FilePipeline|FileTailer" $FC_SERVICE_LOG_GLOB 2>/dev/null | tail -20 || echo "(no file-collection log lines found)"
  1179. FC_FAIL=1
  1180. fi
  1181. # Check service log for file-collection activity
  1182. if grep -q "FileCollectionManager.*started" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
  1183. echo "[file-collection-e2e] OK: FileCollectionManager started in service log"
  1184. else
  1185. echo "[file-collection-e2e] WARN: FileCollectionManager start not found in service log"
  1186. fi
  1187. if grep -q "FilePipeline.*started" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
  1188. echo "[file-collection-e2e] OK: FilePipeline started in service log"
  1189. else
  1190. echo "[file-collection-e2e] WARN: FilePipeline start not found in service log"
  1191. fi
  1192. # Step 5: Test log rotation (write more data to verify incremental read)
  1193. echo ""
  1194. echo "[file-collection-e2e] Step 5: Testing incremental read..."
  1195. OFFSET_BEFORE=""
  1196. if [ -f "$(fc_state_file)" ]; then
  1197. OFFSET_BEFORE=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1198. fi
  1199. echo "[file-collection-e2e] offset before append: $OFFSET_BEFORE"
  1200. for i in $(seq 21 30); do
  1201. echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] e2e-incremental-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
  1202. done
  1203. echo "[file-collection-e2e] appended 10 more lines"
  1204. # Wait for next poll cycle
  1205. sleep 15
  1206. OFFSET_AFTER=""
  1207. if [ -f "$(fc_state_file)" ]; then
  1208. OFFSET_AFTER=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1209. fi
  1210. echo "[file-collection-e2e] offset after append: $OFFSET_AFTER"
  1211. if [ "$OFFSET_AFTER" -gt "$OFFSET_BEFORE" ] 2>/dev/null; then
  1212. echo "[file-collection-e2e] OK: offset advanced ($OFFSET_BEFORE -> $OFFSET_AFTER), incremental read works"
  1213. else
  1214. echo "[file-collection-e2e] WARN: offset did not advance (may need more time)"
  1215. fi
  1216. # ──────────────────────────────────────────────────────────
  1217. # Step 6: Rename rotation test
  1218. # ──────────────────────────────────────────────────────────
  1219. echo ""
  1220. echo "[file-collection-e2e] Step 6: Testing RENAME rotation..."
  1221. # 6a. Record current state (offset + inode) before rotation
  1222. INODE_BEFORE=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];const e=s[k]?.extra||{};console.log(e.inode||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1223. OFFSET_BEFORE=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1224. echo "[file-collection-e2e] before rename: inode=$INODE_BEFORE offset=$OFFSET_BEFORE"
  1225. # 6b. Append lines that haven't been collected yet (simulate unread tail)
  1226. for i in $(seq 1 5); do
  1227. echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] rename-pre-rotate-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
  1228. done
  1229. echo "[file-collection-e2e] appended 5 lines before rotation (these must be drained from old file)"
  1230. # 6c. Simulate rename rotation: mv app.log -> app.log.1, create new app.log
  1231. mv "$FC_TEST_LOG_DIR/app.log" "$FC_TEST_LOG_DIR/app.log.1"
  1232. for i in $(seq 1 5); do
  1233. echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] rename-post-rotate-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
  1234. done
  1235. echo "[file-collection-e2e] renamed app.log -> app.log.1, created new app.log with 5 lines"
  1236. # 6d. Wait for poll cycle to detect rotation and drain
  1237. sleep 15
  1238. INODE_AFTER=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];const e=s[k]?.extra||{};console.log(e.inode||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1239. OFFSET_AFTER=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1240. echo "[file-collection-e2e] after rename: inode=$INODE_AFTER offset=$OFFSET_AFTER"
  1241. if [ "$INODE_AFTER" != "$INODE_BEFORE" ] && [ "$INODE_AFTER" != "0" ]; then
  1242. echo "[file-collection-e2e] OK: inode changed ($INODE_BEFORE -> $INODE_AFTER), rename rotation detected"
  1243. else
  1244. echo "[file-collection-e2e] FAIL: inode did not change after rename rotation"
  1245. FC_FAIL=1
  1246. fi
  1247. if [ "$OFFSET_AFTER" -gt 0 ] 2>/dev/null; then
  1248. echo "[file-collection-e2e] OK: new file read (offset=$OFFSET_AFTER)"
  1249. else
  1250. echo "[file-collection-e2e] FAIL: new file not read after rename rotation"
  1251. FC_FAIL=1
  1252. fi
  1253. # 6e. Verify old file drain via service log
  1254. if grep -q "drained old file after rotation" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
  1255. echo "[file-collection-e2e] OK: old file drain logged (unread lines from app.log.1 collected)"
  1256. else
  1257. echo "[file-collection-e2e] WARN: old file drain not found in service log (may have been fully read before rotation)"
  1258. fi
  1259. # ──────────────────────────────────────────────────────────
  1260. # Step 7: Copytruncate rotation test
  1261. # ──────────────────────────────────────────────────────────
  1262. echo ""
  1263. echo "[file-collection-e2e] Step 7: Testing COPYTRUNCATE rotation..."
  1264. # 7a. Wait for current data to be collected
  1265. sleep 15
  1266. OFFSET_BEFORE_CT=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1267. INODE_BEFORE_CT=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];const e=s[k]?.extra||{};console.log(e.inode||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1268. echo "[file-collection-e2e] before copytruncate: inode=$INODE_BEFORE_CT offset=$OFFSET_BEFORE_CT"
  1269. # 7b. Simulate copytruncate: cp app.log -> app.log.2, truncate app.log, write new data
  1270. cp "$FC_TEST_LOG_DIR/app.log" "$FC_TEST_LOG_DIR/app.log.2"
  1271. : > "$FC_TEST_LOG_DIR/app.log"
  1272. for i in $(seq 1 5); do
  1273. echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] copytruncate-new-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
  1274. done
  1275. echo "[file-collection-e2e] copytruncate done: truncated app.log, wrote 5 new lines"
  1276. # 7c. Wait for poll cycle
  1277. sleep 15
  1278. INODE_AFTER_CT=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];const e=s[k]?.extra||{};console.log(e.inode||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1279. OFFSET_AFTER_CT=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1280. echo "[file-collection-e2e] after copytruncate: inode=$INODE_AFTER_CT offset=$OFFSET_AFTER_CT"
  1281. if [ "$INODE_AFTER_CT" = "$INODE_BEFORE_CT" ]; then
  1282. echo "[file-collection-e2e] OK: inode unchanged ($INODE_AFTER_CT), copytruncate correctly detected (same file)"
  1283. else
  1284. echo "[file-collection-e2e] WARN: inode changed unexpectedly ($INODE_BEFORE_CT -> $INODE_AFTER_CT)"
  1285. fi
  1286. if [ "$OFFSET_AFTER_CT" -lt "$OFFSET_BEFORE_CT" ] 2>/dev/null && [ "$OFFSET_AFTER_CT" -gt 0 ] 2>/dev/null; then
  1287. echo "[file-collection-e2e] OK: offset reset and advanced ($OFFSET_BEFORE_CT -> $OFFSET_AFTER_CT), truncated file re-read from start"
  1288. else
  1289. echo "[file-collection-e2e] FAIL: offset not properly reset after copytruncate (before=$OFFSET_BEFORE_CT after=$OFFSET_AFTER_CT)"
  1290. FC_FAIL=1
  1291. fi
  1292. # Verify truncation detection in service log
  1293. if grep -q "copytruncate rotation" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
  1294. echo "[file-collection-e2e] OK: copytruncate rotation detected in service log"
  1295. else
  1296. echo "[file-collection-e2e] WARN: copytruncate detection not found in service log"
  1297. fi
  1298. # 7d. Edge case: copytruncate where new data exceeds old offset (signature-based detection)
  1299. echo ""
  1300. echo "[file-collection-e2e] Step 7b: Testing copytruncate with new data exceeding old offset..."
  1301. sleep 15
  1302. OFFSET_BEFORE_SIG=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1303. echo "[file-collection-e2e] current offset: $OFFSET_BEFORE_SIG"
  1304. # Simulate: cp + truncate + write MORE data than old file size
  1305. cp "$FC_TEST_LOG_DIR/app.log" "$FC_TEST_LOG_DIR/app.log.3"
  1306. : > "$FC_TEST_LOG_DIR/app.log"
  1307. for i in $(seq 1 50); do
  1308. echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] copytruncate-overflow-line-$i padding-data-to-exceed-old-offset" >> "$FC_TEST_LOG_DIR/app.log"
  1309. done
  1310. NEW_SIZE=$(wc -c < "$FC_TEST_LOG_DIR/app.log" | tr -d ' ')
  1311. echo "[file-collection-e2e] truncated + wrote 50 lines ($NEW_SIZE bytes, old offset was $OFFSET_BEFORE_SIG)"
  1312. sleep 15
  1313. OFFSET_AFTER_SIG=$(node -e "try{const s=require('$(fc_state_file)');const k=Object.keys(s)[0];console.log(s[k]?.lastOffset||0)}catch{console.log(0)}" 2>/dev/null || echo "0")
  1314. echo "[file-collection-e2e] after signature-based copytruncate: offset=$OFFSET_AFTER_SIG"
  1315. if grep -q "signature changed.*copytruncate rotation.*content replaced" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
  1316. echo "[file-collection-e2e] OK: signature-based copytruncate detected (file head content changed)"
  1317. elif grep -q "copytruncate rotation.*size < offset" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
  1318. echo "[file-collection-e2e] OK: size-based copytruncate detected (fallback, new data didn't exceed old offset)"
  1319. else
  1320. echo "[file-collection-e2e] WARN: copytruncate detection not found for overflow case (may need more time)"
  1321. fi
  1322. # ──────────────────────────────────────────────────────────
  1323. # Step 8: Rotated file count check
  1324. # ──────────────────────────────────────────────────────────
  1325. echo ""
  1326. echo "[file-collection-e2e] Step 8: Rotated file handling summary..."
  1327. ROTATED_COUNT=$(ls "$FC_TEST_LOG_DIR"/app.log.* 2>/dev/null | wc -l | tr -d ' ')
  1328. echo "[file-collection-e2e] rotated files in directory: $ROTATED_COUNT (app.log.1, app.log.2, ...)"
  1329. echo "[file-collection-e2e] INFO: drain supports 1 immediate predecessor per rotation event (by inode lookup)"
  1330. echo "[file-collection-e2e] INFO: glob pattern *.log only matches app.log, rotated files (app.log.1) are not re-collected"
  1331. ls -la "$FC_TEST_LOG_DIR"/ 2>/dev/null
  1332. # ──────────────────────────────────────────────────────────
  1333. # Step 9: Verify data delivery status
  1334. # ──────────────────────────────────────────────────────────
  1335. echo ""
  1336. echo "[file-collection-e2e] Step 9: Verifying data delivery..."
  1337. FC_FAILED_LOG="$HOME/.loongsuite-pilot/logs/pipeline-failed/$FC_CONFIG_NAME.jsonl"
  1338. FC_LEGACY_FAILED_LOG="$HOME/.loongsuite-pilot/logs/file-collection-failed/$FC_CONFIG_NAME.jsonl"
  1339. if [ ! -f "$FC_FAILED_LOG" ] && [ -f "$FC_LEGACY_FAILED_LOG" ]; then
  1340. FC_FAILED_LOG="$FC_LEGACY_FAILED_LOG"
  1341. fi
  1342. if [ -f "$FC_FAILED_LOG" ]; then
  1343. FC_FAILED_LINES=$(wc -l < "$FC_FAILED_LOG" | tr -d ' ')
  1344. echo "[file-collection-e2e] WARN: failed-log has $FC_FAILED_LINES entries (some data failed to deliver to SLS)"
  1345. echo "[file-collection-e2e] failed-log sample:"
  1346. head -1 "$FC_FAILED_LOG" | cut -c1-200
  1347. else
  1348. echo "[file-collection-e2e] OK: no failed-log (all data delivered to SLS successfully)"
  1349. fi
  1350. # Cleanup
  1351. echo ""
  1352. echo "[file-collection-e2e] Cleaning up test config..."
  1353. rm -f "$FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
  1354. if [ "$FC_FAIL" -eq 0 ]; then
  1355. echo ""
  1356. echo "=== [file-collection-e2e] File Collection Validation PASSED ==="
  1357. else
  1358. echo ""
  1359. echo "=== [file-collection-e2e] File Collection Validation FAILED ==="
  1360. exit 1
  1361. fi
  1362. `;
  1363. }
  1364. // ──────────────────────────────────────────────────────────
  1365. // Helpers used by both run-l1.mjs and run-docker-e2e.mjs.
  1366. // Moved from run-docker-e2e.mjs so L1 can reuse without copy.
  1367. // ──────────────────────────────────────────────────────────
  1368. export function preflightScript() {
  1369. return `
  1370. set -euo pipefail
  1371. echo "=== uname ==="
  1372. uname -a || true
  1373. echo "=== node ==="
  1374. command -v node && node -v || echo "node missing"
  1375. echo "=== npm ==="
  1376. command -v npm && npm -v || echo "npm missing"
  1377. echo "=== agents ==="
  1378. for b in codex claude cursor cursor-agent agent qoder qodercli qwen opencode; do
  1379. if command -v "$b" >/dev/null 2>&1; then
  1380. echo "have $b: $("$b" --version 2>/dev/null || echo 'version unknown')"
  1381. else
  1382. echo "missing $b"
  1383. fi
  1384. done
  1385. echo "=== disk ==="
  1386. df -h . 2>/dev/null || true
  1387. echo "=== E2E_DOCKER_MODE ==="
  1388. echo "Running inside Docker container"
  1389. `;
  1390. }
  1391. export function localBuildInstallScript(userId, env) {
  1392. const id = (userId || '').replace(/'/g, `'\\''`);
  1393. const installerFlags = [`--user.id '${id}'`];
  1394. if (shouldPropagateSlsToRemoteInstall(env)) {
  1395. const rawEndpoint = env.E2E_SLS_ENDPOINT?.trim() || 'cn-hangzhou.log.aliyuncs.com';
  1396. const endpoint = /^https?:\/\//i.test(rawEndpoint) ? rawEndpoint : `https://${rawEndpoint}`;
  1397. installerFlags.push(`--sls-endpoint ${shellSingleQuoteBash(endpoint)}`);
  1398. installerFlags.push(`--sls-project ${shellSingleQuoteBash(env.E2E_SLS_PROJECT.trim())}`);
  1399. installerFlags.push(`--sls-logstore ${shellSingleQuoteBash(env.E2E_SLS_LOGSTORE.trim())}`);
  1400. if (env.E2E_SLS_ACCESS_KEY_ID?.trim() && env.E2E_SLS_ACCESS_KEY_SECRET?.trim()) {
  1401. installerFlags.push(`--sls-ak-id ${shellSingleQuoteBash(env.E2E_SLS_ACCESS_KEY_ID.trim())}`);
  1402. installerFlags.push(`--sls-ak-secret ${shellSingleQuoteBash(env.E2E_SLS_ACCESS_KEY_SECRET.trim())}`);
  1403. }
  1404. }
  1405. const extraFlags = (env.E2E_INSTALLER_EXTRA_FLAGS ?? '').trim();
  1406. if (extraFlags) {
  1407. installerFlags.push(extraFlags);
  1408. }
  1409. const flagsStr = installerFlags.join(' \\\n ');
  1410. return `
  1411. set -euo pipefail
  1412. INSTALLER=/opt/project/deploy/installer.sh
  1413. PACKAGE=/opt/project/loongsuite-pilot.tar.gz
  1414. echo "[installer-e2e] Verifying local package and installer..."
  1415. if [ ! -f "$PACKAGE" ]; then
  1416. echo "[installer-e2e] ERROR: $PACKAGE not found. Run 'deploy/package.sh' first."
  1417. exit 1
  1418. fi
  1419. if [ ! -f "$INSTALLER" ]; then
  1420. echo "[installer-e2e] ERROR: $INSTALLER not found."
  1421. exit 1
  1422. fi
  1423. echo "[installer-e2e] Running installer with local package..."
  1424. bash "$INSTALLER" install \\
  1425. --package-url "file://$PACKAGE" \\
  1426. ${flagsStr}
  1427. echo "[installer-e2e] Verifying installation..."
  1428. command -v loongsuite-pilot >/dev/null || {
  1429. echo "[installer-e2e] ERROR: loongsuite-pilot not on PATH after install"
  1430. export PATH="$HOME/.local/bin:$PATH"
  1431. command -v loongsuite-pilot >/dev/null || exit 1
  1432. }
  1433. echo "[installer-e2e] config.json (redacted):"
  1434. node - <<'NODE' 2>/dev/null || echo "(no config found or redaction failed)"
  1435. const fs = require('fs');
  1436. const os = require('os');
  1437. const path = require('path');
  1438. const p = path.join(os.homedir(), '.loongsuite-pilot', 'config.json');
  1439. const cfg = JSON.parse(fs.readFileSync(p, 'utf8'));
  1440. function redact(value, key = '') {
  1441. if (Array.isArray(value)) return value.map(v => redact(v));
  1442. if (value && typeof value === 'object') {
  1443. const out = {};
  1444. for (const [k, v] of Object.entries(value)) out[k] = redact(v, k);
  1445. return out;
  1446. }
  1447. if (typeof value === 'string' && /(secret|token|password|accessKey|apiKey|ak|sk)/i.test(key)) return '<redacted>';
  1448. return value;
  1449. }
  1450. console.log(JSON.stringify(redact(cfg), null, 2));
  1451. NODE
  1452. echo "[installer-e2e] service status:"
  1453. loongsuite-pilot status || true
  1454. echo "[installer-e2e] installer flow complete"
  1455. `;
  1456. }
  1457. /**
  1458. * Build a bash script that validates cli-probe.cjs detection results.
  1459. * Runs the probe independently and asserts expected agents are detected
  1460. * (cursor via ~/.cursor path, CLI agents via command lookup).
  1461. */
  1462. export function buildProbeDetectionValidationScript(requiredAgentsCsv = 'claude-code,codex,qoder,cursor,qwen-code-cli,opencode') {
  1463. const requiredAgents = requiredAgentsCsv.split(',').map(s => s.trim()).filter(Boolean).join(' ');
  1464. return `
  1465. set -euo pipefail
  1466. echo "[probe-validate] Running cli-probe.cjs detection validation..."
  1467. PROBE_CJS="$HOME/.loongsuite-pilot/versions/$(cat $HOME/.loongsuite-pilot/current)/dist/cli-probe.cjs"
  1468. if [ ! -f "$PROBE_CJS" ]; then
  1469. echo "[probe-validate] ERROR: cli-probe.cjs not found at $PROBE_CJS"
  1470. exit 1
  1471. fi
  1472. PROBE_OUTPUT=$(node "$PROBE_CJS" 2>/dev/null) || {
  1473. echo "[probe-validate] ERROR: cli-probe.cjs failed to run"
  1474. exit 1
  1475. }
  1476. echo "[probe-validate] probe output: $PROBE_OUTPUT"
  1477. FAIL=0
  1478. for AGENT_ID in ${requiredAgents}; do
  1479. DETECTED=$(node -e "
  1480. const r = JSON.parse(process.argv[1]);
  1481. const a = r.find(x => x.id === process.argv[2]);
  1482. if (!a) { console.log('missing'); process.exit(0); }
  1483. console.log(a.detected ? 'yes' : 'no');
  1484. " "$PROBE_OUTPUT" "$AGENT_ID")
  1485. if [ "$DETECTED" = "yes" ]; then
  1486. echo "[probe-validate] OK: $AGENT_ID detected"
  1487. elif [ "$DETECTED" = "missing" ]; then
  1488. echo "[probe-validate] SKIP: $AGENT_ID not in definitions"
  1489. else
  1490. echo "[probe-validate] FAIL: $AGENT_ID NOT detected"
  1491. FAIL=1
  1492. fi
  1493. done
  1494. if [ "$FAIL" -ne 0 ]; then
  1495. echo "[probe-validate] FAILED: some agents not detected"
  1496. exit 1
  1497. fi
  1498. echo "[probe-validate] ALL expected agents detected successfully"
  1499. `;
  1500. }
  1501. export function uninstallScript(installerUrl) {
  1502. const u = installerUrl.replace(/'/g, `'\\''`);
  1503. return `
  1504. set -euo pipefail
  1505. INSTALLER_URL='${u}'
  1506. curl -fsSL "$INSTALLER_URL" | bash -s -- uninstall --purge
  1507. echo "uninstall: script finished"
  1508. `;
  1509. }
  1510. /**
  1511. * Build a bash script that checks all required agents have produced non-empty JSONL files.
  1512. * @param {string} requiredAgentsCsv - comma-separated agent prefixes (e.g. "claude-code,codex,qoder")
  1513. */
  1514. export function buildJsonlAgentCoverageCheck(requiredAgentsCsv) {
  1515. const agents = requiredAgentsCsv.split(',').map(s => s.trim()).filter(Boolean);
  1516. const checks = agents.map(agent => [
  1517. `_found_${agent.replace(/[^a-zA-Z0-9]/g, '_')}=0`,
  1518. `for f in "$LOG_DIR"/${agent}-*.jsonl "$LOG_DIR"/${agent}.jsonl; do`,
  1519. ` if [ -f "$f" ] && [ -s "$f" ]; then`,
  1520. ` _found_${agent.replace(/[^a-zA-Z0-9]/g, '_')}=1`,
  1521. ` echo "[agent-coverage] OK: ${agent} -> $(basename "$f") ($(wc -l < "$f") lines)"`,
  1522. ` break`,
  1523. ` fi`,
  1524. `done`,
  1525. `if [ "$_found_${agent.replace(/[^a-zA-Z0-9]/g, '_')}" -eq 0 ]; then`,
  1526. ` echo "[agent-coverage] MISSING: ${agent} — no JSONL output found"`,
  1527. ` MISSING="$MISSING ${agent}"`,
  1528. `fi`,
  1529. ].join('\n')).join('\n\n');
  1530. return [
  1531. 'set -euo pipefail',
  1532. 'LOG_DIR="${E2E_JSONL_LOG_DIR:-$HOME/.loongsuite-pilot/logs/output}"',
  1533. 'MISSING=""',
  1534. '',
  1535. 'echo "[agent-coverage] checking: ' + agents.join(', ') + '"',
  1536. 'echo "[agent-coverage] log dir: $LOG_DIR"',
  1537. 'ls "$LOG_DIR"/*.jsonl 2>/dev/null || echo "[agent-coverage] (no jsonl files found)"',
  1538. '',
  1539. checks,
  1540. '',
  1541. 'if [ -n "$MISSING" ]; then',
  1542. ' echo ""',
  1543. ' echo "[agent-coverage] FAILED: missing agents:$MISSING"',
  1544. ' echo "[agent-coverage] All of: ' + agents.join(', ') + ' must produce JSONL data."',
  1545. ' exit 1',
  1546. 'fi',
  1547. 'echo "[agent-coverage] ALL required agents produced JSONL data."',
  1548. ].join('\n');
  1549. }
  1550. /**
  1551. * Build script that writes agent configs (codex config.toml, claude onboarding, proxy).
  1552. * Should run before `waitForPilotReady`: pilot polls discovery every 30s, so as long
  1553. * as configs land before the 180s readiness wait completes, pilot will pick them up
  1554. * within the wait window. (Runs after `loongsuite-pilot start` in install-smoke; the
  1555. * first poll may see no configs, but a subsequent poll will.)
  1556. */
  1557. export function buildAgentConfigSetupScript(env) {
  1558. let body = '';
  1559. body += buildRemoteCodexConfigSh(env);
  1560. body += buildRemoteClaudeOnboardingSkipSh(env);
  1561. body += buildRemoteClaudeProxyConfigSh(env);
  1562. return body;
  1563. }
  1564. function shouldEnsureAgentClis(env, useMatrixProbe) {
  1565. const v = env.E2E_ENSURE_AGENT_CLIS?.trim().toLowerCase();
  1566. if (v === '0' || v === 'false' || v === 'no') return false;
  1567. if (v === '1' || v === 'true' || v === 'yes') return true;
  1568. return useMatrixProbe;
  1569. }
  1570. export function buildAgentEnsureOnlyScript(env) {
  1571. const useMatrix = env.E2E_USE_MATRIX_PROBE?.trim() === '1';
  1572. if (!shouldEnsureAgentClis(env, useMatrix)) return '';
  1573. const matrix = loadAgentMatrix(env);
  1574. console.log('[e2e-docker] Ensuring agent-matrix CLIs');
  1575. return buildEnsureAgentClisScript(matrix, env);
  1576. }
  1577. /**
  1578. * Build the probe-only script (ensure CLIs + run probes).
  1579. * Agent configs must already be written and plugins deployed before this runs.
  1580. */
  1581. export function buildAgentProbeOnlyScript(env) {
  1582. const useMatrix = env.E2E_USE_MATRIX_PROBE?.trim() === '1';
  1583. const customProbe = env.E2E_AGENT_PROBE_CMD?.trim();
  1584. if (!useMatrix && !customProbe) return '';
  1585. const matrix = loadAgentMatrix(env);
  1586. const ensure = shouldEnsureAgentClis(env, useMatrix);
  1587. let body = '';
  1588. if (ensure) {
  1589. console.log('[e2e-docker] Ensuring agent-matrix CLIs');
  1590. body += buildEnsureAgentClisScript(matrix, env);
  1591. body += '\n';
  1592. }
  1593. if (useMatrix) {
  1594. body += buildMatrixProbeScript(matrix, env);
  1595. return body;
  1596. }
  1597. body += buildAgentProbeRemoteBody(customProbe);
  1598. return body;
  1599. }
  1600. export function buildProbeEnvInjections(env) {
  1601. const chunks = [buildRemoteSecretExportsSh(env)];
  1602. const tok = normalizeE2eQoderPersonalAccessToken(env.E2E_QODER_PERSONAL_ACCESS_TOKEN);
  1603. if (tok) {
  1604. console.log(
  1605. `[e2e-docker] Injecting QODER_PERSONAL_ACCESS_TOKEN (${tok.length} chars)`,
  1606. );
  1607. chunks.push(`export QODER_PERSONAL_ACCESS_TOKEN=${shellSingleQuoteBash(tok)}`);
  1608. }
  1609. const cursorKey = env.E2E_CURSOR_API_KEY?.trim();
  1610. if (cursorKey) {
  1611. console.log(`[e2e-docker] Injecting CURSOR_API_KEY (${cursorKey.length} chars)`);
  1612. chunks.push(`export CURSOR_API_KEY=${shellSingleQuoteBash(cursorKey)}`);
  1613. }
  1614. const joined = chunks.filter(Boolean).join('\n');
  1615. return joined ? `${joined}\n` : '';
  1616. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.