Files
hose-use/src/cli/commands/context.ts
T
gitea b787130880 feat(agent): 增强开放平台文档自省与端点检索引导
- 规约硬化:在 SKILL.md 新增第 18 条执行原则,严禁 Agent 盲目翻找源码或用脚本暴力解析底层 specs JSON,确立 hose-use docs search/show 为唯一合法第一入口;
- 参考专卷:新增 skills/hose-use/references/docs.md,系统阐述 4 大文档子命令、加权搜索机制与售前方案调研 SOP;
- 内嵌打包:在 src/packaging/embedded-skill.ts 注册 references/docs.md,确保二进制与全局 Skill 分发无遗漏;
- 上下文自省:在 hose-use context (及 --json) 注入开放平台文档库就绪指标 (330 篇文档 / 279 个端点),并在诊断提示中显式引导 docs search 用法;
- 架构总纲:在 AGENTS.md 登记 docs 领域说明与零原始 JSON 侵入原则。
2026-11-17 14:29:50 +08:00

187 lines
8.3 KiB
TypeScript

import { getActiveAccount } from "../../core/auth/account-store.js";
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
import {
resolveGlobalConfigFile,
resolvePrimaryEnterprisesDir,
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { ApprovalRepository } from "../../domains/approval/index.js";
import { getDocsCatalog } from "../../domains/docs/tools.js";
import { VERSION } from "../../version.js";
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { handleWhoami } from "./corps/whoami.js";
export async function handleContextCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
// `whoami` 输出按企业逐一列出当前执行身份;`context/status` 保留全局诊断。
const invoked = (parsed.raw ?? []).find((arg) => !arg.startsWith("-"));
if (invoked?.toLowerCase() === "whoami") {
return handleWhoami(parsed, runtime);
}
const currentCorp = runtime.selectedCorp;
const allCorps = runtime.corpContext.listCorps();
const activeAccount = getActiveAccount();
const isStateful = runtime.corpContext.isStateful();
const configFile = resolveGlobalConfigFile();
const enterprisesDir = resolvePrimaryEnterprisesDir() || resolveWritableEnterprisesDir();
let scopesCount = 0;
let rulesCount = 0;
let scopes: Array<{ index: number; scope: string; ruleCount: number }> = [];
let totalRunsCount = 0;
let pendingRunsCount = 0;
try {
const repo = new ApprovalRepository();
const loadedScopes = repo.listScopes("active");
scopesCount = loadedScopes.length;
scopes = loadedScopes.map((s) => ({
index: s.index,
scope: s.scope,
ruleCount: s.ruleCount,
}));
const loadedRules = repo.listRules();
rulesCount = loadedRules.length;
const runs = currentCorp?.id ? repo.listRuns({ corpId: currentCorp.id }) : repo.listRuns();
totalRunsCount = runs.length;
pendingRunsCount = runs.filter((r) => r.decision === "PENDING").length;
} catch {
// 容错处理(如 SQLite 尚未初始化等场景)
}
let docsStats = { totalDocs: 0, totalEndpoints: 0, ready: false };
try {
const catalog = await getDocsCatalog();
docsStats = {
totalDocs: catalog.totalDocs,
totalEndpoints: catalog.totalEndpoints,
ready: true,
};
} catch {
// 容错处理
}
const now = Date.now();
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
const currentPersistent = currentCorp ? canRefreshCorpAccessToken(currentCorp) : false;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
tool: "hose-use",
version: VERSION,
account: activeAccount
? {
accountId: activeAccount.accountId,
userId: activeAccount.userId || null,
corporationCount: activeAccount.corporations.length,
}
: currentCorp?.accountId
? {
accountId: currentCorp.accountId,
userId: null,
corporationCount: allCorps.filter((c) => c.accountId === currentCorp.accountId).length,
}
: null,
activeCorporation: currentCorp
? {
id: currentCorp.id,
name: currentCorp.name,
env: currentCorp.env,
isTest: currentCorp.isTest,
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
source: currentCorp.source,
persistent: currentPersistent,
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
expired: currentPersistent
? false
: (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
: false,
baseUrl: currentCorp.baseUrl,
accountId: currentCorp.accountId || null,
}
: null,
corporationsSummary: {
total: allCorps.length,
validCount: validCorps.length,
expiredCount: expiredCorps.length,
prodCount: allCorps.filter((c) => c.env === "prod").length,
testCount: allCorps.filter((c) => c.env === "test").length,
demoCount: allCorps.filter((c) => c.env === "demo").length,
activeCorpId: currentCorp?.id || null,
},
aiProGateway: {
connectedCorpId: currentCorp?.id || null,
scopesCount,
rulesCount,
scopes,
pendingRunsCount,
totalRunsCount,
},
docsCatalog: docsStats,
runtime: {
mode: isStateful ? "stateful" : "stateless",
configFile,
enterprisesDir,
candidates: getEnterprisesDirCandidates(),
},
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const accountStr = activeAccount?.accountId || currentCorp?.accountId || "-";
const userIdStr = activeAccount?.userId ? ` (用户 ID: ${activeAccount.userId})` : "";
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
const prodCount = allCorps.filter((c) => c.env === "prod").length;
const testCount = allCorps.filter((c) => c.env === "test").length;
const demoCount = allCorps.filter((c) => c.env === "demo").length;
const scopesStr =
scopes.length > 0
? `已加载 ${scopesCount} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ")}),共 ${rulesCount} 条仲裁规则`
: "暂未配置场景规则 (可使用 hose-use rule add 添加)";
const lines = [
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
` 当前活跃账号 : ${accountStr}${userIdStr}`,
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id}) [${formatCorpEnvLabel(currentCorp.env)}]` : "⚠️ 未激活任何企业"}`,
` 当前操作员工 : ${corpStaffId}`,
` 员工真实姓名 : ${corpStaffName}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
` 开放平台接口库: ${docsStats.ready ? `已就绪 (${docsStats.totalDocs} 篇文档 / ${docsStats.totalEndpoints} 个端点,可用 hose-use docs search 检索)` : "未就绪"}`,
` AI PRO 规约库 : ${scopesStr}`,
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
` 全局配置文件 : ${configFile}`,
` 企业凭证目录 : ${enterprisesDir}`,
"",
"提示:",
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
" - 调研合思开放接口与参数规范: hose-use docs search <关键词> 或 hose-use docs show <Path>",
" - 切换全局默认企业: hose-use corps switch <企业ID>",
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
" - AI PRO 专属上下文: hose-aipro status",
"",
];
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
}