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.
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
Markdown
[](/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
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.
- ---
- name: loongsuite-pilot-ops
- description: loongsuite-pilot-ops
- ---
- # loongsuite-pilot-ops
- ## Overview
- loongsuite-pilot-ops
- ## Quick Start
- ```bash
- # TODO: Add quick start commands
- ```
- ## Usage
- 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.
- # LoongSuite Pilot
- 
- **Local telemetry collector for AI coding agents**
- [](https://github.com/alibaba/loongsuite-pilot/actions/workflows/ci.yml)
- [](https://github.com/alibaba/loongsuite-pilot/releases/latest)
- [](LICENSE)
- [](https://nodejs.org/)
- [](https://opentelemetry.io/)
- **English** | [简体中文](README.zh-CN.md)
- [Overview](#overview) | [Quick Start](#quick-start) | [Documentation](#documentation) | [Community](#community) | [Contributing](#contributing)
- ---
- ## Overview
- 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.
- <p align="center">
- <img src="docs/_assets/img/dashboard.png" alt="LoongSuite Pilot local dashboard" width="880">
- <br>
- <em>Built-in local dashboard — multi-agent token usage, sessions, requests, tools, models, providers, and repository activity at a glance.</em>
- </p>
- 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.
- Pilot is designed to answer practical questions:
- - Which agents are being used?
- - What model, session, turn, and tool activity happened?
- - How much token usage is available from each agent?
- - Where should the data be exported: local files, SLS, HTTP, or traces?
- - How should sensitive prompts, tool arguments, and secrets be controlled before export?
- ## Highlights
- | Capability | What Pilot Does |
- | ------------------------ | ---------------------------------------------------------------------------------- |
- | Agent discovery | Detects supported agents from local paths and commands. |
- | Collection deployment | Installs hooks or plugins and reads local logs, sessions, or data files. |
- | Unified event schema | Normalizes agent-native events into a shared GenAI schema. |
- | Multi-destination output | Exports to JSONL, Alibaba Cloud SLS, HTTP, and OTLP trace backends. |
- | Privacy controls | Supports secret masking before output. |
- | Local operations | Provides service status, restart, rollback, and a built-in local dashboard. |
- ## Supported Agents
- | Agent | Integration | Trace Export | Log Export | Token Usage | Conversation / Tool Calls |
- | ------------- | ------------------------- | ------------ | ---------- | ----------- | ------------------------- |
- | Claude Code | Hook | Yes | Yes | Yes | Yes |
- | Codex | Hook | Yes | Yes | Yes | Yes |
- | GitHub Copilot CLI | Native plugin + transcript / native OTel | Yes | Yes | Yes (native OTel) | Yes |
- | Cursor | Hook | Yes | Yes | Yes | Yes |
- | Cursor CLI | Shared Cursor hook | Yes | Yes | Yes | Yes |
- | DeepSeek Harness | YAML patch plugin + local JSONL polling | Yes | Yes | Yes | Yes |
- | Grok Build | Hook + local session logs | Yes | Yes | Yes | Yes |
- | Hermes Agent | Native directory plugin | Yes | Yes | Yes | Yes |
- | Kiro CLI | Hook / session polling | Yes | Yes | No | Yes |
- | MiMo Code | Plugin injection | Yes | Yes | Yes | Yes |
- | OpenClaw | Plugin injection | Yes | Yes | Yes | Yes |
- | OpenCode | Plugin injection | Yes | Yes | Yes | Yes |
- | Pi Coding Agent | Extension injection | Yes | Yes | Yes | Yes |
- | Qoder | Hook | Yes | Yes | Yes | Yes |
- | Qoder CN | Hook | Yes | Yes | Yes | Yes |
- | Qoder for JetBrains | Detection-only | Yes | Yes | Yes | Yes |
- | Qoder CLI | Hook / session polling | Yes | Yes | Yes | Yes |
- | Qoder Work | Hook / local data polling | Yes | Yes | Yes | Yes |
- | Qoder Work CN | Hook / local data polling | Yes | Yes | Yes | Yes |
- | Qwen Code CLI | Hook | Yes | Yes | Yes | Yes |
- | Qwen Work CN | Hook / local data polling | Yes | Yes | Yes | Yes |
- | Wukong | CLI API polling | Yes | Yes | Yes | Yes |
- | WorkBuddy | Hook wakeup + local transcript watch/poll fallback | Yes | Yes | Yes | Yes |
- | [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 |
- 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).
- 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).
- DeepSeek Harness (`dsh`) loads Pilot's observability plugin from its user-level
- `cordis.patch.yml`. The integration captures native LLM, reasoning, tool, token,
- and time-to-first-token events. See [Agent Configuration](docs/agents.md#deepseek-harness-collection-and-lifecycle)
- for activation, source-log, disable, and uninstall behavior.
- ### Documented Windows Agent Support
- 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:
- | Agent | Windows Integration | Trace Export | Log Export | Token Usage | Conversation / Tool Calls | Requirement |
- |-------|---------------------|--------------|------------|-------------|---------------------------|-------------|
- | Claude Code | Hook | Yes | Yes | Yes | Yes | — |
- | Cursor | Hook | Yes | Yes | Yes | Yes | — |
- | Qoder Work | Hook / local data source | Yes | Yes | No | Yes | User edition |
- | Qoder CLI | Hook | Yes | Yes | No | Yes | — |
- | Qoder IDE | Hook / local data source | Yes | Yes | Yes | Yes | Qoder 1.10.0 or later, User edition |
- | OpenCode | Plugin injection | Yes | Yes | Yes | Yes | — |
- | WorkBuddy | Hook wakeup + local transcript | Yes | Yes | Yes | Yes | WorkBuddy Desktop 5.3.5.0; Windows 11 installed-product E2E |
- 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.
- Agent definitions live in `agents.d/`. You can add new agents without changing the deployment framework; see [Agent Onboarding](docs/agent-onboarding.md).
- ## Quick Start
- Prerequisites:
- - 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.
- - `npm`
- - `curl` or `wget`
- - PowerShell 5.1 or later on Windows
- Install from the public package on Linux or macOS:
- ```bash
- 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:
- ```powershell
- $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:
- ```bash
- loongsuite-pilot status
- loongsuite-pilot info
- ```
- 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`.
- For installer options, uninstall commands, and source builds, see [Installation](docs/installation.md).
- ## Configure Pilot
- Configuration is loaded in this order: environment variables, then `~/.loongsuite-pilot/config.json`, then built-in defaults.
- Start with the guide that matches what you want to change:
- | Task | Guide |
- | ------------------------------------------------ | ------------------------------------------------ |
- | Choose agents | [Agent Configuration](docs/agents.md) |
- | Write local JSONL logs | [Local JSONL Output](docs/local-jsonl-output.md) |
- | Report logs to SLS | [SLS Output](docs/sls-output.md) |
- | Report OTLP traces | [Trace Output](docs/trace-output.md) |
- | POST events to HTTP | [HTTP Output](docs/http-output.md) |
- | Mask secrets before output | [Data Masking](docs/masking.md) |
- | See global config loading and retention settings | [Configuration Guide](docs/configuration.md) |
- ### Upstream Trace Linking (optional)
- 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).
- | Setting | Values | Default |
- | ------- | ------ | ------- |
- | `LOONGSUITE_PILOT_UPSTREAM_LINK` (env) · `upstreamLink.enabled` (config.json) | `true` / `1` to enable; unset, `false`, or `0` to disable | disabled |
- | `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 |
- | `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 |
- | `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 |
- | `LOONGSUITE_PILOT_UPSTREAM_LINK_TTL_MS` (env) · `upstreamLink.ttlMs` (config.json) | cleanup TTL in ms for `acp-correlate` files | `86400000` (24h) |
- 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):
- - **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.
- - **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.
- 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.
- 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.
- ## Output Data
- | Backend | Use Case |
- | ---------- | ----------------------------------------------------------------------- |
- | JSONL | Local backup and easy inspection. Disabled by default; enable explicitly. |
- | SLS | Alibaba Cloud Log Service reporting. Supports WebTracking, AK, and API Key modes. |
- | HTTP | POST batches to a custom endpoint. |
- | OTLP Trace | Export GenAI activity as OpenTelemetry traces. |
- 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.
- ## Operate Pilot
- Use the `loongsuite-pilot` command after installation:
- ```bash
- loongsuite-pilot start
- loongsuite-pilot stop
- loongsuite-pilot restart
- loongsuite-pilot status
- loongsuite-pilot info
- loongsuite-pilot token-usage
- loongsuite-pilot rollback
- ```
- The local dashboard is disabled by default. Run `loongsuite-pilot dashboard start`
- to enable it on port 8765, or `loongsuite-pilot dashboard start 9999` to choose a
- port. Run `loongsuite-pilot dashboard stop` to disable it. These commands restart
- a running collector; collection remains enabled. The page reads the collector-owned
- `logs/metrics-summary.json` file directly.
- On macOS, optionally run `loongsuite-pilot dashboard shortcut install` to create a
- Dashboard `.webloc` shortcut with a radar icon and add it to the Dock's files area.
- Normal installation and upgrades do not add shortcuts. It opens the configured
- URL in your default browser without starting or stopping Pilot. After changing
- the port, run the shortcut install command again. See [Dashboard shortcut](docs/installation.md#macos-dashboard-shortcut).
- macOS menu bar app:
- 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).
- 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.
- If you quit the menu bar app, reopen it without restarting collection:
- ```bash
- loongsuite-pilot menubar start
- ```
- 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.
- 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.
- <p align="center">
- <img src="docs/_assets/img/menubar.jpg" alt="LoongSuite Pilot macOS menu bar app" width="360">
- </p>
- 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.
- ## Documentation
- [User Manual](docs/README.md) - Complete guide to installing, configuring, operating, and extending Pilot
- [Installation Guide](docs/installation.md) - Install from package, verify service, uninstall, and run from source
- [Configuration Reference](docs/configuration.md) - Global config loading, runtime switches, retention, and links to output and privacy setup
- [Output Schema](docs/output-event-schema.md) - Normalized event names, fields, provider values, and finish reasons
- [Developer Guide](docs/agent-onboarding.md) - Add support for a new AI coding agent
- ## Development
- ```bash
- git clone https://github.com/alibaba/loongsuite-pilot.git
- cd loongsuite-pilot
- npm install
- npm run build
- node scripts/postinstall.js
- node dist/index.js
- ```
- For local development:
- ```bash
- npm install
- npm run build
- npm run typecheck
- npm test
- ```
- For packaging and service installation from a local build, see [Installation](docs/installation.md).
- ## Contributing
- Issues and pull requests are welcome. Before submitting a change, run the same core checks used by CI:
- ```bash
- npm ci
- npm run typecheck
- npm test
- npm run build
- ```
- 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).
- ## Community
- We are looking forward to your feedback and suggestions. Scan the QR code below to join the LoongSuite Pilot DingTalk group.
- | LoongSuite Pilot SIG |
- |----|
- | <img src="docs/_assets/img/loongsuite-pilot-sig-dingtalk.jpg" height="150"> |
- ## LoongSuite Ecosystem
- | Project | Role |
- | ------- | ---- |
- | [LoongCollector](https://github.com/alibaba/loongcollector) | High-performance collector for logs, metrics, traces, events, and profiles. |
- | [LoongSuite Java](https://github.com/alibaba/loongsuite-java) | Shared GenAI telemetry utilities for Java instrumentation. |
- | [LoongSuite Go](https://github.com/alibaba/loongsuite-go) | Compile-time auto-instrumentation for Go applications. |
- | [LoongSuite Python](https://github.com/alibaba/loongsuite-python) | OpenTelemetry auto-instrumentation for Python and GenAI applications. |
- | [LoongSuite JS](https://github.com/alibaba/loongsuite-js) | OpenTelemetry integrations for JavaScript AI agents. |
- | [LoongSuite Pilot](https://github.com/alibaba/loongsuite-pilot) | Local telemetry collector for AI coding agents. |
- ## License
- Apache License 2.0 - see [LICENSE](LICENSE) for details.
deploy/installer-opensource.ps1 · Bundled script · 3,756 lines · 2 findings marked
- # installer-opensource.ps1 — Open-source installer for loongsuite-pilot (Windows)
- #
- # Install (first time):
- # 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
- # .\installer-opensource.ps1 install `
- # -SlsEndpoint "https://cn-hangzhou.log.aliyuncs.com" `
- # -SlsProject "my-project" `
- # -SlsLogstore "my-logstore" `
- # -SlsAkId "your-ak-id" `
- # -SlsAkSecret "your-ak-secret"
- # .\installer-opensource.ps1 install `
- # -SlsEndpoint "https://cn-hangzhou.log.aliyuncs.com" `
- # -SlsProject "my-project" `
- # -SlsLogstore "my-logstore" `
- # -SlsApiKey "your-api-key" `
- # -MultimodalMode all
- #
- # Install a specific version:
- # .\installer-opensource.ps1 install -Version 1.2.0
- #
- # Optional Dashboard port (default: 8765; preserve existing port on reinstall):
- # .\installer-opensource.ps1 install -DashboardPort 9000
- #
- # Upgrade (preserve config, auto-rollback on failure):
- # .\installer-opensource.ps1 upgrade
- #
- # Uninstall:
- # .\installer-opensource.ps1 uninstall
- # .\installer-opensource.ps1 uninstall -Purge
- [CmdletBinding()]
- param(
- [Parameter(Position = 0)]
- [ValidateSet("install", "upgrade", "uninstall")]
- [string]$Command = "install",
- [string]$SlsEndpoint,
- [string]$SlsProject,
- [string]$SlsLogstore,
- [string]$SlsAkId,
- [string]$SlsAkSecret,
- [string]$SlsApiKey,
- [string]$PackageUrl,
- [string]$DataDir,
- [string]$DashboardPort,
- [string]$LogLevel,
- [Alias("user.id")]
- [string]$UserId,
- [string]$Lang,
- [string]$Version,
- [string[]]$ExcludeWorkspace,
- [string]$CollectLog,
- [string]$CollectTrace,
- [ValidateSet("true", "false")]
- [string]$EnableStatusBarApp,
- [string]$CmsLicenseKey,
- [string]$CmsEndpoint,
- [string]$CmsWorkspace,
- [string]$ServiceNamePrefix,
- [string]$Agents,
- [switch]$AllAgents,
- [AllowEmptyString()]
- [string]$MultimodalMode,
- [string]$MaskMode,
- [string]$MaskTypes,
- [string]$MaskReplacementMode,
- [string]$InterceptorMode,
- [string]$InterceptorTypes,
- [switch]$Purge,
- [switch]$PreferSystemNode
- )
- $ErrorActionPreference = "Stop"
- foreach ($excludedWorkspace in $ExcludeWorkspace) {
- if ($excludedWorkspace -notmatch '^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+)') {
- throw "-ExcludeWorkspace requires absolute local directories"
- }
- }
- # Wrap in try/catch: setting a static property on [Console] throws under Constrained
- # Language Mode (WDAC), and with $ErrorActionPreference=Stop that would abort the whole
- # script at load. Console encoding is cosmetic, so degrade silently.
- try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}
- # ============================================================
- # Constants
- # ============================================================
- $PACKAGE_NAME = "loongsuite-pilot"
- $DEFAULT_PILOT_DIR = Join-Path $env:USERPROFILE ".loongsuite-pilot"
- $CACHE_DIR = if ($env:LOONGSUITE_PILOT_CACHE_DIR) {
- $env:LOONGSUITE_PILOT_CACHE_DIR
- } else {
- $DEFAULT_PILOT_DIR
- }
- $PERMANENT_DIR = Join-Path $CACHE_DIR "package"
- $_OSS_BASE_URL = "https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot"
- # Managed Node.js runtime + prebuilt node_modules (downloaded from OSS at install time)
- if ($env:LOONGSUITE_PILOT_NODE_VERSION) { $script:NODE_VERSION = $env:LOONGSUITE_PILOT_NODE_VERSION } else { $script:NODE_VERSION = "22.22.2" }
- 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" }
- 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" }
- # ============================================================
- # Defaults
- # ============================================================
- if (-not $DataDir) {
- $DataDir = if ($env:LOONGSUITE_PILOT_DATA_DIR) {
- $env:LOONGSUITE_PILOT_DATA_DIR
- } else {
- $DEFAULT_PILOT_DIR
- }
- }
- $env:LOONGSUITE_PILOT_DATA_DIR = $DataDir
- $env:LOONGSUITE_PILOT_CACHE_DIR = $CACHE_DIR
- $env:AGENT_DATA_COLLECTION_CONFIG = Join-Path $DataDir "config.json"
- if (-not $PackageUrl -and $env:LOONGSUITE_PILOT_PACKAGE_URL) {
- $PackageUrl = $env:LOONGSUITE_PILOT_PACKAGE_URL
- }
- # ============================================================
- # Validate install options
- # ============================================================
- if ($PSBoundParameters.Keys -contains 'EnableStatusBarApp' -and $Command -ne 'install') {
- Write-Error "-EnableStatusBarApp is only supported with install"
- exit 1
- }
- if ($PSBoundParameters.Keys -contains 'DashboardPort') {
- if ($DashboardPort -notmatch '\A[0-9]{1,5}\z' -or [int]$DashboardPort -lt 1 -or [int]$DashboardPort -gt 65535) {
- Write-Error "-DashboardPort must be an integer between 1 and 65535"
- exit 1
- }
- }
- if ($MaskMode) {
- if ($MaskMode -notin @("all", "none", "custom")) {
- Write-Error "Unknown mask mode: $MaskMode (use 'all', 'custom', or 'none')"
- exit 1
- }
- }
- if ($MaskMode -eq "custom" -and -not $MaskTypes) {
- Write-Error "--MaskTypes is required when -MaskMode custom"
- exit 1
- }
- if ($MaskTypes -and $MaskMode -ne "custom") {
- Write-Error "-MaskTypes can only be used with -MaskMode custom"
- exit 1
- }
- if ($MaskReplacementMode -and $MaskReplacementMode -notin @("placeholder", "preview")) {
- Write-Error "Unknown mask replacement mode: $MaskReplacementMode (use 'placeholder' or 'preview')"
- exit 1
- }
- if ($InterceptorMode) {
- if ($InterceptorMode -notin @("all", "none", "custom")) {
- Write-Error "Unknown interceptor mode: $InterceptorMode (use 'all', 'custom', or 'none')"
- exit 1
- }
- }
- if ($InterceptorMode -eq "custom" -and -not $InterceptorTypes) {
- Write-Error "--InterceptorTypes is required when -InterceptorMode custom"
- exit 1
- }
- if ($InterceptorTypes -and $InterceptorMode -ne "custom") {
- Write-Error "-InterceptorTypes can only be used with -InterceptorMode custom"
- exit 1
- }
- if ($SlsApiKey -and ($SlsAkId -or $SlsAkSecret)) {
- Write-Error "-SlsApiKey cannot be used with -SlsAkId or -SlsAkSecret"
- exit 1
- }
- if ($PSBoundParameters.Keys -contains 'MultimodalMode' -and -not $MultimodalMode) {
- Write-Error "-MultimodalMode requires 'none', 'input', 'output', or 'all'"
- exit 1
- }
- $script:MultimodalMode = $MultimodalMode
- # Keep in sync with MULTIMODAL_SUPPORTED_AGENT_IDS.
- $script:MultimodalSupportedAgents = "codex,qoder"
- if ($MultimodalMode) {
- if ($MultimodalMode -notin @("none", "input", "output", "all")) {
- Write-Error "Unknown multimodal mode: $MultimodalMode (use 'none', 'input', 'output', or 'all')"
- exit 1
- }
- }
- if ($MultimodalMode -and $Command -ne "install") {
- Write-Error "-MultimodalMode is only supported with install (got $Command)"
- exit 1
- }
- if ($MultimodalMode -and $MultimodalMode -ne "none") {
- if ($SlsEndpoint -notmatch '\S' -or $SlsProject -notmatch '\S' -or $SlsLogstore -notmatch '\S' -or $SlsApiKey -notmatch '\S') {
- Write-Error "-MultimodalMode $MultimodalMode requires -SlsEndpoint, -SlsProject, -SlsLogstore, and -SlsApiKey"
- exit 1
- }
- }
- # ============================================================
- # Resolve package URL
- # ============================================================
- if (-not $PackageUrl) {
- if ($Version) {
- $PackageUrl = "$_OSS_BASE_URL/$Version/$PACKAGE_NAME.zip"
- } else {
- $PackageUrl = "$_OSS_BASE_URL/latest/$PACKAGE_NAME.zip"
- }
- }
- # ============================================================
- # Language detection
- # ============================================================
- function Detect-Lang {
- if ($Lang) { return $Lang }
- if ($env:LOONGSUITE_PILOT_LANG) { return $env:LOONGSUITE_PILOT_LANG }
- # $PSUICulture is an automatic variable (no .NET static call), so it works under
- # Constrained Language Mode where [CultureInfo]::CurrentUICulture would throw.
- if ($PSUICulture -match "zh") { return "zh" }
- return "en"
- }
- $LANG_MODE = Detect-Lang
- function Msg {
- param([string]$zh, [string]$en)
- if ($LANG_MODE -eq "zh") { Write-Host $zh } else { Write-Host $en }
- }
- function Test-CanPrompt {
- # Each .NET call below throws under Constrained Language Mode (WDAC); guard every one
- # and default to non-interactive (the safe degrade — irm|iex installs are non-interactive).
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 225 on GitHub
- try {
- $processArgs = [Environment]::GetCommandLineArgs()
- if ($processArgs -contains "-NonInteractive") { return $false }
- } catch {}
- try {
- if ([Console]::IsInputRedirected) { return $false }
- } catch {}
- try {
- return [Environment]::UserInteractive -and $null -ne $Host.UI.RawUI
- } catch { return $false }
- }
- # ============================================================
- # Node.js resolution
- # ============================================================
- # node:sqlite is unflagged from 22.13 and 23.4. A major check accepts Node 20
- # and 22.12, whose require('node:sqlite') throws, so install succeeds and
- # SQLite collection does not. The require is the check.
- # Native stderr under EAP=Stop becomes a terminating error and hides $LASTEXITCODE.
- function Test-NodeSupportsSqlite {
- param([string]$bin)
- if (-not $bin -or -not (Test-Path -LiteralPath $bin)) { return $false }
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $code = 1
- try {
- $sqliteProbe = & $bin -e "require('node:sqlite')" 2>&1
- $code = $LASTEXITCODE
- if ($null -eq $code) { $code = 1 }
- } catch {
- $code = 1
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- return ($code -eq 0)
- }
- function Test-NodeSuitable {
- param([string]$bin)
- return (Test-NodeSupportsSqlite $bin)
- }
- function Resolve-Node {
- $candidates = @()
- # Existing installations pin the exact Node binary used for deployment.
- #
- # The pin file holds one absolute path to node.exe, and for a managed runtime that
- # path sits under the data dir -- i.e. under %USERPROFILE%, which can be non-ASCII.
- # 5.1 defaults both Get-Content and Set-Content to the ANSI codepage, so an
- # unqualified write stored "C:\Users\??.HOST\..." and every reader then failed
- # Test-NodeSuitable and silently fell back to whatever node.exe the candidate search
- # found first -- on a shared machine that was another account's nvm install.
- # -Encoding UTF8 always emits a BOM on 5.1 (there is no utf8NoBOM), and U+FEFF is not
- # whitespace, so .Trim() alone leaves it in the path: strip it explicitly first.
- foreach ($pinFile in @(
- (Join-Path $DataDir "node-bin"),
- (Join-Path $CACHE_DIR "node-bin")
- )) {
- if (-not (Test-Path -LiteralPath $pinFile)) { continue }
- $pinned = ([string](Get-Content -LiteralPath $pinFile -Raw -Encoding UTF8 -ErrorAction SilentlyContinue)).Trim([char]0xFEFF).Trim()
- if ($pinned) { $candidates += $pinned }
- }
- # nvm-windows. Both probes below must be non-fatal. NVM_HOME is often a *machine*
- # level variable pointing into another account's profile
- # (C:\Users\Administrator\AppData\Local\nvm was measured), and that directory's DACL
- # grants nothing to the current user: a bare Test-Path raises a PermissionDenied
- # UnauthorizedAccessException record, which the file header's
- # $ErrorActionPreference = "Stop" promotes to a terminating error. Resolve-Node is
- # called from uninstall before any cleanup runs, so one unreadable third-party node
- # manager aborted the entire uninstall and left config.json -- credentials included --
- # on disk even with -Purge. The Get-ChildItem calls were already guarded; these two
- # were not. -LiteralPath as well, because a version manager path may contain [ or ].
- $nvmHome = $env:NVM_HOME
- if ($nvmHome -and (Test-Path -LiteralPath $nvmHome -ErrorAction SilentlyContinue)) {
- $nvmDirs = Get-ChildItem $nvmHome -Directory -ErrorAction SilentlyContinue |
- Sort-Object Name -Descending
- foreach ($d in $nvmDirs) {
- $candidates += Join-Path $d.FullName "node.exe"
- }
- }
- # fnm -- same unreadable-directory hazard as the nvm branch above.
- $fnmDir = Join-Path $env:USERPROFILE ".fnm\node-versions"
- if (Test-Path -LiteralPath $fnmDir -ErrorAction SilentlyContinue) {
- $fnmDirs = Get-ChildItem $fnmDir -Directory -ErrorAction SilentlyContinue |
- Sort-Object Name -Descending
- foreach ($d in $fnmDirs) {
- $candidates += Join-Path $d.FullName "installation\node.exe"
- }
- }
- # Volta
- $voltaNode = Join-Path $env:USERPROFILE ".volta\bin\node.exe"
- $candidates += $voltaNode
- # Common install paths
- $candidates += "C:\Program Files\nodejs\node.exe"
- $candidates += "C:\Program Files (x86)\nodejs\node.exe"
- # PATH lookup
- $pathNode = Get-Command node -ErrorAction SilentlyContinue
- if ($pathNode) { $candidates += $pathNode.Source }
- foreach ($c in $candidates) {
- if (Test-NodeSuitable $c) {
- return $c
- }
- }
- return $null
- }
- # >>> managed-node-runtime >>>
- # Managed Node.js runtime + prebuilt node_modules, downloaded from OSS.
- function Get-ManagedNodePlatform {
- $archRaw = $env:PROCESSOR_ARCHITEW6432
- if (-not $archRaw) { $archRaw = $env:PROCESSOR_ARCHITECTURE }
- switch ($archRaw) {
- "AMD64" { return [pscustomobject]@{ Os = "win"; Arch = "x64" } }
- "ARM64" {
- Msg " ⚠️ 托管 Node.js 无 win-arm64 产物,回退系统 node + npm install" `
- " ⚠️ No win-arm64 managed Node.js artifact, falling back to system node + npm install"
- return $null
- }
- default {
- Msg " ⚠️ 托管 Node.js 不支持架构 $archRaw,回退系统 node + npm install" `
- " ⚠️ Managed Node.js does not support arch $archRaw, falling back to system node + npm install"
- return $null
- }
- }
- }
- # >>> pilot-short-path >>>
- # 8.3 short paths: why every delete and move below goes through a helper.
- #
- # Windows hands out %TEMP% in 8.3 short form whenever the profile name does not fit 8.3,
- # which a dot in an account name is often enough to do: C:\Users\zhang.wang becomes
- # C:\Users\ZHANG~1.WAN, the four characters after the dot being one too many for an 8.3
- # extension. %USERPROFILE% stays long, so a single install sees both forms. Reading such a
- # path works everywhere (Test-Path, Get-Item, Get-ChildItem, Get-Content, Set-Content,
- # Add-Content, New-Item, Out-File and Copy-Item all resolve it, and so does a Move-Item
- # destination), but Remove-Item, Move-Item, Rename-Item, Set-Location and Push-Location
- # fail with
- #
- # An object at the specified path C:\Users\ZHANG~1.WAN does not exist.
- #
- # naming the prefix their walk broke on rather than the path that was passed in.
- #
- # It is one guard in FileSystemProvider.NormalizeThePath, which is what the .NET stack
- # trace on the PSArgumentException names. That walk accumulates currentPath in the form you
- # typed it and, for each segment, compares the resolved item against it:
- #
- # if (fsinfo.FullName.Length < currentPath.Length)
- # throw NewArgumentException("path", ItemDoesNotExist, currentPath);
- # if (fsinfo.Name.Length >= childName.Length)
- # childName = fsinfo.Name; // "Expand the short file name"
- #
- # The guard is aimed at a child name of two or more dots, which .NET resolves to the parent
- # and so hands back shorter. An 8.3 name longer than the name it stands for is the other way
- # to make resolved shorter than typed, and the guard cannot tell the two apart -- note that
- # the very next line expands a short name only when doing so would not shorten it.
- #
- # So the trigger is not "a segment is in 8.3 form". Measured on 5.1.26100 over 13 profile
- # names and 7 nesting cases, it is a length comparison on every prefix:
- #
- # zhang.wang -> ZHANG~1.WAN 11 > 10 throws
- # abcd.wang -> ABCD~1.WAN 10 > 9 throws
- # ab.wang -> ABxxxx~1.WAN 12 > 7 throws (<=2 chars of base get a hash)
- # wang.zhang -> WANG~1.ZHA 10 = 10 works
- # zhangsan.wang -> ZHANGS~1.WAN 12 < 13 works
- # zhang.san -> no short name at all works
- #
- # It takes a short base with an over-long extension, which is why it looks rare in the
- # field. Depth is not irrelevant either: the first prefix whose typed length exceeds its
- # resolved length is the one that throws, so an earlier segment resolving much longer masks
- # a later offender (VERYLO~1\ZHANG~1.WAN is fine) while those same two segments in the other
- # order still throw (ZHANG~1.WAN\VERYLO~1 breaks on the first one). -LiteralPath behaves
- # identically to -Path, so quoting is not the fix, and neither is Convert-Path or
- # Resolve-Path -- both hand the short form straight back. Get-Item .FullName expands it.
- function Get-PilotLongPath {
- param([string]$Path)
- if (-not $Path) { return $Path }
- try {
- $item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
- if ($item.FullName) { return $item.FullName }
- } catch {
- # Not there, or not there yet -- a Move-Item destination is the common case. Only
- # an existing directory can carry a short name, so expanding the parent is enough.
- try {
- $parent = Split-Path -Parent $Path
- $leaf = Split-Path -Leaf $Path
- if ($parent -and $leaf) {
- $parentItem = Get-Item -LiteralPath $parent -Force -ErrorAction Stop
- if ($parentItem.FullName) { return (Join-Path $parentItem.FullName $leaf) }
- }
- } catch {}
- }
- return $Path
- }
- # Best-effort delete, for cleanup only. Every caller is a catch or a finally, where an
- # exception is not merely unhelpful but destructive, so this has to be incapable of
- # raising one: -ErrorAction SilentlyContinue covers the ordinary non-terminating half (a
- # file a virus scanner still holds open) and the catch covers everything else, the
- # binding failure above included. Deliberately returns nothing -- a caller that needs to
- # know whether the path is gone asks Test-Path.
- function Remove-PilotPathQuietly {
- param([string]$Path)
- if (-not $Path) { return }
- try {
- Remove-Item -LiteralPath (Get-PilotLongPath $Path) -Recurse -Force -ErrorAction SilentlyContinue
- } catch {}
- }
- # <<< pilot-short-path <<<
- # >>> pilot-ascii-temp >>>
- # Temp root guaranteed to be ASCII, for the two tar.exe staging dirs only.
- #
- # PowerShell hands native command arguments to CreateProcessW as UTF-16, but bsdtar
- # (%SystemRoot%\System32\tar.exe) enters through the ANSI CRT and converts them back
- # through the machine's ANSI codepage, so on an en-US box every character that page
- # cannot represent reaches tar as a literal "?": with $env:TEMP under a non-ASCII
- # %USERPROFILE% (e.g. C:\Users\<CJK name>\AppData\Local\Temp) both -f and -C pointed at
- # paths that do not exist and extraction failed with "Failed to open ...", which is what
- # stalled the install right after the download. Measured on that box: neither
- # [Console]::OutputEncoding = UTF8 nor `chcp 65001` changes it (they affect stdio
- # decoding, not argv conversion), and the 8.3 short name works but only where 8dot3
- # creation is still enabled, so it cannot be relied on.
- #
- # Callers keep the archive and the extraction dir inside this root and only then
- # Move-Item the result into the real (possibly non-ASCII) destination -- Move-Item is
- # pure Win32 and Unicode-safe. This root can be machine-wide (%SystemRoot%\Temp), so it
- # is for downloaded archives only: never stage credentials or config here, use $DataDir.
- #
- # The base resolution repeats Get-PilotTempRoot's fallback chain instead of calling it,
- # so this block stays byte-identical across the installers -- installer-opensource.ps1
- # has no Get-PilotTempRoot. Keep the two chains in sync. Environment variables only:
- # [System.IO.Path]::GetTempPath() is a static call on an off-list type and throws under
- # ConstrainedLanguage (WDAC / Device Guard).
- $script:PILOT_ASCII_TEMP_ROOT = ""
- function Get-PilotAsciiTempRoot {
- if ($script:PILOT_ASCII_TEMP_ROOT) { return $script:PILOT_ASCII_TEMP_ROOT }
- $root = "C:\Windows\Temp"
- if ($env:TEMP) { $root = $env:TEMP }
- elseif ($env:TMP) { $root = $env:TMP }
- elseif ($env:SystemRoot) { $root = (Join-Path $env:SystemRoot "Temp") }
- # 8.3 TEMP (ZHANG~1.WAN) is ASCII, so a charset check on $root used to
- # return it as-is and skip the long-name expand that Remove-Item /
- # Move-Item need. Expanding is still required -- but only keep the
- # expanded form when it is still ASCII. A CJK profile (short base +
- # over-long extension) hands out an ASCII 8.3 TEMP that Get-PilotLongPath
- # turns back into the long CJK path; tar.exe then fails with
- # "Failed to open 'C:\Users\??.HOST\...'". In that case keep $root as
- # the 8.3 form, try the machine-wide ASCII candidates below, and if
- # none of those are writable return the 8.3 so tar still has a path
- # it can open. Remove-Item / Move-Item callers wrap Get-PilotLongPath
- # themselves.
- $expanded = Get-PilotLongPath $root
- if ($expanded -notmatch '[^\x20-\x7E]') {
- $script:PILOT_ASCII_TEMP_ROOT = $expanded
- return $expanded
- }
- $candidates = @()
- if ($env:SystemRoot) { $candidates += (Join-Path $env:SystemRoot "Temp") }
- if ($env:SystemDrive) { $candidates += ($env:SystemDrive + "\loongsuite-pilot-tmp") }
- $candidates += "C:\Windows\Temp"
- foreach ($candidate in $candidates) {
- if ($candidate -match '[^\x20-\x7E]') { continue }
- # Probe by writing: %SystemRoot%\Temp grants Users write by default, but a
- # hardened host may not, and Test-Path cannot tell us that.
- try {
- if (-not (Test-Path -LiteralPath $candidate)) {
- New-Item -ItemType Directory -Path $candidate -Force -ErrorAction Stop | Out-Null
- }
- $probe = Join-Path $candidate ("pilot-w-" + $PID + ".tmp")
- Set-Content -LiteralPath $probe -Value "1" -ErrorAction Stop
- Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
- $script:PILOT_ASCII_TEMP_ROOT = $candidate
- return $candidate
- } catch {}
- }
- # Nothing writable: prefer the original ASCII 8.3 over the expanded CJK
- # long name. If $root itself is already CJK there is no ASCII option
- # left; return $expanded (same as $root) rather than failing here.
- if ($root -notmatch '[^\x20-\x7E]') {
- $script:PILOT_ASCII_TEMP_ROOT = $root
- return $root
- }
- $script:PILOT_ASCII_TEMP_ROOT = $expanded
- return $expanded
- }
- # Re-inherit the destination's ACL on a tree that was Move-Item'd out of the ASCII root.
- #
- # Move-Item is a rename, and a rename carries the source's ACEs along unchanged --
- # they keep their "inherited" flag but now describe a parent that no longer supplies
- # them, so the tree does not pick up the ACL of its new parent. Everything staged in
- # %SystemRoot%\Temp therefore lands in the profile with %SystemRoot%\Temp's permissions:
- # Users get (S,WD,AD,X), which is write and traverse but *not read*, and the read grant
- # comes from CREATOR OWNER. Run elevated -- an admin account, or "Run as administrator"
- # -- the owner of a new file is BUILTIN\Administrators, so CREATOR OWNER resolves to
- # Administrators and the moved tree ends up with no ACE for the user at all (measured:
- # node_modules\pino\package.json had exactly Administrators:(I)(F) and SYSTEM:(I)(F)).
- # The install then looks fine and the collector still cannot start, because the
- # scheduled task runs with a filtered token where Administrators is deny-only: node
- # cannot read the package.json it found and reports the confusing
- # ERR_MODULE_NOT_FOUND: Cannot find package 'pino' imported from ...\dist\index.js
- # in logs\last-startup-crash.json, while the same tree reads fine from an elevated
- # shell -- which is where anyone reproducing it by hand would look first.
- #
- # Copy-Item is not affected: a copy creates new files, which do inherit normally. Only
- # the Move-Item paths out of Get-PilotAsciiTempRoot need this.
- #
- # icacls, unlike tar.exe, handles a non-ASCII path correctly (verified against a CJK
- # profile: "Successfully processed 31950 files"), so the destination goes straight
- # through. Get-Acl / Set-Acl cannot express this: re-enabling inheritance needs
- # $acl.SetAccessRuleProtection(), a method call on an off-list type that CLM blocks.
- function Reset-PilotInheritedAcl {
- param([string]$Path)
- $script:PILOT_LAST_ACL_ERR = ""
- if (-not $Path -or -not (Test-Path -LiteralPath $Path)) {
- $script:PILOT_LAST_ACL_ERR = "path not found: $Path"
- return $false
- }
- # /T all descendants, /C keep going past a single failure, /Q stay quiet. Native
- # commands do not throw on a nonzero exit, so $LASTEXITCODE is the signal; the try
- # only covers icacls failing to launch, which $ErrorActionPreference = "Stop" would
- # otherwise turn into a terminating error.
- try {
- $aclOut = & icacls $Path /reset /T /C /Q 2>&1
- if ($LASTEXITCODE -eq 0) { return $true }
- $script:PILOT_LAST_ACL_ERR = "icacls (exit $LASTEXITCODE): $(($aclOut | Out-String).Trim())"
- return $false
- } catch {
- $script:PILOT_LAST_ACL_ERR = "icacls failed to run: $($_.Exception.Message)"
- return $false
- }
- }
- # <<< pilot-ascii-temp <<<
- # Extract a .tar.gz into $DestDir. Returns $true on success; on failure the last
- # error text is left in $script:PILOT_LAST_TAR_ERR for the caller to surface.
- #
- # Never invoke a bare `tar` on Windows. On a machine with Git for Windows
- # installed, PATH normally resolves `tar` to Git's bundled GNU tar (MSYS), and GNU
- # tar reads the colon in `-f C:\...\archive.tar.gz` as rsh host:path syntax: it
- # treats "C" as a remote host and dies with "Cannot connect to C: resolve failed"
- # (older builds hang instead). Windows' own bsdtar
- # (%SystemRoot%\System32\tar.exe, Win10 1803+ / Server 2019+) parses drive-letter
- # paths correctly, so try it first and only then fall back to PATH's tar with
- # --force-local, which is what makes GNU tar read the colon as part of a local
- # filename. Do not pass --force-local to bsdtar: it rejects the unknown flag and
- # exits immediately, which is why it is attached to the PATH candidate only.
- function Expand-PilotTarGz {
- param([string]$ArchivePath, [string]$DestDir)
- $script:PILOT_LAST_TAR_ERR = ""
- $exes = @()
- if ($env:SystemRoot) {
- # Inside a 32-bit PowerShell on 64-bit Windows, System32 is redirected to
- # SysWOW64, which ships no tar.exe; Sysnative reaches the real System32.
- foreach ($dir in @("System32", "Sysnative")) {
- $candidate = Join-Path $env:SystemRoot "$dir\tar.exe"
- if (Test-Path $candidate) { $exes += $candidate }
- }
- }
- # Everything from this index on is an unknown tar and needs --force-local.
- $nativeCount = $exes.Count
- # Require .Source: a `tar` that resolves to an alias or function has none, and
- # only an external binary can be invoked with an argument array. -notcontains
- # compares strings case-insensitively, so a PATH hit that is already the
- # System32 binary under different casing is not retried.
- $pathTar = Get-Command tar -ErrorAction SilentlyContinue
- if ($pathTar -and $pathTar.Source -and ($exes -notcontains $pathTar.Source)) {
- $exes += $pathTar.Source
- }
- if ($exes.Count -eq 0) {
- $script:PILOT_LAST_TAR_ERR = "tar not found (looked in %SystemRoot%\System32, Sysnative and PATH)"
- return $false
- }
- for ($i = 0; $i -lt $exes.Count; $i++) {
- $exe = $exes[$i]
- $tarArgs = @('-xzf', $ArchivePath, '-C', $DestDir)
- if ($i -ge $nativeCount) { $tarArgs = @('--force-local') + $tarArgs }
- # Naming the binary is the whole diagnostic: "Cannot connect to C: resolve
- # failed" only makes sense once you can see it came from Git's tar. Msg wraps
- # Write-Host, so this never lands in the return value.
- Msg " tar: $exe" " tar: $exe"
- # Native commands do not throw on a nonzero exit, so $LASTEXITCODE is the
- # only signal; the try only covers a binary that fails to launch at all,
- # which $ErrorActionPreference = "Stop" would otherwise make terminating.
- try {
- $tarOut = & $exe @tarArgs 2>&1
- if ($LASTEXITCODE -eq 0) { return $true }
- $script:PILOT_LAST_TAR_ERR = "$exe (exit $LASTEXITCODE): $(($tarOut | Out-String).Trim())"
- } catch {
- $script:PILOT_LAST_TAR_ERR = "$exe : $_"
- }
- Msg " ⚠️ tar 解包失败: $($script:PILOT_LAST_TAR_ERR)" `
- " ⚠️ tar failed: $($script:PILOT_LAST_TAR_ERR)"
- }
- return $false
- }
- function Invoke-ManagedNodeDownload {
- param([string]$Url, [string]$Dest)
- try {
- $prevProgress = $ProgressPreference
- $ProgressPreference = "SilentlyContinue"
- Invoke-WebRequest -Uri $Url -OutFile $Dest -UseBasicParsing -TimeoutSec 600
- $ProgressPreference = $prevProgress
- return $true
- } catch {
- return $false
- }
- }
- function Test-ManagedNodeChecksum {
- param([string]$Archive, [string]$ShasumsFile, [string]$Name)
- try {
- $expected = $null
- foreach ($line in (Get-Content $ShasumsFile)) {
- if ($line -match ("^([0-9a-fA-F]{64})\s+\*?" + [regex]::Escape($Name) + "\s*$")) {
- $expected = $Matches[1].ToLower()
- break
- }
- }
- if (-not $expected) {
- Msg " ❌ SHASUMS256.txt 中缺少 $Name 的校验和" " ❌ SHASUMS256.txt has no entry for $Name"
- return $false
- }
- $actual = (Get-FileHash -Algorithm SHA256 -Path $Archive).Hash.ToLower()
- if ($actual -ne $expected) {
- Msg " ❌ $Name sha256 校验失败 (expected $expected, got $actual)" " ❌ sha256 mismatch for $Name (expected $expected, got $actual)"
- return $false
- }
- return $true
- } catch {
- return $false
- }
- }
- function Resolve-ManagedNodeBin {
- param([string]$NodeDir)
- # Prefer the bin/ layout; official Node.js win zips put node.exe at the root.
- $binLayout = Join-Path $NodeDir "bin\node.exe"
- if (Test-Path $binLayout) { return $binLayout }
- $officialLayout = Join-Path $NodeDir "node.exe"
- if (Test-Path $officialLayout) { return $officialLayout }
- return $null
- }
- function Ensure-ManagedNode {
- $platform = Get-ManagedNodePlatform
- if (-not $platform) { return $null }
- $runtimeDir = Join-Path $DataDir "runtime"
- $archive = "node-v$($script:NODE_VERSION)-$($platform.Os)-$($platform.Arch).zip"
- $nodeDir = Join-Path $runtimeDir "node-v$($script:NODE_VERSION)-$($platform.Os)-$($platform.Arch)"
- $nodeBin = Resolve-ManagedNodeBin $nodeDir
- if ($nodeBin) {
- try {
- $v = (& $nodeBin --version 2>$null)
- if ($v -eq "v$($script:NODE_VERSION)") { return $nodeBin }
- } catch { }
- }
- $base = $script:NODE_DEPS_BASE.TrimEnd('/') + "/$($script:NODE_VERSION)"
- $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("pilot-managed-node-" + [guid]::NewGuid().ToString("N"))
- New-Item -ItemType Directory -Path $tmp -Force | Out-Null
- try {
- Msg "==> 下载托管 Node.js v$($script:NODE_VERSION) (win-x64)..." "==> Downloading managed Node.js v$($script:NODE_VERSION) (win-x64)..."
- $archivePath = Join-Path $tmp $archive
- $shasumsPath = Join-Path $tmp "SHASUMS256.txt"
- if (-not (Invoke-ManagedNodeDownload "$base/$archive" $archivePath)) { return $null }
- if (-not (Invoke-ManagedNodeDownload "$base/SHASUMS256.txt" $shasumsPath)) { return $null }
- if (-not (Test-ManagedNodeChecksum $archivePath $shasumsPath $archive)) { return $null }
- if (Test-Path $nodeDir) { Remove-Item -LiteralPath (Get-PilotLongPath $nodeDir) -Recurse -Force }
- if (-not (Test-Path $runtimeDir)) { New-Item -ItemType Directory -Path $runtimeDir -Force | Out-Null }
- Expand-Archive -Path $archivePath -DestinationPath $runtimeDir -Force
- $nodeBin = Resolve-ManagedNodeBin $nodeDir
- if (-not $nodeBin) {
- Msg " ❌ 解压产物中未找到 node.exe(bin\ 或根目录布局)" " ❌ No node.exe found in extracted archive (bin\ or root layout)"
- Remove-PilotPathQuietly $nodeDir
- return $null
- }
- return $nodeBin
- } catch {
- Remove-PilotPathQuietly $nodeDir
- return $null
- } finally {
- Remove-PilotPathQuietly $tmp
- }
- }
- function Ensure-NodeModules {
- param([string]$AppVersion = "latest")
- $platform = Get-ManagedNodePlatform
- if (-not $platform) { return $false }
- $modulesDir = Join-Path $script:PERMANENT_DIR "node_modules"
- $marker = Join-Path $modulesDir ".pilot-modules-version"
- $stamp = "$AppVersion $($platform.Os) $($platform.Arch)"
- if ((Test-Path $modulesDir) -and (Test-Path $marker)) {
- $existing = (Get-Content $marker -ErrorAction SilentlyContinue | Out-String).Trim()
- if ($existing -eq $stamp) { return $true }
- }
- $archive = "node-modules-$($platform.Os)-$($platform.Arch).tar.gz"
- $base = $script:NODE_MODULES_BASE.TrimEnd('/') + "/$AppVersion"
- # ASCII temp root: the archive is unpacked with tar.exe, which cannot see a
- # non-ASCII path (see Get-PilotAsciiTempRoot). Move-Item below lands it in the
- # real, possibly non-ASCII, install dir.
- $tmp = Join-Path (Get-PilotAsciiTempRoot) ("pilot-node-modules-" + [guid]::NewGuid().ToString("N"))
- New-Item -ItemType Directory -Path $tmp -Force | Out-Null
- try {
- Msg "==> 下载预编译 node_modules (win-x64, app v$AppVersion)..." "==> Downloading prebuilt node_modules (win-x64, app v$AppVersion)..."
- $archivePath = Join-Path $tmp $archive
- $shasumsPath = Join-Path $tmp "SHASUMS256.txt"
- if (-not (Invoke-ManagedNodeDownload "$base/$archive" $archivePath)) { return $false }
- if (-not (Invoke-ManagedNodeDownload "$base/SHASUMS256.txt" $shasumsPath)) { return $false }
- if (-not (Test-ManagedNodeChecksum $archivePath $shasumsPath $archive)) { return $false }
- $stage = Join-Path $tmp "stage"
- New-Item -ItemType Directory -Path $stage -Force | Out-Null
- # Expand-PilotTarGz already logged which tar ran and how it failed; name what
- # that cost so the "prebuilt node_modules unavailable, falling back to npm
- # install" notice below is not misread as "OSS has no artifact for this
- # version". A local tar conflict and a missing archive used to look identical.
- if (-not (Expand-PilotTarGz $archivePath $stage)) {
- Msg " ⚠️ 预编译 node_modules 解压失败" `
- " ⚠️ Failed to extract prebuilt node_modules"
- return $false
- }
- $stagedModules = Join-Path $stage "node_modules"
- if (-not (Test-Path $stagedModules)) {
- Msg " ⚠️ 预编译包中缺少 node_modules 目录" `
- " ⚠️ Extracted archive contains no node_modules directory"
- return $false
- }
- Set-Content -Path (Join-Path $stagedModules ".pilot-modules-version") -Value $stamp
- if (Test-Path $modulesDir) { Remove-Item -LiteralPath (Get-PilotLongPath $modulesDir) -Recurse -Force }
- # $stagedModules sits under the ASCII temp root, i.e. under whatever %TEMP%
- # gave us, and Move-Item cannot see an 8.3 segment either -- without this the
- # prebuilt tree silently lost every install on such a profile to npm install.
- Move-Item (Get-PilotLongPath $stagedModules) $modulesDir
- # The move brought the ASCII root's ACL with it, which can leave the tree
- # unreadable to the non-elevated scheduled task -- see Reset-PilotInheritedAcl.
- # If that cannot be repaired, throw the prebuilt tree away rather than deploy
- # dependencies the collector will not be able to read: returning $false falls
- # back to npm install, which creates node_modules in place and inherits normally.
- if (-not (Reset-PilotInheritedAcl $modulesDir)) {
- Msg " ⚠️ 预编译 node_modules 权限修复失败: $script:PILOT_LAST_ACL_ERR" `
- " ⚠️ Could not reset permissions on prebuilt node_modules: $script:PILOT_LAST_ACL_ERR"
- Remove-PilotPathQuietly $modulesDir
- return $false
- }
- return $true
- } catch {
- return $false
- } finally {
- Remove-PilotPathQuietly $tmp
- }
- }
- # <<< managed-node-runtime <<<
- # ============================================================
- # Check dependencies
- # ============================================================
- $script:NODE_BIN = ""
- $script:NPM_BIN = ""
- function Check-Deps {
- Msg "==> 检查依赖..." "==> Checking dependencies..."
- $script:NODE_BIN = ""
- if ($PreferSystemNode) {
- $script:NODE_BIN = Resolve-Node
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 系统 Node.js 不可用或无法加载 node:sqlite(需要 22.13+ 或 23.4+),改用托管运行时" `
- " ⚠️ System Node.js is missing or cannot load node:sqlite (need 22.13+ or 23.4+); using the managed runtime"
- $script:NODE_BIN = Ensure-ManagedNode
- }
- } else {
- $script:NODE_BIN = Ensure-ManagedNode
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 托管 Node.js 不可用(平台不支持或下载失败),回退系统 node" `
- " ⚠️ Managed Node.js unavailable (unsupported platform or download failed), falling back to system node"
- $script:NODE_BIN = Resolve-Node
- }
- }
- if (-not $script:NODE_BIN) {
- Msg "❌ 缺少可用的 Node.js:需要能加载 node:sqlite 的版本(22.13+ / 23.4+),或成功下载托管运行时" `
- "❌ No usable Node.js: node:sqlite must load (22.13+ / 23.4+), or the managed runtime must download"
- exit 1
- }
- if (-not (Test-NodeSupportsSqlite $script:NODE_BIN)) {
- $nodeVer = "unknown"
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- $verOut = & $script:NODE_BIN --version 2>&1
- $code = $LASTEXITCODE
- if ($code -eq 0 -and $verOut) { $nodeVer = "$verOut".Trim() }
- } catch {
- $nodeVer = "unknown"
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- Msg "❌ 当前 Node.js 无法加载 node:sqlite($nodeVer)。需要 22.13+ 或 23.4+(无需 --experimental-sqlite),或托管运行时。" `
- "❌ This Node.js cannot load node:sqlite ($nodeVer). Need 22.13+ or 23.4+ (unflagged), or the managed runtime."
- exit 1
- }
- # Pin node binary path. -Encoding UTF8 is required, not cosmetic: the path can sit
- # under a non-ASCII %USERPROFILE% and the 5.1 default (ANSI) would store "??" there,
- # see the note on Resolve-Node.
- if (-not (Test-Path $CACHE_DIR)) { New-Item -ItemType Directory -Path $CACHE_DIR -Force | Out-Null }
- Set-Content -LiteralPath (Join-Path $CACHE_DIR "node-bin") -Value $script:NODE_BIN -Encoding UTF8
- # Hook entrypoints can always derive DataDir from their deployed location,
- # while GUI agents do not necessarily inherit the installer's CacheDir.
- if (-not (Test-Path $DataDir)) { New-Item -ItemType Directory -Path $DataDir -Force | Out-Null }
- Set-Content -LiteralPath (Join-Path $DataDir "node-bin") -Value $script:NODE_BIN -Encoding UTF8
- # Derive npm
- $npmPath = Join-Path (Split-Path $script:NODE_BIN) "npm.cmd"
- if (Test-Path $npmPath) {
- $script:NPM_BIN = $npmPath
- } else {
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- if ($npmCmd) {
- $script:NPM_BIN = $npmCmd.Source
- } else {
- Msg "❌ 缺少依赖: npm,请先安装后重试" "❌ Missing dependency: npm — please install it first"
- exit 1
- }
- }
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- $nodeVer = & $script:NODE_BIN --version
- $npmVer = & $script:NPM_BIN --version
- $ErrorActionPreference = $prevEAP
- Msg " ✅ node $nodeVer npm $npmVer" " ✅ node $nodeVer npm $npmVer"
- Msg " node pinned: $($script:NODE_BIN)" " node pinned: $($script:NODE_BIN)"
- Write-Host ""
- }
- # ============================================================
- # Download and extract package
- # ============================================================
- $script:INSTALL_SRC = ""
- function Download-AndExtract {
- $tmpDir = Join-Path $env:TEMP "loongsuite-pilot-install-$(Get-Random)"
- New-Item -ItemType Directory -Path $tmpDir -Force | Out-Null
- $script:TMP_DIR = $tmpDir
- $archivePath = Join-Path $tmpDir "package.zip"
- Msg "==> 下载安装包: $PackageUrl" "==> Downloading: $PackageUrl"
- try {
- if (Test-Path -LiteralPath $PackageUrl) {
- Copy-Item -LiteralPath $PackageUrl -Destination $archivePath -Force
- } elseif ($PackageUrl -match '^file://') {
- # Strip the file:// scheme with string ops instead of casting to [Uri], which is
- # forbidden under Constrained Language Mode (WDAC). Handles file:///C:/x and
- # file://C:/x; forward slashes are normalized to backslashes.
- $localPackagePath = ($PackageUrl -replace '^file:/{2,3}', '') -replace '/', '\'
- Copy-Item -LiteralPath $localPackagePath -Destination $archivePath -Force
- } else {
- # Best-effort TLS1.2 bump; setting this static property throws under Constrained
- # Language Mode (WDAC), so swallow it (modern Windows defaults to TLS1.2 anyway).
- try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {}
- Invoke-WebRequest -Uri $PackageUrl -OutFile $archivePath -UseBasicParsing
- }
- } catch {
- Msg "❌ 下载失败: $_" "❌ Download failed: $_"
- exit 1
- }
- Msg " ✅ 下载完成" " ✅ Downloaded"
- Write-Host ""
- Msg "==> 解压安装包..." "==> Extracting..."
- try {
- Expand-Archive -Path $archivePath -DestinationPath $tmpDir -Force
- } catch {
- Msg "❌ 解压失败: $_" "❌ Extraction failed: $_"
- exit 1
- }
- $pkgDir = Join-Path $tmpDir $PACKAGE_NAME
- if (Test-Path $pkgDir) {
- $script:INSTALL_SRC = $pkgDir
- } elseif (Test-Path (Join-Path $tmpDir "package.json")) {
- $script:INSTALL_SRC = $tmpDir
- } else {
- $found = Get-ChildItem $tmpDir -Recurse -Depth 2 -Filter "package.json" -ErrorAction SilentlyContinue | Select-Object -First 1
- if ($found) {
- $script:INSTALL_SRC = $found.DirectoryName
- } else {
- Msg "❌ 解压后未找到 package.json,安装包结构异常" "❌ package.json not found — unexpected package structure"
- exit 1
- }
- }
- Msg " ✅ 解压完成" " ✅ Extracted"
- Write-Host ""
- }
- # ============================================================
- # Agent probe
- # ============================================================
- $script:PROBE_RESULT = "[]"
- function Probe-Agents {
- Msg "==> 探测 AI Agent..." "==> Probing AI Agents..."
- $probeScript = Join-Path $script:INSTALL_SRC "dist\cli-probe.cjs"
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- if (Test-Path $probeScript) {
- try {
- $raw = & $script:NODE_BIN $probeScript --installer --config-path (Join-Path $DataDir 'config.json') 2>$null
- if ($raw) {
- $script:PROBE_RESULT = if ($raw -is [array]) { $raw -join "" } else { $raw }
- }
- } catch {
- Msg " ⚠️ Agent 探测失败,将跳过选择" " ⚠️ Agent probe failed, skipping selection"
- $script:PROBE_RESULT = "[]"
- }
- }
- $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
- $ErrorActionPreference = $prevEAP
- if (-not $count) { $count = "0" }
- Msg " ✅ 探测到 ${count} 个 Agent 定义" " ✅ Found ${count} agent definitions"
- Write-Host ""
- }
- # ============================================================
- # Agent selection
- # ============================================================
- $script:SELECTED_AGENTS = $Agents
- $script:AGENT_SELECTION_EXPLICIT = if ($Agents) { '1' } else { '0' }
- function Select-Agents {
- # -AllAgents: collect every agent. Skip selection entirely and leave no gate
- # in config (other agent settings survive), so pilot auto-detects all
- # agents at runtime -- including ones installed after this run.
- if ($AllAgents) {
- if ($script:SELECTED_AGENTS) {
- Msg " ⚠️ -AllAgents 已启用,忽略 -Agents 指定的列表" `
- " ⚠️ -AllAgents is set; ignoring the -Agents list"
- $script:SELECTED_AGENTS = ""
- }
- Msg " 采集全部 Agent (不写入选择,由 pilot 运行时自动探测)" `
- " Collecting all agents (no selection written; pilot auto-detects at runtime)"
- Write-Host ""
- return
- }
- if ($script:SELECTED_AGENTS) {
- Msg " 使用指定的 Agent: $($script:SELECTED_AGENTS)" " Using specified agents: $($script:SELECTED_AGENTS)"
- Write-Host ""
- return
- }
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- $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
- $ErrorActionPreference = $prevEAP
- if (-not $agentCount -or $agentCount -eq "0") { return }
- # Non-interactive detection
- $isInteractive = Test-CanPrompt
- if (-not $isInteractive) {
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- $script:SELECTED_AGENTS = $script:PROBE_RESULT | & $script:NODE_BIN -e @'
- const r = JSON.parse(require('fs').readFileSync(0,'utf-8'));
- const detected = r.filter(a => a.detected).map(a => a.id);
- process.stdout.write(detected.join(','));
- '@ 2>$null
- $ErrorActionPreference = $prevEAP
- Msg " (非交互模式) 自动选择已检测到的 Agent: $($script:SELECTED_AGENTS)" `
- " (non-interactive) Auto-selected detected agents: $($script:SELECTED_AGENTS)"
- Write-Host ""
- return
- }
- # Interactive menu
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- $script:PROBE_RESULT | & $script:NODE_BIN -e @'
- const r = JSON.parse(require('fs').readFileSync(0,'utf-8'));
- const lang = process.argv[1];
- const defaults = [];
- for (let i = 0; i < r.length; i++) {
- const a = r[i];
- const status = lang === 'zh'
- ? (a.detected ? '已检测到: ' + a.reason : '未检测到' + (a.reason ? ': ' + a.reason : ''))
- : (a.detected ? 'detected: ' + a.reason : 'not detected' + (a.reason ? ': ' + a.reason : ''));
- console.log(' [' + (i+1) + '] ' + a.displayName.padEnd(16) + '(' + status + ')');
- if (a.detected) defaults.push(i+1);
- }
- console.log('');
- if (lang === 'zh') {
- console.log(' 默认选择已检测到的 Agent: ' + defaults.join(','));
- console.log(' 输入要启用的编号 (逗号分隔),直接回车使用默认:');
- } else {
- console.log(' Default selection (detected): ' + defaults.join(','));
- console.log(' Enter numbers to enable (comma-separated), press Enter for default:');
- }
- '@ $LANG_MODE
- $ErrorActionPreference = $prevEAP
- $rawSelection = Read-Host " >"
- $selectInput = if ($null -eq $rawSelection) { "" } else { $rawSelection.Trim() }
- $selectInput = $selectInput -replace '[,、;]', ','
- if ($selectInput) { $script:AGENT_SELECTION_EXPLICIT = '1' }
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- $script:SELECTED_AGENTS = $script:PROBE_RESULT | & $script:NODE_BIN -e @'
- const r = JSON.parse(require('fs').readFileSync(0,'utf-8'));
- const input = (process.argv[1] || '').replace(/[,、;]/g, ',');
- let indices;
- if (!input.trim()) {
- indices = r.map((a, i) => a.detected ? i : -1).filter(i => i >= 0);
- } else {
- indices = [...new Set(input.trim().split(/[\s,]+/).map(Number).filter(n => n >= 1 && n <= r.length))].map(n => n - 1);
- }
- const ids = indices.sort((a,b) => a-b).map(i => r[i].id);
- process.stdout.write(ids.join(','));
- '@ $selectInput 2>$null
- $ErrorActionPreference = $prevEAP
- if ($script:SELECTED_AGENTS) {
- Msg " 已选择: $($script:SELECTED_AGENTS)" " Selected: $($script:SELECTED_AGENTS)"
- } else {
- Msg " 未选择任何 Agent" " No agents selected"
- }
- Write-Host ""
- }
- # ============================================================
- # Prompt for userId
- # ============================================================
- function Prompt-UserId {
- if ($UserId) { return }
- $configFile = Join-Path $DataDir "config.json"
- $existingUid = ""
- if (Test-Path $configFile) {
- try {
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- $existingUid = & $script:NODE_BIN -e @'
- try { const c=JSON.parse(require('fs').readFileSync(process.argv[1],'utf-8')); process.stdout.write(c.userId||''); } catch {}
- '@ $configFile 2>$null
- $ErrorActionPreference = $prevEAP
- } catch {}
- }
- # Reinstall preserves the existing identity without prompting. To change it,
- # callers must pass -UserId explicitly; this keeps scripted installs fully
- # non-interactive and avoids Read-Host failures in Windows PowerShell 5.1.
- if ($existingUid) {
- $script:UserId = $existingUid
- return
- }
- $isInteractive = Test-CanPrompt
- if (-not $isInteractive) {
- return
- }
- Write-Host ""
- if ($existingUid) {
- Msg " 当前 userId: $existingUid" " Current userId: $existingUid"
- Msg " 直接回车保留,或输入新值:" " Press Enter to keep, or type a new value:"
- } else {
- Msg " 请输入你的 userId(用于数据归属,可直接回车跳过):" `
- " Enter your userId (for data attribution, press Enter to skip):"
- }
- $rawInput = Read-Host " >"
- $input = if ($null -eq $rawInput) { "" } else { $rawInput.Trim() }
- if ($input) {
- $script:UserId = $input
- } elseif ($existingUid) {
- $script:UserId = $existingUid
- }
- }
- # ============================================================
- # Confirm config overwrite
- # ============================================================
- function Confirm-ConfigOverwrite {
- $configFile = Join-Path $DataDir "config.json"
- if (-not (Test-Path $configFile)) { return }
- $slsModeForDiff = ""
- if ($SlsApiKey) {
- $slsModeForDiff = "apiKey"
- } elseif ($SlsAkId -and $SlsAkSecret) {
- $slsModeForDiff = "ak"
- }
- $jsonArg = @{
- slsEndpoint = $SlsEndpoint
- slsProject = $SlsProject
- slsLogstore = $SlsLogstore
- slsMode = $slsModeForDiff
- cmsLicenseKey = $CmsLicenseKey
- cmsEndpoint = $CmsEndpoint
- cmsWorkspace = $CmsWorkspace
- serviceNamePrefix = $ServiceNamePrefix
- dashboardPort = $DashboardPort
- maskMode = $MaskMode
- maskTypes = $MaskTypes
- maskReplacementMode = $MaskReplacementMode
- interceptorMode = $InterceptorMode
- interceptorTypes = $InterceptorTypes
- multimodalMode = $script:MultimodalMode
- } | ConvertTo-Json -Compress
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- $diffs = & $script:NODE_BIN -e @'
- const fs = require('fs');
- let old = {};
- try { old = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8')); } catch { process.exit(0); }
- const newVals = JSON.parse(process.argv[2]);
- const normalizeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean).join(',');
- const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
- const parseTypeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean);
- const uniqueTypes = list => [...new Set(list)];
- const interceptorModeFinal = newVals.interceptorMode || (old.interceptor||{}).mode || '';
- const interceptorTypesFinal = interceptorModeFinal === 'all'
- ? INTERCEPTOR_TYPE_SET.slice()
- : interceptorModeFinal === 'custom'
- ? parseTypeCsv(newVals.interceptorMode ? newVals.interceptorTypes : ((old.interceptor||{}).types||[]).join(',')).filter(t => INTERCEPTOR_TYPE_SET.indexOf(t) !== -1)
- : [];
- const maskModeFinal = newVals.maskMode || (old.mask||{}).mode || '';
- const maskTypesFinal = maskModeFinal === 'custom'
- ? parseTypeCsv(newVals.maskMode ? newVals.maskTypes : ((old.mask||{}).types||[]).join(','))
- : [];
- const coveredMaskMode = interceptorTypesFinal.length && maskModeFinal !== 'all' ? 'custom' : maskModeFinal;
- const coveredMaskTypes = coveredMaskMode === 'custom' ? uniqueTypes(maskTypesFinal.concat(interceptorTypesFinal)) : [];
- const slsModeOf = sls => {
- if (!sls) return '';
- if (sls.mode) return sls.mode;
- if (sls.apiKey) return 'apiKey';
- if (sls.accessKeyId || sls.accessKeySecret) return 'ak';
- return '';
- };
- const checks = [
- { label: 'sls.endpoint', oldVal: (old.sls||{}).endpoint||'', newVal: newVals.slsEndpoint },
- { label: 'sls.project', oldVal: (old.sls||{}).project||'', newVal: newVals.slsProject },
- { label: 'sls.logstore', oldVal: (old.sls||{}).logstore||'', newVal: newVals.slsLogstore },
- { label: 'sls.mode', oldVal: slsModeOf(old.sls), newVal: newVals.slsMode },
- { label: 'cms.licenseKey', oldVal: (old.cms||{}).licenseKey||'', newVal: newVals.cmsLicenseKey },
- { label: 'cms.endpoint', oldVal: (old.cms||{}).endpoint||'', newVal: newVals.cmsEndpoint },
- { label: 'cms.workspace', oldVal: (old.cms||{}).workspace||'', newVal: newVals.cmsWorkspace },
- { label: 'serviceNamePrefix', oldVal: old.serviceNamePrefix||'', newVal: newVals.serviceNamePrefix },
- { label: 'dashboard.port', oldVal: (old.dashboard||{}).port||'', newVal: newVals.dashboardPort ? Number(newVals.dashboardPort) : '' },
- { label: 'mask.mode', oldVal: (old.mask||{}).mode||'', newVal: coveredMaskMode },
- { label: 'mask.types', oldVal: (old.mask||{}).mode === 'custom' && Array.isArray((old.mask||{}).types) ? normalizeCsv(old.mask.types.join(',')) : '', newVal: coveredMaskTypes.join(',') },
- { label: 'mask.replacementMode', oldVal: (old.mask||{}).replacementMode||'', newVal: newVals.maskReplacementMode },
- { label: 'interceptor.mode', oldVal: (old.interceptor||{}).mode||'', newVal: newVals.interceptorMode },
- { label: 'interceptor.types', oldVal: Array.isArray((old.interceptor||{}).types) ? normalizeCsv(old.interceptor.types.join(',')) : '', newVal: normalizeCsv(newVals.interceptorTypes) },
- { 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' : '' },
- ];
- const changed = checks.filter(c => c.newVal && c.oldVal && c.newVal !== c.oldVal);
- if (!changed.length) process.exit(0);
- for (const c of changed) {
- console.log(c.label + ': ' + c.oldVal + ' -> ' + c.newVal);
- }
- '@ $configFile $jsonArg 2>$null
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if (-not $diffs) { return }
- Write-Host ""
- Msg "⚠️ 以下配置将被覆盖:" "⚠️ The following config will be overwritten:"
- $diffs | ForEach-Object { Write-Host " $_" }
- $isInteractive = Test-CanPrompt
- if ($isInteractive) {
- Write-Host ""
- Msg " 确认覆盖? (y/N):" " Confirm overwrite? (y/N):"
- $answer = Read-Host " >"
- if ($answer -notin @("y", "Y", "yes", "YES")) {
- Msg "已取消安装" "Installation cancelled"
- exit 0
- }
- } else {
- Msg " (非交互模式) 继续覆盖" " (non-interactive) Proceeding with overwrite"
- }
- }
- # ============================================================
- # Deploy bootstrap scripts
- # ============================================================
- function Deploy-BootstrapScripts {
- $srcDir = Join-Path $script:PERMANENT_DIR "scripts"
- $bootDir = Join-Path $CACHE_DIR "bin"
- if (-not (Test-Path $bootDir)) { New-Item -ItemType Directory -Path $bootDir -Force | Out-Null }
- Copy-Item (Join-Path $srcDir "collector-daemon.js") $bootDir -Force
- }
- # ============================================================
- # Deploy package to versions/ directory
- # ============================================================
- function Deploy-Package {
- param([string]$src)
- $cacheDir = $CACHE_DIR
- $versionsDir = Join-Path $cacheDir "versions"
- $currentFile = Join-Path $cacheDir "current"
- $previousFile = Join-Path $cacheDir "previous"
- $ver = ""; $commit = ""
- $versionFile = Join-Path $src "VERSION"
- if (Test-Path $versionFile) {
- $content = Get-Content $versionFile
- foreach ($line in $content) {
- if ($line -match "^version=(.+)") { $ver = $Matches[1] }
- if ($line -match "^git_commit=(.+)") { $commit = $Matches[1] }
- }
- }
- $deployedDirName = ""
- $oldDir = ""
- if ($ver -and $commit) {
- if (Test-Path $currentFile) {
- $oldDir = (Get-Content $currentFile -ErrorAction SilentlyContinue).Trim()
- }
- $baseDirName = "${ver}_${commit}"
- $deployedDirName = $baseDirName
- $target = Join-Path $versionsDir $deployedDirName
- if (Test-Path -LiteralPath $target) {
- # Never overwrite a version directory in place. A collector may still
- # have native modules loaded from it, especially when replacing an old
- # S4U task that the current shell cannot terminate.
- $suffix = "$(Get-Date -Format 'yyyyMMddHHmmss')_$(Get-Random -Minimum 1000 -Maximum 9999)"
- $deployedDirName = "${baseDirName}_${suffix}"
- $target = Join-Path $versionsDir $deployedDirName
- }
- Msg "==> 部署到 $target ..." "==> Deploying to $target ..."
- if (-not (Test-Path $versionsDir)) { New-Item -ItemType Directory -Path $versionsDir -Force | Out-Null }
- Copy-Item $src $target -Recurse
- $script:PERMANENT_DIR = $target
- } else {
- Msg "==> 部署到 $($script:PERMANENT_DIR) ..." "==> Deploying to $($script:PERMANENT_DIR) ..."
- $parentDir = Split-Path $script:PERMANENT_DIR
- if (-not (Test-Path $parentDir)) { New-Item -ItemType Directory -Path $parentDir -Force | Out-Null }
- if (Test-Path $script:PERMANENT_DIR) { Remove-Item $script:PERMANENT_DIR -Recurse -Force }
- Copy-Item $src $script:PERMANENT_DIR -Recurse
- }
- Msg " ✅ 部署完成" " ✅ Deployed"
- Write-Host ""
- Msg "==> 安装依赖..." "==> Installing dependencies..."
- $modulesVer = $ver
- if (-not $modulesVer) { if ($Version) { $modulesVer = $Version } else { $modulesVer = "latest" } }
- $modulesFromOss = Ensure-NodeModules $modulesVer
- if (-not $modulesFromOss) {
- Msg " ⚠️ 预编译 node_modules 不可用,回退 npm install" " ⚠️ Prebuilt node_modules unavailable, falling back to npm install"
- $nodeDir = Split-Path $script:NODE_BIN
- $savedPath = $env:PATH
- if ($env:PATH -notlike "*$nodeDir*") { $env:PATH = "$nodeDir;$env:PATH" }
- Push-Location $script:PERMANENT_DIR
- try {
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- & $script:NPM_BIN install --omit=dev --omit=optional 2>&1 | Select-Object -Last 1
- $npmExit = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
- } finally {
- Pop-Location
- $env:PATH = $savedPath
- }
- if ($npmExit -ne 0) {
- Msg "❌ 依赖安装失败 (exit=$npmExit),请检查 npm 日志" "❌ Dependencies installation failed (exit=$npmExit), check npm logs"
- exit 1
- }
- }
- # Only publish current/previous after the candidate is complete. This keeps
- # the old version recoverable when dependency installation fails.
- if ($deployedDirName) {
- if ($oldDir -and $oldDir -ne $deployedDirName) {
- Set-Content -Path $previousFile -Value $oldDir
- }
- Set-Content -Path $currentFile -Value $deployedDirName
- }
- Deploy-BootstrapScripts
- if ($modulesFromOss) {
- Msg " ✅ 依赖安装完成(预编译 node_modules)" " ✅ Dependencies installed (prebuilt node_modules)"
- } else {
- Msg " ✅ 依赖安装完成" " ✅ Dependencies installed"
- }
- Write-Host ""
- # >>> pilot-postinstall-exit-check >>>
- Msg "==> 部署 hook 脚本..." "==> Deploying hook scripts..."
- $postinstallScript = Join-Path $script:PERMANENT_DIR "scripts\postinstall.js"
- $postinstallExit = 0
- $postinstallPartial = $false
- # Empty means "nothing went wrong". The caller aborts on a non-empty value -- the policy
- # lives at the call sites so this block stays byte-identical across the installers, same
- # split as $script:PILOT_LAST_RESTART_ERR.
- $script:PILOT_POSTINSTALL_ERR = ""
- if (Test-Path $postinstallScript) {
- # postinstall.js resolves its target as LOONGSUITE_PILOT_DATA_DIR, falling back to
- # $env:USERPROFILE\.loongsuite-pilot. Unset, an install started with -DataDir would
- # put hooks/skills/plugins in the default tree while its config lives elsewhere, and
- # the collector would then find no hooks at all. Set for this child only and
- # restored afterwards: the rest of the installer must keep seeing what it had.
- $hadPostinstallDataDir = Test-Path Env:LOONGSUITE_PILOT_DATA_DIR
- $priorPostinstallDataDir = if ($hadPostinstallDataDir) {
- (Get-Item Env:LOONGSUITE_PILOT_DATA_DIR).Value
- } else { $null }
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- try {
- $env:LOONGSUITE_PILOT_DATA_DIR = $DataDir
- # Captured rather than streamed because the per-tree verdict is in the output and
- # nowhere else (see below). 2>&1 because postinstall.js reports it on stderr.
- $postinstallOut = & $script:NODE_BIN $postinstallScript 2>&1
- $postinstallExit = $LASTEXITCODE
- $postinstallOut | ForEach-Object { Write-Host $_ }
- if (($postinstallOut | Out-String) -match "failed asset tree|Post-install failed") { $postinstallPartial = $true }
- } finally {
- $ErrorActionPreference = $prevEAP
- if ($hadPostinstallDataDir) {
- Set-Item Env:LOONGSUITE_PILOT_DATA_DIR -Value $priorPostinstallDataDir
- } else {
- Remove-Item Env:LOONGSUITE_PILOT_DATA_DIR -ErrorAction SilentlyContinue
- }
- }
- }
- # Never print the check mark for a postinstall that did not finish. That is exactly how
- # the hooks/skills/plugins trees went missing on every Windows install without a word:
- # fs.cpSync fail-fasts with 0xC0000409 on the bundled Node, killing the script before it
- # copied anything, and this line printed "Hook scripts deployed" regardless.
- #
- # Three distinct outcomes, and the exit code only covers the first. postinstall.js
- # deliberately exits 0 after a per-tree failure -- a non-zero exit would abort the npm
- # install fallback above -- and announces it as "N failed asset tree(s)" instead; its
- # top-level catch is the same story, printing "Post-install failed: <reason>" and still
- # exiting 0. So a non-zero code means the process died outright, while the other two are
- # legible only in the output. Keying the check mark off the exit code alone printed it over
- # an install that had just reported a tree it could not copy.
- #
- # An install with no hooks/plugins is not an install: the collector finds nothing to load
- # and every collection cycle fails on a plugin that was never written. The caller aborts
- # (install) or rolls back (upgrade) on $script:PILOT_POSTINSTALL_ERR.
- if ($postinstallExit -ne 0) {
- $script:PILOT_POSTINSTALL_ERR = "postinstall.js (exit $postinstallExit)"
- Msg " ❌ Hook 脚本部署失败 (exit=$postinstallExit),hooks/plugins 缺失" `
- " ❌ Hook script deployment failed (exit=$postinstallExit); hooks/plugins are missing"
- } elseif ($postinstallPartial) {
- $script:PILOT_POSTINSTALL_ERR = "postinstall.js reported a failed asset tree"
- Msg " ❌ Hook 脚本部分部署失败(见上方输出),hooks/plugins 缺失" `
- " ❌ Some hook asset trees failed to deploy (see the output above); hooks/plugins are missing"
- } else {
- Msg " ✅ Hook 脚本已部署" " ✅ Hook scripts deployed"
- }
- # <<< pilot-postinstall-exit-check <<<
- Write-Host ""
- }
- # ============================================================
- # Migrate legacy layout
- # ============================================================
- function Migrate-LegacyLayout {
- $cacheDir = $CACHE_DIR
- $currentFile = Join-Path $cacheDir "current"
- $legacyDir = Join-Path $cacheDir "package"
- $versionsDir = Join-Path $cacheDir "versions"
- if (Test-Path $currentFile) { return }
- if (-not (Test-Path (Join-Path $legacyDir "dist\index.js"))) { return }
- Msg "==> 迁移旧版本目录结构..." "==> Migrating legacy directory layout..."
- $ver = "0.0.0"; $commit = "legacy"
- $versionFile = Join-Path $legacyDir "VERSION"
- if (Test-Path $versionFile) {
- $content = Get-Content $versionFile
- foreach ($line in $content) {
- if ($line -match "^version=(.+)") { $ver = $Matches[1] }
- if ($line -match "^git_commit=(.+)") { $commit = $Matches[1] }
- }
- }
- $dirName = "${ver}_${commit}"
- $target = Join-Path $versionsDir $dirName
- if (-not (Test-Path $versionsDir)) { New-Item -ItemType Directory -Path $versionsDir -Force | Out-Null }
- Copy-Item $legacyDir $target -Recurse
- Set-Content -Path $currentFile -Value $dirName
- $script:PERMANENT_DIR = $target
- Msg " ✅ 已迁移到 $target" " ✅ Migrated to $target"
- Write-Host ""
- }
- # ============================================================
- # Write config.json
- # ============================================================
- function Write-Config {
- $configFile = Join-Path $DataDir "config.json"
- Msg "==> 写入配置文件 $configFile ..." "==> Writing config to $configFile ..."
- if (-not (Test-Path $DataDir)) { New-Item -ItemType Directory -Path $DataDir -Force | Out-Null }
- # Bundle all params as JSON to avoid PowerShell dropping empty-string args to native commands
- $cfgArgs = [ordered]@{
- configPath = $configFile
- dataDir = $DataDir
- dashboardPort = "$DashboardPort"
- slsEndpoint = "$SlsEndpoint"
- slsProject = "$SlsProject"
- slsLogstore = "$SlsLogstore"
- slsAkId = "$SlsAkId"
- slsAkSecret = "$SlsAkSecret"
- slsApiKey = "$SlsApiKey"
- logLevel = "$LogLevel"
- userId = "$($script:UserId)"
- excludeWorkspaces = @($ExcludeWorkspace | Where-Object { $null -ne $_ })
- collectLog = "$CollectLog"
- collectTrace = "$CollectTrace"
- enableStatusBarApp = "$EnableStatusBarApp"
- cmsLicenseKey = "$CmsLicenseKey"
- cmsEndpoint = "$CmsEndpoint"
- cmsWorkspace = "$CmsWorkspace"
- serviceNamePrefix = "$ServiceNamePrefix"
- selectedAgents = "$($script:SELECTED_AGENTS)"
- allAgentsMode = $(if ($AllAgents) { "1" } else { "" })
- multimodalMode = "$($script:MultimodalMode)"
- multimodalSupportedAgents = "$($script:MultimodalSupportedAgents)"
- agentSelectionExplicit = "$($script:AGENT_SELECTION_EXPLICIT)"
- maskMode = "$MaskMode"
- maskTypes = "$MaskTypes"
- maskReplacementMode = "$MaskReplacementMode"
- interceptorMode = "$InterceptorMode"
- interceptorTypes = "$InterceptorTypes"
- probeResult = "$($script:PROBE_RESULT)"
- }
- $cfgJson = $cfgArgs | ConvertTo-Json -Compress
- # Stage the JSON through a temp file rather than piping it to node's stdin. Under Windows
- # PowerShell 5.1 a string piped to a native command is encoded with $OutputEncoding (default
- # ASCII), so any non-ASCII value (Chinese serviceNamePrefix/userId, a Chinese username in the
- # path, custom mask types...) would be mangled to "?" before node ever sees it. Set-Content
- # -Encoding UTF8 is CLM-safe (no forbidden .NET calls) and encodes UTF-8 correctly regardless
- # of $OutputEncoding; it prepends a BOM in PS5.1, which node strips below before JSON.parse.
- $cfgTmp = Join-Path $env:TEMP ("lp-config-" + (Get-Random) + ".json")
- Set-Content -LiteralPath $cfgTmp -Value $cfgJson -Encoding UTF8 -NoNewline
- # Native node does not throw; read $LASTEXITCODE on the next line so a JSON
- # or write failure cannot print "Config written" and keep installing.
- $cfgExit = 1
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- & $script:NODE_BIN -e @'
- const fs = require('fs');
- let raw = fs.readFileSync(process.argv[1], 'utf-8');
- if (raw.charCodeAt(0) === 0xFEFF) raw = raw.slice(1);
- const opts = JSON.parse(raw);
- let existing = {};
- try { existing = JSON.parse(fs.readFileSync(opts.configPath, 'utf-8')); } catch {}
- const config = {
- ...existing,
- enabled: true,
- dataDir: opts.dataDir,
- };
- if (Array.isArray(opts.excludeWorkspaces) && opts.excludeWorkspaces.length > 0) {
- if (opts.excludeWorkspaces.some(value => typeof value !== 'string' || !require('path').win32.isAbsolute(value))) {
- throw new Error('-ExcludeWorkspace requires absolute local directories');
- }
- config.privacy = { ...config.privacy, excludeWorkspaces: opts.excludeWorkspaces };
- }
- if (!config.dashboard || typeof config.dashboard !== 'object' || Array.isArray(config.dashboard)) {
- config.dashboard = {};
- }
- if (opts.dashboardPort) config.dashboard.port = Number(opts.dashboardPort);
- if (config.dashboard.port === undefined) config.dashboard.port = 8765;
- delete config.internal;
- if (config.userId === undefined && config['user.id'] !== undefined) {
- config.userId = config['user.id'];
- }
- delete config['user.id'];
- if (opts.slsEndpoint || opts.slsProject || opts.slsLogstore || opts.slsApiKey) {
- config.sls = config.sls || {};
- delete config.sls.destinationOverride;
- if (opts.slsEndpoint) config.sls.endpoint = opts.slsEndpoint;
- if (opts.slsApiKey) {
- config.sls.mode = 'apiKey';
- config.sls.apiKey = opts.slsApiKey;
- delete config.sls.accessKeyId;
- delete config.sls.accessKeySecret;
- } else if (opts.slsAkId && opts.slsAkSecret) {
- config.sls.mode = 'ak';
- config.sls.accessKeyId = opts.slsAkId;
- config.sls.accessKeySecret = opts.slsAkSecret;
- delete config.sls.apiKey;
- } else if (opts.slsEndpoint || opts.slsProject || opts.slsLogstore) {
- config.sls.mode = 'webtracking';
- delete config.sls.apiKey;
- delete config.sls.accessKeyId;
- delete config.sls.accessKeySecret;
- }
- if (opts.slsProject && opts.slsLogstore) {
- config.sls.project = opts.slsProject;
- config.sls.logstore = opts.slsLogstore;
- delete config.sls.endpoints;
- }
- }
- if (opts.logLevel) config.logLevel = opts.logLevel;
- if (opts.userId) { config.userId = opts.userId; delete config.identity; }
- if (opts.collectLog) config.collectLog = opts.collectLog === 'true';
- if (opts.collectTrace) config.collectTrace = opts.collectTrace === 'true';
- if (opts.enableStatusBarApp) config.enableStatusBarApp = opts.enableStatusBarApp.toLowerCase() === 'true';
- if (opts.cmsLicenseKey || opts.cmsEndpoint || opts.cmsWorkspace) {
- config.cms = config.cms || {};
- if (opts.cmsLicenseKey) config.cms.licenseKey = opts.cmsLicenseKey;
- if (opts.cmsEndpoint) config.cms.endpoint = opts.cmsEndpoint;
- if (opts.cmsWorkspace) config.cms.workspace = opts.cmsWorkspace;
- }
- if (opts.serviceNamePrefix) config.serviceNamePrefix = opts.serviceNamePrefix;
- if (opts.maskMode) {
- config.mask = config.mask || {};
- config.mask.mode = opts.maskMode;
- if (opts.maskMode === 'custom') {
- config.mask.types = opts.maskTypes.split(',').map(t => t.trim()).filter(Boolean);
- } else { delete config.mask.types; }
- }
- if (opts.maskReplacementMode) {
- config.mask = config.mask || {};
- config.mask.replacementMode = opts.maskReplacementMode;
- }
- if (opts.interceptorMode) {
- config.interceptor = config.interceptor || {};
- config.interceptor.mode = opts.interceptorMode;
- if (opts.interceptorMode === 'custom') {
- config.interceptor.types = opts.interceptorTypes.split(',').map(t => t.trim()).filter(Boolean);
- } else { delete config.interceptor.types; }
- }
- const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
- (function ensureMaskCoversInterceptor(config) {
- const interceptor = config.interceptor || {};
- const extra = interceptor.mode === 'all'
- ? INTERCEPTOR_TYPE_SET.slice()
- : interceptor.mode === 'custom' && Array.isArray(interceptor.types)
- ? interceptor.types.filter(type => INTERCEPTOR_TYPE_SET.indexOf(type) !== -1)
- : [];
- if (extra.length === 0) return;
- if ((config.mask || {}).mode === 'all') return;
- const current = (config.mask || {}).mode === 'custom' && Array.isArray((config.mask || {}).types)
- ? config.mask.types.filter(type => typeof type === 'string' && type.trim())
- : [];
- config.mask = config.mask && typeof config.mask === 'object' && !Array.isArray(config.mask)
- ? config.mask
- : {};
- config.mask.mode = 'custom';
- config.mask.types = [...new Set(current.concat(extra))];
- })(config);
- const allAgents = JSON.parse(opts.probeResult || '[]');
- if (opts.allAgentsMode === '1') {
- // Clear enable gates, not metadata such as a persisted OpenClaw entry.
- for (const agent of Object.values(config.agents || {})) delete agent.enabled;
- } else if (opts.selectedAgents) {
- config.agents = config.agents || {};
- const previousOpenclaw = config.agents.openclaw;
- const selected = opts.selectedAgents.split(',').map(s => s.trim()).filter(Boolean);
- for (const agent of allAgents) {
- config.agents[agent.id] = config.agents[agent.id] || {};
- // A transient discovery miss is not consent to uninstall a live plugin.
- if (agent.id === 'openclaw' && !agent.detected && opts.agentSelectionExplicit !== '1'
- && previousOpenclaw !== undefined) {
- console.log('OpenClaw: detection unavailable; preserving previous enabled state and entry');
- continue;
- }
- config.agents[agent.id].enabled = selected.includes(agent.id);
- }
- }
- const openclaw = allAgents.find(agent => agent.id === 'openclaw');
- if (openclaw && openclaw.detected && openclaw.openclawCliPath
- && (opts.allAgentsMode === '1' || (config.agents && config.agents.openclaw && config.agents.openclaw.enabled !== false))) {
- config.agents = config.agents || {};
- config.agents.openclaw = config.agents.openclaw || {};
- const previousEntry = config.agents.openclaw.cliPath;
- if (typeof previousEntry === 'string' && previousEntry !== openclaw.openclawCliPath) {
- console.log('OpenClaw: updating launch entry ' + JSON.stringify(previousEntry) + ' -> ' + JSON.stringify(openclaw.openclawCliPath));
- }
- config.agents.openclaw.cliPath = openclaw.openclawCliPath;
- }
- if (opts.multimodalMode) {
- config.agents = config.agents || {};
- const supported = String(opts.multimodalSupportedAgents || '').split(',').map(s => s.trim()).filter(Boolean);
- const selected = new Set(String(opts.selectedAgents || '').split(',').map(s => s.trim()).filter(Boolean));
- const allSupported = opts.allAgentsMode === '1' && opts.multimodalMode !== 'none';
- for (const id of supported) {
- if (allSupported) config.agents[id] = config.agents[id] || {};
- else if (!config.agents[id]) continue;
- if (opts.multimodalMode === 'none') {
- delete config.agents[id].multimodal;
- continue;
- }
- const prev = (config.agents[id].multimodal && typeof config.agents[id].multimodal === 'object')
- ? config.agents[id].multimodal
- : {};
- config.agents[id].multimodal = { ...prev, uploadMode: (allSupported || selected.has(id)) ? opts.multimodalMode : 'none' };
- }
- }
- if (opts.multimodalMode && opts.multimodalMode !== 'none' && opts.slsEndpoint && opts.slsProject && opts.slsLogstore && opts.slsApiKey) {
- config.multimodal = {
- storage: {
- type: 'sls',
- target: { endpoint: opts.slsEndpoint, project: opts.slsProject, logstore: opts.slsLogstore },
- },
- };
- }
- fs.writeFileSync(opts.configPath, JSON.stringify(config, null, 2) + '\n');
- '@ $cfgTmp
- $cfgExit = $LASTEXITCODE
- } finally {
- $ErrorActionPreference = $prevEAP
- Remove-PilotPathQuietly $cfgTmp
- }
- if ($cfgExit -ne 0) {
- Msg "❌ 配置写入失败 (exit=$cfgExit)" "❌ Failed to write config (exit=$cfgExit)"
- exit 1
- }
- Msg " ✅ 配置已写入" " ✅ Config written"
- Write-Host ""
- }
- # reg.exe removes overrides under CLM; the guarded .NET call notifies Explorer.
- function Get-PilotRuntimeOverride {
- param([string]$Name)
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- $regOut = reg.exe query "HKCU\Environment" /v $Name 2>$null
- $regExitCode = $LASTEXITCODE
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if ($regExitCode -ne 0) { return "" }
- foreach ($line in $regOut) {
- if (($line -match '^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*)$') -and $Matches[1] -ieq $Name) {
- return $Matches[2].Trim()
- }
- }
- return ""
- }
- function Remove-PilotRuntimeOverride {
- param([string]$Name)
- reg.exe delete "HKCU\Environment" /v $Name /f 2>$null | Out-Null
- if ($LASTEXITCODE -ne 0) { throw "Failed to remove $Name" }
- try {
- [Environment]::SetEnvironmentVariable($Name, $null, 'User')
- return $true
- } catch {
- return $false
- }
- }
- function Retire-PilotRuntimeOverride {
- param([string]$Name, [string]$WrapperPath)
- $current = Get-PilotRuntimeOverride -Name $Name
- if (-not $current) { return }
- # Pilot-owned only: a third-party override must survive untouched.
- if (($current -ieq $WrapperPath) -or ($current -like '*loongsuite-pilot*')) {
- $broadcasted = Remove-PilotRuntimeOverride -Name $Name
- if (-not $broadcasted) { $script:RUNTIME_ENV_BROADCAST_FAILED = $true }
- Msg " ✅ 已退役 $Name" " ✅ Retired $Name"
- }
- }
- function Retire-QoderworkRuntimeOverrides {
- $wrapperPath = Join-Path $DataDir "hooks\qoderwork-runtime-wrapper.mjs"
- $script:RUNTIME_ENV_BROADCAST_FAILED = $false
- Retire-PilotRuntimeOverride -Name 'QW_QODER_WORKER_RUNTIME_PATH' -WrapperPath $wrapperPath
- Retire-PilotRuntimeOverride -Name 'QODER_WORKER_RUNTIME_PATH' -WrapperPath $wrapperPath
- if ($script:RUNTIME_ENV_BROADCAST_FAILED) {
- Msg " 环境变量已清理,但无法通知 Explorer;请注销并重新登录 Windows" `
- " Environment overrides removed but Explorer could not be notified; sign out and back in"
- } else {
- Msg " 请完全退出并重新打开对应应用以生效" `
- " Fully quit and restart the corresponding apps for changes to take effect"
- }
- Write-Host ""
- }
- # ============================================================
- # Install loongsuite-pilot command (batch wrapper)
- # ============================================================
- function Install-Command {
- Msg "==> 安装服务管理脚本..." "==> Installing service management script..."
- $binDir = Join-Path $env:USERPROFILE ".local\bin"
- if (-not (Test-Path $binDir)) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null }
- # Copy the PowerShell service management script. Deploy it as loongsuite-pilot-service.ps1,
- # NOT loongsuite-pilot.ps1: in PowerShell a bare `loongsuite-pilot` resolves an on-PATH .ps1
- # (ExternalScript) BEFORE the .cmd shim, and a directly-run .ps1 obeys the session
- # ExecutionPolicy (often Restricted) instead of the shim's -ExecutionPolicy Bypass. A
- # non-colliding name keeps the .cmd the only match for the bare command name.
- $ps1File = Join-Path $binDir "loongsuite-pilot-service.ps1"
- $ps1Src = Join-Path $script:PERMANENT_DIR "scripts\loongsuite-pilot.ps1"
- if (Test-Path $ps1Src) {
- Copy-Item $ps1Src $ps1File -Force
- }
- # Remove any stale same-name script from older installs that would shadow the .cmd shim.
- $legacyPs1 = Join-Path $binDir "loongsuite-pilot.ps1"
- if (Test-Path $legacyPs1) { Remove-Item $legacyPs1 -Force -ErrorAction SilentlyContinue }
- $layoutFile = Join-Path $binDir "loongsuite-pilot-layout.json"
- $layout = [ordered]@{
- dataDir = $DataDir
- cacheDir = $CACHE_DIR
- } | ConvertTo-Json
- # loongsuite-pilot.ps1 reads this back with Get-Content -Encoding UTF8 | ConvertFrom-Json,
- # which tolerates a BOM, so Set-Content is fine here (and CLM-safe, unlike WriteAllText).
- Set-Content -LiteralPath $layoutFile -Value $layout -Encoding UTF8
- # Create a .cmd shim that forwards to the PowerShell script
- $cmdFile = Join-Path $binDir "loongsuite-pilot.cmd"
- $cmdContent = @'
- @echo off
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0loongsuite-pilot-service.ps1" %*
- '@
- Set-Content -Path $cmdFile -Value $cmdContent -Encoding ASCII
- Msg " ✅ 已安装: $cmdFile" " ✅ Installed: $cmdFile"
- # Add to user PATH if not already there. The persistent write uses reg.exe (a native command,
- # CLM-safe) rather than [Environment]::SetEnvironmentVariable (a .NET static call WDAC forbids)
- # or Set-ItemProperty. Two hazards this avoids:
- # 1. Set-ItemProperty writes plain REG_SZ by default, DOWNGRADING a REG_EXPAND_SZ Path.
- # 2. Get-ItemProperty returns Path already EXPANDED; writing that back FREEZES
- # %USERPROFILE%/%SystemRoot% tokens into literal paths.
- # So we read the RAW (unexpanded) value and its type via `reg query`, then write it back with
- # `reg add /t <type>` to preserve REG_EXPAND_SZ and the tokens. The presence check still uses
- # the EXPANDED value so a bin dir already present via a %VAR% token is not added twice.
- $expandedPath = (Get-ItemProperty -Path 'HKCU:\Environment' -Name Path -ErrorAction SilentlyContinue).Path
- if ($expandedPath -notlike "*$binDir*") {
- $pathType = 'REG_EXPAND_SZ'
- $rawUserPath = ''
- $regOut = reg query "HKCU\Environment" /v Path 2>$null
- if ($LASTEXITCODE -eq 0) {
- foreach ($line in $regOut) {
- if ($line -match '^\s*Path\s+(REG_(?:EXPAND_)?SZ)\s+(.*)$') {
- $pathType = $Matches[1]
- $rawUserPath = $Matches[2]
- break
- }
- }
- }
- # Never drop the existing PATH: if reg query yielded nothing usable, fall back to the
- # expanded value (worst case re-freezes tokens, but preserves all entries).
- if (-not $rawUserPath -and $expandedPath) { $rawUserPath = $expandedPath }
- $newPath = if ($rawUserPath) { "$binDir;$rawUserPath" } else { $binDir }
- reg add "HKCU\Environment" /v Path /t $pathType /d "$newPath" /f | Out-Null
- # Best-effort broadcast so already-open Explorer-spawned terminals refresh their PATH
- # without a re-login: [Environment]::SetEnvironmentVariable persists AND sends
- # WM_SETTINGCHANGE. It is a .NET static call CLM forbids, so swallow failures — the reg add
- # above already persisted the typed value. $newPath still carries raw %VAR% tokens, so on
- # non-CLM hosts .NET also writes REG_EXPAND_SZ (no downgrade).
- try { [Environment]::SetEnvironmentVariable('Path', $newPath, 'User') } catch {}
- Msg " 已将 $binDir 添加到用户 PATH" " Added $binDir to user PATH"
- $env:Path = "$binDir;$env:Path"
- }
- Write-Host ""
- }
- # ============================================================
- # Version helpers
- # ============================================================
- function Get-InstalledVersion {
- $cacheDir = $CACHE_DIR
- $currentFile = Join-Path $cacheDir "current"
- $versionsDir = Join-Path $cacheDir "versions"
- if (Test-Path $currentFile) {
- $dir = (Get-Content $currentFile -ErrorAction SilentlyContinue).Trim()
- $vf = Join-Path $versionsDir "$dir\VERSION"
- if ($dir -and (Test-Path $vf)) {
- $content = Get-Content $vf
- foreach ($line in $content) {
- if ($line -match "^version=(.+)") { return $Matches[1] }
- }
- }
- }
- $vf = Join-Path $script:PERMANENT_DIR "VERSION"
- if (Test-Path $vf) {
- $content = Get-Content $vf
- foreach ($line in $content) {
- if ($line -match "^version=(.+)") { return $Matches[1] }
- }
- }
- return ""
- }
- function Get-VersionFromDir {
- param([string]$dir)
- $vf = Join-Path $dir "VERSION"
- if (Test-Path $vf) {
- $content = Get-Content $vf
- foreach ($line in $content) {
- if ($line -match "^version=(.+)") { return $Matches[1] }
- }
- }
- return ""
- }
- function Get-CommitFromDir {
- param([string]$dir)
- $vf = Join-Path $dir "VERSION"
- if (Test-Path $vf) {
- $content = Get-Content $vf
- foreach ($line in $content) {
- if ($line -match "^git_commit=(.+)") { return $Matches[1] }
- }
- }
- return ""
- }
- function Show-VersionInfo {
- param([string]$dir)
- $vf = Join-Path $dir "VERSION"
- if (Test-Path $vf) {
- $v = ""; $c = ""; $t = ""
- $content = Get-Content $vf
- foreach ($line in $content) {
- if ($line -match "^version=(.+)") { $v = $Matches[1] }
- if ($line -match "^git_commit=(.+)") { $c = $Matches[1] }
- if ($line -match "^build_time=(.+)") { $t = $Matches[1] }
- }
- return "v${v} (${c}, ${t})"
- }
- return "unknown"
- }
- # ============================================================
- # Print summary
- # ============================================================
- function Print-Summary {
- param([string]$action)
- $configFile = Join-Path $DataDir "config.json"
- Write-Host "============================================================"
- $ver = Show-VersionInfo $script:PERMANENT_DIR
- switch ($action) {
- "install" { Msg "✅ 安装完成!版本: $ver" "✅ Installation complete! Version: $ver" }
- "upgrade" { Msg "✅ 升级完成!版本: $ver" "✅ Upgrade complete! Version: $ver" }
- }
- Write-Host ""
- Msg "配置文件: $configFile" "Config file: $configFile"
- Msg "数据目录: $DataDir" "Data directory: $DataDir"
- Msg "Hook 目录: $DataDir\hooks" "Hooks directory: $DataDir\hooks"
- Write-Host ""
- if ($SlsEndpoint) {
- Msg "SLS 后端: $SlsEndpoint" "SLS backend: $SlsEndpoint"
- if ($SlsProject) { Msg " 项目: $SlsProject" " Project: $SlsProject" }
- if ($SlsLogstore) { Msg " 日志库: $SlsLogstore" " Logstore: $SlsLogstore" }
- Write-Host ""
- }
- Msg "命令:" "Commands:"
- Write-Host " loongsuite-pilot # 查看状态 / Status"
- Write-Host " loongsuite-pilot info # 版本与配置 / Version & config"
- Write-Host ""
- Msg "提示: 请新开一个终端后再使用 loongsuite-pilot 命令 (WDAC/受限环境可能需注销重登)。" `
- "Tip: open a NEW terminal before using the loongsuite-pilot command (a WDAC/locked-down environment may require signing out and back in)."
- Write-Host "============================================================"
- }
- # >>> pilot-restart-stale-collector >>>
- # Displace a collector that outlived Stop-PilotService and therefore still serves the
- # PREVIOUS version dir. `start` is deliberately a no-op when a collector is already
- # running, and on a re-install one usually is: Stop-PilotService only ends the current
- # task instance, and Task Scheduler (or the updater's own collector watchdog) relaunches
- # it within seconds -- while `current` still names the old version dir, because
- # Deploy-Package writes the new one only after Ensure-NodeModules. collector-daemon.js
- # resolves `current` exactly once at startup, so that survivor keeps running the old
- # dist forever, while `status` reads `current` and confidently reports the NEW version.
- # Nothing crashes and nothing logs: the install says "Service started" and the bytes the
- # user just installed are simply never loaded. Measured on a re-install where the
- # survivor started 30s before the new version dir even existed.
- #
- # This became silent only once re-installs stopped overwriting the live version dir (pinned
- # by tests/unit/deploy/installer-version-dir-not-overwritten.test.mjs): while Deploy-Package still
- # did Remove-Item on it, the same survivor died with ERR_MODULE_NOT_FOUND and got restarted
- # onto the new version, so the bug announced itself. Keeping the old dir is right; this is
- # the other half of it.
- #
- # restart-collector (not restart) is what the updater uses after deploying a version: it
- # stops the collector unconditionally, kills orphans, then re-registers and starts it, and
- # it leaves the updater alone. Skipped when $priorVersion is empty -- a fresh install has
- # no survivor to displace, and `start` just launched the collector from the new `current`.
- #
- # Skipped again when `start` did not say "already running". That line (Cmd-Start, off
- # Get-CollectorRuntime or the pid file) is the only evidence a survivor was there; without
- # it `start` launched the collector itself, from the new `current`, and there is nothing
- # stale to displace. The bounce is not free either: replacing a task the running principal
- # cannot write to is denied, and because callers treat a failed displacement as a failed
- # deploy, an unnecessary one can roll back an upgrade whose collector had come up correctly.
- # Callers pass the captured start output, hence Out-String -- it arrives as lines. Passing
- # nothing would silently turn this whole block back into a no-op, so every call site has to
- # pass a variable it filled from `start`, pinned by
- # tests/unit/deploy/installer-restart-stale-collector.test.mjs.
- #
- # $serviceEntry is whichever entry point the caller already resolved: the .ps1 needs
- # powershell.exe -File, the .cmd wrapper is invoked directly. Branching here rather than at
- # the call sites keeps this block byte-identical across the three installers.
- #
- # Returns $true when there is nothing to displace or the displacement succeeded, $false with
- # the reason in $script:PILOT_LAST_RESTART_ERR otherwise. Native commands do not throw on a
- # nonzero exit, so $LASTEXITCODE is the only signal there is -- and discarding it put the
- # failure right back where this block came from. Cmd-RestartCollector exits 1 when the node
- # runtime cannot be resolved, when the bootstrap entry is missing, and when the service
- # manager refuses to restart a non-degraded install; in every one of those the survivor is
- # still running the OLD version dir. Callers must not print success on a $false: `status`
- # resolves `current`, which the survivor answers to exactly as well as the new collector
- # would, so "is running" cannot tell the two apart. That is the entire bug.
- function Restart-StaleCollector {
- param([string]$serviceEntry, [string]$priorVersion, $startOutput = "")
- $script:PILOT_LAST_RESTART_ERR = ""
- if (-not $priorVersion) { return $true }
- if (-not $serviceEntry) { return $true }
- if (-not (Test-Path $serviceEntry)) { return $true }
- if (($startOutput | Out-String) -notmatch "already running") { return $true }
- # Locally forced to Continue: with 2>&1 in effect a caller left on Stop turns the first
- # stderr line into a NativeCommandError, which would report a successful restart as a
- # failure. restart-collector writes progress to stderr on purpose.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- if ($serviceEntry -match '\.ps1$') {
- $restartOut = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $serviceEntry restart-collector 2>&1
- } else {
- $restartOut = & $serviceEntry restart-collector 2>&1
- }
- if ($LASTEXITCODE -eq 0) { return $true }
- $script:PILOT_LAST_RESTART_ERR = "restart-collector (exit $LASTEXITCODE): $(($restartOut | Out-String).Trim())"
- return $false
- } catch {
- $script:PILOT_LAST_RESTART_ERR = "restart-collector failed to run: $($_.Exception.Message)"
- return $false
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- }
- # <<< pilot-restart-stale-collector <<<
- # ============================================================
- # Stop service by PID file
- # ============================================================
- function Stop-PilotService {
- $pidFile = Join-Path $DataDir "loongsuite-pilot.pid"
- if (Test-Path $pidFile) {
- $oldPid = (Get-Content $pidFile -ErrorAction SilentlyContinue).Trim()
- if ($oldPid) {
- $proc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
- if ($proc) {
- Msg "==> 停止运行中的服务 (PID $oldPid)..." "==> Stopping running service (PID $oldPid)..."
- Stop-Process -Id $oldPid -Force -ErrorAction SilentlyContinue
- $count = 0
- while ($count -lt 10) {
- $proc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
- if (-not $proc) { break }
- Start-Sleep -Seconds 1
- $count++
- }
- Msg " ✅ 已停止" " ✅ Stopped"
- Write-Host ""
- }
- }
- Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
- }
- # Also try the loongsuite-pilot command (use .ps1 directly to avoid cmd.exe popup)
- $ps1Path = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
- if (Test-Path $ps1Path) {
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ps1Path stop 2>$null
- $ErrorActionPreference = $prevEAP
- }
- }
- # >>> pilot-hold-tasks-during-deploy >>>
- # Stop-PilotService only ends the current task instance. The updater task has a
- # repeating trigger every 5 minutes plus RestartCount, so it comes back while
- # Deploy-Package is still filling a versions/ directory that neither current nor
- # previous names. gcOldVersions then deletes that directory. Disable-ScheduledTask
- # writes Enabled=false on the task definition and actually holds that relaunch;
- # Stop-ScheduledTask does not.
- #
- # Callers Disable BEFORE Stop-PilotService. Disable does not kill a running
- # instance, so Stop is still required, but Stop-Process -Force while the task
- # is still Enabled can arm RestartCount (collector interval is 1 minute).
- # Closing the definition first means a stop cannot be scheduled as a restart.
- #
- # Disable is a write, so it can fail with Access is denied: a -RunLevel Limited
- # task grants its own principal only Read, Synchronize, and an elevated first
- # install leaves the tasks owned by Administrators (same ACL that makes uninstall
- # fail to delete them). A failed disable must not abort the install. Track only
- # names we actually disabled so Enable cannot turn on a task we never held.
- #
- # Enable lives in finally and is idempotent. Start stays on the success path: a
- # failed postinstall must not launch a collector whose hooks were never written.
- # Keep this block byte-identical across every .ps1 installer that carries it.
- $script:PILOT_HELD_TASK_NAMES = @()
- function Get-PilotDeployTaskNames {
- $tag = Get-PilotUserTag
- @("LoongsuitePilot-$tag", "LoongsuitePilotUpdater-$tag")
- }
- function Disable-PilotScheduledTasksDuringDeploy {
- $script:PILOT_HELD_TASK_NAMES = @()
- $taskFolder = "\LoongsuitePilot\"
- foreach ($taskName in (Get-PilotDeployTaskNames)) {
- $task = Get-ScheduledTask -TaskName $taskName -TaskPath $taskFolder -ErrorAction SilentlyContinue
- if (-not $task) { continue }
- $enabled = $true
- try { $enabled = [bool]$task.Settings.Enabled } catch { $enabled = $true }
- if (-not $enabled) { continue }
- try {
- Disable-ScheduledTask -TaskName $taskName -TaskPath $taskFolder -ErrorAction Stop | Out-Null
- $script:PILOT_HELD_TASK_NAMES += $taskName
- } catch {
- Msg " ⚠️ 无法禁用计划任务 ${taskName}: $($_.Exception.Message)" `
- " ⚠️ Could not disable scheduled task ${taskName}: $($_.Exception.Message)"
- }
- }
- if (@($script:PILOT_HELD_TASK_NAMES).Count -gt 0) {
- Msg " 已禁用计划任务(部署期间): $($script:PILOT_HELD_TASK_NAMES -join ', ')" `
- " Disabled scheduled tasks for the deploy: $($script:PILOT_HELD_TASK_NAMES -join ', ')"
- }
- }
- function Enable-PilotScheduledTasksAfterDeploy {
- $taskFolder = "\LoongsuitePilot\"
- $stillHeld = @()
- foreach ($taskName in @($script:PILOT_HELD_TASK_NAMES)) {
- try {
- Enable-ScheduledTask -TaskName $taskName -TaskPath $taskFolder -ErrorAction Stop | Out-Null
- } catch {
- Msg " ⚠️ 无法重新启用计划任务 ${taskName}: $($_.Exception.Message)" `
- " ⚠️ Could not re-enable scheduled task ${taskName}: $($_.Exception.Message)"
- # Keep the name so finally can retry. Wiping the list here would
- # make a failed success-path Enable a no-op on the way out.
- $stillHeld += $taskName
- }
- }
- $script:PILOT_HELD_TASK_NAMES = @($stillHeld)
- }
- # <<< pilot-hold-tasks-during-deploy <<<
- # ============================================================
- # GC old versions
- # ============================================================
- function GC-OldVersions {
- $cacheDir = $CACHE_DIR
- $versionsDir = Join-Path $cacheDir "versions"
- $currentFile = Join-Path $cacheDir "current"
- $previousFile = Join-Path $cacheDir "previous"
- if (-not (Test-Path $versionsDir)) { return }
- $keepCurrent = ""; $keepPrevious = ""
- if (Test-Path $currentFile) { $keepCurrent = (Get-Content $currentFile -ErrorAction SilentlyContinue).Trim() }
- if (Test-Path $previousFile) { $keepPrevious = (Get-Content $previousFile -ErrorAction SilentlyContinue).Trim() }
- Get-ChildItem $versionsDir -Directory -ErrorAction SilentlyContinue | ForEach-Object {
- if ($_.Name -ne $keepCurrent -and $_.Name -ne $keepPrevious) {
- Remove-Item $_.FullName -Recurse -Force
- }
- }
- }
- # ============================================================
- # Remove hook configs
- # ============================================================
- function Remove-HookConfigs {
- $HOOK_MARKER = ".loongsuite-pilot"
- $configs = @(
- (Join-Path $env:USERPROFILE ".cursor\hooks.json"),
- (Join-Path $env:USERPROFILE ".qoder\settings.json"),
- (Join-Path $env:USERPROFILE ".qoder-cn\settings.json"),
- (Join-Path $env:USERPROFILE ".qoderwork\settings.json"),
- (Join-Path $env:USERPROFILE ".qoderworkcn\settings.json"),
- (Join-Path $env:USERPROFILE ".qwenworkcn\settings.json"),
- (Join-Path $env:USERPROFILE ".claude\settings.json"),
- (Join-Path $env:USERPROFILE ".kiro\agents\pilot-kiro.json"),
- (Join-Path $env:USERPROFILE ".qwen\settings.json"),
- (Join-Path $env:USERPROFILE ".workbuddy\settings.json")
- )
- foreach ($cfg in $configs) {
- if (-not (Test-Path $cfg)) { continue }
- $short = $cfg.Replace($env:USERPROFILE, "~")
- # Same guard Remove-OpenClawPlugin and Remove-OtelPlugin already carry, and the
- # reason uninstall may now reach this function without a Node: without it the
- # call below runs as & "" against a hook config that then goes unreported.
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- }
- # Saved and restored around the try, not inside it: a throw from the native call
- # (an install-dir node-bin pin that no longer exists, say) used to skip the
- # restore and leave the whole rest of uninstall running at "Continue", where the
- # later fail-fast checks stop failing fast.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- & $script:NODE_BIN -e @'
- const fs = require('fs');
- const cfg = process.argv[1];
- const marker = process.argv[2];
- try {
- const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
- const hooks = data.hooks;
- if (!hooks || typeof hooks !== 'object') process.exit(0);
- let changed = false;
- for (const [event, entries] of Object.entries(hooks)) {
- if (!Array.isArray(entries)) continue;
- const filtered = entries.filter(e => {
- const cmd = e.command || '';
- const nested = Array.isArray(e.hooks) ? e.hooks : [];
- const hasMarker = cmd.includes(marker) || nested.some(h => (h.command || '').includes(marker));
- if (hasMarker) changed = true;
- return !hasMarker;
- });
- if (filtered.length === 0) { delete hooks[event]; changed = true; }
- else hooks[event] = filtered;
- }
- if (Object.keys(hooks).length === 0) {
- delete data.hooks;
- changed = true;
- }
- if (changed) {
- fs.writeFileSync(cfg, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- }
- } catch(e) { process.stderr.write(e.message); process.exit(1); }
- '@ $cfg $HOOK_MARKER 2>$null
- Msg " ✅ 已清理: $short" " ✅ Cleaned: $short"
- } catch {
- Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)"
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- }
- }
- # Grok Build's hook file is Pilot-owned, but still preserve any third-party
- # entries that may have been added to it. Stable script-name matching also
- # works when Pilot was installed with a custom data directory.
- function Remove-GrokBuildHookConfig {
- $grokHome = if ($env:GROK_HOME) { $env:GROK_HOME } else { Join-Path $env:USERPROFILE ".grok" }
- $cfg = Join-Path $grokHome "hooks\loongsuite-pilot.json"
- $stateFile = Join-Path $DataDir "deployed-agents.json"
- if ($script:NODE_BIN -and (Test-Path -LiteralPath $stateFile)) {
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- $persisted = & $script:NODE_BIN -e @'
- const fs = require("fs");
- const path = require("path");
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- const value = state?.["grok-build"]?.hookSettingsPath;
- if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
- } catch {}
- '@ $stateFile 2>$null
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if ($persisted) { $cfg = [string]$persisted }
- }
- if (-not (Test-Path -LiteralPath $cfg)) { return }
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (无 Node.js,请手动清理 Grok Build Pilot hook)" `
- " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (Node.js unavailable; remove the Grok Build Pilot hook manually)"
- return
- }
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $result = & $script:NODE_BIN -e @'
- const fs = require("fs");
- const cfg = process.argv[1];
- const owned = value => typeof value === "string"
- && /(?:^|[\\/])grok-build-loongsuite-pilot-hook\.(?:sh|ps1)(?:"|\s|$)/i.test(value);
- try {
- const data = JSON.parse(fs.readFileSync(cfg, "utf8"));
- const hooks = data && typeof data.hooks === "object" && data.hooks ? data.hooks : null;
- if (!hooks) { process.stdout.write("nochange"); process.exit(0); }
- let changed = false;
- for (const [event, entries] of Object.entries(hooks)) {
- if (!Array.isArray(entries)) continue;
- const kept = [];
- for (const entry of entries) {
- if (owned(entry && entry.command)) { changed = true; continue; }
- if (entry && Array.isArray(entry.hooks)) {
- const nested = entry.hooks.filter(hook => !owned(hook && hook.command));
- if (nested.length !== entry.hooks.length) changed = true;
- if (entry.hooks.length > 0 && nested.length === 0) continue;
- kept.push({ ...entry, hooks: nested });
- } else {
- kept.push(entry);
- }
- }
- if (kept.length === 0) delete hooks[event];
- else hooks[event] = kept;
- }
- if (!changed) { process.stdout.write("nochange"); process.exit(0); }
- if (Object.keys(hooks).length === 0) delete data.hooks;
- if (Object.keys(data).length === 0) {
- fs.unlinkSync(cfg);
- } else {
- const tmp = `${cfg}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
- fs.renameSync(tmp, cfg);
- }
- process.stdout.write("cleaned");
- } catch (error) {
- process.stderr.write(error.message); process.exit(1);
- }
- '@ $cfg 2>$null
- $exitCode = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
- $result = ([string]($result -join "")).Trim()
- if ($exitCode -eq 0 -and $result -in @("cleaned", "nochange")) {
- Msg " ✅ 已清理: ~/.grok/hooks/loongsuite-pilot.json" `
- " ✅ Cleaned: ~/.grok/hooks/loongsuite-pilot.json"
- } else {
- Msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (需手动清理)" `
- " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (manual cleanup needed)"
- }
- }
- # ============================================================
- # Remove plugin-inject specs (OpenCode)
- # ============================================================
- # OpenCode uses deployMode "plugin-inject": a spec is written into its own
- # config file's plugin array, not a shared settings.json. Remove-HookConfigs
- # does not cover it, so clean it here to avoid a dangling spec.
- function Remove-OpenCodePlugin {
- $configs = @(
- (Join-Path $env:USERPROFILE ".config\opencode\opencode.jsonc"),
- (Join-Path $env:USERPROFILE ".config\opencode\opencode.json"),
- (Join-Path $env:USERPROFILE ".config\opencode\config.json")
- )
- foreach ($cfg in $configs) {
- if (-not (Test-Path $cfg)) { continue }
- $short = $cfg.Replace($env:USERPROFILE, "~")
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- }
- $result = & $script:NODE_BIN -e @'
- const fs = require('fs');
- const f = process.argv[1];
- // Match legacy plugins/opencode/plugin.mjs only under this installation.
- const normalize = value => {
- if (typeof value !== 'string') return '';
- let plain = value;
- if (plain.startsWith('file://')) {
- try {
- const url = new URL(plain);
- plain = decodeURIComponent(url.pathname);
- if (plain[0] === '/' && plain[2] === ':') plain = plain.slice(1);
- if (url.hostname && url.hostname !== 'localhost') {
- if (process.platform !== 'win32') return '';
- plain = '//' + url.hostname + plain;
- }
- } catch { return ''; }
- }
- plain = plain.split(String.fromCharCode(92)).join('/');
- while (plain.endsWith('/')) plain = plain.slice(0, -1);
- return process.platform === 'win32' ? plain.toLowerCase() : plain;
- };
- const dataDir = normalize(process.argv[2]);
- const managed = dataDir ? dataDir + '/plugins/opencode' : null;
- const isOurs = s => typeof s === 'string' && (
- s === 'loongsuite-pilot-opencode' || s.startsWith('loongsuite-pilot-opencode@') ||
- (managed !== null && (normalize(s) === managed || normalize(s) === managed + '/plugin.mjs'))
- );
- const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : (e?.package ?? ''));
- const stripJsonc = src => src
- .replace(/\/\*[\s\S]*?\*\//g, '')
- .replace(/^\s*\/\/.*$/gm, '')
- .replace(/[ \t]+\/\/.*$/gm, '');
- try {
- const raw = fs.readFileSync(f, 'utf-8');
- let data, hadComments = false;
- try { data = JSON.parse(raw); }
- catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
- let removed = 0;
- for (const key of ['plugin', 'plugins']) {
- if (!Array.isArray(data[key])) continue;
- const before = data[key].length;
- data[key] = data[key].filter(e => !isOurs(entryStr(e)));
- removed += before - data[key].length;
- }
- if (!removed) { process.stdout.write('nochange'); process.exit(0); }
- if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
- fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- '@ $cfg $DataDir 2>$null
- switch ($result) {
- "cleaned" { Msg " ✅ 已清理: $short" " ✅ Cleaned: $short" }
- "cleaned-bak" { Msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" }
- "nochange" { }
- default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
- }
- }
- }
- function Remove-HermesPlugin {
- $hermesHome = if ($env:HERMES_HOME) { $env:HERMES_HOME } else { Join-Path $env:USERPROFILE ".hermes" }
- $pluginDir = Join-Path $hermesHome "plugins\loongsuite-pilot"
- $stateFile = Join-Path $DataDir "deployed-agents.json"
- if (Test-Path $stateFile) {
- try {
- $state = Get-Content $stateFile -Raw | ConvertFrom-Json
- $recorded = $state.'hermes-agent'.targetDir
- if ($recorded -and [System.IO.Path]::IsPathRooted([string]$recorded)) {
- $pluginDir = [string]$recorded
- }
- } catch {
- # Fall back to the current HERMES_HOME-derived path.
- }
- }
- $marker = Join-Path $pluginDir ".loongsuite-pilot-managed.json"
- if (-not (Test-Path $marker)) { return }
- try {
- $meta = Get-Content $marker -Raw | ConvertFrom-Json
- if ($meta.owner -ne "loongsuite-pilot" -or $meta.agentId -ne "hermes-agent") {
- Msg " ⚠️ 保留未受 Pilot 管理的 Hermes 插件: $pluginDir" `
- " ⚠️ Preserved unmanaged Hermes plugin: $pluginDir"
- return
- }
- $hermesCli = if ($env:HERMES_CLI) {
- $env:HERMES_CLI
- } else {
- Join-Path $hermesHome "hermes-agent\venv\Scripts\hermes.exe"
- }
- if (-not (Test-Path $hermesCli)) {
- $hermesCommand = Get-Command hermes -ErrorAction SilentlyContinue
- if ($hermesCommand) { $hermesCli = $hermesCommand.Source }
- }
- if (Test-Path $hermesCli) {
- & $hermesCli plugins disable loongsuite-pilot *> $null
- }
- Remove-Item $pluginDir -Recurse -Force
- Msg " ✅ 已清理: $pluginDir" " ✅ Cleaned: $pluginDir"
- } catch {
- Msg " ⚠️ 跳过: $pluginDir (需手动清理)" `
- " ⚠️ Skipped: $pluginDir (manual cleanup needed)"
- }
- }
- # ============================================================
- # Remove Pi Coding Agent extension injection
- # ============================================================
- function Remove-PiCodingAgentExtension {
- $piAgentDir = if ($env:PI_CODING_AGENT_DIR) { $env:PI_CODING_AGENT_DIR } else { Join-Path $env:USERPROFILE ".pi\agent" }
- $cfg = Join-Path $piAgentDir "settings.json"
- $stateFile = Join-Path $DataDir "deployed-agents.json"
- if ($script:NODE_BIN -and (Test-Path -LiteralPath $stateFile)) {
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- $persisted = & $script:NODE_BIN -e @'
- const fs = require("fs");
- const path = require("path");
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- const value = state?.["pi-coding-agent"]?.pluginInjectConfigPath;
- if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
- } catch {}
- '@ $stateFile 2>$null
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if ($persisted) { $cfg = [string]$persisted }
- }
- $short = $cfg.Replace($env:USERPROFILE, "~")
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- return
- }
- $result = & $script:NODE_BIN -e @'
- const fs = require('fs');
- const path = require('path');
- const defaultConfig = process.argv[1];
- const dataDir = process.argv[2];
- const targets = [{ configPath: defaultConfig, markers: ['loongsuite-pilot-pi-coding-agent', 'plugins/pi-coding-agent/index.mjs'] }];
- const resolveValue = value => typeof value === 'string'
- ? value.replace(/^~(?=[\\/])/, process.env.USERPROFILE || '').replaceAll('$PILOT_DATA', dataDir)
- : value;
- const stripJsoncComments = text => {
- let result = '';
- let index = 0;
- let inString = false;
- let escape = false;
- while (index < text.length) {
- const ch = text[index];
- if (inString) {
- result += ch;
- if (escape) escape = false;
- else if (ch.charCodeAt(0) === 92) escape = true;
- else if (ch === '"') inString = false;
- index++;
- continue;
- }
- if (ch === '"') {
- inString = true;
- result += ch;
- index++;
- continue;
- }
- if (ch === '/' && text[index + 1] === '/') {
- index += 2;
- while (index < text.length && text[index] !== '\n') index++;
- continue;
- }
- if (ch === '/' && text[index + 1] === '*') {
- index += 2;
- while (index + 1 < text.length && !(text[index] === '*' && text[index + 1] === '/')) index++;
- index += 2;
- continue;
- }
- result += ch;
- index++;
- }
- return result;
- };
- const comparable = value => typeof value === 'string'
- ? value.split(String.fromCharCode(92)).join('/')
- : '';
- const localDir = path.join(dataDir, 'agents.d.local');
- try {
- for (const name of fs.existsSync(localDir) ? fs.readdirSync(localDir) : []) {
- if (!name.endsWith('.json')) continue;
- let def;
- try { def = JSON.parse(fs.readFileSync(path.join(localDir, name), 'utf8')); } catch { continue; }
- if (def?.piSdk?.schemaVersion !== 1 || !def?.pluginInject?.pluginId?.startsWith('loongsuite-pilot-pi-sdk-')) continue;
- const spec = resolveValue(def.pluginInject.pluginSpec);
- for (const configPath of def.pluginInject.configPaths || []) {
- targets.push({
- configPath: resolveValue(configPath),
- markers: [def.pluginInject.pluginId, spec, 'plugins/pi-coding-agent/agents/'].filter(Boolean),
- });
- }
- }
- let cleaned = 0;
- let skipped = 0;
- for (const target of targets) {
- if (!target.configPath || !fs.existsSync(target.configPath)) continue;
- try {
- const raw = fs.readFileSync(target.configPath, 'utf-8');
- const data = JSON.parse(stripJsoncComments(raw));
- if (!Array.isArray(data.extensions)) continue;
- const before = data.extensions.length;
- data.extensions = data.extensions.filter(entry => {
- const value = comparable(entry);
- return !target.markers.some(marker => value === comparable(marker) || value.includes(comparable(marker)));
- });
- if (data.extensions.length === before) continue;
- if (raw !== JSON.stringify(data, null, 2) + '\n') {
- try {
- fs.copyFileSync(target.configPath, target.configPath + '.bak', fs.constants.COPYFILE_EXCL);
- } catch (e) {
- if (e?.code !== 'EEXIST') throw e;
- }
- }
- fs.writeFileSync(target.configPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- cleaned++;
- } catch {
- skipped++;
- }
- }
- process.stdout.write(cleaned > 0 ? (skipped > 0 ? 'partial' : 'cleaned') : (skipped > 0 ? 'skipped' : 'nochange'));
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- '@ $cfg $DATA_DIR 2>$null
- switch ($result) {
- "cleaned" { Msg " ✅ 已清理 Pi / PI SDK Agent 扩展配置" " ✅ Cleaned Pi / PI SDK Agent extension configs" }
- "partial" { Msg " ⚠️ 已清理可读取的 Pi 配置,部分损坏配置需手动清理" `
- " ⚠️ Cleaned readable Pi configs; some invalid configs need manual cleanup" }
- "skipped" { Msg " ⚠️ Pi 配置损坏,需手动清理" " ⚠️ Invalid Pi configs skipped (manual cleanup needed)" }
- "nochange" { }
- default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
- }
- }
- # ============================================================
- # Remove plugin-inject specs (MiMo Code)
- # ============================================================
- # MiMo Code uses deployMode "plugin-inject": a spec is written into its own
- # config file's plugin array. Same shape as Remove-OpenCodePlugin but for
- # ~/.config/mimocode/mimocode.json[c]. Without this, the spec survives
- # uninstall and points at a (possibly purged) plugin.mjs.
- function Remove-MimoCodePlugin {
- $configs = @(
- (Join-Path $env:USERPROFILE ".config\mimocode\mimocode.jsonc"),
- (Join-Path $env:USERPROFILE ".config\mimocode\mimocode.json")
- )
- foreach ($cfg in $configs) {
- if (-not (Test-Path $cfg)) { continue }
- $short = $cfg.Replace($env:USERPROFILE, "~")
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- }
- $result = & $script:NODE_BIN -e @'
- const fs = require('fs');
- const f = process.argv[1];
- const isOurs = s => typeof s === 'string' && (s.includes('loongsuite-pilot-mimo-code') || s.includes('plugins/mimo-code/plugin.mjs'));
- const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : '');
- const stripJsonc = src => src
- .replace(/\/\*[\s\S]*?\*\//g, '')
- .replace(/^\s*\/\/.*$/gm, '')
- .replace(/[ \t]+\/\/.*$/gm, '');
- try {
- const raw = fs.readFileSync(f, 'utf-8');
- let data, hadComments = false;
- try { data = JSON.parse(raw); }
- catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
- const key = Array.isArray(data.plugins) ? 'plugins' : (Array.isArray(data.plugin) ? 'plugin' : null);
- if (!key) { process.stdout.write('nochange'); process.exit(0); }
- const before = data[key].length;
- data[key] = data[key].filter(e => !isOurs(entryStr(e)));
- if (data[key].length === before) { process.stdout.write('nochange'); process.exit(0); }
- if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
- fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- '@ $cfg 2>$null
- switch ($result) {
- "cleaned" { Msg " ✅ 已清理: $short" " ✅ Cleaned: $short" }
- "cleaned-bak" { Msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" }
- "nochange" { }
- default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
- }
- }
- }
- # ============================================================
- # Remove OpenClaw's nested plugin entry and load path.
- # ============================================================
- function Remove-OpenClawPlugin {
- $stateDir = if ($env:OPENCLAW_STATE_DIR) {
- $env:OPENCLAW_STATE_DIR
- } else {
- Join-Path $env:USERPROFILE ".openclaw"
- }
- $configs = @()
- if ($env:OPENCLAW_CONFIG_PATH) { $configs += $env:OPENCLAW_CONFIG_PATH }
- $configs += @(
- (Join-Path $stateDir "openclaw.json"),
- (Join-Path $stateDir "config.json"),
- (Join-Path $env:USERPROFILE ".openclaw\openclaw.json"),
- (Join-Path $env:USERPROFILE ".openclaw\config.json")
- )
- $managedPath = Join-Path $DataDir "plugins\openclaw"
- $cleanupScript = @'
- const fs = require('fs');
- const f = process.env.PILOT_OC_CONFIG;
- const managed = process.env.PILOT_OC_MANAGED.replaceAll('\\', '/');
- const entryStr = value => typeof value === 'string'
- ? value
- : (Array.isArray(value) && typeof value[0] === 'string' ? value[0] : '');
- const isOurs = value => {
- const normalized = entryStr(value).replaceAll('\\', '/');
- const plain = normalized.startsWith('file://') ? normalized.slice('file://'.length) : normalized;
- return plain === managed ||
- plain === managed + '/plugin.mjs' ||
- normalized.includes('loongsuite-pilot-openclaw') ||
- normalized.includes('plugins/openclaw/plugin.mjs') && plain.includes('.loongsuite-pilot/');
- };
- try {
- const data = JSON.parse(fs.readFileSync(f, 'utf-8'));
- let changed = false;
- for (const key of ['plugin', 'plugins']) {
- if (!Array.isArray(data[key])) continue;
- const filtered = data[key].filter(value => !isOurs(value));
- if (filtered.length !== data[key].length) { data[key] = filtered; changed = true; }
- }
- const plugins = data.plugins && typeof data.plugins === 'object' && !Array.isArray(data.plugins)
- ? data.plugins
- : null;
- if (plugins) {
- if (plugins.load && typeof plugins.load === 'object' && Array.isArray(plugins.load.paths)) {
- const filtered = plugins.load.paths.filter(value => !isOurs(value));
- if (filtered.length !== plugins.load.paths.length) { plugins.load.paths = filtered; changed = true; }
- }
- if (plugins.entries && typeof plugins.entries === 'object' && !Array.isArray(plugins.entries) &&
- Object.prototype.hasOwnProperty.call(plugins.entries, 'loongsuite-pilot-openclaw')) {
- delete plugins.entries['loongsuite-pilot-openclaw'];
- changed = true;
- }
- }
- if (!changed) { process.stdout.write('nochange'); process.exit(0); }
- fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write('cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- '@
- foreach ($cfg in ($configs | Select-Object -Unique)) {
- if (-not (Test-Path $cfg)) { continue }
- $short = $cfg.Replace($env:USERPROFILE, "~")
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- }
- $hadConfigEnv = Test-Path Env:PILOT_OC_CONFIG
- $hadManagedEnv = Test-Path Env:PILOT_OC_MANAGED
- $previousConfigEnv = $env:PILOT_OC_CONFIG
- $previousManagedEnv = $env:PILOT_OC_MANAGED
- try {
- $env:PILOT_OC_CONFIG = $cfg
- $env:PILOT_OC_MANAGED = $managedPath
- $result = $cleanupScript | & $script:NODE_BIN 2>$null
- if ($LASTEXITCODE -ne 0) { $result = "error" }
- } finally {
- if ($hadConfigEnv) { $env:PILOT_OC_CONFIG = $previousConfigEnv }
- else { Remove-Item Env:PILOT_OC_CONFIG -ErrorAction SilentlyContinue }
- if ($hadManagedEnv) { $env:PILOT_OC_MANAGED = $previousManagedEnv }
- else { Remove-Item Env:PILOT_OC_MANAGED -ErrorAction SilentlyContinue }
- }
- switch ($result) {
- "cleaned" { Msg " ✅ 已清理: $short" " ✅ Cleaned: $short" }
- "nochange" { }
- default { Msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" }
- }
- }
- }
- # ============================================================
- # Remove legacy Claude OTel plugin
- # ============================================================
- function Remove-OtelPlugin {
- $OTEL_CLAUDE_DIR = Join-Path $env:USERPROFILE ".cache\opentelemetry.instrumentation.claude"
- # Clean Claude settings.json hooks
- $claudeSettings = Join-Path $env:USERPROFILE ".claude\settings.json"
- if ((Test-Path $claudeSettings) -and $script:NODE_BIN) {
- $content = Get-Content $claudeSettings -Raw -ErrorAction SilentlyContinue
- if ($content -match "otel-claude-hook|hook-entry") {
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- & $script:NODE_BIN -e @'
- const fs = require('fs');
- const f = process.argv[1];
- const isOurs = c => c.includes('otel-claude-hook') || c.includes('hook-entry.sh');
- try {
- const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
- if (d && d.hooks) {
- for (const ev of Object.keys(d.hooks)) {
- if (!Array.isArray(d.hooks[ev])) continue;
- d.hooks[ev] = d.hooks[ev].map(m => {
- if (!Array.isArray(m.hooks)) return m;
- m.hooks = m.hooks.filter(h => !(h.command && isOurs(h.command)));
- return m.hooks.length > 0 ? m : null;
- }).filter(Boolean);
- if (d.hooks[ev].length === 0) delete d.hooks[ev];
- }
- if (Object.keys(d.hooks).length === 0) delete d.hooks;
- fs.writeFileSync(f, JSON.stringify(d, null, 2) + '\n');
- }
- } catch {}
- '@ $claudeSettings 2>$null
- $ErrorActionPreference = $prevEAP
- Msg " ✅ settings.json hooks 已清理" " ✅ settings.json hooks cleaned"
- }
- }
- # Remove plugin directories
- foreach ($dir in @($OTEL_CLAUDE_DIR)) {
- if (Test-Path $dir) {
- if ($Purge) {
- Remove-Item $dir -Recurse -Force
- Msg " ✅ 插件目录已完全删除 (--Purge): $dir" " ✅ Plugin directory fully removed (-Purge): $dir"
- } else {
- Get-ChildItem $dir -ErrorAction SilentlyContinue |
- Where-Object { $_.Name -ne "sessions" } |
- ForEach-Object { Remove-Item $_.FullName -Recurse -Force }
- Msg " ✅ 插件文件已删除(sessions/ 已保留)" " ✅ Plugin files removed (sessions/ preserved)"
- }
- }
- }
- }
- function Start-PilotAndWait {
- param(
- [Parameter(Mandatory = $true)]
- [string]$ScriptPath,
- [string]$PriorVersion = "",
- [int]$TimeoutSeconds = 30
- )
- if (-not (Test-Path -LiteralPath $ScriptPath)) { return $false }
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $startOutput = & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $ScriptPath start 2>&1
- $startExit = $LASTEXITCODE
- $startOutput | ForEach-Object { Write-Host $_ }
- $staleOk = Restart-StaleCollector $ScriptPath $PriorVersion $startOutput
- if (-not $staleOk) {
- Write-Host " $script:PILOT_LAST_RESTART_ERR" -ForegroundColor Yellow
- }
- $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
- do {
- $statusOutput = & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $ScriptPath status 2>$null
- if ($statusOutput -match "is running") {
- $ErrorActionPreference = $prevEAP
- # Deliberately $staleOk, not $true: a collector that outlived the deploy answers
- # "is running" from the old version dir just as convincingly as the new one.
- return $staleOk
- }
- Start-Sleep -Seconds 2
- } while ((Get-Date) -lt $deadline)
- $ErrorActionPreference = $prevEAP
- if ($startExit -ne 0) {
- Write-Host " start command exited with code $startExit" -ForegroundColor Yellow
- }
- return $false
- }
- # ============================================================
- # CMD: install
- # ============================================================
- function Assert-SingleSlsConfig {
- $configFile = Join-Path $DataDir "config.json"
- if (-not (Test-Path -LiteralPath $configFile)) { return }
- $prevEAP = $ErrorActionPreference
- $configExit = 1
- $global:LASTEXITCODE = 1
- $nodeOut = $null
- try {
- $ErrorActionPreference = "Continue"
- $nodeOut = & $script:NODE_BIN -e @'
- const fs = require("fs");
- try {
- const config = JSON.parse(fs.readFileSync(process.argv[1], "utf8").replace(/^\uFEFF/, ""));
- process.exit(Array.isArray(config?.sls) ? 12 : 0);
- } catch { process.exit(13); }
- '@ $configFile 2>&1
- $configExit = $global:LASTEXITCODE
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if ($configExit -eq 12) {
- Msg "❌ 配置包含多个 SLS flusher;安装器不支持修改,请手动编辑 config.json" `
- "❌ Multiple SLS flushers found; the installer cannot modify them. Edit config.json manually."
- exit 1
- }
- if ($configExit -ne 0) {
- $detail = (($nodeOut | Out-String).Trim())
- Msg "❌ 无法检查现有 config.json,请检查文件后重试`n$detail" `
- "❌ Cannot inspect existing config.json; check the file and retry.`n$detail"
- exit 1
- }
- }
- function Cmd-Install {
- Msg "==> 开始安装 $PACKAGE_NAME ..." "==> Installing $PACKAGE_NAME ..."
- Write-Host ""
- # Before anything is downloaded or registered, so Ctrl+C is still cheap.
- Warn-ElevatedInstall
- Check-Deps
- Assert-SingleSlsConfig
- Migrate-LegacyLayout
- $curVer = Get-InstalledVersion
- if ($curVer) {
- Msg "⚠️ 检测到已安装版本 v${curVer},将执行重新安装" "⚠️ Existing installation v${curVer} detected, re-installing"
- Write-Host ""
- }
- try {
- Disable-PilotScheduledTasksDuringDeploy
- Stop-PilotService
- Download-AndExtract
- Probe-Agents
- Select-Agents
- Prompt-UserId
- Confirm-ConfigOverwrite
- Deploy-Package $script:INSTALL_SRC
- # Nothing downstream can repair this: postinstall.js is the only thing that fills
- # $DataDir\{hooks,skills,plugins}, and a collector with no hooks collects nothing.
- # Better to stop with the reason on screen than to finish and report success.
- if ($script:PILOT_POSTINSTALL_ERR) {
- Msg "❌ 安装中止:$script:PILOT_POSTINSTALL_ERR" `
- "❌ Install aborted: $script:PILOT_POSTINSTALL_ERR"
- Msg " 请检查上方输出后重试安装" " Check the output above and re-run the install"
- exit 1
- }
- Write-Config
- Install-Command
- Retire-QoderworkRuntimeOverrides
- Enable-PilotScheduledTasksAfterDeploy
- Msg "==> 启动服务..." "==> Starting service..."
- $ps1Path = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
- $started = Start-PilotAndWait -ScriptPath $ps1Path -PriorVersion $curVer
- if (-not $started) {
- if ($curVer -and (Test-Path (Join-Path $CACHE_DIR "previous"))) {
- Msg "⚠️ 新安装未产生运行心跳,正在恢复 previous 版本..." `
- "⚠️ The new installation produced no runtime heartbeat; restoring the previous version..."
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $ps1Path rollback 2>$null
- $ErrorActionPreference = $prevEAP
- }
- throw "Collector failed to produce a runtime heartbeat after installation."
- }
- Msg " ✅ 服务已启动" " ✅ Service started"
- Write-Host ""
- Print-Summary "install"
- } finally {
- Enable-PilotScheduledTasksAfterDeploy
- Remove-PilotPathQuietly $script:TMP_DIR
- }
- }
- # ============================================================
- # CMD: upgrade
- # ============================================================
- function Cmd-Upgrade {
- Msg "==> 开始升级 $PACKAGE_NAME ..." "==> Upgrading $PACKAGE_NAME ..."
- Write-Host ""
- Migrate-LegacyLayout
- $oldVer = Get-InstalledVersion
- if (-not $oldVer) {
- Msg "❌ 未检测到已安装的 loongsuite-pilot,请先执行 install" `
- "❌ No existing installation found. Please run install first."
- exit 1
- }
- Msg " 当前版本: $oldVer" " Current version: $oldVer"
- Write-Host ""
- Check-Deps
- try {
- Download-AndExtract
- $newVer = Get-VersionFromDir $script:INSTALL_SRC
- $newCommit = Get-CommitFromDir $script:INSTALL_SRC
- $oldCommit = Get-CommitFromDir $script:PERMANENT_DIR
- if ($newVer -and $newVer -eq $oldVer -and $newCommit -eq $oldCommit) {
- Msg "✅ 已是最新版本 v${newVer} (${newCommit}),无需升级" `
- "✅ Already at latest version v${newVer} (${newCommit}), nothing to do"
- exit 0
- }
- Msg " 新版本: ${newVer} (${newCommit})" " New version: ${newVer} (${newCommit})"
- Write-Host ""
- Msg "==> 停止服务..." "==> Stopping service..."
- Disable-PilotScheduledTasksDuringDeploy
- Stop-PilotService
- Write-Host ""
- Deploy-Package $script:INSTALL_SRC
- Install-Command
- Retire-QoderworkRuntimeOverrides
- Enable-PilotScheduledTasksAfterDeploy
- Msg "==> 启动新版本..." "==> Starting new version..."
- $ps1Path = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
- # A failed postinstall is a failed upgrade: no point starting the new version, and the
- # rollback below is what keeps `current` on a version whose assets are known complete.
- $started = $false
- if ($script:PILOT_POSTINSTALL_ERR) {
- Msg " ❌ Hook 脚本部署失败: $script:PILOT_POSTINSTALL_ERR" `
- " ❌ Hook script deployment failed: $script:PILOT_POSTINSTALL_ERR"
- } else {
- $started = Start-PilotAndWait -ScriptPath $ps1Path -PriorVersion $oldVer
- }
- if ($started) {
- Msg " ✅ 新版本启动成功" " ✅ New version started successfully"
- Write-Host ""
- GC-OldVersions
- Print-Summary "upgrade"
- }
- if (-not $started) {
- Write-Host ""
- Msg "⚠️ 新版本启动失败,正在回滚..." "⚠️ New version failed to start, rolling back..."
- if (Test-Path $ps1Path) {
- $prevEAP = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ps1Path stop 2>$null
- & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ps1Path rollback 2>$null
- $ErrorActionPreference = $prevEAP
- }
- Msg "❌ 升级失败,已回滚到 v${oldVer}" "❌ Upgrade failed, rolled back to v${oldVer}"
- Msg " 请检查日志: loongsuite-pilot log" " Check logs: loongsuite-pilot log"
- exit 1
- }
- } finally {
- Enable-PilotScheduledTasksAfterDeploy
- Remove-PilotPathQuietly $script:TMP_DIR
- }
- }
- # Write UTF-8 *without BOM* in a way that works under Constrained Language Mode (WDAC),
- # where [System.IO.File]::WriteAllText / New-Object UTF8Encoding are forbidden. We stage the
- # content through a temp file (Set-Content prepends a BOM) and let node rewrite it BOM-free,
- # because these files (.codex/hooks.json, config.toml) are read by node/Codex, which choke
- # on a BOM. Falls back to Set-Content (with BOM) only if node is somehow unavailable.
- function Write-FileUtf8NoBom {
- param(
- [Parameter(Mandatory = $true)][string]$Path,
- [Parameter(Mandatory = $true)][string]$Content
- )
- if (-not $script:NODE_BIN) {
- Set-Content -LiteralPath $Path -Value $Content -Encoding UTF8 -NoNewline
- return
- }
- $tmp = Join-Path $env:TEMP ("lp-write-" + (Get-Random) + ".tmp")
- Set-Content -LiteralPath $tmp -Value $Content -Encoding UTF8 -NoNewline
- # Windows PowerShell 5.1 strips nested double quotes while marshalling a
- # single-quoted -e argument to a native executable. Keep the JavaScript in a
- # here-string and use JS single-quoted literals so node receives the quotes.
- $rewriteScript = @'
- const fs = require('fs');
- let content = fs.readFileSync(process.argv[1], 'utf-8');
- if (content.charCodeAt(0) === 0xFEFF) content = content.slice(1);
- fs.writeFileSync(process.argv[2], content);
- '@
- $rewriteExit = 1
- $prevEAP = $ErrorActionPreference
- try {
- $ErrorActionPreference = "Continue"
- & $script:NODE_BIN -e $rewriteScript $tmp $Path
- $rewriteExit = $LASTEXITCODE
- } finally {
- $ErrorActionPreference = $prevEAP
- Remove-PilotPathQuietly $tmp
- }
- if ($rewriteExit -ne 0) { throw "Failed to write UTF-8 file: $Path" }
- }
- function Test-IsPilotCodexHookCommand {
- param([object]$Command)
- if ($null -eq $Command) { return $false }
- return ([string]$Command) -match '(?i)(?:^|[\/\\"''\s])codex-loongsuite-pilot-hook\.(?:mjs|sh|ps1)(?:["''\s]|$)'
- }
- function Remove-CodexHookConfig {
- $configPath = Join-Path $env:USERPROFILE ".codex\hooks.json"
- if (-not (Test-Path -LiteralPath $configPath)) { return }
- try {
- # Get-Content -Encoding UTF8 handles both BOM and no-BOM files and is CLM-safe,
- # unlike [System.IO.File]::ReadAllText.
- $raw = Get-Content -LiteralPath $configPath -Raw -Encoding UTF8
- $data = $raw | ConvertFrom-Json
- if (-not $data.hooks -or
- $null -eq $data.hooks.PSObject -or
- $null -eq $data.hooks.PSObject.Properties) {
- return
- }
- $changed = $false
- $eventProperties = @(
- $data.hooks.PSObject.Properties |
- Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace($_.Name) }
- )
- if ($eventProperties.Count -eq 0) { return }
- foreach ($eventProperty in $eventProperties) {
- $eventName = $eventProperty.Name
- $entries = @($eventProperty.Value)
- $keptEntries = @()
- foreach ($entry in $entries) {
- # Preserve malformed or extension-owned null/scalar entries. They
- # are not Pilot commands and uninstall must not fail on them.
- if ($null -eq $entry -or $null -eq $entry.PSObject) {
- $keptEntries += ,$entry
- continue
- }
- $commandProperty = $entry.PSObject.Properties["command"]
- $directCommand = if ($commandProperty) { $commandProperty.Value } else { $null }
- if (Test-IsPilotCodexHookCommand $directCommand) {
- $changed = $true
- continue
- }
- $nestedProperty = $entry.PSObject.Properties["hooks"]
- if ($nestedProperty -and $null -ne $nestedProperty.Value) {
- $nestedHooks = @($nestedProperty.Value)
- $keptNestedHooks = @(
- $nestedHooks | Where-Object {
- if ($null -eq $_ -or $null -eq $_.PSObject) {
- return $true
- }
- $nestedCommandProperty = $_.PSObject.Properties["command"]
- $nestedCommand = if ($nestedCommandProperty) {
- $nestedCommandProperty.Value
- } else {
- $null
- }
- -not (Test-IsPilotCodexHookCommand $nestedCommand)
- }
- )
- if ($keptNestedHooks.Count -ne $nestedHooks.Count) {
- $changed = $true
- $entry.hooks = @($keptNestedHooks)
- }
- if ($nestedHooks.Count -gt 0 -and $keptNestedHooks.Count -eq 0) {
- continue
- }
- }
- $keptEntries += ,$entry
- }
- if ($keptEntries.Count -eq 0) {
- $data.hooks.PSObject.Properties.Remove($eventName)
- } else {
- $data.hooks.$eventName = @($keptEntries)
- }
- }
- if ($changed) {
- $updated = ($data | ConvertTo-Json -Depth 100) + "`r`n"
- Write-FileUtf8NoBom -Path $configPath -Content $updated
- }
- # Do not report success until the resulting config is independently
- # checked for both direct and nested Pilot commands.
- $verifyData = (
- Get-Content -LiteralPath $configPath -Raw -Encoding UTF8 |
- ConvertFrom-Json
- )
- if ($verifyData.hooks) {
- $verifyEventProperties = @(
- $verifyData.hooks.PSObject.Properties |
- Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace($_.Name) }
- )
- foreach ($eventProperty in $verifyEventProperties) {
- foreach ($entry in @($eventProperty.Value)) {
- if ($null -eq $entry -or $null -eq $entry.PSObject) { continue }
- $commandProperty = $entry.PSObject.Properties["command"]
- $directCommand = if ($commandProperty) { $commandProperty.Value } else { $null }
- if (Test-IsPilotCodexHookCommand $directCommand) {
- throw "Pilot Codex hook command is still present"
- }
- $nestedProperty = $entry.PSObject.Properties["hooks"]
- $nestedHooks = if ($nestedProperty) { @($nestedProperty.Value) } else { @() }
- foreach ($nestedHook in $nestedHooks) {
- if ($null -eq $nestedHook -or $null -eq $nestedHook.PSObject) { continue }
- $nestedCommandProperty = $nestedHook.PSObject.Properties["command"]
- $nestedCommand = if ($nestedCommandProperty) {
- $nestedCommandProperty.Value
- } else {
- $null
- }
- if (Test-IsPilotCodexHookCommand $nestedCommand) {
- throw "Pilot Codex nested hook command is still present"
- }
- }
- }
- }
- }
- if ($changed) {
- Msg " ✅ 已清理: ~\.codex\hooks.json" `
- " ✅ Cleaned: ~\.codex\hooks.json"
- }
- } catch {
- throw "Failed to clean Pilot hooks from $configPath`: $($_.Exception.Message)"
- }
- }
- function Remove-OnePilotScheduledTask {
- param(
- [Parameter(Mandatory = $true)]
- [string]$TaskName,
- [Parameter(Mandatory = $true)]
- [string]$TaskPath
- )
- $task = Get-ScheduledTask `
- -TaskName $TaskName `
- -TaskPath $TaskPath `
- -ErrorAction SilentlyContinue
- if (-not $task) { return }
- if ($task.State -eq "Running") {
- Stop-ScheduledTask `
- -TaskName $TaskName `
- -TaskPath $TaskPath `
- -ErrorAction SilentlyContinue
- }
- $unregisterError = $null
- try {
- Unregister-ScheduledTask `
- -TaskName $TaskName `
- -TaskPath $TaskPath `
- -Confirm:$false `
- -ErrorAction Stop
- } catch {
- $unregisterError = $_.Exception.Message
- $fullTaskName = "$($TaskPath.TrimEnd('\'))\$TaskName"
- # Locally forced to Continue for the native call below. On Windows PowerShell 5.1
- # a native command that writes stderr *while a 2> redirection is in effect*
- # raises a NativeCommandError, and the file header's
- # $ErrorActionPreference = "Stop" promotes that to a terminating error whose
- # Message is nothing but the raw stderr line. schtasks.exe prints
- # "ERROR: Access is denied." there on exactly the failure this branch exists to
- # report, so the throw below -- the only place that tells the user why the task
- # survived and what to do about it -- was unreachable: the user saw the bare
- # stderr line and nothing else. Restored in finally so the rest of uninstall
- # keeps failing fast. $schtasksExit starts at 1 so a schtasks.exe that cannot
- # launch at all is treated as failure rather than inheriting a stale
- # $LASTEXITCODE of 0.
- $schtasksExit = 1
- $schtasksOut = ""
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- $schtasksOut = & schtasks.exe /Delete /TN $fullTaskName /F 2>&1
- $schtasksExit = $LASTEXITCODE
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- if ($schtasksExit -ne 0) {
- # Each element here is an ErrorRecord, not a string: at "Continue" the
- # NativeCommandError still goes to the error stream and 2>&1 merges the record
- # itself, so Out-String rendered the whole PowerShell error block -- source
- # line, squiggle line, CategoryInfo, FullyQualifiedErrorId -- into the middle
- # of the sentence below. Measured on a 5.1 box: schtasks.exe emits two records
- # for one stderr line, the second one empty. .Exception.Message is a property
- # get, so it stays CLM-safe, and it is the raw stderr text and nothing else.
- $schtasksLines = @()
- foreach ($schtasksLine in $schtasksOut) {
- $lineText = ""
- if ($schtasksLine.Exception) { $lineText = [string]$schtasksLine.Exception.Message }
- else { $lineText = [string]$schtasksLine }
- $lineText = $lineText.Trim()
- if ($lineText) { $schtasksLines += $lineText }
- }
- $schtasksDetail = $schtasksLines -join " "
- 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."
- }
- }
- $remaining = Get-ScheduledTask `
- -TaskName $TaskName `
- -TaskPath $TaskPath `
- -ErrorAction SilentlyContinue
- if ($remaining) {
- $fullTaskName = "$($TaskPath.TrimEnd('\'))\$TaskName"
- throw "Scheduled task still exists after deletion: $fullTaskName"
- }
- }
- # >>> pilot-account-identity >>>
- # Windows account identity, DOMAIN\user, without whoami. On 5.1 a native command's
- # stdout is decoded with [Console]::OutputEncoding -- the console codepage, 437 on an
- # en-US box -- so `whoami` returns "host\??" for a non-ASCII account name: every
- # character the codepage cannot represent arrives as a literal U+003F, measured on a
- # C:\Users\<CJK name> profile. That corrupted string used to reach
- # New-ScheduledTaskPrincipal -UserId, where Task Scheduler rejected the registration
- # with "No mapping between account names and security IDs was done" (HRESULT
- # 0x80131500), so such a user never got an autostart task at all; it also collapsed
- # every non-ASCII account to the same "___" task-name tag.
- #
- # The environment variables carry the real UTF-16 string and are CLM-safe, unlike
- # [Security.Principal.WindowsIdentity]::GetCurrent() (CLM: "Method invocation is
- # supported only on core types") and unlike [Environment]::UserName. USERDOMAIN is not
- # always an account domain: under some logon providers (OpenSSH sshd among them) it is
- # the literal "WORKGROUP", which maps to no SID either, so fall back to the machine
- # name -- which is also what whoami prints for a local account, keeping the tag below
- # byte-identical for ASCII users who upgrade in place.
- function Get-PilotAccountName {
- $user = [string]$env:USERNAME
- if (-not $user) { return "" }
- $domain = [string]$env:USERDOMAIN
- if ((-not $domain) -or ($domain -eq "WORKGROUP")) { $domain = [string]$env:COMPUTERNAME }
- if ($domain) { return ($domain + "\" + $user) }
- return $user
- }
- # Task names are per-user: multiple users can run on one machine, each with their
- # own data dir under %USERPROFILE%. A global task name would collide -- the second
- # user cannot delete or overwrite the first user's task (Access is denied), so it
- # would fail with "already exists" and drop to the background fallback. The shared
- # \LoongsuitePilot folder stays cross-user writable; only the task name is scoped.
- # Tag from the full DOMAIN\user identity, not $env:USERNAME alone (bare SAM name):
- # two same-named accounts from different domains (CORP\alice vs DEV\alice) would
- # otherwise share one task name and re-introduce the cross-user "already exists"
- # collision this scoping is meant to prevent. Task names live in the file system, so
- # everything outside [A-Za-z0-9._-] becomes "_" -- which turns a non-ASCII account
- # name into a row of underscores that two such users on one machine would fight over,
- # hence the short deterministic digest appended in that case only. ASCII installs keep
- # the exact tag they already have, so their registered tasks stay upgradeable in place.
- function Get-PilotUserTag {
- $name = (Get-PilotAccountName).ToLower()
- $tag = $name -replace '[^A-Za-z0-9._-]', '_'
- if ($name -match '[^\x20-\x7E]') {
- $hash = 0
- foreach ($ch in $name.ToCharArray()) { $hash = ($hash * 31 + [int]$ch) % 1000000007 }
- $tag = $tag + "-" + $hash
- }
- return $tag
- }
- # <<< pilot-account-identity <<<
- # >>> pilot-elevation-warning >>>
- # "Run as administrator" is the reflex a lot of Windows users have for an installer, and
- # here it quietly costs them the ability to uninstall. The scheduled tasks are registered
- # with -RunLevel Limited into the shared \LoongsuitePilot folder, and the only reason a
- # standard user can delete them again is that folder's inherited CREATOR OWNER :
- # FullControl ACE. Under an elevated token CREATOR OWNER resolves to
- # BUILTIN\Administrators, so the tasks come out owned by Administrators and the same
- # account's ordinary session keeps only Read, Synchronize -- schtasks /Delete answers
- # "ERROR: Access is denied." and uninstall cannot remove them. Same mechanism as the file
- # ACLs that Reset-PilotInheritedAcl already repairs with icacls /reset; the task side has
- # no equivalent yet, so for now all we can do is say so before the user commits.
- #
- # The probe is best-effort by construction: both the cast and GetCurrent() are "supported
- # only on core types" under Constrained Language Mode, so under WDAC this throws and we
- # report not-elevated. Losing the hint is acceptable; failing an install over a hint is
- # not.
- function Test-PilotElevated {
- try {
- $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
- $principal = [Security.Principal.WindowsPrincipal]$identity
- return [bool]$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
- } catch {
- return $false
- }
- }
- function Warn-ElevatedInstall {
- if (-not (Test-PilotElevated)) { return }
- Msg "⚠️ 当前是提权(管理员)会话" "⚠️ This is an elevated (administrator) session"
- Msg " 这样注册出来的计划任务归 BUILTIN\Administrators,本账号的普通会话之后删不掉" " Scheduled tasks registered from it are owned by BUILTIN\Administrators, and this account's ordinary sessions cannot delete them afterwards"
- Msg " 继续安装的话,卸载(-Uninstall)也必须在提权会话里执行" " If you continue, uninstall (-Uninstall) will have to run elevated as well"
- Msg " 想让普通会话自己就能卸载:Ctrl+C 退出,在非提权 PowerShell 里重新安装" " To keep uninstall working without elevation: press Ctrl+C and re-run the install from a non-elevated PowerShell"
- Write-Host ""
- }
- # <<< pilot-elevation-warning <<<
- function Remove-PilotScheduledTasks {
- $taskFolder = "\LoongsuitePilot"
- # Reconstruct the task names with the same helpers that registered them -- the tag
- # must match byte for byte or uninstall silently leaves the tasks behind.
- $currentIdentity = Get-PilotAccountName
- $currentUser = $env:USERNAME
- $userTag = Get-PilotUserTag
- $currentUserTasks = @(
- "LoongsuitePilot-$userTag",
- "LoongsuitePilotUpdater-$userTag"
- )
- $legacyTasks = @("LoongsuitePilot", "LoongsuitePilotUpdater")
- foreach ($taskName in @($currentUserTasks + $legacyTasks)) {
- $isLegacy = $taskName -in $legacyTasks
- $task = Get-ScheduledTask `
- -TaskName $taskName `
- -TaskPath "$taskFolder\" `
- -ErrorAction SilentlyContinue
- if ($isLegacy) {
- if (-not $task) { continue }
- $taskOwner = [string]$task.Principal.UserId
- $isCurrentOwner = (
- -not $taskOwner -or
- $taskOwner -ieq $currentIdentity -or
- $taskOwner -ieq $currentUser -or
- $taskOwner.ToLower().EndsWith("\$currentUser".ToLower())
- )
- if (-not $isCurrentOwner) { continue }
- }
- Remove-OnePilotScheduledTask `
- -TaskName $taskName `
- -TaskPath "$taskFolder\"
- }
- }
- function Assert-SafePilotDirectory {
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Purpose
- )
- # CLM-safe path normalization: Convert-Path resolves the absolute path without the
- # forbidden [System.IO.Path]::GetFullPath; fall back to the raw path if it can't be
- # resolved (e.g. it no longer exists). Split-Path -Qualifier gives the drive root ("C:").
- $fullPath = $Path
- try { $fullPath = (Convert-Path -LiteralPath $Path -ErrorAction Stop) } catch { $fullPath = $Path }
- $fullPath = $fullPath.TrimEnd('\')
- $rootPath = (Split-Path -Qualifier $fullPath -ErrorAction SilentlyContinue)
- $profilePath = $env:USERPROFILE.TrimEnd('\')
- if (-not $fullPath -or $fullPath -ieq $rootPath -or $fullPath -ieq "$rootPath\" -or $fullPath -ieq $profilePath) {
- throw "Refusing to use unsafe $Purpose directory: $Path"
- }
- return $fullPath
- }
- function ConvertTo-ExtendedLengthPath {
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path
- )
- $fullPath = $Path
- try { $fullPath = (Convert-Path -LiteralPath $Path -ErrorAction Stop) } catch { $fullPath = $Path }
- if ($fullPath.StartsWith("\\?\")) { return $fullPath }
- if ($fullPath.StartsWith("\\")) {
- return "\\?\UNC\$($fullPath.Substring(2))"
- }
- return "\\?\$fullPath"
- }
- function Remove-PilotPath {
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path
- )
- if (-not (Test-Path -LiteralPath $Path)) { return }
- $extendedPath = ConvertTo-ExtendedLengthPath -Path $Path
- $lastError = $null
- $isFullLanguage = $ExecutionContext.SessionState.LanguageMode -eq 'FullLanguage'
- for ($attempt = 1; $attempt -le 3; $attempt++) {
- try {
- if ($isFullLanguage) {
- # Fast path: .NET calls handle the \\?\ extended-length path (deep node_modules
- # trees that exceed MAX_PATH). Available only under Full Language Mode.
- if ([System.IO.Directory]::Exists($extendedPath)) {
- [System.IO.Directory]::Delete($extendedPath, $true)
- } elseif ([System.IO.File]::Exists($extendedPath)) {
- [System.IO.File]::SetAttributes($extendedPath, [System.IO.FileAttributes]::Normal)
- [System.IO.File]::Delete($extendedPath)
- }
- } else {
- # Constrained Language Mode (WDAC): the .NET calls above are forbidden. Fall
- # back to Remove-Item on the original path — covers all but pathological >260-char
- # paths, which are rare and can be cleaned manually if they ever surface.
- Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction Stop
- }
- return
- } catch {
- $lastError = $_
- if ($attempt -lt 3) { Start-Sleep -Milliseconds (100 * $attempt) }
- }
- }
- throw $lastError
- }
- function Remove-PilotInstallationFiles {
- $cachePath = Assert-SafePilotDirectory -Path $CACHE_DIR -Purpose "cache"
- $dataPath = Assert-SafePilotDirectory -Path $DataDir -Purpose "data"
- $cachePrefix = $cachePath + '\'
- $cacheContainsData = $dataPath.ToLower().StartsWith($cachePrefix.ToLower())
- if ($cachePath -ine $dataPath -and -not $cacheContainsData) {
- if (Test-Path -LiteralPath $cachePath) {
- Remove-PilotPath -Path $cachePath
- }
- } else {
- foreach ($relativePath in @(
- "versions",
- "bin",
- "package",
- "current",
- "previous",
- "node-bin"
- )) {
- $target = Join-Path $cachePath $relativePath
- if (Test-Path -LiteralPath $target) {
- Remove-PilotPath -Path $target
- }
- }
- }
- foreach ($relativePath in @("hooks", "skills", "plugins")) {
- $target = Join-Path $dataPath $relativePath
- if (Test-Path -LiteralPath $target) {
- Remove-PilotPath -Path $target
- }
- }
- }
- # >>> dsh-unpatch-refusal >>>
- # Would removing the plugin assets leave a reference behind? Only a patch file that still
- # carries our managed block would, so that is the one question worth refusing over.
- #
- # Consulted only on the paths that would otherwise refuse to continue, never on the
- # working path: this reads a file owned by a third-party tool, and an unreadable one must
- # not be able to turn a healthy uninstall into a failing one. Unreadable is answered
- # "still managed" on purpose -- we cannot prove nothing dangles, so we keep the
- # conservative answer and let the caller refuse.
- function Test-DshPatchStillManaged {
- param([string]$PatchPath)
- if (-not $PatchPath) { return $false }
- if (-not (Test-Path -LiteralPath $PatchPath -ErrorAction SilentlyContinue)) { return $false }
- try {
- return [bool](Select-String -LiteralPath $PatchPath -SimpleMatch "# BEGIN PILOT-OBSERVABILITY-MANAGED" -Quiet)
- } catch {
- return $true
- }
- }
- # <<< dsh-unpatch-refusal <<<
- # ============================================================
- # Remove the Pilot-owned DeepSeek Harness YAML patch before plugin assets.
- # Unix and Windows both execute assets/plugins/dsh/cleanup.mjs.
- # ============================================================
- function Remove-DshYamlPatch {
- $pluginDir = Join-Path $DataDir "plugins\dsh"
- $cleanupScript = Join-Path $pluginDir "cleanup.mjs"
- $dshHome = if ($env:DSH_HOME) { $env:DSH_HOME } else { Join-Path $env:USERPROFILE ".dsh" }
- $patchPath = Join-Path $dshHome "cordis.patch.yml"
- # DSH_HOME may differ between install and uninstall. Prefer the exact path
- # persisted by DeploymentManager, with the current environment as a legacy fallback.
- $stateFile = Join-Path $DataDir "deployed-agents.json"
- if (Test-Path -LiteralPath $stateFile) {
- try {
- $state = Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json
- $persistedPatch = $state.dsh.dshPatchPath
- if ($persistedPatch -and ([string]$persistedPatch -match '^(?:[A-Za-z]:[\\/]|\\\\)')) {
- $patchPath = [string]$persistedPatch
- }
- } catch {
- # Preserve compatibility with missing or legacy state and use the fallback above.
- }
- }
- if (-not (Test-Path -LiteralPath $cleanupScript)) {
- if (Test-DshPatchStillManaged -PatchPath $patchPath) {
- throw "DSH cleanup helper is missing; refusing to remove plugin assets still referenced by $patchPath"
- }
- return
- }
- if (-not $script:NODE_BIN) {
- # Gated the same way as the branch above, which it was not. Resolve-Node returns
- # $null when no candidate is suitable, so this throw has always been reachable,
- # and uninstall now also arrives here after a failed Node probe instead of dying
- # inside Resolve-Node itself. Refusing unconditionally aborted the entire
- # uninstall -- Cmd-Uninstall calls this before every other cleanup step, and
- # -Purge, the step that deletes config.json and the reporting credentials in it,
- # is the last thing in the function -- on machines where DSH was never patched and
- # there was nothing to protect. Refuse only when something would really dangle.
- if (Test-DshPatchStillManaged -PatchPath $patchPath) {
- throw "No usable Node.js; cannot safely remove the DSH YAML patch at $patchPath"
- }
- Msg " ⚠️ 跳过: 无可用 node,且 $patchPath 里没有 Pilot 托管块,无需 unpatch" `
- " ⚠️ Skipped: no usable node, and $patchPath carries no Pilot-managed block, so there is nothing to unpatch"
- return
- }
- & $script:NODE_BIN $cleanupScript --patch $patchPath --plugin-dir $pluginDir
- if ($LASTEXITCODE -ne 0) {
- throw "DSH YAML patch cleanup failed; Pilot assets were preserved"
- }
- Msg " ✅ 已清理 DSH YAML patch" " ✅ Cleaned DSH YAML patch"
- }
- # ============================================================
- # CMD: uninstall
- # ============================================================
- function Remove-CopilotPlugin {
- $copilotHome = Join-Path $env:USERPROFILE '.copilot'
- if (-not (Test-Path -LiteralPath $copilotHome)) { return }
- $helper = $null
- $candidates = @((Join-Path $script:PERMANENT_DIR 'dist/copilot-cleanup.cjs'))
- $currentFile = Join-Path $CACHE_DIR 'current'
- if (Test-Path -LiteralPath $currentFile) {
- $version = (Get-Content -LiteralPath $currentFile -Raw -Encoding UTF8).Trim()
- $candidates = @((Join-Path $CACHE_DIR "versions/$version/dist/copilot-cleanup.cjs")) + $candidates
- }
- foreach ($candidate in $candidates) {
- if (Test-Path -LiteralPath $candidate) { $helper = $candidate; break }
- }
- if (-not $script:NODE_BIN -or -not $helper) {
- Write-Warning 'Copilot cleanup skipped: safe Node JSONC helper unavailable; config and plugin assets preserved'
- return
- }
- $savedPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Continue'
- & $script:NODE_BIN $helper $copilotHome
- $cleanupExit = $LASTEXITCODE
- } finally { $ErrorActionPreference = $savedPreference }
- if ($cleanupExit -ne 0) { Write-Warning 'Copilot cleanup incomplete; config and plugin assets preserved for retry' }
- }
- function Remove-CopilotOtelEnvironment {
- # Best-effort legacy cleanup: Copilot automatic deployment is Unix-only.
- # A profile access/CLM failure must not interrupt other agents or -Purge.
- foreach ($relative in @('Documents/PowerShell/Microsoft.PowerShell_profile.ps1', 'Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1')) {
- $tmp = $null
- try {
- $profilePath = Join-Path $env:USERPROFILE $relative
- if (-not (Test-Path -LiteralPath $profilePath)) { continue }
- $before = Get-Content -LiteralPath $profilePath -Raw -Encoding UTF8
- $after = $before -replace '(?s)\r?\n?# >>> loongsuite-pilot copilot otel >>>.*?# <<< loongsuite-pilot copilot otel <<<\r?\n?', "`n"
- if ($before -ne $after) {
- $tmp = "$profilePath.pilot-$PID.tmp"
- Set-Content -LiteralPath $tmp -Value $after -Encoding UTF8 -NoNewline
- Move-Item -LiteralPath (Get-PilotLongPath $tmp) -Destination (Get-PilotLongPath $profilePath) -Force
- }
- } catch { Write-Warning "Copilot profile cleanup incomplete; continuing uninstall" }
- finally { if ($tmp) { Remove-PilotPathQuietly $tmp } }
- }
- Remove-Item -LiteralPath (Join-Path $DATA_DIR 'state/copilot/otel-enabled') -Force -ErrorAction SilentlyContinue
- }
- function Cmd-Uninstall {
- Msg "🗑️ 开始卸载 $PACKAGE_NAME ..." "🗑️ Uninstalling $PACKAGE_NAME ..."
- Write-Host ""
- Msg "==> 停止服务..." "==> Stopping service..."
- Stop-PilotService
- Msg " ✅ 服务已停止" " ✅ Service stopped"
- Write-Host ""
- Remove-PilotScheduledTasks
- Msg " ✅ 已移除计划任务" " ✅ Removed scheduled tasks"
- # Resolve the pinned runtime before installation files (including node-bin)
- # are removed. JSON config cleanup must also work when Node is absent from PATH.
- if (-not $script:NODE_BIN) {
- try {
- $script:NODE_BIN = Resolve-Node
- } catch {
- # Non-fatal on purpose. Resolve-Node probes third-party version-manager
- # directories, and under the file header's $ErrorActionPreference = "Stop"
- # any unexpected error record in there becomes terminating. Unguarded, that
- # aborted Cmd-Uninstall right here -- before plugin cleanup, before the
- # install directory was deleted, and before -Purge -- so config.json
- # survived on disk with its credentials in it. Every step below that needs
- # Node already checks $script:NODE_BIN and reports what it skipped.
- $script:NODE_BIN = ""
- Msg " ⚠️ 解析 Node 失败: $($_.Exception.Message)" `
- " ⚠️ Resolving Node failed: $($_.Exception.Message)"
- }
- }
- if (-not $script:NODE_BIN) {
- Msg " ⚠️ 未解析到可用的 Node;依赖 Node 的清理步骤会逐项跳过并提示,其余步骤继续" `
- " ⚠️ No usable Node resolved; each Node-dependent cleanup step will be skipped with a notice, the rest continues"
- }
- Msg "==> 清理 DSH YAML patch..." "==> Cleaning up DSH YAML patch..."
- Remove-DshYamlPatch
- Write-Host ""
- # Read the persisted target before the default data/install directory is removed.
- Msg "==> 清理 Hermes 插件..." "==> Cleaning up Hermes plugin..."
- Remove-HermesPlugin
- Write-Host ""
- Msg "==> 清理 OpenClaw 插件配置..." "==> Cleaning up OpenClaw plugin config..."
- Remove-OpenClawPlugin
- Write-Host ""
- # This cleanup executes Node.js. Run it before installation assets or a
- # pinned runtime can disappear, matching the POSIX uninstall ordering.
- Msg "==> 清理 Grok Build hook 配置..." "==> Cleaning up Grok Build hook config..."
- Remove-GrokBuildHookConfig
- try { Remove-CopilotOtelEnvironment } catch { Write-Warning "Copilot environment cleanup failed; continuing uninstall" }
- try { Remove-CopilotPlugin } catch { Write-Warning "Copilot plugin cleanup failed; continuing uninstall" }
- Write-Host ""
- Msg "==> 清理 hook 配置..." "==> Cleaning up hook configs..."
- Remove-HookConfigs
- try {
- Remove-CodexHookConfig
- } catch {
- Msg " ⚠️ Codex hook 清理失败,继续卸载: $($_.Exception.Message)" `
- " ⚠️ Codex hook cleanup failed; continuing uninstall: $($_.Exception.Message)"
- }
- Write-Host ""
- Msg "==> 清理 QoderWork 系列环境变量..." "==> Cleaning up QoderWork-family env vars..."
- $wrapperPath = Join-Path $DataDir "hooks\qoderwork-runtime-wrapper.mjs"
- $script:RUNTIME_ENV_BROADCAST_FAILED = $false
- $runtimeEnvCleanupFailed = $false
- foreach ($envName in @('QW_QODER_WORKER_RUNTIME_PATH', 'QODER_WORKER_RUNTIME_PATH')) {
- try {
- $currentRuntime = Get-PilotRuntimeOverride -Name $envName
- if ($currentRuntime -and $currentRuntime -ieq $wrapperPath) {
- $broadcasted = Remove-PilotRuntimeOverride -Name $envName
- if (-not $broadcasted) { $script:RUNTIME_ENV_BROADCAST_FAILED = $true }
- Msg " ✅ 已移除 $envName" " ✅ Removed $envName"
- }
- } catch {
- $runtimeEnvCleanupFailed = $true
- Msg " ⚠️ 清理 $envName 失败,已保留安装文件以便重试: $($_.Exception.Message)" `
- " ⚠️ Failed to clean $envName; installation files will be preserved for retry: $($_.Exception.Message)"
- }
- }
- if ($script:RUNTIME_ENV_BROADCAST_FAILED) {
- Msg " ⚠️ 请注销并重新登录 Windows 以刷新 Explorer 环境" `
- " ⚠️ Sign out and back in to refresh the Explorer environment"
- }
- Write-Host ""
- Msg "==> 清理 Claude 旧插件..." "==> Cleaning up legacy Claude plugin..."
- Remove-OtelPlugin
- Write-Host ""
- Msg "==> 清理 OpenCode 插件配置..." "==> Cleaning up OpenCode plugin config..."
- Remove-OpenCodePlugin
- Write-Host ""
- Msg "==> 清理 Pi Coding Agent Extension 配置..." "==> Cleaning up Pi Coding Agent extension config..."
- Remove-PiCodingAgentExtension
- Write-Host ""
- Msg "==> 清理 MiMo Code 插件配置..." "==> Cleaning up MiMo Code plugin config..."
- Remove-MimoCodePlugin
- Write-Host ""
- if ($runtimeEnvCleanupFailed) {
- throw "Runtime environment cleanup failed; installation files were preserved for retry"
- }
- # Keep the pinned node runtime and deployed helper assets available until
- # every external config and runtime override has been cleaned. In
- # particular, never leave a User env var pointing at a deleted wrapper.
- Msg "==> 删除安装目录..." "==> Removing installation..."
- Remove-PilotInstallationFiles
- Msg " ✅ 已删除安装文件" " ✅ Removed installation files"
- Msg "==> 删除 loongsuite-pilot 命令..." "==> Removing loongsuite-pilot command..."
- $cmdFile = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot.cmd"
- $ps1File = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-service.ps1"
- $legacyPs1File = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot.ps1"
- $layoutFile = Join-Path $env:USERPROFILE ".local\bin\loongsuite-pilot-layout.json"
- if (Test-Path $cmdFile) { Remove-Item $cmdFile -Force }
- if (Test-Path $ps1File) { Remove-Item $ps1File -Force }
- if (Test-Path $legacyPs1File) { Remove-Item $legacyPs1File -Force }
- if (Test-Path $layoutFile) { Remove-Item $layoutFile -Force }
- Msg " ✅ loongsuite-pilot 命令已删除" " ✅ loongsuite-pilot command removed"
- Write-Host ""
- if ($Purge) {
- Msg "==> 删除数据目录 (-Purge)..." "==> Removing data directory (-Purge)..."
- $safeDataDir = Assert-SafePilotDirectory -Path $DataDir -Purpose "data"
- if (Test-Path -LiteralPath $safeDataDir) {
- Remove-PilotPath -Path $safeDataDir
- }
- Msg " ✅ 已删除 $DataDir" " ✅ Removed $DataDir"
- } else {
- Msg "📁 数据目录已保留: $DataDir" "📁 Data directory preserved: $DataDir"
- # Names the credentials rather than saying "config": this line is the only notice
- # a user gets that an uninstall they consider finished left an SLS AccessKeySecret
- # readable on disk, and "contains config and logs" does not read like that.
- Msg " (包含配置和日志,其中 config.json 里有上报凭据;如需彻底删除请加 -Purge)" `
- " (contains config and logs -- config.json holds reporting credentials; add -Purge to remove)"
- }
- Write-Host ""
- Write-Host "============================================================"
- Msg "✅ 卸载完成!" "✅ Uninstallation complete!"
- Write-Host "============================================================"
- }
- # ============================================================
- # Main dispatcher
- # ============================================================
- switch ($Command) {
- "install" { Cmd-Install }
- "upgrade" { Cmd-Upgrade }
- "uninstall" { Cmd-Uninstall }
- default {
- Write-Host "Usage: .\installer-opensource.ps1 {install|upgrade|uninstall} [options]"
- exit 1
- }
- }
deploy/installer-opensource.sh · Bundled script · 3,242 lines · 1 finding marked
- #!/usr/bin/env bash
- # installer-opensource.sh — Open-source installer for loongsuite-pilot
- #
- # Install (first time):
- # 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
- # curl -fsSL <URL>/installer.sh | bash -s -- install \
- # --sls-endpoint "https://cn-hangzhou.log.aliyuncs.com" \
- # --sls-project "my-project" \
- # --sls-logstore "my-logstore" \
- # --sls-ak-id "your-ak-id" \
- # --sls-ak-secret "your-ak-secret"
- # curl -fsSL <URL>/installer.sh | bash -s -- install \
- # --sls-endpoint "https://cn-hangzhou.log.aliyuncs.com" \
- # --sls-project "my-project" \
- # --sls-logstore "my-logstore" \
- # --sls-api-key "your-api-key" \
- # --multimodal-mode all
- #
- # Install a specific version:
- # curl -fsSL <URL>/installer.sh | bash -s -- install --version 1.2.0
- #
- # Optional Dashboard port (default: 8765; preserve existing port on reinstall):
- # curl -fsSL <URL>/installer.sh | bash -s -- install --dashboard-port 9000
- #
- # Upgrade (preserve config, auto-rollback on failure):
- # curl -fsSL <URL>/installer.sh | bash -s -- upgrade
- #
- # Uninstall:
- # curl -fsSL <URL>/installer.sh | bash -s -- uninstall
- # curl -fsSL <URL>/installer.sh | bash -s -- uninstall --purge
- set -euo pipefail
- # ============================================================
- # Constants
- # ============================================================
- PACKAGE_NAME="loongsuite-pilot"
- PERMANENT_DIR="$HOME/.loongsuite-pilot/package"
- DEFAULT_DATA_DIR="$HOME/.loongsuite-pilot"
- # OSS download base URL
- _OSS_BASE_URL="https://loongcollector-community-edition.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot"
- # Managed Node.js runtime + prebuilt node_modules (downloaded from OSS at install time)
- NODE_VERSION="${LOONGSUITE_PILOT_NODE_VERSION:-22.22.2}"
- NODE_DEPS_BASE="${LOONGSUITE_PILOT_NODE_DEPS_URL:-https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node}"
- NODE_MODULES_BASE="${LOONGSUITE_PILOT_NODE_MODULES_URL:-https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node-modules}"
- # ============================================================
- # Parse sub-command
- # ============================================================
- COMMAND=""
- PACKAGE_URL="${LOONGSUITE_PILOT_PACKAGE_URL:-}"
- INSTALL_VERSION=""
- SLS_ENDPOINT=""
- SLS_PROJECT=""
- SLS_LOGSTORE=""
- SLS_AK_ID=""
- SLS_AK_SECRET=""
- SLS_API_KEY=""
- DATA_DIR="$DEFAULT_DATA_DIR"
- DASHBOARD_PORT=""
- DASHBOARD_PORT_SET=0
- LOG_LEVEL=""
- USER_ID=""
- COLLECT_LOG=""
- COLLECT_TRACE=""
- ENABLE_STATUS_BAR_APP=""
- CMS_LICENSE_KEY=""
- CMS_ENDPOINT=""
- CMS_WORKSPACE=""
- SERVICE_NAME_PREFIX=""
- SELECTED_AGENTS=""
- HOOK_INSTALL_SCOPE=""
- AGENT_SELECTION_EXPLICIT=0
- ALL_AGENTS=0
- MULTIMODAL_MODE=""
- MULTIMODAL_MODE_SET=0
- # Keep in sync with MULTIMODAL_SUPPORTED_AGENT_IDS.
- MULTIMODAL_SUPPORTED_AGENTS="codex,qoder"
- EXCLUDE_WORKSPACES=()
- MASK_MODE=""
- MASK_TYPES=""
- MASK_REPLACEMENT_MODE=""
- INTERCEPTOR_MODE=""
- INTERCEPTOR_TYPES=""
- HAS_SUDO=0
- PURGE=0
- PREFER_SYSTEM_NODE=0
- # First arg is sub-command (or option -> default to install)
- if [[ $# -gt 0 ]]; then
- case "$1" in
- install|upgrade|uninstall)
- COMMAND="$1"; shift ;;
- -*)
- COMMAND="install" ;;
- *)
- COMMAND="install" ;;
- esac
- else
- COMMAND="install"
- fi
- while [[ $# -gt 0 ]]; do
- case "$1" in
- --sls-endpoint) SLS_ENDPOINT="$2"; shift 2 ;;
- --sls-endpoint=*) SLS_ENDPOINT="${1#*=}"; shift ;;
- --sls-project) SLS_PROJECT="$2"; shift 2 ;;
- --sls-project=*) SLS_PROJECT="${1#*=}"; shift ;;
- --sls-logstore) SLS_LOGSTORE="$2"; shift 2 ;;
- --sls-logstore=*) SLS_LOGSTORE="${1#*=}"; shift ;;
- --sls-ak-id) SLS_AK_ID="$2"; shift 2 ;;
- --sls-ak-id=*) SLS_AK_ID="${1#*=}"; shift ;;
- --sls-ak-secret) SLS_AK_SECRET="$2"; shift 2 ;;
- --sls-ak-secret=*) SLS_AK_SECRET="${1#*=}"; shift ;;
- --sls-api-key) SLS_API_KEY="$2"; shift 2 ;;
- --sls-api-key=*) SLS_API_KEY="${1#*=}"; shift ;;
- --package-url) PACKAGE_URL="$2"; shift 2 ;;
- --package-url=*) PACKAGE_URL="${1#--package-url=}"; shift ;;
- --data-dir) DATA_DIR="$2"; shift 2 ;;
- --data-dir=*) DATA_DIR="${1#*=}"; shift ;;
- --dashboard-port)
- if [ "$#" -lt 2 ] || [[ "$2" == --* ]]; then
- echo "--dashboard-port requires an integer between 1 and 65535" >&2
- exit 1
- fi
- DASHBOARD_PORT="$2"; DASHBOARD_PORT_SET=1; shift 2 ;;
- --dashboard-port=*) DASHBOARD_PORT="${1#*=}"; DASHBOARD_PORT_SET=1; shift ;;
- --log-level) LOG_LEVEL="$2"; shift 2 ;;
- --log-level=*) LOG_LEVEL="${1#*=}"; shift ;;
- --userId|--user.id) USER_ID="$2"; shift 2 ;;
- --userId=*|--user.id=*) USER_ID="${1#*=}"; shift ;;
- --lang) export LOONGSUITE_PILOT_LANG="$2"; shift 2 ;;
- --lang=*) export LOONGSUITE_PILOT_LANG="${1#--lang=}"; shift ;;
- --version) INSTALL_VERSION="$2"; shift 2 ;;
- --version=*) INSTALL_VERSION="${1#*=}"; shift ;;
- --exclude-workspace)
- if [ "$#" -lt 2 ] || [[ "$2" != /* ]]; then
- echo "--exclude-workspace requires an absolute local directory" >&2
- exit 1
- fi
- EXCLUDE_WORKSPACES+=("$2"); shift 2 ;;
- --exclude-workspace=*)
- excluded_workspace="${1#*=}"
- if [[ "$excluded_workspace" != /* ]]; then
- echo "--exclude-workspace requires an absolute local directory" >&2
- exit 1
- fi
- EXCLUDE_WORKSPACES+=("$excluded_workspace"); shift ;;
- --collect-log) COLLECT_LOG="$2"; shift 2 ;;
- --collect-log=*) COLLECT_LOG="${1#*=}"; shift ;;
- --collect-trace) COLLECT_TRACE="$2"; shift 2 ;;
- --collect-trace=*) COLLECT_TRACE="${1#*=}"; shift ;;
- --enable-status-bar-app|--enable-status-bar-app=*)
- if [[ "$1" == *=* ]]; then
- ENABLE_STATUS_BAR_APP="${1#*=}"; shift
- else
- if [ "$#" -lt 2 ]; then
- echo "--enable-status-bar-app requires true or false" >&2
- exit 1
- fi
- ENABLE_STATUS_BAR_APP="$2"; shift 2
- fi
- case "$ENABLE_STATUS_BAR_APP" in
- true|false) ;;
- *) echo "--enable-status-bar-app requires true or false" >&2; exit 1 ;;
- esac ;;
- --cms-license-key) CMS_LICENSE_KEY="$2"; shift 2 ;;
- --cms-license-key=*) CMS_LICENSE_KEY="${1#*=}"; shift ;;
- --cms-endpoint) CMS_ENDPOINT="$2"; shift 2 ;;
- --cms-endpoint=*) CMS_ENDPOINT="${1#*=}"; shift ;;
- --cms-workspace) CMS_WORKSPACE="$2"; shift 2 ;;
- --cms-workspace=*) CMS_WORKSPACE="${1#*=}"; shift ;;
- --service-name-prefix) SERVICE_NAME_PREFIX="$2"; shift 2 ;;
- --service-name-prefix=*) SERVICE_NAME_PREFIX="${1#*=}"; shift ;;
- --agents) SELECTED_AGENTS="$2"; AGENT_SELECTION_EXPLICIT=1; shift 2 ;;
- --agents=*) SELECTED_AGENTS="${1#*=}"; AGENT_SELECTION_EXPLICIT=1; shift ;;
- --scope)
- [ "$#" -ge 2 ] || { echo "--scope requires user or system" >&2; exit 1; }
- HOOK_INSTALL_SCOPE="$2"; shift 2 ;;
- --scope=*) HOOK_INSTALL_SCOPE="${1#*=}"; shift ;;
- --all-agents) ALL_AGENTS=1; shift ;;
- --multimodal-mode) MULTIMODAL_MODE="${2-}"; MULTIMODAL_MODE_SET=1; shift 2 || shift ;;
- --multimodal-mode=*) MULTIMODAL_MODE="${1#*=}"; MULTIMODAL_MODE_SET=1; shift ;;
- --mask-mode) MASK_MODE="$2"; shift 2 ;;
- --mask-mode=*) MASK_MODE="${1#*=}"; shift ;;
- --mask-types) MASK_TYPES="$2"; shift 2 ;;
- --mask-types=*) MASK_TYPES="${1#*=}"; shift ;;
- --mask-replacement-mode) MASK_REPLACEMENT_MODE="$2"; shift 2 ;;
- --mask-replacement-mode=*) MASK_REPLACEMENT_MODE="${1#*=}"; shift ;;
- --interceptor-mode) INTERCEPTOR_MODE="$2"; shift 2 ;;
- --interceptor-mode=*) INTERCEPTOR_MODE="${1#*=}"; shift ;;
- --interceptor-types) INTERCEPTOR_TYPES="$2"; shift 2 ;;
- --interceptor-types=*) INTERCEPTOR_TYPES="${1#*=}"; shift ;;
- --purge) PURGE=1; shift ;;
- --prefer-system-node) PREFER_SYSTEM_NODE=1; shift ;;
- --prefer-system-node=*) PREFER_SYSTEM_NODE=1; shift ;;
- --system-service)
- echo "⚠️ --system-service is deprecated and ignored. Auto-detection is now the default." >&2
- shift ;;
- *)
- echo "Unknown option: $1" >&2
- exit 1 ;;
- esac
- done
- if [ -n "$HOOK_INSTALL_SCOPE" ]; then
- case "$HOOK_INSTALL_SCOPE" in
- user|system) ;;
- *) echo "--scope requires user or system" >&2; exit 1 ;;
- esac
- if [ "$COMMAND" != "install" ]; then
- echo "--scope is only supported with install; upgrades preserve recorded hook scope" >&2
- exit 1
- fi
- fi
- if [ -n "$ENABLE_STATUS_BAR_APP" ] && [ "$COMMAND" != "install" ]; then
- echo "--enable-status-bar-app is only supported with install" >&2
- exit 1
- fi
- if [ "$DASHBOARD_PORT_SET" -eq 1 ]; then
- if ! [[ "$DASHBOARD_PORT" =~ ^[0-9]{1,5}$ ]] || (( 10#$DASHBOARD_PORT < 1 || 10#$DASHBOARD_PORT > 65535 )); then
- echo "--dashboard-port must be an integer between 1 and 65535" >&2
- exit 1
- fi
- fi
- if [ -n "$MASK_MODE" ]; then
- case "$MASK_MODE" in
- all|none|custom) ;;
- *)
- echo "❌ Unknown mask mode: $MASK_MODE (use 'all', 'custom', or 'none')" >&2
- exit 1 ;;
- esac
- fi
- if [ "$MASK_MODE" = "custom" ] && [ -z "$MASK_TYPES" ]; then
- echo "❌ --mask-types is required when --mask-mode custom" >&2
- exit 1
- fi
- if [ -n "$MASK_TYPES" ] && [ "$MASK_MODE" != "custom" ]; then
- echo "❌ --mask-types can only be used with --mask-mode custom" >&2
- exit 1
- fi
- if [ -n "$MASK_REPLACEMENT_MODE" ] && [ "$MASK_REPLACEMENT_MODE" != "placeholder" ] && [ "$MASK_REPLACEMENT_MODE" != "preview" ]; then
- echo "❌ Unknown mask replacement mode: $MASK_REPLACEMENT_MODE (use 'placeholder' or 'preview')" >&2
- exit 1
- fi
- if [ -n "$INTERCEPTOR_MODE" ]; then
- case "$INTERCEPTOR_MODE" in
- all|none|custom) ;;
- *)
- echo "❌ Unknown interceptor mode: $INTERCEPTOR_MODE (use 'all', 'custom', or 'none')" >&2
- exit 1 ;;
- esac
- fi
- if [ "$INTERCEPTOR_MODE" = "custom" ] && [ -z "$INTERCEPTOR_TYPES" ]; then
- echo "❌ --interceptor-types is required when --interceptor-mode custom" >&2
- exit 1
- fi
- if [ -n "$INTERCEPTOR_TYPES" ] && [ "$INTERCEPTOR_MODE" != "custom" ]; then
- echo "❌ --interceptor-types can only be used with --interceptor-mode custom" >&2
- exit 1
- fi
- if [ -n "$SLS_API_KEY" ] && { [ -n "$SLS_AK_ID" ] || [ -n "$SLS_AK_SECRET" ]; }; then
- echo "❌ --sls-api-key cannot be used with --sls-ak-id or --sls-ak-secret" >&2
- exit 1
- fi
- if [ "$MULTIMODAL_MODE_SET" -eq 1 ]; then
- if [ -z "$MULTIMODAL_MODE" ]; then
- echo "❌ --multimodal-mode requires 'none', 'input', 'output', or 'all'" >&2
- exit 1
- fi
- case "$MULTIMODAL_MODE" in
- none|input|output|all) ;;
- *)
- echo "❌ Unknown multimodal mode: $MULTIMODAL_MODE (use 'none', 'input', 'output', or 'all')" >&2
- exit 1 ;;
- esac
- if [ "$COMMAND" != "install" ]; then
- echo "❌ --multimodal-mode is only supported with install (got $COMMAND)" >&2
- exit 1
- fi
- if [ "$MULTIMODAL_MODE" != "none" ]; then
- if [[ "$SLS_ENDPOINT" != *[![:space:]]* ]] || [[ "$SLS_PROJECT" != *[![:space:]]* ]] \
- || [[ "$SLS_LOGSTORE" != *[![:space:]]* ]] || [[ "$SLS_API_KEY" != *[![:space:]]* ]]; then
- echo "❌ --multimodal-mode $MULTIMODAL_MODE requires --sls-endpoint, --sls-project, --sls-logstore, and --sls-api-key" >&2
- exit 1
- fi
- fi
- fi
- # Validate current user and sudo access on Linux
- validate_install_user() {
- case "$(uname -s)" in
- Linux)
- local current_user
- current_user=$(whoami)
- if [ "$(id -u)" -eq 0 ]; then
- HAS_SUDO=1
- msg " ✅ 以 root 身份安装(自动使用系统级服务)" \
- " ✅ Installing as root (auto system-level service)"
- else
- msg " Install user: $current_user(服务类型将在启动时自动检测)" \
- " Install user: $current_user (service type auto-detected at start)"
- fi
- ;;
- esac
- }
- # Resolve PACKAGE_URL from OSS if not explicitly set
- if [ -z "$PACKAGE_URL" ]; then
- if [ -n "$INSTALL_VERSION" ]; then
- PACKAGE_URL="${_OSS_BASE_URL}/${INSTALL_VERSION}/${PACKAGE_NAME}.tar.gz"
- else
- PACKAGE_URL="${_OSS_BASE_URL}/latest/${PACKAGE_NAME}.tar.gz"
- fi
- fi
- # ============================================================
- # Language detection
- # ============================================================
- detect_lang() {
- if [ -n "${LOONGSUITE_PILOT_LANG:-}" ]; then echo "$LOONGSUITE_PILOT_LANG"; return; fi
- for v in "${LANGUAGE:-}" "${LC_ALL:-}" "${LC_MESSAGES:-}" "${LANG:-}"; do
- if echo "$v" | grep -qi "zh"; then echo "zh"; return; fi
- done
- if [ "$(uname)" = "Darwin" ]; then
- local al
- al=$(defaults read -g AppleLanguages 2>/dev/null | grep -i "zh" | head -1 || true)
- if [ -n "$al" ]; then echo "zh"; return; fi
- fi
- echo "en"
- }
- LANG_MODE=$(detect_lang)
- msg() { [ "$LANG_MODE" = "zh" ] && echo "$1" || echo "$2"; }
- # ============================================================
- # Common: check dependencies
- # ============================================================
- _resolve_realpath() {
- realpath "$1" 2>/dev/null || readlink -f "$1" 2>/dev/null || echo "$1"
- }
- _node_is_app_bundle() {
- local resolved
- resolved=$(_resolve_realpath "$1")
- case "$resolved" in
- /Applications/*.app/Contents/*|/System/Applications/*.app/Contents/*|"$HOME"/Applications/*.app/Contents/*)
- return 0
- ;;
- esac
- return 1
- }
- # node:sqlite is unflagged from 22.13 and 23.4. A major-version check accepts
- # Node 20 and 22.12, whose require('node:sqlite') throws, so install would
- # succeed and SQLite collection would not. The require is the check.
- _node_supports_sqlite() {
- "$1" -e "require('node:sqlite')" >/dev/null 2>&1
- }
- _node_is_suitable() {
- local bin="$1"
- [ -x "$bin" ] || return 1
- _node_is_app_bundle "$bin" && return 1
- _node_supports_sqlite "$bin" || return 1
- return 0
- }
- resolve_node() {
- local _candidates=()
- local _nvm_candidates=("$HOME/.nvm/versions/node"/*/bin/node)
- local i
- for (( i=${#_nvm_candidates[@]}-1; i>=0; i-- )); do
- _candidates+=("${_nvm_candidates[i]}")
- done
- _candidates+=(
- "$HOME/.volta/bin/node"
- "$HOME/.fnm/aliases/default/bin/node"
- /opt/homebrew/bin/node
- /usr/local/bin/node
- "$HOME/.local/bin/node"
- )
- if command -v node >/dev/null 2>&1; then
- _candidates+=("$(command -v node)")
- fi
- for candidate in "${_candidates[@]}"; do
- if _node_is_suitable "$candidate"; then
- _resolve_realpath "$candidate"
- return 0
- fi
- done
- return 1
- }
- # >>> managed-node-runtime >>>
- # Managed Node.js runtime + prebuilt node_modules, downloaded from OSS.
- # Everything here logs to stderr only: ensure_managed_node is captured via
- # $(...) and must print the node path — and nothing else — on stdout.
- _mn_msg() {
- if [ "${LANG_MODE:-en}" = "zh" ]; then echo "$1" >&2; else echo "$2" >&2; fi
- }
- managed_node_platform() {
- local os arch
- case "$(uname -s)" in
- Darwin) os="darwin" ;;
- Linux) os="linux" ;;
- MINGW*|MSYS*|CYGWIN*) os="win" ;;
- *)
- echo "managed node: unsupported platform $(uname -s)" >&2
- return 1 ;;
- esac
- case "$(uname -m)" in
- arm64|aarch64) arch="arm64" ;;
- x86_64|amd64) arch="x64" ;;
- *)
- echo "managed node: unsupported architecture $(uname -m)" >&2
- return 1 ;;
- esac
- if [ "$os" = "win" ] && [ "$arch" = "arm64" ]; then
- _mn_msg "managed node: win-arm64 无托管产物,回退系统 node + npm install" \
- "managed node: no win-arm64 artifact, falling back to system node + npm install"
- return 1
- fi
- if [ "$os" = "linux" ] && managed_node_is_musl; then
- _mn_msg "managed node: linux musl (Alpine) 无托管产物,回退系统 node + npm install" \
- "managed node: no linux-musl artifact, falling back to system node + npm install"
- return 1
- fi
- echo "$os $arch"
- }
- managed_node_is_musl() {
- ls /lib/ld-musl-* >/dev/null 2>&1 && return 0
- ldd --version 2>&1 | grep -qi musl && return 0
- return 1
- }
- managed_node_download() {
- # managed_node_download <url> <dest>
- # Bounded timeouts mirror the .ps1 installer (-TimeoutSec 600); without
- # them a stalled TCP connection hangs the installer indefinitely.
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL --retry 2 --connect-timeout 20 --max-time 600 "$1" -o "$2"
- elif command -v wget >/dev/null 2>&1; then
- wget -q --tries=2 --timeout=20 "$1" -O "$2"
- else
- return 1
- fi
- }
- managed_node_sha256() {
- if command -v shasum >/dev/null 2>&1; then
- shasum -a 256 "$1" | awk '{print $1}'
- elif command -v sha256sum >/dev/null 2>&1; then
- sha256sum "$1" | awk '{print $1}'
- else
- echo "managed node: neither shasum nor sha256sum available" >&2
- return 1
- fi
- }
- managed_node_verify() {
- # managed_node_verify <archive> <shasums-file> <archive-basename>
- local expected actual
- # [*]? accepts sha256sum binary-mode lines ("<hash> *<name>"), matching
- # the .ps1 installer's Test-ManagedNodeChecksum.
- expected=$(grep -E "[[:space:]][*]?${3}\$" "$2" 2>/dev/null | awk '{print $1}' | head -1)
- if [ -z "$expected" ]; then
- echo "managed node: SHASUMS256.txt has no entry for $3" >&2
- return 1
- fi
- actual=$(managed_node_sha256 "$1") || return 1
- if [ "$expected" != "$actual" ]; then
- echo "managed node: sha256 mismatch for $3 (expected $expected, got $actual)" >&2
- return 1
- fi
- return 0
- }
- managed_node_bin() {
- # managed_node_bin <node-dir> <os>
- # Prefer the bin/ layout; official Node.js win zips put node.exe at the root.
- local bin="$1/bin/node"
- [ "$2" = "win" ] && bin="$1/bin/node.exe"
- if [ -x "$bin" ]; then
- echo "$bin"
- return 0
- fi
- if [ "$2" = "win" ] && [ -x "$1/node.exe" ]; then
- echo "$1/node.exe"
- return 0
- fi
- return 1
- }
- ensure_managed_node() {
- local runtime_dir="$DATA_DIR/runtime"
- local tuple os arch
- tuple=$(managed_node_platform) || return 1
- os="${tuple% *}"; arch="${tuple#* }"
- local ext="tar.gz"
- [ "$os" = "win" ] && ext="zip"
- local archive="node-v${NODE_VERSION}-${os}-${arch}.${ext}"
- local node_dir="$runtime_dir/node-v${NODE_VERSION}-${os}-${arch}"
- local node_bin=""
- node_bin=$(managed_node_bin "$node_dir" "$os") || node_bin=""
- if [ -n "$node_bin" ] && [ "$("$node_bin" --version 2>/dev/null)" = "v${NODE_VERSION}" ]; then
- echo "$node_bin"
- return 0
- fi
- local base="${NODE_DEPS_BASE%/}/${NODE_VERSION}"
- local tmp
- tmp=$(mktemp -d) || return 1
- _mn_msg "==> 下载托管 Node.js v${NODE_VERSION} (${os}-${arch})..." \
- "==> Downloading managed Node.js v${NODE_VERSION} (${os}-${arch})..."
- if ! managed_node_download "$base/$archive" "$tmp/$archive" \
- || ! managed_node_download "$base/SHASUMS256.txt" "$tmp/SHASUMS256.txt" \
- || ! managed_node_verify "$tmp/$archive" "$tmp/SHASUMS256.txt" "$archive"; then
- rm -rf "$tmp"
- return 1
- fi
- mkdir -p "$runtime_dir"
- rm -rf "$node_dir"
- if [ "$ext" = "zip" ]; then
- if ! command -v unzip >/dev/null 2>&1 || ! unzip -q "$tmp/$archive" -d "$runtime_dir"; then
- rm -rf "$tmp" "$node_dir"
- return 1
- fi
- else
- if ! { tar --warning=no-unknown-keyword -xzf "$tmp/$archive" -C "$runtime_dir" 2>/dev/null \
- || tar -xzf "$tmp/$archive" -C "$runtime_dir"; }; then
- rm -rf "$tmp" "$node_dir"
- return 1
- fi
- fi
- rm -rf "$tmp"
- node_bin=$(managed_node_bin "$node_dir" "$os") || node_bin=""
- if [ -z "$node_bin" ]; then
- echo "managed node: extracted archive has no usable node binary under $node_dir (bin/node or node.exe)" >&2
- rm -rf "$node_dir"
- return 1
- fi
- if [ "$os" = "darwin" ] && command -v xattr >/dev/null 2>&1; then
- xattr -dr com.apple.quarantine "$node_dir" 2>/dev/null || true
- fi
- echo "$node_bin"
- }
- ensure_node_modules() {
- # ensure_node_modules <app-version> (expects PERMANENT_DIR to point at the deployed version dir)
- local app_version="${1:-latest}"
- local tuple os arch
- tuple=$(managed_node_platform) || return 1
- os="${tuple% *}"; arch="${tuple#* }"
- local modules_dir="$PERMANENT_DIR/node_modules"
- local marker="$modules_dir/.pilot-modules-version"
- local stamp="${app_version} ${os} ${arch}"
- if [ -d "$modules_dir" ] && [ "$(cat "$marker" 2>/dev/null)" = "$stamp" ]; then
- return 0
- fi
- local archive="node-modules-${os}-${arch}.tar.gz"
- local base="${NODE_MODULES_BASE%/}/${app_version}"
- local tmp
- tmp=$(mktemp -d) || return 1
- _mn_msg "==> 下载预编译 node_modules (${os}-${arch}, app v${app_version})..." \
- "==> Downloading prebuilt node_modules (${os}-${arch}, app v${app_version})..."
- if ! managed_node_download "$base/$archive" "$tmp/$archive" \
- || ! managed_node_download "$base/SHASUMS256.txt" "$tmp/SHASUMS256.txt" \
- || ! managed_node_verify "$tmp/$archive" "$tmp/SHASUMS256.txt" "$archive"; then
- rm -rf "$tmp"
- return 1
- fi
- local stage="$tmp/stage"
- mkdir -p "$stage"
- if ! { tar --warning=no-unknown-keyword -xzf "$tmp/$archive" -C "$stage" 2>/dev/null \
- || tar -xzf "$tmp/$archive" -C "$stage"; }; then
- rm -rf "$tmp"
- return 1
- fi
- if [ ! -d "$stage/node_modules" ]; then
- rm -rf "$tmp"
- echo "managed node_modules: archive does not contain node_modules/" >&2
- return 1
- fi
- echo "$stamp" > "$stage/node_modules/.pilot-modules-version"
- rm -rf "$modules_dir"
- if ! mv "$stage/node_modules" "$modules_dir"; then
- rm -rf "$tmp"
- return 1
- fi
- rm -rf "$tmp"
- return 0
- }
- run_npm() {
- # npm shipped with the managed runtime is a symlink to npm-cli.js, whose
- # `#!/usr/bin/env node` shebang resolves node through PATH. The runtime's bin dir
- # is not on PATH, so calling "$NPM_BIN" directly dies with
- # "env: node: No such file or directory" on hosts without a system node — exactly
- # the hosts the managed runtime exists for. Mirrors the .ps1 npm fallback, which
- # already prepends the node dir.
- PATH="$(dirname "$NODE_BIN"):$PATH" "$NPM_BIN" "$@"
- }
- # <<< managed-node-runtime <<<
- check_deps() {
- msg "==> 检查依赖..." "==> Checking dependencies..."
- NODE_BIN=""
- if [ "${PREFER_SYSTEM_NODE:-0}" -eq 1 ]; then
- NODE_BIN=$(resolve_node) || NODE_BIN=""
- if [ -z "$NODE_BIN" ]; then
- msg " ⚠️ 系统 Node.js 不可用或无法加载 node:sqlite(需要 22.13+ 或 23.4+),改用托管运行时" \
- " ⚠️ System Node.js is missing or cannot load node:sqlite (need 22.13+ or 23.4+); using the managed runtime"
- NODE_BIN=$(ensure_managed_node) || NODE_BIN=""
- fi
- else
- NODE_BIN=$(ensure_managed_node) || NODE_BIN=""
- if [ -z "$NODE_BIN" ]; then
- msg " ⚠️ 托管 Node.js 不可用(平台不支持或下载失败),回退系统 node" \
- " ⚠️ Managed Node.js unavailable (unsupported platform or download failed), falling back to system node"
- NODE_BIN=$(resolve_node) || NODE_BIN=""
- fi
- fi
- if [ -z "$NODE_BIN" ]; then
- msg "❌ 缺少可用的 Node.js:需要能加载 node:sqlite 的版本(22.13+ / 23.4+),或成功下载托管运行时" \
- "❌ No usable Node.js: node:sqlite must load (22.13+ / 23.4+), or the managed runtime must download"
- exit 1
- fi
- if ! _node_supports_sqlite "$NODE_BIN"; then
- local node_ver
- node_ver="$("$NODE_BIN" --version 2>/dev/null || echo unknown)"
- msg "❌ 当前 Node.js 无法加载 node:sqlite(${node_ver})。需要 22.13+ 或 23.4+(无需 --experimental-sqlite),或托管运行时。" \
- "❌ This Node.js cannot load node:sqlite (${node_ver}). Need 22.13+ or 23.4+ (unflagged), or the managed runtime."
- exit 1
- fi
- # Pin the node binary path
- mkdir -p "$DATA_DIR" 2>/dev/null || true
- echo "$NODE_BIN" > "$DATA_DIR/node-bin"
- # Derive npm from the same installation
- NPM_BIN="$(dirname "$NODE_BIN")/npm"
- if [ ! -x "$NPM_BIN" ]; then
- if command -v npm &>/dev/null; then
- NPM_BIN=$(command -v npm)
- else
- msg "❌ 缺少依赖: npm,请先安装后重试" \
- "❌ Missing dependency: npm — please install it first"
- exit 1
- fi
- fi
- if [ "$(uname)" = "Darwin" ]; then
- local sys_arch; sys_arch=$(uname -m)
- local node_arch; node_arch=$("$NODE_BIN" -e "process.stdout.write(process.arch)")
- if [ "$sys_arch" = "arm64" ] && [ "$node_arch" = "x64" ]; then
- msg "⚠️ 架构不匹配: 系统为 arm64 (Apple Silicon),但 Node.js 为 x64 (Intel)" \
- "⚠️ Architecture mismatch: system is arm64 but Node.js is x64 (Intel)"
- msg " 原生模块可能无法正常加载,建议安装 arm64 版本的 Node.js" \
- " Native modules may fail to load. Please install arm64 Node.js"
- fi
- fi
- if ! command -v curl &>/dev/null && ! command -v wget &>/dev/null; then
- msg "❌ 需要 curl 或 wget,请先安装" \
- "❌ curl or wget is required — please install one first"
- exit 1
- fi
- msg " ✅ node $("$NODE_BIN" --version) npm $(run_npm --version)" \
- " ✅ node $("$NODE_BIN" --version) npm $(run_npm --version)"
- msg " node pinned: $NODE_BIN" " node pinned: $NODE_BIN"
- echo ""
- }
- # ============================================================
- # Common: download and extract package -> sets INSTALL_SRC
- # ============================================================
- download_and_extract() {
- TMP_DIR="$(mktemp -d)"
- # TMP_DIR cleanup is handled by the caller's trap
- msg "==> 下载安装包: $PACKAGE_URL" \
- "==> Downloading: $PACKAGE_URL"
- if command -v curl &>/dev/null; then
- curl -fsSL "$PACKAGE_URL" -o "$TMP_DIR/package.tar.gz"
- else
- wget -q "$PACKAGE_URL" -O "$TMP_DIR/package.tar.gz"
- fi
- msg " ✅ 下载完成" " ✅ Downloaded"
- echo ""
- msg "==> 解压安装包..." "==> Extracting..."
- if tar --warning=no-unknown-keyword -xzf "$TMP_DIR/package.tar.gz" -C "$TMP_DIR" 2>/dev/null; then
- :
- else
- tar -xzf "$TMP_DIR/package.tar.gz" -C "$TMP_DIR"
- fi
- if [ -d "$TMP_DIR/$PACKAGE_NAME" ]; then
- INSTALL_SRC="$TMP_DIR/$PACKAGE_NAME"
- elif [ -f "$TMP_DIR/package.json" ]; then
- INSTALL_SRC="$TMP_DIR"
- else
- INSTALL_SRC=$(find "$TMP_DIR" -name "package.json" -maxdepth 2 -exec dirname {} \; | head -1 || true)
- if [ -z "$INSTALL_SRC" ]; then
- msg "❌ 解压后未找到 package.json,安装包结构异常" \
- "❌ package.json not found — unexpected package structure"
- exit 1
- fi
- fi
- msg " ✅ 解压完成" " ✅ Extracted"
- echo ""
- }
- # ============================================================
- # Agent probe: detect available agents via Node.js CLI probe
- # ============================================================
- PROBE_RESULT="[]"
- probe_agents() {
- msg "==> 探测 AI Agent..." "==> Probing AI Agents..."
- PROBE_RESULT=$("$NODE_BIN" "$INSTALL_SRC/dist/cli-probe.cjs" --installer --config-path "$DATA_DIR/config.json" 2>/dev/null) || {
- msg " ⚠️ Agent 探测失败,将跳过选择" " ⚠️ Agent probe failed, skipping selection"
- PROBE_RESULT="[]"
- return 0
- }
- local count
- 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")
- msg " ✅ 探测到 ${count} 个 Agent 定义" " ✅ Found ${count} agent definitions"
- echo ""
- }
- # ============================================================
- # Agent selection: interactive menu or --agents flag
- # ============================================================
- select_agents() {
- # --all-agents: collect every agent. Skip selection entirely and leave no
- # enabled gate in config (other agent settings survive), so pilot auto-detects
- # all agents at runtime — including ones installed after this run.
- if [ "$ALL_AGENTS" = "1" ]; then
- if [ -n "$SELECTED_AGENTS" ]; then
- msg " ⚠️ --all-agents 已启用,忽略 --agents 指定的列表" \
- " ⚠️ --all-agents is set; ignoring the --agents list"
- SELECTED_AGENTS=""
- fi
- msg " 采集全部 Agent (不写入选择,由 pilot 运行时自动探测)" \
- " Collecting all agents (no selection written; pilot auto-detects at runtime)"
- echo ""
- return 0
- fi
- if [ -n "$SELECTED_AGENTS" ]; then
- msg " 使用指定的 Agent: $SELECTED_AGENTS" " Using specified agents: $SELECTED_AGENTS"
- echo ""
- return 0
- fi
- local agent_count
- 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")
- if [ "$agent_count" = "0" ]; then
- return 0
- fi
- # Non-interactive: auto-select all detected agents
- if [ ! -t 0 ] || [ "$HOOK_INSTALL_SCOPE" = system ]; then
- SELECTED_AGENTS=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
- const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
- const detected = r.filter(a => a.detected).map(a => a.id);
- process.stdout.write(detected.join(','));
- " 2>/dev/null || true)
- msg " 自动选择已检测到的 Agent: $SELECTED_AGENTS" \
- " Auto-selected detected agents: $SELECTED_AGENTS"
- echo ""
- return 0
- fi
- # Interactive menu
- printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
- const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
- const lang = process.argv[1];
- const defaults = [];
- for (let i = 0; i < r.length; i++) {
- const a = r[i];
- const status = lang === 'zh'
- ? (a.detected ? '已检测到: ' + a.reason : '未检测到' + (a.reason ? ': ' + a.reason : ''))
- : (a.detected ? 'detected: ' + a.reason : 'not detected' + (a.reason ? ': ' + a.reason : ''));
- console.log(' [' + (i+1) + '] ' + a.displayName.padEnd(16) + '(' + status + ')');
- if (a.detected) defaults.push(i+1);
- }
- console.log('');
- if (lang === 'zh') {
- console.log(' 默认选择已检测到的 Agent: ' + defaults.join(','));
- console.log(' 输入要启用的编号 (逗号分隔),直接回车使用默认:');
- } else {
- console.log(' Default selection (detected): ' + defaults.join(','));
- console.log(' Enter numbers to enable (comma-separated), press Enter for default:');
- }
- " "$LANG_MODE"
- # Read user input (Node readline handles UTF-8 editing; normalize Chinese punctuation).
- # Prompt must go to stderr so it is visible and not captured by $().
- local select_input
- select_input=$("$NODE_BIN" -e "
- const readline = require('readline');
- const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
- rl.question(' > ', (answer) => {
- const normalized = answer.replace(/[,、;]/g, ',').trim();
- process.stdout.write(normalized);
- rl.close();
- });
- ") || {
- printf " > " >&2
- read -r select_input
- select_input=$(printf '%s' "$select_input" | sed 's/,/,/g; s/、/,/g; s/;/,/g')
- }
- # Compute final selection: empty input = detected agents, otherwise use exact input
- if [ -n "$select_input" ]; then AGENT_SELECTION_EXPLICIT=1; fi
- SELECTED_AGENTS=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
- const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
- const input = (process.argv[1] || '').replace(/[,、;]/g, ',');
- let indices;
- if (!input.trim()) {
- indices = r.map((a, i) => a.detected ? i : -1).filter(i => i >= 0);
- } else {
- indices = [...new Set(input.trim().split(/[\s,]+/).map(Number).filter(n => n >= 1 && n <= r.length))].map(n => n - 1);
- }
- const ids = indices.sort((a,b) => a-b).map(i => r[i].id);
- process.stdout.write(ids.join(','));
- " "$select_input" 2>/dev/null || true)
- if [ -n "$SELECTED_AGENTS" ]; then
- msg " 已选择: $SELECTED_AGENTS" " Selected: $SELECTED_AGENTS"
- else
- msg " 未选择任何 Agent" " No agents selected"
- fi
- echo ""
- }
- # ============================================================
- # Interactive: prompt for userId (skipped when --userId given or non-interactive)
- # ============================================================
- prompt_user_id() {
- if [ -n "$USER_ID" ]; then return 0; fi
- if [ ! -t 0 ]; then return 0; fi
- local existing_uid=""
- local config_file="$DATA_DIR/config.json"
- if [ -f "$config_file" ]; then
- existing_uid=$("$NODE_BIN" -e "
- try { const c=JSON.parse(require('fs').readFileSync(process.argv[1],'utf-8')); process.stdout.write(c.userId||''); } catch {}
- " -- "$config_file" 2>/dev/null || true)
- fi
- echo ""
- if [ -n "$existing_uid" ]; then
- msg " 当前 userId: $existing_uid" \
- " Current userId: $existing_uid"
- msg " 直接回车保留,或输入新值:" \
- " Press Enter to keep, or type a new value:"
- else
- msg " 请输入你的 userId(用于数据归属,可直接回车跳过):" \
- " Enter your userId (for data attribution, press Enter to skip):"
- fi
- printf " > "
- local input
- read -r input
- input=$(echo "$input" | tr -d '[:space:]')
- if [ -n "$input" ]; then
- USER_ID="$input"
- elif [ -n "$existing_uid" ]; then
- USER_ID="$existing_uid"
- fi
- }
- # ============================================================
- # Interactive: confirm config overwrite when key fields differ
- # ============================================================
- confirm_config_overwrite() {
- local config_file="$DATA_DIR/config.json"
- if [ ! -f "$config_file" ]; then return 0; fi
- local diffs
- diffs=$("$NODE_BIN" -e "
- const fs = require('fs');
- let old = {};
- try { old = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8')); } catch { process.exit(0); }
- const newVals = JSON.parse(process.argv[2]);
- const normalizeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean).join(',');
- const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
- const parseTypeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean);
- const uniqueTypes = list => [...new Set(list)];
- const interceptorModeFinal = newVals.interceptorMode || (old.interceptor||{}).mode || '';
- const interceptorTypesFinal = interceptorModeFinal === 'all'
- ? INTERCEPTOR_TYPE_SET.slice()
- : interceptorModeFinal === 'custom'
- ? parseTypeCsv(newVals.interceptorMode ? newVals.interceptorTypes : ((old.interceptor||{}).types||[]).join(',')).filter(t => INTERCEPTOR_TYPE_SET.indexOf(t) !== -1)
- : [];
- const maskModeFinal = newVals.maskMode || (old.mask||{}).mode || '';
- const maskTypesFinal = maskModeFinal === 'custom'
- ? parseTypeCsv(newVals.maskMode ? newVals.maskTypes : ((old.mask||{}).types||[]).join(','))
- : [];
- const coveredMaskMode = interceptorTypesFinal.length && maskModeFinal !== 'all' ? 'custom' : maskModeFinal;
- const coveredMaskTypes = coveredMaskMode === 'custom' ? uniqueTypes(maskTypesFinal.concat(interceptorTypesFinal)) : [];
- const slsModeOf = sls => {
- if (!sls) return '';
- if (sls.mode) return sls.mode;
- if (sls.apiKey) return 'apiKey';
- if (sls.accessKeyId || sls.accessKeySecret) return 'ak';
- return '';
- };
- const checks = [
- { label: 'sls.endpoint', oldVal: (old.sls||{}).endpoint||'', newVal: newVals.slsEndpoint },
- { label: 'sls.project', oldVal: (old.sls||{}).project||'', newVal: newVals.slsProject },
- { label: 'sls.logstore', oldVal: (old.sls||{}).logstore||'', newVal: newVals.slsLogstore },
- { label: 'sls.mode', oldVal: slsModeOf(old.sls), newVal: newVals.slsMode },
- { label: 'cms.licenseKey', oldVal: (old.cms||{}).licenseKey||'', newVal: newVals.cmsLicenseKey },
- { label: 'cms.endpoint', oldVal: (old.cms||{}).endpoint||'', newVal: newVals.cmsEndpoint },
- { label: 'cms.workspace', oldVal: (old.cms||{}).workspace||'', newVal: newVals.cmsWorkspace },
- { label: 'serviceNamePrefix', oldVal: old.serviceNamePrefix||'', newVal: newVals.serviceNamePrefix },
- { label: 'dashboard.port', oldVal: (old.dashboard||{}).port||'', newVal: newVals.dashboardPort ? Number(newVals.dashboardPort) : '' },
- { label: 'mask.mode', oldVal: (old.mask||{}).mode||'', newVal: coveredMaskMode },
- { label: 'mask.types', oldVal: (old.mask||{}).mode === 'custom' && Array.isArray((old.mask||{}).types) ? normalizeCsv(old.mask.types.join(',')) : '', newVal: coveredMaskTypes.join(',') },
- { label: 'mask.replacementMode', oldVal: (old.mask||{}).replacementMode||'', newVal: newVals.maskReplacementMode },
- { label: 'interceptor.mode', oldVal: (old.interceptor||{}).mode||'', newVal: newVals.interceptorMode },
- { label: 'interceptor.types', oldVal: Array.isArray((old.interceptor||{}).types) ? normalizeCsv(old.interceptor.types.join(',')) : '', newVal: normalizeCsv(newVals.interceptorTypes) },
- { 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' : '' },
- ];
- const changed = checks.filter(c => c.newVal && c.oldVal && c.newVal !== c.oldVal);
- if (!changed.length) process.exit(0);
- for (const c of changed) {
- console.log(c.label + ': ' + c.oldVal + ' -> ' + c.newVal);
- }
- " -- "$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"}' \
- "$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)
- if [ -z "$diffs" ]; then return 0; fi
- echo ""
- msg "⚠️ 以下配置将被覆盖:" "⚠️ The following config will be overwritten:"
- echo "$diffs" | while IFS= read -r line; do
- echo " $line"
- done
- if [ -t 0 ]; then
- echo ""
- msg " 确认覆盖? (y/N):" " Confirm overwrite? (y/N):"
- printf " > "
- local answer
- read -r answer
- case "$answer" in
- y|Y|yes|YES) ;;
- *)
- msg "已取消安装" "Installation cancelled"
- exit 0
- ;;
- esac
- else
- msg " (非交互模式) 继续覆盖" \
- " (non-interactive) Proceeding with overwrite"
- fi
- }
- # ============================================================
- # Common: deploy bootstrap scripts from the current version
- # ============================================================
- deploy_bootstrap_scripts() {
- local src_dir="$PERMANENT_DIR/scripts"
- local boot_dir="$HOME/.loongsuite-pilot/bin"
- mkdir -p "$boot_dir"
- cp -f "$src_dir/collector-daemon.js" "$boot_dir/"
- [ -f "$src_dir/updater-daemon.js" ] && cp -f "$src_dir/updater-daemon.js" "$boot_dir/" || true
- }
- # ============================================================
- # Common: deploy package to versions/ directory
- # ============================================================
- deploy_package() {
- local src="$1"
- local cache_dir="$HOME/.loongsuite-pilot"
- local versions_dir="$cache_dir/versions"
- local current_file="$cache_dir/current"
- local previous_file="$cache_dir/previous"
- local ver="" commit=""
- if [ -f "$src/VERSION" ]; then
- ver=$(grep '^version=' "$src/VERSION" | cut -d= -f2)
- commit=$(grep '^git_commit=' "$src/VERSION" | cut -d= -f2)
- fi
- if [ -n "$ver" ] && [ -n "$commit" ]; then
- local dir_name="${ver}_${commit}"
- local target="$versions_dir/$dir_name"
- if [ -f "$current_file" ]; then
- local old_dir
- old_dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
- if [ -n "$old_dir" ] && [ "$old_dir" != "$dir_name" ]; then
- echo "$old_dir" > "$previous_file"
- fi
- fi
- msg "==> 部署到 $target ..." "==> Deploying to $target ..."
- mkdir -p "$versions_dir"
- rm -rf "$target"
- if ! cp -r "$src" "$target"; then
- msg " ❌ 文件部署失败" " ❌ File deployment failed"
- return 1
- fi
- PERMANENT_DIR="$target"
- else
- msg "==> 部署到 $PERMANENT_DIR ..." \
- "==> Deploying to $PERMANENT_DIR ..."
- mkdir -p "$(dirname "$PERMANENT_DIR")"
- rm -rf "$PERMANENT_DIR"
- if ! cp -r "$src" "$PERMANENT_DIR"; then
- msg " ❌ 文件部署失败" " ❌ File deployment failed"
- return 1
- fi
- fi
- msg " ✅ 部署完成" " ✅ Deployed"
- echo ""
- deploy_bootstrap_scripts
- msg "==> 安装依赖..." "==> Installing dependencies..."
- local modules_ver="${ver:-${INSTALL_VERSION:-latest}}"
- if ensure_node_modules "$modules_ver"; then
- msg " ✅ 依赖安装完成(预编译 node_modules)" " ✅ Dependencies installed (prebuilt node_modules)"
- else
- msg " ⚠️ 预编译 node_modules 不可用,回退 npm install" \
- " ⚠️ Prebuilt node_modules unavailable, falling back to npm install"
- if ! (cd "$PERMANENT_DIR" && run_npm install --production --no-optional 2>&1 | tail -1); then
- msg " ❌ 依赖安装失败" " ❌ Dependency installation failed"
- return 1
- fi
- msg " ✅ 依赖安装完成" " ✅ Dependencies installed"
- fi
- echo ""
- msg "==> 部署 hook 脚本..." "==> Deploying hook scripts..."
- if [ -f "$PERMANENT_DIR/scripts/postinstall.js" ]; then
- # postinstall.js falls back to $HOME/.loongsuite-pilot when this is unset, so
- # --data-dir would otherwise put hooks/skills/plugins in the default tree while
- # the config lives elsewhere.
- # Captured because two of the three failure modes are only in the output: a per-tree
- # failure and a thrown main() both exit 0 on purpose (a non-zero exit would abort the
- # npm install fallback above), announcing themselves as "N failed asset tree(s)" and
- # "Post-install failed: <reason>" instead. 2>&1 because both go to stderr.
- postinstall_exit=0
- postinstall_out="$(LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
- "$NODE_BIN" "$PERMANENT_DIR/scripts/postinstall.js" 2>&1)" || postinstall_exit=$?
- # `if`, not `[ -n ... ] && printf`: under set -e the latter aborts the function when
- # the output is empty.
- if [ -n "$postinstall_out" ]; then
- printf '%s\n' "$postinstall_out"
- fi
- if [ "$postinstall_exit" -ne 0 ]; then
- msg " ❌ Hook 脚本部署失败 (exit=$postinstall_exit),hooks/plugins 缺失" \
- " ❌ Hook script deployment failed (exit=$postinstall_exit); hooks/plugins are missing"
- return 1
- fi
- if printf '%s' "$postinstall_out" | grep -qE "failed asset tree|Post-install failed"; then
- msg " ❌ Hook 脚本部分部署失败(见上方输出),hooks/plugins 缺失" \
- " ❌ Some hook asset trees failed to deploy (see the output above); hooks/plugins are missing"
- return 1
- fi
- msg " ✅ Hook 脚本已部署" " ✅ Hook scripts deployed"
- msg " 如使用 Codex 桌面版,首次启动需在桌面端手动信任 hooks" \
- " If using Codex desktop app, please manually trust hooks on first launch"
- else
- msg " ⚠️ postinstall.js 未找到,跳过 Hook 部署" \
- " ⚠️ postinstall.js not found, skipping hook deployment"
- fi
- echo ""
- # Write current pointer only after all deploy steps succeed
- if [ -n "$ver" ] && [ -n "$commit" ]; then
- echo "$dir_name" > "$current_file.tmp"
- mv -f "$current_file.tmp" "$current_file"
- fi
- }
- # ============================================================
- # Migrate legacy single-directory layout to versions/ layout
- # ============================================================
- migrate_legacy_layout() {
- local cache_dir="$HOME/.loongsuite-pilot"
- local current_file="$cache_dir/current"
- local legacy_dir="$cache_dir/package"
- local versions_dir="$cache_dir/versions"
- if [ -f "$current_file" ]; then
- return 0
- fi
- if [ ! -d "$legacy_dir" ] || [ ! -f "$legacy_dir/dist/index.js" ]; then
- return 0
- fi
- msg "==> 迁移旧版本目录结构..." "==> Migrating legacy directory layout..."
- local ver="" commit=""
- if [ -f "$legacy_dir/VERSION" ]; then
- ver=$(grep '^version=' "$legacy_dir/VERSION" | cut -d= -f2)
- commit=$(grep '^git_commit=' "$legacy_dir/VERSION" | cut -d= -f2)
- fi
- ver="${ver:-0.0.0}"
- commit="${commit:-legacy}"
- local dir_name="${ver}_${commit}"
- local target="$versions_dir/$dir_name"
- mkdir -p "$versions_dir"
- cp -r "$legacy_dir" "$target"
- echo "$dir_name" > "$current_file"
- PERMANENT_DIR="$target"
- msg " ✅ 已迁移到 $target" " ✅ Migrated to $target"
- echo ""
- }
- # ============================================================
- # Common: write / merge config.json
- # ============================================================
- write_config() {
- local config_file="$DATA_DIR/config.json"
- msg "==> 写入配置文件 $config_file ..." \
- "==> Writing config to $config_file ..."
- mkdir -p "$DATA_DIR"
- local excluded_workspaces_json=""
- if [ "${#EXCLUDE_WORKSPACES[@]}" -gt 0 ]; then
- excluded_workspaces_json=$("$NODE_BIN" -e 'console.log(JSON.stringify(process.argv.slice(1)))' -- "${EXCLUDE_WORKSPACES[@]}")
- fi
- printf '%s' "$PROBE_RESULT" | \
- LP_EXCLUDE_WORKSPACES="$excluded_workspaces_json" \
- LP_SLS_API_KEY="$SLS_API_KEY" \
- LP_SELECTED_AGENTS="$SELECTED_AGENTS" \
- LP_AGENT_SELECTION_EXPLICIT="$AGENT_SELECTION_EXPLICIT" \
- LP_MULTIMODAL_MODE="$MULTIMODAL_MODE" \
- LP_MULTIMODAL_SUPPORTED_AGENTS="$MULTIMODAL_SUPPORTED_AGENTS" \
- LP_DASHBOARD_PORT="$DASHBOARD_PORT" \
- LP_ENABLE_STATUS_BAR_APP="$ENABLE_STATUS_BAR_APP" \
- "$NODE_BIN" -e "
- const fs = require('fs');
- const path = '$config_file';
- let existing = {};
- try { existing = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
- const config = {
- ...existing,
- enabled: true,
- dataDir: '$DATA_DIR',
- };
- if (!config.dashboard || typeof config.dashboard !== 'object' || Array.isArray(config.dashboard)) {
- config.dashboard = {};
- }
- if (process.env.LP_EXCLUDE_WORKSPACES) {
- config.privacy = { ...config.privacy, excludeWorkspaces: JSON.parse(process.env.LP_EXCLUDE_WORKSPACES) };
- }
- const dashboardPort = process.env.LP_DASHBOARD_PORT || '';
- const enableStatusBarApp = process.env.LP_ENABLE_STATUS_BAR_APP || '';
- if (enableStatusBarApp) config.enableStatusBarApp = enableStatusBarApp === 'true';
- if (dashboardPort) config.dashboard.port = Number(dashboardPort);
- if (config.dashboard.port === undefined) config.dashboard.port = 8765;
- delete config.internal;
- if (config.userId === undefined && config['user.id'] !== undefined) {
- config.userId = config['user.id'];
- }
- delete config['user.id'];
- const slsEndpoint = '${SLS_ENDPOINT}';
- const slsProject = '${SLS_PROJECT}';
- const slsLogstore = '${SLS_LOGSTORE}';
- const slsAkId = '${SLS_AK_ID}';
- const slsAkSecret = '${SLS_AK_SECRET}';
- const slsApiKey = process.env.LP_SLS_API_KEY || '';
- const logLevel = '${LOG_LEVEL}';
- const userId = '${USER_ID}';
- if (slsEndpoint || slsProject || slsLogstore || slsApiKey) {
- config.sls = config.sls || {};
- delete config.sls.destinationOverride;
- if (slsEndpoint) {
- config.sls.endpoint = slsEndpoint;
- }
- if (slsApiKey) {
- config.sls.mode = 'apiKey';
- config.sls.apiKey = slsApiKey;
- delete config.sls.accessKeyId;
- delete config.sls.accessKeySecret;
- } else if (slsAkId && slsAkSecret) {
- config.sls.mode = 'ak';
- config.sls.accessKeyId = slsAkId;
- config.sls.accessKeySecret = slsAkSecret;
- delete config.sls.apiKey;
- } else if (slsEndpoint || slsProject || slsLogstore) {
- config.sls.mode = 'webtracking';
- delete config.sls.apiKey;
- delete config.sls.accessKeyId;
- delete config.sls.accessKeySecret;
- }
- if (slsProject && slsLogstore) {
- config.sls.project = slsProject;
- config.sls.logstore = slsLogstore;
- delete config.sls.endpoints;
- }
- }
- if (logLevel) {
- config.logLevel = logLevel;
- }
- if (userId) {
- config.userId = userId;
- delete config.identity;
- }
- const collectLog = '${COLLECT_LOG}';
- const collectTrace = '${COLLECT_TRACE}';
- const cmsLicenseKey = '${CMS_LICENSE_KEY}';
- const cmsEndpoint = '${CMS_ENDPOINT}';
- const cmsWorkspace = '${CMS_WORKSPACE}';
- const serviceNamePrefix = '${SERVICE_NAME_PREFIX}';
- const selectedAgents = process.env.LP_SELECTED_AGENTS || '';
- const allAgentsMode = '${ALL_AGENTS}';
- const multimodalMode = process.env.LP_MULTIMODAL_MODE || '';
- const maskMode = '${MASK_MODE}';
- const maskTypes = '${MASK_TYPES}';
- const maskReplacementMode = '${MASK_REPLACEMENT_MODE}';
- const interceptorMode = '${INTERCEPTOR_MODE}';
- const interceptorTypes = '${INTERCEPTOR_TYPES}';
- if (collectLog) config.collectLog = collectLog === 'true';
- if (collectTrace) config.collectTrace = collectTrace === 'true';
- if (cmsLicenseKey || cmsEndpoint || cmsWorkspace) {
- config.cms = config.cms || {};
- if (cmsLicenseKey) config.cms.licenseKey = cmsLicenseKey;
- if (cmsEndpoint) config.cms.endpoint = cmsEndpoint;
- if (cmsWorkspace) config.cms.workspace = cmsWorkspace;
- }
- if (serviceNamePrefix) config.serviceNamePrefix = serviceNamePrefix;
- if (maskMode) {
- config.mask = config.mask || {};
- config.mask.mode = maskMode;
- if (maskMode === 'custom') {
- config.mask.types = maskTypes
- .split(',')
- .map(type => type.trim())
- .filter(Boolean);
- } else {
- delete config.mask.types;
- }
- }
- if (maskReplacementMode) {
- config.mask = config.mask || {};
- config.mask.replacementMode = maskReplacementMode;
- }
- if (interceptorMode) {
- config.interceptor = config.interceptor || {};
- config.interceptor.mode = interceptorMode;
- if (interceptorMode === 'custom') {
- config.interceptor.types = interceptorTypes
- .split(',')
- .map(type => type.trim())
- .filter(Boolean);
- } else {
- delete config.interceptor.types;
- }
- }
- const INTERCEPTOR_TYPE_SET = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
- (function ensureMaskCoversInterceptor(config) {
- const interceptor = config.interceptor || {};
- const extra = interceptor.mode === 'all'
- ? INTERCEPTOR_TYPE_SET.slice()
- : interceptor.mode === 'custom' && Array.isArray(interceptor.types)
- ? interceptor.types.filter(type => INTERCEPTOR_TYPE_SET.indexOf(type) !== -1)
- : [];
- if (extra.length === 0) return;
- if ((config.mask || {}).mode === 'all') return;
- const current = (config.mask || {}).mode === 'custom' && Array.isArray((config.mask || {}).types)
- ? config.mask.types.filter(type => typeof type === 'string' && type.trim())
- : [];
- config.mask = config.mask && typeof config.mask === 'object' && !Array.isArray(config.mask)
- ? config.mask
- : {};
- config.mask.mode = 'custom';
- config.mask.types = [...new Set(current.concat(extra))];
- })(config);
- const allAgents = JSON.parse(fs.readFileSync(0, 'utf8') || '[]');
- if (allAgentsMode === '1') {
- // Clear enable gates, not metadata such as a persisted OpenClaw entry.
- for (const agent of Object.values(config.agents || {})) delete agent.enabled;
- } else if (selectedAgents) {
- config.agents = config.agents || {};
- const previousOpenclaw = config.agents.openclaw;
- const selected = selectedAgents.split(',').map(s => s.trim()).filter(Boolean);
- for (const agent of allAgents) {
- config.agents[agent.id] = config.agents[agent.id] || {};
- // A transient discovery miss is not consent to uninstall a live plugin.
- if (agent.id === 'openclaw' && !agent.detected && process.env.LP_AGENT_SELECTION_EXPLICIT !== '1'
- && previousOpenclaw !== undefined) {
- console.log('OpenClaw: detection unavailable; preserving previous enabled state and entry');
- continue;
- }
- config.agents[agent.id].enabled = selected.includes(agent.id);
- }
- }
- const openclaw = allAgents.find(agent => agent.id === 'openclaw');
- if (openclaw && openclaw.detected && openclaw.openclawCliPath
- && (allAgentsMode === '1' || (config.agents && config.agents.openclaw && config.agents.openclaw.enabled !== false))) {
- config.agents = config.agents || {};
- config.agents.openclaw = config.agents.openclaw || {};
- const previousEntry = config.agents.openclaw.cliPath;
- if (typeof previousEntry === 'string' && previousEntry !== openclaw.openclawCliPath) {
- console.log('OpenClaw: updating launch entry ' + JSON.stringify(previousEntry) + ' -> ' + JSON.stringify(openclaw.openclawCliPath));
- }
- config.agents.openclaw.cliPath = openclaw.openclawCliPath;
- }
- if (multimodalMode) {
- config.agents = config.agents || {};
- const supported = (process.env.LP_MULTIMODAL_SUPPORTED_AGENTS || '').split(',').map(s => s.trim()).filter(Boolean);
- const selected = new Set(selectedAgents.split(',').map(s => s.trim()).filter(Boolean));
- const allSupported = allAgentsMode === '1' && multimodalMode !== 'none';
- for (const id of supported) {
- if (allSupported) config.agents[id] = config.agents[id] || {};
- else if (!config.agents[id]) continue;
- if (multimodalMode === 'none') {
- delete config.agents[id].multimodal;
- continue;
- }
- const prev = (config.agents[id].multimodal && typeof config.agents[id].multimodal === 'object')
- ? config.agents[id].multimodal
- : {};
- config.agents[id].multimodal = { ...prev, uploadMode: (allSupported || selected.has(id)) ? multimodalMode : 'none' };
- }
- }
- if (multimodalMode && multimodalMode !== 'none' && slsEndpoint && slsProject && slsLogstore && slsApiKey) {
- config.multimodal = {
- storage: {
- type: 'sls',
- target: { endpoint: slsEndpoint, project: slsProject, logstore: slsLogstore },
- },
- };
- }
- fs.writeFileSync(path, JSON.stringify(config, null, 2) + '\n');
- "
- msg " ✅ 配置已写入" " ✅ Config written"
- echo ""
- }
- # ============================================================
- # Common: install/update the loongsuite-pilot service management script
- # ============================================================
- install_loongsuite_pilot_command() {
- msg "==> 安装服务管理脚本..." "==> Installing service management script..."
- local global_bin_dir="$HOME/.local/bin"
- mkdir -p "$global_bin_dir"
- local loongsuite_pilot_cmd="$global_bin_dir/loongsuite-pilot"
- cp -f "$PERMANENT_DIR/scripts/loongsuite-pilot.sh" "$loongsuite_pilot_cmd"
- chmod +x "$loongsuite_pilot_cmd"
- msg " ✅ 已安装: $loongsuite_pilot_cmd" " ✅ Installed: $loongsuite_pilot_cmd"
- # If /usr/local/bin is writable (root), create a symlink for immediate PATH access
- if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
- ln -sf "$loongsuite_pilot_cmd" /usr/local/bin/loongsuite-pilot
- msg " ✅ 已链接到 /usr/local/bin/loongsuite-pilot" " ✅ Linked to /usr/local/bin/loongsuite-pilot"
- else
- ensure_path_block() {
- local file="$1"
- if [ ! -f "$file" ]; then
- touch "$file" 2>/dev/null || return 0
- fi
- if [ ! -w "$file" ]; then
- msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
- return 0
- fi
- if grep -q '\.local/bin' "$file" 2>/dev/null; then return 0; fi
- # Ensure file ends with a newline before appending
- [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
- cat >> "$file" << 'PATHBLOCK'
- # loongsuite-pilot: add ~/.local/bin to PATH
- export PATH="$HOME/.local/bin:$PATH"
- PATHBLOCK
- msg " 已将 ~/.local/bin 添加到 PATH ($file)" \
- " Added ~/.local/bin to PATH ($file)"
- }
- case "${SHELL:-/bin/bash}" in
- */zsh)
- ensure_path_block "$HOME/.zshrc" || true
- ;;
- */bash)
- ensure_path_block "$HOME/.bashrc" || true
- # Do not create ~/.bash_profile just to add PATH. On Debian/Ubuntu
- # style accounts, its mere presence prevents bash login shells from
- # reading ~/.profile, which often sources ~/.bashrc and user aliases.
- if [ -f "$HOME/.bash_profile" ]; then
- ensure_path_block "$HOME/.bash_profile" || true
- elif [ -f "$HOME/.bash_login" ]; then
- ensure_path_block "$HOME/.bash_login" || true
- else
- ensure_path_block "$HOME/.profile" || true
- fi
- ;;
- *)
- ensure_path_block "$HOME/.bashrc" || true
- ;;
- esac
- fi
- echo ""
- # Ensure loongsuite-pilot is on PATH for the rest of this script
- export PATH="$global_bin_dir:$PATH"
- }
- # ============================================================
- # qodercli token intercept: inject/remove shell function
- # ============================================================
- _sed_inplace() {
- if [[ "$(uname)" == "Darwin" ]]; then
- sed -i '' "$@"
- else
- sed -i "$@"
- fi
- }
- # Is `needle` present INSIDE the begin/end marker region of `file`?
- # Signature checks must be scoped this way rather than grepping the whole rc
- # file: the qodercli and qoderclicn blocks both name the same wrapper script, so
- # a file-wide match lets one block vouch for the other and a stale block never
- # gets migrated. Mirrors extractMarkerBlock() in src/core/hook-watchdog.ts.
- _rc_block_contains() {
- local file="$1" begin="$2" end="$3" needle="$4"
- sed -n "/$begin/,/$end/p" "$file" 2>/dev/null | grep -qF "$needle"
- }
- inject_qodercli_token_intercept() {
- # Not selected: clean up any stale block from a prior install, then bail.
- if [ "$ALL_AGENTS" != "1" ] && ! echo "$SELECTED_AGENTS" | grep -q 'qoder'; then remove_qodercli_token_intercept; return 0; fi
- if ! command -v qodercli >/dev/null 2>&1; then return 0; fi
- local intercept_script="$DATA_DIR/hooks/qodercli-token-intercept.mjs"
- local runtime_wrapper="$DATA_DIR/hooks/qodercli-runtime-wrapper.sh"
- if [ ! -f "$intercept_script" ] || [ ! -f "$runtime_wrapper" ]; then return 0; fi
- msg "==> 配置 qodercli token 采集..." "==> Configuring qodercli token intercept..."
- _inject_to_rc() {
- local file="$1"
- if [ ! -f "$file" ]; then return 0; fi
- if [ ! -w "$file" ]; then
- msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
- return 0
- fi
- # Migrate-or-skip: our block may already be present. If it is the current
- # guard shape (signature line present) we're done; otherwise it is an
- # older released bare-function block sharing the same marker — remove it
- # so the new guarded block below replaces it (the old bare block
- # parse-errors under a user alias, which is exactly what we're fixing).
- if grep -q 'loongsuite-pilot BEGIN qodercli-intercept' "$file" 2>/dev/null; then
- if _rc_block_contains "$file" \
- 'loongsuite-pilot BEGIN qodercli-intercept' \
- 'loongsuite-pilot END qodercli-intercept' \
- 'qodercli-runtime-wrapper.sh'; then return 0; fi
- _sed_inplace '/# loongsuite-pilot BEGIN qodercli-intercept/,/# loongsuite-pilot END qodercli-intercept/d' "$file"
- fi
- [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
- # Double-quoted heredoc so $DATA_DIR expands at install time, honoring
- # --data-dir overrides. $@ is escaped to defer expansion to runtime.
- # The `if ! alias ... eval '...'` shape guards against clobbering a
- # user's own qodercli alias/function AND avoids a parse error: a bare
- # qodercli() token would fail to parse under an active alias (interactive
- # shells expand aliases at parse time, before the guard runs), so the
- # definition is deferred behind eval. Keep byte-identical to the
- # watchdog's blockFn (src/core/hook-watchdog.ts).
- cat >> "$file" << INTERCEPTBLOCK
- # loongsuite-pilot BEGIN qodercli-intercept
- if ! alias qodercli >/dev/null 2>&1 && ! typeset -f qodercli >/dev/null 2>&1; then
- eval 'qodercli() { "$DATA_DIR/hooks/qodercli-runtime-wrapper.sh" "\$@"; }'
- fi
- # loongsuite-pilot END qodercli-intercept
- INTERCEPTBLOCK
- msg " ✅ 已写入 $file (请执行 source $file 或打开新终端)" \
- " ✅ Written to $file (run: source $file or open a new terminal)"
- }
- case "${SHELL:-/bin/bash}" in
- */zsh) _inject_to_rc "$HOME/.zshrc" ;;
- */bash) _inject_to_rc "$HOME/.bashrc" ;;
- *) _inject_to_rc "$HOME/.bashrc" ;;
- esac
- # If the user already defines their own `qodercli`, our guard skipped the
- # wrapper (to avoid clobbering it), so collection won't run. Tell them how
- # to opt in, since there is otherwise no signal explaining the silence.
- if _rc_user_override_present qodercli \
- 'loongsuite-pilot BEGIN qodercli-intercept' \
- 'loongsuite-pilot END qodercli-intercept'; then
- msg " ⚠️ 检测到你已自定义 qodercli(alias/function),为避免覆盖,采集未启用。" \
- " ⚠️ Detected your own 'qodercli' (alias/function); collection is disabled to avoid clobbering it."
- msg " 如需启用采集,请让你的定义调用: $runtime_wrapper" \
- " To enable collection, have your definition call: $runtime_wrapper"
- fi
- echo ""
- }
- remove_qodercli_token_intercept() {
- for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
- if [ -f "$file" ] && grep -q 'loongsuite-pilot BEGIN qodercli-intercept' "$file" 2>/dev/null; then
- _sed_inplace '/# loongsuite-pilot BEGIN qodercli-intercept/,/# loongsuite-pilot END qodercli-intercept/d' "$file"
- msg " 已清理 qodercli token intercept ($file)" \
- " Cleaned up qodercli token intercept ($file)"
- fi
- done
- }
- # The CN line gets its own function rather than sharing the one above: that
- # block's exact bytes are part of a released idempotency contract (the watchdog
- # greps for them), so it is left untouched. Only the marker and the flavor
- # variable differ here — the wrapper and preload script are the same assets.
- inject_qoderclicn_token_intercept() {
- # Not selected: clean up any stale block from a prior install, then bail.
- if [ "$ALL_AGENTS" != "1" ] && ! echo "$SELECTED_AGENTS" | grep -q 'qoder-cn'; then remove_qoderclicn_token_intercept; return 0; fi
- if ! command -v qoderclicn >/dev/null 2>&1; then return 0; fi
- local intercept_script="$DATA_DIR/hooks/qodercli-token-intercept.mjs"
- local runtime_wrapper="$DATA_DIR/hooks/qodercli-runtime-wrapper.sh"
- if [ ! -f "$intercept_script" ] || [ ! -f "$runtime_wrapper" ]; then return 0; fi
- msg "==> 配置 qoderclicn token 采集..." "==> Configuring qoderclicn token intercept..."
- _inject_cn_to_rc() {
- local file="$1"
- if [ ! -f "$file" ]; then return 0; fi
- if [ ! -w "$file" ]; then
- msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
- return 0
- fi
- # Migrate-or-skip, same shape as the qodercli block: the signature is the
- # flavor assignment, since the wrapper name cannot tell the two apart.
- if grep -q 'loongsuite-pilot BEGIN qoderclicn-intercept' "$file" 2>/dev/null; then
- if _rc_block_contains "$file" \
- 'loongsuite-pilot BEGIN qoderclicn-intercept' \
- 'loongsuite-pilot END qoderclicn-intercept' \
- 'LOONGSUITE_QODERCLI_FLAVOR=qoderclicn'; then return 0; fi
- _sed_inplace '/# loongsuite-pilot BEGIN qoderclicn-intercept/,/# loongsuite-pilot END qoderclicn-intercept/d' "$file"
- fi
- [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
- # Double-quoted heredoc so $DATA_DIR expands at install time. $@ is
- # escaped to defer expansion to runtime. Keep byte-identical to the
- # watchdog's blockFn (src/core/hook-watchdog.ts, id qoderclicn-rc).
- cat >> "$file" << INTERCEPTBLOCK
- # loongsuite-pilot BEGIN qoderclicn-intercept
- if ! alias qoderclicn >/dev/null 2>&1 && ! typeset -f qoderclicn >/dev/null 2>&1; then
- eval 'qoderclicn() { LOONGSUITE_QODERCLI_FLAVOR=qoderclicn "$DATA_DIR/hooks/qodercli-runtime-wrapper.sh" "\$@"; }'
- fi
- # loongsuite-pilot END qoderclicn-intercept
- INTERCEPTBLOCK
- msg " ✅ 已写入 $file (请执行 source $file 或打开新终端)" \
- " ✅ Written to $file (run: source $file or open a new terminal)"
- }
- case "${SHELL:-/bin/bash}" in
- */zsh) _inject_cn_to_rc "$HOME/.zshrc" ;;
- */bash) _inject_cn_to_rc "$HOME/.bashrc" ;;
- *) _inject_cn_to_rc "$HOME/.bashrc" ;;
- esac
- if _rc_user_override_present qoderclicn \
- 'loongsuite-pilot BEGIN qoderclicn-intercept' \
- 'loongsuite-pilot END qoderclicn-intercept'; then
- msg " ⚠️ 检测到你已自定义 qoderclicn(alias/function),为避免覆盖,采集未启用。" \
- " ⚠️ Detected your own 'qoderclicn' (alias/function); collection is disabled to avoid clobbering it."
- msg " 如需启用采集,请让你的定义调用: LOONGSUITE_QODERCLI_FLAVOR=qoderclicn $runtime_wrapper" \
- " To enable collection, have your definition call: LOONGSUITE_QODERCLI_FLAVOR=qoderclicn $runtime_wrapper"
- fi
- echo ""
- }
- remove_qoderclicn_token_intercept() {
- for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
- if [ -f "$file" ] && grep -q 'loongsuite-pilot BEGIN qoderclicn-intercept' "$file" 2>/dev/null; then
- _sed_inplace '/# loongsuite-pilot BEGIN qoderclicn-intercept/,/# loongsuite-pilot END qoderclicn-intercept/d' "$file"
- msg " 已清理 qoderclicn token intercept ($file)" \
- " Cleaned up qoderclicn token intercept ($file)"
- fi
- done
- }
- # Restore app defaults without requiring the old wrapper, app, or agent selection to exist.
- retire_qoderwork_runtime_overrides() {
- if [ "$(uname)" != "Darwin" ]; then return 0; fi
- local plist_path
- for plist_path in \
- "$HOME/Library/LaunchAgents/com.loongsuite-pilot.qoderwork-env.plist" \
- "$HOME/Library/LaunchAgents/com.loongsuite-pilot.qwenworkcn-env.plist"; do
- if [ -f "$plist_path" ]; then
- launchctl unload "$plist_path" 2>/dev/null || true
- rm -f "$plist_path"
- fi
- done
- local env_name current_runtime
- for env_name in QW_QODER_WORKER_RUNTIME_PATH QODER_WORKER_RUNTIME_PATH; do
- current_runtime=$(launchctl getenv "$env_name" 2>/dev/null || true)
- if [ "$current_runtime" = "$DATA_DIR/hooks/qoderwork-runtime-wrapper.mjs" ] || printf '%s' "$current_runtime" | grep -q 'loongsuite-pilot'; then
- launchctl unsetenv "$env_name"
- msg " 已清理 $env_name" " Cleaned up $env_name"
- fi
- done
- }
- # ============================================================
- # Claude Code fetch intercept: inject/remove shell function
- #
- # Why a shell wrapper instead of ~/.claude/settings.json env:
- # Claude Code is a Bun-compiled binary. Bun reads BUN_OPTIONS at runtime
- # startup (before any JS executes), so settings.json env values are too
- # late — they only affect Claude Code's child processes, not the Bun
- # preload of the main process. A shell wrapper that sets BUN_OPTIONS
- # before invoking `claude` is the only reliable injection point.
- #
- # The wrapper prepends our preload but preserves any existing BUN_OPTIONS
- # the user (or qodercli wrapper, or launchd setenv) may have set.
- # ============================================================
- # Detect a user-defined <cli> alias/function OUTSIDE our managed block.
- # $1=cli name $2=BEGIN marker substring $3=END marker substring
- # Returns 0 (true) when found. Our injected wrapper's `if ! alias ...` guard
- # intentionally skips such users to avoid clobbering their setup — which means
- # collection is silently off for them. This lets the installer surface a
- # one-time, actionable hint at install time (rc is sourced too often to warn on
- # every shell). Heuristic: scans common rc files with our block stripped; misses
- # aliases defined in files those rc's source.
- _rc_user_override_present() {
- local cli="$1" begin="$2" end="$3" file
- for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
- [ -f "$file" ] || continue
- if sed "/$begin/,/$end/d" "$file" 2>/dev/null \
- | grep -Eq "^[[:space:]]*(alias[[:space:]]+$cli=|(function[[:space:]]+)?$cli[[:space:]]*\(\)|function[[:space:]]+$cli([[:space:]]|\{|\$))"; then
- return 0
- fi
- done
- return 1
- }
- inject_claude_code_fetch_intercept() {
- # Not selected: clean up any stale block from a prior install, then bail.
- if [ "$ALL_AGENTS" != "1" ] && ! echo "$SELECTED_AGENTS" | grep -q 'claude-code'; then remove_claude_code_fetch_intercept; return 0; fi
- if ! command -v claude >/dev/null 2>&1; then return 0; fi
- local intercept_script="$DATA_DIR/hooks/claude-code-fetch-intercept.mjs"
- if [ ! -f "$intercept_script" ]; then return 0; fi
- msg "==> 配置 claude-code fetch 拦截..." "==> Configuring claude-code fetch intercept..."
- _inject_to_rc() {
- local file="$1"
- if [ ! -f "$file" ]; then return 0; fi
- if [ ! -w "$file" ]; then
- msg " ⚠️ $file 不可写,跳过" " ⚠️ $file is not writable, skipping"
- return 0
- fi
- # Migrate-or-skip: our block may already be present. If it is the current
- # guard shape (signature line present) we're done; otherwise it is an
- # older released bare-function block sharing the same marker — remove it
- # so the new guarded block below replaces it (the old bare block
- # parse-errors under a user alias, which is exactly what we're fixing).
- if grep -q 'loongsuite-pilot BEGIN claude-code-intercept' "$file" 2>/dev/null; then
- if grep -qF 'if ! alias claude >/dev/null 2>&1' "$file"; then return 0; fi
- _sed_inplace '/# loongsuite-pilot BEGIN claude-code-intercept/,/# loongsuite-pilot END claude-code-intercept/d' "$file"
- fi
- [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
- # Double-quoted heredoc so $DATA_DIR expands at install time, honoring
- # --data-dir overrides. Other refs (${BUN_OPTIONS}, $@) are escaped to
- # defer expansion until the wrapper actually runs in the user's shell.
- # The `if ! alias ... eval '...'` shape guards against clobbering a
- # user's own claude alias/function (e.g. a proxy+flags alias) AND avoids
- # a parse error: a bare claude() token would fail to parse under an
- # active alias (interactive shells expand aliases at parse time, before
- # the guard runs), so the definition is deferred behind eval. Keep
- # byte-identical to the watchdog's blockFn (src/core/hook-watchdog.ts).
- cat >> "$file" << INTERCEPTBLOCK
- # loongsuite-pilot BEGIN claude-code-intercept
- if ! alias claude >/dev/null 2>&1 && ! typeset -f claude >/dev/null 2>&1; then
- eval 'claude() { BUN_OPTIONS="--preload=$DATA_DIR/hooks/claude-code-fetch-intercept.mjs \${BUN_OPTIONS}" command claude "\$@"; }'
- fi
- # loongsuite-pilot END claude-code-intercept
- INTERCEPTBLOCK
- msg " ✅ 已写入 $file (请执行 source $file 或打开新终端)" \
- " ✅ Written to $file (run: source $file or open a new terminal)"
- }
- case "${SHELL:-/bin/bash}" in
- */zsh) _inject_to_rc "$HOME/.zshrc" ;;
- */bash) _inject_to_rc "$HOME/.bashrc" ;;
- *) _inject_to_rc "$HOME/.bashrc" ;;
- esac
- # If the user already defines their own `claude`, our guard skipped the
- # wrapper (to avoid clobbering it), so collection won't run. Tell them how
- # to opt in, since there is otherwise no signal explaining the silence.
- if _rc_user_override_present claude \
- 'loongsuite-pilot BEGIN claude-code-intercept' \
- 'loongsuite-pilot END claude-code-intercept'; then
- msg " ⚠️ 检测到你已自定义 claude(alias/function),为避免覆盖,采集未启用。" \
- " ⚠️ Detected your own 'claude' (alias/function); collection is disabled to avoid clobbering it."
- msg " 如需启用采集,请在你的 claude 定义中加入: BUN_OPTIONS=\"--preload=$DATA_DIR/hooks/claude-code-fetch-intercept.mjs \${BUN_OPTIONS}\"" \
- " To enable collection, add to your claude definition: BUN_OPTIONS=\"--preload=$DATA_DIR/hooks/claude-code-fetch-intercept.mjs \${BUN_OPTIONS}\""
- fi
- echo ""
- }
- # Remove only the Pilot-owned Copilot startup block. Native telemetry files are data.
- remove_copilot_plugin() {
- local copilot_home="$HOME/.copilot"
- [ -d "$copilot_home" ] || return 0
- local node_bin="${NODE_BIN:-}" helper="" version="" cache="$HOME/.loongsuite-pilot"
- if [ ! -x "$node_bin" ] && [ -f "$cache/node-bin" ]; then
- node_bin=$(tr -d '\r\n' < "$cache/node-bin")
- fi
- if [ ! -x "$node_bin" ]; then node_bin=$(command -v node) || node_bin=""; fi
- if [ -f "$cache/current" ]; then version=$(tr -d '\r\n' < "$cache/current"); fi
- local candidate
- for candidate in "$cache/versions/$version/dist/copilot-cleanup.cjs" "${PERMANENT_DIR:-$cache/package}/dist/copilot-cleanup.cjs"; do
- if [ -f "$candidate" ]; then helper="$candidate"; break; fi
- done
- if [ -z "$node_bin" ] || [ -z "$helper" ]; then
- echo "Copilot cleanup skipped: safe Node JSONC helper unavailable; config and plugin assets preserved" >&2
- return 0
- fi
- if ! "$node_bin" "$helper" "$copilot_home"; then
- echo "Copilot cleanup incomplete; config and plugin assets preserved for retry" >&2
- fi
- }
- remove_copilot_otel_environment() {
- local file
- for file in "$HOME/.bashrc" "$HOME/.zshrc"; do
- [ -f "$file" ] || continue
- local tmp="${file}.pilot-copilot-$$.tmp"
- if sed '/^# >>> loongsuite-pilot copilot otel >>>$/,/^# <<< loongsuite-pilot copilot otel <<<$/{d;}' "$file" > "$tmp"; then
- cat "$tmp" > "$file"
- fi
- rm -f "$tmp"
- done
- rm -f "$DATA_DIR/state/copilot/otel-enabled"
- }
- remove_claude_code_fetch_intercept() {
- for file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
- if [ -f "$file" ] && grep -q 'loongsuite-pilot BEGIN claude-code-intercept' "$file" 2>/dev/null; then
- _sed_inplace '/# loongsuite-pilot BEGIN claude-code-intercept/,/# loongsuite-pilot END claude-code-intercept/d' "$file"
- msg " 已清理 claude-code fetch intercept ($file)" \
- " Cleaned up claude-code fetch intercept ($file)"
- fi
- done
- }
- # ============================================================
- # Common: read VERSION file fields
- # ============================================================
- get_installed_version() {
- local cache_dir="$HOME/.loongsuite-pilot"
- local current_file="$cache_dir/current"
- local versions_dir="$cache_dir/versions"
- if [ -f "$current_file" ]; then
- local dir
- dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
- if [ -n "$dir" ] && [ -f "$versions_dir/$dir/VERSION" ]; then
- grep '^version=' "$versions_dir/$dir/VERSION" | cut -d= -f2
- return 0
- fi
- fi
- local vf="$PERMANENT_DIR/VERSION"
- if [ -f "$vf" ]; then
- grep '^version=' "$vf" | cut -d= -f2
- else
- echo ""
- fi
- }
- get_version_from_dir() {
- local vf="$1/VERSION"
- if [ -f "$vf" ]; then
- grep '^version=' "$vf" | cut -d= -f2
- else
- echo ""
- fi
- }
- get_commit_from_dir() {
- local vf="$1/VERSION"
- if [ -f "$vf" ]; then
- grep '^git_commit=' "$vf" | cut -d= -f2
- else
- echo ""
- fi
- }
- show_version_info() {
- local dir="$1"
- local vf="$dir/VERSION"
- if [ -f "$vf" ]; then
- local v; v=$(grep '^version=' "$vf" | cut -d= -f2)
- local c; c=$(grep '^git_commit=' "$vf" | cut -d= -f2)
- local t; t=$(grep '^build_time=' "$vf" | cut -d= -f2)
- echo "v${v} (${c}, ${t})"
- else
- echo "unknown"
- fi
- }
- # ============================================================
- # Common: print summary
- # ============================================================
- # ============================================================
- # Remove legacy Claude OTel plugin
- # ============================================================
- remove_otel_plugin() {
- local OTEL_CLAUDE_DIR="$HOME/.cache/opentelemetry.instrumentation.claude"
- # Prevent NODE_OPTIONS --require intercept.js from breaking node commands
- # after the Claude plugin directory (and intercept.js) is deleted
- unset NODE_OPTIONS 2>/dev/null || true
- if [ -f "$OTEL_CLAUDE_DIR/package/scripts/uninstall.sh" ]; then
- bash "$OTEL_CLAUDE_DIR/package/scripts/uninstall.sh" 2>/dev/null || true
- msg " ✅ Claude Code 插件 hooks 和 alias 已清理" \
- " ✅ Claude Code plugin hooks and alias cleaned"
- else
- for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.bash_profile"; do
- [ -f "$rc" ] || continue
- if grep -q "# BEGIN otel-claude-hook" "$rc" 2>/dev/null; then
- sed -i.bak '/# BEGIN otel-claude-hook/,/# END otel-claude-hook/d' "$rc"
- rm -f "${rc}.bak"
- fi
- if grep -q "# BEGIN otel-claude-hook-env" "$rc" 2>/dev/null; then
- sed -i.bak '/# BEGIN otel-claude-hook-env/,/# END otel-claude-hook-env/d' "$rc"
- rm -f "${rc}.bak"
- fi
- done
- msg " ✅ claude alias 已清理" " ✅ claude alias cleaned"
- # Clean settings.json hooks (fallback when uninstall.sh is unavailable)
- local claude_settings="$HOME/.claude/settings.json"
- if [ -f "$claude_settings" ] && grep -qE "otel-claude-hook|hook-entry\.sh" "$claude_settings" 2>/dev/null && command -v node &>/dev/null; then
- node -e "
- const fs = require('fs');
- const f = process.argv[1];
- const isOurs = c => c.includes('otel-claude-hook') || c.includes('hook-entry.sh');
- try {
- const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
- if (d && d.hooks) {
- for (const ev of Object.keys(d.hooks)) {
- if (!Array.isArray(d.hooks[ev])) continue;
- d.hooks[ev] = d.hooks[ev].map(m => {
- if (!Array.isArray(m.hooks)) return m;
- m.hooks = m.hooks.filter(h => !(h.command && isOurs(h.command)));
- return m.hooks.length > 0 ? m : null;
- }).filter(Boolean);
- if (d.hooks[ev].length === 0) delete d.hooks[ev];
- }
- if (Object.keys(d.hooks).length === 0) delete d.hooks;
- fs.writeFileSync(f, JSON.stringify(d, null, 2) + '\n');
- }
- } catch {}
- " "$claude_settings" 2>/dev/null || true
- msg " ✅ settings.json hooks 已清理" " ✅ settings.json hooks cleaned"
- fi
- fi
- local otel_config="$HOME/.claude/otel-config.json"
- if [ -f "$otel_config" ] && command -v node &>/dev/null; then
- node -e "
- const fs = require('fs');
- try {
- const cfg = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8'));
- delete cfg.log_enabled;
- delete cfg.log_dir;
- delete cfg.log_filename_format;
- fs.writeFileSync(process.argv[1], JSON.stringify(cfg, null, 2) + '\n');
- } catch {}
- " "$otel_config" 2>/dev/null || true
- fi
- if [ -d "$OTEL_CLAUDE_DIR" ]; then
- if [ "$PURGE" -eq 1 ]; then
- rm -rf "$OTEL_CLAUDE_DIR"
- msg " ✅ 插件目录已完全删除 (--purge): $OTEL_CLAUDE_DIR" \
- " ✅ Plugin directory fully removed (--purge): $OTEL_CLAUDE_DIR"
- else
- find "$OTEL_CLAUDE_DIR" -maxdepth 1 \
- ! -name sessions \
- ! -name "$(basename "$OTEL_CLAUDE_DIR")" \
- -exec rm -rf {} + 2>/dev/null || true
- msg " ✅ 插件文件已删除(sessions/ 已保留)" \
- " ✅ Plugin files removed (sessions/ preserved)"
- fi
- fi
- }
- print_summary() {
- local action="$1" # install / upgrade
- local config_file="$DATA_DIR/config.json"
- echo "============================================================"
- local ver; ver=$(show_version_info "$PERMANENT_DIR")
- case "$action" in
- install)
- msg "✅ 安装完成!版本: $ver" "✅ Installation complete! Version: $ver" ;;
- upgrade)
- msg "✅ 升级完成!版本: $ver" "✅ Upgrade complete! Version: $ver" ;;
- esac
- echo ""
- msg "配置文件: $config_file" "Config file: $config_file"
- msg "数据目录: $DATA_DIR" "Data directory: $DATA_DIR"
- msg "Hook 目录: $DATA_DIR/hooks" "Hooks directory: $DATA_DIR/hooks"
- echo ""
- if [ -n "$SLS_ENDPOINT" ]; then
- msg "SLS 后端: $SLS_ENDPOINT" "SLS backend: $SLS_ENDPOINT"
- [ -n "$SLS_PROJECT" ] && msg " 项目: $SLS_PROJECT" " Project: $SLS_PROJECT"
- [ -n "$SLS_LOGSTORE" ] && msg " 日志库: $SLS_LOGSTORE" " Logstore: $SLS_LOGSTORE"
- echo ""
- fi
- msg "命令:" "Commands:"
- echo " loongsuite-pilot status # 查看状态 / Status"
- echo " loongsuite-pilot info # 版本与配置 / Version & config"
- echo "============================================================"
- }
- # >>> pilot-stop-for-deploy >>>
- # Overlay `install` used to SIGTERM only the collector pid file. The updater
- # stayed up, and gcOldVersions() deletes any versions/<dir> that is not
- # current/previous -- including the directory this deploy just copied, before
- # current is published. installer-opensource.sh writes current after
- # node_modules + postinstall, so that window is minutes. `loongsuite-pilot stop`
- # unloads LaunchAgent / disables systemd (autostart_remove) so neither process
- # comes back mid-deploy. That is the Unix counterpart of Disable-ScheduledTask.
- #
- # stop deletes the unit files. restore_pilot_after_deploy (EXIT trap) is the
- # counterpart of Enable-ScheduledTask in finally: it re-registers autostart
- # via start. Container installs must not start a daemon in the build layer.
- #
- # Fresh install has no CLI yet. Fall back to both pid files so a leftover
- # collector or updater still goes down.
- # All CLI after stop must go through run_pilot_cli so --data-dir matches.
- PILOT_HELD_FOR_DEPLOY=0
- resolve_pilot_cli() {
- if command -v loongsuite-pilot &>/dev/null; then
- command -v loongsuite-pilot
- elif [ -f "$HOME/.local/bin/loongsuite-pilot" ]; then
- printf '%s\n' "$HOME/.local/bin/loongsuite-pilot"
- fi
- }
- run_pilot_cli() {
- local cli
- cli="$(resolve_pilot_cli)"
- [ -n "$cli" ] || return 1
- # deploy_package writes versions/current under $HOME/.loongsuite-pilot
- # (the CLI cache default). Do not point CACHE_DIR at DATA_DIR.
- LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
- "$cli" "$@"
- }
- stop_one_pilot_pid_file() {
- local pid_file="$1"
- [ -f "$pid_file" ] || return 0
- local old_pid
- old_pid=$(cat "$pid_file")
- if kill -0 "$old_pid" 2>/dev/null; then
- kill "$old_pid" 2>/dev/null || true
- local count=0
- while kill -0 "$old_pid" 2>/dev/null && [ $count -lt 10 ]; do
- sleep 1
- count=$((count + 1))
- done
- if kill -0 "$old_pid" 2>/dev/null; then
- kill -9 "$old_pid" 2>/dev/null || true
- fi
- rm -f "$pid_file"
- else
- rm -f "$pid_file"
- fi
- }
- stop_pilot_for_deploy() {
- PILOT_HELD_FOR_DEPLOY=0
- local cli
- cli="$(resolve_pilot_cli)"
- if [ -z "$cli" ] && [ ! -f "$DATA_DIR/loongsuite-pilot.pid" ] && [ ! -f "$DATA_DIR/loongsuite-pilot-updater.pid" ]; then
- return 0
- fi
- msg "==> 停止服务..." "==> Stopping service..."
- if [ -n "$cli" ]; then
- PILOT_HELD_FOR_DEPLOY=1
- if ! run_pilot_cli stop; then
- msg " ⚠️ 无法停止服务,覆盖安装期间 updater 可能仍会 GC" \
- " ⚠️ Could not stop the service; updater may still GC during this overlay"
- fi
- fi
- # Leftovers: no CLI on PATH, or an updater the CLI did not track.
- stop_one_pilot_pid_file "$DATA_DIR/loongsuite-pilot.pid"
- stop_one_pilot_pid_file "$DATA_DIR/loongsuite-pilot-updater.pid"
- echo ""
- }
- restore_pilot_after_deploy() {
- [ "${PILOT_HELD_FOR_DEPLOY:-0}" -eq 1 ] || return 0
- [ "${INSTALL_MODE:-host}" = "container" ] && return 0
- PILOT_HELD_FOR_DEPLOY=0
- if ! run_pilot_cli start; then
- msg " ⚠️ 无法恢复自启,请手动运行: loongsuite-pilot start" \
- " ⚠️ Could not restore autostart, run manually: loongsuite-pilot start"
- fi
- }
- # <<< pilot-stop-for-deploy <<<
- # ============================================================
- # CMD: install
- # ============================================================
- reject_multi_sls_config() {
- local config_file="$DATA_DIR/config.json"
- [ -f "$config_file" ] || return 0
- local status
- if "$NODE_BIN" -e '
- const fs = require("fs");
- try {
- const config = JSON.parse(fs.readFileSync(process.argv[1], "utf8").replace(/^\uFEFF/, ""));
- process.exit(Array.isArray(config?.sls) ? 12 : 0);
- } catch { process.exit(13); }
- ' "$config_file"; then
- return 0
- else
- status=$?
- fi
- if [ "$status" -eq 12 ]; then
- msg "❌ 配置包含多个 SLS flusher;安装器不支持修改,请手动编辑 config.json" \
- "❌ Multiple SLS flushers found; the installer cannot modify them. Edit config.json manually." >&2
- else
- msg "❌ 无法检查现有 config.json,请检查文件后重试" \
- "❌ Cannot inspect existing config.json; check the file and retry." >&2
- fi
- return 1
- }
- apply_installation_scope() {
- [ -n "$HOOK_INSTALL_SCOPE" ] || return 0
- local scope_args=(hook install --scope "$HOOK_INSTALL_SCOPE" --json)
- if [ -n "$SELECTED_AGENTS" ]; then scope_args+=(--agents "$SELECTED_AGENTS"); fi
- if ! run_pilot_cli "${scope_args[@]}"; then
- # A partial registration can require recovery. Keep its runtime and
- # leave the collector stopped instead of the EXIT trap starting it.
- PILOT_HELD_FOR_DEPLOY=0
- msg "❌ Hook 安装未完成;已保留运行文件,请修复后重试 hook install" \
- "❌ Hook installation incomplete; runtime retained. Resolve the error and retry hook install." >&2
- return 1
- fi
- }
- cmd_install() {
- msg "==> 开始安装 $PACKAGE_NAME ..." \
- "==> Installing $PACKAGE_NAME ..."
- echo ""
- validate_install_user
- check_deps
- reject_multi_sls_config
- # Migrate legacy layout if needed
- migrate_legacy_layout
- # Check if already installed
- local cur_ver; cur_ver=$(get_installed_version)
- if [ -n "$cur_ver" ]; then
- msg "⚠️ 检测到已安装版本 v${cur_ver},将执行重新安装" \
- "⚠️ Existing installation v${cur_ver} detected, re-installing"
- echo ""
- fi
- # Stop collector AND updater, and unload launchd / disable systemd so GC
- # cannot delete the in-flight versions dir. See stop_pilot_for_deploy.
- # Arm restore before stop: autostart_remove is not reversible if we die
- # between stop and trap.
- trap 'restore_pilot_after_deploy; rm -rf "${TMP_DIR:-}"' EXIT
- stop_pilot_for_deploy
- download_and_extract
- probe_agents
- select_agents
- prompt_user_id
- confirm_config_overwrite
- # set -e would end the install here anyway; saying why beats an exit code on its own.
- if ! deploy_package "$INSTALL_SRC"; then
- echo ""
- msg "❌ 安装中止:hook 脚本部署失败,请检查上方输出后重试" \
- "❌ Install aborted: hook script deployment failed; check the output above and retry"
- exit 1
- fi
- write_config
- install_loongsuite_pilot_command
- retire_qoderwork_runtime_overrides
- inject_qodercli_token_intercept
- inject_qoderclicn_token_intercept
- inject_claude_code_fetch_intercept
- apply_installation_scope
- msg "==> 启动服务..." "==> Starting service..."
- if run_pilot_cli start; then
- sleep 2
- local _status_out
- _status_out="$(run_pilot_cli status 2>/dev/null || true)"
- if echo "$_status_out" | grep -q "is running"; then
- PILOT_HELD_FOR_DEPLOY=0
- msg " ✅ 服务已启动" " ✅ Service started"
- else
- msg " ⚠️ 服务可能尚未就绪,请检查: loongsuite-pilot status" \
- " ⚠️ Service may not be ready. Check: loongsuite-pilot status"
- fi
- else
- msg " ⚠️ 服务启动失败,请手动运行: loongsuite-pilot start" \
- " ⚠️ Service failed to start, run manually: loongsuite-pilot start"
- fi
- echo ""
- print_summary "install"
- }
- # ============================================================
- # CMD: upgrade
- # ============================================================
- cmd_upgrade() {
- msg "==> 开始升级 $PACKAGE_NAME ..." \
- "==> Upgrading $PACKAGE_NAME ..."
- echo ""
- validate_install_user
- # Migrate legacy layout if needed
- migrate_legacy_layout
- # Must have an existing installation
- local old_ver; old_ver=$(get_installed_version)
- if [ -z "$old_ver" ]; then
- msg "❌ 未检测到已安装的 loongsuite-pilot,请先执行 install" \
- "❌ No existing installation found. Please run install first."
- exit 1
- fi
- msg " 当前版本: ${old_ver:-unknown}" " Current version: ${old_ver:-unknown}"
- echo ""
- check_deps
- trap 'restore_pilot_after_deploy; rm -rf "${TMP_DIR:-}"' EXIT
- download_and_extract
- local new_ver; new_ver=$(get_version_from_dir "$INSTALL_SRC")
- local new_commit; new_commit=$(get_commit_from_dir "$INSTALL_SRC")
- local old_commit; old_commit=$(get_commit_from_dir "$PERMANENT_DIR")
- if [ -n "$new_ver" ] && [ "$new_ver" = "$old_ver" ] && [ "$new_commit" = "$old_commit" ]; then
- msg "✅ 已是最新版本 v${new_ver} (${new_commit}),无需升级" \
- "✅ Already at latest version v${new_ver} (${new_commit}), nothing to do"
- exit 0
- fi
- msg " 新版本: ${new_ver:-unknown} (${new_commit:-unknown})" \
- " New version: ${new_ver:-unknown} (${new_commit:-unknown})"
- echo ""
- stop_pilot_for_deploy
- # Deploy new version to versions/<ver>_<commit>/
- # Old version stays untouched; deploy_package writes current/previous pointers
- if ! deploy_package "$INSTALL_SRC"; then
- echo ""
- msg "⚠️ 部署失败,正在回滚到旧版本..." \
- "⚠️ Deployment failed, rolling back to old version..."
- local _rollback_ok=1
- run_pilot_cli rollback 2>/dev/null || _rollback_ok=0
- if [ "$_rollback_ok" -eq 1 ]; then
- if run_pilot_cli start; then
- PILOT_HELD_FOR_DEPLOY=0
- else
- _rollback_ok=0
- fi
- fi
- if [ "$_rollback_ok" -eq 1 ]; then
- msg "❌ 升级失败(部署/依赖安装出错),已回滚到 v${old_ver:-unknown} 并重启服务" \
- "❌ Upgrade failed (deploy/dependency error), rolled back to v${old_ver:-unknown} and restarted"
- else
- msg "❌ 升级失败且自动回滚未成功,请手动恢复:" \
- "❌ Upgrade failed and auto-rollback did not succeed. Manual recovery:"
- msg " loongsuite-pilot rollback && loongsuite-pilot start" \
- " loongsuite-pilot rollback && loongsuite-pilot start"
- fi
- exit 1
- fi
- install_loongsuite_pilot_command
- retire_qoderwork_runtime_overrides
- # Start the new version
- msg "==> 启动新版本..." "==> Starting new version..."
- if run_pilot_cli start; then
- sleep 2
- local _status_out
- _status_out="$(run_pilot_cli status 2>/dev/null || true)"
- if echo "$_status_out" | grep -q "is running"; then
- PILOT_HELD_FOR_DEPLOY=0
- msg " ✅ 新版本启动成功" " ✅ New version started successfully"
- echo ""
- # GC: remove old versions beyond current + previous
- gc_old_versions
- print_summary "upgrade"
- return 0
- fi
- fi
- # --- Rollback via version pointer ---
- echo ""
- msg "⚠️ 新版本启动失败,正在回滚..." \
- "⚠️ New version failed to start, rolling back..."
- run_pilot_cli stop 2>/dev/null || true
- local _rb_ok=1
- run_pilot_cli rollback 2>/dev/null || _rb_ok=0
- if [ "$_rb_ok" -eq 1 ]; then
- if run_pilot_cli start; then
- PILOT_HELD_FOR_DEPLOY=0
- msg "❌ 升级失败,已回滚到 v${old_ver:-unknown}" \
- "❌ Upgrade failed, rolled back to v${old_ver:-unknown}"
- msg " 请检查日志: loongsuite-pilot log" " Check logs: loongsuite-pilot log"
- else
- msg "❌ 升级失败,已回滚但未能重启服务" \
- "❌ Upgrade failed, rolled back but could not restart"
- msg " 请手动运行: loongsuite-pilot start" \
- " Run manually: loongsuite-pilot start"
- fi
- else
- msg "❌ 升级失败且回滚未成功,请手动恢复:" \
- "❌ Upgrade failed and rollback did not succeed. Manual recovery:"
- msg " loongsuite-pilot rollback && loongsuite-pilot start" \
- " loongsuite-pilot rollback && loongsuite-pilot start"
- fi
- exit 1
- }
- # ============================================================
- # GC: remove old version directories beyond current + previous
- # ============================================================
- gc_old_versions() {
- local cache_dir="$HOME/.loongsuite-pilot"
- local versions_dir="$cache_dir/versions"
- local current_file="$cache_dir/current"
- local previous_file="$cache_dir/previous"
- [ -d "$versions_dir" ] || return 0
- local keep_current="" keep_previous=""
- if [ -f "$current_file" ]; then
- keep_current=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
- fi
- if [ -f "$previous_file" ]; then
- keep_previous=$(cat "$previous_file" 2>/dev/null | tr -d '[:space:]')
- fi
- for d in "$versions_dir"/*/; do
- [ -d "$d" ] || continue
- local name
- name=$(basename "$d")
- if [ "$name" = "$keep_current" ] || [ "$name" = "$keep_previous" ]; then
- continue
- fi
- rm -rf "$d"
- done
- }
- # ============================================================
- # Remove hook entries injected into tool config files
- # ============================================================
- remove_hook_configs() {
- local HOOK_MARKER=".loongsuite-pilot"
- local configs=(
- "$HOME/.cursor/hooks.json"
- "$HOME/.qoder/settings.json"
- "$HOME/.qoder-cn/settings.json"
- "$HOME/.qoderwork/settings.json"
- "$HOME/.qoderworkcn/settings.json"
- "$HOME/.qwenworkcn/settings.json"
- "$HOME/.claude/settings.json"
- "$HOME/.codex/hooks.json"
- "$HOME/.kiro/agents/pilot-kiro.json"
- "$HOME/.qwen/settings.json"
- "$HOME/.workbuddy/settings.json"
- )
- local _has_node=0
- if command -v node &>/dev/null; then
- _has_node=1
- else
- msg " ⚠️ 未找到 Node.js,含 hook 的配置文件将跳过自动清理" \
- " ⚠️ Node.js not found, config files with hooks will skip auto-cleanup"
- fi
- for cfg in "${configs[@]}"; do
- [ -f "$cfg" ] || continue
- local short="${cfg/#$HOME/\~}"
- local ok=0
- if [ "$_has_node" -eq 1 ]; then
- node -e "
- const fs = require('fs');
- const cfg = process.argv[1];
- const marker = process.argv[2];
- try {
- const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
- const hooks = data.hooks;
- if (!hooks || typeof hooks !== 'object') process.exit(0);
- let changed = false;
- const isCodex = cfg.endsWith('/.codex/hooks.json');
- const isPilotCodex = c => typeof c === 'string' && c.includes(marker)
- && new RegExp('(^|[ /])codex-loongsuite-pilot-hook[.](sh|mjs|ps1)([^A-Za-z0-9_.-]|$)', 'i').test(c);
- for (const [event, entries] of Object.entries(hooks)) {
- if (!Array.isArray(entries)) continue;
- const candidates = isCodex ? entries.flatMap(e => {
- if (!e || typeof e !== 'object') return [e];
- if (isPilotCodex(e.command)) { changed = true; return []; }
- if (!Array.isArray(e.hooks)) return [e];
- const nested = e.hooks.filter(h => !isPilotCodex(h && h.command));
- if (nested.length === e.hooks.length) return [e];
- changed = true;
- return nested.length ? [{ ...e, hooks: nested }] : [];
- }) : entries;
- const filtered = isCodex ? candidates : candidates.filter(e => {
- const cmd = e.command || '';
- const nested = Array.isArray(e.hooks) ? e.hooks : [];
- const hasMarker = cmd.includes(marker) || nested.some(h => (h.command || '').includes(marker));
- if (hasMarker) changed = true;
- return !hasMarker;
- });
- if (filtered.length === 0) { delete hooks[event]; changed = true; }
- else hooks[event] = filtered;
- }
- if (changed) {
- fs.writeFileSync(cfg, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write('cleaned');
- } else {
- process.stdout.write('skip');
- }
- } catch(e) { process.stderr.write(e.message); process.exit(1); }
- " "$cfg" "$HOOK_MARKER" && ok=1
- else
- # Node unavailable: skip auto-cleanup to avoid over-deletion
- if grep -q "$HOOK_MARKER" "$cfg" 2>/dev/null; then
- msg " ⚠️ 跳过: $short (无 Node.js,请手动删除含 $HOOK_MARKER 的 hook 条目)" \
- " ⚠️ Skipped: $short (no Node.js, manually remove hook entries containing $HOOK_MARKER)"
- else
- ok=1
- fi
- fi
- if [ "$ok" -eq 1 ]; then
- msg " ✅ 已清理: $short" " ✅ Cleaned: $short"
- else
- msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)"
- fi
- done
- }
- # Grok Build uses a dedicated Pilot-owned hook file. Match the stable entry
- # script name instead of the data-dir path so custom LOONGSUITE_PILOT_DATA_DIR
- # installations uninstall correctly, while unrelated hooks in the file remain.
- remove_native_system_hooks() {
- [ -f "$DATA_DIR/deployed-agents.json" ] || return 0
- local cache="${PILOT_CACHE_DIR:-$HOME/.loongsuite-pilot}"
- local version="$(cat "$cache/current" 2>/dev/null || true)"
- local node_bin="${NODE_BIN:-}"
- if [ ! -x "$node_bin" ] && [ -f "$DATA_DIR/node-bin" ]; then
- node_bin=$(tr -d '\r\n' < "$DATA_DIR/node-bin")
- fi
- if [ ! -x "$node_bin" ]; then node_bin=$(command -v node) || node_bin=""; fi
- if [ -z "$node_bin" ]; then
- echo "System hook cleanup requires Node.js; Pilot assets retained for retry" >&2
- return 1
- fi
- local candidate
- 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
- if [ -f "$candidate" ]; then
- if ! "$node_bin" "$candidate" "$DATA_DIR"; then
- echo "System hook cleanup failed; uninstall stopped and Pilot assets retained for retry" >&2
- return 1
- fi
- return 0
- fi
- done
- # Refuse to delete assets while recorded system hooks still reference them.
- "$node_bin" - "$DATA_DIR/deployed-agents.json" <<'NODE'
- const fs = require('fs');
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
- if (Object.values(state).some(r => r?.hookScope === 'system' || r?.hookPendingMigration)) {
- throw new Error('System hook cleanup helper missing; retain Pilot assets and retry with the installed package');
- }
- } catch (error) {
- if (error.code !== 'ENOENT') { console.error(error.message); process.exitCode = 1; }
- }
- NODE
- }
- remove_grok_build_hook_config() {
- local grok_home="${GROK_HOME:-$HOME/.grok}"
- local cfg="$grok_home/hooks/loongsuite-pilot.json"
- local state_file="$DATA_DIR/deployed-agents.json"
- if command -v node &>/dev/null && [ -f "$state_file" ]; then
- local persisted
- persisted=$(node -e '
- const fs = require("fs");
- const path = require("path");
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- const value = state?.["grok-build"]?.hookSettingsPath;
- if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
- } catch {}
- ' "$state_file")
- if [ -n "$persisted" ]; then cfg="$persisted"; fi
- fi
- [ -f "$cfg" ] || return 0
- if ! command -v node &>/dev/null; then
- msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (无 Node.js,请手动清理 Grok Build Pilot hook)" \
- " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (Node.js unavailable; remove the Grok Build Pilot hook manually)"
- return 0
- fi
- local result
- result="$(node -e '
- const fs = require("fs");
- const cfg = process.argv[1];
- const owned = value => typeof value === "string"
- && /(?:^|[\\/])grok-build-loongsuite-pilot-hook\.(?:sh|ps1)(?:"|\s|$)/i.test(value);
- try {
- const data = JSON.parse(fs.readFileSync(cfg, "utf8"));
- const hooks = data && typeof data.hooks === "object" && data.hooks ? data.hooks : null;
- if (!hooks) { process.stdout.write("nochange"); process.exit(0); }
- let changed = false;
- for (const [event, entries] of Object.entries(hooks)) {
- if (!Array.isArray(entries)) continue;
- const kept = [];
- for (const entry of entries) {
- if (owned(entry && entry.command)) { changed = true; continue; }
- if (entry && Array.isArray(entry.hooks)) {
- const nested = entry.hooks.filter(hook => !owned(hook && hook.command));
- if (nested.length !== entry.hooks.length) changed = true;
- if (entry.hooks.length > 0 && nested.length === 0) continue;
- kept.push({ ...entry, hooks: nested });
- } else {
- kept.push(entry);
- }
- }
- if (kept.length === 0) delete hooks[event];
- else hooks[event] = kept;
- }
- if (!changed) { process.stdout.write("nochange"); process.exit(0); }
- if (Object.keys(hooks).length === 0) delete data.hooks;
- if (Object.keys(data).length === 0) {
- fs.unlinkSync(cfg);
- } else {
- const tmp = `${cfg}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
- fs.renameSync(tmp, cfg);
- }
- process.stdout.write("cleaned");
- } catch (error) {
- process.stderr.write(error.message); process.exit(1);
- }
- ' "$cfg" 2>/dev/null || true)"
- if [ "$result" = "cleaned" ] || [ "$result" = "nochange" ]; then
- msg " ✅ 已清理: ~/.grok/hooks/loongsuite-pilot.json" \
- " ✅ Cleaned: ~/.grok/hooks/loongsuite-pilot.json"
- else
- msg " ⚠️ 跳过: ~/.grok/hooks/loongsuite-pilot.json (需手动清理)" \
- " ⚠️ Skipped: ~/.grok/hooks/loongsuite-pilot.json (manual cleanup needed)"
- fi
- }
- # ============================================================
- # Remove the Pilot-owned DeepSeek Harness YAML patch before plugin assets.
- # The same helper is invoked by the PowerShell installer.
- # ============================================================
- remove_dsh_yaml_patch() {
- local plugin_dir="$DATA_DIR/plugins/dsh"
- local cleanup_script="$plugin_dir/cleanup.mjs"
- local node_bin=""
- for pin_file in "$DATA_DIR/node-bin" "$HOME/.loongsuite-pilot/node-bin"; do
- if [ -f "$pin_file" ]; then
- local pinned
- pinned=$(tr -d '\r\n' < "$pin_file")
- if _node_is_suitable "$pinned"; then node_bin="$pinned"; break; fi
- fi
- done
- if [ -z "$node_bin" ]; then node_bin=$(resolve_node) || node_bin=""; fi
- if [ -z "$node_bin" ]; then
- msg " ❌ 无可用 Node.js,无法安全清理 DSH YAML patch" \
- " ❌ No usable Node.js; cannot safely remove the DSH YAML patch"
- return 1
- fi
- # DSH_HOME may differ between install and uninstall. Prefer the exact path
- # recorded when Pilot deployed the block, then fall back for legacy state.
- local dsh_home="${DSH_HOME:-$HOME/.dsh}"
- local patch_path="$dsh_home/cordis.patch.yml"
- local state_file="$DATA_DIR/deployed-agents.json"
- if [ -f "$state_file" ]; then
- local persisted_patch
- persisted_patch=$("$node_bin" -e '
- const fs = require("fs");
- const path = require("path");
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- const value = state?.dsh?.dshPatchPath;
- if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
- } catch {}
- ' "$state_file")
- if [ -n "$persisted_patch" ]; then patch_path="$persisted_patch"; fi
- fi
- if [ ! -f "$cleanup_script" ]; then
- if [ -f "$patch_path" ] && grep -Fq '# BEGIN PILOT-OBSERVABILITY-MANAGED' "$patch_path"; then
- msg " ❌ DSH 清理脚本缺失,拒绝删除仍被 YAML 引用的插件资产" \
- " ❌ DSH cleanup helper is missing; refusing to remove plugin assets still referenced by YAML"
- return 1
- fi
- return 0
- fi
- if ! "$node_bin" "$cleanup_script" --patch "$patch_path" --plugin-dir "$plugin_dir"; then
- msg " ❌ DSH YAML patch 清理失败;卸载已停止,Pilot 资产保持不变" \
- " ❌ DSH YAML patch cleanup failed; uninstall stopped and Pilot assets were preserved"
- return 1
- fi
- msg " ✅ 已清理 DSH YAML patch" " ✅ Cleaned DSH YAML patch"
- }
- # ============================================================
- # Remove plugin-inject specs (OpenCode)
- # ============================================================
- # OpenCode uses deployMode "plugin-inject": a spec is written into its own
- # config file's plugin array, not a shared settings.json. remove_hook_configs
- # does not cover it, so clean it here to avoid a dangling spec that points at
- # the (possibly purged) data dir.
- remove_opencode_plugin() {
- local configs=(
- "$HOME/.config/opencode/opencode.jsonc"
- "$HOME/.config/opencode/opencode.json"
- "$HOME/.config/opencode/config.json"
- )
- for cfg in "${configs[@]}"; do
- [ -f "$cfg" ] || continue
- local short="${cfg/#$HOME/\~}"
- if ! command -v node &>/dev/null; then
- msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- fi
- local result
- result=$(node -e "
- const fs = require('fs');
- const f = process.argv[1];
- // Match legacy plugins/opencode/plugin.mjs only under this installation.
- const normalize = value => {
- if (typeof value !== 'string') return '';
- let plain = value;
- if (plain.startsWith('file://')) {
- try {
- const url = new URL(plain);
- plain = decodeURIComponent(url.pathname);
- if (plain[0] === '/' && plain[2] === ':') plain = plain.slice(1);
- if (url.hostname && url.hostname !== 'localhost') {
- if (process.platform !== 'win32') return '';
- plain = '//' + url.hostname + plain;
- }
- } catch { return ''; }
- }
- plain = plain.split(String.fromCharCode(92)).join('/');
- while (plain.endsWith('/')) plain = plain.slice(0, -1);
- return process.platform === 'win32' ? plain.toLowerCase() : plain;
- };
- const dataDir = normalize(process.argv[2]);
- const managed = dataDir ? dataDir + '/plugins/opencode' : null;
- const isOurs = s => typeof s === 'string' && (
- s === 'loongsuite-pilot-opencode' || s.startsWith('loongsuite-pilot-opencode@') ||
- (managed !== null && (normalize(s) === managed || normalize(s) === managed + '/plugin.mjs'))
- );
- const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : (e?.package ?? ''));
- // JSONC fallback: strip block comments, whole-line // comments, and trailing
- // // comments preceded by whitespace. URL values like file:/// are never
- // touched because their slashes are not preceded by whitespace.
- const stripJsonc = src => src
- .replace(/\/\*[\s\S]*?\*\//g, '')
- .replace(/^\s*\/\/.*\$/gm, '')
- .replace(/[ \t]+\/\/.*\$/gm, '');
- try {
- const raw = fs.readFileSync(f, 'utf-8');
- let data, hadComments = false;
- try { data = JSON.parse(raw); }
- catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
- let removed = 0;
- for (const key of ['plugin', 'plugins']) {
- if (!Array.isArray(data[key])) continue;
- const before = data[key].length;
- data[key] = data[key].filter(e => !isOurs(entryStr(e)));
- removed += before - data[key].length;
- }
- if (!removed) { process.stdout.write('nochange'); process.exit(0); }
- if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
- fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- " "$cfg" "$DATA_DIR" 2>/dev/null) || result="error"
- case "$result" in
- cleaned)
- msg " ✅ 已清理: $short" " ✅ Cleaned: $short" ;;
- cleaned-bak)
- msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" \
- " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" ;;
- nochange)
- : ;;
- *)
- msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
- esac
- done
- }
- # Remove only the Hermes directory plugin owned by this Pilot installation.
- remove_hermes_plugin() {
- local hermes_home="${HERMES_HOME:-$HOME/.hermes}"
- local default_plugin_dir="$hermes_home/plugins/loongsuite-pilot"
- local state_file="$DATA_DIR/deployed-agents.json"
- local plugin_dir="$default_plugin_dir"
- if ! command -v node &>/dev/null; then
- msg " ⚠️ 跳过: $plugin_dir (无 node,需手动清理)" \
- " ⚠️ Skipped: $plugin_dir (node unavailable, manual cleanup needed)"
- return 0
- fi
- plugin_dir=$(node -e "
- const fs = require('fs');
- const path = require('path');
- const stateFile = process.argv[1];
- let target = process.argv[2];
- try {
- const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
- const recorded = state?.['hermes-agent']?.targetDir;
- if (typeof recorded === 'string' && path.isAbsolute(recorded)) target = recorded;
- } catch {}
- process.stdout.write(target);
- " "$state_file" "$default_plugin_dir" 2>/dev/null) || plugin_dir="$default_plugin_dir"
- local marker="$plugin_dir/.loongsuite-pilot-managed.json"
- [ -f "$marker" ] || return 0
- local ownership
- ownership=$(node -e "
- const fs = require('fs');
- const path = require('path');
- const dir = process.argv[1];
- const marker = path.join(dir, '.loongsuite-pilot-managed.json');
- try {
- const meta = JSON.parse(fs.readFileSync(marker, 'utf8'));
- if (meta.owner !== 'loongsuite-pilot' || meta.agentId !== 'hermes-agent') {
- process.stdout.write('unmanaged');
- process.exit(0);
- }
- process.stdout.write('owned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- " "$plugin_dir" 2>/dev/null) || ownership="error"
- if [ "$ownership" = "owned" ]; then
- local hermes_cli="${HERMES_CLI:-$hermes_home/hermes-agent/venv/bin/hermes}"
- if [ ! -x "$hermes_cli" ] && command -v hermes &>/dev/null; then
- hermes_cli=$(command -v hermes)
- fi
- if [ -x "$hermes_cli" ]; then
- "$hermes_cli" plugins disable loongsuite-pilot >/dev/null 2>&1 || true
- fi
- fi
- local result="$ownership"
- if [ "$ownership" = "owned" ]; then
- result=$(node -e "
- const fs = require('fs');
- const path = require('path');
- const dir = process.argv[1];
- const marker = path.join(dir, '.loongsuite-pilot-managed.json');
- try {
- const meta = JSON.parse(fs.readFileSync(marker, 'utf8'));
- if (meta.owner !== 'loongsuite-pilot' || meta.agentId !== 'hermes-agent') {
- process.stdout.write('unmanaged');
- process.exit(0);
- }
- fs.rmSync(dir, { recursive: true, force: true });
- process.stdout.write('cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- " "$plugin_dir" 2>/dev/null) || result="error"
- fi
- case "$result" in
- cleaned)
- msg " ✅ 已清理: $plugin_dir" " ✅ Cleaned: $plugin_dir" ;;
- unmanaged)
- msg " ⚠️ 保留未受 Pilot 管理的 Hermes 插件: $plugin_dir" \
- " ⚠️ Preserved unmanaged Hermes plugin: $plugin_dir" ;;
- *)
- msg " ⚠️ 跳过: $plugin_dir (需手动清理)" \
- " ⚠️ Skipped: $plugin_dir (manual cleanup needed)" ;;
- esac
- }
- # ============================================================
- # Remove Pi Coding Agent extension injection
- # ============================================================
- remove_pi_coding_agent_extension() {
- local cfg="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}/settings.json"
- local state_file="$DATA_DIR/deployed-agents.json"
- if command -v node &>/dev/null && [ -f "$state_file" ]; then
- local persisted
- persisted=$(node -e '
- const fs = require("fs");
- const path = require("path");
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- const value = state?.["pi-coding-agent"]?.pluginInjectConfigPath;
- if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
- } catch {}
- ' "$state_file")
- if [ -n "$persisted" ]; then cfg="$persisted"; fi
- fi
- local short="${cfg/#$HOME/\~}"
- if ! command -v node &>/dev/null; then
- msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- return 0
- fi
- local result
- result=$(node -e "
- const fs = require('fs');
- const path = require('path');
- const defaultConfig = process.argv[1];
- const dataDir = process.argv[2];
- const targets = [{ configPath: defaultConfig, markers: ['loongsuite-pilot-pi-coding-agent', 'plugins/pi-coding-agent/index.mjs'] }];
- const resolveValue = value => typeof value === 'string'
- ? value.replace(/^~(?=[\\/])/, process.env.HOME || '').replaceAll('\$PILOT_DATA', dataDir)
- : value;
- const stripJsoncComments = text => {
- let result = '';
- let index = 0;
- let inString = false;
- let escape = false;
- while (index < text.length) {
- const ch = text[index];
- if (inString) {
- result += ch;
- if (escape) escape = false;
- else if (ch.charCodeAt(0) === 92) escape = true;
- else if (ch === '\"') inString = false;
- index++;
- continue;
- }
- if (ch === '\"') {
- inString = true;
- result += ch;
- index++;
- continue;
- }
- if (ch === '/' && text[index + 1] === '/') {
- index += 2;
- while (index < text.length && text[index] !== '\n') index++;
- continue;
- }
- if (ch === '/' && text[index + 1] === '*') {
- index += 2;
- while (index + 1 < text.length && !(text[index] === '*' && text[index + 1] === '/')) index++;
- index += 2;
- continue;
- }
- result += ch;
- index++;
- }
- return result;
- };
- const comparable = value => typeof value === 'string'
- ? value.split(String.fromCharCode(92)).join('/')
- : '';
- const localDir = path.join(dataDir, 'agents.d.local');
- try {
- for (const name of fs.existsSync(localDir) ? fs.readdirSync(localDir) : []) {
- if (!name.endsWith('.json')) continue;
- let def;
- try { def = JSON.parse(fs.readFileSync(path.join(localDir, name), 'utf8')); } catch { continue; }
- if (def?.piSdk?.schemaVersion !== 1 || !def?.pluginInject?.pluginId?.startsWith('loongsuite-pilot-pi-sdk-')) continue;
- const spec = resolveValue(def.pluginInject.pluginSpec);
- for (const configPath of def.pluginInject.configPaths || []) {
- targets.push({
- configPath: resolveValue(configPath),
- markers: [def.pluginInject.pluginId, spec, 'plugins/pi-coding-agent/agents/'].filter(Boolean),
- });
- }
- }
- let cleaned = 0;
- let skipped = 0;
- for (const target of targets) {
- if (!target.configPath || !fs.existsSync(target.configPath)) continue;
- try {
- const raw = fs.readFileSync(target.configPath, 'utf-8');
- const data = JSON.parse(stripJsoncComments(raw));
- if (!Array.isArray(data.extensions)) continue;
- const before = data.extensions.length;
- data.extensions = data.extensions.filter(entry => {
- const value = comparable(entry);
- return !target.markers.some(marker => value === comparable(marker) || value.includes(comparable(marker)));
- });
- if (data.extensions.length === before) continue;
- if (raw !== JSON.stringify(data, null, 2) + '\n') {
- try {
- fs.copyFileSync(target.configPath, target.configPath + '.bak', fs.constants.COPYFILE_EXCL);
- } catch (e) {
- if (e?.code !== 'EEXIST') throw e;
- }
- }
- fs.writeFileSync(target.configPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- cleaned++;
- } catch {
- skipped++;
- }
- }
- process.stdout.write(cleaned > 0 ? (skipped > 0 ? 'partial' : 'cleaned') : (skipped > 0 ? 'skipped' : 'nochange'));
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- " "$cfg" "$DATA_DIR" 2>/dev/null) || result="error"
- case "$result" in
- cleaned)
- msg " ✅ 已清理 Pi / PI SDK Agent 扩展配置" " ✅ Cleaned Pi / PI SDK Agent extension configs" ;;
- partial)
- msg " ⚠️ 已清理可读取的 Pi 配置,部分损坏配置需手动清理" \
- " ⚠️ Cleaned readable Pi configs; some invalid configs need manual cleanup" ;;
- skipped)
- msg " ⚠️ Pi 配置损坏,需手动清理" " ⚠️ Invalid Pi configs skipped (manual cleanup needed)" ;;
- nochange)
- : ;;
- *)
- msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
- esac
- }
- # ============================================================
- # MiMo Code also uses deployMode "plugin-inject": a spec is written into its
- # own config file's plugin array. Same shape as remove_opencode_plugin but for
- # ~/.config/mimocode/mimocode.json[c]. Without this, the spec survives
- # uninstall and points at a (possibly purged) plugin.mjs, so the next MiMo
- # Code launch loads a non-existent module.
- # ============================================================
- remove_mimocode_plugin() {
- local configs=(
- "$HOME/.config/mimocode/mimocode.jsonc"
- "$HOME/.config/mimocode/mimocode.json"
- )
- for cfg in "${configs[@]}"; do
- [ -f "$cfg" ] || continue
- local short="${cfg/#$HOME/\~}"
- if ! command -v node &>/dev/null; then
- msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- fi
- local result
- result=$(node -e "
- const fs = require('fs');
- const f = process.argv[1];
- const isOurs = s => typeof s === 'string' && (s.includes('loongsuite-pilot-mimo-code') || s.includes('plugins/mimo-code/plugin.mjs'));
- const entryStr = e => typeof e === 'string' ? e : (Array.isArray(e) ? String(e[0]) : '');
- const stripJsonc = src => src
- .replace(/\/\*[\s\S]*?\*\//g, '')
- .replace(/^\s*\/\/.*\$/gm, '')
- .replace(/[ \t]+\/\/.*\$/gm, '');
- try {
- const raw = fs.readFileSync(f, 'utf-8');
- let data, hadComments = false;
- try { data = JSON.parse(raw); }
- catch { data = JSON.parse(stripJsonc(raw)); hadComments = true; }
- const key = Array.isArray(data.plugins) ? 'plugins' : (Array.isArray(data.plugin) ? 'plugin' : null);
- if (!key) { process.stdout.write('nochange'); process.exit(0); }
- const before = data[key].length;
- data[key] = data[key].filter(e => !isOurs(entryStr(e)));
- if (data[key].length === before) { process.stdout.write('nochange'); process.exit(0); }
- if (hadComments) fs.writeFileSync(f + '.bak', raw, 'utf-8');
- fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write(hadComments ? 'cleaned-bak' : 'cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- " "$cfg" 2>/dev/null) || result="error"
- case "$result" in
- cleaned)
- msg " ✅ 已清理: $short" " ✅ Cleaned: $short" ;;
- cleaned-bak)
- msg " ✅ 已清理: $short (含注释,原文件备份为 $short.bak)" \
- " ✅ Cleaned: $short (had comments, original backed up to $short.bak)" ;;
- nochange)
- : ;;
- *)
- msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
- esac
- done
- }
- # ============================================================
- # Remove OpenClaw's nested plugin entry and load path.
- # ============================================================
- # OpenClaw stores injected plugins under plugins.load.paths plus
- # plugins.entries. The generic hook cleanup does not cover this shape, and
- # leaving either value behind makes OpenClaw load a path that uninstall is
- # about to remove. Only Pilot-owned values are removed; unrelated plugins and
- # their configuration remain semantically unchanged.
- remove_openclaw_plugin() {
- local state_dir="${OPENCLAW_STATE_DIR:-$HOME/.openclaw}"
- local managed_path="$DATA_DIR/plugins/openclaw"
- local configs=()
- [ -n "${OPENCLAW_CONFIG_PATH:-}" ] && configs+=("$OPENCLAW_CONFIG_PATH")
- configs+=(
- "$state_dir/openclaw.json"
- "$state_dir/config.json"
- "$HOME/.openclaw/openclaw.json"
- "$HOME/.openclaw/config.json"
- )
- local seen="|"
- for cfg in "${configs[@]}"; do
- [ -f "$cfg" ] || continue
- case "$seen" in *"|$cfg|"*) continue ;; esac
- seen="${seen}${cfg}|"
- local short="${cfg/#$HOME/\~}"
- if ! command -v node &>/dev/null; then
- msg " ⚠️ 跳过: $short (无 node,需手动清理)" " ⚠️ Skipped: $short (node unavailable, manual cleanup needed)"
- continue
- fi
- local result
- result=$(PILOT_OC_CONFIG="$cfg" PILOT_OC_MANAGED="$managed_path" node 2>/dev/null <<'NODE'
- const fs = require('fs');
- const f = process.env.PILOT_OC_CONFIG;
- const managed = process.env.PILOT_OC_MANAGED.replaceAll('\\', '/');
- const entryStr = value => typeof value === 'string'
- ? value
- : (Array.isArray(value) && typeof value[0] === 'string' ? value[0] : '');
- const isOurs = value => {
- const normalized = entryStr(value).replaceAll('\\', '/');
- const plain = normalized.startsWith('file://') ? normalized.slice('file://'.length) : normalized;
- return plain === managed ||
- plain === managed + '/plugin.mjs' ||
- normalized.includes('loongsuite-pilot-openclaw') ||
- normalized.includes('plugins/openclaw/plugin.mjs') && plain.includes('.loongsuite-pilot/');
- };
- try {
- const data = JSON.parse(fs.readFileSync(f, 'utf-8'));
- let changed = false;
- for (const key of ['plugin', 'plugins']) {
- if (!Array.isArray(data[key])) continue;
- const filtered = data[key].filter(value => !isOurs(value));
- if (filtered.length !== data[key].length) { data[key] = filtered; changed = true; }
- }
- const plugins = data.plugins && typeof data.plugins === 'object' && !Array.isArray(data.plugins)
- ? data.plugins
- : null;
- if (plugins) {
- if (plugins.load && typeof plugins.load === 'object' && Array.isArray(plugins.load.paths)) {
- const filtered = plugins.load.paths.filter(value => !isOurs(value));
- if (filtered.length !== plugins.load.paths.length) { plugins.load.paths = filtered; changed = true; }
- }
- if (plugins.entries && typeof plugins.entries === 'object' && !Array.isArray(plugins.entries) &&
- Object.prototype.hasOwnProperty.call(plugins.entries, 'loongsuite-pilot-openclaw')) {
- delete plugins.entries['loongsuite-pilot-openclaw'];
- changed = true;
- }
- }
- if (!changed) { process.stdout.write('nochange'); process.exit(0); }
- fs.writeFileSync(f, JSON.stringify(data, null, 2) + '\n', 'utf-8');
- process.stdout.write('cleaned');
- } catch (e) { process.stderr.write(e.message); process.exit(1); }
- NODE
- ) || result="error"
- case "$result" in
- cleaned)
- msg " ✅ 已清理: $short" " ✅ Cleaned: $short" ;;
- nochange)
- : ;;
- *)
- msg " ⚠️ 跳过: $short (需手动清理)" " ⚠️ Skipped: $short (manual cleanup needed)" ;;
- esac
- done
- }
- # ============================================================
- # CMD: uninstall
- # ============================================================
- cmd_uninstall() {
- msg "🗑️ 开始卸载 $PACKAGE_NAME ..." \
- "🗑️ Uninstalling $PACKAGE_NAME ..."
- echo ""
- # Stop service (also removes autostart)
- msg "==> 停止服务..." "==> Stopping service..."
- if command -v loongsuite-pilot &>/dev/null; then
- loongsuite-pilot stop 2>/dev/null || true
- elif [ -f "$HOME/.local/bin/loongsuite-pilot" ]; then
- "$HOME/.local/bin/loongsuite-pilot" stop 2>/dev/null || true
- else
- local pid_file="$DATA_DIR/loongsuite-pilot.pid"
- if [ -f "$pid_file" ]; then
- local pid; pid=$(cat "$pid_file")
- kill "$pid" 2>/dev/null || true
- sleep 2
- kill -9 "$pid" 2>/dev/null || true
- rm -f "$pid_file"
- fi
- # Manual autostart cleanup when loongsuite-pilot is unavailable
- case "$(uname -s)" in
- Darwin)
- local _plist="$HOME/Library/LaunchAgents/com.loongsuite-pilot.plist"
- local _uplist="$HOME/Library/LaunchAgents/com.loongsuite-pilot.updater.plist"
- for f in "$_uplist" "$_plist"; do
- if [ -f "$f" ]; then
- launchctl unload -w "$f" 2>/dev/null || true
- rm -f "$f"
- fi
- done
- ;;
- Linux)
- local _run_user
- _run_user="$(whoami)"
- # Clean up user-level systemd units
- local _user_unit_dir="$HOME/.config/systemd/user"
- if [ -f "$_user_unit_dir/loongsuite-pilot.service" ]; then
- systemctl --user disable --now loongsuite-pilot.service &>/dev/null || true
- systemctl --user disable --now loongsuite-pilot-updater.service &>/dev/null || true
- rm -f "$_user_unit_dir/loongsuite-pilot.service"
- rm -f "$_user_unit_dir/loongsuite-pilot-updater.service"
- systemctl --user daemon-reload &>/dev/null || true
- fi
- # Clean up system-level systemd units
- local _sys_unit="/etc/systemd/system/loongsuite-pilot-${_run_user}.service"
- local _sys_uunit="/etc/systemd/system/loongsuite-pilot-updater-${_run_user}.service"
- for f in "$_sys_uunit" "$_sys_unit"; do
- if [ -f "$f" ]; then
- sudo systemctl disable --now "$(basename "$f")" &>/dev/null || true
- sudo rm -f "$f"
- fi
- done
- sudo systemctl daemon-reload &>/dev/null || true
- # Clean up init.d scripts
- local _initd="/etc/init.d/loongsuite-pilot-${_run_user}"
- local _initd_u="/etc/init.d/loongsuite-pilot-updater-${_run_user}"
- for f in "$_initd_u" "$_initd"; do
- if [ -f "$f" ]; then
- sudo "$f" stop &>/dev/null || true
- local _name; _name=$(basename "$f")
- if command -v chkconfig &>/dev/null; then sudo chkconfig --del "$_name" &>/dev/null || true
- elif command -v update-rc.d &>/dev/null; then sudo update-rc.d "$_name" remove &>/dev/null || true; fi
- sudo rm -f "$f"
- fi
- done
- ;;
- esac
- fi
- msg " ✅ 服务已停止" " ✅ Service stopped"
- echo ""
- msg "==> 清理 DSH YAML patch..." "==> Cleaning up DSH YAML patch..."
- if ! remove_dsh_yaml_patch; then
- return 1
- fi
- echo ""
- # Read the persisted target before the data/install directory is removed.
- msg "==> 清理 Hermes 插件..." "==> Cleaning up Hermes plugin..."
- remove_hermes_plugin
- echo ""
- msg "==> 清理 OpenClaw 插件配置..." "==> Cleaning up OpenClaw plugin config..."
- remove_openclaw_plugin
- echo ""
- # Remove hook entries from tool configs BEFORE removing install dir
- msg "==> 清理 hook 配置..." "==> Cleaning up hook configs..."
- if ! remove_native_system_hooks; then
- return 1
- fi
- remove_hook_configs
- if ! remove_grok_build_hook_config; then
- return 1
- fi
- remove_qodercli_token_intercept
- remove_qoderclicn_token_intercept
- retire_qoderwork_runtime_overrides
- remove_claude_code_fetch_intercept
- remove_copilot_otel_environment
- remove_copilot_plugin
- echo ""
- # Remove OTel Claude plugin
- msg "==> 清理 Claude 旧插件..." "==> Cleaning up legacy Claude plugin..."
- remove_otel_plugin
- echo ""
- # Remove plugin-inject specs (OpenCode)
- msg "==> 清理 OpenCode 插件配置..." "==> Cleaning up OpenCode plugin config..."
- remove_opencode_plugin
- echo ""
- msg "==> 清理 Pi Coding Agent Extension 配置..." "==> Cleaning up Pi Coding Agent extension config..."
- remove_pi_coding_agent_extension
- echo ""
- # Remove plugin-inject specs (MiMo Code)
- msg "==> 清理 MiMo Code 插件配置..." "==> Cleaning up MiMo Code plugin config..."
- remove_mimocode_plugin
- echo ""
- # Remove installation artifacts
- msg "==> 删除安装目录..." "==> Removing installation..."
- local _cache_dir="$HOME/.loongsuite-pilot"
- rm -rf "${_cache_dir:?}/versions"
- rm -rf "${_cache_dir:?}/bin"
- rm -rf "${_cache_dir:?}/package"
- rm -f "${_cache_dir:?}/current"
- rm -f "${_cache_dir:?}/previous"
- rm -f "${_cache_dir:?}/node-bin"
- msg " ✅ 已删除安装文件" " ✅ Installation files removed"
- # Remove loongsuite-pilot command
- msg "==> 删除 loongsuite-pilot 命令..." "==> Removing loongsuite-pilot command..."
- rm -f "$HOME/.local/bin/loongsuite-pilot"
- rm -f /usr/local/bin/loongsuite-pilot 2>/dev/null || true
- msg " ✅ loongsuite-pilot 命令已删除" " ✅ loongsuite-pilot command removed"
- echo ""
- # Data directory
- if [ "$PURGE" -eq 1 ]; then
- msg "==> 删除数据目录 (--purge)..." "==> Removing data directory (--purge)..."
- rm -rf "$DATA_DIR"
- msg " ✅ 已删除 $DATA_DIR" " ✅ Removed $DATA_DIR"
- else
- msg "📁 数据目录已保留: $DATA_DIR" \
- "📁 Data directory preserved: $DATA_DIR"
- msg " (包含配置和日志,如需彻底删除请加 --purge)" \
- " (contains config and logs, add --purge to remove)"
- fi
- echo ""
- echo "============================================================"
- msg "✅ 卸载完成!" "✅ Uninstallation complete!"
- echo "============================================================"
- }
- # ============================================================
- # Main dispatcher
- # ============================================================
- case "$COMMAND" in
- install) cmd_install ;;
- upgrade) cmd_upgrade ;;
- uninstall) cmd_uninstall ;;
- *)
- echo "Usage: $0 {install|upgrade|uninstall} [options]"
- exit 1 ;;
- esac
scripts/e2e/lib/agent-matrix.mjs · Bundled script · 359 lines · 2 findings marked
- import { Buffer } from 'node:buffer';
- import { readFileSync } from 'node:fs';
- import * as path from 'node:path';
- import { fileURLToPath } from 'node:url';
- import { shellSingleQuoteBash } from './propagate-sls-install.mjs';
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- export function defaultAgentMatrixPath() {
- return path.join(__dirname, '..', 'agent-matrix.json');
- }
- export function loadAgentMatrix(env = process.env) {
- const p = env.E2E_AGENT_MATRIX_PATH?.trim() || defaultAgentMatrixPath();
- const raw = readFileSync(p, 'utf8');
- const j = JSON.parse(raw);
- if (!Array.isArray(j.agents)) throw new Error(`agent-matrix.json missing agents[] (${p})`);
- return { path: p, agents: j.agents };
- }
- /** 旧 glibc 主机(RHEL/CentOS/AliOS 7)profile 检测,影响默认 Cursor 安装策略。 */
- export function isE2eOldGlibcCursorHostProfile(env = process.env) {
- const p = (env.E2E_PROFILE ?? 'linux-8u').trim().toLowerCase();
- return p === 'linux-7u' || p === '7u' || p === 'alios7' || p === 'linux-alios7';
- }
- /** E2E_CURSOR_INSTALL_STRATEGY 显式优先;否则旧 glibc profile → watzon,其余 → official。 */
- export function resolveE2eCursorInstallStrategy(env = process.env) {
- const raw = env.E2E_CURSOR_INSTALL_STRATEGY?.trim();
- if (raw) return raw.toLowerCase() === 'watzon' ? 'watzon' : 'official';
- return isE2eOldGlibcCursorHostProfile(env) ? 'watzon' : 'official';
- }
- /**
- * cursor: official=cursor.com/install Agent CLI; watzon=AppImage 提取。E2E_CURSOR_ENSURE_INSTALL_SH 最优先。
- */
- export function resolveEnsureInstallSh(agent, env = process.env) {
- const bin = String(agent.binary ?? '').trim();
- if (bin === 'cursor') {
- if (env.E2E_CURSOR_ENSURE_INSTALL_SH?.trim()) {
- return env.E2E_CURSOR_ENSURE_INSTALL_SH.trim();
- }
- const strategy = resolveE2eCursorInstallStrategy(env);
- if (strategy === 'watzon') {
- const stripInstallPath = u => String(u).trim().replace(/\/install\.sh\/?$/i, '');
- const jsdelivrBase = env.E2E_CURSOR_JSDELIVR_BASE?.trim()
- ? env.E2E_CURSOR_JSDELIVR_BASE.trim()
- : env.E2E_CURSOR_INSTALL_SCRIPT_URL?.trim()
- ? stripInstallPath(env.E2E_CURSOR_INSTALL_SCRIPT_URL)
- : 'https://cdn.jsdelivr.net/gh/watzon/cursor-linux-installer@main';
- const rawBase = env.E2E_CURSOR_RAW_BASE?.trim()
- ? env.E2E_CURSOR_RAW_BASE.trim()
- : env.E2E_CURSOR_INSTALL_SCRIPT_URL_FALLBACK?.trim()
- ? stripInstallPath(env.E2E_CURSOR_INSTALL_SCRIPT_URL_FALLBACK)
- : 'https://raw.githubusercontent.com/watzon/cursor-linux-installer/main';
- const failMsg =
- "echo '[e2e-ensure] Cursor (watzon) failed — try E2E_CURSOR_INSTALL_STRATEGY=official or E2E_CURSOR_ENSURE_INSTALL_SH'";
- return (
- `( _d="$HOME/.cache/loongsuite-e2e-cursor-install"; mkdir -p "$_d" && cd "$_d" || exit 1; ` +
- `_b="${jsdelivrBase}"; _f="${rawBase}"; ` +
- `_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"; }; ` +
- `_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" && ` +
- `chmod +x install.sh cursor.sh && bash ./install.sh stable --extract ) || ${failMsg}`
- );
- }
- const failOfficial =
- "echo '[e2e-ensure] Cursor official installer failed — set E2E_CURSOR_ENSURE_INSTALL_SH or E2E_CURSOR_INSTALL_STRATEGY=watzon'";
- return (
- `( set +e; export NO_COLOR=1; mkdir -p "$HOME/.local/bin"; ` +
- `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
- `|| ${failOfficial}`
- );
- }
- return String(agent.ensureInstallSh ?? '').trim();
- }
- function buildCodexEnsureInstallSh(bin, env) {
- if (bin !== 'codex') return null;
- const spec = env.E2E_CODEX_NPM_SPEC?.trim() || '@openai/codex';
- return `npm install -g ${shellSingleQuoteBash(spec)} || echo '[e2e-ensure] npm install codex failed'`;
- }
- function buildEnsureSummaryScript(matrix) {
- const lines = [
- 'echo "[e2e-ensure] summary:"',
- ];
- const seen = new Set();
- for (const a of matrix.agents ?? []) {
- const bin = String(a.binary ?? '').trim();
- if (!bin || seen.has(bin)) continue;
- seen.add(bin);
- const label = String(a.id ?? a.name ?? bin).replace(/'/g, `'\''`);
- if (bin === 'cursor') {
- lines.push(
- `if [ "$_e2e_cursor_incompat" -eq 1 ] && [ "\${_e2e_have_cf:-0}" -ne 1 ]; then`,
- ` echo "[e2e-ensure] ${label}: cursor incompatible (glibc too old; skipped)"`,
- `elif [ "\${_e2e_have_cf:-0}" -eq 1 ]; then`,
- ` echo "[e2e-ensure] ${label}: have cursor"`,
- `elif command -v agent >/dev/null 2>&1 || command -v cursor-agent >/dev/null 2>&1; then`,
- ` echo "[e2e-ensure] ${label}: have cursor (via agent/cursor-agent CLI)"`,
- `elif command -v cursor-installer >/dev/null 2>&1; then`,
- ` echo "[e2e-ensure] ${label}: have cursor (cursor-installer on PATH; run cursor-installer --update if needed)"`,
- `else`,
- ` echo "[e2e-ensure] ${label}: missing cursor"`,
- `fi`,
- );
- continue;
- }
- if (bin === 'qoder') {
- lines.push(
- `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`,
- );
- continue;
- }
- const binEsc = bin.replace(/'/g, `'\''`);
- lines.push(
- `if command -v '${binEsc}' >/dev/null 2>&1; then echo "[e2e-ensure] ${label}: have ${binEsc}"; else echo "[e2e-ensure] ${label}: missing ${binEsc}"; fi`,
- );
- }
- return lines;
- }
- /** 生成远端 ensure 脚本:npm 安装缺失 CLI,cursor 改用 --version 真实探测。 */
- export function buildEnsureAgentClisScript(matrix, env = process.env) {
- const cursorStrat = resolveE2eCursorInstallStrategy(env);
- const cursorSkipIfIncompat = (env.E2E_CURSOR_SKIP_IF_INCOMPAT ?? '1').trim() === '0' ? '0' : '1';
- const lines = [
- 'set +euo pipefail',
- 'export PATH="$HOME/.local/bin:$PATH"',
- `_E2E_CURSOR_STRAT=${shellSingleQuoteBash(cursorStrat)}`,
- `export _E2E_CURSOR_SKIP_IF_INCOMPAT=${shellSingleQuoteBash(cursorSkipIfIncompat)}`,
- '_e2e_cursor_incompat=0',
- '# 探测二进制是否可运行:0=OK, 2=glibc 不兼容, 1=其他失败。',
- '_e2e_cursor_runnable() {',
- ' _b="$1"',
- ' [ -n "$_b" ] || return 1',
- ' if [ ! -x "$_b" ] && ! command -v "$_b" >/dev/null 2>&1; then return 1; fi',
- ' _out=$("$_b" --version </dev/null 2>&1); _rc=$?',
- ' if [ "$_rc" -eq 0 ]; then return 0; fi',
- ' case "$_out" in',
- ' *GLIBC_*|*"not found"*|*"No such file or directory"*|*"cannot execute"*) return 2;;',
- ' esac',
- ' return 1',
- '}',
- 'echo "[e2e-ensure] checking agent matrix CLIs (scripts/e2e/agent-matrix.json)"',
- ];
- const extra = env.E2E_EXTRA_ENSURE_BASH?.trim();
- if (extra) {
- if (extra.length > 10_000) {
- console.warn('[e2e] E2E_EXTRA_ENSURE_BASH exceeds 10 000 chars — verify no accidental injection');
- }
- lines.push('# E2E_EXTRA_ENSURE_BASH');
- lines.push(extra);
- }
- lines.push('if ! command -v npm >/dev/null 2>&1; then');
- lines.push(' echo "[e2e-ensure] npm not on PATH; skipping npm-based installs"');
- lines.push('else');
- lines.push(' _npfx="$(npm config get prefix 2>/dev/null || true)"');
- lines.push(' if [ -n "$_npfx" ] && [ -d "$_npfx/bin" ]; then export PATH="$_npfx/bin:$PATH"; fi');
- const forceCodex = env.E2E_CODEX_FORCE_ENSURE?.trim() === '1';
- const skipAgents = resolveProbeSkipAgents(env);
- for (const a of matrix.agents) {
- const bin = String(a.binary ?? '').trim();
- if (!bin) continue;
- if (skipAgents.has(bin.toLowerCase())) continue;
- const label = String(a.name ?? bin);
- let install = resolveEnsureInstallSh(a, env);
- const codexSh = buildCodexEnsureInstallSh(bin, env);
- if (codexSh) install = codexSh;
- lines.push(` echo "[e2e-ensure] binary: ${bin} (${label})"`);
- if (bin === 'cursor') {
- lines.push(' _e2e_have_cf=0');
- lines.push(' _e2e_cf_probe() {');
- lines.push(' _cand="$1"');
- lines.push(' [ -n "$_cand" ] || return 1');
- lines.push(' _e2e_cursor_runnable "$_cand"');
- lines.push(' _rrc=$?');
- lines.push(' if [ "$_rrc" -eq 0 ]; then _e2e_have_cf=1; return 0; fi');
- lines.push(' if [ "$_rrc" -eq 2 ]; then _e2e_cursor_incompat=1; fi');
- lines.push(' return 1');
- lines.push(' }');
- lines.push(' if [ "$_E2E_CURSOR_STRAT" = "watzon" ]; then');
- lines.push(
- ' for _cp in "$HOME/.local/share/cursor/cursor/usr/bin/cursor" "$HOME/.cursor/cursor/usr/bin/cursor" "$(command -v cursor 2>/dev/null)"; do',
- );
- lines.push(' [ "$_e2e_have_cf" -eq 1 ] && break');
- lines.push(' _e2e_cf_probe "$_cp" || true');
- lines.push(' done');
- lines.push(' else');
- lines.push(
- ' # official: legacy AppImage `cursor` on PATH does not count — need Cursor Agent CLI that actually runs.',
- );
- lines.push(
- ' 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',
- );
- lines.push(' [ "$_e2e_have_cf" -eq 1 ] && break');
- lines.push(' _e2e_cf_probe "$_cp" || true');
- lines.push(' done');
- lines.push(
- ' if [ "$_e2e_have_cf" -eq 0 ] && [ -d "$HOME/.local/share/cursor-agent/versions" ]; then',
- );
- lines.push(
- ' for _vdir in "$HOME/.local/share/cursor-agent/versions"/*/cursor-agent; do',
- );
- lines.push(' [ "$_e2e_have_cf" -eq 1 ] && break');
- lines.push(' _e2e_cf_probe "$_vdir" || true');
- lines.push(' done');
- lines.push(' fi');
- lines.push(' fi');
- lines.push(' if [ "$_e2e_have_cf" -eq 1 ]; then');
- lines.push(
- ' echo "[e2e-ensure] ok: cursor family (strategy=$_E2E_CURSOR_STRAT; verified via --version)"',
- );
- lines.push(' elif [ "$_e2e_cursor_incompat" -eq 1 ]; then');
- lines.push(
- ' 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)"',
- );
- lines.push(' else');
- if (install) {
- lines.push(` echo "[e2e-ensure] installing ${label}..."`);
- lines.push(` ${install}`);
- } else {
- lines.push(
- ` echo "[e2e-ensure] no ensureInstallSh for ${label}; install ${bin} manually or append E2E_EXTRA_ENSURE_BASH"`,
- );
- }
- lines.push(' fi');
- continue;
- }
- if (bin === 'codex' && forceCodex) {
- lines.push(` echo "[e2e-ensure] E2E_CODEX_FORCE_ENSURE=1: reinstalling ${label}"`);
- if (install) {
- lines.push(` ${install}`);
- } else {
- lines.push(` echo "[e2e-ensure] no codex ensure command (internal error)"`);
- }
- continue;
- }
- lines.push(` if command -v ${bin} >/dev/null 2>&1; then`);
- lines.push(` echo "[e2e-ensure] ok: ${bin}"`);
- lines.push(` else`);
- if (install) {
- lines.push(` echo "[e2e-ensure] installing ${label}..."`);
- lines.push(` ${install}`);
- } else {
- lines.push(
- ` echo "[e2e-ensure] no ensureInstallSh for ${label}; install ${bin} manually or append E2E_EXTRA_ENSURE_BASH"`,
- );
- }
- lines.push(` fi`);
- }
- lines.push('fi');
- lines.push(
- 'if command -v cursor-installer >/dev/null 2>&1 && ! command -v cursor >/dev/null 2>&1; then',
- ' echo "[e2e-ensure] cursor-installer present but cursor shim missing; trying cursor-installer --extract --update stable"',
- ' cursor-installer --extract --update stable || echo "[e2e-ensure] cursor-installer --extract --update failed (non-fatal if extract already done)"',
- 'fi',
- '# official: always put Agent CLI first as `~/.local/bin/cursor` (PATH may still have legacy AppImage earlier)',
- 'if [ "$_E2E_CURSOR_STRAT" != "watzon" ] && command -v agent >/dev/null 2>&1; then',
- ' mkdir -p "$HOME/.local/bin"',
- ' ln -sf "$(command -v agent)" "$HOME/.local/bin/cursor" && echo "[e2e-ensure] official: ~/.local/bin/cursor -> agent (overrides legacy shim order)"',
- 'elif ! command -v cursor >/dev/null 2>&1 && command -v agent >/dev/null 2>&1; then',
- ' mkdir -p "$HOME/.local/bin"',
- ' ln -sf "$(command -v agent)" "$HOME/.local/bin/cursor" && echo "[e2e-ensure] linked ~/.local/bin/cursor -> agent (Agent CLI)"',
- 'fi',
- '# Always fix wrong-depth path .../cursor/cursor/cursor when extract exists (watzon / legacy)',
- '_e2e_cursor_bin=""',
- 'for _p in "$HOME/.local/share/cursor/cursor/usr/bin/cursor" "$HOME/.cursor/cursor/usr/bin/cursor"; do',
- ' if [ -x "$_p" ]; then',
- ' _e2e_cursor_runnable "$_p"',
- ' _prc=$?',
- ' if [ "$_prc" -eq 0 ]; then _e2e_cursor_bin="$_p"; break; fi',
- ' if [ "$_prc" -eq 2 ]; then _e2e_cursor_incompat=1; fi',
- ' fi',
- 'done',
- 'if [ -n "$_e2e_cursor_bin" ]; then',
- ' for _legacy_root in "$HOME/.local/share/cursor/cursor" "$HOME/.cursor/cursor"; do',
- ' if [ -d "$_legacy_root" ]; then',
- ' ln -sf "$_e2e_cursor_bin" "$_legacy_root/cursor" && echo "[e2e-ensure] compat symlink $_legacy_root/cursor -> $_e2e_cursor_bin"',
- ' fi',
- ' done',
- 'fi',
- 'if ! command -v cursor >/dev/null 2>&1; then',
- ' if [ -n "$_e2e_cursor_bin" ]; then',
- ' mkdir -p "$HOME/.local/bin"',
- ' ln -sf "$_e2e_cursor_bin" "$HOME/.local/bin/cursor" && echo "[e2e-ensure] linked ~/.local/bin/cursor -> $_e2e_cursor_bin"',
- ' elif [ "$_e2e_cursor_incompat" -eq 1 ]; then',
- ' echo "[e2e-ensure] skip cursor shim creation: extracted binary incompatible with host glibc"',
- ' elif ! command -v agent >/dev/null 2>&1; then',
- ' echo "[e2e-ensure] no cursor/agent on PATH and no extracted Cursor binary under ~/.local/share/cursor or ~/.cursor"',
- ' fi',
- 'fi',
- );
- lines.push(...buildEnsureSummaryScript(matrix));
- return `${lines.join('\n')}\n`;
- }
- /**
- * Parse E2E_PROBE_SKIP_AGENTS: comma-separated list of agent binary names to skip.
- * @param {NodeJS.ProcessEnv} [env]
- * @returns {Set<string>}
- */
- export function resolveProbeSkipAgents(env = process.env) {
- const raw = (env?.E2E_PROBE_SKIP_AGENTS ?? '').toString().trim();
- if (!raw) return new Set();
- return new Set(raw.split(',').map(s => s.trim().toLowerCase()).filter(Boolean));
- }
- /**
- * One isolated bash -s per agent (stdin from decoded pipe, not SSH session).
- * @param {{ agents: object[] }} matrix
- * @param {NodeJS.ProcessEnv} [env]
- */
- export function buildMatrixProbeScript(matrix, env = process.env) {
- const cursorSkipIfIncompat = (env.E2E_CURSOR_SKIP_IF_INCOMPAT ?? '1').trim() === '0' ? '0' : '1';
- const skipAgents = resolveProbeSkipAgents(env);
- const lines = [
- 'set +e -o pipefail',
- 'export PATH="$HOME/.local/bin:$PATH"',
- `export _E2E_CURSOR_SKIP_IF_INCOMPAT=${shellSingleQuoteBash(cursorSkipIfIncompat)}`,
- 'cd "$HOME" || true',
- 'echo "[e2e-probe] running one isolated bash per agent (order = agent-matrix.json)"',
- ];
- for (const a of matrix.agents) {
- const block = String(a.defaultProbeSh ?? '').trim();
- if (!block) continue;
- const bin = String(a.binary ?? '').trim();
- const label = String(a.name ?? bin ?? 'agent').replace(/'/g, `'\\''`);
- const binEsc = bin.replace(/'/g, `'\\''`);
- if (skipAgents.has(bin.toLowerCase())) {
- lines.push(`echo "[e2e-probe] >>> SKIP: ${label} (binary=${binEsc}) — E2E_PROBE_SKIP_AGENTS"`);
- continue;
- }
- const b64 = Buffer.from(`${block}\n`, 'utf8').toString('base64');
- lines.push(`echo "[e2e-probe] >>> start: ${label} (binary=${binEsc})"`);
- lines.push(`echo "[e2e-probe] command:"; printf '%s' '${b64}' | base64 -d | sed 's/^/ /'`);
- lines.push(`echo ""`);
- lines.push(
- `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
- `if [ "$_st" -eq 0 ]; then echo "[e2e-probe] <<< end: ${label} (exit 0)"; ` +
- `else echo "[e2e-probe] <<< end: ${label} (exit \${_st}, non-fatal)"; fi`,
- );
- }
- lines.push('echo "[e2e-probe] all matrix blocks finished"');
- return `${lines.join('\n')}\n`;
- }
scripts/e2e/lib/agent-probe-body.mjs · Bundled script · 46 lines · 1 finding marked
- /**
- * Build remote bash for agent probes. Uses optional `---` line separators: first segment runs as a
- * normal preamble (PATH, cd); each following segment runs in its own `bash -s` fed by base64 so
- * tools like Codex cannot consume the rest of the SSH-delivered script from inherited stdin.
- *
- * If there is no `---`, the entire command is executed via one base64-wrapped inner bash (still
- * avoids sharing the outer SSH stdin pipe with grandchildren in most setups).
- *
- * @param {string} probeCmd
- * @returns {string} full remote bash source (include set +e yourself inside probeCmd or rely on outer)
- */
- export function buildAgentProbeRemoteBody(probeCmd) {
- const raw = probeCmd.trim();
- if (!raw) return '';
- const parts = raw.split(/\r?\n---\r?\n/).map(p => p.trim()).filter(Boolean);
- if (parts.length === 1) {
- return [
- 'set +euo pipefail',
- 'echo "[e2e-probe] stdin-isolated inner bash (use lines containing only --- between agents for per-agent isolation)"',
- wrapInBase64Bash(parts[0]),
- ].join('\n');
- }
- const lines = [
- 'set +euo pipefail',
- 'echo "[e2e-probe] multi-block probe (' +
- String(parts.length - 1) +
- ' isolated segment(s) after preamble; divider = line --- only)"',
- wrapInBase64Bash(parts[0]),
- ];
- for (let i = 1; i < parts.length; i++) {
- lines.push(`echo "[e2e-probe] --- block ${i} ---"`);
- lines.push(wrapInBase64Bash(parts[i]));
- }
- return lines.join('\n');
- }
- /**
- * @param {string} bashSnippet
- * @returns {string} one remote statement
- */
- export function wrapInBase64Bash(bashSnippet) {
- const b64 = Buffer.from(`${bashSnippet}\n`, 'utf8').toString('base64');
- 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
- }
scripts/e2e/lib/e2e-scenarios.mjs · Bundled script · 1,795 lines · 1 finding marked
- /**
- * Helper module to export E2E scenario script generators for testing.
- * This separates the test-exportable functions from the main entry script.
- */
- import {
- buildRemoteInstallSlsCliQuotedArgs,
- shouldPropagateSlsToRemoteInstall,
- shellSingleQuoteBash,
- } from './propagate-sls-install.mjs';
- import { normalizeE2eQoderPersonalAccessToken } from './qoder-pat.mjs';
- import {
- buildRemoteSecretExportsSh,
- buildRemoteCodexConfigSh,
- buildRemoteClaudeOnboardingSkipSh,
- buildRemoteClaudeProxyConfigSh,
- } from './remote-agent-config.mjs';
- import {
- loadAgentMatrix,
- buildEnsureAgentClisScript,
- buildMatrixProbeScript,
- } from './agent-matrix.mjs';
- import { buildAgentProbeRemoteBody } from './agent-probe-body.mjs';
- /**
- * Default installer URL shared by run-remote-e2e and the per-scenario script generators.
- * Points at the loongsuite-dev OSS bucket so pre-release artifacts are exercised.
- */
- export const DEFAULT_E2E_INSTALLER_URL =
- 'https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-dev/loongsuite-pilot/loongsuite-pilot-installer-inner.sh';
- /**
- * Reboot autostart verification script generator.
- * 默认自动 sudo reboot。关键技巧:用 `nohup ... &` + `disown` 让 reboot 后台触发,
- * 然后本地脚本主动 exit 0,避免 SSH 被强制断开时得到 "Connection reset by peer" 被误判为失败。
- * @param {string} installerUrl
- * @param {string} userId
- * @param {NodeJS.ProcessEnv} env
- */
- export function rebootAutostartScript(installerUrl, userId, env) {
- const u = installerUrl.replace(/'/g, `'\\''`);
- const id = userId.replace(/'/g, `'\\''`);
- const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
- const installTail = slsFlags ? ` ${slsFlags}` : '';
- return `
- set -euo pipefail
- INSTALLER_URL='${u}'
- USER_ID='${id}'
- # Step 1: Install pilot
- echo "=== Phase 1: Install loongsuite-pilot ==="
- curl -fsSL "$INSTALLER_URL" | bash -s -- install --user.id "$USER_ID"${installTail}
- command -v loongsuite-pilot >/dev/null
- echo "install: loongsuite-pilot on PATH"
- # Step 2: Verify service is running
- echo "=== Phase 2: Verify initial service status ==="
- loongsuite-pilot status
- # Check systemd (no sudo needed for is-active query) and launchd
- if systemctl --user is-active --quiet loongsuite-pilot.service 2>/dev/null; then
- echo "✓ autostart: systemd user unit is active"
- elif systemctl is-active --quiet loongsuite-pilot.service 2>/dev/null; then
- echo "✓ autostart: systemd system-level unit is active"
- elif command -v launchctl >/dev/null 2>&1 && launchctl list 2>/dev/null | grep -q loongsuite-pilot; then
- echo "✓ autostart: launchd job is loaded"
- elif pgrep -f 'loongsuite-pilot|collector-daemon|updater-daemon' >/dev/null; then
- echo "✓ autostart: process running (service manager unknown)"
- else
- echo "✗ WARNING: service not detected"
- fi
- # Step 3: Capture current version and diagnostics
- loongsuite-pilot info
- echo "=== Pre-reboot diagnostics ==="
- ps aux | grep -E 'loongsuite-pilot|node.*dist/index' | grep -v grep || true
- ls -la "$HOME/.loongsuite-pilot/current" 2>/dev/null || true
- # Step 4: Stop service cleanly before reboot
- echo "=== Phase 3: Stop service and prepare reboot ==="
- loongsuite-pilot stop || true
- sleep 2
- # Write marker file (proves this is the same machine after reboot)
- echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$HOME/.loongsuite-pilot/.e2e-reboot-marker"
- echo "✓ Marker written: $HOME/.loongsuite-pilot/.e2e-reboot-marker"
- # Step 5: Auto-reboot
- # Check sudo availability (passwordless required for non-interactive ssh pipe)
- if ! sudo -n true 2>/dev/null; then
- echo "❌ ERROR: passwordless sudo is required for auto-reboot"
- echo ""
- echo "Please configure passwordless sudo on the remote host:"
- echo " echo \"$USER ALL=(ALL) NOPASSWD: /sbin/reboot, /usr/sbin/reboot\" | sudo tee /etc/sudoers.d/loongsuite-pilot-e2e"
- exit 1
- fi
- echo "=== Phase 4: Triggering reboot (SSH will disconnect — this is EXPECTED) ==="
- echo "ℹ 'Connection reset by peer' / 'Broken pipe' is normal: remote sshd is killed during reboot."
- echo "ℹ The local runner treats this as SUCCESS for reboot-autostart scenario."
- # Key trick: schedule reboot asynchronously and exit immediately.
- # • nohup + & + disown — detach from current shell so SSH can close cleanly
- # • 'sleep 1' delay — gives the local side a chance to receive the final echoes
- # • redirect all output — prevents reboot daemon from holding stdout/stderr
- nohup bash -c 'sleep 1 && sudo reboot' >/dev/null 2>&1 &
- disown || true
- echo "✓ Reboot scheduled (will fire in ~1 second)"
- echo "✓ Phase 1 complete. After ~30s, run:"
- echo " export E2E_SCENARIO=post-reboot-verify"
- echo " npm run test:e2e:remote"
- # Proactively exit with 0 so that SSH disconnect during reboot doesn't surface as error
- exit 0
- `;
- }
- /**
- * Post-reboot verification script generator.
- */
- export function postRebootVerificationScript() {
- return `
- set -euo pipefail
- echo "=== Post-Reboot Verification ==="
- # Check marker file
- MARKER="$HOME/.loongsuite-pilot/.e2e-reboot-marker"
- if [ -f "$MARKER" ]; then
- echo "Reboot marker found (written at: $(cat "$MARKER"))"
- else
- echo "ERROR: Reboot marker not found — this may be a fresh machine"
- exit 1
- fi
- # Check if pilot command is available
- if ! command -v loongsuite-pilot >/dev/null; then
- echo "ERROR: loongsuite-pilot not on PATH after reboot"
- exit 1
- fi
- echo "✓ loongsuite-pilot on PATH"
- # Check service status
- if systemctl --user is-active --quiet loongsuite-pilot.service 2>/dev/null; then
- echo "✓ systemd user unit loongsuite-pilot.service is ACTIVE"
- systemctl --user status loongsuite-pilot.service --no-pager || true
- elif systemctl is-active --quiet loongsuite-pilot.service 2>/dev/null; then
- echo "✓ systemd system-level unit loongsuite-pilot.service is ACTIVE"
- systemctl status loongsuite-pilot.service --no-pager 2>/dev/null || true
- else
- echo "✗ systemd unit NOT active (checking alternatives...)"
- if pgrep -f 'loongsuite-pilot|node.*dist/index' >/dev/null; then
- echo "✓ loongsuite-pilot process found (via pgrep)"
- ps aux | grep -E 'loongsuite-pilot|node.*dist/index' | grep -v grep || true
- else
- echo "✗ No pilot process found"
- exit 1
- fi
- fi
- # Check updater daemon
- if systemctl --user is-active --quiet loongsuite-pilot-updater.service 2>/dev/null; then
- echo "✓ updater daemon is ACTIVE (user-level)"
- elif systemctl is-active --quiet loongsuite-pilot-updater.service 2>/dev/null; then
- echo "✓ updater daemon is ACTIVE (system-level)"
- else
- echo "⚠ updater daemon not detected via systemd (may still be running)"
- fi
- # Verify data integrity
- if [ -d "$HOME/.loongsuite-pilot" ]; then
- echo "✓ data directory exists"
- ls -la "$HOME/.loongsuite-pilot/" || true
- else
- echo "✗ data directory missing"
- exit 1
- fi
- # Quick version check
- loongsuite-pilot info
- echo "=== Post-reboot verification PASSED ==="
- `;
- }
- /**
- * Multi-account install script generator.
- */
- export function multiAccountInstallScript(installerUrl, userIds, env) {
- const u = installerUrl.replace(/'/g, `'\\''`);
- const ids = userIds.replace(/'/g, `'\\''`);
- const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
- const installTail = slsFlags ? ` ${slsFlags}` : '';
- return `
- set -euo pipefail
- INSTALLER_URL='${u}'
- USER_IDS='${ids}'
- echo "=== Multi-Account Install Test ==="
- echo "User IDs: $USER_IDS"
- # Parse comma-separated user IDs
- IFS=',' read -ra USERS <<< "$USER_IDS"
- for i in "\${!USERS[@]}"; do
- USER_ID="\${USERS[$i]}"
- USER_HOME=$(eval echo "~user\${i}")
- echo ""
- echo "--- Installing for user\${i} (ID: $USER_ID) ---"
- # Check if user exists, create if not
- if ! id "user\${i}" &>/dev/null; then
- echo "Creating user\${i}..."
- sudo useradd -m -s /bin/bash "user\${i}" || {
- echo "WARNING: Cannot create user\${i} (may need root), using current user with different config dir"
- USER_HOME="$HOME/.loongsuite-pilot-test-user\${i}"
- }
- fi
- # Install pilot for this user
- if id "user\${i}" &>/dev/null; then
- sudo -u "user\${i}" bash -c "
- set -euo pipefail
- export HOME=$(eval echo ~user\${i})
- curl -fsSL '${u}' | bash -s -- install --user.id '\${USER_ID}'${installTail}
- command -v loongsuite-pilot >/dev/null || echo 'WARNING: loongsuite-pilot not in PATH for user\${i}'
- test -d \"\$HOME/.loongsuite-pilot\" && echo '✓ data dir created' || echo '✗ data dir missing'
- "
- else
- # Fallback: install in isolated directory under current user
- mkdir -p "$USER_HOME"
- AGENT_DATA_COLLECTION_CONFIG="$USER_HOME/config.json" curl -fsSL "$INSTALLER_URL" | bash -s -- install --user.id "$USER_ID"${installTail}
- echo "✓ Installed for user\${i} (isolated mode in $USER_HOME)"
- fi
- done
- # Verify all installations
- echo ""
- echo "=== Verification ==="
- for i in "\${!USERS[@]}"; do
- if id "user\${i}" &>/dev/null; then
- sudo -u "user\${i}" bash -c "
- echo \"user\${i}: \$(loongsuite-pilot info 2>&1 || echo 'info command failed')\"
- test -f \"\$HOME/.loongsuite-pilot/config.json\" && echo \" ✓ config.json exists\" || echo \" ✗ config.json missing\"
- "
- else
- echo "user\${i}: (isolated mode)"
- test -f "$HOME/.loongsuite-pilot-test-user\${i}/config.json" && echo " ✓ config.json exists" || echo " ✗ config.json missing"
- fi
- done
- echo ""
- echo "=== Multi-account install test completed ==="
- `;
- }
- /**
- * Auto-upgrade test script generator.
- */
- export function autoUpgradeScript(installerUrl, userId, env) {
- const u = installerUrl.replace(/'/g, `'\\''`);
- const id = userId.replace(/'/g, `'\\''`);
- const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
- const installTail = slsFlags ? ` ${slsFlags}` : '';
- return `
- set -euo pipefail
- INSTALLER_URL='${u}'
- USER_ID='${id}'
- echo "=== Auto-Upgrade Test ==="
- # Phase 1: Initial install
- echo "--- Phase 1: Install pilot ---"
- curl -fsSL "$INSTALLER_URL" | bash -s -- install --user.id "$USER_ID"${installTail}
- command -v loongsuite-pilot >/dev/null
- echo "✓ Initial install successful"
- # Capture initial version
- INITIAL_VERSION=$(loongsuite-pilot info 2>&1 | head -1)
- INITIAL_COMMIT=$(cat "$HOME/.loongsuite-pilot/VERSION" | grep git_commit | cut -d'=' -f2)
- echo "Initial version: $INITIAL_VERSION"
- echo "Initial commit: $INITIAL_COMMIT"
- # Phase 2: Verify initial service running
- echo ""
- echo "--- Phase 2: Verify initial service ---"
- loongsuite-pilot status || true
- ps aux | grep -E 'loongsuite-pilot|node.*dist/index' | grep -v grep || true
- # Phase 3: Trigger upgrade
- echo ""
- echo "--- Phase 3: Trigger upgrade ---"
- echo "Running upgrade command..."
- curl -fsSL "$INSTALLER_URL" | bash -s -- upgrade
- # Wait for upgrade to complete
- echo "Waiting 10s for upgrade to stabilize..."
- sleep 10
- # Phase 4: Verify upgraded version
- echo ""
- echo "--- Phase 4: Verify upgraded version ---"
- if [ -f "$HOME/.loongsuite-pilot/VERSION" ]; then
- NEW_VERSION=$(loongsuite-pilot info 2>&1 | head -1)
- NEW_COMMIT=$(cat "$HOME/.loongsuite-pilot/VERSION" | grep git_commit | cut -d'=' -f2)
- echo "New version: $NEW_VERSION"
- echo "New commit: $NEW_COMMIT"
- if [ "$INITIAL_COMMIT" = "$NEW_COMMIT" ]; then
- echo "⚠ Version unchanged (may already be latest)"
- else
- echo "✓ Version changed from $INITIAL_COMMIT to $NEW_COMMIT"
- fi
- else
- echo "✗ VERSION file missing after upgrade"
- exit 1
- fi
- # Phase 5: Verify service restarted after upgrade
- echo ""
- echo "--- Phase 5: Verify service auto-restart ---"
- if systemctl --user is-active --quiet loongsuite-pilot.service 2>/dev/null; then
- echo "✓ systemd service is ACTIVE after upgrade (user-level)"
- systemctl --user status loongsuite-pilot.service --no-pager | head -10 || true
- elif systemctl is-active --quiet loongsuite-pilot.service 2>/dev/null; then
- echo "✓ systemd service is ACTIVE after upgrade (system-level)"
- systemctl status loongsuite-pilot.service --no-pager 2>/dev/null | head -10 || true
- else
- if pgrep -f 'loongsuite-pilot|node.*dist/index' >/dev/null; then
- echo "✓ pilot process found after upgrade"
- else
- echo "✗ pilot process NOT found after upgrade"
- exit 1
- fi
- fi
- # Phase 6: Verify data integrity
- echo ""
- echo "--- Phase 6: Verify data integrity ---"
- if [ -f "$HOME/.loongsuite-pilot/config.json" ]; then
- echo "✓ config.json preserved"
- cat "$HOME/.loongsuite-pilot/config.json" | grep -o '"userId":"[^"]*"' || true
- else
- echo "✗ config.json missing after upgrade"
- exit 1
- fi
- if [ -d "$HOME/.loongsuite-pilot/versions" ]; then
- echo "✓ versions directory exists (multi-version management)"
- ls -la "$HOME/.loongsuite-pilot/versions/" || true
- else
- echo "⚠ versions directory not found"
- fi
- echo ""
- echo "=== Auto-Upgrade Test PASSED ==="
- `;
- }
- /**
- * 解析 E2E_AGENT_VERSIONS_N,默认 3。
- * @param {NodeJS.ProcessEnv} env
- */
- export function resolveVersionMatrixN(env) {
- const raw = (env?.E2E_AGENT_VERSIONS_N ?? '3').toString().trim();
- const n = Number.parseInt(raw, 10);
- if (!Number.isFinite(n) || n <= 0) return 3;
- return Math.min(n, 20);
- }
- /**
- * 解析 E2E_AGENT_VERSIONS_FILTER(逗号分隔的 binary 或 id),空值表示不过滤。
- * @param {NodeJS.ProcessEnv} env
- */
- export function resolveVersionMatrixFilter(env) {
- const raw = (env?.E2E_AGENT_VERSIONS_FILTER ?? '').toString().trim();
- if (!raw) return null;
- return raw
- .split(',')
- .map(s => s.trim().toLowerCase())
- .filter(Boolean);
- }
- /**
- * 从 matrix 中筛选出支持版本矩阵的 agents(npmPackage 非空)。
- * @param {{agents: object[]}} matrix
- * @param {NodeJS.ProcessEnv} env
- */
- export function resolveVersionMatrixAgents(matrix, env = process.env) {
- const filter = resolveVersionMatrixFilter(env);
- const agents = (matrix?.agents ?? []).filter(a => {
- const pkg = typeof a.npmPackage === 'string' ? a.npmPackage.trim() : '';
- if (!pkg) return false;
- if (!filter) return true;
- const bin = String(a.binary ?? '').trim().toLowerCase();
- const id = String(a.id ?? '').trim().toLowerCase();
- return filter.includes(bin) || filter.includes(id);
- });
- return agents;
- }
- /**
- * Agent 鉴权 / 配置注入 prologue(复用 install-smoke 的处理):
- * - CODEX_OPENAI_API_KEY / ANTHROPIC_BASE_URL / ANTHROPIC_API_KEY / ANTHROPIC_MODEL / CURSOR_API_KEY
- * - 可选:~/.codex/config.toml、~/.claude.json(hasCompletedOnboarding)、~/.config/claude-code-proxy/config.json
- * - QODER_PERSONAL_ACCESS_TOKEN
- * 这些 export 的环境变量会被后续 `bash --norc --noprofile -s` 子 shell 继承(shell 进程默认继承环境变量)。
- * @param {NodeJS.ProcessEnv} env
- * @returns {string}
- */
- export function buildVersionMatrixPrologueSh(env = process.env) {
- const chunks = [];
- const secrets = buildRemoteSecretExportsSh(env);
- if (secrets) chunks.push(secrets.trimEnd());
- const codexCfg = buildRemoteCodexConfigSh(env);
- if (codexCfg) chunks.push(codexCfg.trimEnd());
- const claudeOnboard = buildRemoteClaudeOnboardingSkipSh(env);
- if (claudeOnboard) chunks.push(claudeOnboard.trimEnd());
- const claudeProxy = buildRemoteClaudeProxyConfigSh(env);
- if (claudeProxy) chunks.push(claudeProxy.trimEnd());
- const tok = normalizeE2eQoderPersonalAccessToken(env?.E2E_QODER_PERSONAL_ACCESS_TOKEN);
- if (tok) chunks.push(`export QODER_PERSONAL_ACCESS_TOKEN=${shellSingleQuoteBash(tok)}`);
- if (!chunks.length) return '';
- return `${chunks.join('\n')}\n`;
- }
- /**
- * version-matrix 场景可选的 loongsuite-pilot 安装前导(类似 install-smoke)。
- * 如果 env 里有 E2E_USER_ID(+ 可选 SLS flags),则在 Node 升级后、agent 循环前自动重装 pilot,保证 SLS 能看到数据。
- * @param {NodeJS.ProcessEnv} env
- */
- export function buildVersionMatrixInstallPreludeSh(env = process.env) {
- const userId = (env?.E2E_USER_ID ?? '').trim();
- if (!userId) return '';
- const installerUrl = (env?.E2E_INSTALLER_URL ?? DEFAULT_E2E_INSTALLER_URL).replace(/'/g, `'\\''`);
- const slsFlags = buildRemoteInstallSlsCliQuotedArgs(env);
- const installTail = slsFlags ? ` ${slsFlags}` : '';
- const uid = userId.replace(/'/g, `'\\''`);
- return `
- # [version-matrix] 重装/刷新 pilot + SLS 配置(同 install-smoke),保证 SLS Logstore 能收到数据
- echo "[version-matrix] (re-)installing loongsuite-pilot with SLS flags ..."
- curl -fsSL '${installerUrl}' | bash -s -- install --user.id '${uid}'${installTail} || {
- echo "[version-matrix] WARN: pilot install failed (may already be installed) — continuing"
- }
- `;
- }
- /**
- * 生成远端 version-matrix 脚本:对每个支持版本矩阵的 agent,串行安装最近 N 个版本并执行 probe。
- * 当 E2E_USER_ID 存在时自动重装 pilot(带 SLS flags)以保证遥测数据可观测。
- * @param {{agents: object[]}} matrix
- * @param {NodeJS.ProcessEnv} env
- */
- export function versionMatrixScript(matrix, env = process.env) {
- const agents = resolveVersionMatrixAgents(matrix, env);
- const n = resolveVersionMatrixN(env);
- const requirePilot = (env?.E2E_VERSION_MATRIX_REQUIRE_PILOT ?? '1').toString().trim() !== '0';
- const restoreLatest = (env?.E2E_VERSION_MATRIX_RESTORE_LATEST ?? '1').toString().trim() !== '0';
- const prologue = buildVersionMatrixPrologueSh(env);
- const installPrelude = buildVersionMatrixInstallPreludeSh(env);
- if (agents.length === 0) {
- return `
- set +e
- ${prologue}echo "[version-matrix] no agents with npmPackage found (filter=\${E2E_AGENT_VERSIONS_FILTER:-})"
- exit 0
- `;
- }
- const perAgentBlocks = agents
- .map(a => {
- const pkg = a.npmPackage.replace(/'/g, `'\\''`);
- const bin = String(a.binary ?? '').replace(/'/g, `'\\''`);
- const label = String(a.name ?? a.binary ?? pkg).replace(/'/g, `'\\''`);
- const probe = (a.defaultProbeSh ?? '').toString();
- const probeB64 = Buffer.from(probe + '\n', 'utf8').toString('base64');
- return `
- echo ""
- echo "########################################"
- echo "# [version-matrix] agent=${label} (binary=${bin}, pkg=${pkg})"
- echo "########################################"
- _run_agent_matrix '${pkg}' '${bin}' '${label}' '${probeB64}'
- `;
- })
- .join('\n');
- return `
- set +e
- ${prologue}
- # prepend npm global bin to avoid stale PATH symlinks
- _NPM_PREFIX="$(npm config get prefix 2>/dev/null || true)"
- if [ -n "$_NPM_PREFIX" ] && [ -d "$_NPM_PREFIX/bin" ]; then
- export PATH="$_NPM_PREFIX/bin:$HOME/.local/bin:$PATH"
- else
- export PATH="$HOME/.local/bin:$PATH"
- fi
- echo "[version-matrix] mode=serial; versions_per_agent=${n}; filter=\${E2E_AGENT_VERSIONS_FILTER:-<none>}; npm_prefix=\${_NPM_PREFIX:-<unknown>}"
- # remove stale ~/.local/bin/<bin> -> qodercli symlinks left by old scripts
- _cleanup_stale_bin() {
- _b="$1"
- [ "$_b" = "qoder" ] && return 0
- _p="$HOME/.local/bin/$_b"
- if [ -L "$_p" ]; then
- _tgt="$(readlink "$_p" 2>/dev/null || true)"
- case "$_tgt" in
- *qodercli*|*@qoder-ai*) rm -f "$_p" && echo "[version-matrix] removed stale $_p -> $_tgt";;
- esac
- fi
- }
- if ! command -v npm >/dev/null 2>&1; then
- echo "[version-matrix] ERROR: npm not on PATH on remote. Install Node.js/npm first."
- exit 2
- fi
- if ! command -v node >/dev/null 2>&1; then
- echo "[version-matrix] ERROR: node not on PATH on remote."
- exit 2
- fi
- # auto-upgrade Node via nvm if below min (old Node may crash newer CLI bundles)
- _MIN_NODE_MAJOR="\${E2E_VERSION_MATRIX_MIN_NODE:-22}"
- _AUTO_UPGRADE_NODE="\${E2E_VERSION_MATRIX_AUTO_UPGRADE_NODE:-1}"
- _node_major() { node -v 2>/dev/null | sed -E 's/^v([0-9]+).*/\\1/'; }
- _cur_major="$(_node_major)"
- if [ -z "$_cur_major" ] || [ "$_cur_major" -lt "$_MIN_NODE_MAJOR" ] 2>/dev/null; then
- echo "[version-matrix] current node=v$_cur_major < required v$_MIN_NODE_MAJOR (to avoid bundle/runtime incompat on old Node)"
- if [ "$_AUTO_UPGRADE_NODE" != "1" ]; then
- echo "[version-matrix] ERROR: auto-upgrade disabled. Upgrade Node manually or set E2E_VERSION_MATRIX_AUTO_UPGRADE_NODE=1."
- exit 2
- fi
- _OLD_NPM_BIN="$(npm config get prefix 2>/dev/null)/bin"
- export NVM_DIR="\${NVM_DIR:-$HOME/.nvm}"
- if [ ! -s "$NVM_DIR/nvm.sh" ]; then
- echo "[version-matrix] installing nvm 0.39.7 to $NVM_DIR ..."
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash >/tmp/.e2e-vm-nvm-install.log 2>&1 || {
- echo "[version-matrix] ERROR: nvm install failed (tail):"; tail -20 /tmp/.e2e-vm-nvm-install.log; exit 2;
- }
- elif command -v wget >/dev/null 2>&1; then
- wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash >/tmp/.e2e-vm-nvm-install.log 2>&1 || {
- echo "[version-matrix] ERROR: nvm install failed (tail):"; tail -20 /tmp/.e2e-vm-nvm-install.log; exit 2;
- }
- else
- echo "[version-matrix] ERROR: neither curl nor wget on PATH; cannot install nvm."; exit 2;
- fi
- fi
- # shellcheck disable=SC1090
- . "$NVM_DIR/nvm.sh" || { echo "[version-matrix] ERROR: cannot source $NVM_DIR/nvm.sh"; exit 2; }
- echo "[version-matrix] nvm install $_MIN_NODE_MAJOR ..."
- nvm install "$_MIN_NODE_MAJOR" >/tmp/.e2e-vm-nvm-node.log 2>&1 || {
- echo "[version-matrix] ERROR: nvm install $_MIN_NODE_MAJOR failed (tail):"; tail -30 /tmp/.e2e-vm-nvm-node.log; exit 2;
- }
- nvm use "$_MIN_NODE_MAJOR" >/dev/null 2>&1 || { echo "[version-matrix] ERROR: nvm use $_MIN_NODE_MAJOR failed"; exit 2; }
- nvm alias default "$_MIN_NODE_MAJOR" >/dev/null 2>&1 || true
- # old-glibc hosts (Linux 7U / CentOS 7): apply Aliyun patchelf if node -v fails
- _AUTO_PATCHELF="\${E2E_VERSION_MATRIX_AUTO_PATCHELF:-1}"
- _node_try="$(node -v 2>&1)"
- _node_try_st=$?
- if [ "$_node_try_st" -ne 0 ] || printf '%s' "$_node_try" | grep -qE 'GLIBC|GLIBCXX|CXXABI|not found|error while loading' 2>/dev/null; then
- echo "[version-matrix] node=v$_MIN_NODE_MAJOR has glibc/libstdc++ incompat on this host (Linux 7U / CentOS 7 pattern):"
- printf '%s\n' "$_node_try" | head -5 | sed 's/^/ /'
- if [ "$_AUTO_PATCHELF" != "1" ]; then
- echo "[version-matrix] ERROR: auto-patchelf disabled (E2E_VERSION_MATRIX_AUTO_PATCHELF=0). Apply patch manually."
- exit 2
- fi
- echo "[version-matrix] applying Aliyun patchelf_node_for_7u.sh ..."
- _patchelf_log="/tmp/.e2e-vm-patchelf.log"
- _patchelf_url="https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite/loongsuite-pilot/patchelf_node_for_7u.sh"
- if command -v curl >/dev/null 2>&1; then
- curl -fsSL "$_patchelf_url" | bash >"$_patchelf_log" 2>&1
- elif command -v wget >/dev/null 2>&1; then
- wget -qO- "$_patchelf_url" | bash >"$_patchelf_log" 2>&1
- else
- echo "[version-matrix] ERROR: neither curl nor wget on PATH; cannot fetch patchelf script."; exit 2;
- fi
- _patch_st=$?
- if [ "$_patch_st" -ne 0 ]; then
- echo "[version-matrix] ERROR: patchelf_node_for_7u.sh failed (rc=$_patch_st) tail:"
- tail -30 "$_patchelf_log" 2>/dev/null || true
- exit 2
- fi
- _node_try2="$(node -v 2>&1)"
- if [ $? -ne 0 ] || printf '%s' "$_node_try2" | grep -qE 'GLIBC|GLIBCXX|CXXABI|not found|error while loading' 2>/dev/null; then
- echo "[version-matrix] ERROR: node still broken after patchelf:"
- printf '%s\n' "$_node_try2" | head -10 | sed 's/^/ /'
- echo "[version-matrix] patchelf log tail:"; tail -20 "$_patchelf_log" 2>/dev/null || true
- exit 2
- fi
- echo "[version-matrix] patchelf succeeded; node=$_node_try2"
- fi
- echo "[version-matrix] switched to node=$(node -v 2>/dev/null) npm=$(npm -v 2>/dev/null)"
- _NPM_PREFIX="$(npm config get prefix 2>/dev/null || true)"
- if [ -n "$_NPM_PREFIX" ] && [ -d "$_NPM_PREFIX/bin" ]; then
- export PATH="$_NPM_PREFIX/bin:$HOME/.local/bin:$PATH"
- fi
- if [ -n "$_OLD_NPM_BIN" ] && [ -d "$_OLD_NPM_BIN" ] && [ "$_OLD_NPM_BIN" != "$_NPM_PREFIX/bin" ]; then
- case ":$PATH:" in *":$_OLD_NPM_BIN:"*) ;; *) export PATH="$PATH:$_OLD_NPM_BIN";; esac
- fi
- echo "[version-matrix] npm_prefix(updated)=\${_NPM_PREFIX:-<unknown>}"
- fi
- ${installPrelude}
- ${requirePilot ? `if ! command -v loongsuite-pilot >/dev/null 2>&1; then
- echo "[version-matrix] ERROR: loongsuite-pilot not installed. Run install-smoke first or set E2E_VERSION_MATRIX_REQUIRE_PILOT=0 to skip."
- exit 2
- fi
- loongsuite-pilot info 2>&1 | head -3 || true` : '# Pilot precheck skipped (E2E_VERSION_MATRIX_REQUIRE_PILOT=0)'}
- _latest_versions() {
- _pkg="$1"; _n="$2"
- npm view "$_pkg" versions --json 2>/dev/null | node -e "
- let raw='';
- process.stdin.on('data', c => raw += c);
- process.stdin.on('end', () => {
- try {
- const j = JSON.parse(raw);
- const arr = Array.isArray(j) ? j : [j];
- 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;
- const filtered = arr.filter(v => typeof v === 'string' && !PLAT.test(v));
- const n = parseInt(process.argv[1], 10) || 3;
- const slice = filtered.slice(-n).reverse();
- for (const v of slice) process.stdout.write(v + '\\n');
- } catch (e) { process.exit(0); }
- });
- " "$_n"
- }
- _run_agent_matrix() {
- _pkg="$1"; _bin="$2"; _label="$3"; _probe_b64="$4"
- _cleanup_stale_bin "\${_bin}"
- echo "[version-matrix] querying npm: \${_pkg}"
- _versions="$(_latest_versions "\${_pkg}" "${n}")"
- if [ -z "\${_versions}" ]; then
- echo "[version-matrix] WARN: cannot fetch versions for \${_pkg} (network? package renamed?) — skipping"
- return 0
- fi
- echo "[version-matrix] \${_label} most recent versions (latest first):"
- echo "\${_versions}" | sed 's/^/ - /'
- npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
- for _v in \${_versions}; do
- echo ""
- echo ">>> [version-matrix] agent=\${_label} version=\${_v} >>>"
- _spec="\${_pkg}@\${_v}"
- if ! npm install -g "\${_spec}" >/tmp/.e2e-vm-install.log 2>&1; then
- echo "[version-matrix] install failed for \${_spec} (tail):"
- tail -20 /tmp/.e2e-vm-install.log || true
- echo "<<< [version-matrix] agent=\${_label} version=\${_v} SKIPPED <<<"
- continue
- fi
- _abs_bin=""
- if [ -n "$_NPM_PREFIX" ] && [ -x "$_NPM_PREFIX/bin/\${_bin}" ]; then
- _abs_bin="$_NPM_PREFIX/bin/\${_bin}"
- elif [ "\${_bin}" = "qoder" ] && [ -n "$_NPM_PREFIX" ] && [ -x "$_NPM_PREFIX/bin/qodercli" ]; then
- _abs_bin="$_NPM_PREFIX/bin/qodercli"
- mkdir -p "$HOME/.local/bin" && ln -sf "$_abs_bin" "$HOME/.local/bin/qoder" 2>/dev/null || true
- elif command -v "\${_bin}" >/dev/null 2>&1; then
- _abs_bin="$(command -v "\${_bin}")"
- elif [ "\${_bin}" = "qoder" ] && command -v qodercli >/dev/null 2>&1; then
- _abs_bin="$(command -v qodercli)"
- mkdir -p "$HOME/.local/bin" && ln -sf "$_abs_bin" "$HOME/.local/bin/qoder" 2>/dev/null || true
- fi
- if [ -z "$_abs_bin" ]; then
- echo "[version-matrix] WARN: \${_bin} not on PATH after install (likely platform-specific subpackage without top-level bin) — SKIPPED"
- echo "<<< [version-matrix] agent=\${_label} version=\${_v} SKIPPED <<<"
- npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
- continue
- fi
- echo "[version-matrix] resolved \${_bin} -> $_abs_bin"
- _ver_out="$("$_abs_bin" --version 2>&1)"
- _ver_st=$?
- printf '%s\n' "$_ver_out" | head -3
- if [ "$_ver_st" -ne 0 ] || printf '%s' "$_ver_out" | grep -qE 'SyntaxError|Invalid regular expression|ERR_UNSUPPORTED|Cannot find module' 2>/dev/null; then
- echo "[version-matrix] WARN: \${_bin} --version failed (rc=$_ver_st) — likely bundle/runtime incompatibility; SKIPPED probe for this version"
- _node_v="$(node -v 2>/dev/null || echo unknown)"
- echo "[version-matrix] node=$_node_v; consider newer Node (20+/22+) or newer CLI version"
- echo "<<< [version-matrix] agent=\${_label} version=\${_v} SKIPPED (incompat) <<<"
- npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
- continue
- fi
- # dedup codex [hooks.state."..."] to avoid duplicate-key warnings
- if [ "\${_bin}" = "codex" ] && [ -f "$HOME/.codex/config.toml" ]; then
- _cfg="$HOME/.codex/config.toml"
- awk '
- /^\\[hooks\\.state\\./ {
- if ($0 in seen) { skip = 1; next }
- seen[$0] = 1; skip = 0; print; next
- }
- /^\\[/ { skip = 0 }
- !skip { print }
- ' "$_cfg" > "$_cfg.vmtmp" && mv "$_cfg.vmtmp" "$_cfg" || rm -f "$_cfg.vmtmp"
- fi
- _probe_log="$(mktemp 2>/dev/null || echo "/tmp/.e2e-vm-probe-$$")"
- printf '%s' "\${_probe_b64}" | base64 -d | bash --norc --noprofile -s >"$_probe_log" 2>&1
- Dismissed after review: Decodes base64 and runs the result in a shell
- Line 701 on GitHub
- _st=$?
- _lines=$(wc -l < "$_probe_log" 2>/dev/null | tr -d ' ' || echo 0)
- _max=\${E2E_VERSION_MATRIX_PROBE_LOG_LINES:-40}
- if [ "$_lines" -gt "$_max" ]; then
- head -n "$_max" "$_probe_log"
- echo "[version-matrix] ... (probe output truncated at $_max/$_lines lines; E2E_VERSION_MATRIX_PROBE_LOG_LINES to override)"
- else
- cat "$_probe_log"
- fi
- rm -f "$_probe_log" 2>/dev/null || true
- if [ "\${_st}" -eq 0 ]; then
- echo "<<< [version-matrix] agent=\${_label} version=\${_v} probe exit 0 <<<"
- else
- echo "<<< [version-matrix] agent=\${_label} version=\${_v} probe exit \${_st} (non-fatal) <<<"
- fi
- npm uninstall -g "\${_pkg}" >/dev/null 2>&1 || true
- done
- ${restoreLatest ? `echo "[version-matrix] restoring \${_pkg}@latest ..."
- npm install -g "\${_pkg}" >/tmp/.e2e-vm-restore.log 2>&1 || {
- echo "[version-matrix] WARN: restore latest failed (tail):"
- tail -10 /tmp/.e2e-vm-restore.log || true
- }` : '# restore latest disabled (E2E_VERSION_MATRIX_RESTORE_LATEST=0)'}
- }
- ${perAgentBlocks}
- echo ""
- echo "=== [version-matrix] all agents finished ==="
- echo "ℹ SLS 数据差异以运行时间段 + 上面的 '>>> agent=X version=Y >>>' 日志指示线人工对齐。"
- ${buildJsonlValidationSh(env)}
- exit 0
- `;
- }
- /**
- * 生成内嵌在远端 bash 中的 Node 校验器源码,校验 ~/.loongsuite-pilot/logs/output/*.jsonl
- * 是否满足 AgentActivityEntry (src/types/events.ts) 的必填字段 schema。
- * 独立导出便于单元测试。
- */
- export const JSONL_VALIDATOR_JS = `'use strict';
- const fs = require('fs');
- const path = require('path');
- const LOG_DIR = process.env._JV_LOG_DIR || (process.env.HOME + '/.loongsuite-pilot/logs/output');
- const SINCE_SECONDS = parseInt(process.env.E2E_JSONL_SINCE_SECONDS || '0', 10);
- const STRICT = (process.env.E2E_JSONL_STRICT || '0') === '1';
- const DEFAULT_AGENT_FILTER = 'claude-code,codex,qoder-cli,cursor-cli,qwen-code-cli,opencode';
- const _RAW_FILTER = process.env.E2E_JSONL_AGENT_FILTER;
- const _FILTER_SRC = (_RAW_FILTER === undefined || _RAW_FILTER === '') ? DEFAULT_AGENT_FILTER : _RAW_FILTER;
- const AGENT_FILTER = (_FILTER_SRC.trim().toLowerCase() === 'all' || _FILTER_SRC.trim() === '*')
- ? []
- : _FILTER_SRC.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
- const MAX_SAMPLES = parseInt(process.env.E2E_JSONL_MAX_SAMPLES || '3', 10);
- const COMMON_REQUIRED = [
- 'time_unix_nano', 'event.id', 'user.id', 'event.name',
- 'gen_ai.session.id', 'gen_ai.agent.type', 'gen_ai.provider.name',
- ];
- const EVENT_NAME_ENUM = new Set([
- 'gen_ai.agent.invoke', 'gen_ai.agent.result',
- 'llm.request', 'llm.response', 'tool.call', 'tool.result',
- 'gen_ai.model.request', 'gen_ai.model.response', 'gen_ai.tool.call', 'gen_ai.tool.result',
- 'gen_ai.agent.invoke', 'gen_ai.agent.result',
- 'skill.use', 'tool.approve', 'agent.input', 'other',
- ]);
- const CONDITIONAL_REQUIRED = {
- 'tool.call': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
- 'tool.result': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
- 'gen_ai.tool.call': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
- 'gen_ai.tool.result': ['gen_ai.tool.name', 'gen_ai.tool.call.id'],
- 'gen_ai.agent.invoke': ['gen_ai.agent.invocation.id'],
- 'gen_ai.agent.result': ['gen_ai.agent.invocation.id'],
- 'skill.use': ['gen_ai.skill.name'],
- };
- const COVERAGE_FIELDS = [
- ...COMMON_REQUIRED,
- 'trace_id', 'span_id', 'gen_ai.turn.id', 'gen_ai.step.id',
- 'gen_ai.agent.invocation.id', 'gen_ai.agent.parent.invocation.id',
- 'gen_ai.turn.start', 'gen_ai.turn.end',
- 'gen_ai.request.id', 'gen_ai.request.model',
- 'gen_ai.response.id', 'gen_ai.response.model', 'gen_ai.response.finish_reasons',
- 'gen_ai.input.messages_delta', 'gen_ai.output.messages',
- 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens', 'gen_ai.usage.total_tokens',
- 'gen_ai.tool.name', 'gen_ai.tool.call.id', 'gen_ai.tool.call.duration',
- 'tool.result.status', 'error.type',
- 'gen_ai.agent.id', 'gen_ai.agent.parent.id', 'gen_ai.agent.peer.id',
- 'gen_ai.agent.invocation.id', 'gen_ai.agent.parent.invocation.id',
- ];
- const NUMBER_FIELDS = [
- 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens',
- 'gen_ai.usage.cache_read.input_tokens', 'gen_ai.usage.cache_creation.input_tokens',
- 'gen_ai.usage.total_tokens', 'gen_ai.usage.input_cost',
- 'gen_ai.usage.output_cost', 'gen_ai.usage.cache_read.input_cost',
- 'gen_ai.usage.cache_creation.input_cost', 'gen_ai.usage.total_cost',
- ];
- const ARRAY_FIELDS = [
- 'gen_ai.response.finish_reasons', 'gen_ai.input.messages',
- 'gen_ai.input.messages_delta', 'gen_ai.output.messages',
- 'gen_ai.system_instructions', 'gen_ai.tool.definitions',
- ];
- const PLACEHOLDER_FIELDS = [
- 'gen_ai.provider.name', 'gen_ai.request.model', 'gen_ai.response.model',
- ];
- const PLACEHOLDERS = new Set(['unknown', 'n/a', 'na', 'none', 'null', 'undefined']);
- const TERMINAL_FINISH_REASONS = new Set(['stop', 'end_turn', 'cancelled', 'error']);
- function listJsonl(dir) {
- if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return [];
- return fs.readdirSync(dir)
- .filter(f => f.endsWith('.jsonl'))
- .map(f => path.join(dir, f));
- }
- function matchesAgentFilter(file) {
- if (!AGENT_FILTER.length) return true;
- const base = path.basename(file, '.jsonl').toLowerCase();
- return AGENT_FILTER.some(a => base.startsWith(a + '-') || base === a);
- }
- function withinWindow(entry) {
- if (!SINCE_SECONDS || SINCE_SECONDS <= 0) return true;
- const ns = entry && entry.time_unix_nano;
- if (!ns || typeof ns !== 'string') return true;
- const ms = Number(ns.slice(0, -6)) || 0;
- return (Date.now() - ms) <= SINCE_SECONDS * 1000;
- }
- function pct(num, total) {
- if (!total) return '0.0%';
- return ((num / total) * 100).toFixed(1) + '%';
- }
- function hasValue(value) {
- return value !== undefined && value !== null && value !== '';
- }
- function pairingEventName(value) {
- return ({
- 'gen_ai.model.request': 'llm.request',
- 'gen_ai.model.response': 'llm.response',
- 'gen_ai.tool.call': 'tool.call',
- 'gen_ai.tool.result': 'tool.result',
- })[value] || value;
- }
- function normalizedAgentType(value) {
- return String(value || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
- }
- function isTerminalTurnEntry(entry) {
- const agentType = normalizedAgentType(entry['gen_ai.agent.type']);
- if (entry['gen_ai.agent.scope'] === 'subagent' && agentType !== 'codex') return false;
- if (entry['gen_ai.turn.end'] === true) return true;
- // Codex status applies to every record; only the native marker closes a turn.
- if (agentType === 'codex') return false;
- if (agentType === 'openclaw') {
- return entry['agent.openclaw.hook'] === 'llm_output';
- }
- const reasons = entry['gen_ai.response.finish_reasons'];
- return Array.isArray(reasons) && reasons.some(reason => TERMINAL_FINISH_REASONS.has(reason));
- }
- function increment(target, key, amount = 1) {
- target[key] = (target[key] || 0) + amount;
- }
- function validTraceId(value) {
- return typeof value === 'string' && /^[0-9a-f]{32}$/i.test(value) && !/^0{32}$/.test(value);
- }
- function validSpanId(value) {
- return typeof value === 'string' && /^[0-9a-f]{16}$/i.test(value) && !/^0{16}$/.test(value);
- }
- const files = listJsonl(LOG_DIR).filter(matchesAgentFilter);
- if (!files.length) {
- console.log('[jsonl-validate] no .jsonl files in ' + LOG_DIR + (AGENT_FILTER.length ? ' (filter=' + AGENT_FILTER.join(',') + ')' : ''));
- console.log('[jsonl-validate] hint: run install-smoke + agent probe, or version-matrix with E2E_USER_ID first.');
- process.exit(STRICT ? 1 : 0);
- }
- let totalEntries = 0;
- let totalWindowed = 0;
- let hardIssueTotal = 0;
- const globalEventName = Object.create(null);
- const globalAgentType = Object.create(null);
- const globalProvider = Object.create(null);
- const issueCounts = Object.create(null);
- const issueSamples = [];
- const fileStats = new Map();
- const rows = [];
- const coverage = Object.create(null);
- function addIssue(file, category, fields = []) {
- hardIssueTotal++;
- increment(issueCounts, category);
- const stat = fileStats.get(file);
- if (stat) stat.issues++;
- if (issueSamples.length < MAX_SAMPLES) {
- issueSamples.push({ file, category, fields: [...new Set(fields)].sort() });
- }
- }
- function recordCoverage(eventName, entry) {
- const name = typeof eventName === 'string' && eventName ? eventName : '<missing>';
- if (!coverage[name]) coverage[name] = { count: 0, fields: Object.create(null) };
- coverage[name].count++;
- for (const field of COVERAGE_FIELDS) {
- if (hasValue(entry[field])) increment(coverage[name].fields, field);
- }
- }
- function validateTypes(file, entry) {
- const bad = [];
- if (hasValue(entry.time_unix_nano) && (typeof entry.time_unix_nano !== 'string' || !/^\\d+$/.test(entry.time_unix_nano))) bad.push('time_unix_nano');
- 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');
- for (const field of ['event.id', 'user.id', 'event.name', 'gen_ai.session.id', 'gen_ai.agent.type', 'gen_ai.provider.name']) {
- if (hasValue(entry[field]) && typeof entry[field] !== 'string') bad.push(field);
- }
- if (hasValue(entry.trace_id) && !validTraceId(entry.trace_id)) bad.push('trace_id');
- if (hasValue(entry.span_id) && !validSpanId(entry.span_id)) bad.push('span_id');
- if (hasValue(entry.parent_span_id) && !validSpanId(entry.parent_span_id)) bad.push('parent_span_id');
- for (const field of NUMBER_FIELDS) {
- if (hasValue(entry[field]) && (typeof entry[field] !== 'number' || !Number.isFinite(entry[field]) || entry[field] < 0)) bad.push(field);
- }
- if (hasValue(entry['gen_ai.tool.call.duration'])
- && (typeof entry['gen_ai.tool.call.duration'] !== 'number'
- || !Number.isFinite(entry['gen_ai.tool.call.duration'])
- || entry['gen_ai.tool.call.duration'] <= 0)) {
- bad.push('gen_ai.tool.call.duration');
- }
- for (const field of ARRAY_FIELDS) {
- if (hasValue(entry[field]) && !Array.isArray(entry[field])) bad.push(field);
- }
- for (const field of ['gen_ai.turn.start', 'gen_ai.turn.end']) {
- if (hasValue(entry[field]) && typeof entry[field] !== 'boolean') bad.push(field);
- }
- for (const field of ['gen_ai.tool.call.arguments', 'gen_ai.tool.call.result']) {
- const value = entry[field];
- if (typeof value === 'string' && /^[\\s]*[\\[{]/.test(value)) bad.push(field);
- }
- if (bad.length) addIssue(file, 'type_error', bad);
- }
- for (const file of files) {
- const base = path.basename(file);
- const stat = { entries: 0, windowed: 0, issues: 0, eventName: Object.create(null) };
- fileStats.set(base, stat);
- const raw = fs.readFileSync(file, 'utf8').split(/\\r?\\n/);
- for (const line of raw) {
- if (!line.trim()) continue;
- let entry;
- try {
- entry = JSON.parse(line);
- } catch (e) {
- stat.entries++;
- totalEntries++;
- addIssue(base, 'parse_error');
- continue;
- }
- stat.entries++;
- totalEntries++;
- if (!withinWindow(entry)) continue;
- stat.windowed++;
- totalWindowed++;
- const en = entry['event.name'];
- const conditional = CONDITIONAL_REQUIRED[en] || [];
- const miss = [...COMMON_REQUIRED, ...conditional].filter(k => !hasValue(entry[k]));
- const failedStatus = typeof entry['tool.result.status'] === 'string'
- && ['failure', 'failed', 'error'].includes(entry['tool.result.status'].toLowerCase());
- const finishReasons = Array.isArray(entry['gen_ai.response.finish_reasons'])
- ? entry['gen_ai.response.finish_reasons'] : [];
- if ((failedStatus || finishReasons.includes('error') || hasValue(entry['error.message']))
- && !hasValue(entry['error.type'])) {
- miss.push('error.type');
- }
- if (miss.length) {
- addIssue(base, 'missing_required', miss);
- }
- if (en !== undefined && !EVENT_NAME_ENUM.has(en)) addIssue(base, 'bad_event_name', ['event.name']);
- if (en) increment(stat.eventName, en);
- if (en) globalEventName[en] = (globalEventName[en] || 0) + 1;
- const at = entry['gen_ai.agent.type']; if (at) globalAgentType[at] = (globalAgentType[at] || 0) + 1;
- const pr = entry['gen_ai.provider.name']; if (pr) globalProvider[pr] = (globalProvider[pr] || 0) + 1;
- validateTypes(base, entry);
- recordCoverage(en, entry);
- rows.push({ file: base, entry });
- }
- }
- const seenEventIds = new Map();
- for (const row of rows) {
- const eventId = row.entry['event.id'];
- if (typeof eventId !== 'string' || !eventId) continue;
- if (seenEventIds.has(eventId)) addIssue(row.file, 'duplicate_event_id', ['event.id']);
- else seenEventIds.set(eventId, row);
- }
- const steps = new Map();
- for (const row of rows) {
- const entry = row.entry;
- const eventName = pairingEventName(entry['event.name']);
- if (eventName !== 'llm.request' && eventName !== 'llm.response') continue;
- if (!hasValue(entry['gen_ai.step.id'])) continue;
- const key = String(entry['gen_ai.session.id']) + '\\0' + String(entry['gen_ai.turn.id'] || '') + '\\0' + String(entry['gen_ai.step.id']);
- if (!steps.has(key)) steps.set(key, []);
- steps.get(key).push(row);
- }
- for (const stepRows of steps.values()) {
- const requests = stepRows.filter(row => pairingEventName(row.entry['event.name']) === 'llm.request');
- const responses = stepRows.filter(row => pairingEventName(row.entry['event.name']) === 'llm.response');
- if (requests.length !== 1 || responses.length !== 1) {
- addIssue(stepRows[0].file, 'model_pair_error', ['event.name', 'gen_ai.step.id']);
- }
- }
- const tools = new Map();
- for (const row of rows) {
- const entry = row.entry;
- const eventName = pairingEventName(entry['event.name']);
- if (eventName !== 'tool.call' && eventName !== 'tool.result') continue;
- const callId = entry['gen_ai.tool.call.id'];
- if (!hasValue(callId)) continue;
- const key = String(entry['gen_ai.session.id']) + '\\0' + String(callId);
- if (!tools.has(key)) tools.set(key, []);
- tools.get(key).push(row);
- }
- for (const toolRows of tools.values()) {
- const calls = toolRows.filter(row => pairingEventName(row.entry['event.name']) === 'tool.call');
- const results = toolRows.filter(row => pairingEventName(row.entry['event.name']) === 'tool.result');
- const names = new Set(toolRows.map(row => row.entry['gen_ai.tool.name']).filter(hasValue));
- if (calls.length !== 1 || results.length !== 1 || names.size !== 1) {
- addIssue(toolRows[0].file, 'tool_pair_error', ['event.name', 'gen_ai.tool.call.id', 'gen_ai.tool.name']);
- }
- }
- const turns = new Map();
- for (const row of rows) {
- const entry = row.entry;
- if (entry['event.name'] === 'gen_ai.agent.invoke' || entry['event.name'] === 'gen_ai.agent.result') continue;
- if (!hasValue(entry['gen_ai.turn.id'])) continue;
- if (entry['gen_ai.agent.scope'] === 'subagent'
- && normalizedAgentType(entry['gen_ai.agent.type']) !== 'codex') continue;
- if (entry['event.name'] === 'gen_ai.agent.invoke' || entry['event.name'] === 'gen_ai.agent.result') continue;
- const key = String(entry['gen_ai.agent.type']) + '\\0'
- + String(entry['gen_ai.session.id']) + '\\0' + String(entry['gen_ai.turn.id']);
- if (!turns.has(key)) turns.set(key, []);
- turns.get(key).push(row);
- }
- for (const turnRows of turns.values()) {
- const starts = turnRows.filter(row => row.entry['gen_ai.turn.start'] === true).length;
- const ends = turnRows.filter(row => row.entry['gen_ai.turn.end'] === true).length;
- const completed = turnRows.some(row => isTerminalTurnEntry(row.entry));
- if (starts !== 1 || ends !== (completed ? 1 : 0)) {
- addIssue(turnRows[0].file, 'turn_boundary_error', ['gen_ai.turn.start', 'gen_ai.turn.end']);
- }
- }
- let placeholderCount = 0;
- for (const row of rows) {
- for (const field of PLACEHOLDER_FIELDS) {
- const value = row.entry[field];
- if (typeof value === 'string' && PLACEHOLDERS.has(value.trim().toLowerCase())) placeholderCount++;
- }
- }
- if (SINCE_SECONDS > 0 && totalWindowed === 0) {
- addIssue(path.basename(files[0]), 'empty_window');
- }
- for (const [base, stat] of fileStats) {
- const tag = stat.issues ? 'FAIL' : 'OK';
- const summary = Object.entries(stat.eventName).map(([k, v]) => k + '=' + v).join(', ') || '<none>';
- console.log('[jsonl-validate] ' + tag + ' ' + base + ' entries=' + stat.entries + ' windowed=' + stat.windowed + ' issues=' + stat.issues + ' event.name{' + summary + '}');
- }
- console.log('');
- console.log('=== [jsonl-validate] summary ===');
- console.log(' files=' + files.length + ' entries=' + totalEntries + ' windowed=' + totalWindowed);
- for (const category of [
- 'missing_required', 'bad_event_name', 'parse_error', 'type_error',
- 'duplicate_event_id', 'model_pair_error', 'tool_pair_error', 'turn_boundary_error',
- 'empty_window',
- ]) {
- console.log(' ' + category + '=' + (issueCounts[category] || 0));
- }
- console.log(' suspicious_placeholders=' + placeholderCount + ' (reported, not a universal failure)');
- console.log(' event.name: ' + (Object.entries(globalEventName).map(([k, v]) => k + '=' + v).join(', ') || '<none>'));
- console.log(' gen_ai.agent.type: ' + (Object.entries(globalAgentType).map(([k, v]) => k + '=' + v).join(', ') || '<none>'));
- console.log(' gen_ai.provider.name: ' + (Object.entries(globalProvider).map(([k, v]) => k + '=' + v).join(', ') || '<none>'));
- console.log(' per-event field coverage:');
- for (const eventName of Object.keys(coverage).sort()) {
- const eventCoverage = coverage[eventName];
- console.log(' ' + eventName + ' count=' + eventCoverage.count);
- for (const field of COVERAGE_FIELDS) {
- const count = eventCoverage.fields[field] || 0;
- console.log(' ' + field + '=' + count + ' (' + pct(count, eventCoverage.count) + ')');
- }
- }
- if (issueSamples.length) {
- console.log(' issue samples (field names only, up to ' + MAX_SAMPLES + '):');
- for (const sample of issueSamples) {
- console.log(' - file=' + sample.file + ' category=' + sample.category + ' fields=[' + sample.fields.join(',') + ']');
- }
- }
- if (hardIssueTotal > 0 && STRICT) {
- console.error('[jsonl-validate] STRICT: failures detected → exit 1');
- process.exit(1);
- }
- process.exit(0);
- `;
- /**
- * 追加到 install-smoke (probe 之后) / version-matrix 末尾的 JSONL 字段校验 bash 片段。
- * 校验 ~/.loongsuite-pilot/logs/output/*.jsonl 是否满足 AgentActivityEntry schema。
- * 环境变量:
- * E2E_JSONL_VALIDATE=0 禁用
- * E2E_JSONL_STRICT=1 schema、类型、唯一性或关联错误时 exit 1
- * E2E_JSONL_SINCE_SECONDS=600 仅统计最近 N 秒的条目
- * E2E_JSONL_AGENT_FILTER=claude-code,codex,qoder-cli,cursor-cli,qwen-code-cli,opencode 仅校验 agent 前缀匹配的文件(默认);设为 all 或 * 关闭过滤
- * E2E_JSONL_LOG_DIR=/path 覆盖默认 ~/.loongsuite-pilot/logs/output
- * @param {NodeJS.ProcessEnv} env
- * @returns {string}
- */
- export function buildJsonlValidationSh(env = process.env) {
- if ((env?.E2E_JSONL_VALIDATE ?? '1').toString().trim() === '0') return '';
- const b64 = Buffer.from(JSONL_VALIDATOR_JS, 'utf8').toString('base64');
- return `
- # === [jsonl-validate] AgentActivityEntry schema check (src/types/events.ts) ===
- if ! command -v node >/dev/null 2>&1; then
- echo "[jsonl-validate] WARN: node not on PATH — skipping schema check"
- else
- export _JV_LOG_DIR="\${E2E_JSONL_LOG_DIR:-$HOME/.loongsuite-pilot/logs/output}"
- if [ ! -d "$_JV_LOG_DIR" ]; then
- echo "[jsonl-validate] WARN: log dir not found: $_JV_LOG_DIR (pilot may not have flushed yet)"
- else
- echo ""
- echo "=== [jsonl-validate] scanning $_JV_LOG_DIR ==="
- printf '%s' '${b64}' | base64 -d | node -
- _jv_st=$?
- if [ "$_jv_st" -ne 0 ]; then
- if [ "\${E2E_JSONL_STRICT:-0}" = "1" ]; then
- echo "[jsonl-validate] STRICT mode: validation failed (exit $_jv_st)"
- exit $_jv_st
- else
- echo "[jsonl-validate] validation returned non-zero ($_jv_st) — set E2E_JSONL_STRICT=1 to fail the job"
- fi
- fi
- fi
- fi
- `;
- }
- // ──────────────────────────────────────────────────────────
- // File Collection E2E validation
- // ──────────────────────────────────────────────────────────
- /**
- * Build a bash script that creates a file-collection config + test log files,
- * waits for pilot to pick them up, and verifies the pipeline processed them.
- */
- export function buildFileCollectionValidationSh() {
- return `
- set -euo pipefail
- echo ""
- echo "=== [file-collection-e2e] File Collection Pipeline Validation ==="
- # Step 0: Enable file collection in pilot config and restart
- echo "[file-collection-e2e] Step 0: Enabling fileCollection in config.json..."
- PILOT_CONFIG="$HOME/.loongsuite-pilot/config.json"
- echo "[file-collection-e2e] stopping pilot before config update..."
- loongsuite-pilot stop 2>/dev/null || true
- sleep 2
- if [ -f "$PILOT_CONFIG" ]; then
- node -e "
- const fs = require('fs');
- const cfg = JSON.parse(fs.readFileSync(process.argv[1], 'utf8'));
- cfg.fileCollection = { enabled: true };
- fs.writeFileSync(process.argv[1], JSON.stringify(cfg, null, 2));
- " "$PILOT_CONFIG"
- else
- echo '{"fileCollection":{"enabled":true}}' > "$PILOT_CONFIG"
- fi
- echo "[file-collection-e2e] config updated: $(node -e "const c=require('$PILOT_CONFIG');console.log(JSON.stringify(c.fileCollection))" 2>/dev/null)"
- echo "[file-collection-e2e] starting pilot with fileCollection.enabled..."
- loongsuite-pilot start 2>/dev/null || true
- sleep 5
- FC_CONFIG_DIR="$HOME/.loongsuite-pilot/configs/local"
- FC_STATE_DIR="$HOME/.loongsuite-pilot/state/pipeline"
- FC_LEGACY_STATE_DIR="$HOME/.loongsuite-pilot/state/file-collection"
- FC_SERVICE_LOG_GLOB="$HOME/.loongsuite-pilot/logs/loongsuite-pilot-service.log*"
- FC_TEST_LOG_DIR="$HOME/.loongsuite-pilot/e2e-test-logs"
- FC_CONFIG_NAME="e2e-file-test"
- fc_state_file() {
- if [ -f "$FC_STATE_DIR/$FC_CONFIG_NAME.json" ]; then echo "$FC_STATE_DIR/$FC_CONFIG_NAME.json"; return; fi
- if [ -f "$FC_LEGACY_STATE_DIR/$FC_CONFIG_NAME.json" ]; then echo "$FC_LEGACY_STATE_DIR/$FC_CONFIG_NAME.json"; return; fi
- echo "$FC_STATE_DIR/$FC_CONFIG_NAME.json"
- }
- # Step 1: Create test log directory and write test data
- echo "[file-collection-e2e] Step 1: Creating test log files..."
- mkdir -p "$FC_TEST_LOG_DIR"
- for i in $(seq 1 20); do
- 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"
- done
- echo "[file-collection-e2e] wrote 20 lines to $FC_TEST_LOG_DIR/app.log"
- # Step 2: Create file-collection config using real SLS endpoint from E2E env
- echo "[file-collection-e2e] Step 2: Creating file-collection config..."
- mkdir -p "$FC_CONFIG_DIR"
- # Read SLS config from pilot's config.json (written by installer with real E2E_SLS_* values)
- 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)
- 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)
- 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)
- echo "[file-collection-e2e] using SLS: endpoint=$FC_SLS_ENDPOINT project=$FC_SLS_PROJECT logstore=$FC_SLS_LOGSTORE"
- node -e "
- const config = {
- configName: 'e2e-file-test',
- inputs: [{
- Type: 'input_file',
- FilePaths: [process.argv[1]],
- FileEncoding: 'utf8',
- MaxDirSearchDepth: 0
- }],
- flushers: [{
- Type: 'flusher_sls',
- Endpoint: process.argv[2],
- Project: process.argv[3],
- Logstore: process.argv[4],
- TelemetryType: 'logs'
- }]
- };
- require('fs').writeFileSync(process.argv[5], JSON.stringify(config, null, 2));
- " "$FC_TEST_LOG_DIR/*.log" "$FC_SLS_ENDPOINT" "$FC_SLS_PROJECT" "$FC_SLS_LOGSTORE" "$FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
- echo "[file-collection-e2e] config written: $FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
- cat "$FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
- # Step 3: Wait for pilot to detect the config and process files
- # FileCollectionManager rescans every 60s; we also trigger via fs.watch.
- echo "[file-collection-e2e] Step 3: Waiting for pilot to process config (up to 90s)..."
- TIMEOUT=90
- ELAPSED=0
- while [ $ELAPSED -lt $TIMEOUT ]; do
- if [ -f "$(fc_state_file)" ]; then
- STATE_SIZE=$(wc -c < "$(fc_state_file)" | tr -d ' ')
- if [ "$STATE_SIZE" -gt 2 ]; then
- echo "[file-collection-e2e] state file detected after \${ELAPSED}s (size=\${STATE_SIZE}B)"
- break
- fi
- fi
- sleep 3
- ELAPSED=$((ELAPSED + 3))
- done
- # Step 4: Validate results
- echo "[file-collection-e2e] Step 4: Validating results..."
- FC_FAIL=0
- # Check state file exists and is non-empty
- if [ -f "$(fc_state_file)" ]; then
- STATE_CONTENT=$(cat "$(fc_state_file)")
- STATE_SIZE=$(echo -n "$STATE_CONTENT" | wc -c | tr -d ' ')
- if [ "$STATE_SIZE" -gt 2 ]; then
- echo "[file-collection-e2e] OK: state file exists and has content (\${STATE_SIZE}B)"
- # Check that offset was advanced (file was read)
- if echo "$STATE_CONTENT" | grep -q '"lastOffset"'; then
- echo "[file-collection-e2e] OK: state contains lastOffset (file was read)"
- else
- echo "[file-collection-e2e] WARN: state exists but no lastOffset found"
- fi
- if echo "$STATE_CONTENT" | grep -q '"inode"'; then
- echo "[file-collection-e2e] OK: state contains inode (rotation tracking active)"
- fi
- else
- echo "[file-collection-e2e] FAIL: state file exists but is empty/trivial"
- FC_FAIL=1
- fi
- else
- echo "[file-collection-e2e] FAIL: state file not found at $(fc_state_file)"
- echo "[file-collection-e2e] pilot service log (last 20 lines with FileCollection):"
- grep -iE "FileCollection|file-collection|FilePipeline|FileTailer" $FC_SERVICE_LOG_GLOB 2>/dev/null | tail -20 || echo "(no file-collection log lines found)"
- FC_FAIL=1
- fi
- # Check service log for file-collection activity
- if grep -q "FileCollectionManager.*started" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
- echo "[file-collection-e2e] OK: FileCollectionManager started in service log"
- else
- echo "[file-collection-e2e] WARN: FileCollectionManager start not found in service log"
- fi
- if grep -q "FilePipeline.*started" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
- echo "[file-collection-e2e] OK: FilePipeline started in service log"
- else
- echo "[file-collection-e2e] WARN: FilePipeline start not found in service log"
- fi
- # Step 5: Test log rotation (write more data to verify incremental read)
- echo ""
- echo "[file-collection-e2e] Step 5: Testing incremental read..."
- OFFSET_BEFORE=""
- if [ -f "$(fc_state_file)" ]; then
- 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")
- fi
- echo "[file-collection-e2e] offset before append: $OFFSET_BEFORE"
- for i in $(seq 21 30); do
- echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] e2e-incremental-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
- done
- echo "[file-collection-e2e] appended 10 more lines"
- # Wait for next poll cycle
- sleep 15
- OFFSET_AFTER=""
- if [ -f "$(fc_state_file)" ]; then
- 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")
- fi
- echo "[file-collection-e2e] offset after append: $OFFSET_AFTER"
- if [ "$OFFSET_AFTER" -gt "$OFFSET_BEFORE" ] 2>/dev/null; then
- echo "[file-collection-e2e] OK: offset advanced ($OFFSET_BEFORE -> $OFFSET_AFTER), incremental read works"
- else
- echo "[file-collection-e2e] WARN: offset did not advance (may need more time)"
- fi
- # ──────────────────────────────────────────────────────────
- # Step 6: Rename rotation test
- # ──────────────────────────────────────────────────────────
- echo ""
- echo "[file-collection-e2e] Step 6: Testing RENAME rotation..."
- # 6a. Record current state (offset + inode) before rotation
- 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")
- 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")
- echo "[file-collection-e2e] before rename: inode=$INODE_BEFORE offset=$OFFSET_BEFORE"
- # 6b. Append lines that haven't been collected yet (simulate unread tail)
- for i in $(seq 1 5); do
- echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] rename-pre-rotate-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
- done
- echo "[file-collection-e2e] appended 5 lines before rotation (these must be drained from old file)"
- # 6c. Simulate rename rotation: mv app.log -> app.log.1, create new app.log
- mv "$FC_TEST_LOG_DIR/app.log" "$FC_TEST_LOG_DIR/app.log.1"
- for i in $(seq 1 5); do
- echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] rename-post-rotate-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
- done
- echo "[file-collection-e2e] renamed app.log -> app.log.1, created new app.log with 5 lines"
- # 6d. Wait for poll cycle to detect rotation and drain
- sleep 15
- 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")
- 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")
- echo "[file-collection-e2e] after rename: inode=$INODE_AFTER offset=$OFFSET_AFTER"
- if [ "$INODE_AFTER" != "$INODE_BEFORE" ] && [ "$INODE_AFTER" != "0" ]; then
- echo "[file-collection-e2e] OK: inode changed ($INODE_BEFORE -> $INODE_AFTER), rename rotation detected"
- else
- echo "[file-collection-e2e] FAIL: inode did not change after rename rotation"
- FC_FAIL=1
- fi
- if [ "$OFFSET_AFTER" -gt 0 ] 2>/dev/null; then
- echo "[file-collection-e2e] OK: new file read (offset=$OFFSET_AFTER)"
- else
- echo "[file-collection-e2e] FAIL: new file not read after rename rotation"
- FC_FAIL=1
- fi
- # 6e. Verify old file drain via service log
- if grep -q "drained old file after rotation" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
- echo "[file-collection-e2e] OK: old file drain logged (unread lines from app.log.1 collected)"
- else
- echo "[file-collection-e2e] WARN: old file drain not found in service log (may have been fully read before rotation)"
- fi
- # ──────────────────────────────────────────────────────────
- # Step 7: Copytruncate rotation test
- # ──────────────────────────────────────────────────────────
- echo ""
- echo "[file-collection-e2e] Step 7: Testing COPYTRUNCATE rotation..."
- # 7a. Wait for current data to be collected
- sleep 15
- 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")
- 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")
- echo "[file-collection-e2e] before copytruncate: inode=$INODE_BEFORE_CT offset=$OFFSET_BEFORE_CT"
- # 7b. Simulate copytruncate: cp app.log -> app.log.2, truncate app.log, write new data
- cp "$FC_TEST_LOG_DIR/app.log" "$FC_TEST_LOG_DIR/app.log.2"
- : > "$FC_TEST_LOG_DIR/app.log"
- for i in $(seq 1 5); do
- echo "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ) [INFO] copytruncate-new-line-$i" >> "$FC_TEST_LOG_DIR/app.log"
- done
- echo "[file-collection-e2e] copytruncate done: truncated app.log, wrote 5 new lines"
- # 7c. Wait for poll cycle
- sleep 15
- 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")
- 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")
- echo "[file-collection-e2e] after copytruncate: inode=$INODE_AFTER_CT offset=$OFFSET_AFTER_CT"
- if [ "$INODE_AFTER_CT" = "$INODE_BEFORE_CT" ]; then
- echo "[file-collection-e2e] OK: inode unchanged ($INODE_AFTER_CT), copytruncate correctly detected (same file)"
- else
- echo "[file-collection-e2e] WARN: inode changed unexpectedly ($INODE_BEFORE_CT -> $INODE_AFTER_CT)"
- fi
- if [ "$OFFSET_AFTER_CT" -lt "$OFFSET_BEFORE_CT" ] 2>/dev/null && [ "$OFFSET_AFTER_CT" -gt 0 ] 2>/dev/null; then
- echo "[file-collection-e2e] OK: offset reset and advanced ($OFFSET_BEFORE_CT -> $OFFSET_AFTER_CT), truncated file re-read from start"
- else
- echo "[file-collection-e2e] FAIL: offset not properly reset after copytruncate (before=$OFFSET_BEFORE_CT after=$OFFSET_AFTER_CT)"
- FC_FAIL=1
- fi
- # Verify truncation detection in service log
- if grep -q "copytruncate rotation" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
- echo "[file-collection-e2e] OK: copytruncate rotation detected in service log"
- else
- echo "[file-collection-e2e] WARN: copytruncate detection not found in service log"
- fi
- # 7d. Edge case: copytruncate where new data exceeds old offset (signature-based detection)
- echo ""
- echo "[file-collection-e2e] Step 7b: Testing copytruncate with new data exceeding old offset..."
- sleep 15
- 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")
- echo "[file-collection-e2e] current offset: $OFFSET_BEFORE_SIG"
- # Simulate: cp + truncate + write MORE data than old file size
- cp "$FC_TEST_LOG_DIR/app.log" "$FC_TEST_LOG_DIR/app.log.3"
- : > "$FC_TEST_LOG_DIR/app.log"
- for i in $(seq 1 50); do
- 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"
- done
- NEW_SIZE=$(wc -c < "$FC_TEST_LOG_DIR/app.log" | tr -d ' ')
- echo "[file-collection-e2e] truncated + wrote 50 lines ($NEW_SIZE bytes, old offset was $OFFSET_BEFORE_SIG)"
- sleep 15
- 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")
- echo "[file-collection-e2e] after signature-based copytruncate: offset=$OFFSET_AFTER_SIG"
- if grep -q "signature changed.*copytruncate rotation.*content replaced" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
- echo "[file-collection-e2e] OK: signature-based copytruncate detected (file head content changed)"
- elif grep -q "copytruncate rotation.*size < offset" $FC_SERVICE_LOG_GLOB 2>/dev/null; then
- echo "[file-collection-e2e] OK: size-based copytruncate detected (fallback, new data didn't exceed old offset)"
- else
- echo "[file-collection-e2e] WARN: copytruncate detection not found for overflow case (may need more time)"
- fi
- # ──────────────────────────────────────────────────────────
- # Step 8: Rotated file count check
- # ──────────────────────────────────────────────────────────
- echo ""
- echo "[file-collection-e2e] Step 8: Rotated file handling summary..."
- ROTATED_COUNT=$(ls "$FC_TEST_LOG_DIR"/app.log.* 2>/dev/null | wc -l | tr -d ' ')
- echo "[file-collection-e2e] rotated files in directory: $ROTATED_COUNT (app.log.1, app.log.2, ...)"
- echo "[file-collection-e2e] INFO: drain supports 1 immediate predecessor per rotation event (by inode lookup)"
- echo "[file-collection-e2e] INFO: glob pattern *.log only matches app.log, rotated files (app.log.1) are not re-collected"
- ls -la "$FC_TEST_LOG_DIR"/ 2>/dev/null
- # ──────────────────────────────────────────────────────────
- # Step 9: Verify data delivery status
- # ──────────────────────────────────────────────────────────
- echo ""
- echo "[file-collection-e2e] Step 9: Verifying data delivery..."
- FC_FAILED_LOG="$HOME/.loongsuite-pilot/logs/pipeline-failed/$FC_CONFIG_NAME.jsonl"
- FC_LEGACY_FAILED_LOG="$HOME/.loongsuite-pilot/logs/file-collection-failed/$FC_CONFIG_NAME.jsonl"
- if [ ! -f "$FC_FAILED_LOG" ] && [ -f "$FC_LEGACY_FAILED_LOG" ]; then
- FC_FAILED_LOG="$FC_LEGACY_FAILED_LOG"
- fi
- if [ -f "$FC_FAILED_LOG" ]; then
- FC_FAILED_LINES=$(wc -l < "$FC_FAILED_LOG" | tr -d ' ')
- echo "[file-collection-e2e] WARN: failed-log has $FC_FAILED_LINES entries (some data failed to deliver to SLS)"
- echo "[file-collection-e2e] failed-log sample:"
- head -1 "$FC_FAILED_LOG" | cut -c1-200
- else
- echo "[file-collection-e2e] OK: no failed-log (all data delivered to SLS successfully)"
- fi
- # Cleanup
- echo ""
- echo "[file-collection-e2e] Cleaning up test config..."
- rm -f "$FC_CONFIG_DIR/$FC_CONFIG_NAME.json"
- if [ "$FC_FAIL" -eq 0 ]; then
- echo ""
- echo "=== [file-collection-e2e] File Collection Validation PASSED ==="
- else
- echo ""
- echo "=== [file-collection-e2e] File Collection Validation FAILED ==="
- exit 1
- fi
- `;
- }
- // ──────────────────────────────────────────────────────────
- // Helpers used by both run-l1.mjs and run-docker-e2e.mjs.
- // Moved from run-docker-e2e.mjs so L1 can reuse without copy.
- // ──────────────────────────────────────────────────────────
- export function preflightScript() {
- return `
- set -euo pipefail
- echo "=== uname ==="
- uname -a || true
- echo "=== node ==="
- command -v node && node -v || echo "node missing"
- echo "=== npm ==="
- command -v npm && npm -v || echo "npm missing"
- echo "=== agents ==="
- for b in codex claude cursor cursor-agent agent qoder qodercli qwen opencode; do
- if command -v "$b" >/dev/null 2>&1; then
- echo "have $b: $("$b" --version 2>/dev/null || echo 'version unknown')"
- else
- echo "missing $b"
- fi
- done
- echo "=== disk ==="
- df -h . 2>/dev/null || true
- echo "=== E2E_DOCKER_MODE ==="
- echo "Running inside Docker container"
- `;
- }
- export function localBuildInstallScript(userId, env) {
- const id = (userId || '').replace(/'/g, `'\\''`);
- const installerFlags = [`--user.id '${id}'`];
- if (shouldPropagateSlsToRemoteInstall(env)) {
- const rawEndpoint = env.E2E_SLS_ENDPOINT?.trim() || 'cn-hangzhou.log.aliyuncs.com';
- const endpoint = /^https?:\/\//i.test(rawEndpoint) ? rawEndpoint : `https://${rawEndpoint}`;
- installerFlags.push(`--sls-endpoint ${shellSingleQuoteBash(endpoint)}`);
- installerFlags.push(`--sls-project ${shellSingleQuoteBash(env.E2E_SLS_PROJECT.trim())}`);
- installerFlags.push(`--sls-logstore ${shellSingleQuoteBash(env.E2E_SLS_LOGSTORE.trim())}`);
- if (env.E2E_SLS_ACCESS_KEY_ID?.trim() && env.E2E_SLS_ACCESS_KEY_SECRET?.trim()) {
- installerFlags.push(`--sls-ak-id ${shellSingleQuoteBash(env.E2E_SLS_ACCESS_KEY_ID.trim())}`);
- installerFlags.push(`--sls-ak-secret ${shellSingleQuoteBash(env.E2E_SLS_ACCESS_KEY_SECRET.trim())}`);
- }
- }
- const extraFlags = (env.E2E_INSTALLER_EXTRA_FLAGS ?? '').trim();
- if (extraFlags) {
- installerFlags.push(extraFlags);
- }
- const flagsStr = installerFlags.join(' \\\n ');
- return `
- set -euo pipefail
- INSTALLER=/opt/project/deploy/installer.sh
- PACKAGE=/opt/project/loongsuite-pilot.tar.gz
- echo "[installer-e2e] Verifying local package and installer..."
- if [ ! -f "$PACKAGE" ]; then
- echo "[installer-e2e] ERROR: $PACKAGE not found. Run 'deploy/package.sh' first."
- exit 1
- fi
- if [ ! -f "$INSTALLER" ]; then
- echo "[installer-e2e] ERROR: $INSTALLER not found."
- exit 1
- fi
- echo "[installer-e2e] Running installer with local package..."
- bash "$INSTALLER" install \\
- --package-url "file://$PACKAGE" \\
- ${flagsStr}
- echo "[installer-e2e] Verifying installation..."
- command -v loongsuite-pilot >/dev/null || {
- echo "[installer-e2e] ERROR: loongsuite-pilot not on PATH after install"
- export PATH="$HOME/.local/bin:$PATH"
- command -v loongsuite-pilot >/dev/null || exit 1
- }
- echo "[installer-e2e] config.json (redacted):"
- node - <<'NODE' 2>/dev/null || echo "(no config found or redaction failed)"
- const fs = require('fs');
- const os = require('os');
- const path = require('path');
- const p = path.join(os.homedir(), '.loongsuite-pilot', 'config.json');
- const cfg = JSON.parse(fs.readFileSync(p, 'utf8'));
- function redact(value, key = '') {
- if (Array.isArray(value)) return value.map(v => redact(v));
- if (value && typeof value === 'object') {
- const out = {};
- for (const [k, v] of Object.entries(value)) out[k] = redact(v, k);
- return out;
- }
- if (typeof value === 'string' && /(secret|token|password|accessKey|apiKey|ak|sk)/i.test(key)) return '<redacted>';
- return value;
- }
- console.log(JSON.stringify(redact(cfg), null, 2));
- NODE
- echo "[installer-e2e] service status:"
- loongsuite-pilot status || true
- echo "[installer-e2e] installer flow complete"
- `;
- }
- /**
- * Build a bash script that validates cli-probe.cjs detection results.
- * Runs the probe independently and asserts expected agents are detected
- * (cursor via ~/.cursor path, CLI agents via command lookup).
- */
- export function buildProbeDetectionValidationScript(requiredAgentsCsv = 'claude-code,codex,qoder,cursor,qwen-code-cli,opencode') {
- const requiredAgents = requiredAgentsCsv.split(',').map(s => s.trim()).filter(Boolean).join(' ');
- return `
- set -euo pipefail
- echo "[probe-validate] Running cli-probe.cjs detection validation..."
- PROBE_CJS="$HOME/.loongsuite-pilot/versions/$(cat $HOME/.loongsuite-pilot/current)/dist/cli-probe.cjs"
- if [ ! -f "$PROBE_CJS" ]; then
- echo "[probe-validate] ERROR: cli-probe.cjs not found at $PROBE_CJS"
- exit 1
- fi
- PROBE_OUTPUT=$(node "$PROBE_CJS" 2>/dev/null) || {
- echo "[probe-validate] ERROR: cli-probe.cjs failed to run"
- exit 1
- }
- echo "[probe-validate] probe output: $PROBE_OUTPUT"
- FAIL=0
- for AGENT_ID in ${requiredAgents}; do
- DETECTED=$(node -e "
- const r = JSON.parse(process.argv[1]);
- const a = r.find(x => x.id === process.argv[2]);
- if (!a) { console.log('missing'); process.exit(0); }
- console.log(a.detected ? 'yes' : 'no');
- " "$PROBE_OUTPUT" "$AGENT_ID")
- if [ "$DETECTED" = "yes" ]; then
- echo "[probe-validate] OK: $AGENT_ID detected"
- elif [ "$DETECTED" = "missing" ]; then
- echo "[probe-validate] SKIP: $AGENT_ID not in definitions"
- else
- echo "[probe-validate] FAIL: $AGENT_ID NOT detected"
- FAIL=1
- fi
- done
- if [ "$FAIL" -ne 0 ]; then
- echo "[probe-validate] FAILED: some agents not detected"
- exit 1
- fi
- echo "[probe-validate] ALL expected agents detected successfully"
- `;
- }
- export function uninstallScript(installerUrl) {
- const u = installerUrl.replace(/'/g, `'\\''`);
- return `
- set -euo pipefail
- INSTALLER_URL='${u}'
- curl -fsSL "$INSTALLER_URL" | bash -s -- uninstall --purge
- echo "uninstall: script finished"
- `;
- }
- /**
- * Build a bash script that checks all required agents have produced non-empty JSONL files.
- * @param {string} requiredAgentsCsv - comma-separated agent prefixes (e.g. "claude-code,codex,qoder")
- */
- export function buildJsonlAgentCoverageCheck(requiredAgentsCsv) {
- const agents = requiredAgentsCsv.split(',').map(s => s.trim()).filter(Boolean);
- const checks = agents.map(agent => [
- `_found_${agent.replace(/[^a-zA-Z0-9]/g, '_')}=0`,
- `for f in "$LOG_DIR"/${agent}-*.jsonl "$LOG_DIR"/${agent}.jsonl; do`,
- ` if [ -f "$f" ] && [ -s "$f" ]; then`,
- ` _found_${agent.replace(/[^a-zA-Z0-9]/g, '_')}=1`,
- ` echo "[agent-coverage] OK: ${agent} -> $(basename "$f") ($(wc -l < "$f") lines)"`,
- ` break`,
- ` fi`,
- `done`,
- `if [ "$_found_${agent.replace(/[^a-zA-Z0-9]/g, '_')}" -eq 0 ]; then`,
- ` echo "[agent-coverage] MISSING: ${agent} — no JSONL output found"`,
- ` MISSING="$MISSING ${agent}"`,
- `fi`,
- ].join('\n')).join('\n\n');
- return [
- 'set -euo pipefail',
- 'LOG_DIR="${E2E_JSONL_LOG_DIR:-$HOME/.loongsuite-pilot/logs/output}"',
- 'MISSING=""',
- '',
- 'echo "[agent-coverage] checking: ' + agents.join(', ') + '"',
- 'echo "[agent-coverage] log dir: $LOG_DIR"',
- 'ls "$LOG_DIR"/*.jsonl 2>/dev/null || echo "[agent-coverage] (no jsonl files found)"',
- '',
- checks,
- '',
- 'if [ -n "$MISSING" ]; then',
- ' echo ""',
- ' echo "[agent-coverage] FAILED: missing agents:$MISSING"',
- ' echo "[agent-coverage] All of: ' + agents.join(', ') + ' must produce JSONL data."',
- ' exit 1',
- 'fi',
- 'echo "[agent-coverage] ALL required agents produced JSONL data."',
- ].join('\n');
- }
- /**
- * Build script that writes agent configs (codex config.toml, claude onboarding, proxy).
- * Should run before `waitForPilotReady`: pilot polls discovery every 30s, so as long
- * as configs land before the 180s readiness wait completes, pilot will pick them up
- * within the wait window. (Runs after `loongsuite-pilot start` in install-smoke; the
- * first poll may see no configs, but a subsequent poll will.)
- */
- export function buildAgentConfigSetupScript(env) {
- let body = '';
- body += buildRemoteCodexConfigSh(env);
- body += buildRemoteClaudeOnboardingSkipSh(env);
- body += buildRemoteClaudeProxyConfigSh(env);
- return body;
- }
- function shouldEnsureAgentClis(env, useMatrixProbe) {
- const v = env.E2E_ENSURE_AGENT_CLIS?.trim().toLowerCase();
- if (v === '0' || v === 'false' || v === 'no') return false;
- if (v === '1' || v === 'true' || v === 'yes') return true;
- return useMatrixProbe;
- }
- export function buildAgentEnsureOnlyScript(env) {
- const useMatrix = env.E2E_USE_MATRIX_PROBE?.trim() === '1';
- if (!shouldEnsureAgentClis(env, useMatrix)) return '';
- const matrix = loadAgentMatrix(env);
- console.log('[e2e-docker] Ensuring agent-matrix CLIs');
- return buildEnsureAgentClisScript(matrix, env);
- }
- /**
- * Build the probe-only script (ensure CLIs + run probes).
- * Agent configs must already be written and plugins deployed before this runs.
- */
- export function buildAgentProbeOnlyScript(env) {
- const useMatrix = env.E2E_USE_MATRIX_PROBE?.trim() === '1';
- const customProbe = env.E2E_AGENT_PROBE_CMD?.trim();
- if (!useMatrix && !customProbe) return '';
- const matrix = loadAgentMatrix(env);
- const ensure = shouldEnsureAgentClis(env, useMatrix);
- let body = '';
- if (ensure) {
- console.log('[e2e-docker] Ensuring agent-matrix CLIs');
- body += buildEnsureAgentClisScript(matrix, env);
- body += '\n';
- }
- if (useMatrix) {
- body += buildMatrixProbeScript(matrix, env);
- return body;
- }
- body += buildAgentProbeRemoteBody(customProbe);
- return body;
- }
- export function buildProbeEnvInjections(env) {
- const chunks = [buildRemoteSecretExportsSh(env)];
- const tok = normalizeE2eQoderPersonalAccessToken(env.E2E_QODER_PERSONAL_ACCESS_TOKEN);
- if (tok) {
- console.log(
- `[e2e-docker] Injecting QODER_PERSONAL_ACCESS_TOKEN (${tok.length} chars)`,
- );
- chunks.push(`export QODER_PERSONAL_ACCESS_TOKEN=${shellSingleQuoteBash(tok)}`);
- }
- const cursorKey = env.E2E_CURSOR_API_KEY?.trim();
- if (cursorKey) {
- console.log(`[e2e-docker] Injecting CURSOR_API_KEY (${cursorKey.length} chars)`);
- chunks.push(`export CURSOR_API_KEY=${shellSingleQuoteBash(cursorKey)}`);
- }
- const joined = chunks.filter(Boolean).join('\n');
- return joined ? `${joined}\n` : '';
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.