From 97bf3301a379f88817c6e48db66e586ca8dd358e Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:16:12 +0800 Subject: [PATCH] Keep `seal-use probe`'s stdout to a single JSON document MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `runProbe` wrote its progress notes and three separate JSON blobs to stdout, so every consumer parsing the output — `seal-use probe | jq`, the Agent Harness — got prose interleaved with data. The command is also in the help registry, so this was a documented command breaking its own contract. The probe now returns one `ProbeResult` and the command prints it through `printJson`; the `[probe] …` narration moves to stderr, which is the diagnostics channel. The dev-script entry point keeps the same payload and its exit code. Classified read-only too: `probe` reads tenant state and writes nothing, but the allow-list had no entry, so the MCP read-only tool refused it. Its trailing token is an enterprise selector rather than a verb, so the matcher accepts the bare form and bare-plus-selector while still refusing a third token. --- src/cli/commands/probe.ts | 4 +- src/cli/read-only.test.ts | 8 +++ src/cli/read-only.ts | 13 ++++ src/probe.test.ts | 124 ++++++++++++++++++++++++++++++++++++++ src/probe.ts | 60 ++++++++++++------ 5 files changed, 190 insertions(+), 19 deletions(-) create mode 100644 src/probe.test.ts diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts index 4432061..4b2b3f8 100644 --- a/src/cli/commands/probe.ts +++ b/src/cli/commands/probe.ts @@ -1,8 +1,10 @@ import { runProbe } from "../../probe.js"; import { stringOption } from "../parser.js"; +import { printJson } from "../printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined); - await runProbe({ corpId }); + // One JSON document on stdout; runProbe narrates progress on stderr only. + printJson(await runProbe({ corpId })); } diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index 806dd1b..1085410 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -128,6 +128,14 @@ describe("CLI read-only classification", () => { expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false); }); + test("probe is read-only bare or with its enterprise selector, but not beyond", () => { + // `seal-use probe []` takes a selector, not a verb: the allow-list + // entry covers the bare form and the selector form is matched separately. + expect(isReadOnlyCliCommand(["probe"])).toBe(true); + expect(isReadOnlyCliCommand(["probe", "corp-a"])).toBe(true); + expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false); + }); + test("refuses command lines that cannot be parsed", () => { expect(isReadOnlyCliCommand(["--json"])).toBe(false); }); diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index 474d02b..a5e17e9 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -81,9 +81,20 @@ const READ_ONLY_COMMANDS: Record = { skill: ["dump", "status"], service: ["status", "logs"], doctor: ["", "guide", "paths", "tenant", "auth"], + // Bare form only; the optional trailing `` selector is handled by + // SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens. + probe: [""], openapi: [""] }; +/** + * Areas whose trailing positional is an enterprise selector, not a subcommand: + * `seal-use probe []` has no verb to list, so its read form is the bare + * command plus at most that one selector. A second token is not a form the area + * accepts at all, and falls through to the refusal below. + */ +const SELECTOR_POSITIONAL_AREAS = new Set(["probe"]); + /** * Read-only commands handled by the CLI outside the help registry (no area/subcommand shape). * `help` is limited to the bare form on purpose: `help ` adds nothing over the skill docs. @@ -110,6 +121,8 @@ export function isReadOnlyCliCommand(argv: string[]): boolean { } if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true; + // The `` selector form; the bare form falls through to the `""` entry. + if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true; const allowed = READ_ONLY_COMMANDS[area]; if (!allowed) return false; diff --git a/src/probe.test.ts b/src/probe.test.ts new file mode 100644 index 0000000..e0165a3 --- /dev/null +++ b/src/probe.test.ts @@ -0,0 +1,124 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runCli } from "./cli/runner.js"; + +const ENV_KEYS = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_DISABLE_BG_UPDATE"] as const; +const ORIGINAL_ENV: Record = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); +const ORIGINAL_FETCH = globalThis.fetch; +const tempDirs: string[] = []; + +afterEach(() => { + globalThis.fetch = ORIGINAL_FETCH; + for (const key of ENV_KEYS) { + if (ORIGINAL_ENV[key] === undefined) delete process.env[key]; + else process.env[key] = ORIGINAL_ENV[key]!; + } + for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function makeProbeEnv(corpId = "demo-corp"): string { + const dir = mkdtempSync(join(tmpdir(), "seal-use-probe-test-")); + tempDirs.push(dir); + writeFileSync( + join(dir, `${corpId}.json`), + JSON.stringify({ + id: corpId, + name: "Demo Corp", + source: { type: "seal", token: "seal-token", sealUrl: `https://${corpId}.sealai.cc` } + }) + ); + + process.env.SEAL_USE_ENTERPRISES_DIR = dir; + process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json"); + process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json"); + process.env.SEAL_DISABLE_BG_UPDATE = "1"; + return dir; +} + +type Route = (url: string) => Response | undefined; + +/** Routes the four upstream calls a probe makes; unhandled URLs fail loudly. */ +function mockSealApi(route: Route): void { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = input instanceof Request ? input.url : String(input); + const response = route(url); + if (!response) throw new Error(`probe test received an unexpected request: ${url}`); + return response; + }) as typeof fetch; +} + +function json(payload: unknown, status = 200): Response { + return new Response(JSON.stringify(payload), { + status, + headers: { "Content-Type": "application/json" } + }); +} + +function okApi(): Route { + return (url) => { + if (url.includes("/api/v1/auth/me")) { + return json({ + user: { id: "user-1", tenantId: "tenant-1", name: "Tester" }, + tenant: { id: "tenant-1", name: "Demo Tenant" } + }); + } + if (url.includes("/api/v1/rules")) { + return json({ + rules: [{ id: "rule-1", description: "差旅报销规则", scope: "travel", strictness: "MUST_FOLLOW" }], + hasPendingDeletes: false + }); + } + if (url.includes("/api/v1/knowledge/articles")) return json({ articles: [], total: 0 }); + if (url.includes("/api/v1/agent/ai-approval/config")) return json({ tone: "precise" }); + return undefined; + }; +} + +describe("seal-use probe stream contract", () => { + test("writes exactly one JSON document to stdout and narrates on stderr", async () => { + makeProbeEnv(); + mockSealApi(okApi()); + + const result = await runCli(["probe", "demo-corp"]); + + expect(result.exitCode).toBe(0); + // The whole contract: if the [probe] prose still reached stdout, this + // parse would throw instead of yielding the payload. + const payload = JSON.parse(result.stdout) as Record; + expect(result.stdout).not.toContain("[probe]"); + + expect(payload.corp).toEqual({ id: "demo-corp", name: "Demo Corp", sourceType: "seal" }); + expect(payload.enterprise).toMatchObject({ + provider: "seal", + sealUrl: "https://demo-corp.sealai.cc", + tenantName: "Demo Tenant" + }); + expect(payload.summary).toEqual({ + rules: 1, + hasPendingRuleDeletes: false, + documents: 0, + documentsTotal: 0, + stylePreferences: "ok" + }); + + expect(result.stderr).toContain("[probe] corp=demo-corp source=seal"); + expect(result.stderr).toContain("[probe] approval context summary"); + }); + + test("reports a failing style-preferences endpoint in the payload instead of throwing", async () => { + makeProbeEnv(); + mockSealApi((url) => { + const ok = okApi()(url); + return url.includes("/api/v1/agent/ai-approval/config") ? json({ error: "upstream broke" }, 500) : ok; + }); + + const result = await runCli(["probe", "demo-corp"]); + + expect(result.exitCode).toBe(0); + const payload = JSON.parse(result.stdout) as Record; + expect(payload.summary.stylePreferences).toContain("error:"); + expect(payload.summary.rules).toBe(1); + }); +}); diff --git a/src/probe.ts b/src/probe.ts index f8b7505..faf57a7 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -1,10 +1,25 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js"; import { resolveCorpConfig } from "./core/config/manager.js"; import { createSealClient } from "./core/http/factory.js"; +import type { SealEnterpriseConfig } from "./core/auth/types.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { getApprovalContext } from "./domains/seal/api.js"; +import { printJson } from "./cli/printer.js"; -export async function runProbe(options: { corpId?: string } = {}) { +/** One probe run's payload — the entire stdout of `seal-use probe`. */ +export type ProbeResult = { + corp: { id: string; name: string; sourceType: string }; + enterprise: SealEnterpriseConfig; + summary: { + rules: number; + hasPendingRuleDeletes: boolean; + documents: number; + documentsTotal?: number; + stylePreferences: string; + }; +}; + +export async function runProbe(options: { corpId?: string } = {}): Promise { const corps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); const corp = resolveCorpConfig( @@ -17,11 +32,13 @@ export async function runProbe(options: { corpId?: string } = {}) { getEnterprisesDirCandidates() ); - console.log(`[probe] corp=${corp.id} source=${corp.source.type}`); + // Progress notes go to stderr: stdout carries the JSON payload alone, so + // `seal-use probe | jq` keeps working (it previously held three prose lines + // interleaved with three JSON blobs). + console.error(`[probe] corp=${corp.id} source=${corp.source.type}`); const enterprise = await resolveLiveSealEnterpriseConfig(corp); - console.log("[probe] seal enterprise"); - console.log(JSON.stringify(enterprise, null, 2)); + console.error("[probe] seal enterprise"); const client = await createSealClient(corp); const context = await getApprovalContext(client, { @@ -29,23 +46,30 @@ export async function runProbe(options: { corpId?: string } = {}) { stylePreferencesEndpoint: corp.seal.endpoints.approvalStylePreferences }); - console.log("[probe] approval context summary"); - console.log(JSON.stringify({ - rules: context.rules.rules.length, - hasPendingRuleDeletes: context.rules.hasPendingDeletes, - documents: context.documents.articles.length, - documentsTotal: context.documents.total, - stylePreferences: context.stylePreferences.ok - ? "ok" - : `error: ${context.stylePreferences.error}` - }, null, 2)); + console.error("[probe] approval context summary"); + + return { + corp: { id: corp.id, name: corp.name, sourceType: corp.source.type }, + enterprise, + summary: { + rules: context.rules.rules.length, + hasPendingRuleDeletes: context.rules.hasPendingDeletes, + documents: context.documents.articles.length, + documentsTotal: context.documents.total, + stylePreferences: context.stylePreferences.ok + ? "ok" + : `error: ${context.stylePreferences.error}` + } + }; } if (import.meta.main) { const args = process.argv.slice(2); const corpId = args[0] === "--corp" ? args[1] : args[0]; - runProbe({ corpId }).catch((error) => { - console.error(error instanceof Error ? error.message : error); - process.exit(1); - }); + runProbe({ corpId }) + .then((result) => printJson(result)) + .catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); + }); }