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
+24
View File
@@ -0,0 +1,24 @@
# @byted/streamline-skill
Streamline 的命令行 + Agent Skill,支持 Claude Code、Codex、Cursor。
本地改动的真机验证(`streamline verify`)暂时下线,恢复后会在这里和接入指南里更新。
在对话里直接说「把这个 bug 提给 Streamline」「把这个 Meego 单导入 Streamline」「我那个单修得怎么样了」。
在 Agent 里调研了一半的 bug,说一句「剩下的交给 Streamline 修」,Agent 会把这次会话的调研整理成总结(现象、复现步骤、已确认的事实、怀疑点、已排除)交过去(`streamline task handoff`)。Streamline 把它当作重要线索,但会在真机上重新验证。
```sh
npm i -g @byted/streamline-skill --registry=https://bnpm.byted.org
streamline install # 装给本机所有检测到的 Agent(Claude Code / Codex / Cursor)
streamline auth login # 浏览器 SSO 授权这台电脑(30 天)
```
- 以你本人的身份操作,和在面板上提单、确认执行一样,不需要申请 API Key。确认执行只能确认自己建的单。
- Skill 正本在 `~/.agents/skills/streamline-openapi`,软链到 `~/.claude/skills`、`~/.codex/skills`(或 `$CODEX_HOME/skills`)、`~/.cursor/skills`。只装某几个用 `--agent codex,cursor`;想随仓库共享用 `--project`(拷进当前仓库的 `.claude/` `.codex/` `.cursor/`)。
- 登录凭据存在 `~/.config/streamline/credentials.json`(0600),命令输出里不会出现。
- 每次调用会附带命令行版本和推测的 Agent 名(如 `claude-code`),用于平台的使用统计,不含对话内容。
**系统接入**(你们的服务端程序、机器人调 Streamline)不走这个命令行:在面板头像菜单「开放平台 API」申请 API Key,按[接入文档](https://bytedance.us.larkoffice.com/docx/XUaCdOE7Uo0jOZxaBZbu3Hy8sSf)直接调 HTTP 接口。
`streamline help` 查看全部命令。
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env node
// Streamline 命令行。结果一律以 JSON 打到 stdout(给 Agent 读),提示和进度打到 stderr。
// 以登录用户本人的身份操作(/api/cli/v1/*);任何输出里都不出现登录会话的明文。
// 系统接入(API Key、Webhook、飞书机器人)不在这里:那是服务端程序按接入文档直接调 HTTP 接口的事。
import { readFileSync } from "node:fs";
import { CliError, call } from "../lib/http.js";
import { login } from "../lib/login.js";
import { install, uninstall } from "../lib/install.js";
import { gitContext, parseHandoff } from "../lib/handoff.js";
import { changeUnderTest, parseVerifyCases } from "../lib/verify.js";
import { apiBase, load, save } from "../lib/store.js";
const HELP = `Streamline 命令行(Skill 背后的工具)
登录(以你本人的身份用 Streamline,和在面板上操作一样)
streamline auth login [--no-browser] 浏览器 SSO 授权这台电脑(30 天)
streamline auth status | logout
提单与查进展
streamline task import <Meego 链接> [--watchers a,b]
streamline task create --title <标题> --description <描述> [--platform android|ios]
[--repro <复现步骤>] [--watchers a,b]
streamline task list [--limit 20] 我建的单
streamline task get <taskId>
streamline task execute <taskId> 确认执行(只能确认自己建的单)
streamline task handoff --title <标题> --file <总结.md|-> [--platform android|ios] [--watchers a,b] [--no-git]
接力:把本地 Agent 的调研总结交给 Streamline 从头修
安装 Skill(Claude Code / Codex / Cursor)
streamline install [--agent claude,codex,cursor|all] [--project | --dir <目录>]
默认装给本机检测到的所有 Agent:正本在 ~/.agents/skills/streamline-openapi,
再软链到 ~/.claude/skills、~/.codex/skills、~/.cursor/skills;--project 拷进当前仓库
streamline uninstall [--agent …] [--project]
环境变量:STREAMLINE_API_URL、STREAMLINE_WEB_URL(连自建环境时用)`;
function parse(argv) {
const pos = [], flags = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) { pos.push(a); continue; }
const eq = a.indexOf("=");
if (eq > 0) { flags[a.slice(2, eq)] = a.slice(eq + 1); continue; }
const name = a.slice(2);
if (name.startsWith("no-")) { flags[name.slice(3)] = false; continue; }
const next = argv[i + 1];
if (next === undefined || next.startsWith("--")) flags[name] = true;
else { flags[name] = next; i++; }
}
return { pos, flags };
}
const out = (v) => process.stdout.write(JSON.stringify(v, null, 2) + "\n");
const note = (s) => process.stderr.write(s + "\n");
const list = (v) => (typeof v === "string" ? v.split(",").map((s) => s.trim()).filter(Boolean) : undefined);
function need(flags, name) {
const v = flags[name];
if (typeof v !== "string" || !v.trim()) throw new CliError(`缺少 --${name}`);
return v.trim();
}
const readInput = (file) => readFileSync(file === "-" ? 0 : file, "utf8");
async function auth(sub, flags) {
if (sub === "login") {
const r = await login({ openBrowser: flags.browser !== false });
note(`已登录:${r.email}`);
return out({ loggedIn: true, email: r.email, expiresAt: new Date(r.expiresAt).toISOString() });
}
if (sub === "status") {
const s = load().session;
if (!s) return out({ loggedIn: false, api: apiBase() });
try {
const r = await call("GET", "/api/openapi-cli/auth/session", { auth: "session" });
return out({ loggedIn: true, email: r.email, expiresAt: new Date(r.expiresAt).toISOString(), api: apiBase() });
} catch (err) {
return out({ loggedIn: false, api: apiBase(), error: err.message });
}
}
if (sub === "logout") {
if (load().session) await call("POST", "/api/openapi-cli/auth/logout", { auth: "session", body: {} }).catch(() => {});
save(({ session, ...rest }) => rest);
return out({ loggedOut: true });
}
throw new CliError("用法:streamline auth login | status | logout");
}
// 改动验证暂时下线:--help 和 Skill 里都不再出现,服务端也拒绝新建(routes_cli.ts 的 CHANGE_RUN_OPEN)。
// 命令留着:报错里带着服务端的说明,比「未知命令」好懂。机器数量、按需独占实例、热编译就绪后再放回。
async function verify(sub, pos, flags) {
if (sub === "create") {
const platform = need(flags, "platform");
if (platform !== "android" && platform !== "ios") throw new CliError("--platform 只能是 android 或 ios");
const parsed = parseVerifyCases(readInput(need(flags, "file")));
const change = changeUnderTest({ allowDirty: flags["allow-dirty"] === true });
note(`被测提交 ${change.commit.slice(0, 12)}${change.branch ? `(分支 ${change.branch})` : ""},${parsed.cases.length} 条用例`);
return out(await call("POST", "/api/cli/v1/verifications", {
auth: "session", body: { title: need(flags, "title"), platform, background: parsed.background, cases: parsed.cases, change },
}));
}
if (sub === "rerun") {
if (!pos[0]) throw new CliError("用法:streamline verify rerun <上一次验证的 id>");
const change = changeUnderTest({ allowDirty: flags["allow-dirty"] === true });
note(`复验:被测提交 ${change.commit.slice(0, 12)}${change.branch ? `(分支 ${change.branch})` : ""},沿用上一次的用例`);
return out(await call("POST", `/api/cli/v1/verifications/${encodeURIComponent(pos[0])}/rerun`, { auth: "session", body: { change } }));
}
if (sub === "get") {
if (!pos[0]) throw new CliError("用法:streamline verify get <id>");
return out(await call("GET", `/api/cli/v1/verifications/${encodeURIComponent(pos[0])}`, { auth: "session" }));
}
throw new CliError("用法:streamline verify create | rerun | get");
}
async function task(sub, pos, flags) {
const base = "/api/cli/v1";
if (sub === "create") {
const body = {
title: need(flags, "title"), description: need(flags, "description"),
platform: typeof flags.platform === "string" ? flags.platform : undefined,
reproSteps: typeof flags.repro === "string" ? flags.repro : undefined,
watchers: list(flags.watchers),
};
return out(await call("POST", `${base}/tasks`, { auth: "session", body }));
}
if (sub === "import") {
if (!pos[0]) throw new CliError("用法:streamline task import <Meego 链接>");
return out(await call("POST", `${base}/meego-import`, { auth: "session", body: { meegoLink: pos[0], watchers: list(flags.watchers) } }));
}
if (sub === "handoff") {
const body = {
title: need(flags, "title"),
platform: typeof flags.platform === "string" ? flags.platform : undefined,
watchers: list(flags.watchers),
...parseHandoff(readInput(need(flags, "file"))),
context: flags.git === false ? undefined : gitContext(),
};
return out(await call("POST", `${base}/handoff`, { auth: "session", body }));
}
if (sub === "get") {
if (!pos[0]) throw new CliError("用法:streamline task get <taskId>");
return out(await call("GET", `${base}/tasks/${encodeURIComponent(pos[0])}`, { auth: "session" }));
}
if (sub === "list") {
return out(await call("GET", `${base}/tasks`, { auth: "session", query: { limit: flags.limit } }));
}
if (sub === "execute") {
if (!pos[0]) throw new CliError("用法:streamline task execute <taskId>");
return out(await call("POST", `${base}/tasks/${encodeURIComponent(pos[0])}/execute`, { auth: "session", body: {} }));
}
throw new CliError("用法:streamline task create | import | handoff | get | list | execute");
}
async function main() {
const [cmd, sub, ...rest] = process.argv.slice(2);
const { pos, flags } = parse(rest);
switch (cmd) {
case "auth": return auth(sub, flags);
case "verify": return verify(sub, pos, flags);
case "task": return task(sub, pos, flags);
case "install": return out(install(parse([sub, ...rest].filter((x) => x !== undefined)).flags));
case "uninstall": return out(uninstall(parse([sub, ...rest].filter((x) => x !== undefined)).flags));
case undefined: case "help": case "--help": case "-h": return note(HELP);
default: throw new CliError(`未知命令 ${cmd}`, "运行 streamline help");
}
}
main().catch((err) => {
const e = { error: err.message };
if (err.hint) e.hint = err.hint;
process.stderr.write(JSON.stringify(e) + "\n");
process.exit(1);
});
+61
View File
@@ -0,0 +1,61 @@
// 「接力」:把本地 coding agent 的调研总结交给 Streamline 从头修。服务端的说明见 control-server/src/agent_handoff.ts。
//
// 总结是一份按固定小节写的 Markdown(模板在 skill/SKILL.md)。这里把它拆成三块:
// 现象 → description(提交人看到了什么);复现步骤 → reproSteps;其余小节 → notes(线索,服务端加说明后进 remark)。
import { execFileSync } from "node:child_process";
import { CliError } from "./http.js";
const SECTION_ALIASES = {
symptom: ["现象", "问题现象", "symptom", "symptoms"],
repro: ["复现步骤", "复现", "repro", "repro steps", "steps to reproduce"],
facts: ["已确认的事实", "事实", "已确认事实", "facts", "confirmed facts"],
suspects: ["怀疑点", "疑点", "可能原因", "suspects", "hypotheses"],
ruledOut: ["已排除", "排除", "ruled out"],
fix: ["建议修法", "修复建议", "suggested fix"],
};
function kindOf(heading) {
const h = heading.replace(/[((][^))]*[))]/g, "").trim().toLowerCase();
for (const [kind, names] of Object.entries(SECTION_ALIASES)) if (names.includes(h)) return kind;
return "other";
}
export function parseHandoff(markdown) {
const sections = [];
let current = null;
for (const line of markdown.split(/\r?\n/)) {
const m = line.match(/^##\s+(.+?)\s*$/);
if (m) {
current = { heading: m[1], kind: kindOf(m[1]), body: [] };
sections.push(current);
} else if (current) {
current.body.push(line);
}
}
const text = (s) => s.body.join("\n").trim();
const pick = (kind) => sections.filter((s) => s.kind === kind).map(text).filter(Boolean).join("\n\n");
const description = pick("symptom");
const reproSteps = pick("repro");
if (!description) throw new CliError("总结里缺少「## 现象」小节", "按 Skill 里的模板写:现象、复现步骤、已确认的事实、怀疑点、已排除");
const rest = sections.filter((s) => s.kind !== "symptom" && s.kind !== "repro" && text(s));
if (!rest.some((s) => s.kind === "facts" || s.kind === "suspects"))
throw new CliError("总结里至少要有「## 已确认的事实」或「## 怀疑点」之一", "没有调研结论的话直接用 streamline task create");
const notes = rest.map((s) => `## ${s.heading}\n\n${text(s)}`).join("\n\n");
return { description, reproSteps: reproSteps || null, notes };
}
function git(args, cwd) {
try {
return execFileSync("git", args, { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
} catch { return null; }
}
/** 调研时的代码版本:仓库、分支、提交。远端地址里的用户名口令一律去掉。不在 git 仓库里就全空。 */
export function gitContext(cwd = process.cwd()) {
const remote = git(["remote", "get-url", "origin"], cwd);
return {
repo: remote ? remote.replace(/\/\/[^@/]+@/, "//") : null,
branch: git(["rev-parse", "--abbrev-ref", "HEAD"], cwd),
commit: git(["rev-parse", "HEAD"], cwd),
};
}
+66
View File
@@ -0,0 +1,66 @@
import { readFileSync } from "node:fs";
import { apiBase, load } from "./store.js";
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
/**
* 推测是哪个 Agent 调起的命令,随请求自报给服务端做使用统计(不影响任何行为)。
* Claude Code 设 AI_AGENT / CLAUDECODE,Cursor 的 agent 给 shell 设 CURSOR_AGENT=1;
* Codex 没有固定的标识,看有没有 CODEX_ 开头的运行时变量(CODEX_HOME 只是配置目录,不算)。
*/
export function detectAgent(env = process.env) {
const ai = (env.AI_AGENT || "").toLowerCase();
if (ai.startsWith("claude") || env.CLAUDECODE) return "claude-code";
if (ai.startsWith("cursor") || env.CURSOR_AGENT) return "cursor";
if (ai.startsWith("codex") || Object.keys(env).some((k) => k.startsWith("CODEX_") && k !== "CODEX_HOME")) return "codex";
if (ai) return "other";
return "terminal";
}
const CLIENT = `streamline-cli/${VERSION}; agent=${detectAgent()}`;
export class CliError extends Error {
constructor(message, hint) {
super(message);
this.hint = hint;
}
}
function bearer(auth) {
if (auth === "session") {
const s = load().session;
if (!s || s.expiresAt <= Date.now()) throw new CliError("还没登录,或登录已过期", "运行 streamline auth login");
return s.token;
}
return null;
}
/**
* 调控制面。不跟随重定向:带着凭据被 30x 到别的地方去,宁可报错。
* 非 2xx 一律抛 CliError,带上服务端给的 error / code。
*/
export async function call(method, path, { auth, body, query } = {}) {
const url = new URL(apiBase() + path);
for (const [k, v] of Object.entries(query || {})) if (v != null && v !== "") url.searchParams.set(k, String(v));
const headers = { Accept: "application/json", "X-Streamline-Client": CLIENT };
const token = bearer(auth);
if (token) headers.Authorization = `Bearer ${token}`;
if (body !== undefined) headers["Content-Type"] = "application/json";
let res;
try {
res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "error" });
} catch (err) {
throw new CliError(`连不上 ${apiBase()}:${err.cause?.code || err.message}`, "确认在公司内网 / VPN 上");
}
const text = await res.text();
let data;
try { data = text ? JSON.parse(text) : {}; } catch { data = { error: text.slice(0, 300) }; }
if (!res.ok) {
const msg = `${res.status} ${data.error || res.statusText}${data.code ? ` (${data.code})` : ""}`;
if (res.status === 401 && auth === "session") throw new CliError(msg, "登录已失效,运行 streamline auth login");
if (Array.isArray(data.active) && data.active.length)
throw new CliError(msg, `进行中的:${data.active.map((v) => `${v.title} ${v.panelUrl}`).join(";")}`);
throw new CliError(msg);
}
return data;
}
+110
View File
@@ -0,0 +1,110 @@
// 把包里的 skill/ 装给本机的 Agent:Claude Code、Codex、Cursor。
//
// 用户级(默认):正本放 ~/.agents/skills/<name>,再从各 Agent 的 skills 目录软链过去 ——
// 和 `npx skills` 等安装器的约定一致,升级时只换正本,几个 Agent 同时生效。
// 项目级(--project):直接拷进仓库里各 Agent 的目录。仓库会被别人 clone,指向本人 home 的
// 软链在别人机器上是断的,所以这里不用软链。
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { CliError } from "./http.js";
export const SKILL_NAME = "streamline-openapi";
const SRC = join(dirname(fileURLToPath(import.meta.url)), "..", "skill");
const home = homedir();
/** 各 Agent 的用户级 skills 目录;`root` 存在才算装了这个 Agent。 */
const AGENTS = {
claude: { label: "Claude Code", root: join(home, ".claude"), skills: join(home, ".claude", "skills"), project: ".claude/skills" },
codex: {
label: "Codex", root: process.env.CODEX_HOME || join(home, ".codex"),
skills: join(process.env.CODEX_HOME || join(home, ".codex"), "skills"), project: ".codex/skills",
},
cursor: { label: "Cursor", root: join(home, ".cursor"), skills: join(home, ".cursor", "skills"), project: ".cursor/skills" },
};
const CANONICAL = join(home, ".agents", "skills", SKILL_NAME);
function pickAgents(flag) {
if (typeof flag === "string" && flag !== "auto") {
const names = flag === "all" ? Object.keys(AGENTS) : flag.split(",").map((s) => s.trim()).filter(Boolean);
const bad = names.filter((n) => !AGENTS[n]);
if (bad.length) throw new CliError(`不认识的 Agent:${bad.join(", ")}`, "可选 claude、codex、cursor、all");
return names;
}
const found = Object.keys(AGENTS).filter((n) => existsSync(AGENTS[n].root));
// 一个都没检测到时至少装给 Claude Code,免得什么都没发生。
return found.length ? found : ["claude"];
}
/** 路径上有没有东西(含断掉的软链,existsSync 对它返回 false)。 */
function present(path) {
try { lstatSync(path); return true; } catch { return false; }
}
/** 删掉路径上的东西。rmSync(force) 会把断掉的软链当成不存在而跳过,所以软链单独 unlink。 */
function remove(path) {
if (!present(path)) return;
if (lstatSync(path).isSymbolicLink()) unlinkSync(path);
else rmSync(path, { recursive: true, force: true });
}
/** 目标位置上已有的东西是不是我们装的(软链,或含同名 SKILL.md 的目录)——只覆盖自己的。 */
function ours(path) {
if (!present(path)) return true;
const st = lstatSync(path);
if (st.isSymbolicLink()) return true;
if (!st.isDirectory()) return false;
try { return /^name:\s*streamline-openapi\s*$/m.test(readFileSync(join(path, "SKILL.md"), "utf8")); } catch { return false; }
}
function place(target, linkTo) {
if (!ours(target)) throw new CliError(`${target} 已存在且不是本 Skill,没有覆盖`, "确认后手动删除再重试");
const existed = present(target);
remove(target);
mkdirSync(dirname(target), { recursive: true });
if (linkTo) {
try {
// 相对路径要按真实目录算:skills 目录本身可能是软链(如 $CODEX_HOME/skills → ~/.codex/skills),
// 按字面路径算出来的 ../.. 落到真实目录里就多跳了几层,链接是断的。
symlinkSync(relative(realpathSync(dirname(target)), realpathSync(linkTo)), target, "dir");
if (!existsSync(join(target, "SKILL.md"))) throw new Error("dangling");
return { path: target, mode: "symlink", updated: existed };
} catch {
// 不支持软链(如 Windows 无权限)或链接没指对,就退回拷贝。
remove(target);
}
}
cpSync(linkTo || SRC, target, { recursive: true });
return { path: target, mode: "copy", updated: existed };
}
export function install(flags = {}) {
const agents = pickAgents(flags.agent);
let results;
if (typeof flags.dir === "string") {
results = [{ agent: "custom", ...place(join(resolve(flags.dir), SKILL_NAME), null) }];
} else if (flags.project) {
results = agents.map((a) => ({ agent: a, ...place(join(process.cwd(), AGENTS[a].project, SKILL_NAME), null) }));
} else {
remove(CANONICAL);
mkdirSync(dirname(CANONICAL), { recursive: true });
cpSync(SRC, CANONICAL, { recursive: true });
results = agents.map((a) => ({ agent: a, ...place(join(AGENTS[a].skills, SKILL_NAME), CANONICAL) }));
}
for (const r of results) process.stderr.write(`${r.updated ? "已更新" : "已安装"} ${AGENTS[r.agent]?.label ?? "Skill"}:${r.path}\n`);
process.stderr.write("新开一个 Agent 会话即可生效。下一步:streamline auth login\n");
return { installed: true, skill: SKILL_NAME, canonical: flags.dir || flags.project ? null : CANONICAL, targets: results };
}
export function uninstall(flags = {}) {
const agents = typeof flags.agent === "string" ? pickAgents(flags.agent) : Object.keys(AGENTS);
const removed = [];
const base = flags.project ? (a) => join(process.cwd(), AGENTS[a].project, SKILL_NAME) : (a) => join(AGENTS[a].skills, SKILL_NAME);
for (const a of agents) {
const p = base(a);
if (present(p) && ours(p)) { remove(p); removed.push(p); }
}
if (!flags.project && !flags.agent && present(CANONICAL)) { remove(CANONICAL); removed.push(CANONICAL); }
return { uninstalled: true, removed };
}
+68
View File
@@ -0,0 +1,68 @@
// 浏览器 SSO 登录:本机 127.0.0.1 临时端口收回调 + PKCE(S256),和控制面 openapi_cli_sso.ts 是一份契约的两端。
// 浏览器回调只带一次性授权码,SSO 的 cookie / session 从不经过命令行。
import { createHash, randomBytes } from "node:crypto";
import { createServer } from "node:http";
import { spawn } from "node:child_process";
import { call } from "./http.js";
import { save, webBase } from "./store.js";
export const CALLBACK_PATH = "/streamline/sso/callback";
const WAIT_MS = 5 * 60 * 1000;
const b64 = (buf) => buf.toString("base64url");
function openBrowser(url) {
const [cmd, args] = process.platform === "darwin" ? ["open", [url]]
: process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
: ["xdg-open", [url]];
try {
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
child.on("error", () => {});
child.unref();
} catch { /* 打不开就让用户自己点下面打印的链接 */ }
}
const page = (title, msg) => `<!doctype html><meta charset="utf-8"><title>${title}</title>
<body style="font:15px -apple-system,system-ui,sans-serif;max-width:420px;margin:15vh auto;text-align:center">
<h2>${title}</h2><p>${msg}</p><script>history.replaceState(null,"",location.pathname)</script></body>`;
export async function login({ openBrowser: shouldOpen = true } = {}) {
const state = b64(randomBytes(32));
const verifier = b64(randomBytes(32));
const challenge = b64(createHash("sha256").update(verifier).digest());
let settle;
const result = new Promise((resolve, reject) => { settle = { resolve, reject }; });
const server = createServer((req, res) => {
const u = new URL(req.url, "http://127.0.0.1");
if (u.pathname !== CALLBACK_PATH) { res.writeHead(404).end(); return; }
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("Referrer-Policy", "no-referrer");
res.setHeader("Cache-Control", "no-store");
if (u.searchParams.get("state") !== state || !u.searchParams.get("code")) {
res.writeHead(400).end(page("登录失败", "回调不匹配,请回到终端重新执行 streamline auth login。"));
return;
}
res.writeHead(200).end(page("已授权", "可以关闭这个页面,回到终端继续。"));
settle.resolve(u.searchParams.get("code"));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const redirectUri = `http://127.0.0.1:${server.address().port}${CALLBACK_PATH}`;
const authUrl = new URL(webBase() + "/cli/connect");
authUrl.searchParams.set("redirect_uri", redirectUri);
authUrl.searchParams.set("state", state);
authUrl.searchParams.set("code_challenge", challenge);
authUrl.searchParams.set("code_challenge_method", "S256");
process.stderr.write(`在浏览器里完成授权(5 分钟内有效):\n ${authUrl.href}\n`);
if (shouldOpen) openBrowser(authUrl.href);
const timer = setTimeout(() => settle.reject(new Error("等待浏览器授权超时,请重新执行 streamline auth login")), WAIT_MS);
let code;
try { code = await result; } finally { clearTimeout(timer); server.close(); }
const token = await call("POST", "/api/openapi-cli/auth/token", {
body: { code, code_verifier: verifier, redirect_uri: redirectUri },
});
save((rec) => ({ ...rec, session: { token: token.access_token, email: token.email, expiresAt: token.expires_at } }));
return { email: token.email, expiresAt: token.expires_at };
}
+54
View File
@@ -0,0 +1,54 @@
// 本机凭据:~/.config/streamline/credentials.json(目录 0700、文件 0600,先写临时文件再改名)。
// 按 API 地址分开存,同一台电脑可以同时连生产和自建环境。
// 里面有登录会话的明文 —— 命令的输出里永远不打印它。
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export const DEFAULT_API = "https://streamline-internal-api.bytedance.net";
export const DEFAULT_WEB = "https://streamline.bytedance.net";
export function apiBase() {
return (process.env.STREAMLINE_API_URL || DEFAULT_API).replace(/\/+$/, "");
}
export function webBase() {
return (process.env.STREAMLINE_WEB_URL || DEFAULT_WEB).replace(/\/+$/, "");
}
function dir() {
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
return join(base, "streamline");
}
function file() {
return join(dir(), "credentials.json");
}
function readAll() {
if (!existsSync(file())) return {};
try { return JSON.parse(readFileSync(file(), "utf8")) || {}; } catch { return {}; }
}
function writeAll(all) {
mkdirSync(dir(), { recursive: true, mode: 0o700 });
chmodSync(dir(), 0o700);
const tmp = `${file()}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
renameSync(tmp, file());
}
/** 当前 API 地址下的记录:{ session?: {token,email,expiresAt} }(老版本存过的 keys 字段不再使用,原样留着无害)。 */
export function load() {
return readAll()[apiBase()] || {};
}
export function save(update) {
const all = readAll();
all[apiBase()] = update(all[apiBase()] || {});
writeAll(all);
}
export function credentialsPath() {
return file();
}
+89
View File
@@ -0,0 +1,89 @@
// 改动验证:本地分支改完、推上去之后,让 Streamline 从这个提交编译出包、在真机上按用例执行、交付报告。
// 这里做两件事:解析用例文件;确认被测提交已经在远端(平台只能拿到推上去的代码)。
import { execFileSync } from "node:child_process";
import { CliError } from "./http.js";
function git(args) {
try {
return execFileSync("git", args, { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
} catch { return null; }
}
/**
* 被测提交:当前目录的 HEAD。要求工作区干净、且这个提交已经推到远端 —— 否则平台验的不是用户以为的代码。
* 用本地记录的远端引用判断(推送时会更新),不额外联网;节点检出时还会再从远端核对一次。
*/
export function changeUnderTest({ allowDirty = false } = {}) {
if (git(["rev-parse", "--is-inside-work-tree"]) !== "true") throw new CliError("当前目录不是 git 仓库", "在被测代码所在的仓库目录里执行");
const commit = git(["rev-parse", "HEAD"]);
if (!commit) throw new CliError("读不到当前提交");
let branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
if (branch === "HEAD") branch = null;
const dirty = git(["status", "--porcelain", "--untracked-files=no"]);
if (dirty && !allowDirty) {
throw new CliError("有还没提交的改动:平台只能验证已经推送的提交,这些改动不会被验证",
"先 commit 并 push;确实只想验证已推送的部分,加 --allow-dirty");
}
// 以「有没有远端分支包含这个提交」为准,而不是和上游比:从 develop 拉出的分支上游常常就是
// origin/develop,比它领先是正常的,提交其实早就推到了自己的远端分支上。
const onRemote = !!git(["branch", "-r", "--contains", "HEAD"]);
if (!onRemote) {
throw new CliError("当前提交还不在任何远端分支上(以本地记录的远端分支为准)",
branch ? `先推送:git push -u origin ${branch}(推过了的话先 git fetch 再试)` : "先把这个提交推到远端分支");
}
const remote = git(["remote", "get-url", "origin"]);
return { commit, branch, repo: remote ? remote.replace(/\/\/[^@/]+@/, "//") : null };
}
/**
* 用例文件(模板在 skill/SKILL.md):
* ## 背景 改了什么、原本要解决什么
* ## 用例
* ### <用例标题>
* 前置:… (可多行)
* 步骤:… (可多行)
* 检查点:
* - 预期 1
* - 预期 2
*/
export function parseVerifyCases(markdown) {
let background = [];
const cases = [];
let section = null, cur = null, field = null;
for (const raw of markdown.split(/\r?\n/)) {
const line = raw.replace(/\s+$/, "");
const h2 = line.match(/^##\s+(.+)$/);
if (h2) {
const name = h2[1].trim();
section = /背景|background/i.test(name) ? "bg" : /用例|cases?/i.test(name) ? "cases" : null;
cur = null; field = null;
continue;
}
if (section === "bg") { background.push(line); continue; }
if (section !== "cases") continue;
const h3 = line.match(/^###\s+(.+)$/);
if (h3) { cur = { title: h3[1].trim(), pre: [], step: [], checkpoints: [] }; cases.push(cur); field = null; continue; }
if (!cur) continue;
const label = line.match(/^\s*(前置(?:条件)?|步骤|操作步骤|检查点|预期)\s*[::]\s*(.*)$/);
if (label) {
field = /前置/.test(label[1]) ? "pre" : /步骤/.test(label[1]) ? "step" : "checkpoints";
if (label[2]) (field === "checkpoints" ? cur.checkpoints : cur[field]).push(label[2]);
continue;
}
if (!field || !line.trim()) continue;
if (field === "checkpoints") {
const bullet = line.match(/^\s*(?:[-*]|\d+[.)、])\s+(.*)$/);
if (bullet) cur.checkpoints.push(bullet[1]);
else if (cur.checkpoints.length) cur.checkpoints[cur.checkpoints.length - 1] += ` ${line.trim()}`;
} else {
cur[field].push(line);
}
}
if (!cases.length) throw new CliError("用例文件里没有用例", "在「## 用例」下面用「### 用例标题」开始每一条,按 Skill 里的模板写");
const empty = cases.find((c) => !c.checkpoints.length);
if (empty) throw new CliError(`用例「${empty.title}」没有检查点`, "每条用例在「检查点:」下面用「- 」列出要看到的结果");
return {
background: background.join("\n").trim(),
cases: cases.map((c) => ({ title: c.title, pre: c.pre.join("\n").trim() || null, step: c.step.join("\n").trim() || null, checkpoints: c.checkpoints.map((x) => x.trim()) })),
};
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "@byted/streamline-skill",
"version": "0.6.0",
"description": "Streamline 的命令行 + Agent Skill(Claude Code / Codex / Cursor):SSO 登录后以本人身份提单、查进展、确认执行",
"type": "module",
"bin": {
"streamline": "bin/streamline.js"
},
"files": [
"bin",
"lib",
"skill",
"README.md"
],
"engines": {
"node": ">=18"
},
"publishConfig": {
"registry": "https://bnpm.byted.org"
},
"license": "UNLICENSED"
}
+105
View File
@@ -0,0 +1,105 @@
---
name: streamline-openapi
description: 提 bug / 导入 Meego 单让 Streamline 在真机上自动修、把本地调研交给 Streamline 接力修、查进展、确认执行。Use when the user wants to 把 bug 提给 Streamline、导入 Meego 单、剩下的交给 Streamline 修、查 Streamline 任务进展、确认执行,or mentions streamline / streamline.bytedance.net 任务链接。
---
# Streamline
Streamline 是在真机上复现、修复缺陷的平台:导入或描述一个 bug,它在真机上复现、起草测试方案、修好后提 MR;本地调研了一半的 bug 也可以交给它接着修。
**本地改动的真机验证(`streamline verify`)暂时下线。** 用户要「在真机上验证一下这个分支」时,如实告诉他这项能力暂不开放,不要调用 `streamline verify`,也不要拿提单、接力绕过去。
所有操作通过本机的 `streamline` 命令完成,**以用户本人的身份**(和他在面板上操作一样)。结果以 JSON 输出到 stdout;出错时 stderr 是 `{"error", "hint"}`,按 hint 做下一步。
如果 `streamline` 命令不存在,先安装:
```sh
npm i -g @byted/streamline-skill --registry=https://bnpm.byted.org
```
`streamline` 要访问公司内网(`streamline-internal-api.bytedance.net`)并读写 `~/.config/streamline/`。如果命令因为沙箱拦了网络或文件写入而失败(Codex、Cursor 的默认沙箱都可能这样),按你所在 Agent 的方式申请在沙箱外执行这条命令,不要改用别的办法绕过。
## 先确认已登录
```sh
streamline auth status
```
没登录就执行 `streamline auth login`:会打开浏览器,用户在 Streamline 页面上点「授权」后命令才返回(最长等 5 分钟)。**调用时把超时设到 5 分钟以上,或放到后台跑**,并告诉用户去浏览器里点授权。
## 提单
```sh
# 从 Meego 工单导入:标题、描述、复现步骤都从工单里取;同一个工单导入过会返回已有任务。
streamline task import "https://meego.bytedance.com/…"
# 直接描述一个 bug:标题和描述必填,平台尽量给。
streamline task create --title "…" --description "…" --platform android --repro "1. …"
```
- 提单会真的在平台上建任务。执行前把标题、描述、平台给用户确认一遍;信息不够(尤其是复现步骤)先问用户,不要编。
- `--watchers a,b`:额外接收通知的人或群(邮箱前缀、完整邮箱、`oc_` 群、`ou_` 个人)。用户本人自动接收,不用加。
- 把返回的 `panelUrl` 给用户。
## 接力:把这次会话里的调研交给 Streamline 修
用户在当前会话里已经调研过某个 bug(看过日志、读过代码、有了初步结论),想让 Streamline 接着在真机上复现、修复、提 MR 时用这个。Streamline 是异步的:交过去就可以去干别的,之后用 `task get` 看进展。
1. **从当前会话里整理一份总结**,按下面的模板写进一个临时文件(如 `/tmp/streamline-handoff.md`)。只写这个 bug 相关的内容:
```markdown
## 现象
用户实际看到了什么(界面 / 行为 / 报错),在哪个页面、什么条件下。
## 复现步骤
1. …(写到能在真机上照着走;不确定的步骤标出来)
## 已确认的事实
- 每条都附证据:日志或堆栈片段、代码位置(文件 + 函数名)、截图路径。只写亲眼看到的,不写推测。
## 怀疑点
- 位置(文件 + 函数名):为什么怀疑它;把握:高 / 中 / 低
## 已排除
- 查过、确认不是原因的方向,以及为什么。
## 建议修法(可选)
- 如果有想法,写思路,不必写代码。
```
2. **写的时候分清事实和推测。** Streamline 会把整份总结当作重要线索,但会在真机上重新验证每一条;写成事实的推测一旦被推翻,反而会误导它。不要放密钥、Token、账号口令或与 bug 无关的个人信息。
3. **把总结和标题给用户看一遍,确认后再提交:**
```sh
streamline task handoff --title "…" --platform android --file /tmp/streamline-handoff.md
```
默认会附上当前目录所在仓库的分支和提交号(`--no-git` 不附)。在 bug 所在的代码仓目录里执行最好。
4. 把返回的 `panelUrl` 给用户,并说明:Streamline 会先自己复现、核实这些线索,再起草测试方案,起草完需要确认执行(`streamline task execute`)。
## 查进展
```sh
streamline task list --limit 10 # 用户自己建的单,新的在前
streamline task get <taskId> # 任意一条单;用户给的面板链接里 task_id= 后面就是 taskId
```
用 `statusLabel`(中文状态)回答;有 `mrUrl` 时一起给出。
## 确认执行
新建的任务先由评估器起草测试方案(`initializing`),起草完进入 `pending_confirmation`,等人确认后才开始修。用户明确要求开始修复时:
```sh
streamline task execute <taskId>
```
- 只能确认用户**自己建的**单;别人的单返回 403,让用户去面板上操作。
- 409 按 `error` 的文字告诉用户:还在起草就稍后再试;信息不足要人补充;已在执行就不用再调。
- 确认前最好让用户在面板上看一眼测试方案(给 `panelUrl`)。
## 规矩
- 不要读取、打印或转述 `~/.config/streamline/credentials.json`。
- 不要轮询、不要循环调用:平台在关键节点会飞书通知用户,用户问的时候才查一次。每次建单都会占用真机和编译资源,不要因为没等到结果就重复提交。
- 用户想让**自己的系统**(服务端程序、机器人)接入 Streamline,那是 API Key 的场景,不在这个 Skill 里办:让他去面板头像菜单「开放平台 API」申请,并看接入文档 https://bytedance.us.larkoffice.com/docx/XUaCdOE7Uo0jOZxaBZbu3Hy8sSf