Files
streamline/openapi-skill/lib/http.js
T
2026-11-16 17:26:44 -08:00

67 lines
2.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}