172 lines
7.4 KiB
TypeScript
172 lines
7.4 KiB
TypeScript
/**
|
||
* `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));
|