Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
chore(desktop): 合并 upstream/main 协调 title-one-shot 重构 + 修复 review 反馈
Shinku67feb902fa26
diff --cc apps/desktop/src/main/maker-host/title-one-shot.tsindex f324760d3d,71f04a1b3c..df7287d6ab--- a/apps/desktop/src/main/maker-host/title-one-shot.ts+++ b/apps/desktop/src/main/maker-host/title-one-shot.ts@@@ -252,19 -262,7 +264,19 @@@ async function fetchAnthropicTitleoauthToken: string,fetchImpl: FetchImpl,signal: AbortSignal,- maxTokens: number = ONE_SHOT_DEFAULT_MAX_TOKENS,++ maxTokens: number = TITLE_MAX_TOKENS,+ systemPrompt?: string,): Promise<string> {+ // Anthropic Messages API 不支持 role: 'system' 消息 —— 系统指令必须写入+ // 顶层 `system` 字段,否则请求会被 API 拒绝。+ const body: Record<string, unknown> = {+ model: toSdkModelString(modelId),+ max_tokens: maxTokens,+ messages: [{ role: 'user', content: prompt }],+ };+ if (systemPrompt) {+ body.system = systemPrompt;+ }const res = await fetchImpl(`${trimTrailingSlash(upstream)}/v1/messages`, {method: 'POST',signal,@@@ -294,15 -296,10 +306,15 @@@ async function fetchCodexTitlecreds: { accessToken: string; accountId: string },fetchImpl: FetchImpl,signal: AbortSignal,- instructions: string = CODEX_DEFAULT_INSTRUCTIONS,++ instructions: string = CODEX_TITLE_INSTRUCTIONS,+ systemPrompt?: string,): Promise<string> {+ const effectiveInstructions = systemPrompt+ ? `${systemPrompt}\n\n${instructions}`+ : instructions;const body: Record<string, unknown> = {model: modelId,- instructions: CODEX_TITLE_INSTRUCTIONS,+ instructions: effectiveInstructions,input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: prompt }] }],tools: [],tool_choice: 'auto',@@@ -338,13 -335,7 +350,13 @@@ async function fetchGatewayTitlegatewayKey: string,fetchImpl: FetchImpl,signal: AbortSignal,- maxTokens: number = ONE_SHOT_DEFAULT_MAX_TOKENS,++ maxTokens: number = TITLE_MAX_TOKENS,+ systemPrompt?: string,): Promise<string> {+ const messages: Array<{ role: string; content: string }> = [];+ if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });+ messages.push({ role: 'user', content: prompt });+const res = await fetchImpl(`${trimTrailingSlash(upstream)}/chat/completions`, {method: 'POST',signal,@@@ -396,53 -387,15 +408,42 @@@ export function parseResponsesSse(raw:return (final || delta).trim();}+/**+ * 非标题 one-shot 调用的可选参数覆盖。标题调用不传(走默认值)。+ * 用于 prompt prediction 等复用同一条 provider 通路但需要不同 token/校验的场景。+ */+export interface OneShotOpts {+ /** 覆盖 max_tokens(标题默认 32)。 */+ maxTokens?: number;- /** 覆盖 Codex instructions(标题默认 CODEX_DEFAULT_INSTRUCTIONS)。 */++ /** 覆盖 Codex instructions(标题默认 CODEX_TITLE_INSTRUCTIONS)。 */+ codexInstructions?: string;+ /** 覆盖输出校验时的最大 Unicode 长度(标题默认 256)。0 跳过 validateTitleOutput。 */+ maxOutputChars?: number;+ /** 校验通过后的 Unicode 截断长度(标题默认 40)。0 跳过截断。 */+ maxVisualChars?: number;+ /**+ * 可选的 system 指令。+ * - Anthropic Messages wire: 写入顶层 `system` 字段(该 API 不接受 role: 'system' 消息)。+ * - Codex Responses wire: 拼接到 instructions 前。+ * - Gateway chat wire: 作为 role: 'system' 消息插入 messages 数组。+ * prompt prediction 用此字段将系统指令与对话上下文正确分离。+ */+ systemPrompt?: string;+}+/**- * 标题 oneShot 主入口:解析本会话 provider → titleModel → 单次 HTTP 起标题。- * 任何环节失败(无 titleModel / 凭证缺失 / HTTP 错 / 空响应 / 超时)→ 返回 null,调用方回落启发式。+ * 标题 oneShot 诊断入口:解析本会话 provider → titleModel → 单次 HTTP 起标题。+ * 仅区分“当前供应商不支持”与通用失败,供手动 AI 重命名给出可操作提示。* 全程不打印 token(只记 providerId / model / wire / 耗时)。+ *+ * `opts` 仅用于非标题场景(如 prompt prediction)覆盖默认 token 数/校验规则;+ * 标题场景不传即可走默认值。*/- export async function runProviderOneShot(+ export async function generateTitleViaProviderResult(args: { sessionId: string; agentKind: AgentKind; prompt: string; signal?: AbortSignal },- deps: ProviderOneShotDeps = {},+ deps: TitleOneShotDeps = {},+ opts?: OneShotOpts,- ): Promise<string | null> {- log.debug('oneShot args', {- sessionId: args.sessionId,- agentKind: args.agentKind,- promptLen: args.prompt.length,- maxTokens: opts?.maxTokens,- maxOutputChars: opts?.maxOutputChars,- maxVisualChars: opts?.maxVisualChars,- hasCodexInstructions: opts?.codexInstructions != null,- hasSystemPrompt: opts?.systemPrompt != null,- });-+ ): Promise<TitleOneShotResult> {// 默认走吃系统代理的 undici fetch:上游可能是境外端点(catalog routing.upstream)。const fetchImpl = deps.fetchImpl ?? outboundUndiciFetch;const readSessionProviderId = deps.readSessionProviderId ?? (async () => null);@@@ -545,12 -505,6 +553,11 @@@});return false;};+ // 非标题场景(如 prompt prediction)可覆盖 token 数/校验规则。- const maxTokens = opts?.maxTokens ?? ONE_SHOT_DEFAULT_MAX_TOKENS;- const codexInstructions = opts?.codexInstructions ?? CODEX_DEFAULT_INSTRUCTIONS;- const maxOutputChars = opts?.maxOutputChars ?? ONE_SHOT_DEFAULT_OUTPUT_MAX_CHARS;++ const maxTokens = opts?.maxTokens ?? TITLE_MAX_TOKENS;++ const codexInstructions = opts?.codexInstructions ?? CODEX_TITLE_INSTRUCTIONS;++ const maxOutputChars = opts?.maxOutputChars ?? TITLE_OUTPUT_MAX_CHARS;+ const maxVisualChars = opts?.maxVisualChars ?? 40;-try {let text = '';switch (target.wire) {@@@ -629,23 -567,14 +626,19 @@@break;}}- log.debug('oneShot raw response', {- wire: target.wire,- model: target.model,- responseLen: text?.length ?? 0,- });// The prompt is advisory; never persist a transcript continuation, role-labelled// response, Markdown wrapper, or multiline answer. Validate the complete response- // before applying the truncation, so a bad suffix cannot hide beyond the slice boundary.+ // before applying the historical 40-character auto-title truncation, so a bad suffix+ // cannot hide beyond the slice boundary.- const normalized = validateTitleOutput(text, TITLE_OUTPUT_MAX_CHARS);- const title = normalized ? Array.from(normalized).slice(0, 40).join('') : null;+ // `maxOutputChars === 0`: skip validation (non-title use cases like prompt prediction).+ const normalized =+ maxOutputChars > 0 ? validateTitleOutput(text, maxOutputChars) : text.trim() || null;- const result =++ const title =+ normalized && maxVisualChars > 0+ ? Array.from(normalized).slice(0, maxVisualChars).join('')+ : normalized;- if (!result) {- log.warn('oneShot rejected invalid model output', {+ if (!title) {+ log.warn('title oneShot rejected invalid model output', {providerId,model: target.model,wire: target.wire,diff --cc apps/desktop/src/main/maker-ipc/promptPrediction.tsindex ef19dda661,0000000000..ef05c7b262mode 100644,000000..100644--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts@@@ -1,205 -1,0 +1,211 @@@+/**+ * promptPrediction —— 输入框推荐提示词的 one-shot 预测。+ *- * 参考 provider-one-shot.ts 的实现模式:复用同一套 provider/凭证/model routing++ * 参考 title-one-shot.ts 的实现模式:复用同一套 provider/凭证/model routing+ * 基础设施,走 provider catalog 中的 titleModel(最经济模型)做单次 HTTP 请求,+ * 预测用户下一步会输入的提示词。不自己发 HTTP,不额外配置 endpoint。+ *+ * 与标题生成的差异:+ * - 触发时机:标题在首条用户消息发送时触发;推荐在 turn 完成后触发。+ * - prompt 构建:提取最近对话上下文,让模型预测下一步用户输入。+ * - 输出长度:标题 ≤20 字;推荐 ≤140 字符。+ * - 错误处理:失败静默返回 null,不 fallback 任何默认文案。+ */++import type { AgentKind } from '@cindy/maker-core';++import { getResolvedMainLocale } from '../i18n.js';+import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';- import { runProviderOneShot } from '../maker-host/provider-one-shot.js';++import { generateTitleViaProviderResult } from '../maker-host/title-one-shot.js';+import { connectedProvidersForAgent, type ProviderView } from '@cindy/model-providers';+import { eq } from 'drizzle-orm';+import { getDbClient } from '../localDb/client/current.js';+import { sessions } from '../localDb/schema.js';+import { createLogger } from '../logger.js';++const log = createLogger('maker-ipc/prompt-prediction');++/** 推荐素材:最近对话截断长度(UTF-16 code unit)。 */+const PREDICTION_CONTEXT_MAX_CHARS = 2000;+/** 单条消息截断长度。 */+const PREDICTION_USER_MSG_MAX = 400;+const PREDICTION_ASSISTANT_MSG_MAX = 600;+/** 最近 N 轮 user↔assistant 配对数。 */+const PREDICTION_RECENT_PAIRS = 3;++type SlimMessage = { role: string; content: string };++/**+ * 从对话历史里提取最近几轮 user↔assistant 配对,截断后拼接成 prompt 素材。+ * 跳过 tool_use / tool_result / thinking / error / system 等非对话角色。+ */+function buildConversationContext(+ messages: SlimMessage[],+ maxPairs: number,+): string {+ const conversational = messages.filter(+ (m) => m.role === 'user' || m.role === 'assistant',+ );+ // 从末尾往前取 maxPairs*2 条(user+assistant)+ const recent = conversational.slice(-maxPairs * 2);+ if (recent.length === 0) return '';++ const lines: string[] = [];+ for (const m of recent) {+ const maxChars = m.role === 'user' ? PREDICTION_USER_MSG_MAX : PREDICTION_ASSISTANT_MSG_MAX;+ const text = m.content.replace(/\s+/g, ' ').trim().slice(0, maxChars);+ if (!text) continue;+ lines.push(`${m.role === 'user' ? 'User' : 'Assistant'}: ${text}`);+ }- return lines.join('\n');++ // 超长时从最旧侧裁剪,保留最新对话(刚完成的回复与结尾指令不丢失)。++ const context = lines.join('\n');++ return context.length > PREDICTION_CONTEXT_MAX_CHARS++ ? context.slice(-PREDICTION_CONTEXT_MAX_CHARS)++ : context;+}++function escapeReferenceData(value: string): string {+ return value.replace(/[&<>]/gu, (char) => {+ if (char === '&') return '&';+ if (char === '<') return '<';+ return '>';+ });+}++function buildPredictionPrompt(+ context: string,+ locale: string,+ workingDir?: string,+): { system: string; user: string } {+ const languageHints: Record<string, string> = {+ 'zh-CN': "Match the user's language. The user types in Simplified Chinese.",+ en: "Match the user's language. The user types in English.",+ ja: "Match the user's language. The user types in Japanese.",+ ko: "Match the user's language. The user types in Korean.",+ };+ const wdLine = workingDir ? `Current working directory: ${escapeReferenceData(workingDir)}` : null;++ // 系统指令写入 Anthropic Messages API 顶层 system 字段(非 Anthropic wire 忽略),+ // 不混入 user message,避免被 Anthropic API 拒绝。+ const system = [+ 'You are a terse predictive text engine for a coding chat input.',+ 'Return only the predicted next user message — no quotes, markdown, commentary, or multiple options.',+ 'Keep it under 140 characters. Make it actionable for a coding agent.',+ languageHints[locale] ?? "Match the user's language and tone.",+ ].join('\n');++ const user = [+ 'Predict the next message the user is likely to type.',+ wdLine,+ '',+ '<recent_conversation>',+ escapeReferenceData(context),+ '</recent_conversation>',+ '',+ 'Return exactly one concise user prompt.',+ "Match the user's tone, brevity, phrasing, and terminology based on their recent messages.",+ 'Do not copy prior messages verbatim.',+ 'Make it actionable.',+ 'Keep it under 140 characters.',+ 'No quotes, markdown, commentary, explanations, or multiple options.',+ ]+ .filter((line): line is string => line !== null)+ .join('\n');++ return { system, user };+}++/** 从 DB 读 sessions.provider_id。失败/空串 → null。 */+async function readSessionProviderIdFromDb(sessionId: string): Promise<string | null> {+ if (!sessionId) return null;+ try {+ const [row] = await getDbClient()+ .drizzle.select({ providerId: sessions.providerId })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ return row?.providerId ?? null;+ } catch {+ return null;+ }+}++/** 某 agent 下已连接的供应商视图列表。失败 → []。 */+async function listConnectedProvidersForAgent(+ agentKind: AgentKind,+): Promise<ProviderView[]> {+ try {+ const all = await getDesktopProviderService().listProviders({ allowSideEffects: true });+ return connectedProvidersForAgent(all, agentKind);+ } catch {+ return [];+ }+}++export interface PromptPredictionParams {+ sessionId: string;+ agentKind: AgentKind;+ messages: SlimMessage[];+ workingDir?: string;+}++/**+ * 预测用户下一步可能输入的提示词。+ * 无已连接 provider / 无 titleModel / 凭证缺失 / HTTP 失败 / 空响应 → 返回 null。+ */+export async function generatePromptPrediction(+ params: PromptPredictionParams,+): Promise<string | null> {+ const context = buildConversationContext(params.messages, PREDICTION_RECENT_PAIRS);+ if (!context) {+ log.debug('prompt prediction skipped: no conversational context');+ return null;+ }++ const locale = getResolvedMainLocale();+ const { system: systemPrompt, user: userPrompt } = buildPredictionPrompt(+ context,+ locale,+ params.workingDir,+ );+- // 截断到上限(char 数),防止超长上下文撑爆 prompt- const truncated = userPrompt.slice(0, PREDICTION_CONTEXT_MAX_CHARS + 1024); // prompt 固定部分 ~200 chars++ // 截断到上限(char 数),防止超长上下文撑爆 prompt。保留最新内容(从尾部截断),++ // 确保刚完成的回复与结尾指令不被丢弃。++ const truncated = userPrompt.slice(-(PREDICTION_CONTEXT_MAX_CHARS + 1024)); // prompt 固定部分 ~200 chars++ // 仅记录长度用于调试,不记录对话内容避免敏感数据泄漏。+ log.debug('prompt prediction params', {+ contextLen: context.length,+ systemLen: systemPrompt.length,+ userLen: truncated.length,+ agentKind: params.agentKind,+ sessionId: params.sessionId,+ });++ // 复用 title one-shot 通路,但覆盖 token/校验参数以适配预测场景:+ // - maxTokens=96: 标题仅需 32 token,预测 ≤140 chars 需要更多+ // - codexInstructions: 告诉模型这是预测而非标题+ // - systemPrompt: Anthropic Messages API 顶层 system 字段(非 Anthropic wire 忽略)+ // - maxOutputChars=512: 恢复 validateTitleOutput 输出校验(拦截多行/Markdown/role label),再交给 maxVisualChars=140 做展示截断+ // - maxVisualChars=140: 截断到推荐提示词上限- return runProviderOneShot(++ const result = await generateTitleViaProviderResult(+ {+ sessionId: params.sessionId,+ agentKind: params.agentKind,+ prompt: truncated,+ },+ {+ readSessionProviderId: readSessionProviderIdFromDb,+ listConnectedProviders: listConnectedProvidersForAgent,+ },+ {+ maxTokens: 96,+ codexInstructions:+ 'Output only the predicted next user message — no quotes, markdown, or commentary.',+ systemPrompt,+ maxOutputChars: 512,+ maxVisualChars: 140,+ },+ );++ return result.status === 'ok' ? result.title : null;+}diff --cc apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 43daa148b1,794636c46b..58756e6724--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@@ -4746,27 -4558,19 +4746,35 @@@ export function ChatInput(// 追加"必须走 cindy 总机"的机器指令;未命中原样发送。// 读取 useInstalledGhosts 的最新窗口级快照。ghosts:changed 会原子更新// 该快照;发送路径无需同步 IPC,仍按当前工作目录执行同一禁用判定。+ const eligibleGhosts = filterGhostsForWorkdir(+ installedGhostsRef.current,+ workingDirRef.current,+ );const ghostCommandWord = parseGhostCommandWord(text);- const usedGhost = hostCapabilityGhost- ? hostCapabilityGhost- : ghostCommandWord- ? findGhostByCommand(eligibleGhosts, ghostCommandWord)- : null;- const textToSend = hostCapability- ? expandHostCapabilityInvocation(- text,- hostCapability,- t('rightSidebar.iosSimulator.startPrompt'),- )- : expandGhostCommand(text, eligibleGhosts);+ const usedGhost = ghostCommandWord+ ? findGhostByCommand(eligibleGhosts, ghostCommandWord)+ : null;+ const textToSend = expandGhostCommand(text, eligibleGhosts);+ // 发送前校验 host-capability 插件仍处于启用且 workdir 可用的状态。+ // 若用户在插入芯片后停用/卸载了该插件,芯片内序列化的 ghostId/capability+ // 已失时效,不应再展开 Host 路由指令(fail-closed)。++ // 额外收口(remote session + manifest 一致性):++ // - SSH(remoteHostId)/device-link(deviceLinkDeviceId) 远程会话不展开控制端 Host 路由;++ // - 插件更新后芯片保留旧 capability 时,manifest 当前声明必须仍匹配才放行。+ const isHostCapabilityValid =+ hostCapability !== undefined &&++ !remoteHostId &&++ !deviceLinkDeviceId &&+ eligibleGhosts.some(- (g) => g.manifest.id === hostCapability.ghostId && g.enabled,++ (g) =>++ g.manifest.id === hostCapability.ghostId &&++ g.enabled &&++ hostCapabilityForGhost(g) === hostCapability.capability,+ );+ const routedText =+ hostCapability && isHostCapabilityValid+ ? expandHostCapabilityInvocation(textToSend, hostCapability, hostCapability.name)+ : textToSend;const sendSnapshot = captureComposerSendSnapshot(editor.getJSON(),latestAttachmentsRef.current,