diff --git a/.agents/skills/unidesk-trans/SKILL.md b/.agents/skills/unidesk-trans/SKILL.md index 7ac9b06b..800e3117 100644 --- a/.agents/skills/unidesk-trans/SKILL.md +++ b/.agents/skills/unidesk-trans/SKILL.md @@ -31,6 +31,11 @@ Host workspace、k3s、Windows、GitHub issue/PR route 见 [references/routes.md ## P0 边界 +- `trans --help` 是高频直接阅读入口: + - 顶层只展示 route 语法、operation 分组和 `trans --help ` 下钻索引。 + - 顶层与 scoped help 都必须有界且直接返回;出现 `outputTruncated` 或 dump 即视为 CLI 缺陷。 + - 修复帮助过长时必须收敛信息结构,禁止提高 stdout 阈值。 + - dump 只允许用于显式 `--full`、`--raw` 或确实无法预先界定的一次性异常证据。 - 远端文本修改优先 `trans apply-patch`;不要 download/upload/sed 拼临时 diff 代替 patch。 - `upload` / `download` 仅用于必要的二进制文件或生成物: - 远端文本读取优先使用 `cat` / `rg`; diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 32ae3309..902e2a8b 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -2,6 +2,12 @@ UniDesk 的统一 CLI 实现入口是根目录 `scripts/cli.ts`,运行方式固定为 `bun scripts/cli.ts `;普通根 CLI 子命令仍使用该入口。`trans ...` 是 SSH/WSL/k3s 透传专用入口,wrapper 委托轻量 `scripts/ssh-cli.ts` 启动链路,避免被无关根 CLI 子命令模块的解析或语法错误拖垮;长期参考文档、AGENTS 索引、CLI help 和人工远端操作示例都必须优先写 `trans ...`,不得再把 `bun scripts/cli.ts ssh ...` 作为默认透传入口。面向人工的默认输出采用 Kubernetes 风格的简洁表格、短摘要和 drill-down 命令;JSON 只用于 `--json`、`--raw`、`--full`、`-o json` 或其他明确机器消费模式。所有成功和失败路径仍必须给出可判定状态,避免无输出造成不可观测。 +- 高频 CLI 默认输出与帮助输出是直接阅读入口: + - 必须保持有界、低噪声并直接展示,不得触发 `outputTruncated` 或 `/tmp/unidesk-cli-output` dump。 + - 顶层帮助只展示分组索引和可执行的下钻命令,详细合同通过 ` --help ` 或等价 scoped help 获取。 + - 默认输出或帮助输出触发 dump 视为 CLI 缺陷,必须收敛信息结构,禁止用提高 stdout 阈值掩盖。 + - dump 只允许用于用户显式请求的 `--full`、`--raw`、机器完整输出,或确实无法预先界定的一次性异常证据。 + 主 server 必须在 PATH 上提供 `/root/.local/bin/trans` 可执行 wrapper,内容委托 repo 内版本化 `scripts/trans` 并执行 `bun scripts/ssh-cli.ts ssh "$@"`;交互 shell 可额外提供 alias,但非交互 Codex `exec` 和脚本不能依赖 alias 展开。 主 server 固定提供 PATH 可见的 `/usr/local/bin/unidesk`,委托版本化 `scripts/unidesk` 执行根 CLI;`/root/.local/bin/unidesk` 可以保留为用户级兼容链接,但不能作为非交互入口的唯一安装位置。高频人工入口优先写 `unidesk `;仓库内验证和未安装 wrapper 的 checkout 使用等价的 `bun scripts/cli.ts `。 @@ -274,7 +280,7 @@ GitHub issue/PR 正文局部修补必须优先使用 `trans gh:/owner/repo/issue `trans [ssh-like args...]` 是面向人的终端透传入口,不包装 JSON 输出,默认由 `scripts/ssh-cli.ts` 只加载 SSH/route/远程前端转发相关模块。主 server 本地执行时会在宿主机启动 `docker exec -i unidesk-backend-core backend-core --ssh-broker ...`,broker 只连接 backend-core 的 Docker 内网 `/ws/ssh`;core 使用 provider WebSocket 下发 open/dispatch 控制消息,但 stdin/stdout/stderr 数据面必须走 provider 主动连接 main server 的 `host.ssh.tcp-pool` TCP warm pool,provider-gateway 最终执行维护用 SSH 连接宿主或 WSL sshd。TTY 策略固定为交互登录 shell 使用 `ssh -tt`,带远端命令的会话使用 `ssh -T`;`apply-patch`、脚本 stdin、`py` 和旧 `apply-patch-v1` fallback 这类命令模式不得被伪终端回显或注入控制字符。该入口不暴露 database,也不改变 frontend/dev frontend/provider ingress 之外的业务边界;provider data TCP port 是 provider 主动连入的数据面端口,不是计算节点入站要求。 -`trans --help` 和 `trans --help` 是本地 JSON 帮助命令,必须快速返回;不能把 `--help` 解析成 Provider ID,不能打开交互 shell,也不能等待 provider 会话。 +`trans --help` 和 `trans --help` 是本地 JSON 帮助命令,必须快速返回;不能把 `--help` 解析成 Provider ID,不能打开交互 shell,也不能等待 provider 会话。顶层只展示 route 语法、operation 分组和 scoped help 索引;operation 细节通过 `trans --help ` 获取。任一默认帮助触发 `outputTruncated` 或 dump 都是缺陷,必须缩减顶层内容,禁止提高 stdout 阈值。 主 server 固定提供 `trans` 缩写,等价于 `bun scripts/ssh-cli.ts ssh "$@"` 的受控 UniDesk SSH 透传入口。这里必须同时保留两层入口:交互式 shell 可额外配置 alias;Codex `exec`、脚本和其他非交互 shell 不会自动展开 alias,所以还必须有 `/root/.local/bin/trans` 可执行 wrapper,内容固定为委托 repo 内版本化脚本: diff --git a/scripts/src/help.ts b/scripts/src/help.ts index 8f8bda0f..0a927ba2 100644 --- a/scripts/src/help.ts +++ b/scripts/src/help.ts @@ -169,111 +169,188 @@ export function serverHelp(action: string | undefined = undefined): unknown { }; } -export type SshHelpScope = "download"; +export type SshHelpScope = + | "argv" | "exec" | "git" | "node" | "kubectl" | "logs" + | "sh" | "bash" | "py" | "ps" | "cmd" + | "pwd" | "ls" | "cat" | "head" | "tail" | "stat" | "wc" | "rg" | "find" | "glob" | "skills" + | "apply-patch" | "apply-patch-v1" | "upload" | "download"; + +type SshOperationHelp = { + group: "process" | "shell" | "filesystem" | "patch" | "transfer"; + description: string; + usage: string[]; + notes?: string[]; +}; + +const SSH_OPERATION_HELP: Record = { + argv: { + group: "process", + description: "以原始 argv 边界运行一个远端进程;需要管道、变量或重定向时改用 sh/bash。", + usage: ["trans argv [args...]", "trans D601:/workspace argv git status --short --branch"], + }, + exec: { + group: "process", + description: "在 k3s workload route 中运行进程,并可显式透传 stdin 或指定容器内 cwd。", + usage: ["trans :k3s::[:] exec [--cwd /path] [--stdin] -- [args...]"], + }, + git: { + group: "process", + description: "在 host/workspace 或 Windows workspace route 中运行 Git convenience wrapper。", + usage: ["trans :/workspace git status --short --branch", "trans :win// git diff --check"], + }, + node: { + group: "process", + description: "在目标 route 中直接运行 Node.js argv。", + usage: ["trans node -e 'console.log(process.version)'"], + }, + kubectl: { + group: "process", + description: "在 k3s control-plane route 上执行有界 kubectl 诊断。", + usage: ["trans :k3s kubectl get pods -n "], + }, + logs: { + group: "process", + description: "从 k3s control-plane 或 workload route 读取有界日志。", + usage: ["trans :k3s:: logs --tail 80", "trans :k3s logs -n -l --tail 120"], + }, + sh: { + group: "shell", + description: "从 stdin 或单个命令字符串执行远端 POSIX /bin/sh。", + usage: ["trans sh <<'SH'", "trans sh -- ''"], + notes: ["sh -- 只接受一个 shell command string;单进程多 argv 使用 argv。"], + }, + bash: { + group: "shell", + description: "仅在需要 pipefail、数组、[[ ]] 等 Bash 语法时执行远端 Bash。", + usage: ["trans bash <<'BASH'", "trans bash -- ''"], + }, + py: { + group: "shell", + description: "从本地 stdin 执行远端 Python 源码,并保留 script argv。", + usage: ["trans py [script-args...] < script.py"], + }, + ps: { + group: "shell", + description: "在 Windows route 中执行 PowerShell 源码或 argv;route 已包含 win。", + usage: ["trans :win[//] ps <<'PS'", "trans :win ps ''"], + }, + cmd: { + group: "shell", + description: "在 Windows route 中以 UTF-8 环境执行 cmd.exe/batch。", + usage: ["trans :win[//] cmd <<'CMD'", "trans :win cmd ver"], + }, + pwd: { group: "filesystem", description: "读取 Windows workspace 当前目录。", usage: ["trans :win// pwd"] }, + ls: { group: "filesystem", description: "有界列出 Windows workspace 文件。", usage: ["trans :win// ls --limit 50"] }, + cat: { group: "filesystem", description: "读取远端文本文件;二进制文件使用 download。", usage: ["trans cat "] }, + head: { group: "filesystem", description: "按行读取远端文本文件开头。", usage: ["trans head -n 40 "] }, + tail: { group: "filesystem", description: "按行读取远端文本文件结尾。", usage: ["trans tail -n 40 "] }, + stat: { group: "filesystem", description: "读取远端文件元数据。", usage: ["trans stat "] }, + wc: { group: "filesystem", description: "统计远端文本的行、词、字符或字节。", usage: ["trans wc [-l|-w|-m|-c] "] }, + rg: { group: "filesystem", description: "执行有界远端 ripgrep;Windows route 使用受控 UTF-8 子集。", usage: ["trans rg [options] [path...]"] }, + find: { group: "filesystem", description: "不依赖 shell quoting 的结构化远端 find。", usage: ["trans find [--contains TEXT] [--limit N]"] }, + glob: { group: "filesystem", description: "通过远端 helper 执行有界 glob 匹配。", usage: ["trans glob [--root DIR] [--pattern PATTERN] [--limit N]"] }, + skills: { group: "filesystem", description: "发现 WSL/Linux 及可选 Windows skill 目录。", usage: ["trans skills [--scope all|wsl|windows] [--limit N]"] }, + "apply-patch": { + group: "patch", + description: "默认远端文本修改入口;本地 v2 engine 计算变更,route 仅负责读写。", + usage: ["trans apply-patch [--cwd /path] < patch.diff"], + notes: ["失败后重读当前目标块并缩小 hunk;不得自动回退 apply-patch-v1 或整文件 upload。"], + }, + "apply-patch-v1": { + group: "patch", + description: "显式调用 legacy remote apply_patch helper;只作为人工确认后的兼容入口。", + usage: ["trans apply-patch-v1 [--allow-loose] < patch.diff"], + }, + upload: { + group: "transfer", + description: "上传必要的二进制文件或生成物并自动核对字节数与 SHA-256。", + usage: ["trans upload "], + notes: ["远端文本读取使用 cat/rg,修改使用 apply-patch。"], + }, + download: { + group: "transfer", + description: "下载必要的二进制文件或生成物并自动核对字节数与 SHA-256。", + usage: ["trans download "], + }, +}; + +const SSH_OPERATION_GROUPS = { + process: ["argv", "exec", "git", "node", "kubectl", "logs"], + shell: ["sh", "bash", "py", "ps", "cmd"], + filesystem: ["pwd", "ls", "cat", "head", "tail", "stat", "wc", "rg", "find", "glob", "skills"], + patch: ["apply-patch", "apply-patch-v1"], + transfer: ["upload", "download"], +} as const satisfies Record; + +const SSH_HELP_SCOPES = Object.keys(SSH_OPERATION_HELP) as SshHelpScope[]; +const SSH_HELP_SCOPE_SET = new Set(SSH_HELP_SCOPES); + +function sshEntrypoint(): "trans" | "tran" | "ssh" { + const rawEntrypoint = process.env.UNIDESK_SSH_ENTRYPOINT?.trim(); + return rawEntrypoint === "trans" || rawEntrypoint === "tran" || rawEntrypoint === "ssh" ? rawEntrypoint : "ssh"; +} export function sshHelpScope(args: string[]): SshHelpScope | undefined { const [top, helpToken, scope] = args; - if (top !== "ssh" || args.length !== 3 || !isHelpToken(helpToken)) return undefined; - return scope === "download" ? scope : undefined; + if (top !== "ssh" || args.length !== 3 || !isHelpToken(helpToken) || !SSH_HELP_SCOPE_SET.has(scope ?? "")) return undefined; + return scope as SshHelpScope; } export function sshHelp(scope: SshHelpScope | undefined = undefined): unknown { if (scope === "download") return sshDownloadHelp(); + if (scope !== undefined) return sshOperationHelp(scope); + const entrypoint = sshEntrypoint(); + const operationGroups = Object.fromEntries( + Object.entries(SSH_OPERATION_GROUPS).map(([group, operations]) => [group, operations.join(" | ")]), + ); return { - command: "ssh", + command: `${entrypoint} --help`, output: "json", - description: "Open a Host SSH / WSL SSH maintenance session through the provider-gateway bridge.", - usage: [ - "trans ", - "trans argv [args...]", - "trans :/absolute/workspace apply-patch < patch.diff", - "trans upload ", - "trans download ", - "trans apply-patch-v1 [--allow-loose] < patch.diff", - "trans py [script-args...] < script.py", - "trans sh [arg...] <<'SH'", - "trans bash [arg...] <<'BASH'", - "trans skills [--scope all|wsl|windows] [--limit N]", - "trans find [--contains TEXT] [--limit N]", - "trans glob [--root DIR] [--pattern PATTERN]", - "trans NC01:/root/hwlab-v03 git status --short --branch", - "trans D601:win ps <<'PS'", - "trans D601:win/c/test ps <<'PS'", - "trans D601:win/c/test cmd <<'CMD'", - "trans D601:win cmd ver", - "trans D601:win/c/test cmd cd", - "trans D601:win/c/test pwd", - "trans D601:win/c/test ls --limit 50", - "trans D601:win/c/test cat README.md", - "trans D601:win/c/test head -n 40 README.md", - "trans D601:win/c/test tail -n 40 README.md", - "trans D601:win/c/test stat README.md", - "trans D601:win/c/test wc README.md", - "trans D601:win/c/test rg -i needle .", - "trans D601:win/c/test git status --short --branch", - "trans D601:win/c/test git diff --check", - "trans D601:win/c/test git commit -m 'fix: update docs'", - "trans D601:win/c/test git exact-commit status", - "trans D601:win/c/test git exact-commit plan --path src/main.c", - "trans D601:win/c/test git exact-commit run --path src/main.c --message 'fix: exact change' --confirm", - "trans D601:win skills [--scope agents|codex|all] [--limit N]", - "trans NC01:k3s", - "trans NC01:k3s kubectl get pods -n hwlab-dev", - "trans NC01:k3s", - "trans NC01:k3s kubectl get pipelineruns -n hwlab-ci", - "trans NC01:k3s sh <<'SH'", - "trans NC01:k3s:hwlab-dev:hwlab-cloud-api:hwlab-cloud-api exec --cwd /app -- pwd", - "trans NC01:k3s:hwlab-dev:hwlab-cloud-api:hwlab-cloud-api apply-patch --cwd /app <<'PATCH'", - "trans NC01:k3s:hwlab-dev:hwlab-cloud-api apply-patch-v1 <<'PATCH'", - "tar -C /path/to/files -cf - . | trans NC01:k3s:unidesk:code-queue exec --cwd /root/unidesk --stdin -- tar -xf - -C /root/unidesk", - "trans D601:win/c/test apply-patch <<'PATCH'", - "trans D601:win upload ./tool.mjs C:\\Temp\\tool.mjs", - "trans D601:win download C:\\Temp\\tool.mjs ./tool.mjs", - "trans NC01:k3s:hwlab-dev:hwlab-cloud-api node -e 'console.log(process.version)'", - "trans NC01:k3s:hwlab-dev:hwlab-cloud-api sh <<'SH'", - "trans NC01:k3s:hwlab-dev:hwlab-cloud-api logs --tail 80", - "trans NC01:k3s logs -n agentrun-ci -l tekton.dev/pipelineRun= --tail 120", - ], - notes: [ - "trans --help and trans --help print this JSON help and never open an interactive session; the underlying ssh subcommand keeps the same help behavior.", - "For non-interactive remote commands, prefer argv for a single process and explicit sh/bash stdin for shell logic.", - "Windows routes have explicit Windows operations, not POSIX shell aliases: `ps` runs Windows PowerShell from stdin or one inline command, `cmd` runs cmd.exe/batch from stdin or one command line, and `skills` discovers Windows skill directories.", - "On Windows routes, the route already contains `win`; write `trans D601:win/c/test ps`, not `trans D601:win/c/test win ps`. Repository commands can use the git convenience wrapper, including `git status`, `git diff`, and non-interactive `git commit -m ...`; commands that need shell review should use `ps` or `cmd`.", - "Windows routes include read-only filesystem convenience operations `pwd`, `ls`, `cat`, `head`, `tail`, `stat`, `wc`, and a bounded UTF-8 `rg` subset. These are implemented through a Windows fs backend with UTF-8/binary checks and bounded output; they do not imply POSIX `sh`/`bash` availability.", - "For Windows PowerShell, use `trans :win ps <<'PS'`; the PowerShell body is written to a temporary .ps1 with UTF-8 settings and executed by powershell.exe. Do not use POSIX `sh` or `bash` for Windows PowerShell.", - "For Windows cmd.exe, use `trans :win// cmd <<'CMD'`; `cmd` with no command-line arguments reads the UTF-8 batch body from stdin, injects UTF-8/Python encoding defaults, runs it from a temp .cmd file, and deletes the temp file.", - "`argv` executes direct argv tokens only: `trans argv ls -la` is valid, but `trans argv 'ls -la'` is rejected because the single string would be treated as an executable path; use `sh -- 'ls -la'` or `bash -- 'ls -la'` for one-line shell logic.", - "For one-line remote shell logic without a heredoc, use `sh -- ''` for POSIX syntax or `bash -- ''` for Bash syntax. Outer shell operators written outside trans, such as `trans NC01:/repo sed ... && sed ...`, are parsed by the local shell before UniDesk starts and therefore cannot be redirected by the CLI.", - "`sh --` and `bash --` accept exactly one shell command string. For direct argv commands with multiple tokens, use `argv`, `exec`, or a known direct subcommand such as `git`, `rg`, `sed`, or `cat`.", - "The removed `script` and `shell` operations intentionally fail. The operation name must declare the shell dialect: `sh` maps to target `/bin/sh`, while `bash` maps to target `bash`.", - "sh and bash helper modes inject a tiny POSIX-compatible printf wrapper before user shell text, so portable printf headings such as `printf \"--- section ---\\n\"` work consistently under dash/sh and bash. Direct argv commands are unchanged.", - "For arbitrary stdin streams into a workload command, use a workload route plus `exec --stdin -- ...`; this keeps the route as location-only and avoids heredoc/base64/tar shell wrapping.", - "`apply-patch` is the default remote text patch entry and uses the v2 local line-based patch engine with remote read/write operations, including Windows routes such as `D601:win/c/test`, so long Unicode/Chinese lines and pure insertion hunks avoid the legacy remote shell hunk parser. Plain multi-file Update File patches on POSIX host/k3s and Windows workspace routes use bulk read/write operations to avoid per-file SSH round trips. Its stdout follows Codex apply_patch text output rather than UniDesk JSON output; stderr keeps Codex-style failure text and appends one `UNIDESK_APPLY_PATCH_TIMING` JSON summary with durationMs, patchBytes, fileCount, hunkCount, changedCount, remoteOperationCount, remoteOperationCounts and remoteElapsedMs so slow patch runs can be attributed without changing success stdout.", - "`upload` 和 `download` 只用于必要的二进制文件或生成物;远端文本应避免反复传输,读取使用 `cat`/`rg`,修改使用 `apply-patch`。成功传输的 JSON 会在 `hint` 中重复该提示,通过远端临时文件写入,自动核对两端字节数和 SHA-256,并返回 `verification.automatic=true`、`verification.verified=true` 和 `verification.match.{bytes,sha256}=true`;该 JSON 已是完整性证据,无需额外执行 `sha256sum`。下载通过 `host.ssh.tcp-pool` 流式传输并输出进度 JSON;受控异步产物任务可传入 `--inactivity-timeout-ms`,只要数据持续流动就不受普通短命令预算影响。Windows route 下载(例如 `trans D601:win download C:\\Temp\\tool.mjs ./tool.mjs`)会自动把盘符路径映射到同一 provider 的 WSL `/mnt/` host route,同时仍返回字节数和 SHA-256 校验证据。", - "`apply-patch-v1` is the only legacy fallback entry: it rejects low-context update hunks by default, reports the matched file:line for each hunk on stderr, and only accepts --allow-loose when the caller has manually reviewed an intentionally ambiguous insertion.", - "`sh` inherits provider proxy variables such as HTTP_PROXY/HTTPS_PROXY/ALL_PROXY/NO_PROXY and runs target `/bin/sh`; use `bash` only for Bash syntax such as `pipefail`, arrays, substring expansion, or `[[ ... ]]`, not as a proxy workaround.", - "Route syntax is `{provider}:{plane}[:{scope...}] {operation} [operation-args...]`: the first argv token locates a distributed target only, and every following token belongs to the operation parser. Host workspace routes use `:/absolute/workspace`; WSL providers can use `:win ps` for Windows PowerShell and `:win cmd` for Windows cmd.exe, with `:win/c/test ...` mapping the Windows cwd to `C:\\test`; native k3s providers such as D601 and G14 use `:k3s` for the control plane and `:k3s::[:]` for a workload/container. In k3s routes, `:` is the distributed route separator; `/...` is only an in-container filesystem cwd and never selects a container. Prefer operation `--cwd /path` when a container is also specified.", - "Use `win`, not `win32`; the win route is a Windows operation plane. `ps` and `cmd` both set UTF-8/Python encoding defaults, while `cmd` also sets `chcp 65001`.", - "`:win skills` discovers the current Windows user's `%USERPROFILE%\\.agents\\skills` by default; use `--scope all` to include `%USERPROFILE%\\.codex\\skills`.", - "Do not put operation names in any colon route segment, including nested k3s namespace/workload/container segments.", - "Do not use post-provider shorthand such as `trans NC01 k3s ...`; write `trans NC01:k3s ...` so location and operation stay separated.", - "If an ssh-like remote command fails with timeout/kex/exit-255 friction, stderr includes one low-noise UNIDESK_SSH_HINT JSON line with the argv retry command.", - "Ordinary non-interactive ssh/trans/tran remote commands have a hard top-level runtime timeout capped at 60s. Timeout writes UNIDESK_SSH_RUNTIME_TIMEOUT or UNIDESK_TRAN_TIMEOUT_HINT and disconnects the broker; long CI/CD, trace, logs, build, or hardware work must use submit-and-poll / short query loops instead of keeping trans open. Whole-file `download` is the narrow exception: controlled async callers can pass `--inactivity-timeout-ms` for a verified progress-emitting tcp-pool transfer.", - "Only slow ssh/trans/tran runtime writes UNIDESK_SSH_TIMING JSON to stderr; operations over 10s are marked level=warning even when they succeed, because slow successful calls are a distributed performance monitoring signal. Check provider latency, remote command cost, helper bootstrap, or remote patch optimization before repeating high-frequency work. Routine short calls do not emit timing noise.", - "The local trans/tran wrapper must not add provider/plane directory locks; rely on k8s/Tekton/Argo/Lease or server-side TTL queues for coordination.", - "Use -- before a remote command that intentionally starts with a dash.", + description: "通过 provider-gateway bridge 访问 Host SSH、WSL、Windows 或 k3s 目标。", + routeSyntax: { + general: `${entrypoint} [operation-args...]`, + hostWorkspace: ":/absolute/workspace", + k3sControlPlane: ":k3s", + k3sWorkload: ":k3s::[:]", + windowsWorkspace: ":win[//]", + githubContent: "gh://[/issue|/pr]/", + }, + operationGroups, + scopedHelp: { + command: `${entrypoint} --help `, + availableOperationCount: SSH_HELP_SCOPES.length, + examples: [`${entrypoint} --help apply-patch`, `${entrypoint} --help download`, `${entrypoint} --help ps`], + }, + boundaries: [ + "route 只定位目标,route 后的 token 全部交给 operation parser。", + "单进程优先 argv;shell 逻辑显式使用 sh/bash,Windows 使用 ps/cmd。", + "远端文本读取优先 cat/rg,修改优先 apply-patch;upload/download 仅用于必要的二进制或生成物。", + "普通 trans 短连接上限保持 60s;长流程使用受控 submit-and-poll 入口。", ], }; } +function sshOperationHelp(scope: Exclude): unknown { + const entrypoint = sshEntrypoint(); + const detail = SSH_OPERATION_HELP[scope]; + return { + command: `${entrypoint} --help ${scope}`, + output: "json", + scope, + group: detail.group, + description: detail.description, + routeSyntax: `${entrypoint} ${scope} [operation-args...]`, + usage: detail.usage.map((value) => value.replace(/^trans\b/u, entrypoint)), + notes: detail.notes ?? [], + next: [`${entrypoint} --help`, `${entrypoint} --help ${scope}`], + }; +} + function sshDownloadHelp(): unknown { const configuredRepoRoot = process.env.UNIDESK_TRANS_REPO_ROOT?.trim() || null; - const rawEntrypoint = process.env.UNIDESK_SSH_ENTRYPOINT?.trim(); - const entrypoint = rawEntrypoint === "trans" || rawEntrypoint === "tran" || rawEntrypoint === "ssh" - ? rawEntrypoint - : "ssh"; + const entrypoint = sshEntrypoint(); return { - command: `${entrypoint} download`, + command: `${entrypoint} --help download`, output: "json", scope: "download", description: "下载一个必要的二进制文件或生成物,并自动核对远端/本地字节数与 SHA-256;远端文本改用 cat/rg/apply-patch。", diff --git a/scripts/src/ssh-help.test.ts b/scripts/src/ssh-help.test.ts index d0b8cbd1..7c7000f3 100644 --- a/scripts/src/ssh-help.test.ts +++ b/scripts/src/ssh-help.test.ts @@ -3,15 +3,74 @@ import { describe, expect, test } from "bun:test"; import { repoRoot } from "./config"; import { sshHelp, sshHelpScope } from "./help"; -describe("ssh download scoped help", () => { - test("selects only the exact help-first download scope", () => { +type RenderedHelp = { + ok: boolean; + command: string; + data: { + command?: string; + scope?: string; + runtime?: { repoRoot: string }; + routeSyntax?: Record | string; + operationGroups?: Record; + scopedHelp?: { availableOperationCount: number }; + usage?: string[]; + outputTruncated?: boolean; + dump?: unknown; + }; +}; + +function runTransHelp(...args: string[]): { stdout: string; rendered: RenderedHelp } { + const result = spawnSync("bun", ["scripts/ssh-cli.ts", ...args], { + cwd: repoRoot, + env: { + ...process.env, + UNIDESK_SSH_ENTRYPOINT: "trans", + UNIDESK_TRANS_REPO_ROOT: repoRoot, + }, + encoding: "utf8", + }); + expect(result.status).toBe(0); + expect(result.stderr).toBe(""); + return { stdout: result.stdout, rendered: JSON.parse(result.stdout) as RenderedHelp }; +} + +describe("ssh bounded progressive help", () => { + test("selects exact help-first operation scopes", () => { expect(sshHelpScope(["ssh", "--help", "download"])).toBe("download"); - expect(sshHelpScope(["ssh", "help", "download"])).toBe("download"); + expect(sshHelpScope(["ssh", "help", "apply-patch"])).toBe("apply-patch"); + expect(sshHelpScope(["ssh", "--help", "ps"])).toBe("ps"); expect(sshHelpScope(["ssh", "--help"])).toBeUndefined(); + expect(sshHelpScope(["ssh", "--help", "unknown"])).toBeUndefined(); expect(sshHelpScope(["ssh", "NC01:k3s", "--help"])).toBeUndefined(); expect(sshHelpScope(["ssh", "--help", "download", "extra"])).toBeUndefined(); }); + test("keeps the top-level model compact while indexing routes and every scoped operation", () => { + const top = sshHelp() as { + routeSyntax: Record; + operationGroups: Record; + scopedHelp: { command: string; availableOperationCount: number }; + outputTruncated?: boolean; + }; + const serialized = JSON.stringify(top); + const grouped = Object.values(top.operationGroups).flatMap((value) => value.split(" | ")); + + expect(Buffer.byteLength(serialized, "utf8")).toBeLessThan(6_144); + expect(top.outputTruncated).toBeUndefined(); + expect(top.routeSyntax.general).toContain(" "); + expect(top.routeSyntax.k3sWorkload).toContain("::"); + expect(top.routeSyntax.windowsWorkspace).toContain(":win"); + expect(top.operationGroups.patch).toBe("apply-patch | apply-patch-v1"); + expect(top.operationGroups.transfer).toBe("upload | download"); + expect(new Set(grouped).size).toBe(top.scopedHelp.availableOperationCount); + expect(top.scopedHelp.command).toContain("--help "); + for (const operation of grouped) { + const scope = sshHelpScope(["ssh", "--help", operation]); + expect(scope).toBe(operation); + expect(Buffer.byteLength(JSON.stringify(sshHelp(scope)), "utf8")).toBeLessThan(6_144); + } + }); + test("keeps download help bounded and discloses the executing source root", () => { const scoped = sshHelp("download") as { scope: string; @@ -20,13 +79,11 @@ describe("ssh download scoped help", () => { examples: Record; contract: { pathOrder: string[]; transport: string; verification: { automatic: boolean } }; }; - const full = sshHelp() as { usage: string[] }; const serialized = JSON.stringify(scoped); expect(scoped.scope).toBe("download"); expect(scoped.usage.length).toBeLessThanOrEqual(4); - expect(scoped.usage.length).toBeLessThan(full.usage.length); - expect(Buffer.byteLength(serialized, "utf8")).toBeLessThan(10_240); + expect(Buffer.byteLength(serialized, "utf8")).toBeLessThan(6_144); expect(serialized).not.toContain("git exact-commit"); expect(scoped.runtime.repoRoot).toBe(repoRoot); expect(scoped.runtime.cliPath).toBe(`${repoRoot}/scripts/ssh-cli.ts`); @@ -40,46 +97,32 @@ describe("ssh download scoped help", () => { "trans NC01:k3s:hwlab-v03:hwlab-cloud-api:hwlab-cloud-api download /tmp/trace.json ./trace.json", ); expect(scoped.examples.windowsDrive).toContain("D:\\tmp\\trace.json"); - expect(scoped.examples.explicitWorktree).toBe( - `UNIDESK_TRANS_REPO_ROOT=${repoRoot} trans NC01:k3s:hwlab-v03:hwlab-cloud-api:hwlab-cloud-api download /tmp/trace.json ./trace.json`, - ); }); - test("renders the original trans command without stdout dump fallback", () => { - const result = spawnSync("bun", ["scripts/ssh-cli.ts", "--help", "download"], { - cwd: repoRoot, - env: { - ...process.env, - UNIDESK_SSH_ENTRYPOINT: "trans", - UNIDESK_TRANS_REPO_ROOT: repoRoot, - }, - encoding: "utf8", - }); + test("renders compact top-level and scoped help without dump fallback", () => { + const top = runTransHelp("--help"); + expect(Buffer.byteLength(top.stdout, "utf8")).toBeLessThan(6_144); + expect(top.rendered.ok).toBe(true); + expect(top.rendered.command).toBe("trans --help"); + expect(top.rendered.data.outputTruncated).toBeUndefined(); + expect(top.rendered.data.dump).toBeUndefined(); + expect(top.rendered.data.operationGroups?.transfer).toContain("download"); - expect(result.status).toBe(0); - expect(result.stderr).toBe(""); - expect(Buffer.byteLength(result.stdout, "utf8")).toBeLessThan(10_240); - const rendered = JSON.parse(result.stdout) as { - ok: boolean; - command: string; - data: { scope: string; runtime: { repoRoot: string }; usage: string[]; outputTruncated?: boolean }; - }; - expect(rendered.ok).toBe(true); - expect(rendered.command).toBe("trans --help download"); - expect(rendered.data.scope).toBe("download"); - expect(rendered.data.runtime.repoRoot).toBe(repoRoot); - expect(rendered.data.usage.length).toBeLessThanOrEqual(4); - expect(rendered.data.outputTruncated).toBeUndefined(); + const routeTop = runTransHelp("NC01:k3s", "--help"); + expect(routeTop.rendered.command).toBe("trans NC01:k3s --help"); + expect(routeTop.rendered.data.outputTruncated).toBeUndefined(); + expect(routeTop.rendered.data.operationGroups).toEqual(top.rendered.data.operationGroups); - const unified = spawnSync("bun", ["scripts/cli.ts", "ssh", "--help", "download"], { - cwd: repoRoot, - env: process.env, - encoding: "utf8", - }); - expect(unified.status).toBe(0); - expect(unified.stderr).toBe(""); - const unifiedRendered = JSON.parse(unified.stdout) as { data: { scope: string; runtime: { repoRoot: string } } }; - expect(unifiedRendered.data.scope).toBe("download"); - expect(unifiedRendered.data.runtime.repoRoot).toBe(repoRoot); + const applyPatch = runTransHelp("--help", "apply-patch"); + expect(applyPatch.rendered.command).toBe("trans --help apply-patch"); + expect(applyPatch.rendered.data.scope).toBe("apply-patch"); + expect(applyPatch.rendered.data.usage?.[0]).toContain("apply-patch"); + expect(applyPatch.rendered.data.outputTruncated).toBeUndefined(); + + const download = runTransHelp("--help", "download"); + expect(download.rendered.command).toBe("trans --help download"); + expect(download.rendered.data.scope).toBe("download"); + expect(download.rendered.data.runtime?.repoRoot).toBe(repoRoot); + expect(download.rendered.data.outputTruncated).toBeUndefined(); }); });