Initial import of streamline

This commit is contained in:
2026-11-16 17:26:44 -08:00
commit 8e4aec1855
1221 changed files with 274256 additions and 0 deletions
+575
View File
@@ -0,0 +1,575 @@
/**
* `wait-for` — the blocking wait primitive the executor agents call instead of
* hand-rolling a polling loop.
*
* ## Why a tool, when `until … do sleep …; done` already exists
*
* Because the loop is not the expensive part — the *turns* are. Every tick of a
* hand-rolled poll is one Bash call, and one Bash call is one model turn:
* thinking, generation, a full cache read (median 54.8 M tokens on a bug round),
* and a tool round-trip. The 2026-09-14 sample measured 1,790 byte-identical
* repeat calls across 50 tasks — `date` 566 times, `pgrep -f "airb pull"` 600
* times, `du -sh ~/iosapp/TikTokM.app` 110 times — plus 3,857 literal sleeps
* totalling 22.9 h. All of it to learn one bit: is the build done yet.
*
* One `wait-for` call answers that bit once, at a cost of one turn, however
* long the wait. That is the entire point; everything below is in service of
* making the single call trustworthy enough that the agent does not feel the
* need to check up on it.
*
* ## What "trustworthy enough" means here
*
* An agent abandons a blocking call and goes back to polling the moment the
* call looks hung. So:
*
* - It **prints progress** (a heartbeat line on a widening interval), so the
* PTY sees output and the model sees that time is passing on purpose.
* - It **always prints the log tail** on exit — success or timeout — because
* the very next thing the agent wants is `tail -3 build.log`, and making it
* issue a second call for that gives back a chunk of what we just saved.
* - It **distinguishes timeout (124) from failure**, so a timeout is a fact
* the agent can report rather than something it has to infer from silence.
* - Each probe gets **its own timeout**. A probe that wedges (a hung `airb
* cmd` over a dropped SSH is the realistic case) must not wedge the wait.
*
* ## 已知代价:等待不再与别的工作重叠(2026-09-15 记)
*
* `--run` 是**阻塞**的,这正是它省掉几十个回合的原因,但同一件事也有代价:以前
* agent 用 `pgrep` / `date` 一格一格轮询时,**间隙里模型还在干别的** —— 读代码、
* 准备证据、记 Conditions。现在一次调用把整个构建从头等到尾,这段时间可能变成了
* 纯等待。
*
* 上线首日(19 个执行轮)的点估计与这条一致:机制指标全线改善(重复调用
* 14.3% → 0.6%,每轮 Bash 调用 161 → 109),而**单轮时长反而升了**(iOS 中位
* 49min → 90min),每轮**全部**工具调用中位 213、没跟着 Bash 一起降。样本太小
* (19 轮 / 20 小时,平台构成与基线差很远),不构成证据,但方向对得上。
*
* **2026-09-29 的正式回测里,单轮时长若仍不降,先查这条,别先怀疑别的。**
* 真要改,方向是让等待能和别的工作重叠 —— 给 `--run` 一个「只起不等、返回 pid
* 和日志路径」的模式(起完先去干别的,晚点再 `--pid` 等),而不是退回轮询。
*
* ## Deliberately not here
*
* No "start the build for me" verb. The build commands differ per platform, per
* repo and per node, they live in node-local skills, and wrapping them here
* would put this file on the critical path of every build-script change. This
* tool only ever *watches*; starting things stays where it already works.
*
* Callable directly (`bun bin/wait-for.ts --until …`) or as the satellite
* bundle's `wait-for` subcommand (see satellite/src/entry.ts), so a deployed
* node runs the same version as the prompt that told it to.
*/
import { spawn } from "node:child_process";
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from "node:fs";
import path from "node:path";
// 相对路径:bin/ 在 workspaces 之外,直接 `bun bin/wait-for.ts` 时解析不到 @bbbug/shared
import { pickProbe, settleLoop } from "../shared/src/settle";
import { uiWaitLoop } from "../shared/src/ui_wait";
const USAGE = `wait-for —— 阻塞等待一个长任务完成,一次调用顶掉几十次轮询。
用法(六选一,互斥):
wait-for --run '<command>' 起一个长命令,等它跑完(构建 / 拉包 / 部署首选)
wait-for --until '<probe>' probe 退出码 0 = 条件达成
wait-for --while '<probe>' probe 退出码 0 = 仍在进行;非 0 = 达成
wait-for --pid <pid> 等这个进程退出
wait-for --pgrep '<pattern>' 等所有匹配该 pattern 的进程退出
wait-for --file <path> 等文件出现(配合 --match 时还要内容命中)
wait-for --settle 等界面稳定:画面指纹连续 --quiet(默认 1.2s)不变就返回,最多 --timeout(默认 8s)
可配 --probe '<cmd>'(stdout 即指纹);不给时用 Android 的 adb 截屏指纹
wait-for --ui-text '<regex>' 等界面上出现这段文案(代替点完 / 冷启后的 sleep):每秒读一次结构树,
出现就返回;默认 --timeout 30s(上限 3m)。等不到时打印**当前屏幕上的文案**,
告诉你实际在哪一页。Android 用 uiautomator,iOS 用正在跑的 cat-supervisor 实例;
也可 --probe '<cmd>'(stdout 是结构树)
wait-for --ui-gone '<regex>' 同上,等这段文案消失(加载中 / Loading / 转圈提示)
选项:
--log <path> 仅配合 --run:命令的输出写到哪(默认落 $TMPDIR/wait-for/)
--match '<regex>' 仅配合 --file:等文件内容出现该正则
--timeout <dur> 默认 30m,上限 4h。超时退出码 124
--interval <dur> 稳态探测间隔,默认 15s(头 60s 自动用 3s 快探)
--probe-timeout <dur> 单次 probe 的上限,默认 60s —— probe 自己卡住不会卡住等待
--tail <path> 达成或超时后打印该文件末尾(最常用:构建日志)
--tail-lines <n> 默认 20;失败/超时时自动打 80(显式传了就一律听你的)
--label '<text>' 进度行里显示,便于在日志里认出在等什么
--quiet 不打印心跳,只打印最终结果
退出码: 0 达成/命令成功 · 1 命令失败(真实退出码见输出) · 124 超时 · 2 用法错 · 3 probe 无法执行
不要用它等**设备 UI 状态**(catuse apps / dumpsys window / uiautomator dump):
UI 可能永远不出现,等不到时你只会拿到「没等到」,不知道现在在哪一页 —— 用 \`catuse ui\`
或截图看一眼。它是给构建 / 拉包 / 部署这类**有确定终点**的长任务用的。
例:
# 起一次 iOS 构建并等它结束 —— 一次调用搞定,不用自己写 nohup + 退出码文件 + 轮询
wait-for --run 'airb cmd "cd /Volumes/ebs/…/TikTok; bundle exec jojo build …"' \
--timeout 45m --label 'iOS build r2'
# 等远端构建落下退出码文件,然后直接把日志尾巴打出来
wait-for --until 'airb cmd "test -f /tmp/r3_build.exit"' \\
--timeout 45m --tail /tmp/r3_build.log --label 'iOS clean build'
# 等本地拉包进程结束
wait-for --pgrep 'airb pull' --timeout 20m --label 'pull app'
# 等日志里出现成功标记
wait-for --file ./pull3.log --match 'pull success' --timeout 20m
`;
/**
* Bare flags map to `true`, valued flags to their string.
*
* The sibling wrappers (bin/conditions.ts, bin/kb.ts) use the literal string
* "true" as the bare-flag sentinel. That is safe for them and NOT safe here:
* `--until true` is a perfectly ordinary probe — `true` is a real command, and
* it is the first thing anyone types to smoke-test this tool. Collapsing the
* two would make that call die with "--until 需要一个值".
*/
type Args = Record<string, string | true>;
function parseArgs(argv: string[]): Args {
const out: Args = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) continue;
const key = a.slice(2);
const next = argv[i + 1];
// A negative number is a value, not a flag; anything else starting with
// `--` begins the next flag.
if (next == null || (next.startsWith("--") && !/^--?\d/.test(next))) {
out[key] = true;
} else {
out[key] = next;
i++;
}
}
return out;
}
/** The string value of a flag, or null when it is absent or bare. */
function val(args: Args, key: string): string | null {
const v = args[key];
return typeof v === "string" ? v : null;
}
function die(code: number, msg: string): never {
process.stderr.write(msg.endsWith("\n") ? msg : msg + "\n");
process.exit(code);
}
/** `45s` / `10m` / `2h` / bare number = seconds. Rejects junk loudly. */
function parseDuration(raw: string | null, fallbackMs: number, what: string): number {
if (raw == null) return fallbackMs;
const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/i.exec(raw.trim());
if (!m) die(2, `${what} 解析不了:「${raw}」。写成 45s / 10m / 2h,或纯数字(按秒)。`);
const n = Number(m[1]);
const unit = (m[2] ?? "s").toLowerCase();
return Math.round(n * (unit === "ms" ? 1 : unit === "s" ? 1000 : unit === "m" ? 60_000 : 3_600_000));
}
const HARD_CAP_MS = 4 * 3_600_000;
/**
* 「这个 probe 在等设备 UI 状态」的识别式。
*
* ## 为什么要专门认它
*
* 上线三天(2026-09-17,66 个执行轮)量到 **33 次超时、累计烧掉 4.4 小时** ——
* 约等于每轮白烧 4 分钟。看它们在等什么,清一色是设备 UI:
*
* --timeout 3m ← catuse apps | grep -q TikTokBase
* --timeout 5m ← adb shell dumpsys window | grep -q "mCurrentFocus=…musically…"
* --timeout 8m ← adb shell "uiautomator dump /sdcard/b2.xml; grep -q Pr…"
*
* 超时值也说明问题:9 次 3m、6 次 4m、4 次 5m —— 全是 UI 尺度,不是构建尺度。
*
* 这是误用,而且是**提示词没写清楚**造成的:原文只说了「长任务(构建、拉包、部署)
* 用它」,没说不该用在哪。
*
* 等构建和等 UI 状态是两件事。构建有确定的终点,等不到就是还没好;**UI 状态没有** ——
* 它可能永远不会出现(点错了页、弹窗挡住了、App 崩了),而这时 `wait-for` 只能回你
* 一句「没等到」。以前一格一格轮询虽然费回合,但 agent 每次都能看一眼屏幕现在在哪一页
* 然后改主意。把可观察的循环换成盲等,是这个工具在这个场景下的净损失。
*
* 所以:**警告,不拦截。**拦截会把 agent 逼去找绕过写法 —— `date` 被敲 566 次就是
* 这么来的(见文件头)。
*/
const DEVICE_PROBE = /\b(catuse\s+(apps|ui|getscreenshot)|dumpsys\s+window|mCurrentFocus|uiautomator\s+dump|screencap|idb\s+ui|actl_|xdotool)/i;
const DEVICE_HINT =
" ⚠️ 这个 probe 在等**设备 UI 状态**,而 wait-for 是给「有确定终点的长任务」\n" +
" (构建 / 拉包 / 部署)用的。UI 状态可能永远不出现(点错页、弹窗挡住、App 崩了),\n" +
" 等不到时你只会拿到一句「没等到」,不知道现在到底在哪一页。\n" +
" 改用 `catuse ui` / 截图看一眼当前状态再决定下一步;真要等就把 --timeout 压到\n" +
" 1-2 分钟,别用构建尺度的值。\n";
/** 失败 / 超时时默认打多少行日志尾巴。见 runWaitFor 里 failLines 的理由。 */
const FAIL_TAIL_LINES = 80;
function fmt(ms: number): string {
const s = Math.round(ms / 1000);
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
if (m < 60) return `${m}m${String(s % 60).padStart(2, "0")}s`;
return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}m`;
}
/**
* Run a probe under its own timeout. Resolves to the exit code, or null when the
* probe itself had to be killed — which is NOT the same as "condition not met"
* and must not be allowed to look like it.
*/
function runProbe(cmd: string, timeoutMs: number): Promise<number | null> {
return new Promise((resolve) => {
const child = spawn("/bin/sh", ["-c", cmd], { stdio: ["ignore", "ignore", "ignore"] });
let killed = false;
const t = setTimeout(() => {
killed = true;
try { child.kill("SIGKILL"); } catch { /* already gone */ }
}, timeoutMs);
child.on("error", () => { clearTimeout(t); resolve(null); });
child.on("close", (code) => {
clearTimeout(t);
resolve(killed ? null : (code ?? 1));
});
});
}
/** Last N lines of a file, tolerant of it not existing yet or being binary-ish. */
function tailFile(p: string, lines: number): string {
try {
if (!existsSync(p)) return `(${p} 还不存在)`;
const size = statSync(p).size;
const buf = readFileSync(p);
// Only the last 256 KiB is ever interesting for a tail and a build log can
// be hundreds of megabytes.
const slice = buf.subarray(Math.max(0, buf.length - 262_144)).toString("utf8");
const out = slice.split("\n").filter((l, i, a) => i < a.length - 1 || l !== "").slice(-lines);
return out.length ? out.join("\n") : `(${p} 是空的,${size} 字节)`;
} catch (e) {
return `(读不了 ${p}: ${(e as Error).message})`;
}
}
interface Mode { kind: "run" | "until" | "while" | "pid" | "pgrep" | "file"; probe: string; desc: string }
function resolveMode(args: Args): Mode {
const picked = (["run", "until", "while", "pid", "pgrep", "file"] as const).filter((k) => args[k] != null);
if (picked.length === 0) die(2, `必须给出等待条件(--until / --while / --pid / --pgrep / --file)。\n\n${USAGE}`);
if (picked.length > 1) die(2, `等待条件只能给一个,收到了:${picked.map((k) => "--" + k).join(" ")}`);
const k = picked[0];
const v = val(args, k);
if (v == null) die(2, `--${k} 需要一个值。`);
// --run 的 probe 在 runCommand 里另建(要先把命令起起来才有得等)。
if (k === "run") return { kind: "run", probe: v, desc: `跑完 \`${short(v)}\`` };
if (k === "until") return { kind: "until", probe: v, desc: `直到 \`${v}\` 退出码为 0` };
if (k === "while") return { kind: "while", probe: v, desc: `直到 \`${v}\` 退出码不再为 0` };
if (k === "pid") {
if (!/^\d+$/.test(v)) die(2, `--pid 要一个数字,收到「${v}」。`);
// `kill -0` is the portable "does this pid exist" probe; sh quoting is safe
// because v is digits-only.
return { kind: "pid", probe: `kill -0 ${v} 2>/dev/null`, desc: `直到 pid ${v} 退出` };
}
if (k === "pgrep") {
return { kind: "pgrep", probe: `pgrep -f ${shq(v)} >/dev/null 2>&1`, desc: `直到没有进程匹配 \`${v}\`` };
}
// file
const match = val(args, "match");
const probe = match
? `test -f ${shq(v)} && grep -Eq ${shq(match)} ${shq(v)}`
: `test -f ${shq(v)}`;
return { kind: "file", probe, desc: match ? `直到 ${v} 里出现 /${match}/` : `直到 ${v} 出现` };
}
/** 命令太长时截短,只用于给人看的描述行。 */
function short(cmd: string): string {
const one = cmd.replace(/\s+/g, " ").trim();
return one.length > 90 ? one.slice(0, 90) + "…" : one;
}
/**
* 起一个长命令并等它结束 —— `--run` 模式。
*
* ## 为什么它值得单独存在,而不是「你自己 nohup 一下再 --until 等退出码文件」
*
* 因为那正是现在在发生的事,而且每一轮都重搓一遍、每次都不一样。2026-09-14 的
* 语料里,同一条 iOS 构建命令被包在至少五种壳里:`nohup bash -c`、`nohup bash -lc`、
* `rm -f x.exit x.log; nohup …`、`timeout N airb cmd …`(于是撞上 Bash 超时)、
* 以及先用 python 写一个 `r2_build.sh` 再跑它。其中一条的下一步就是**再用 python
* 去改自己刚写的那个脚本**,修 `--other_linker_flags` 的引号转义 —— 一次搓错,
* 白烧一个 25 分钟的构建。
*
* 再往后还要配一套轮询:`while true; do airb cmd "ps aux | grep jojo"; sleep; done`。
* 有一轮因此发起了 11 次构建。
*
* 这个模式把「起 + 等 + 拿退出码 + 拿日志尾巴」收成一次调用:
*
* - 命令**脱离本进程**跑(detached),所以 wait-for 自己被超时杀掉不会连累它;
* - 输出全部进日志文件,只把末尾几十行打回来 —— 构建日志几十 MB,不能进上下文;
* - 超时**不杀命令**,而是打印 pid 和一条现成的续等命令。等了 40 分钟的构建
* 不该因为超时设小了就白等。
*/
function startCommand(cmd: string, logPath: string): { pid: number; exitPath: string } {
mkdirSync(path.dirname(logPath), { recursive: true });
const exitPath = logPath + ".exit";
try { rmSync(exitPath, { force: true }); } catch { /* 首次运行本来就没有 */ }
const fd = openSync(logPath, "a");
// 包一层壳把**真实退出码**写到旁文件。不靠在日志里 grep "error:" 猜成败:
// 构建日志里出现 "error:" 太常见(警告、第三方输出、甚至成功构建里也有),
// 猜错的代价是把一次失败的构建报成成功,而下游会拿它当证据。
// 用**子壳**而不是 `{ …; }`:命令里一句 `exit 7` 会把当前 shell 整个退掉,
// 后面写退出码那一句就永远跑不到,于是每一次失败都被报成「拿不到退出码」。
const wrapped = `( ${cmd}\n) ; printf '%s' "$?" > ${shq(exitPath)}`;
const child = spawn("/bin/sh", ["-c", wrapped], { detached: true, stdio: ["ignore", fd, fd] });
child.unref();
closeSync(fd);
if (!child.pid) die(3, `起不来这条命令:${short(cmd)}`);
return { pid: child.pid, exitPath };
}
/** 读回 startCommand 落下的真实退出码;还没落下就是 null。 */
function readExitCodeOnce(exitPath: string): number | null {
try {
const raw = readFileSync(exitPath, "utf8").trim();
if (!/^\d+$/.test(raw)) return null;
return Number(raw);
} catch { return null; }
}
/**
* pid 消失和退出码落盘之间有几十毫秒的空档 —— 我们观察到的是前者。
* 短暂重试再下结论,否则每次都会偶发地报成「拿不到退出码」。
*/
async function readExitCode(exitPath: string): Promise<number | null> {
for (let i = 0; i < 10; i++) {
const rc = readExitCodeOnce(exitPath);
if (rc != null) return rc;
await new Promise((r) => setTimeout(r, 200));
}
return null;
}
function defaultLogPath(label: string | null): string {
const slug = (label ?? "run").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "run";
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
return path.join(process.env.TMPDIR || "/tmp", "wait-for", `${stamp}-${slug}.log`);
}
/** Single-quote for /bin/sh. */
function shq(s: string): string {
return `'${s.replaceAll("'", `'\\''`)}'`;
}
/**
* `--settle`:和其余模式不同,它等的是「界面不再变化」,时间尺度是秒,不是分钟。
* 逻辑在 bin/settle.ts;这里只管参数、输出和退出码(0 稳定 · 124 一直在变 · 3 指纹取不到)。
*/
async function runSettle(args: Args): Promise<never> {
const quietMs = Math.max(200, parseDuration(val(args, "quiet"), 1200, "--quiet"));
const timeoutMs = Math.min(parseDuration(val(args, "timeout"), 8000, "--timeout"), 60_000);
const r = await settleLoop({ probe: pickProbe(val(args, "probe")), quietMs, timeoutMs });
const secs = (r.elapsedMs / 1000).toFixed(1);
if (r.error) die(3, `⚠️ ${r.error}。设备掉线或这台节点没配界面指纹探针;这次就看一眼屏幕继续。`);
if (r.settled) {
process.stdout.write(`✓ 界面已稳定(${secs}s,取样 ${r.samples} 次)\n`);
process.exit(0);
}
process.stdout.write(`… ${secs}s 内画面一直在变(在播视频或动画?)—— 不是报错,看一眼屏幕继续\n`);
process.exit(124);
}
/** 结构树探针:显式 --probe 优先;否则按平台(AGENT_PLATFORM,缺省看有没有正在跑的 cat-supervisor 实例)。 */
function uiTreeProbe(probeCmd: string | null): () => Promise<string | null> {
const run = (cmd: string) => new Promise<string | null>((resolve) => {
const p = spawn("/bin/sh", ["-c", cmd], { stdio: ["ignore", "pipe", "ignore"] });
let out = "";
const t = setTimeout(() => { try { p.kill("SIGKILL"); } catch { /* gone */ } }, 15_000);
p.stdout.on("data", (b) => { out += b; });
p.on("close", () => { clearTimeout(t); resolve(out.trim() ? out : null); });
p.on("error", () => { clearTimeout(t); resolve(null); });
});
if (probeCmd) return () => run(probeCmd);
let cmd: string | null = null;
return async () => {
if (!cmd) {
const plat = (process.env.AGENT_PLATFORM || "").toLowerCase();
const list = plat === "android" ? null : await run("cat-supervisor list 2>/dev/null");
let inst: string | null = null;
try {
const d = JSON.parse(list || "{}") as { instances?: { id: string; state?: string }[] };
inst = (d.instances ?? []).find((i) => i.state === "running")?.id ?? null;
} catch { /* not ios */ }
cmd = inst
? `catuse ui --instance ${shq(inst)} 2>/dev/null`
: "adb exec-out uiautomator dump /dev/tty 2>/dev/null | sed 's#UI hierchary dumped to: /dev/tty##'";
}
return run(cmd);
};
}
/**
* `--ui-text` / `--ui-gone`:秒级等界面文案出现 / 消失。逻辑在 shared/src/ui_wait.ts。
* 退出码:0 达成 · 124 没等到(打印当前屏幕文案)· 3 结构树一次都没取到 · 2 用法错。
*/
async function runUiWait(args: Args): Promise<never> {
const gone = args["ui-gone"] != null;
const raw = val(args, gone ? "ui-gone" : "ui-text");
if (!raw) die(2, `--${gone ? "ui-gone" : "ui-text"} 需要一个正则(界面上的文案,例 'Inbox|收件箱')`);
let pattern: RegExp;
try { pattern = new RegExp(raw, "i"); } catch { die(2, `正则写错了:「${raw}」`); }
const timeoutMs = Math.min(parseDuration(val(args, "timeout"), 30_000, "--timeout"), 180_000);
const r = await uiWaitLoop({ probe: uiTreeProbe(val(args, "probe")), pattern: pattern!, gone, timeoutMs });
const secs = (r.elapsedMs / 1000).toFixed(1);
if (r.error) die(3, `⚠️ ${r.error}(设备掉线 / 实例没在跑 / 没装 catuse?)—— 截一张图看看现在的状态`);
if (r.ok) {
process.stdout.write(gone ? `✓ 「${raw}」已消失(${secs}s)\n` : `✓ 出现「${r.hit}」(${secs}s)\n`);
process.exit(0);
}
const shown = r.lastTexts.slice(0, 20).map((t) => ` · ${t.length > 60 ? `${t.slice(0, 59)}…` : t}`).join("\n");
process.stdout.write(`… ${secs}s 内${gone ? `「${raw}」一直在` : `没等到「${raw}」`} —— 当前屏幕上的文案:\n${shown || " (结构树里没有文案)"}\n`);
process.exit(124);
}
export async function runWaitFor(argv: string[]): Promise<never> {
if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
process.stdout.write(USAGE);
process.exit(argv.length === 0 ? 2 : 0);
}
const args = parseArgs(argv);
if (args.settle != null) await runSettle(args);
if (args["ui-text"] != null || args["ui-gone"] != null) await runUiWait(args);
const mode = resolveMode(args);
// `--while` and `--pgrep`/`--pid` are "keep waiting while the probe says 0";
// `--until`/`--file` are "stop when the probe says 0".
const doneOnZero = mode.kind === "until" || mode.kind === "file";
const timeoutMs = Math.min(parseDuration(val(args, "timeout"), 30 * 60_000, "--timeout"), HARD_CAP_MS);
const intervalMs = Math.max(1000, parseDuration(val(args, "interval"), 15_000, "--interval"));
const probeTimeoutMs = Math.max(1000, parseDuration(val(args, "probe-timeout"), 60_000, "--probe-timeout"));
const tailPath = val(args, "tail");
/**
* 成功时打 20 行够了;**失败和超时时不够**。
*
* 上线首日(2026-09-15,19 个执行轮)量到:有 25 次调用是在 wait-for 之后**再去读
* 它自己那份日志** —— `tail -c 4000 "$L"`、`grep -i "no space|Internal compiler
* error|What went wrong"`、`sed -n '30,90p'`。也就是说「省掉紧随其后那次 tail」
* 这个卖点,在最需要它的那一刻(构建挂了)没兑现:20 行里通常只有收尾噪音,
* 真正的报错在更上面。
*
* 所以失败路径默认多打。用户显式传了 --tail-lines 就一律听他的 —— 这里区分
* 「没传」和「传了 20」,所以不能用 ?? 兜默认值。
*/
const tailExplicit = val(args, "tail-lines");
const tailLines = Math.max(1, Number(tailExplicit ?? 20) || 20);
const failLines = tailExplicit != null ? tailLines : FAIL_TAIL_LINES;
const label = val(args, "label");
const quiet = args.quiet === true;
const tag = label ? `[${label}] ` : "";
const started = Date.now();
const deadline = started + timeoutMs;
// --run:先把命令起起来,再退化成「等这个 pid 消失」。日志路径同时成为 --tail 的
// 默认值 —— 跑完第一件想看的事就是日志尾巴,不该让它再发一次调用。
let runPid: number | null = null;
let runLog: string | null = null;
let runExit: string | null = null;
let probe = mode.probe;
let doneWhenZero = doneOnZero;
if (mode.kind === "run") {
runLog = val(args, "log") ?? defaultLogPath(label);
const startedCmd = startCommand(mode.probe, runLog);
runPid = startedCmd.pid;
runExit = startedCmd.exitPath;
probe = `kill -0 ${runPid} 2>/dev/null`;
doneWhenZero = false; // pid 还在 = kill -0 返回 0 = 还没跑完
process.stdout.write(`▶️ ${tag}已起:${short(mode.probe)}\n pid ${runPid} · 日志 ${runLog}\n`);
}
const finalTail = tailPath ?? runLog;
process.stdout.write(`⏳ ${tag}开始等待:${mode.desc}(上限 ${fmt(timeoutMs)})\n`);
// 只对「轮询一个条件」的两种模式提示:--run 跑一条 adb/catuse 命令是正常用法。
const deviceProbe = (mode.kind === "until" || mode.kind === "while") && DEVICE_PROBE.test(mode.probe);
if (deviceProbe) process.stdout.write(DEVICE_HINT);
let probeErrors = 0;
let lastHeartbeat = started;
// Heartbeat spacing widens with the wait so a 45-minute build does not produce
// 180 identical lines, while a 30-second wait still says something.
const heartbeatGap = (elapsed: number) => (elapsed < 120_000 ? 30_000 : elapsed < 900_000 ? 120_000 : 300_000);
for (;;) {
const elapsed = Date.now() - started;
const code = await runProbe(probe, probeTimeoutMs);
if (code === null) {
probeErrors++;
// A probe that cannot run at all is a setup mistake, not a slow build —
// say so early instead of burning the whole timeout on it.
if (probeErrors >= 3 && elapsed < 60_000) {
process.stdout.write(`❌ ${tag}probe 连续 ${probeErrors} 次无法执行或超时(${fmt(probeTimeoutMs)}):${probe}\n`);
if (finalTail) process.stdout.write(`--- ${finalTail} 末 ${failLines} 行 ---\n${tailFile(finalTail, failLines)}\n`);
process.exit(3);
}
} else if ((code === 0) === doneWhenZero) {
const took = Date.now() - started;
if (mode.kind === "run") {
// 真实退出码来自 startCommand 落的旁文件。读不到就说读不到 —— 不猜。
const rc = runExit ? await readExitCode(runExit) : null;
const ok = rc === 0;
process.stdout.write(
`${ok ? "✅" : rc == null ? "⚠️" : "❌"} ${tag}命令已结束,用时 ${fmt(took)}` +
(rc == null ? "(拿不到退出码,进程可能被外部杀掉了)" : `,退出码 ${rc}`) + `\n`,
);
const n = ok ? tailLines : failLines;
if (finalTail) process.stdout.write(`--- ${finalTail} 末 ${n} 行 ---\n${tailFile(finalTail, n)}\n`);
if (!ok && finalTail) process.stdout.write(` 完整日志(要翻更多就直接读它,别再 tail 一次):${finalTail}\n`);
process.exit(ok ? 0 : 1);
}
process.stdout.write(`✅ ${tag}条件达成,用时 ${fmt(took)}(probe 退出码 ${code})\n`);
if (finalTail) process.stdout.write(`--- ${finalTail} 末 ${tailLines} 行 ---\n${tailFile(finalTail, tailLines)}\n`);
process.exit(0);
}
const now = Date.now();
if (now >= deadline) {
if (mode.kind === "run") {
// 关键:**不杀它**。命令是 detached 起的,wait-for 退出不影响它。
// 等了 40 分钟的构建不该因为 --timeout 设小了就白等。
process.stdout.write(
`⌛ ${tag}等到上限 ${fmt(timeoutMs)},命令还在跑(pid ${runPid})—— 没有杀它。\n` +
` 续等:wait-for --pid ${runPid} --tail ${finalTail} --timeout 30m\n` +
` 放弃:kill ${runPid}\n`,
);
if (finalTail) process.stdout.write(`--- ${finalTail} 末 ${failLines} 行 ---\n${tailFile(finalTail, failLines)}\n`);
process.exit(124);
}
process.stdout.write(
`⌛ ${tag}等到上限 ${fmt(timeoutMs)} 仍未达成(${mode.desc})。\n` +
(deviceProbe
? " 这是个**设备 UI 状态**的等待 —— 再等下去多半也不会变。不要调大 --timeout 重来,\n" +
" 先 `catuse ui` 或截图看一眼现在到底在哪一页,再决定下一步。\n"
: " 这不代表失败 —— 可能只是比预期慢。要继续等就再发一次同样的命令并调大 --timeout;\n" +
" 要放弃就把「等了 " + fmt(timeoutMs) + " 未完成」如实写进报告,不要改成「环境阻塞」。\n"),
);
if (finalTail) process.stdout.write(`--- ${finalTail} 末 ${failLines} 行 ---\n${tailFile(finalTail, failLines)}\n`);
process.exit(124);
}
if (!quiet && now - lastHeartbeat >= heartbeatGap(now - started)) {
lastHeartbeat = now;
const note = probeErrors ? ` · probe 失败 ${probeErrors} 次` : "";
process.stdout.write(` ⏳ ${tag}已等 ${fmt(now - started)} / ${fmt(timeoutMs)}${note}\n`);
}
// 头一分钟快探,之后回到稳态间隔。本地 probe(kill -0 / pgrep)几乎不花钱,
// 可以 1s;--until 这类 probe 往往是一次 SSH 往返,1s 会把对端打爆,用 3s。
const localProbe = mode.kind === "run" || mode.kind === "pid" || mode.kind === "pgrep";
const gap = (now - started) < 60_000 ? (localProbe ? 1_000 : 3_000) : intervalMs;
await new Promise((r) => setTimeout(r, Math.min(gap, Math.max(0, deadline - Date.now()) || gap)));
}
}
if (import.meta.main) await runWaitFor(process.argv.slice(2));