diff --git a/packages/commands/src/commands/text/builtin-tools.ts b/packages/commands/src/commands/text/builtin-tools.ts new file mode 100644 index 000000000..35ffa0c1e --- /dev/null +++ b/packages/commands/src/commands/text/builtin-tools.ts @@ -0,0 +1,285 @@ +import type { ChatRequest, LocalizedText } from "bailian-cli-core"; + +export const BUILTIN_TOOL_NAMES = [ + "web_search", + "web_extractor", + "code_interpreter", + "web_search_image", + "image_search", +] as const; + +export type BuiltinToolName = (typeof BUILTIN_TOOL_NAMES)[number]; + +export type BuiltinChatSupport = "map" | "reject"; + +export interface BuiltinToolSpec { + name: BuiltinToolName; + chat: BuiltinChatSupport; + /** Tools auto-injected on Responses when this tool is selected via --builtin-tool. */ + autoAdd?: readonly BuiltinToolName[]; + requiresImage?: boolean; +} + +export const BUILTIN_TOOL_SPECS: Record = { + web_search: { name: "web_search", chat: "map" }, + web_extractor: { + name: "web_extractor", + chat: "reject", + autoAdd: ["web_search"], + }, + code_interpreter: { name: "code_interpreter", chat: "map" }, + web_search_image: { name: "web_search_image", chat: "reject" }, + image_search: { name: "image_search", chat: "reject", requiresImage: true }, +}; + +const BUILTIN_TOOL_NAME_SET = new Set(BUILTIN_TOOL_NAMES); + +export function isBuiltinToolName(value: string): value is BuiltinToolName { + return BUILTIN_TOOL_NAME_SET.has(value); +} + +/** Deduplicate while preserving first-seen order. */ +export function dedupeBuiltinTools(names: string[] | undefined): BuiltinToolName[] { + if (!names || names.length === 0) return []; + const selected: BuiltinToolName[] = []; + const seen = new Set(); + for (const name of names) { + if (!isBuiltinToolName(name) || seen.has(name)) continue; + seen.add(name); + selected.push(name); + } + return selected; +} + +export function builtinRequiresImage(tools: readonly BuiltinToolName[]): boolean { + return tools.some((toolName) => BUILTIN_TOOL_SPECS[toolName].requiresImage); +} + +export function builtinWantsThinking(tools: readonly BuiltinToolName[]): boolean { + return tools.includes("web_extractor") || tools.includes("code_interpreter"); +} + +function customToolTypes(customTools: Array>): Set { + const types = new Set(); + for (const tool of customTools) { + if (typeof tool.type === "string") types.add(tool.type); + } + return types; +} + +/** + * --tool path does not auto-add companions. Reject bare web_extractor without web_search + * unless --builtin-tool already supplies extractor (which auto-adds search) or search. + */ +export function validateWebExtractorCompanion( + builtinTools: readonly BuiltinToolName[], + customTools: Array>, +): LocalizedText | undefined { + const customTypes = customToolTypes(customTools); + const customHasExtractor = customTypes.has("web_extractor"); + if (!customHasExtractor) return undefined; + + // --builtin-tool web_extractor auto-adds web_search in mergeResponsesTools. + if (builtinTools.includes("web_extractor")) return undefined; + + const hasSearch = builtinTools.includes("web_search") || customTypes.has("web_search"); + if (hasSearch) return undefined; + + return { + "en-US": + '--tool {"type":"web_extractor"} requires an explicit web_search tool (or use --builtin-tool web_extractor, which auto-adds web_search). The --tool path does not auto-add companions.', + "zh-CN": + '--tool {"type":"web_extractor"} 需要同时提供 web_search(或改用 --builtin-tool web_extractor,它会自动补 web_search)。--tool 路径不会自动补齐依赖工具。', + }; +} + +export interface BuiltinToolFlagState { + api: "chat" | "responses"; + builtinTools: BuiltinToolName[]; + enableSearch?: boolean; + enableThinking?: boolean; + batch?: boolean; + prime?: boolean; + hasImageFlag?: boolean; + hasMessagesFile?: boolean; +} + +export function validateBuiltinToolFlags(state: BuiltinToolFlagState): LocalizedText | undefined { + const { api, builtinTools } = state; + if (builtinTools.length === 0) return undefined; + + if (api === "chat") { + for (const toolName of builtinTools) { + if (BUILTIN_TOOL_SPECS[toolName].chat === "reject") { + return { + "en-US": `--builtin-tool ${toolName} requires --api responses.`, + "zh-CN": `--builtin-tool ${toolName} 需要 --api responses。`, + }; + } + } + } + + if (state.batch) { + const disallowed = builtinTools.filter((toolName) => toolName !== "web_search"); + if (disallowed.length > 0) { + return { + "en-US": `--batch only supports --builtin-tool web_search (got ${disallowed.join(", ")}).`, + "zh-CN": `--batch 仅支持 --builtin-tool web_search(收到 ${disallowed.join(", ")})。`, + }; + } + } + + if (state.prime) { + const disallowed = builtinTools.filter( + (toolName) => toolName !== "web_search" && toolName !== "code_interpreter", + ); + if (disallowed.length > 0) { + return { + "en-US": `--prime only supports --builtin-tool web_search or code_interpreter (got ${disallowed.join(", ")}).`, + "zh-CN": `--prime 仅支持 --builtin-tool web_search 或 code_interpreter(收到 ${disallowed.join(", ")})。`, + }; + } + } + + if (api === "chat" && builtinTools.includes("web_search") && state.enableSearch === false) { + return { + "en-US": + "--builtin-tool web_search conflicts with --enable-search false. Remove one of them.", + "zh-CN": "--builtin-tool web_search 与 --enable-search false 冲突。请移除其中一个。", + }; + } + + if ( + api === "chat" && + builtinTools.includes("code_interpreter") && + state.enableThinking === false + ) { + return { + "en-US": + "--builtin-tool code_interpreter conflicts with --enable-thinking false. Code interpreter requires thinking mode.", + "zh-CN": + "--builtin-tool code_interpreter 与 --enable-thinking false 冲突。代码解释器需要思考模式。", + }; + } + + if (api === "chat" && builtinTools.includes("code_interpreter") && state.batch) { + return { + "en-US": + "--builtin-tool code_interpreter requires streaming and cannot combine with --batch.", + "zh-CN": "--builtin-tool code_interpreter 需要流式输出,不能与 --batch 同用。", + }; + } + + if (builtinRequiresImage(builtinTools) && !state.hasImageFlag && !state.hasMessagesFile) { + return { + "en-US": + "--builtin-tool image_search requires --image or a --messages-file that already contains input_image.", + "zh-CN": + "--builtin-tool image_search 需要 --image,或在 --messages-file 中提供含 input_image 的消息。", + }; + } + + return undefined; +} + +export function parseCustomTools( + toolValues: string[] | undefined, + readFile: (path: string) => string, +) { + if (!toolValues || toolValues.length === 0) return [] as Array>; + return toolValues.map((toolValue) => { + try { + return JSON.parse(toolValue) as Record; + } catch { + const raw = readFile(toolValue); + return JSON.parse(raw) as Record; + } + }); +} + +/** + * Merge builtin tool types with custom --tool JSON. + * Builtin entries come first. Only builtin types may be overridden by a custom object + * of the same type; all other custom tools are appended in original order (including + * multiple `{type:"function"}` entries). + * Companion auto-add applies only to --builtin-tool selections, not to --tool. + */ +export function mergeResponsesTools( + builtinTools: readonly BuiltinToolName[], + customTools: Array>, +): Array> { + const expanded: BuiltinToolName[] = []; + const seen = new Set(); + for (const toolName of builtinTools) { + for (const autoAdd of BUILTIN_TOOL_SPECS[toolName].autoAdd ?? []) { + if (!seen.has(autoAdd)) { + seen.add(autoAdd); + expanded.push(autoAdd); + } + } + if (!seen.has(toolName)) { + seen.add(toolName); + expanded.push(toolName); + } + } + + const expandedSet = new Set(expanded); + const customOverrideByBuiltinType = new Map>(); + const passthroughCustomTools: Array> = []; + for (const tool of customTools) { + const toolType = typeof tool.type === "string" ? tool.type : undefined; + // Only consume a custom tool as an override when that builtin was selected + // (or auto-added). Otherwise keep it in original order as passthrough. + if (toolType && isBuiltinToolName(toolType) && expandedSet.has(toolType)) { + customOverrideByBuiltinType.set(toolType, tool); + continue; + } + passthroughCustomTools.push(tool); + } + + const merged: Array> = []; + for (const toolName of expanded) { + const custom = customOverrideByBuiltinType.get(toolName); + merged.push(custom ?? { type: toolName }); + } + merged.push(...passthroughCustomTools); + return merged; +} + +export interface ApplyChatBuiltinResult { + forceStream: boolean; +} + +/** Apply Chat Completions mappings for supported builtin tools. */ +export function applyChatBuiltinTools( + body: ChatRequest, + builtinTools: readonly BuiltinToolName[], + flags: { enableSearch?: boolean; enableThinking?: boolean }, +): ApplyChatBuiltinResult { + let forceStream = false; + + if (builtinTools.includes("web_search") && flags.enableSearch === undefined) { + body.enable_search = true; + } + + if (builtinTools.includes("code_interpreter")) { + body.enable_code_interpreter = true; + forceStream = true; + if (flags.enableThinking === undefined) { + body.enable_thinking = true; + } + } + + return { forceStream }; +} + +/** Ensure Responses thinking defaults for tools that officially recommend it. */ +export function applyResponsesThinkingDefault( + body: { enable_thinking?: boolean }, + builtinTools: readonly BuiltinToolName[], + enableThinking: boolean | undefined, +): void { + if (enableThinking !== undefined) return; + if (!builtinWantsThinking(builtinTools)) return; + body.enable_thinking = true; +} diff --git a/packages/commands/src/commands/text/chat.ts b/packages/commands/src/commands/text/chat.ts index cda5cb32f..ec6a2a47c 100644 --- a/packages/commands/src/commands/text/chat.ts +++ b/packages/commands/src/commands/text/chat.ts @@ -1,5 +1,7 @@ import { buildChatMessages, parseTextMessages, runChatCompletions } from "./run-chat.ts"; import { + BailianError, + ExitCode, defineCommand, resolveBatchChatEndpoint, batchUsage, @@ -19,6 +21,25 @@ import { extractResponsesText, } from "./responses.ts"; import { PRIME_FLAGS, resolvePrimeEndpoint, validatePrimeFlags } from "../shared/prime.ts"; +import { + BUILTIN_TOOL_NAMES, + applyChatBuiltinTools, + applyResponsesThinkingDefault, + builtinRequiresImage, + dedupeBuiltinTools, + mergeResponsesTools, + parseCustomTools, + validateBuiltinToolFlags, + validateWebExtractorCompanion, +} from "./builtin-tools.ts"; +import { + IMAGE_REQUIRES_RESPONSES, + assertImageSearchHasImage, + buildResponsesInput, + redactResponsesInput, + resolvePendingImageUploads, + validateResponsesImageFlags, +} from "./responses-input.ts"; /** Models that enable built-in web search by default on the Chat Completions API. */ const SEARCH_BY_DEFAULT_MODELS = new Set(["qwen3.8-max"]); @@ -86,6 +107,27 @@ const CHAT_FLAGS = { "zh-CN": "启用模型内置联网搜索(仅 Chat Completions API;qwen3.8-max 默认开启)", }, }, + builtinTool: { + type: "array", + // valueHint is required by FlagsDef; help rendering prefers choices when present. + valueHint: "", + choices: BUILTIN_TOOL_NAMES, + description: { + "en-US": + "Built-in model tool (repeatable). Responses: tools[].type; Chat maps web_search/code_interpreter only", + "zh-CN": + "模型内置工具(可重复)。Responses 写入 tools[].type;Chat 仅映射 web_search / code_interpreter", + }, + }, + image: { + type: "array", + valueHint: "", + description: { + "en-US": + "Image for Responses input_image (repeatable; --api responses only; required for image_search)", + "zh-CN": "Responses input_image 图片(可重复;仅 --api responses;image_search 必填)", + }, + }, stream: { type: "switch", description: { @@ -143,6 +185,27 @@ export default defineCommand({ "en-US": `--api responses --model qwen3.8-max --tool '{"type":"web_search"}' --message "Search for recent Alibaba Cloud news"`, "zh-CN": `--api responses --model qwen3.8-max --tool '{"type":"web_search"}' --message "搜索近期的阿里云新闻"`, }, + { + "en-US": + '--api responses --builtin-tool web_extractor --message "Summarize the linked doc" --enable-thinking', + "zh-CN": + '--api responses --builtin-tool web_extractor --message "总结链接文档要点" --enable-thinking', + }, + { + "en-US": + '--api responses --builtin-tool web_search_image --message "Find a tech PPT cover image"', + "zh-CN": '--api responses --builtin-tool web_search_image --message "找一张科技感 PPT 封面"', + }, + { + "en-US": + '--api responses --builtin-tool image_search --image https://example.com/a.png --message "Find similar scenic images"', + "zh-CN": + '--api responses --builtin-tool image_search --image https://example.com/a.png --message "找相似风格风景图"', + }, + { + "en-US": '--builtin-tool code_interpreter --message "Compute 12 cubed"', + "zh-CN": '--builtin-tool code_interpreter --message "计算 12 的 3 次方"', + }, { "en-US": '--model qwen-max --system "You are a coding assistant." --message "Write fizzbuzz in Python"', @@ -200,9 +263,15 @@ export default defineCommand({ }, { "en-US": - '--enable-search maps to the Chat Completions enable_search parameter and requires a model with built-in web search support; whitelisted models (qwen3.8-max) enable it by default unless --enable-search false is passed; for the Responses API use --tool \'{"type":"web_search"}\' instead.', + '--enable-search maps to Chat Completions enable_search and requires a model with built-in web search; whitelisted models (qwen3.8-max) enable it by default unless --enable-search false is passed. Responses: use --builtin-tool web_search or --tool \'{"type":"web_search"}\'.', + "zh-CN": + '--enable-search 映射为 Chat Completions 的 enable_search,需要模型支持内置联网搜索;白名单模型(qwen3.8-max)默认开启,可传 --enable-search false 显式关闭。Responses 请用 --builtin-tool web_search 或 --tool \'{"type":"web_search"}\'。', + }, + { + "en-US": + '--builtin-tool enables Responses tools (web_search, web_extractor, code_interpreter, web_search_image, image_search). Chat only maps web_search→enable_search and code_interpreter→enable_code_interpreter (forced streaming). --builtin-tool web_extractor auto-adds web_search; the --tool path does not auto-add companions—bare --tool {"type":"web_extractor"} requires an explicit web_search (or use --builtin-tool web_extractor). Responses code_interpreter does not require streaming. When --enable-thinking is omitted, Responses web_extractor/code_interpreter and Chat code_interpreter default enable_thinking=true (billable reasoning tokens); pass --enable-thinking false to opt out where the API allows. image_search requires --image (or messages-file input_image) and --api responses. Tool call details appear only in non-streaming --output json; streaming JSON returns { content } only. web_search_image / image_search can be slow—prefer --stream or a higher --timeout. Image shortest side must be >10px (service-enforced). Token Plan connections are unverified for these tools.', "zh-CN": - '--enable-search 映射为 Chat Completions 的 enable_search 参数,需要模型支持内置联网搜索;白名单模型(qwen3.8-max)默认开启,可传 --enable-search false 显式关闭;Responses API 请改用 --tool \'{"type":"web_search"}\'。', + '--builtin-tool 启用 Responses 内置工具(web_search、web_extractor、code_interpreter、web_search_image、image_search)。Chat 仅映射 web_search→enable_search 与 code_interpreter→enable_code_interpreter(强制流式)。--builtin-tool web_extractor 会自动补 web_search;--tool 路径不会自动补齐依赖——单独传 --tool {"type":"web_extractor"} 时必须显式提供 web_search(或改用 --builtin-tool web_extractor)。Responses 的 code_interpreter 不要求流式。未传 --enable-thinking 时,Responses 的 web_extractor/code_interpreter 与 Chat 的 code_interpreter 默认 enable_thinking=true(会产生可计费思考 Token);可在 API 允许时传 --enable-thinking false 关闭。image_search 需要 --image(或 messages-file 内 input_image)且 --api responses。工具调用明细仅在非流式 --output json 中可见;流式 JSON 只返回 { content }。文搜图/图搜图可能较慢,建议 --stream 或增大 --timeout。图片最短边须 >10px(由服务端校验)。Token Plan 连接下这些工具尚未验证。', }, { "en-US": @@ -224,8 +293,35 @@ export default defineCommand({ return "--thinking-budget is not supported by the Responses API."; } if (flags.api === "responses" && flags.enableSearch !== undefined) { - return '--enable-search is not supported by the Responses API; use --tool \'{"type":"web_search"}\' instead. / --enable-search 不支持 Responses API,请改用 --tool \'{"type":"web_search"}\'。'; + return '--enable-search is not supported by the Responses API; use --builtin-tool web_search or --tool \'{"type":"web_search"}\' instead. / --enable-search 不支持 Responses API,请改用 --builtin-tool web_search 或 --tool \'{"type":"web_search"}\'。'; + } + + const api = flags.api === "responses" ? "responses" : "chat"; + const builtinTools = dedupeBuiltinTools(flags.builtinTool); + const builtinValidation = validateBuiltinToolFlags({ + api, + builtinTools, + enableSearch: flags.enableSearch, + enableThinking: flags.enableThinking, + batch: flags.batch, + prime: flags.prime, + hasImageFlag: (flags.image?.length ?? 0) > 0, + hasMessagesFile: Boolean(flags.messagesFile), + }); + if (builtinValidation) return builtinValidation; + + if ((flags.image?.length ?? 0) > 0 && api !== "responses") { + return IMAGE_REQUIRES_RESPONSES; } + + try { + const customTools = parseCustomTools(flags.tool, (path) => readFileSync(path, "utf-8")); + const companionValidation = validateWebExtractorCompanion(builtinTools, customTools); + if (companionValidation) return companionValidation; + } catch { + // Leave malformed --tool to run(). + } + return undefined; }, async run(ctx) { @@ -242,7 +338,31 @@ export default defineCommand({ const allMessages = buildChatMessages(parseTextMessages(flags)); const api = flags.api ?? "chat"; const model = flags.model || settings.defaultTextModel || "qwen3.8-max"; - const shouldStream = flags.batch ? false : flags.stream || process.stdout.isTTY; + const builtinTools = dedupeBuiltinTools(flags.builtinTool); + const customTools = parseCustomTools(flags.tool, (path) => readFileSync(path, "utf-8")); + + const companionValidation = validateWebExtractorCompanion(builtinTools, customTools); + if (companionValidation) { + throw new BailianError(ctx.localize(companionValidation), ExitCode.USAGE); + } + + const imageFlagValidation = validateResponsesImageFlags({ + api: api === "responses" ? "responses" : "chat", + images: flags.image, + messages: allMessages, + }); + if (imageFlagValidation) { + throw new BailianError(ctx.localize(imageFlagValidation), ExitCode.USAGE); + } + + assertImageSearchHasImage({ + requiresImage: builtinRequiresImage(builtinTools), + images: flags.image, + messages: allMessages, + localize: ctx.localize, + }); + + let shouldStream = flags.batch ? false : flags.stream || process.stdout.isTTY; const format = settings.output; let body: ChatRequest | ResponsesRequest; @@ -283,6 +403,19 @@ export default defineCommand({ } else if (SEARCH_BY_DEFAULT_MODELS.has(model)) { body.enable_search = true; } + + const chatBuiltin = applyChatBuiltinTools(body, builtinTools, { + enableSearch: flags.enableSearch, + enableThinking: flags.enableThinking, + }); + if (chatBuiltin.forceStream) { + shouldStream = true; + body.stream = true; + } + + if (customTools.length > 0) { + body.tools = customTools as unknown as ChatRequest["tools"]; + } } const requestPath = flags.batch @@ -293,16 +426,93 @@ export default defineCommand({ ? responsesPath() : chatPath(); - if (flags.tool) { - const tools = flags.tool.map((toolValue) => { - try { - return JSON.parse(toolValue); - } catch { - const raw = readFileSync(toolValue, "utf-8"); - return JSON.parse(raw); + if (api === "responses" && "input" in body) { + applyResponsesThinkingDefault(body, builtinTools, flags.enableThinking); + + const mergedTools = mergeResponsesTools(builtinTools, customTools); + if (mergedTools.length > 0) body.tools = mergedTools; + + const preview = await buildResponsesInput({ + messages: allMessages, + images: flags.image, + previewOnly: true, + client: ctx.client, + model, + localize: ctx.localize, + }); + body.input = preview.input; + + if (settings.dryRun) { + const dryBody: ResponsesRequest = { + ...body, + input: redactResponsesInput(preview.input), + }; + ctx.output.result( + flags.batch + ? { endpoint: requestPath, request: dryBody, timeout: settings.timeout } + : flags.prime + ? { endpoint: requestPath, request: dryBody } + : { request: dryBody }, + ); + return; + } + + if (preview.pendingLocalUploads.length > 0) { + await resolvePendingImageUploads( + preview.input, + preview.pendingLocalUploads, + ctx.client, + model, + ctx.localize, + ); + } + body.input = preview.input; + + if (shouldStream) { + const responseStream = await ctx.client.request({ + path: requestPath, + method: "POST", + body, + stream: true, + }); + + let textContent = ""; + let responsesCompleted = false; + const writesStreamingStdout = format === "text"; + const resultOut = process.stdout; + + for await (const event of parseSSE(responseStream)) { + if (event.data === "[DONE]") break; + let parsedEvent: ResponsesStreamEvent; + try { + parsedEvent = JSON.parse(event.data) as ResponsesStreamEvent; + } catch { + continue; + } + + const update = inspectResponsesStreamEvent(parsedEvent); + if (update.delta) { + textContent += update.delta; + if (writesStreamingStdout) resultOut.write(update.delta); + } + if (update.completed) { + responsesCompleted = true; + break; + } } + assertResponsesStreamCompleted(responsesCompleted); + ctx.output.result({ content: textContent }, format === "text" ? { text: "" } : undefined); + return; + } + + const response = await ctx.client.requestJson({ + path: requestPath, + method: "POST", + body, }); - body.tools = tools; + const text = extractResponsesText(response); + ctx.output.result(response, format === "text" ? { text } : undefined); + return; } if (api === "chat" && "messages" in body) { @@ -322,63 +532,6 @@ export default defineCommand({ shouldStream, dryRunResult, }); - return; - } - - if (settings.dryRun) { - ctx.output.result( - flags.batch - ? { endpoint: requestPath, request: body, timeout: settings.timeout } - : flags.prime - ? { endpoint: requestPath, request: body } - : { request: body }, - ); - return; } - - if (shouldStream) { - const responseStream = await ctx.client.request({ - path: requestPath, - method: "POST", - body, - stream: true, - }); - - let textContent = ""; - let responsesCompleted = false; - const writesStreamingStdout = format === "text"; - const resultOut = process.stdout; - - for await (const event of parseSSE(responseStream)) { - if (event.data === "[DONE]") break; - let parsedEvent: ResponsesStreamEvent; - try { - parsedEvent = JSON.parse(event.data) as ResponsesStreamEvent; - } catch { - continue; - } - - const update = inspectResponsesStreamEvent(parsedEvent); - if (update.delta) { - textContent += update.delta; - if (writesStreamingStdout) resultOut.write(update.delta); - } - if (update.completed) { - responsesCompleted = true; - break; - } - } - assertResponsesStreamCompleted(responsesCompleted); - ctx.output.result({ content: textContent }, format === "text" ? { text: "" } : undefined); - return; - } - - const response = await ctx.client.requestJson({ - path: requestPath, - method: "POST", - body, - }); - const text = extractResponsesText(response); - ctx.output.result(response, format === "text" ? { text } : undefined); }, }); diff --git a/packages/commands/src/commands/text/responses-input.ts b/packages/commands/src/commands/text/responses-input.ts new file mode 100644 index 000000000..fb0d2fde2 --- /dev/null +++ b/packages/commands/src/commands/text/responses-input.ts @@ -0,0 +1,339 @@ +import { existsSync, statSync } from "fs"; +import { basename } from "path"; +import { + BailianError, + ExitCode, + imageFileToDataUri, + isLocalFile, + redactDataUri, + type ChatMessage, + type Client, + type LocalizedText, + type ResponsesInputContent, + type ResponsesInputMessage, +} from "bailian-cli-core"; + +export const LOCAL_DATA_URI_MAX_BYTES = 5 * 1024 * 1024; + +export const IMAGE_REQUIRES_RESPONSES: LocalizedText = { + "en-US": + "--image is only supported with --api responses. Use `vision describe` for Chat Completions vision, or pass --api responses.", + "zh-CN": + "--image 仅支持 --api responses。Chat Completions 视觉请用 `vision describe`,或改用 --api responses。", +}; + +export const IMAGE_SOURCE_CONFLICT: LocalizedText = { + "en-US": + "--image cannot be combined with image content (input_image or image_url) on the last user message. Use one image source.", + "zh-CN": + "--image 不能与最后一条 user 消息中已有的图片内容(input_image 或 image_url)同用。请只保留一种图片来源。", +}; + +export type ResponsesInputItem = ChatMessage | ResponsesInputMessage; + +export interface BuildResponsesInputParams { + messages: ChatMessage[]; + images?: string[]; + /** When true, large local files stay as pending-upload placeholders (dry-run). */ + previewOnly: boolean; + client: Client; + model: string; + localize: (text: LocalizedText) => string; +} + +export interface BuildResponsesInputResult { + input: ResponsesInputItem[]; + pendingLocalUploads: Array<{ messageIndex: number; contentIndex: number; path: string }>; +} + +function isHttpUrl(value: string): boolean { + return /^https?:\/\//i.test(value); +} + +function isDataUri(value: string): boolean { + return /^data:/i.test(value); +} + +function partType(part: unknown): string | undefined { + if (typeof part !== "object" || part === null || !("type" in part)) return undefined; + const type = (part as { type?: unknown }).type; + return typeof type === "string" ? type : undefined; +} + +/** True when content already carries any image-shaped part. */ +function contentHasImagePart(content: unknown): boolean { + if (!Array.isArray(content)) return false; + return content.some((part) => { + const type = partType(part); + return type === "input_image" || type === "image_url"; + }); +} + +export function messagesContainInputImage(messages: ChatMessage[]): boolean { + return messages.some((message) => { + if (!Array.isArray(message.content)) return false; + return message.content.some((part) => partType(part) === "input_image"); + }); +} + +function findLastUserIndex(messages: Array<{ role?: string }>): number { + for (let index = messages.length - 1; index >= 0; index--) { + if (messages[index]?.role === "user") return index; + } + return -1; +} + +export function validateResponsesImageFlags(params: { + api: "chat" | "responses"; + images?: string[]; + messages: ChatMessage[]; +}): LocalizedText | undefined { + const images = params.images ?? []; + if (images.length === 0) return undefined; + + if (params.api !== "responses") { + return IMAGE_REQUIRES_RESPONSES; + } + + const lastUserIndex = findLastUserIndex(params.messages); + if (lastUserIndex >= 0 && contentHasImagePart(params.messages[lastUserIndex]?.content)) { + return IMAGE_SOURCE_CONFLICT; + } + + return undefined; +} + +async function resolveImageSource( + source: string, + opts: { + previewOnly: boolean; + client: Client; + model: string; + localize: (text: LocalizedText) => string; + }, +): Promise<{ imageUrl: string; pendingPath?: string }> { + if (isHttpUrl(source) || isDataUri(source) || source.startsWith("oss://")) { + return { imageUrl: source }; + } + + if (!existsSync(source)) { + throw new BailianError( + opts.localize({ + "en-US": `Image not found: ${source}`, + "zh-CN": `图片不存在:${source}`, + }), + ExitCode.USAGE, + ); + } + + if (!isLocalFile(source)) { + throw new BailianError( + opts.localize({ + "en-US": `Unsupported image input: ${source}. Use an HTTP(S) URL, Data URI, or local file path.`, + "zh-CN": `不支持的图片输入:${source}。请使用 HTTP(S) URL、Data URI 或本地文件路径。`, + }), + ExitCode.USAGE, + ); + } + + const fileSize = statSync(source).size; + if (fileSize > LOCAL_DATA_URI_MAX_BYTES) { + if (opts.previewOnly) { + return { + imageUrl: ``, + pendingPath: source, + }; + } + const uploaded = await opts.client.resolveImageInput(source, opts.model); + return { imageUrl: uploaded }; + } + + return { imageUrl: imageFileToDataUri(source) }; +} + +function isTextShapedPart(part: unknown): part is { type: string; text: string } { + const type = partType(part); + if (type !== "text" && type !== "input_text") return false; + if (typeof part !== "object" || part === null || !("text" in part)) return false; + return typeof (part as { text?: unknown }).text === "string"; +} + +/** + * Build Responses `input` from chat messages and optional --image values. + * Large local images are placeholder-marked in previewOnly mode; call + * `resolvePendingImageUploads` after dry-run returns. + */ +export async function buildResponsesInput( + params: BuildResponsesInputParams, +): Promise { + const images = params.images ?? []; + const input: ResponsesInputItem[] = params.messages.map((message) => ({ ...message })); + const pendingLocalUploads: BuildResponsesInputResult["pendingLocalUploads"] = []; + + if (images.length === 0) { + return { input, pendingLocalUploads }; + } + + const lastUserIndex = findLastUserIndex(input); + if (lastUserIndex < 0) { + throw new BailianError( + params.localize({ + "en-US": "--image requires at least one user message (--message or --messages-file).", + "zh-CN": "--image 需要至少一条 user 消息(--message 或 --messages-file)。", + }), + ExitCode.USAGE, + ); + } + + const lastUser = input[lastUserIndex]!; + if (contentHasImagePart(lastUser.content)) { + throw new BailianError(params.localize(IMAGE_SOURCE_CONFLICT), ExitCode.USAGE); + } + + const content: unknown[] = []; + if (typeof lastUser.content === "string") { + if (lastUser.content) content.push({ type: "input_text", text: lastUser.content }); + } else if (Array.isArray(lastUser.content)) { + for (const part of lastUser.content) { + if (isTextShapedPart(part)) { + const type = partType(part) === "text" ? "input_text" : (partType(part) ?? "input_text"); + content.push({ type, text: part.text }); + continue; + } + // Preserve unrecognized non-image parts (audio, files, etc.). + content.push(part); + } + } + + for (const imageSource of images) { + const resolved = await resolveImageSource(imageSource, { + previewOnly: params.previewOnly, + client: params.client, + model: params.model, + localize: params.localize, + }); + content.push({ type: "input_image", image_url: resolved.imageUrl }); + if (resolved.pendingPath) { + pendingLocalUploads.push({ + messageIndex: lastUserIndex, + contentIndex: content.length - 1, + path: resolved.pendingPath, + }); + } + } + + input[lastUserIndex] = { + role: "user", + content: content as ResponsesInputContent[], + }; + return { input, pendingLocalUploads }; +} + +export async function resolvePendingImageUploads( + input: ResponsesInputItem[], + pending: BuildResponsesInputResult["pendingLocalUploads"], + client: Client, + model: string, + localize: (text: LocalizedText) => string, +): Promise { + for (const item of pending) { + const message = input[item.messageIndex]; + if (!message || typeof message.content === "string" || !Array.isArray(message.content)) { + throw new BailianError( + localize({ + "en-US": `Failed to resolve pending image upload for ${item.path}: message content missing.`, + "zh-CN": `无法解析待上传图片 ${item.path}:消息内容缺失。`, + }), + ExitCode.GENERAL, + ); + } + const part = message.content[item.contentIndex] as + | { type?: string; image_url?: string } + | undefined; + if (!part || part.type !== "input_image") { + throw new BailianError( + localize({ + "en-US": `Failed to resolve pending image upload for ${item.path}: expected input_image placeholder.`, + "zh-CN": `无法解析待上传图片 ${item.path}:未找到 input_image 占位符。`, + }), + ExitCode.GENERAL, + ); + } + part.image_url = await client.resolveImageInput(item.path, model); + } +} + +function redactContentPart(part: unknown): unknown { + if (typeof part !== "object" || part === null) return part; + const type = partType(part); + if (type === "input_image" && "image_url" in part) { + const imageUrl = (part as { image_url?: unknown }).image_url; + return { + ...part, + image_url: typeof imageUrl === "string" ? redactDataUri(imageUrl) : imageUrl, + }; + } + if ((type === "input_text" || type === "text") && "text" in part) { + const text = (part as { text?: unknown }).text; + return { + ...part, + text: typeof text === "string" ? redactDataUri(text) : text, + }; + } + if (type === "image_url" && "image_url" in part) { + const imageUrlValue = (part as { image_url?: unknown }).image_url; + if (typeof imageUrlValue === "string") { + return { ...part, image_url: redactDataUri(imageUrlValue) }; + } + if (typeof imageUrlValue === "object" && imageUrlValue !== null && "url" in imageUrlValue) { + const url = (imageUrlValue as { url?: unknown }).url; + return { + ...part, + image_url: { + ...imageUrlValue, + url: typeof url === "string" ? redactDataUri(url) : url, + }, + }; + } + } + // Preserve unknown parts as-is so dry-run matches the wire body shape. + return part; +} + +/** Redact Data URIs inside Responses input for dry-run output. */ +export function redactResponsesInput(input: ResponsesInputItem[]): ResponsesInputItem[] { + return input.map((message): ResponsesInputItem => { + if (typeof message.content === "string") { + return { role: message.role, content: redactDataUri(message.content) }; + } + if (!Array.isArray(message.content)) { + return { role: message.role, content: message.content }; + } + + return { + role: message.role, + content: message.content.map((part) => redactContentPart(part)) as ResponsesInputContent[], + }; + }); +} + +export function assertImageSearchHasImage(params: { + requiresImage: boolean; + images?: string[]; + messages: ChatMessage[]; + localize: (text: LocalizedText) => string; +}): void { + if (!params.requiresImage) return; + if ((params.images?.length ?? 0) > 0) return; + // image_search needs Responses input_image; chat-style image_url alone is not enough. + if (messagesContainInputImage(params.messages)) return; + throw new BailianError( + params.localize({ + "en-US": + "--builtin-tool image_search requires --image or a --messages-file that already contains input_image.", + "zh-CN": + "--builtin-tool image_search 需要 --image,或在 --messages-file 中提供含 input_image 的消息。", + }), + ExitCode.USAGE, + ); +} diff --git a/packages/commands/tests/e2e/text-builtin-tools.e2e.test.ts b/packages/commands/tests/e2e/text-builtin-tools.e2e.test.ts new file mode 100644 index 000000000..175e81eae --- /dev/null +++ b/packages/commands/tests/e2e/text-builtin-tools.e2e.test.ts @@ -0,0 +1,638 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { deflateSync } from "node:zlib"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test } from "vite-plus/test"; +import { + isDashScopeE2EReady, + parseStdoutJson, + runCommandHelp, + runCommandE2e, + runCommandInProcess, +} from "./helpers.ts"; +import { TEXT_CHAT_ROUTES } from "./topic-routes.ts"; + +let isolatedDirectory: string; + +beforeEach(() => { + isolatedDirectory = mkdtempSync(join(tmpdir(), "bl-text-builtin-e2e-")); + writeFileSync(join(isolatedDirectory, "config.json"), "{}"); +}); + +afterEach(() => { + rmSync(isolatedDirectory, { recursive: true, force: true }); +}); + +function crc32(buffer: Buffer): number { + let crc = 0xffffffff; + for (let index = 0; index < buffer.length; index++) { + crc ^= buffer[index]!; + for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); + } + return (crc ^ 0xffffffff) >>> 0; +} + +function pngChunk(type: string, data: Buffer): Buffer { + const typeBuffer = Buffer.from(type); + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const crcBuffer = Buffer.alloc(4); + crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data]))); + return Buffer.concat([length, typeBuffer, data, crcBuffer]); +} + +function makePng(width: number, height: number): Buffer { + const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; + ihdr[9] = 2; + const stride = 1 + width * 3; + const raw = Buffer.alloc(stride * height); + for (let rowIndex = 0; rowIndex < height; rowIndex++) { + const rowOffset = rowIndex * stride; + raw[rowOffset] = 0; + for (let columnIndex = 0; columnIndex < width; columnIndex++) { + const pixelOffset = rowOffset + 1 + columnIndex * 3; + raw[pixelOffset] = 30; + raw[pixelOffset + 1] = 144; + raw[pixelOffset + 2] = 255; + } + } + return Buffer.concat([ + signature, + pngChunk("IHDR", ihdr), + pngChunk("IDAT", deflateSync(raw)), + pngChunk("IEND", Buffer.alloc(0)), + ]); +} + +describe("e2e: text chat builtin tools", () => { + test("help lists builtin-tool choices and image flag", async () => { + const { stderr, exitCode } = await runCommandHelp(TEXT_CHAT_ROUTES, ["text", "chat", "--help"]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--builtin-tool/); + expect(stderr).toMatch(/web_extractor/); + expect(stderr).toMatch(/image_search/); + expect(stderr).toMatch(/--image/); + expect(stderr).toMatch(/does not auto-add|不会自动补齐/); + expect(stderr).toMatch(/does not require streaming|不要求流式/); + }); + + test("dry-run without new flags keeps qwen3.8-max enable_search default", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--model", + "qwen3.8-max", + "--message", + "hello", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ request?: Record }>(stdout); + expect(data.request).toMatchObject({ + model: "qwen3.8-max", + enable_search: true, + }); + expect(data.request).not.toHaveProperty("enable_code_interpreter"); + expect(data.request).not.toHaveProperty("tools"); + }); + + test("responses dry-run merges web_extractor with auto web_search", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--builtin-tool", + "web_extractor", + "--message", + "summarize", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { tools?: Array<{ type?: string }>; enable_thinking?: boolean }; + }>(stdout); + expect(data.request?.tools).toEqual([{ type: "web_search" }, { type: "web_extractor" }]); + expect(data.request?.enable_thinking).toBe(true); + }); + + test("responses rejects bare --tool web_extractor without web_search", async () => { + const { stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--tool", + '{"type":"web_extractor"}', + "--message", + "summarize", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/web_search|自动补|auto-add/i); + }); + + test("chat dry-run maps code_interpreter and forces stream", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--builtin-tool", + "code_interpreter", + "--model", + "qwen3.5-plus", + "--message", + "2+2", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { + enable_code_interpreter?: boolean; + enable_thinking?: boolean; + stream?: boolean; + }; + }>(stdout); + expect(data.request?.enable_code_interpreter).toBe(true); + expect(data.request?.enable_thinking).toBe(true); + expect(data.request?.stream).toBe(true); + }); + + test("chat rejects responses-only builtin tools", async () => { + const { stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + ["text", "chat", "--builtin-tool", "web_extractor", "--message", "x", "--dry-run"], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/responses/i); + }); + + test("image_search without image exits with usage", async () => { + const { stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--api", + "responses", + "--builtin-tool", + "image_search", + "--message", + "find similar", + "--dry-run", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/image_search|--image/i); + }); + + test("responses dry-run attaches image url to last user message", async () => { + const imageUrl = + "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png"; + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--builtin-tool", + "image_search", + "--image", + imageUrl, + "--message", + "find similar", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { + tools?: Array<{ type?: string }>; + input?: Array<{ role?: string; content?: unknown }>; + }; + }>(stdout); + expect(data.request?.tools).toEqual([{ type: "image_search" }]); + const userMessage = data.request?.input?.find((item) => item.role === "user"); + expect(userMessage?.content).toEqual([ + { type: "input_text", text: "find similar" }, + { type: "input_image", image_url: imageUrl }, + ]); + }); + + test("responses dry-run redacts local data-uri images", async () => { + const pngPath = join(isolatedDirectory, "probe.png"); + writeFileSync(pngPath, makePng(32, 32)); + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--image", + pngPath, + "--message", + "describe", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + expect(stdout).not.toMatch(/base64,[A-Za-z0-9+/=]{20,}/); + const data = parseStdoutJson<{ + request?: { input?: Array<{ content?: Array<{ type?: string; image_url?: string }> }> }; + }>(stdout); + const imagePart = data.request?.input + ?.flatMap((message) => (Array.isArray(message.content) ? message.content : [])) + .find((part) => part.type === "input_image"); + expect(imagePart?.image_url).toMatch(/^data:image\/png;base64,$/); + }); + + test("responses dry-run keeps pending-upload placeholder for >5MB local images", async () => { + const largePath = join(isolatedDirectory, "large.png"); + writeFileSync(largePath, Buffer.alloc(5 * 1024 * 1024 + 1, 1)); + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--image", + largePath, + "--message", + "describe", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { input?: Array<{ content?: Array<{ type?: string; image_url?: string }> }> }; + }>(stdout); + const imagePart = data.request?.input + ?.flatMap((message) => (Array.isArray(message.content) ? message.content : [])) + .find((part) => part.type === "input_image"); + expect(imagePart?.image_url).toBe(""); + }); + + test("rejects --image with messages-file that already has image_url", async () => { + const messagesPath = join(isolatedDirectory, "with-image.json"); + writeFileSync( + messagesPath, + JSON.stringify([ + { + role: "user", + content: [ + { type: "text", text: "look" }, + { type: "image_url", image_url: { url: "https://example.com/a.png" } }, + ], + }, + ]), + ); + const { stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--api", + "responses", + "--messages-file", + messagesPath, + "--image", + "https://example.com/b.png", + "--dry-run", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/image content|图片内容|image_url|input_image/i); + }); + + test("allows --image when only an earlier messages-file turn has image_url", async () => { + const messagesPath = join(isolatedDirectory, "earlier-image.json"); + writeFileSync( + messagesPath, + JSON.stringify([ + { + role: "user", + content: [ + { type: "text", text: "earlier" }, + { type: "image_url", image_url: { url: "https://example.com/a.png" } }, + ], + }, + { role: "assistant", content: "ok" }, + { + role: "user", + content: [ + { type: "text", text: "attach another" }, + { type: "input_audio", input_audio: { data: "AAA", format: "wav" } }, + ], + }, + ]), + ); + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--messages-file", + messagesPath, + "--image", + "https://example.com/b.png", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { input?: Array<{ role?: string; content?: unknown }> }; + }>(stdout); + const lastUser = [...(data.request?.input ?? [])] + .reverse() + .find((item) => item.role === "user"); + expect(lastUser?.content).toEqual([ + { type: "input_text", text: "attach another" }, + { type: "input_audio", input_audio: { data: "AAA", format: "wav" } }, + { type: "input_image", image_url: "https://example.com/b.png" }, + ]); + }); + + test("responses dry-run keeps multiple custom function tools", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--tool", + '{"type":"function","name":"lookup"}', + "--tool", + '{"type":"function","name":"get_weather"}', + "--message", + "hi", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ request?: { tools?: Array<{ type?: string; name?: string }> } }>( + stdout, + ); + expect(data.request?.tools).toEqual([ + { type: "function", name: "lookup" }, + { type: "function", name: "get_weather" }, + ]); + }); + + test("chat rejects --image", async () => { + const { stderr, exitCode } = await runCommandInProcess( + TEXT_CHAT_ROUTES, + ["text", "chat", "--image", "https://example.com/a.png", "--message", "x", "--dry-run"], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/responses|vision describe/i); + }); + + test("representative subprocess dry-run for builtin-tool", async () => { + const { stdout, stderr, exitCode } = await runCommandE2e( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--dry-run", + "--api", + "responses", + "--builtin-tool", + "web_search", + "--message", + "news", + "--output", + "json", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "sk-test", + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ request?: { tools?: Array<{ type?: string }> } }>(stdout); + expect(data.request?.tools).toEqual([{ type: "web_search" }]); + }); +}); + +describe.skipIf(!isDashScopeE2EReady())("e2e: text chat builtin tools (live)", () => { + test("responses web_extractor returns text", async () => { + const { stdout, stderr, exitCode } = await runCommandE2e( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--api", + "responses", + "--builtin-tool", + "web_extractor", + "--model", + "qwen3.8-max", + "--message", + "访问 https://www.aliyun.com ,用一句话总结首页主题", + "--max-tokens", + "128", + "--output", + "json", + "--timeout", + "180", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ output?: unknown[]; output_text?: string }>(stdout); + expect(Array.isArray(data.output) || typeof data.output_text === "string").toBe(true); + }, 240_000); + + test("chat code_interpreter streams a numeric answer", async () => { + const { stdout, stderr, exitCode } = await runCommandE2e( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--builtin-tool", + "code_interpreter", + "--model", + "qwen3.5-plus", + "--message", + "计算 12 的 3 次方,只输出数字", + "--max-tokens", + "64", + "--output", + "json", + "--timeout", + "120", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ content?: string }>(stdout); + expect(String(data.content ?? stdout)).toMatch(/1728/); + }, 180_000); + + test("responses image_search with public url", async () => { + const { stdout, stderr, exitCode } = await runCommandE2e( + TEXT_CHAT_ROUTES, + [ + "text", + "chat", + "--api", + "responses", + "--builtin-tool", + "image_search", + "--image", + "https://img.alicdn.com/imgextra/i4/O1CN01YbrnSS1qtmsAkw0Ud_!!6000000005554-2-tps-788-450.png", + "--model", + "qwen3.8-max", + "--message", + "找与这张图相似风格的风景图,一句话即可", + "--max-tokens", + "512", + "--output", + "json", + "--timeout", + "180", + ], + { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + }, + ); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + status?: string; + output?: Array<{ type?: string }>; + }>(stdout); + const types = (data.output ?? []).map((item) => item.type); + expect( + data.status === "completed" || + types.includes("image_search_call") || + types.includes("message"), + ).toBe(true); + }, 240_000); +}); diff --git a/packages/commands/tests/text-builtin-tools.test.ts b/packages/commands/tests/text-builtin-tools.test.ts new file mode 100644 index 000000000..03889d9ab --- /dev/null +++ b/packages/commands/tests/text-builtin-tools.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, test } from "vite-plus/test"; +import { + applyChatBuiltinTools, + dedupeBuiltinTools, + mergeResponsesTools, + validateBuiltinToolFlags, + validateWebExtractorCompanion, +} from "../src/commands/text/builtin-tools.ts"; +import type { ChatRequest } from "bailian-cli-core"; + +describe("builtin-tools helpers", () => { + test("dedupes while preserving order", () => { + expect(dedupeBuiltinTools(["web_search", "web_extractor", "web_search"])).toEqual([ + "web_search", + "web_extractor", + ]); + }); + + test("mergeResponsesTools auto-adds web_search for web_extractor and keeps custom object", () => { + const merged = mergeResponsesTools( + ["web_extractor"], + [ + { type: "web_search", max_uses: 3 }, + { type: "function", name: "lookup" }, + ], + ); + expect(merged).toEqual([ + { type: "web_search", max_uses: 3 }, + { type: "web_extractor" }, + { type: "function", name: "lookup" }, + ]); + }); + + test("mergeResponsesTools keeps multiple custom function tools in order", () => { + const merged = mergeResponsesTools( + [], + [ + { type: "function", name: "lookup" }, + { type: "function", name: "get_weather" }, + { type: "web_search", max_uses: 3 }, + ], + ); + expect(merged).toEqual([ + { type: "function", name: "lookup" }, + { type: "function", name: "get_weather" }, + { type: "web_search", max_uses: 3 }, + ]); + }); + + test("mergeResponsesTools lets custom builtin-type override and still keeps functions", () => { + const merged = mergeResponsesTools( + ["web_search"], + [ + { type: "function", name: "lookup" }, + { type: "web_search", max_uses: 5 }, + { type: "function", name: "get_weather" }, + ], + ); + expect(merged).toEqual([ + { type: "web_search", max_uses: 5 }, + { type: "function", name: "lookup" }, + { type: "function", name: "get_weather" }, + ]); + }); + + test("applyChatBuiltinTools maps search and forces stream for code_interpreter", () => { + const body: ChatRequest = { + model: "qwen3.5-plus", + messages: [{ role: "user", content: "hi" }], + }; + const result = applyChatBuiltinTools(body, ["code_interpreter", "web_search"], {}); + expect(result.forceStream).toBe(true); + expect(body.enable_code_interpreter).toBe(true); + expect(body.enable_thinking).toBe(true); + expect(body.enable_search).toBe(true); + }); + + test("validate rejects chat-only misuse of responses tools", () => { + const error = validateBuiltinToolFlags({ + api: "chat", + builtinTools: ["web_extractor"], + }); + expect(error).toMatchObject({ + "en-US": expect.stringContaining("--api responses"), + }); + }); + + test("validate rejects image_search without image source", () => { + const error = validateBuiltinToolFlags({ + api: "responses", + builtinTools: ["image_search"], + hasImageFlag: false, + hasMessagesFile: false, + }); + expect(error).toMatchObject({ + "zh-CN": expect.stringContaining("image_search"), + }); + }); + + test("validateWebExtractorCompanion rejects bare --tool web_extractor", () => { + const error = validateWebExtractorCompanion([], [{ type: "web_extractor" }]); + expect(error).toMatchObject({ + "en-US": expect.stringContaining("--tool"), + "zh-CN": expect.stringContaining("web_search"), + }); + }); + + test("validateWebExtractorCompanion allows --tool extractor when search is present", () => { + expect( + validateWebExtractorCompanion([], [{ type: "web_search" }, { type: "web_extractor" }]), + ).toBeUndefined(); + expect( + validateWebExtractorCompanion(["web_search"], [{ type: "web_extractor" }]), + ).toBeUndefined(); + expect( + validateWebExtractorCompanion(["web_extractor"], [{ type: "web_extractor" }]), + ).toBeUndefined(); + }); +}); diff --git a/packages/commands/tests/text-responses-input.test.ts b/packages/commands/tests/text-responses-input.test.ts new file mode 100644 index 000000000..459b525f0 --- /dev/null +++ b/packages/commands/tests/text-responses-input.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, test } from "vite-plus/test"; +import { BailianError } from "bailian-cli-core"; +import { + buildResponsesInput, + redactResponsesInput, + resolvePendingImageUploads, + validateResponsesImageFlags, +} from "../src/commands/text/responses-input.ts"; +import type { ChatMessage, Client, LocalizedText } from "bailian-cli-core"; + +const localize = (text: LocalizedText) => (typeof text === "string" ? text : text["en-US"]); + +function fakeClient(resolveImageInput?: Client["resolveImageInput"]): Client { + return { + resolveImageInput: + resolveImageInput ?? + (async (path: string) => { + throw new Error(`unexpected resolveImageInput(${path})`); + }), + } as Client; +} + +describe("responses-input helpers", () => { + test("rejects --image when last user message already has image parts", () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: [ + { type: "text", text: "look" }, + { type: "image_url", image_url: { url: "https://example.com/a.png" } }, + ], + }, + ]; + const error = validateResponsesImageFlags({ + api: "responses", + images: ["https://example.com/b.png"], + messages, + }); + expect(error).toMatchObject({ + "en-US": expect.stringContaining("image content"), + }); + }); + + test("allows --image when only an earlier user message has image parts", () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: [ + { type: "text", text: "earlier" }, + { type: "image_url", image_url: { url: "https://example.com/a.png" } }, + ], + }, + { role: "assistant", content: "ok" }, + { role: "user", content: "now attach another" }, + ]; + expect( + validateResponsesImageFlags({ + api: "responses", + images: ["https://example.com/b.png"], + messages, + }), + ).toBeUndefined(); + }); + + test("buildResponsesInput preserves unrecognized non-image parts on rewrite", async () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: [ + { type: "text", text: "caption" }, + { type: "input_audio", input_audio: { data: "AAA", format: "wav" } } as never, + { type: "custom_part", payload: "keep-me" } as never, + ], + }, + ]; + const result = await buildResponsesInput({ + messages, + images: ["https://example.com/b.png"], + previewOnly: true, + client: fakeClient(), + model: "qwen3.8-max", + localize, + }); + expect(result.input[0]?.content).toEqual([ + { type: "input_text", text: "caption" }, + { type: "input_audio", input_audio: { data: "AAA", format: "wav" } }, + { type: "custom_part", payload: "keep-me" }, + { type: "input_image", image_url: "https://example.com/b.png" }, + ]); + }); + + test("redactResponsesInput preserves unknown parts", () => { + const redacted = redactResponsesInput([ + { + role: "user", + content: [ + { type: "input_text", text: "data:image/png;base64,AAAA" }, + { type: "custom_part", payload: "keep-me" } as never, + { + type: "image_url", + image_url: { url: "data:image/png;base64,BBBB" }, + } as never, + ], + }, + ]); + expect(redacted[0]?.content).toEqual([ + { type: "input_text", text: "data:image/png;base64," }, + { type: "custom_part", payload: "keep-me" }, + { + type: "image_url", + image_url: { url: "data:image/png;base64," }, + }, + ]); + }); + + test("resolvePendingImageUploads throws when placeholder indexes do not match", async () => { + await expect( + resolvePendingImageUploads( + [{ role: "user", content: "plain text" }], + [{ messageIndex: 0, contentIndex: 0, path: "/tmp/big.png" }], + fakeClient(), + "qwen3.8-max", + localize, + ), + ).rejects.toBeInstanceOf(BailianError); + + await expect( + resolvePendingImageUploads( + [ + { + role: "user", + content: [{ type: "input_text", text: "hi" }], + }, + ], + [{ messageIndex: 0, contentIndex: 0, path: "/tmp/big.png" }], + fakeClient(), + "qwen3.8-max", + localize, + ), + ).rejects.toMatchObject({ + message: expect.stringContaining("input_image"), + }); + }); +}); diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts index 8edbd7bf5..e8554f6a3 100644 --- a/packages/core/src/types/api.ts +++ b/packages/core/src/types/api.ts @@ -51,6 +51,7 @@ export interface ChatRequest { enable_thinking?: boolean; thinking_budget?: number; enable_search?: boolean; + enable_code_interpreter?: boolean; modalities?: string[]; audio?: { voice: string; format?: string }; stream_options?: { include_usage?: boolean }; @@ -120,9 +121,19 @@ export interface StreamChunk { // ---- Responses (OpenAI Compatible) ---- +/** Responses multimodal content parts (distinct from Chat Completions image_url parts). */ +export type ResponsesInputContent = + | { type: "input_text"; text: string } + | { type: "input_image"; image_url: string }; + +export interface ResponsesInputMessage { + role: "system" | "user" | "assistant"; + content: string | ResponsesInputContent[]; +} + export interface ResponsesRequest { model: string; - input: ChatMessage[]; + input: string | Array; max_output_tokens?: number; temperature?: number; top_p?: number; diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 42b5d127b..4d09c2a05 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -69,55 +69,56 @@ Do not guess flags — use the reference files or `--help`. Use this table only after the decision table in [`bailian-protocol`](../bailian-protocol/SKILL.md#provider-selection-and-consent) has routed the request to `bl` (class 4, or class 2 after the user picks Bailian). Hub-owned intents only — for media / fine-tune / agents.yaml / Sandbox, soft hand-off to the domain skill. -| User intent | Command | Notes | -| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | -| Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | -| 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | -| 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | -| Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | -| Explicit ParseX parsing / structured field extraction | `bl parsex parse submit` / `result`; `bl parsex extract submit` / `result` | Workspace + API key; submit returns biz_id, result --follow waits. HTTP(S) source URLs; extraction can reuse a parsed document. See `reference/parsex.md`. | -| Bailian agent / workflow | `bl flow-agent call` | Needs `--app-id` | -| Find app by name | `bl flow-agent list` then `bl flow-agent call` | Console auth; `--type workflow` lists workflows | -| Create / update / publish / delete / copy an app | `bl flow-agent create` / `update` / `publish` / `delete` / `copy` / `get` / `versions` | Console auth; agent config via `--model`/`--instructions`/`--config-json`; `delete` needs `--yes`; see [`reference/flow-agent.md`](reference/flow-agent.md) | -| Workflow canvas read / save / publish / export | `bl flow-agent workflow get` / `save` / `publish` / `export` | Console auth; `save` replaces the whole draft canvas; see [`reference/flow-agent.md`](reference/flow-agent.md) | -| Personal memory / Bailian memory resources | → skill `bailian-memory` | User-enabled personal memory; explicit resource operations use `bl memory --help` as fallback. | -| Personal documents / Bailian knowledge workflows | Read skill `bailian-knowledge` | If missing: `bl knowledge --help` or `bl skill init` | -| Resolve a Console file key / error-report URL | `bl file url` | Console auth; use the returned business file key, not a file ID or upload URI. Resolves only; no download or fixed expiry. Existing URLs need no resolution. | -| Upload a file as a step of a Bailian workflow | `bl file upload` | When you need `oss://` URL explicitly; not for generic hosting | -| Bailian model selection / recommendation | `bl advisor recommend` | Intent → candidate recall → LLM ranking | -| Bailian model catalog / pricing / params | `bl model list` | No auth (public catalog); `--model ` for detail, `--enrich` for input params | -| Find a model by keyword / modality | `bl model search` | Weighted ranking; `--input-modality` / `--output-modality`; offline models hidden by default | -| SDK sample code for calling a model | `bl model code` | `--sdk openai\|dashscope`, `--lang`; text output is the snippet alone, safe to redirect | -| Install / list / update / remove registry skills | `bl skill add` / `list` / `update` / `remove` | OSS `--name`, cloud `--code`. `add --all` installs the registry. `update --all` updates installed OSS skills. Filter by `--agent` / `--scope`. [Reference](reference/skill.md) | -| Find cloud skills or inspect local installation paths | `bl skill search` / `bl skill get` | Search the cloud with a Bailian API key. Pass the returned `skill_code` to `get --code`. Use `get --name` for an OSS skill. | -| Find and run a workspace connector tool | `bl connector tools --query` → `schema` → `call` | Use the discovered toolRef and authorized instanceId. Pass the returned traceId to both subsequent commands. | -| Inspect activated MCP servers, details or tools | `bl mcp list` / `get` / `tools` / `call` | — | -| Find MCP tools by task or inspect a server's tools | `bl mcp tool search` / `bl mcp tool list` | Search with `--query` or list with `--server`. Both operations may trigger OneKey activation. Preview with `--dry-run`. | -| Call a tool by server code and tool name | `bl mcp tool call` / `bl mcp call` | Use `--server` and `--tool` for OpenAPI, or `--target ` for an MCP session. | -| Activate or stop MCP servers | `bl mcp activate` / `deactivate` | API key. Use `--server ` to select servers and `--dry-run` to preview the batch. | -| Manage a custom Bailian MCP server | `bl mcp create` / `update` / `delete` | API key. Preview changes with `--dry-run`. Deleting a server requires `--yes`. | -| Register or remove a Bailian MCP in an Agent | `bl mcp connect` / `disconnect` | Choose `--agent` and `--scope user\|project`. Connect previews the workspace endpoint and any activation. Disconnect uses the local registration. | -| Bailian pipeline workflow (a step in a bl flow) | `bl pipeline run` / `validate` | JSON/YAML workflow definitions | -| Bailian rate limits / quota | `bl quota list` / `check` / `request` | Console auth; class 2 — ask which product first if unnamed | -| Bailian free tier / usage stats | `bl usage free` / `stats` / `freetier` | Console auth; class 2 — ask which product first if unnamed | -| Bailian Token Plan quota usage | `bl usage token-plan` | Console auth; class 2 — ask which product first if unnamed | -| Token Plan harness entitlement quota | `bl token-plan harness-quota` | Console auth; issued quota usage + still-issuing harnesses | -| Bailian Coding Plan quota usage | `bl usage coding-plan` | Console auth; class 2 — ask which product first if unnamed | -| Model monitoring (calls, latency, errors, delivery) | `bl monitor overview` / `models` / `metrics` / `errors` / `delivery *` | Console auth; see [`reference/monitor.md`](reference/monitor.md) | -| Model call logs / traces | `bl log audit *` / `bl log inference *` / `bl log status` / `bl log trace *` | Console auth; audit and inference logs have separate APIs and switches; see [`reference/log.md`](reference/log.md) | -| Model alert rules / templates / history | `bl alert list` / `create` / `update` / `delete` / `enable` / `disable` / `history` / `metrics` / `template *` | Console auth; contacts are managed in the CloudMonitor console; see [`reference/alert.md`](reference/alert.md) | -| Console API (advanced) | `bl console call` | Console auth | -| Bailian workspace listing | `bl workspace list` | Console auth | -| Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | -| Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | -| Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | -| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | -| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | -| Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | -| agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | -| Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | -| Web search (mode-aware routing) | → skill `bailian-web-search` | Default model mode vs explicit `--mode mcp` + fallback; fallback: `bl search web --help` | +| User intent | Command | Notes | +| ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | +| Built-in tools (web extract / code interpreter / text-to-image search / image-to-image search) | `bl text chat --builtin-tool …` (+ `--api responses` / `--image` as needed) | Prefer Responses for extractor / image tools; Chat maps `web_search` and `code_interpreter` only; see `reference/text.md`. Ordinary web search routing stays `bailian-web-search`. | +| Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | +| 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | +| 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | +| Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | +| Explicit ParseX parsing / structured field extraction | `bl parsex parse submit` / `result`; `bl parsex extract submit` / `result` | Workspace + API key; submit returns biz_id, result --follow waits. HTTP(S) source URLs; extraction can reuse a parsed document. See `reference/parsex.md`. | +| Bailian agent / workflow | `bl flow-agent call` | Needs `--app-id` | +| Find app by name | `bl flow-agent list` then `bl flow-agent call` | Console auth; `--type workflow` lists workflows | +| Create / update / publish / delete / copy an app | `bl flow-agent create` / `update` / `publish` / `delete` / `copy` / `get` / `versions` | Console auth; agent config via `--model`/`--instructions`/`--config-json`; `delete` needs `--yes`; see [`reference/flow-agent.md`](reference/flow-agent.md) | +| Workflow canvas read / save / publish / export | `bl flow-agent workflow get` / `save` / `publish` / `export` | Console auth; `save` replaces the whole draft canvas; see [`reference/flow-agent.md`](reference/flow-agent.md) | +| Personal memory / Bailian memory resources | → skill `bailian-memory` | User-enabled personal memory; explicit resource operations use `bl memory --help` as fallback. | +| Personal documents / Bailian knowledge workflows | Read skill `bailian-knowledge` | If missing: `bl knowledge --help` or `bl skill init` | +| Resolve a Console file key / error-report URL | `bl file url` | Console auth; use the returned business file key, not a file ID or upload URI. Resolves only; no download or fixed expiry. Existing URLs need no resolution. | +| Upload a file as a step of a Bailian workflow | `bl file upload` | When you need `oss://` URL explicitly; not for generic hosting | +| Bailian model selection / recommendation | `bl advisor recommend` | Intent → candidate recall → LLM ranking | +| Bailian model catalog / pricing / params | `bl model list` | No auth (public catalog); `--model ` for detail, `--enrich` for input params | +| Find a model by keyword / modality | `bl model search` | Weighted ranking; `--input-modality` / `--output-modality`; offline models hidden by default | +| SDK sample code for calling a model | `bl model code` | `--sdk openai\|dashscope`, `--lang`; text output is the snippet alone, safe to redirect | +| Install / list / update / remove registry skills | `bl skill add` / `list` / `update` / `remove` | OSS `--name`, cloud `--code`. `add --all` installs the registry. `update --all` updates installed OSS skills. Filter by `--agent` / `--scope`. [Reference](reference/skill.md) | +| Find cloud skills or inspect local installation paths | `bl skill search` / `bl skill get` | Search the cloud with a Bailian API key. Pass the returned `skill_code` to `get --code`. Use `get --name` for an OSS skill. | +| Find and run a workspace connector tool | `bl connector tools --query` → `schema` → `call` | Use the discovered toolRef and authorized instanceId. Pass the returned traceId to both subsequent commands. | +| Inspect activated MCP servers, details or tools | `bl mcp list` / `get` / `tools` / `call` | — | +| Find MCP tools by task or inspect a server's tools | `bl mcp tool search` / `bl mcp tool list` | Search with `--query` or list with `--server`. Both operations may trigger OneKey activation. Preview with `--dry-run`. | +| Call a tool by server code and tool name | `bl mcp tool call` / `bl mcp call` | Use `--server` and `--tool` for OpenAPI, or `--target ` for an MCP session. | +| Activate or stop MCP servers | `bl mcp activate` / `deactivate` | API key. Use `--server ` to select servers and `--dry-run` to preview the batch. | +| Manage a custom Bailian MCP server | `bl mcp create` / `update` / `delete` | API key. Preview changes with `--dry-run`. Deleting a server requires `--yes`. | +| Register or remove a Bailian MCP in an Agent | `bl mcp connect` / `disconnect` | Choose `--agent` and `--scope user\|project`. Connect previews the workspace endpoint and any activation. Disconnect uses the local registration. | +| Bailian pipeline workflow (a step in a bl flow) | `bl pipeline run` / `validate` | JSON/YAML workflow definitions | +| Bailian rate limits / quota | `bl quota list` / `check` / `request` | Console auth; class 2 — ask which product first if unnamed | +| Bailian free tier / usage stats | `bl usage free` / `stats` / `freetier` | Console auth; class 2 — ask which product first if unnamed | +| Bailian Token Plan quota usage | `bl usage token-plan` | Console auth; class 2 — ask which product first if unnamed | +| Token Plan harness entitlement quota | `bl token-plan harness-quota` | Console auth; issued quota usage + still-issuing harnesses | +| Bailian Coding Plan quota usage | `bl usage coding-plan` | Console auth; class 2 — ask which product first if unnamed | +| Model monitoring (calls, latency, errors, delivery) | `bl monitor overview` / `models` / `metrics` / `errors` / `delivery *` | Console auth; see [`reference/monitor.md`](reference/monitor.md) | +| Model call logs / traces | `bl log audit *` / `bl log inference *` / `bl log status` / `bl log trace *` | Console auth; audit and inference logs have separate APIs and switches; see [`reference/log.md`](reference/log.md) | +| Model alert rules / templates / history | `bl alert list` / `create` / `update` / `delete` / `enable` / `disable` / `history` / `metrics` / `template *` | Console auth; contacts are managed in the CloudMonitor console; see [`reference/alert.md`](reference/alert.md) | +| Console API (advanced) | `bl console call` | Console auth | +| Bailian workspace listing | `bl workspace list` | Console auth | +| Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | +| Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | +| Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | +| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | +| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | +| Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | +| agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | +| Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | +| Web search (mode-aware routing) | → skill `bailian-web-search` | Default model mode vs explicit `--mode mcp` + fallback; fallback: `bl search web --help` | Flags, usage, and examples: see hub [`reference/`](reference/index.md) or `bl --help` — do not guess flags. Domain command details live in the owning skill's `reference/`. Examples in `reference/` stay bare; wrap with Call attribution when running. diff --git a/skills/bailian-cli/reference/text.md b/skills/bailian-cli/reference/text.md index 64800c81c..f9773d660 100644 --- a/skills/bailian-cli/reference/text.md +++ b/skills/bailian-cli/reference/text.md @@ -25,26 +25,28 @@ Index: [index.md](index.md) #### Flags -| Flag | Type | Required | Description | -| --------------------------------- | ------- | -------- | ------------------------------------------------------------------------------------- | -| `--api ` | string | no | API to call (default: chat) | -| `--model ` | string | no | Model ID (default: qwen3.8-max) | -| `--message ` | array | no | Message text (repeatable, prefix role: to set role); or use --messages-file | -| `--messages-file ` | string | no | Messages array for one request (use - for stdin) | -| `--system ` | string | no | System prompt | -| `--max-tokens ` | number | no | Maximum tokens to generate (default: 4096) | -| `--temperature ` | number | no | Sampling temperature (0.0, 2.0] | -| `--top-p ` | number | no | Nucleus sampling threshold | -| `--enable-search ` | boolean | no | Enable built-in web search (Chat Completions API only; default: true for qwen3.8-max) | -| `--stream` | switch | no | Stream response tokens (default: on in TTY) | -| `--tool ` | array | no | Tool definition as JSON or file path (repeatable) | -| `--enable-thinking [true\|false]` | boolean | no | Set thinking/reasoning mode; bare flag means true (model support is service-defined) | -| `--thinking-budget ` | number | no | Max tokens for thinking (default: 4096) | -| `--batch` | switch | no | Single synchronous Batch Chat request (non-streaming) | -| `--prime` | switch | no | Use Prime mode with a workspace-scoped endpoint | -| `--workspace-id ` | string | no | Workspace ID for the default Prime endpoint (or set BAILIAN_WORKSPACE_ID) | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ---------------------------------------------------------------------------------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------- | +| `--api ` | string | no | API to call (default: chat) | +| `--model ` | string | no | Model ID (default: qwen3.8-max) | +| `--message ` | array | no | Message text (repeatable, prefix role: to set role); or use --messages-file | +| `--messages-file ` | string | no | Messages array for one request (use - for stdin) | +| `--system ` | string | no | System prompt | +| `--max-tokens ` | number | no | Maximum tokens to generate (default: 4096) | +| `--temperature ` | number | no | Sampling temperature (0.0, 2.0] | +| `--top-p ` | number | no | Nucleus sampling threshold | +| `--enable-search ` | boolean | no | Enable built-in web search (Chat Completions API only; default: true for qwen3.8-max) | +| `--builtin-tool ` | array | no | Built-in model tool (repeatable). Responses: tools[].type; Chat maps web_search/code_interpreter only | +| `--image ` | array | no | Image for Responses input_image (repeatable; --api responses only; required for image_search) | +| `--stream` | switch | no | Stream response tokens (default: on in TTY) | +| `--tool ` | array | no | Tool definition as JSON or file path (repeatable) | +| `--enable-thinking [true\|false]` | boolean | no | Set thinking/reasoning mode; bare flag means true (model support is service-defined) | +| `--thinking-budget ` | number | no | Max tokens for thinking (default: 4096) | +| `--batch` | switch | no | Single synchronous Batch Chat request (non-streaming) | +| `--prime` | switch | no | Use Prime mode with a workspace-scoped endpoint | +| `--workspace-id ` | string | no | Workspace ID for the default Prime endpoint (or set BAILIAN_WORKSPACE_ID) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes @@ -52,7 +54,8 @@ Index: [index.md](index.md) - Batch Chat total request timeout defaults to 300s; --timeout must be 60–3600s. - Prime mode requires an explicit model and currently supports only the Chat Completions API. - Prime endpoint: configured --base-url, DASHSCOPE_BASE_URL, or profile base_url takes precedence; otherwise workspace is resolved from --workspace-id, BAILIAN_WORKSPACE_ID, then config workspace_id. -- --enable-search maps to the Chat Completions enable_search parameter and requires a model with built-in web search support; whitelisted models (qwen3.8-max) enable it by default unless --enable-search false is passed; for the Responses API use --tool '{"type":"web_search"}' instead. +- --enable-search maps to Chat Completions enable_search and requires a model with built-in web search; whitelisted models (qwen3.8-max) enable it by default unless --enable-search false is passed. Responses: use --builtin-tool web_search or --tool '{"type":"web_search"}'. +- --builtin-tool enables Responses tools (web_search, web_extractor, code_interpreter, web_search_image, image_search). Chat only maps web_search→enable_search and code_interpreter→enable_code_interpreter (forced streaming). --builtin-tool web_extractor auto-adds web_search; the --tool path does not auto-add companions—bare --tool {"type":"web_extractor"} requires an explicit web_search (or use --builtin-tool web_extractor). Responses code_interpreter does not require streaming. When --enable-thinking is omitted, Responses web_extractor/code_interpreter and Chat code_interpreter default enable_thinking=true (billable reasoning tokens); pass --enable-thinking false to opt out where the API allows. image_search requires --image (or messages-file input_image) and --api responses. Tool call details appear only in non-streaming --output json; streaming JSON returns { content } only. web_search_image / image_search can be slow—prefer --stream or a higher --timeout. Image shortest side must be >10px (service-enforced). Token Plan connections are unverified for these tools. - For dedicated Qwen-MT text translation, use `text translate` instead of this chat entry. #### Examples @@ -65,6 +68,22 @@ bl text chat --message "What is Qwen?" bl text chat --api responses --model qwen3.8-max --tool '{"type":"web_search"}' --message "Search for recent Alibaba Cloud news" ``` +```bash +bl text chat --api responses --builtin-tool web_extractor --message "Summarize the linked doc" --enable-thinking +``` + +```bash +bl text chat --api responses --builtin-tool web_search_image --message "Find a tech PPT cover image" +``` + +```bash +bl text chat --api responses --builtin-tool image_search --image https://example.com/a.png --message "Find similar scenic images" +``` + +```bash +bl text chat --builtin-tool code_interpreter --message "Compute 12 cubed" +``` + ```bash bl text chat --model qwen-max --system "You are a coding assistant." --message "Write fizzbuzz in Python" ```