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
+117
View File
@@ -0,0 +1,117 @@
/**
* audit-report —— 对 UI 走查报告(evidence/UI-Audit-Report.md)做小块修改,一次改一处。
*
* 为什么:agent 以前每改一次报告都把整份 Markdown 读出来、拼字符串、整段写回(00889383 写了 122 次,
* 其前的思考共 34 分钟),越往后报告越长、每次改写越贵,还常把表格改坏。格式由
* shared/src/audit_report_edit.ts 保证,和平台的解析器是同一份契约。
*
* 报告路径:--report <path>,缺省 $STREAMLINE_WORKSPACE_DIR/evidence/UI-Audit-Report.md。
* 作为卫星 bundle 的 `audit-report` 子命令运行(satellite/src/entry.ts),也可 `bun bin/audit-report.ts`。
*/
import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
import path from "node:path";
import {
addIssue, addPage, doneScene, initReport, recountSummary, setConstructed, setCoverage, setRecipe, setRoute, setScene,
type CovMark,
} from "../shared/src/audit_report_edit";
const USAGE = `audit-report —— 小块修改 UI 走查报告(一次改一处,格式由平台保证)
init --title '<标题>' [--langs en,de] [--meta '截图所用包=…' --meta '设备=…'] 新建报告(已存在则拒绝)
page --page <id> --title '<中文页面名>' --surface '面 3 · 设置' 加一页(第 4 节标题)
issue --page <id> --sev P2 --cat 热区 --langs 'en de' --text '<一句话现象>'
[--repro '<复现条件>'] [--cause '<原因>'] [--detail '<取证>'] [--code '<文件:行>']
[--title …] [--surface …] 加一条问题,覆盖格自动设 ⚠,打印编号
cov --page <id> --lang en --mark ok|issue|missing 设覆盖矩阵一格(页面行 / 语言列不存在会补)
scene --scope '<场景>' --status '待走|BLOCKED(环境)|部分覆盖|…' --why '<已做到哪一步>' 第 3 节加 / 改一行
done --scope '<场景>' 场景走完:从第 3 节删掉
construct --page <id> --how '<怎么造的>' [--script hooks/x.js] 第 5 节登记构造态
route --page <id> --title '<中文名>' --how '<怎么进>' 第 6 节路由
recipe --scene '<场景>' --how '<管用的做法>' 第 6 节做法
summary 按第 4 节重算第 1 节两张汇总表
通用:--report <path>(缺省 $STREAMLINE_WORKSPACE_DIR/evidence/UI-Audit-Report.md)
同一个键(页面 id / 场景名)再写一次是覆盖,不会重复加行。`;
function parseArgs(argv: string[]): { op: string; flags: Record<string, string>; multi: Record<string, string[]> } {
const flags: Record<string, string> = {};
const multi: Record<string, string[]> = {};
let op = "";
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) { if (!op) op = a; continue; }
const k = a.slice(2);
const v = argv[i + 1] != null && !argv[i + 1].startsWith("--") ? argv[++i] : "true";
flags[k] = v;
(multi[k] ??= []).push(v);
}
return { op, flags, multi };
}
function die(code: number, msg: string): never {
process.stderr.write(msg.endsWith("\n") ? msg : msg + "\n");
process.exit(code);
}
function need(f: Record<string, string>, ...keys: string[]): void {
const miss = keys.filter((k) => !f[k] || f[k] === "true");
if (miss.length) die(2, `缺少 ${miss.map((k) => `--${k}`).join(" ")}\n\n${USAGE}`);
}
export async function runAuditReport(argv: string[]): Promise<never> {
const { op, flags: f, multi } = parseArgs(argv);
if (!op || op === "help" || f.help) { process.stdout.write(USAGE + "\n"); process.exit(op ? 0 : 2); }
const ws = process.env.STREAMLINE_WORKSPACE_DIR;
const file = f.report ?? (ws ? path.join(ws, "evidence", "UI-Audit-Report.md") : "");
if (!file) die(2, "不知道报告在哪:传 --report <path>(或在任务环境里运行,会自动用工作区的 evidence/UI-Audit-Report.md)");
if (op === "init") {
need(f, "title");
if (existsSync(file)) die(2, `${file} 已存在 —— 不覆盖。要改用其它子命令。`);
const meta = (multi.meta ?? []).map((kv) => { const i = kv.indexOf("="); return [kv.slice(0, i), kv.slice(i + 1)] as [string, string]; });
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, initReport({ title: f.title, langs: f.langs?.split(/[,\s]+/).filter(Boolean), meta }));
process.stdout.write(`✓ 已新建 ${file}\n`);
process.exit(0);
}
if (!existsSync(file)) die(2, `${file} 不存在 —— 先 \`audit-report init --title …\``);
let md = readFileSync(file, "utf8");
let msg = "";
switch (op) {
case "page": need(f, "page"); md = addPage(md, f.page, { title: f.title, surface: f.surface }); msg = `页面 ${f.page}`; break;
case "issue": {
need(f, "page", "sev", "cat", "langs", "text");
const r = addIssue(md, {
page: f.page, sev: f.sev, cat: f.cat, langs: f.langs.split(/[,\s]+/).filter(Boolean), text: f.text,
repro: f.repro, cause: f.cause, detail: f.detail, code: f.code, title: f.title, surface: f.surface,
});
md = r.md; msg = `${f.page} #${r.n}`; break;
}
case "cov": {
need(f, "page", "lang", "mark");
if (!["ok", "issue", "missing"].includes(f.mark)) die(2, "--mark 只能是 ok / issue / missing");
md = setCoverage(md, f.page, f.lang, f.mark as CovMark); msg = `${f.page} @ ${f.lang} = ${f.mark}`; break;
}
case "scene": need(f, "scope", "status", "why"); md = setScene(md, f.scope, f.status, f.why); msg = `第 3 节「${f.scope}」`; break;
case "done": {
need(f, "scope");
const r = doneScene(md, f.scope);
if (!r.removed) die(1, `第 3 节里没有「${f.scope}」(按第一列精确匹配)`);
md = r.md; msg = `第 3 节删掉「${f.scope}」`; break;
}
case "construct": need(f, "page", "how"); md = setConstructed(md, f.page, f.how, f.script ?? "—"); msg = `第 5 节 ${f.page}`; break;
case "route": need(f, "page", "title", "how"); md = setRoute(md, f.page, f.title, f.how); msg = `第 6 节路由 ${f.page}`; break;
case "recipe": need(f, "scene", "how"); md = setRecipe(md, f.scene, f.how); msg = `第 6 节做法「${f.scene}」`; break;
case "summary": md = recountSummary(md); msg = "第 1 节已按第 4 节重算"; break;
default: die(2, `不认识的子命令 ${op}\n\n${USAGE}`);
}
// 先写临时文件再改名:写到一半被打断(会话被截断 / 交棒)也不会留下半份报告。
const tmp = `${file}.tmp-${process.pid}`;
writeFileSync(tmp, md);
renameSync(tmp, file);
process.stdout.write(`✓ ${msg}\n`);
process.exit(0);
}
if (import.meta.main) await runAuditReport(process.argv.slice(2));
+400
View File
@@ -0,0 +1,400 @@
#!/usr/bin/env bun
/**
* claude-codex — compatibility adapter for Codex CLI's non-interactive mode.
*
* Satellite callers already speak one internal CLI shape and consume Claude
* `stream-json` records. This wrapper accepts that shape, invokes
* `codex exec --json`, and emits the normalised records downstream already
* understands. It deliberately preserves one important runner invariant: a
* clean Codex exit without a required STATUS/ASSESSMENT is a format failure,
* not an infrastructure retry.
*/
import { spawn, type Subprocess } from "bun";
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import {
AGENT_SESSION_FILE_ENV,
mappedAgentSessionIdFromEnv,
recordAgentSessionIdFromEnv,
} from "../shared/src/agent_session";
type ParsedArgs = {
prompt: string;
addDirs: string[];
sessionUuid: string | null;
resumeUuid: string | null;
appendSys: string | null;
model: string | null;
readOnly: boolean;
};
type Usage = {
input_tokens: number;
output_tokens: number;
cache_read_input_tokens: number;
cache_creation_input_tokens: number;
thinking_tokens: number;
};
const CODEX_BIN = process.env.CODEX_BIN || "codex";
function configuredCodexModel(): string {
const explicit = process.env.STREAMLINE_CODEX_MODEL?.trim();
if (explicit) return explicit;
const codexHome = process.env.CODEX_HOME?.trim() || path.join(homedir(), ".codex");
try {
const config = readFileSync(path.join(codexHome, "config.toml"), "utf8");
const match = config.match(/^\s*model\s*=\s*["']([^"']+)["']/m);
return match?.[1]?.trim() || "";
} catch {
return "";
}
}
const CODEX_MODEL = configuredCodexModel();
const BRIDGE_DIR = process.env.CODEX_BRIDGE_DIR || path.join(homedir(), ".codex-agent-bridge");
const DEBUG = process.env.CLAUDE_CODEX_DEBUG === "1";
function dbg(message: string): void {
if (DEBUG) process.stderr.write(`[claude-codex] ${message}\n`);
}
function parseArgs(argv: string[]): ParsedArgs {
const addDirs: string[] = [];
let prompt: string | null = null;
let sessionUuid: string | null = null;
let resumeUuid: string | null = null;
let appendSys: string | null = null;
let model: string | null = null;
let readOnly = false;
const DROP_WITH_VALUE = new Set([
"--output-format", "--input-format", "--fallback-model", "--max-budget-usd", "--json-schema", "--settings",
]);
const DROP_BARE = new Set([
"--verbose", "--print", "--include-partial-messages", "--replay-user-messages", "--no-session-persistence",
"--dangerously-skip-permissions",
]);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]!;
if (arg === "-p" || arg === "--print") {
const next = argv[i + 1];
if (next !== undefined && !next.startsWith("-")) { prompt = next; i++; }
continue;
}
if (arg === "--add-dir") { const dir = argv[++i]; if (dir) addDirs.push(dir); continue; }
if (arg === "--session-id") { sessionUuid = argv[++i] ?? null; continue; }
if (arg === "--resume") { resumeUuid = argv[++i] ?? null; continue; }
if (arg === "--append-system-prompt") { appendSys = argv[++i] ?? null; continue; }
if (arg === "--model") { model = argv[++i] ?? null; continue; }
if (arg === "--remote-control") { i++; continue; }
if (arg === "--streamline-read-only") { readOnly = true; continue; }
if (DROP_BARE.has(arg)) continue;
if (DROP_WITH_VALUE.has(arg)) { i++; continue; }
if (DROP_WITH_VALUE.has(arg.split("=")[0]!)) continue;
if (!arg.startsWith("-") && prompt === null) { prompt = arg; continue; }
dbg(`dropping unrecognised internal arg: ${arg}`);
}
if (prompt === null) throw new Error("claude-codex: no prompt found in args");
return { prompt, addDirs, sessionUuid, resumeUuid, appendSys, model, readOnly };
}
function bridgePath(uuid: string): string {
return path.join(BRIDGE_DIR, `${uuid}.thread`);
}
function readThreadId(uuid: string): string | null {
const managed = mappedAgentSessionIdFromEnv("codex", uuid);
if (managed) return managed;
try {
const value = readFileSync(bridgePath(uuid), "utf8").trim();
return value || null;
} catch { return null; }
}
function writeThreadId(uuid: string, threadId: string): void {
recordAgentSessionIdFromEnv("codex", threadId);
try {
mkdirSync(BRIDGE_DIR, { recursive: true });
writeFileSync(bridgePath(uuid), threadId, "utf8");
} catch (err) {
dbg(`could not persist Codex thread mapping: ${(err as Error).message}`);
}
}
function normaliseSandbox(value: string | undefined, readOnly: boolean): "read-only" | "workspace-write" | "danger-full-access" {
if (readOnly) return "read-only";
if (value === "read-only" || value === "workspace-write" || value === "danger-full-access") return value;
if (value) dbg(`invalid STREAMLINE_CODEX_SANDBOX=${value}; using workspace-write`);
return "workspace-write";
}
function clip(value: string, max = 8_000): string {
return value.length <= max ? value : `${value.slice(0, max)}\n…(truncated)`;
}
function stringValue(value: unknown): string {
if (typeof value === "string") return value;
if (value === null || value === undefined) return "";
try { return JSON.stringify(value); } catch { return String(value); }
}
function toolName(type: string): string {
const names: Record<string, string> = {
command_execution: "Bash",
file_change: "Edit",
mcp_tool_call: "MCP",
web_search: "WebSearch",
error: "CodexError",
};
return names[type] || (type ? type[0]!.toUpperCase() + type.slice(1) : "tool");
}
function mapUsage(raw: unknown): Usage {
const usage = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
const num = (key: string) => typeof usage[key] === "number" ? usage[key] as number : 0;
const tokenDetail = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? value : 0;
const outputDetails = usage.output_tokens_details && typeof usage.output_tokens_details === "object"
? usage.output_tokens_details as Record<string, unknown>
: {};
return {
input_tokens: num("input_tokens"),
output_tokens: num("output_tokens"),
cache_read_input_tokens: num("cached_input_tokens"),
cache_creation_input_tokens: num("cache_write_input_tokens"),
thinking_tokens: tokenDetail(
usage.thinking_tokens
?? outputDetails.thinking_tokens
?? usage.reasoning_output_tokens
?? usage.reasoning_tokens
?? outputDetails.reasoning_tokens,
),
};
}
const AUTOMODE_SYSPROMPT = [
"本会话运行在无人值守的自动化流水线中,没有任何人类在观看或会作出回应。",
"绝对禁止等待用户回复;遇到需要选择的情况,直接采用你推荐的可行方案并继续执行。",
"自主推进任务至完成,并按提示词要求写出全部报告、证据和终端状态。",
].join("\n");
export async function runClaudeCodex(argv: string[]): Promise<void> {
let parsed: ParsedArgs;
try {
parsed = parseArgs(argv);
} catch (err) {
process.stderr.write(`${(err as Error).message}\n`);
process.exit(2);
}
const isManagedRun = Boolean(process.env[AGENT_SESSION_FILE_ENV]?.trim());
const isAsking = !isManagedRun && !!(parsed.sessionUuid || parsed.resumeUuid);
const wrapperSessionId = parsed.resumeUuid || parsed.sessionUuid || randomUUID();
const bridgeKey = parsed.resumeUuid || parsed.sessionUuid;
const resumeThreadId = parsed.resumeUuid ? readThreadId(parsed.resumeUuid) : null;
const finalMessagePath = path.join(tmpdir(), `streamline-codex-${randomUUID()}.last-message`);
const sandbox = normaliseSandbox(process.env.STREAMLINE_CODEX_SANDBOX, parsed.readOnly);
const startedAt = Date.now();
let emittedInit = false;
let emittedText = "";
let finalised = false;
let lastError = "";
let turnUsage: Usage = {
input_tokens: 0,
output_tokens: 0,
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
thinking_tokens: 0,
};
let fatalEvent = false;
const pendingTools = new Map<string, string>();
let child: Subprocess<"ignore", "pipe", "pipe"> | null = null;
const emit = (value: Record<string, unknown>) => process.stdout.write(`${JSON.stringify(value)}\n`);
const emitInit = () => {
if (emittedInit) return;
emittedInit = true;
emit({
type: "system", subtype: "init", cwd: process.cwd(), session_id: wrapperSessionId,
tools: [], model: parsed.model || CODEX_MODEL || "", permissionMode: sandbox,
apiKeySource: "none", mcp_servers: [], slash_commands: [], codex_exec: true,
});
};
const emitText = (text: string) => {
if (!text.trim()) return;
emitInit();
emittedText += (emittedText ? "\n" : "") + text;
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "text", text }] },
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
});
};
const emitThinking = (text: string) => {
if (!text.trim()) return;
emitInit();
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "thinking", thinking: text }] },
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
});
};
const startTool = (item: Record<string, unknown>) => {
const type = typeof item.type === "string" ? item.type : "tool";
if (["agent_message", "reasoning"].includes(type)) return;
const id = typeof item.id === "string" ? item.id : randomUUID();
if (pendingTools.has(id)) return;
const input = item.command ?? item.arguments ?? item.input ?? item;
pendingTools.set(id, toolName(type));
emitInit();
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "tool_use", id, name: toolName(type), input }] },
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
});
};
const finishTool = (item: Record<string, unknown>) => {
const type = typeof item.type === "string" ? item.type : "tool";
if (["agent_message", "reasoning"].includes(type)) return;
const id = typeof item.id === "string" ? item.id : randomUUID();
startTool({ ...item, id });
const name = pendingTools.get(id) || toolName(type);
pendingTools.delete(id);
const output = clip(stringValue(item.aggregated_output ?? item.output ?? item.message ?? item.error ?? item));
const exitCode = item.exit_code;
const isError = typeof exitCode === "number" ? exitCode !== 0 : type === "error";
emit({
type: "user",
message: { role: "user", content: [{ type: "tool_result", tool_use_id: id, content: output, is_error: isError }] },
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
});
if (type === "error") lastError = output;
void name;
};
const finalize = (subtype: string, isError: boolean, result: string) => {
if (finalised) return;
finalised = true;
emitInit();
emit({
type: "result", subtype, is_error: isError, result,
session_id: wrapperSessionId, duration_ms: Date.now() - startedAt,
total_cost_usd: 0, usage: turnUsage,
});
};
const promptParts: string[] = [];
if (!isAsking) promptParts.push(AUTOMODE_SYSPROMPT);
if (parsed.appendSys) promptParts.push(parsed.appendSys);
promptParts.push(parsed.prompt);
const prompt = promptParts.join("\n\n");
const model = parsed.model || CODEX_MODEL;
const common = ["--json", "--output-last-message", finalMessagePath, "--skip-git-repo-check"];
if (model) common.push("--model", model);
let codexArgs: string[];
if (resumeThreadId) {
// Current Codex releases persist the initial session's sandbox/add-dir
// policy; `exec resume` intentionally exposes a narrower flag surface.
codexArgs = ["exec", "resume", ...common, resumeThreadId, prompt];
} else {
codexArgs = ["exec", ...common, "--color", "never", "--sandbox", sandbox];
for (const dir of parsed.addDirs) codexArgs.push("--add-dir", dir);
if (!bridgeKey) codexArgs.push("--ephemeral");
codexArgs.push(prompt);
}
const consumeEvent = (event: Record<string, unknown>) => {
const type = typeof event.type === "string" ? event.type : "";
if (type === "thread.started") {
const threadId = typeof event.thread_id === "string" ? event.thread_id : "";
if (threadId && bridgeKey) writeThreadId(bridgeKey, threadId);
emitInit();
return;
}
if (type === "turn.started") { emitInit(); return; }
const item = event.item && typeof event.item === "object" ? event.item as Record<string, unknown> : null;
if (type === "item.started" && item) { startTool(item); return; }
if (type === "item.completed" && item) {
const itemType = typeof item.type === "string" ? item.type : "";
if (itemType === "agent_message") emitText(stringValue(item.text));
else if (itemType === "reasoning") emitThinking(stringValue(item.text ?? item.summary));
// Codex emits non-fatal CLI/config diagnostics as `item.error` too. They
// can precede a perfectly successful turn, so don't render them as a
// failed tool call; retain the text for a genuinely failing terminal run.
else if (itemType === "error") {
lastError = clip(stringValue(item.message ?? item.error ?? item), 2_000);
dbg(`non-terminal Codex diagnostic: ${lastError}`);
}
else finishTool(item);
return;
}
if (type === "turn.completed") { turnUsage = mapUsage(event.usage); return; }
if (type === "turn.failed" || type === "error") {
lastError = stringValue(event.error ?? event.message ?? event);
fatalEvent = true;
return;
}
dbg(`unhandled Codex event: ${type || "unknown"}`);
};
for (const signal of ["SIGINT", "SIGTERM"] as const) {
process.on(signal, () => {
lastError = `Codex wrapper received ${signal}`;
fatalEvent = true;
try { child?.kill(); } catch { /* already exited */ }
finalize("error_during_execution", true, lastError);
process.exit(143);
});
}
try {
dbg(`spawning ${CODEX_BIN} ${codexArgs.slice(0, -1).join(" ")} [prompt ${prompt.length} chars]`);
child = spawn({ cmd: [CODEX_BIN, ...codexArgs], cwd: process.cwd(), stdin: "ignore", stdout: "pipe", stderr: "pipe" });
const stdoutTask = (async () => {
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of child!.stdout) {
buffer += decoder.decode(chunk, { stream: true });
let newline: number;
while ((newline = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, newline).trim();
buffer = buffer.slice(newline + 1);
if (!line || !line.startsWith("{")) continue;
try { consumeEvent(JSON.parse(line) as Record<string, unknown>); }
catch (err) { dbg(`could not decode Codex event: ${(err as Error).message}`); }
}
}
const line = buffer.trim();
if (line.startsWith("{")) {
try { consumeEvent(JSON.parse(line) as Record<string, unknown>); }
catch (err) { dbg(`could not decode trailing Codex event: ${(err as Error).message}`); }
}
})();
const stderrTask = (async () => {
const decoder = new TextDecoder();
let stderr = "";
for await (const chunk of child!.stderr) stderr += decoder.decode(chunk, { stream: true });
if (stderr.trim()) dbg(`codex stderr: ${clip(stderr.trim(), 1_000)}`);
return stderr;
})();
const exitCode = await child.exited;
const [, stderr] = await Promise.all([stdoutTask, stderrTask]);
let finalMessage = "";
try { finalMessage = readFileSync(finalMessagePath, "utf8").trim(); } catch { /* no final message */ }
if (finalMessage && !emittedText.includes(finalMessage)) emitText(finalMessage);
if (exitCode !== 0 && !lastError) lastError = clip(stderr.trim() || `codex exited ${exitCode}`, 2_000);
const failed = exitCode !== 0 || fatalEvent;
finalize(failed ? "error_during_execution" : "success", failed, finalMessage || lastError || emittedText || "");
process.exit(failed ? (exitCode || 1) : 0);
} catch (err) {
lastError = (err as Error).message;
fatalEvent = true;
finalize("error_during_execution", true, lastError);
process.exit(1);
} finally {
try { unlinkSync(finalMessagePath); } catch { /* best effort */ }
}
}
if (import.meta.main) await runClaudeCodex(process.argv.slice(2));
+684
View File
@@ -0,0 +1,684 @@
#!/usr/bin/env bun
/**
* claude-cursor — drop-in replacement for
* `claude -p <prompt> --output-format stream-json --verbose \
* --dangerously-skip-permissions [--add-dir X] [--session-id|--resume U]`
* that runs Cursor's `cursor-agent` instead of Claude Code, while emitting the
* SAME Claude stream-json line shape on stdout. Every downstream consumer in the
* satellite (session.log tailer, the STATUS/ASSESSMENT sentinel parser in the
* runners/evaluators, the client-side LogPanel, asking's event normaliser) reads
* that shape, so swapping the engine here keeps log-return and per-task
* association fully compatible.
*
* Why a translator is needed: cursor-agent's `--output-format stream-json` is
* close to Claude's but not identical. Notably it emits tool calls and thinking
* as their OWN top-level frames:
* {"type":"tool_call","subtype":"started","call_id","tool_call":{…}}
* {"type":"tool_call","subtype":"completed","call_id","tool_call":{…}}
* {"type":"thinking","subtype":"delta"|"completed","text"}
* whereas Claude (and thus our consumers) expect those FOLDED INTO message
* content: a `tool_use` block inside an `assistant` frame, a `tool_result` block
* inside a `user` frame, and a `thinking` block inside an `assistant` frame.
* This wrapper performs that folding. Text + result frames are already
* Claude-shaped and pass through (with session_id normalised).
*
* Arg mapping (claude → cursor):
* -p <prompt> positional prompt (cursor's -p is a bare
* --print boolean, so the prompt moves to a
* positional and --print is added)
* --output-format stream-json --output-format stream-json (kept)
* --verbose / --remote-control X dropped (no cursor equivalent)
* --dangerously-skip-permissions --force --trust --approve-mcps
* --add-dir X --add-dir X (same flag)
* --session-id U (first turn) create-chat → chatId, persist U→chatId,
* run --resume chatId
* --resume U (later turns) look up U→chatId, run --resume chatId
*
* The U→chatId map is a per-uuid sidecar file so the resumable asking session
* survives across the fresh process each turn spawns.
*
* Env knobs:
* CURSOR_BIN cursor-agent binary (default "cursor-agent")
* STREAMLINE_CURSOR_MODEL --model to pass (e.g. "claude-opus-4-8[context=1m]")
* CURSOR_BRIDGE_DIR where U→chatId sidecars live
* (default ~/.cursor-agent-bridge)
* CLAUDE_CURSOR_DEBUG=1 mirror raw cursor-agent stdout/stderr to stderr
*/
import { spawn, spawnSync, type Subprocess } from "bun";
import {
existsSync, mkdirSync, readFileSync, writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { CursorCliDiagnosticBuffer, redactCursorCliDiagnostic } from "../satellite/src/security_telemetry/cursor_cli_diagnostics";
import { isCursorApiKeyMode } from "../satellite/src/security_telemetry/agent_account_gate";
import {
AGENT_SESSION_FILE_ENV,
AGENT_SESSION_KIND_ENV,
mappedAgentSessionIdFromEnv,
recordAgentSessionIdFromEnv,
} from "../shared/src/agent_session";
const CURSOR_BIN = process.env.CURSOR_BIN || "cursor-agent";
const CURSOR_MODEL = process.env.STREAMLINE_CURSOR_MODEL || "";
const BRIDGE_DIR = process.env.CURSOR_BRIDGE_DIR || path.join(homedir(), ".cursor-agent-bridge");
const DEBUG = process.env.CLAUDE_CURSOR_DEBUG === "1";
function dbg(msg: string) {
if (DEBUG) console.error(`[claude-cursor] ${msg}`);
}
// Same automation instruction the PTY wrapper injects, but prepended to the
// prompt (cursor-agent has no --append-system-prompt). Only used for headless
// runs; the human-in-the-loop asking session must NOT be told "nobody is
// watching", so we skip it there (see `isAsking`).
const AUTOMODE_SYSPROMPT = [
"本会话运行在无人值守的自动化流水线中,没有任何人类在观看或会作出回应。",
"绝对禁止以提问等待用户回复的方式中断任务;",
"如必须在多个方案中取舍,直接采用你推荐的(或第一个可行的)方案并继续执行,事后在输出中说明即可。",
"任务必须自主推进到完成。",
].join("");
// ── arg parsing ────────────────────────────────────────────────────────────
interface ParsedArgs {
prompt: string;
addDirs: string[];
sessionUuid: string | null; // --session-id (first turn of a resumable session)
resumeUuid: string | null; // --resume (later turns)
appendSys: string | null; // --append-system-prompt (folded into prompt)
model: string | null; // --model override from caller
}
function parseArgs(argv: string[]): ParsedArgs {
const addDirs: string[] = [];
let prompt: string | null = null;
let sessionUuid: string | null = null;
let resumeUuid: string | null = null;
let appendSys: string | null = null;
let model: string | null = null;
// claude flags whose VALUE we must consume but otherwise ignore for cursor.
const DROP_WITH_VALUE = new Set([
"--output-format", "--input-format", "--fallback-model",
"--max-budget-usd", "--json-schema", "--settings",
]);
const DROP_BARE = new Set([
"--verbose", "--print", "--include-partial-messages",
"--replay-user-messages", "--no-session-persistence",
"--dangerously-skip-permissions",
]);
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "-p" || a === "--print") {
const next = argv[i + 1];
if (next !== undefined && !next.startsWith("-")) { prompt = next; i++; }
continue;
}
if (a === "--add-dir") { const v = argv[++i]; if (v) addDirs.push(v); continue; }
if (a === "--session-id") { sessionUuid = argv[++i] ?? null; continue; }
if (a === "--resume") { resumeUuid = argv[++i] ?? null; continue; }
if (a === "--append-system-prompt") { appendSys = argv[++i] ?? null; continue; }
if (a === "--model") { model = argv[++i] ?? null; continue; }
if (a === "--remote-control") { i++; continue; }
if (DROP_BARE.has(a)) continue;
if (DROP_WITH_VALUE.has(a)) { i++; continue; }
if (DROP_WITH_VALUE.has(a.split("=")[0])) continue;
if (!a.startsWith("-") && prompt === null) { prompt = a; continue; }
// Anything else is an unknown flag: drop it rather than forward — cursor's
// commander aborts hard on unrecognised options.
dbg(`dropping unrecognised arg: ${a}`);
}
if (prompt === null) {
console.error("claude-cursor: no prompt found in args");
process.exit(2);
}
return { prompt, addDirs, sessionUuid, resumeUuid, appendSys, model };
}
// ── U→chatId session bridge ─────────────────────────────────────────────────
function sidecarPath(uuid: string): string {
return path.join(BRIDGE_DIR, `${uuid}.chat`);
}
function readChatId(uuid: string): string | null {
const managed = mappedAgentSessionIdFromEnv("cursor", uuid);
if (managed) return managed;
try {
const p = sidecarPath(uuid);
if (existsSync(p)) { const s = readFileSync(p, "utf8").trim(); if (s) return s; }
} catch { /* fall through */ }
return null;
}
function writeChatId(uuid: string, chatId: string): void {
recordAgentSessionIdFromEnv("cursor", chatId);
try {
mkdirSync(BRIDGE_DIR, { recursive: true });
writeFileSync(sidecarPath(uuid), chatId, "utf8");
} catch (e) { dbg(`could not persist chat id: ${(e as Error).message}`); }
}
/** `cursor-agent create-chat` prints a new empty chat's id. Parse it out. */
function createChat(): string | null {
try {
const p = spawnSync({ cmd: [CURSOR_BIN, "create-chat"], stdout: "pipe", stderr: "pipe" });
const out = (p.stdout?.toString() || "").trim();
if (!out) { dbg(`create-chat produced no output (stderr: ${p.stderr?.toString().trim()})`); return null; }
// Prefer a JSON payload if cursor ever wraps it; else take the last id-ish token.
try {
const j = JSON.parse(out) as Record<string, unknown>;
const id = (j.chatId || j.id || j.chat_id) as string | undefined;
if (id) return id;
} catch { /* not json */ }
const tokens = out.split(/\s+/).filter((t) => /^[\w-]{6,}$/.test(t));
return tokens.length ? tokens[tokens.length - 1] : out;
} catch (e) {
dbg(`create-chat failed: ${(e as Error).message}`);
return null;
}
}
/** Security must not wait indefinitely for a CLI that has already printed its ID. */
async function createSecurityChat(): Promise<string> {
const proc = spawn({ cmd: [CURSOR_BIN, "create-chat"], stdin: "ignore", stdout: "pipe", stderr: "pipe" });
const diagnostics = new CursorCliDiagnosticBuffer();
const stderrDone = (async () => {
const decoder = new TextDecoder();
for await (const chunk of proc.stderr) diagnostics.append(decoder.decode(chunk, { stream: true }));
diagnostics.append(decoder.decode());
})().catch(() => {});
let timedOut = false;
let timer: ReturnType<typeof setTimeout>;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
timedOut = true;
try { proc.kill(); } catch { /* already exited */ }
reject(new Error("Cursor create-chat did not return a session ID within 30s"));
}, 30_000);
});
const reader = proc.stdout.getReader();
let id: string | null = null;
let output = "";
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const parseId = (line: string): string | null => {
const text = line.trim();
if (uuid.test(text)) return text;
try {
const value = JSON.parse(text) as Record<string, unknown>;
const candidate = value.chatId ?? value.id ?? value.chat_id;
return typeof candidate === "string" && uuid.test(candidate) ? candidate : null;
} catch { return null; }
};
try {
const decoder = new TextDecoder();
while (!id) {
const { value, done } = await Promise.race([reader.read(), deadline]);
output += decoder.decode(value, { stream: !done });
if (output.length > 16_384) throw new Error("Cursor create-chat output exceeded the expected size");
let end: number;
while ((end = output.indexOf("\n")) >= 0) {
id = parseId(output.slice(0, end));
output = output.slice(end + 1);
if (id) break;
}
if (done) { id ||= parseId(output); break; }
}
if (id) {
// The CLI writes the ID before its cleanup. Give cleanup a moment, but
// don't let a retained Node handle block this task for an hour.
const code = await Promise.race([proc.exited, Bun.sleep(1_000).then(() => null)]);
if (code !== null && code !== 0) {
await Promise.race([stderrDone, Bun.sleep(1_000)]);
throw new Error(diagnostics.text() || `Cursor create-chat exited with code ${code}`);
}
if (code === null) { try { proc.kill(); } catch { /* already exited */ } }
}
const exitCode = await Promise.race([proc.exited, Bun.sleep(1_000).then(() => null)]);
if (exitCode === null) { try { proc.kill("SIGKILL"); } catch { /* already exited */ } await proc.exited; }
await Promise.race([stderrDone, Bun.sleep(1_000)]);
if (!id) throw new Error(diagnostics.text() || (timedOut
? "Cursor create-chat did not return a session ID within 30s"
: `Cursor create-chat did not return a valid session ID (exit ${exitCode ?? "unknown"})`));
return id;
} finally {
clearTimeout(timer!);
try { reader.releaseLock(); } catch { /* a timed-out read may still be pending */ }
if (proc.exitCode === null && proc.signalCode === null) {
try { proc.kill("SIGKILL"); } catch { /* already exited */ }
}
}
}
/** Resolve the cursor chat id to --resume for this run, honouring the asking
* session's own uuid. Returns null for a plain headless one-shot (fresh chat). */
async function resolveChatId(a: ParsedArgs): Promise<string | null> {
const create = () => isSecurityTask ? createSecurityChat() : Promise.resolve(createChat());
if (a.resumeUuid) {
const existing = readChatId(a.resumeUuid);
if (existing) return existing;
// Asked to resume a session we have no mapping for (e.g. bridge dir wiped):
// start a fresh chat and remember it so subsequent turns stay coherent.
dbg(`no chat id mapped for resume uuid ${a.resumeUuid}; creating a fresh chat`);
const created = await create();
if (created) writeChatId(a.resumeUuid, created);
return created;
}
if (a.sessionUuid) {
const created = await create();
if (created) writeChatId(a.sessionUuid, created);
return created;
}
// Headless runner calls have no stable outer uuid, but we still want an
// actual chat id so an idle-timeout restart can `--resume` the same session.
return create();
}
// ── Claude stream-json emission ─────────────────────────────────────────────
const t0 = Date.now();
function emit(obj: Record<string, unknown>) {
process.stdout.write(JSON.stringify(obj) + "\n");
}
const parsed = parseArgs(process.argv.slice(2));
const isManagedRun = Boolean(process.env[AGENT_SESSION_FILE_ENV]?.trim());
const isSecurityTask = process.env[AGENT_SESSION_KIND_ENV] === "security";
const isAsking = !isManagedRun && !!(parsed.sessionUuid || parsed.resumeUuid);
// Stable session id for every emitted frame: the caller's uuid when it has one
// (keeps a task's logs coherent across turns), else filled from cursor's init.
let outSid = parsed.resumeUuid || parsed.sessionUuid || "";
let emittedInit = false;
// ── cursor → claude frame translation ───────────────────────────────────────
// Cursor streams assistant text and thinking as deltas; buffer them and flush a
// single consolidated block so a STATUS sentinel can't be split across frames
// and the LogPanel shows whole messages (parity with `claude -p`).
let pendingText = "";
let pendingTextCall = "";
let pendingThink = "";
let numTurns = 0;
let finalized = false;
let sawResult = false;
let lastError = "";
function emitAssistantText(text: string) {
if (!text.trim()) return;
numTurns++;
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "text", text }] },
session_id: outSid,
parent_tool_use_id: null,
uuid: randomUUID(),
});
}
function flushText() {
if (!pendingText.trim()) { pendingText = ""; pendingTextCall = ""; return; }
emitAssistantText(pendingText);
pendingText = "";
pendingTextCall = "";
}
function flushThink() {
if (!pendingThink.trim()) { pendingThink = ""; return; }
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "thinking", thinking: pendingThink }] },
session_id: outSid,
parent_tool_use_id: null,
uuid: randomUUID(),
});
pendingThink = "";
}
// Cursor nests the real payload under a single kind-specific key, e.g.
// tool_call: { readToolCall: { args:{…}, result:{ success|error:{…} } },
// toolCallId, startedAtMs, completedAtMs }
// So we locate the `<kind>ToolCall` sub-object and read args/result from it.
const KIND_NAME: Record<string, string> = {
read: "Read", write: "Write", edit: "Edit", searchReplace: "Edit",
multiEdit: "MultiEdit", ls: "LS", list: "LS", grep: "Grep", glob: "Glob",
shell: "Bash", terminal: "Bash", runTerminalCommand: "Bash",
delete: "Delete", todoWrite: "TodoWrite", webSearch: "WebSearch",
fetch: "WebFetch", codebaseSearch: "Search",
};
function findKind(tc: Record<string, any>): { kind: string; inner: Record<string, any> } {
for (const [k, v] of Object.entries(tc)) {
if (k.endsWith("ToolCall") && v && typeof v === "object") {
return { kind: k.slice(0, -"ToolCall".length), inner: v as Record<string, any> };
}
}
return { kind: "", inner: {} };
}
function toolName(kind: string): string {
if (!kind) return "tool";
return KIND_NAME[kind] || (kind[0].toUpperCase() + kind.slice(1));
}
/** Map cursor's nested tool_call → Claude's {name, input}. LogPanel renders the
* name plus the input entries; the fix runner never parses these. */
function deriveToolUse(ev: any): { id: string; name: string; input: Record<string, unknown> } {
const tc = (ev.tool_call || {}) as Record<string, any>;
const id = String(ev.call_id ?? tc.toolCallId ?? randomUUID());
const { kind, inner } = findKind(tc);
const input = (inner.args && typeof inner.args === "object") ? inner.args
: (inner.rawArgs && typeof inner.rawArgs === "object") ? inner.rawArgs
: {};
return { id, name: toolName(kind), input };
}
/** Flatten cursor's tool result (result.success.* / result.error) into a
* readable string and derive the error flag from which branch is present. */
function deriveToolResult(ev: any): { id: string; content: string; isError: boolean } {
const tc = (ev.tool_call || {}) as Record<string, any>;
const id = String(ev.call_id ?? tc.toolCallId ?? "");
const { kind, inner } = findKind(tc);
const res = inner.result as Record<string, any> | undefined;
let isError = false;
let content = "";
if (res && typeof res === "object") {
if (res.error !== undefined || res.failure !== undefined) {
isError = true;
const e = res.error ?? res.failure;
content = typeof e === "string" ? e : (e?.message ?? JSON.stringify(e));
} else {
const ok = res.success ?? res;
content = typeof ok === "string" ? ok
: (ok?.content ?? ok?.output ?? ok?.stdout ?? ok?.text ?? "");
if (!content) content = JSON.stringify(ok);
}
}
if (content.length > 8000) content = content.slice(0, 8000) + "\n…(truncated)";
if (!content) content = `[${kind || "tool"} done]`;
return { id, content, isError };
}
type NormalizedUsage = {
input_tokens: number;
output_tokens: number;
cache_read_input_tokens: number;
cache_creation_input_tokens: number;
thinking_tokens: number;
};
/** cursor result.usage is camelCase; map to Claude's usage field names. */
function mapUsage(u: any): NormalizedUsage {
const g = (k: string) => (typeof u?.[k] === "number" ? u[k] : 0);
const tokenDetail = (...values: unknown[]) => {
const value = values.find((entry) => typeof entry === "number" && Number.isFinite(entry));
return typeof value === "number" ? value : 0;
};
return {
input_tokens: g("inputTokens"),
output_tokens: g("outputTokens"),
cache_read_input_tokens: g("cacheReadTokens"),
cache_creation_input_tokens: g("cacheWriteTokens"),
thinking_tokens: tokenDetail(
u?.thinkingTokens,
u?.thinking_tokens,
u?.reasoningTokens,
u?.reasoning_tokens,
u?.reasoningOutputTokens,
),
};
}
function onCursorEvent(ev: any) {
const type = ev?.type as string | undefined;
switch (type) {
case "system": {
if (ev.subtype === "init") {
if (!outSid) outSid = String(ev.session_id || randomUUID());
if (emittedInit) return;
emittedInit = true;
emit({
type: "system", subtype: "init",
cwd: ev.cwd ?? process.cwd(),
session_id: outSid,
tools: [], model: ev.model ?? parsed.model ?? CURSOR_MODEL ?? "",
permissionMode: "bypassPermissions",
apiKeySource: ev.apiKeySource ?? "none",
mcp_servers: [], slash_commands: [],
cursor_cli: true,
});
}
return;
}
case "user":
// Cursor echoes the initial prompt as a user frame; `claude -p` does not.
// Drop it for parity (the runners never want the prompt echoed back).
return;
case "assistant": {
const content = (ev.message?.content ?? []) as Array<Record<string, any>>;
const text = content.map((c) => (typeof c?.text === "string" ? c.text : "")).join("");
if (!text) return;
const call = String(ev.model_call_id ?? "");
if (pendingText && call && call !== pendingTextCall) flushText();
pendingTextCall = call;
pendingText += text;
return;
}
case "thinking": {
if (ev.subtype === "completed") { flushThink(); return; }
if (typeof ev.text === "string") pendingThink += ev.text;
return;
}
case "tool_call": {
// A tool call means the current text turn is over — flush it first so the
// assistant text and the tool_use land in transcript order.
flushText();
flushThink();
if (ev.subtype === "started") {
const { id, name, input } = deriveToolUse(ev);
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "tool_use", id, name, input }] },
session_id: outSid,
parent_tool_use_id: null,
uuid: randomUUID(),
});
} else if (ev.subtype === "completed") {
const { id, content, isError } = deriveToolResult(ev);
emit({
type: "user",
message: { role: "user", content: [{ type: "tool_result", tool_use_id: id, content, is_error: isError }] },
session_id: outSid,
parent_tool_use_id: null,
uuid: randomUUID(),
});
}
return;
}
case "result": {
flushText();
flushThink();
sawResult = true;
const isError = ev.is_error === true;
const rawResult = ev.result ?? "";
const resultText = isError && isSecurityTask && isCursorApiKeyMode("cursor") && (typeof rawResult === "object" || (ev.error && typeof ev.error === "object"))
? redactCursorCliDiagnostic(JSON.stringify({ result: rawResult, error: ev.error ?? null }) || "") : String(rawResult);
finalize(isError ? "error_during_execution" : "success", isError, resultText, Number(ev.duration_ms ?? (Date.now() - t0)), mapUsage(ev.usage));
return;
}
case "error": {
// Surface cursor's own error so upstream infra-error detection can see it.
const raw = ev.message ?? ev.error ?? ev.text ?? "unknown error";
const msg = isSecurityTask && isCursorApiKeyMode("cursor") && ev.error && typeof ev.error === "object"
? redactCursorCliDiagnostic(JSON.stringify({ message: ev.message ?? ev.text ?? null, error: ev.error }) || "") : String(raw);
lastError = msg;
flushText();
emit({
type: "assistant",
message: { role: "assistant", content: [{ type: "text", text: `API Error: ${msg}` }] },
session_id: outSid,
parent_tool_use_id: null,
uuid: randomUUID(),
});
return;
}
case "turn_ended": {
// Current Cursor CLI reports account exhaustion as a terminal
// `turn_ended/status:error` frame rather than `type:error` or `result`.
// Keep this compatibility change security-only so feature/bug retain the
// wrapper behaviour they had before security gained runner-owned retries.
if (!isSecurityTask || ev.status !== "error") return;
const raw = ev.error ?? ev.message ?? ev.text ?? "Cursor turn ended with an error";
const msg = typeof raw === "string" ? raw : JSON.stringify(raw);
lastError = msg;
flushText();
emit({
type: "assistant",
message: { role: "assistant", model: "<synthetic>", content: [{ type: "text", text: `API Error: ${msg}` }] },
session_id: outSid,
parent_tool_use_id: null,
uuid: randomUUID(),
});
return;
}
default:
dbg(`unhandled cursor frame type: ${type}`);
}
}
const ZERO_USAGE: NormalizedUsage = {
input_tokens: 0,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
thinking_tokens: 0,
};
function finalize(subtype: string, isError: boolean, result: string, durMs: number, usage: NormalizedUsage = ZERO_USAGE) {
if (finalized) return;
finalized = true;
emit({
type: "result",
subtype,
is_error: isError,
duration_ms: durMs,
duration_api_ms: durMs,
num_turns: numTurns,
result,
stop_reason: isError ? null : "end_turn",
session_id: outSid,
uuid: randomUUID(),
total_cost_usd: 0,
usage,
});
}
// ── spawn cursor-agent ──────────────────────────────────────────────────────
let chatId: string | null;
try {
chatId = await resolveChatId(parsed);
} catch (err) {
finalize("error_during_execution", true, redactCursorCliDiagnostic((err as Error).message), Date.now() - t0);
process.exit(1);
}
function buildInitialPrompt(): string {
const parts: string[] = [];
if (!isAsking) parts.push(AUTOMODE_SYSPROMPT);
if (parsed.appendSys) parts.push(parsed.appendSys);
parts.push(parsed.prompt);
return parts.join("\n\n");
}
function buildCursorArgs(promptText: string, resumeChatId: string | null): string[] {
const cursorArgs = [
"--print",
"--output-format", "stream-json",
"--force", "--trust", "--approve-mcps",
];
// Security's host already applies isolation; avoid nesting Cursor's sandbox.
if (isSecurityTask) cursorArgs.push("--sandbox", "disabled");
for (const d of parsed.addDirs) cursorArgs.push("--add-dir", d);
const model = parsed.model || CURSOR_MODEL;
if (model) cursorArgs.push("--model", model);
if (resumeChatId) cursorArgs.push("--resume", resumeChatId);
cursorArgs.push(promptText);
return cursorArgs;
}
let currentChild: Subprocess<"ignore", "pipe", "pipe"> | null = null;
function killTree() {
try { currentChild?.kill(); } catch { /* ignore */ }
}
for (const sig of ["SIGINT", "SIGTERM"] as const) {
process.on(sig, () => {
dbg(`got ${sig}; killing cursor-agent`);
finalize("error_during_execution", true, lastError || "", Date.now() - t0);
killTree();
process.exit(143);
});
}
async function runCursorChild(promptText: string, resumeChatId: string | null): Promise<number> {
const cursorArgs = buildCursorArgs(promptText, resumeChatId);
dbg(`spawning ${CURSOR_BIN} (chat=${resumeChatId ?? "fresh"}, asking=${isAsking}, prompt=${JSON.stringify(promptText)}) cwd=${process.cwd()}`);
const child: Subprocess<"ignore", "pipe", "pipe"> = spawn({
cmd: [CURSOR_BIN, ...cursorArgs],
cwd: process.cwd(),
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
currentChild = child;
// Security evaluate/run opt in explicitly. Feature, bugfix and asking retain
// their previous stderr/terminal behaviour, including DEBUG output.
const diagnostic = isSecurityTask ? new CursorCliDiagnosticBuffer() : null;
const handle = (line: string) => {
const s = line.trim();
if (!s) return;
if (s[0] !== "{") {
diagnostic?.append(`${s}\n`);
return;
}
if (DEBUG) process.stderr.write(`[cursor-raw] ${s}\n`);
let ev: any;
try { ev = JSON.parse(s); } catch { return; }
try { onCursorEvent(ev); } catch (e) { dbg(`translate error: ${(e as Error).message}`); }
};
const stderrTask = (async () => {
const dec = new TextDecoder();
for await (const chunk of child.stderr) {
if (diagnostic) diagnostic.append(dec.decode(chunk, { stream: true }));
else if (DEBUG) process.stderr.write(dec.decode(chunk));
}
if (diagnostic) diagnostic.append(dec.decode());
})().catch(() => {});
const stdoutTask = (async () => {
const dec = new TextDecoder();
let buf = "";
for await (const chunk of child.stdout) {
buf += dec.decode(chunk, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
handle(buf.slice(0, nl));
buf = buf.slice(nl + 1);
}
}
if (buf.trim()) handle(buf);
})().catch((e) => dbg(`stdout reader error: ${(e as Error).message}`));
const code = await child.exited;
await Promise.allSettled([stderrTask, stdoutTask]);
if (diagnostic && !sawResult && (code !== 0 || (numTurns === 0 && !pendingText.trim())) && !lastError) {
lastError = diagnostic.text() || `Cursor CLI exited with code ${code} without a usable result`;
}
if (currentChild === child) currentChild = null;
return code;
}
const code = await runCursorChild(buildInitialPrompt(), chatId);
// Flush anything the stream reader left buffered, then guarantee a result frame
// so the caller's parser never hangs waiting for a terminal frame cursor didn't
// emit (crash / auth failure / empty run).
flushText();
flushThink();
if (!sawResult) {
const ok = !lastError && (numTurns > 0) && code === 0;
finalize(ok ? "success" : "error_during_execution", !ok, lastError || "", Date.now() - t0);
}
process.exit(sawResult ? 0 : (code || 1));
+1261
View File
File diff suppressed because it is too large Load Diff
+261
View File
@@ -0,0 +1,261 @@
/**
* `conditions` — the instrumented wrapper the executor agents call to record what
* they established on the device. Replaces the old `spec-delta` wrapper; see the
* header of shared/src/conditions.ts for why the record was inverted from
* "deviations" to "conditions".
*
* Each invocation appends exactly one line to `<workspace>/Conditions.jsonl`.
* The agent never edits that file by hand, and never edits TestSpec.md — this
* tool is the only write path, which is what makes the record trustworthy enough
* to feed back into future spec drafting.
*
* Two verbs:
* record — one condition (repeat as many times as needed)
* done — close out the round; prints a summary and complains if the round
* recorded nothing, which is nearly always a miss rather than a run
* with genuinely zero preconditions.
*
* Callable directly (`bun bin/conditions.ts record …`) or as the satellite
* bundle's `conditions` subcommand (see satellite/src/entry.ts), so a deployed
* node runs the same version of this code as the runner that reads it back.
*/
import { existsSync, mkdirSync, appendFileSync, readFileSync } from "node:fs";
import path from "node:path";
import {
CONDITIONS_FILE,
CONDITIONS_SCHEMA_VERSION,
CONDITION_KINDS,
CONDITION_KIND_LABEL,
SPEC_AGREEMENT_LABEL,
conditionStats,
matchKind,
newConditionId,
normalizeKbLabels,
parseConditions,
type ConditionEntry,
type ConditionKind,
type ConditionVerdict,
type SpecAgreement,
} from "../shared/src/conditions";
function parseArgs(argv: string[]): Record<string, string> {
const out: Record<string, string> = {};
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];
if (next == null || next.startsWith("--")) {
out[key] = "true";
} else {
out[key] = next;
i++;
}
}
return out;
}
function die(code: number, msg: string): never {
process.stderr.write(msg.endsWith("\n") ? msg : msg + "\n");
process.exit(code);
}
/** A flag the parser filled with the placeholder "true" carries no real value. */
function val(args: Record<string, string>, key: string): string | null {
const v = args[key];
if (v == null || v === "true") return null;
const t = v.trim();
return t ? t : null;
}
/**
* Resolve the workspace directory. Tolerates being handed the `evidence/`
* subdirectory — the agent has been trained by `record-evidence` to pass that
* path, and bouncing it here would just cost a round trip for no reason.
*/
function workspaceDir(args: Record<string, string>): string {
const raw = val(args, "dir") || process.env.CONDITIONS_DIR || process.env.SPEC_DELTA_DIR || "";
if (!raw) die(2, "缺少 --dir <工作区目录>(或设置 $CONDITIONS_DIR)");
let dir = path.resolve(raw);
if (path.basename(dir) === "evidence") dir = path.dirname(dir);
if (!existsSync(dir)) die(2, `工作区目录不存在:${dir}`);
return dir;
}
function resolveRound(args: Record<string, string>): number {
const raw = val(args, "round") || process.env.CONDITIONS_ROUND || process.env.SPEC_DELTA_ROUND || "";
const n = Number(raw);
if (!Number.isFinite(n) || n < 1) {
die(2, "缺少或非法的 --round <轮次>(或设置 $CONDITIONS_ROUND),应为 >= 1 的整数");
}
return Math.floor(n);
}
const filePath = (dir: string) => path.join(dir, CONDITIONS_FILE);
function append(dir: string, entry: ConditionEntry): void {
mkdirSync(dir, { recursive: true });
appendFileSync(filePath(dir), JSON.stringify(entry) + "\n", "utf8");
}
function readExisting(dir: string): ConditionEntry[] {
const f = filePath(dir);
if (!existsSync(f)) return [];
try { return parseConditions(readFileSync(f, "utf8")); } catch { return []; }
}
const KIND_HELP = CONDITION_KINDS.map((k) => ` ${k.padEnd(12)} ${CONDITION_KIND_LABEL[k]}`).join("\n");
const USAGE =
"用法:\n" +
` conditions record --kind <${CONDITION_KINDS.join("|")}> --scope "<业务模块>" --subject "<这条讲哪件事>" --statement "<条件是什么>" \\\n` +
` [--spec <predicted|contradicted|absent>] [--spec-said "<spec 原本怎么写的>"] \\\n` +
" [--payload '<JSON>'] [--evidence <evidence 下的文件名>] [--assumed]\n" +
" conditions done # 本轮记录完毕,打印汇总\n\n" +
"kind 可用值:\n" + KIND_HELP + "\n";
// ── commands ────────────────────────────────────────────────────────────────
function cmdRecord(args: Record<string, string>): never {
const dir = workspaceDir(args);
const round = resolveRound(args);
const statement = val(args, "statement");
if (!statement) die(2, `缺少 --statement "<条件是什么>"(写成将来别人能直接照做的形式)`);
const scope = val(args, "scope");
if (!scope) die(2, `缺少 --scope "<业务模块>"(如 "Story 相机";要稳定、可复用,别写成本任务专有的描述)`);
const subject = val(args, "subject");
if (!subject) {
die(2, `缺少 --subject "<这条讲哪件事>"(如 "特效面板入口路径";同一件事在不同任务里必须写成同一个 subject)`);
}
const rawKind = val(args, "kind");
const kind: ConditionKind | null = matchKind(rawKind);
if (!kind) {
die(2, `缺少或无法识别的 --kind「${rawKind ?? ""}」。可用值:\n${KIND_HELP}`);
}
// How the drafted spec fared. Defaults to `absent` — the honest default when the
// agent doesn't say, since "the spec never mentioned this" is both the most
// common case and the one that understates rather than overstates spec quality.
const rawSpec = val(args, "spec");
let spec: SpecAgreement = "absent";
if (rawSpec) {
if (rawSpec === "predicted" || rawSpec === "contradicted" || rawSpec === "absent") {
spec = rawSpec;
} else {
process.stderr.write(`⚠️ 无法识别的 --spec「${rawSpec}」,按 absent 记录。可用值:predicted / contradicted / absent\n`);
}
}
const specSaid = val(args, "spec-said") || val(args, "specSaid");
if (spec === "contradicted" && !specSaid) {
process.stderr.write("⚠️ --spec contradicted 建议同时给 --spec-said \"<spec 原本怎么写的>\",否则事后无法复盘 spec 错在哪。\n");
}
let payload: Record<string, unknown> | undefined;
const rawPayload = val(args, "payload");
if (rawPayload) {
try {
const p = JSON.parse(rawPayload) as unknown;
if (p && typeof p === "object" && !Array.isArray(p)) payload = p as Record<string, unknown>;
else process.stderr.write("⚠️ --payload 需要是一个 JSON 对象,已忽略。\n");
} catch {
process.stderr.write("⚠️ --payload 不是合法 JSON,已忽略。\n");
}
}
const evidence = val(args, "evidence");
if (evidence) {
const f = path.join(dir, "evidence", evidence.replace(/^evidence\//, ""));
if (!existsSync(f)) {
process.stderr.write(`⚠️ 证据文件不存在:${f}(本条仍会记录,但报告里会是死链)\n`);
}
}
// Default `verified`: this tool is called from a real-device session, so the
// common case is something actually exercised. `--assumed` is the explicit
// downgrade for "I read this off the code but didn't run it".
const verdict: ConditionVerdict = args.assumed ? "assumed" : "verified";
// Which injected knowledge this condition speaks about. A label the prompt
// never showed is dropped with a warning rather than stored: the attribution
// loop resolves labels by POSITION in that run's injected list, so a made-up
// K9 would not fail — it would silently settle whichever claim happens to sit
// at index 8, which is worse than recording no link at all.
const kb = normalizeKbLabels([val(args, "kb") ?? ""]);
const rawKb = val(args, "kb");
if (rawKb && !kb.length) {
process.stderr.write(`⚠️ 无法识别的 --kb「${rawKb}」,已忽略。应为 prompt 里出现过的编号,如 --kb K1 或 --kb K1,K3\n`);
}
const entry: ConditionEntry = {
v: CONDITIONS_SCHEMA_VERSION,
ts: Date.now(),
id: newConditionId(),
round,
source: "agent",
kind,
scope,
subject,
statement,
...(payload ? { payload } : {}),
verdict,
spec,
...(specSaid ? { specSaid } : {}),
...(evidence ? { evidence } : {}),
...(kb.length ? { kb } : {}),
};
append(dir, entry);
process.stdout.write(
`✅ 已记录条件(round ${round}):[${CONDITION_KIND_LABEL[kind]}] ${scope} › ${subject}\n` +
` ${statement}\n` +
` ${verdict === "verified" ? "真机已验证" : "仅推断未验证"} · ${SPEC_AGREEMENT_LABEL[spec]}` +
(kb.length ? ` · 关联知识 ${kb.join(",")}` : "") + "\n",
);
process.exit(0);
}
function cmdDone(args: Record<string, string>): never {
const dir = workspaceDir(args);
const round = resolveRound(args);
const all = readExisting(dir);
const mine = all.filter((e) => e.round === round);
if (!mine.length) {
// Not an error exit: failing here would tempt the agent into skipping the
// tool entirely. But say plainly that this is almost certainly a miss.
process.stdout.write(
`⚠️ round ${round} 没有记录任何执行条件。\n` +
" 几乎每次执行都至少有账号、构建方式、入口路径这类前置条件 —— 一条都没有,\n" +
" 通常意味着漏记了,而不是真的没有。请回看本轮实际做了什么,补记后再执行 done。\n",
);
process.exit(0);
}
const st = conditionStats(mine);
const kinds = st.byKind.map((k) => `${CONDITION_KIND_LABEL[k.kind]}×${k.count}`).join(" · ");
const specs = st.bySpec.map((s) => `${SPEC_AGREEMENT_LABEL[s.spec]}×${s.count}`).join(" · ");
process.stdout.write(
`✅ round ${round} 共记录 ${mine.length} 条执行条件(真机验证 ${st.verified} · 推断 ${st.assumed})\n` +
` 分类:${kinds}\n` +
` spec 命中:${specs}\n`,
);
process.exit(0);
}
/**
* CLI entry, callable two ways — directly (`bun bin/conditions.ts record …`) or as
* the satellite bundle's `conditions` subcommand via satellite/src/entry.ts.
*/
export async function runConditions(argv: string[]): Promise<never> {
const sub = argv[0];
const args = parseArgs(argv.slice(1));
switch (sub) {
case "record": case "add": return cmdRecord(args);
case "done": case "confirm": return cmdDone(args);
case "-h": case "--help": case undefined: return die(sub ? 0 : 2, USAGE);
default: return die(2, `未知子命令「${sub}」\n\n${USAGE}`);
}
}
if (import.meta.main) await runConditions(process.argv.slice(2));
+171
View File
@@ -0,0 +1,171 @@
/**
* `kb` — the knowledge base as a tool the agent can ASK, from inside its own
* session, in the middle of a run.
*
* ## Why a pull side exists at all
*
* Retrieval used to be push-only: the control plane picked what an agent would
* need at the moment it dispatched the work, and that was the agent's only shot.
* For standing knowledge that is exactly right — build-system and device facts
* are chosen by platform and past usefulness precisely because they do not
* depend on the ticket, and in production they are cited 43% of the time.
*
* For everything else it cannot work, and the production numbers say so without
* ambiguity: pushed `experiment` knowledge was shown 89 times and cited 0,
* `entry_path` 79 times and cited 7. Not because the knowledge is bad — because
* the question had not been asked yet. A ticket title is written before anyone
* has seen the screen; the entry path that matters is the one for the screen the
* agent is stuck on forty minutes in. Nothing at dispatch time could have known
* to send it.
*
* So: push what recurs regardless of the ticket, pull what only the moment can
* know.
*
* ## What it prints
*
* A block whose `K<n>` labels CONTINUE this run's numbering (the control plane
* appends the hits to the same injected list the dispatch block came from), so a
* pulled hit is cited exactly like a pushed one — `〔K7〕` in the report, `K7` in
* the final `KB_USED:` line — and the effectiveness numbers keep working.
*
* ## What it never does
*
* Fail loudly. A miss prints "nothing found" and exits 0: the agent's correct
* next move is its own research either way, and a tool that errors on an empty
* result teaches it to stop calling the tool. Exit 1 is reserved for the tool
* being broken (no control plane configured, network down) — a different fact,
* and one the agent should not silently read as "the knowledge base is empty".
*/
import { CONTROL_INTERNAL, PROD_CONTROL_PLANE_URL, DEBUG_CONTROL_PLANE_URL, CLUSTER_SECRET_HEADER } from "../shared/src/protocol";
const CONTROL = (
process.env.CONTROL_PLANE_URL ||
(process.env.STREAMLINE_DEBUG ? DEBUG_CONTROL_PLANE_URL : PROD_CONTROL_PLANE_URL)
).replace(/\/+$/, "");
const TIMEOUT_MS = Number(process.env.KB_RECALL_TIMEOUT_MS || 8000);
function parseArgs(argv: string[]): { flags: Record<string, string>; rest: string[] } {
const flags: Record<string, string> = {};
const rest: string[] = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) { rest.push(a); continue; }
const key = a.slice(2);
const next = argv[i + 1];
if (next == null || next.startsWith("--")) flags[key] = "true";
else { flags[key] = next; i++; }
}
return { flags, rest };
}
const val = (flags: Record<string, string>, key: string): string | null => {
const v = flags[key];
if (v == null || v === "true") return null;
const t = v.trim();
return t ? t : null;
};
const USAGE =
"用法:\n" +
` kb recall --target <bug|feature|security>:<id> "<你的问题>" [--kind entry_path,experiment] [--limit 6]\n\n` +
"说明:\n" +
" 按你的问题检索历史真机确证的知识,命中项接着当前 prompt 里的 K 编号往下排。\n" +
" 查不到会直说 —— 那就按你自己的调研走,别把「没查到」当成「不存在」。\n";
/**
* `bug:abc-123` → the two fields the control plane needs. Also accepts a bare id
* (bug is by far the most common caller) rather than failing on a missing prefix
* mid-run.
*/
export function parseTarget(raw: string | null): { targetKind: string; targetId: string } | null {
if (!raw) return null;
const m = /^(bug|feature|security)[:/](.+)$/i.exec(raw.trim());
if (m) return { targetKind: m[1].toLowerCase(), targetId: m[2].trim() };
const bare = raw.trim();
return bare ? { targetKind: "bug", targetId: bare } : null;
}
async function cmdRecall(argv: string[]): Promise<never> {
const { flags, rest } = parseArgs(argv);
const target = parseTarget(val(flags, "target") || process.env.KB_TARGET || null);
if (!target) {
process.stderr.write(`缺少 --target <bug|feature|security>:<id>(或设置 $KB_TARGET)\n\n${USAGE}`);
process.exit(2);
}
// The question may come as positional words or as --query; both read naturally
// in a shell and an agent will use whichever it happened to see in the prompt.
const query = (val(flags, "query") || rest.join(" ")).trim();
if (!query) {
process.stderr.write(`缺少问题正文。\n\n${USAGE}`);
process.exit(2);
}
const headers: Record<string, string> = { "content-type": "application/json" };
if (process.env.CLUSTER_SECRET) headers[CLUSTER_SECRET_HEADER] = process.env.CLUSTER_SECRET;
let data: {
ok?: boolean; count?: number; block?: string | null;
firstLabel?: string | null; known?: string[];
};
try {
const res = await fetch(CONTROL + CONTROL_INTERNAL.kbRecall, {
method: "POST",
headers,
body: JSON.stringify({
...target,
query,
kinds: (val(flags, "kind") || val(flags, "kinds") || "")
.split(/[,\s]+/).map((k) => k.trim()).filter(Boolean),
...(val(flags, "limit") ? { limit: Number(val(flags, "limit")) } : {}),
}),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (!res.ok) throw new Error(`${res.status}`);
data = (await res.json()) as typeof data;
} catch (err) {
// The tool is broken, not the knowledge base empty. Say which, so the agent
// does not record "no knowledge exists" as a finding about the base.
process.stderr.write(
`⚠️ 知识库检索没跑通(${(err as Error).message})—— 这是工具/网络的问题,不代表库里没有。\n` +
" 按你自己的调研继续,不要因此下「无相关知识」的结论。\n",
);
process.exit(1);
}
const known = Array.isArray(data.known) ? data.known : [];
if (!data.block || !data.count) {
// "You already have it" and "there is none" are different answers, and
// collapsing them into the second is how an agent learns to stop asking.
process.stdout.write(known.length
? `🔍 跟「${query}」相关的知识你已经拿到了:${known.join("、")} —— 回到 prompt 里那几条看。\n`
: `🔍 知识库里没有跟「${query}」相关的已确证知识。\n` +
" 按你自己的代码调研 / 真机试验继续 —— 这就是常态,不是异常。\n" +
" 如果你这一轮把它跑通了,记得用 conditions record 记下来,下一个任务就能查到。\n");
process.exit(0);
}
process.stdout.write(
`${data.block}\n` +
(known.length ? `(另外 ${known.join("、")} 也相关,它们已经在你上面的 prompt 里了。)\n` : "") +
`(共 ${data.count} 条,编号从 ${data.firstLabel || "K?"} 起。采纳了哪条就在报告里标 〔编号〕,并计入最后的 KB_USED: 行;` +
"验证或推翻了哪条,记条件时加 --kb <编号>。)\n",
);
process.exit(0);
}
/** CLI entry — direct (`bun bin/kb.ts recall …`) or as the bundle's `kb` subcommand. */
export async function runKb(argv: string[]): Promise<never> {
const sub = argv[0];
switch (sub) {
case "recall": case "search": case "query": return await cmdRecall(argv.slice(1));
case "-h": case "--help": case undefined:
process.stdout.write(USAGE);
process.exit(sub ? 0 : 2);
default:
process.stderr.write(`未知子命令「${sub}」\n\n${USAGE}`);
process.exit(2);
}
}
if (import.meta.main) await runKb(process.argv.slice(2));
File diff suppressed because it is too large Load Diff
+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));