Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(chat): add vendor native web search in composer
LectWolf15d7663e43dc
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex f7d7bd5e6..855b2c177 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -607,6 +607,7 @@ export function createSessionLaunchRuntime({),...(overrides.turnId ? { turnId: overrides.turnId } : {}),thinkingLevel,+ nativeWebSearch: settings?.nativeWebSearchEnabled === true,commandShell,scratchDir: join(dataDir, "scratch", sessionId),attachmentsDir: join(dataDir, "attachments"),diff --git a/apps/desktop/src/components/CitationBadge.tsx b/apps/desktop/src/components/CitationBadge.tsxnew file mode 100644index 000000000..9a67ba853--- /dev/null+++ b/apps/desktop/src/components/CitationBadge.tsx@@ -0,0 +1,171 @@+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useId,+ useRef,+ useState,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import { useTranslation } from "react-i18next";+import type { HostedSearchSource } from "@pi-desktop/shared";+import { HostedSearchFavicon } from "./HostedSearchFavicon";+import { IconChevronLeft, IconChevronRight } from "./icons";+import {+ hostedSearchLabel,+ hostedSearchTitle,+ openChatHttpUrl,+ sourcesForHref,+} from "../lib/hosted-search-ui";++const HostedSearchCitationsContext = createContext<readonly HostedSearchSource[]>([]);++export function HostedSearchCitationsProvider({+ sources,+ children,+}: {+ sources: readonly HostedSearchSource[];+ children: ReactNode;+}) {+ return (+ <HostedSearchCitationsContext.Provider value={sources}>+ {children}+ </HostedSearchCitationsContext.Provider>+ );+}++export function useHostedSearchCitationSources(+ href: string | undefined,+): HostedSearchSource[] {+ const sources = useContext(HostedSearchCitationsContext);+ return sourcesForHref(href, sources);+}++function formatPublishedAt(value: string | undefined): string {+ if (!value?.trim()) return "";+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return value.trim();+ return date.toLocaleDateString();+}++export function CitationBadge({ sources }: { sources: HostedSearchSource[] }) {+ const { t } = useTranslation();+ const cardId = useId();+ const [open, setOpen] = useState(false);+ const [index, setIndex] = useState(0);+ const rootRef = useRef<HTMLSpanElement | null>(null);+ const cardRef = useRef<HTMLDivElement | null>(null);+ const hideTimer = useRef<number | null>(null);+ const current = sources[Math.min(index, sources.length - 1)];++ const cancelHide = () => {+ if (hideTimer.current !== null) {+ window.clearTimeout(hideTimer.current);+ hideTimer.current = null;+ }+ };+ const show = () => {+ cancelHide();+ setOpen(true);+ };+ const hide = () => {+ cancelHide();+ hideTimer.current = window.setTimeout(() => setOpen(false), 120);+ };++ useEffect(() => () => cancelHide(), []);++ const openSource = useCallback(+ (source: HostedSearchSource | undefined) => {+ if (!source) return;+ openChatHttpUrl(source.url);+ },+ [],+ );++ if (!current) return null;+ const extra = sources.length - 1;+ const label = hostedSearchLabel(current);+ const title = hostedSearchTitle(current);+ const published = formatPublishedAt(current.publishedAt);+ const rect = rootRef.current?.getBoundingClientRect();++ return (+ <span+ ref={rootRef}+ className="citation-badge-wrap"+ onMouseEnter={show}+ onMouseLeave={hide}+ >+ <button+ type="button"+ className="citation-badge"+ aria-describedby={open ? cardId : undefined}+ onClick={() => openSource(current)}+ >+ <HostedSearchFavicon url={current.url} size={12} />+ <span className="citation-badge-label">{label}</span>+ {extra > 0 ? <span className="citation-badge-extra">+{extra}</span> : null}+ </button>+ {open && rect+ ? createPortal(+ <div+ ref={cardRef}+ id={cardId}+ role="tooltip"+ className="citation-card"+ style={{+ top: rect.bottom + 8,+ left: Math.min(rect.left, window.innerWidth - 320),+ }}+ onMouseEnter={show}+ onMouseLeave={hide}+ >+ {sources.length > 1 ? (+ <div className="citation-card-nav">+ <button+ type="button"+ className="citation-card-nav-btn"+ aria-label={t("chat.webSearchCitationPrev")}+ onClick={() =>+ setIndex((value) => (value - 1 + sources.length) % sources.length)+ }+ >+ <IconChevronLeft size={14} />+ </button>+ <span>+ {index + 1}/{sources.length}+ </span>+ <button+ type="button"+ className="citation-card-nav-btn"+ aria-label={t("chat.webSearchCitationNext")}+ onClick={() => setIndex((value) => (value + 1) % sources.length)}+ >+ <IconChevronRight size={14} />+ </button>+ </div>+ ) : null}+ <button+ type="button"+ className="citation-card-body"+ onClick={() => openSource(current)}+ >+ <HostedSearchFavicon url={current.url} size={28} />+ <span className="citation-card-copy">+ <span className="citation-card-publisher">{label}</span>+ <span className="citation-card-title">{title}</span>+ {published ? (+ <span className="citation-card-date">{published}</span>+ ) : null}+ </span>+ </button>+ </div>,+ document.body,+ )+ : null}+ </span>+ );+}diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex 2ffc3cfc8..0b41a7432 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -11,12 +11,14 @@ import type {PermissionMode,} from "@pi-desktop/shared";import {+ supportsNativeWebSearch,initialThinkingLevelForBinding,modelIdsMatch,normalizeLargePasteThreshold,stripInlineComposerFileReferenceTokens,} from "@pi-desktop/shared";import { useAppStore } from "../stores/app-store";+import { api } from "../lib/api";import { latestTurnContextInspector } from "../lib/latest-turn-context";import { isActivePlanExecution } from "../lib/plan-mode-state";import { headAsk, queuedAskCount } from "../lib/pending-asks";@@ -118,6 +120,7 @@ export function Composer({[liveMessages, providerModels, providers, sessionCompactions],);const configureActiveSession = useAppStore((s) => s.configureActiveSession);+ const nativeWebSearchEnabled = useAppStore((s) => Boolean(s.settings?.nativeWebSearchEnabled));const showToast = useAppStore((s) => s.showToast);const composerPrefill = useAppStore((s) => s.composerPrefill);const clearComposerPrefill = useAppStore((s) => s.clearComposerPrefill);@@ -608,6 +611,29 @@ export function Composer({hasDraftContent={hasDraftContent}abort={abort}submit={submit}+ nativeWebSearchEnabled={nativeWebSearchEnabled}+ nativeWebSearchSupported={supportsNativeWebSearch({+ apiStyle: provider?.apiStyle,+ vendorKey: provider?.vendorKey,+ baseUrl: provider?.baseUrl,+ })}+++ onToggleNativeWebSearch={() => {+ const settings = useAppStore.getState().settings;+ if (!settings) return;+ const next = {+ ...settings,+ nativeWebSearchEnabled: !settings.nativeWebSearchEnabled,+ };+ void api.setSettings(next).then(() => {+ useAppStore.setState({ settings: next });+ }).catch((error) => {+ showToast(error instanceof Error ? error.message : String(error), {+ variant: "error",+ });+ });+ }}/></div></div>diff --git a/apps/desktop/src/components/HostedSearchFavicon.tsx b/apps/desktop/src/components/HostedSearchFavicon.tsxnew file mode 100644index 000000000..8e4874358--- /dev/null+++ b/apps/desktop/src/components/HostedSearchFavicon.tsx@@ -0,0 +1,37 @@+import { useMemo, useState } from "react";+import { hostedSearchFaviconCandidates } from "../lib/hosted-search-ui";++export function HostedSearchFavicon({+ url,+ size = 14,+}: {+ url: string;+ size?: number;+}) {+ const candidates = useMemo(() => hostedSearchFaviconCandidates(url), [url]);+ const [index, setIndex] = useState(0);+ const src = candidates[index];+ if (!src) {+ return (+ <span+ className="hosted-search-favicon hosted-search-favicon-fallback"+ style={{ width: size, height: size }}+ aria-hidden+ />+ );+ }+ return (+ <img+ alt=""+ aria-hidden="true"+ className="hosted-search-favicon"+ decoding="async"+ loading="lazy"+ referrerPolicy="no-referrer"+ src={src}+ width={size}+ height={size}+ onError={() => setIndex((current) => current + 1)}+ />+ );+}diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 02b837c09..10b83f1b6 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -37,6 +37,7 @@ import {IconWorkflow,} from "./icons";import { TooltipButton } from "./ui";+import { CitationBadge, useHostedSearchCitationSources } from "./CitationBadge";import { createPortal } from "react-dom";import { api } from "../lib/api";import {@@ -501,6 +502,7 @@ function Anchor({const openUrl = useAppStore((s) => s.openUrlInWorkPanel);const showToast = useAppStore((s) => s.showToast);const linkOpenTarget = useAppStore((s) => s.settings?.linkOpenTarget ?? "workpanel");+ const citationSources = useHostedSearchCitationSources(href);const [menuPosition, setMenuPosition] = useState<{ top: number; left: number } | null>(null);const menuRef = useRef<HTMLDivElement | null>(null);@@ -582,6 +584,10 @@ function Anchor({// Plain click previews in the work panel (or external browser based on setting).// Modified clicks fall through to _blank, which main routes to shell.openExternal.+ if (citationSources.length > 0) {+ return <CitationBadge sources={citationSources} />;+ }+const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;if (!href) return;diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsxindex d2c899052..6260d88fb 100644--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx@@ -16,6 +16,7 @@ import {IconCheck,IconChevronDown,IconPlus,+ IconGlobe,IconSparkles,IconStop,IconUndo2,@@ -64,6 +65,9 @@ export type ComposerToolbarProps = {hasDraftContent: boolean;abort: AppState["abort"];submit: () => Promise<void>;+ nativeWebSearchEnabled: boolean;+ nativeWebSearchSupported: boolean;+ onToggleNativeWebSearch: () => void;};/** Composer controls: mode, permission, model, enhancement, and send/stop. */@@ -99,6 +103,9 @@ export function ComposerToolbar({hasDraftContent,abort,submit,+ nativeWebSearchEnabled,+ nativeWebSearchSupported,+ onToggleNativeWebSearch,}: ComposerToolbarProps) {const platform = (window.piDesktop?.platform ?? "darwin") as ShortcutPlatform;const steeringShortcut = keybindingDisplayParts("Alt+Enter", platform).join("+");@@ -232,6 +239,31 @@ export function ComposerToolbar({<div className="composer-right">{contextUsage ? <ContextUsageInspector {...contextUsage} /> : null}+ <TooltipButton+ type="button"+ className={`icon-btn icon-btn-square ${nativeWebSearchEnabled && nativeWebSearchSupported ? "composer-web-search-on" : ""}`}+ tooltip={+ nativeWebSearchSupported+ ? nativeWebSearchEnabled+ ? t("chat.webSearchOn")+ : t("chat.webSearchOff")+ : t("chat.webSearchUnsupported")+ }+ ariaLabel={+ nativeWebSearchSupported+ ? nativeWebSearchEnabled+ ? t("chat.webSearchOn")+ : t("chat.webSearchOff")+ : t("chat.webSearchUnsupported")+ }+ disabled={controlsBlocked || !nativeWebSearchSupported}+ onClick={() => {+ setPermissionOpen(false);+ onToggleNativeWebSearch();+ }}+ >+ <IconGlobe size={15} aria-hidden="true" />+ </TooltipButton><ComposerModelPickert={t}controller={modelMenu}diff --git a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsxindex 201ca15bd..da91ae2d7 100644--- a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx+++ b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx@@ -52,6 +52,7 @@ import {} from "./shared";import { SubagentTopology } from "./SubagentDetail";import { ToolRow } from "./ToolRow";+import { HostedSearchRow } from "./HostedSearchRow";import { TranscriptSearchContext } from "../../../lib/transcript-search-context";import { useAppStore } from "../../../stores/app-store";import { resolveThinkingDisplayMode } from "../../../lib/turn-process";@@ -69,6 +70,10 @@ export function activityItemDetail(item: ActivityItem): string {.filter(Boolean);return lines[lines.length - 1] || "";}+ if (item.kind === "hostedSearch") {+ const search = item.message.hostedSearch;+ return search?.queries[0] || search?.sources[0]?.title || search?.sources[0]?.url || "";+ }if (lifecycleKindOf(item.message)) {return delegationRosterSummary(delegationRoster(item.message));}@@ -340,16 +345,30 @@ export const ActivityGroup = memo(function ActivityGroup({/>);}- return item.kind === "tool" ? (- <Fragment key={item.message.id}>- <ToolRow+ if (item.kind === "tool") {+ return (+ <Fragment key={item.message.id}>+ <ToolRow+ message={item.message}+ onUserInteraction={claimDisclosure}+ {...(item.delegate ? { delegate: item.delegate } : {})}+ />+ <ReviewChangeCard message={item.message} />+ </Fragment>+ );+ }+ if (item.kind === "hostedSearch") {+ return (+ <HostedSearchRow+ key={`hosted-search-${item.message.id}`}message={item.message}+ streaming={isActive && item.message.status === "streaming"}+ autoOpen={live && itemIndex === items.length - 1}onUserInteraction={claimDisclosure}- {...(item.delegate ? { delegate: item.delegate } : {})}/>- <ReviewChangeCard message={item.message} />- </Fragment>- ) : (+ );+ }+ return (<ThinkingRowkey={`thinking-${item.message.id}`}message={item.message}diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex bbf95b96c..e7982b809 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -7,6 +7,7 @@ import { useTranslation } from "react-i18next";import type {AgentActivity,ContextCompactionMark,+ HostedSearchSource,} from "@pi-desktop/shared";import { formatCompactTokenCount } from "@pi-desktop/shared";import {@@ -28,6 +29,8 @@ import {import { projectTurnProcess } from "../../../lib/turn-process";import { useAppStore } from "../../../stores/app-store";import { Markdown } from "../../../components/Markdown";+import { rewriteInlineCitationMarkup } from "../../../lib/hosted-search-ui";+import { HostedSearchCitationsProvider } from "../../../components/CitationBadge";import { IconBranch, IconReview } from "../../../components/icons";import { TooltipButton } from "../../../components/ui";import {@@ -277,6 +280,18 @@ export const AssistantTurn = memo(function AssistantTurn({timingsRef.current = turnDelegationTimings;const { process, responses } = projectTurnProcess(entry);const activePart = isActive ? entry.parts.at(-1) : undefined;+ const citationSources = useMemo(() => {+ const sources: HostedSearchSource[] = [];+ const seen = new Set<string>();+ for (const message of messages) {+ for (const source of message.hostedSearch?.sources ?? []) {+ if (seen.has(source.url)) continue;+ seen.add(source.url);+ sources.push(source);+ }+ }+ return sources;+ }, [messages]);const renderPart = (part: AssistantTurnPart) =>part.kind === "activity" ? (@@ -302,7 +317,9 @@ export const AssistantTurn = memo(function AssistantTurn({>{part.message.content ? (<div className="prose-chat">- <Markdown source={part.message.content} />+ <Markdown+ source={rewriteInlineCitationMarkup(part.message.content, citationSources)}+ /></div>) : null}{part.message.error ? (@@ -312,6 +329,7 @@ export const AssistantTurn = memo(function AssistantTurn({);return (+ <HostedSearchCitationsProvider sources={citationSources}><divclassName={`message-row assistant assistant-turn${streaming ? " streaming" : ""}`}data-minimap-id={entry.anchorId}@@ -361,6 +379,7 @@ export const AssistantTurn = memo(function AssistantTurn({) : null}</div></div>+ </HostedSearchCitationsProvider>);}, assistantTurnPropsEqual);diff --git a/apps/desktop/src/features/chat/transcript/HostedSearchRow.tsx b/apps/desktop/src/features/chat/transcript/HostedSearchRow.tsxnew file mode 100644index 000000000..3a2cf36c7--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/HostedSearchRow.tsx@@ -0,0 +1,126 @@+import { memo, useCallback, useId, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { hostedSearchHasContent, type UiMessage } from "@pi-desktop/shared";+import { HostedSearchFavicon } from "../../../components/HostedSearchFavicon";+import { IconChevronRight, IconGlobe, IconSearch } from "../../../components/icons";+import {+ HOSTED_SEARCH_PREVIEW_COUNT,+ hostedSearchHost,+ hostedSearchTitle,+ openChatHttpUrl,+} from "../../../lib/hosted-search-ui";+import { useAutomaticDisclosure } from "./shared";++export const HostedSearchRow = memo(function HostedSearchRow({+ message,+ streaming,+ autoOpen = false,+ onUserInteraction,+}: {+ message: UiMessage;+ streaming: boolean;+ autoOpen?: boolean;+ onUserInteraction?: () => void;+}) {+ const { t } = useTranslation();+ const detailsId = useId();+ const search = message.hostedSearch;+ const disclosure = useAutomaticDisclosure(+ autoOpen && search?.status === "completed",+ );+ const { open, toggle: toggleDisclosure } = disclosure;+ const [showAll, setShowAll] = useState(false);+ const toggleRow = useCallback(() => {+ onUserInteraction?.();+ toggleDisclosure();+ }, [onUserInteraction, toggleDisclosure]);++ const queries = useMemo(+ () => (search?.queries ?? []).map((item) => item.trim()).filter(Boolean),+ [search?.queries],+ );+ const sources = search?.sources ?? [];+ const visibleSources = showAll+ ? sources+ : sources.slice(0, HOSTED_SEARCH_PREVIEW_COUNT);+ const hiddenCount = Math.max(0, sources.length - visibleSources.length);+ const running = Boolean(streaming && search?.status === "searching");++ if (!search || (!hostedSearchHasContent(search) && !running)) return null;++ const title = running+ ? t("chat.webSearchRunning")+ : t("chat.webSearchSummary", {+ searchCount: Math.max(queries.length, 1),+ sourceCount: sources.length,+ });++ return (+ <section className={`hosted-search-row${open ? " open" : ""}${running ? " running" : ""}`}>+ <button+ type="button"+ ref={disclosure.titleRef}+ className="tool-activity-header"+ aria-expanded={open}+ aria-controls={detailsId}+ aria-label={t(open ? "chat.webSearchHide" : "chat.webSearchShow")}+ onClick={toggleRow}+ >+ <span className="tool-activity-icon" aria-hidden>+ {running ? <span className="tool-spinner" /> : <IconGlobe size={14} />}+ </span>+ <span className={`tool-activity-label${running ? " running" : ""}`}>{title}</span>+ <span className="tool-activity-caret" aria-hidden>+ <IconChevronRight size={12} />+ </span>+ </button>+ <div id={detailsId} className="hosted-search-body" hidden={!open}>+ {queries.length > 0 ? (+ <ul className="hosted-search-queries">+ {queries.map((query) => (+ <li key={query} className="hosted-search-query">+ <IconSearch size={12} aria-hidden />+ <span>{query}</span>+ </li>+ ))}+ </ul>+ ) : null}+ {sources.length > 0 ? (+ <ul className="hosted-search-sources">+ {visibleSources.map((source) => {+ const host = hostedSearchHost(source.url);+ const label = hostedSearchTitle(source);+ return (+ <li key={source.url}>+ <button+ type="button"+ className="hosted-search-source"+ title={`${label} ${host}`}+ onClick={() => openChatHttpUrl(source.url)}+ >+ <HostedSearchFavicon url={source.url} />+ <span className="hosted-search-source-main">+ <span className="hosted-search-source-title">{label}</span>+ <span className="hosted-search-source-host">{host}</span>+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ ) : (+ <p className="hosted-search-empty">{t("chat.webSearchEmpty")}</p>+ )}+ {hiddenCount > 0 ? (+ <button+ type="button"+ className="hosted-search-more"+ onClick={() => setShowAll(true)}+ >+ {t("chat.webSearchMore", { count: hiddenCount })}+ </button>+ ) : null}+ </div>+ </section>+ );+});diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 69fe4f46f..3a11c854f 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -9,6 +9,7 @@ import { useOpenChatFileRef } from "../../../hooks/use-preview-target";import { splitChatText } from "../../../lib/chat-links";import { useAppStore } from "../../../stores/app-store";import { Markdown } from "../../../components/Markdown";+import { rewriteInlineCitationMarkup } from "../../../lib/hosted-search-ui";import {IconChevronLeft,IconChevronRight,@@ -192,7 +193,7 @@ export const MessageRow = memo(function MessageRow({</>) : (<div className="prose-chat">- <Markdown source={displayed} />+ <Markdown source={rewriteInlineCitationMarkup(displayed, message.hostedSearch?.sources ?? [])} /></div>)}</div>diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex 86fbc4c43..859bdf053 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -1,12 +1,14 @@-import type {- ContextCompactionMark,- MessageUsage,- UiMessage,+import {+ hostedSearchHasContent,+ type ContextCompactionMark,+ type MessageUsage,+ type UiMessage,} from "@pi-desktop/shared";import { isDelegationStartTool } from "./tool-display";export type AssistantActivityItem =| { kind: "thinking"; message: UiMessage }+ | { kind: "hostedSearch"; message: UiMessage }| {kind: "tool";message: UiMessage;@@ -241,6 +243,9 @@ export function buildTranscriptEntries(const current = ensureTurn(message);const thinking = messageThinking(message);if (thinking) pushActivity({ kind: "thinking", message });+ if (hostedSearchHasContent(message.hostedSearch)) {+ pushActivity({ kind: "hostedSearch", message });+ }if ((message.content || "").trim() || !thinking || message.error) {current.parts.push({ kind: "message", message });if (!current.anchorId && (message.content || "").trim()) {diff --git a/apps/desktop/src/lib/hosted-search-ui.ts b/apps/desktop/src/lib/hosted-search-ui.tsnew file mode 100644index 000000000..deb9d21fb--- /dev/null+++ b/apps/desktop/src/lib/hosted-search-ui.ts@@ -0,0 +1,109 @@+import type { HostedSearchSource } from "@pi-desktop/shared";+import { api } from "./api";+import { useAppStore } from "../stores/app-store";++export const HOSTED_SEARCH_PREVIEW_COUNT = 5;++export function hostedSearchHost(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./, "");+ } catch {+ return url;+ }+}++export function hostedSearchFaviconCandidates(url: string): string[] {+ try {+ const parsed = new URL(url);+ const host = parsed.hostname;+ const remote = `https://a.favicon.im/${encodeURIComponent(host)}?larger=true`;+ return parsed.protocol === "https:"+ ? [`${parsed.origin}/favicon.ico`, remote]+ : [remote];+ } catch {+ return [];+ }+}++export function hostedSearchLabel(source: HostedSearchSource): string {+ return source.publisher?.trim() || hostedSearchHost(source.url);+}++function looksLikeUrl(value: string): boolean {+ return /^https?:\/\//i.test(value.trim());+}++/** Visible title for a source. Never falls back to the raw URL or a citation index. */+export function hostedSearchTitle(source: HostedSearchSource): string {+ const title = source.title?.trim() ?? "";+ if (title && !looksLikeUrl(title) && !/^\d+$/.test(title)) return title;+ return hostedSearchHost(source.url);+}+++const INLINE_CITATION_TOKEN =+ /\{\s*render_inline_citation(?:\s*\([^}]*\)|\s+[^}]+)\s*\}|\brender_inline_citation\s*\([^)]*\)/gi;++/** Turn Grok `{render_inline_citation(citation_id=N)}` / `{render_inline_citation citation_id="N"}` into cite links. */+export function rewriteInlineCitationMarkup(+ text: string,+ sources: readonly HostedSearchSource[],+): string {+ if (!text.includes("render_inline_citation")) return text;+ return text.replace(new RegExp(`(?:${INLINE_CITATION_TOKEN.source})+`, "gi"), (run) => {+ const ids = [...run.matchAll(/citation_id\s*=\s*["']?(\d+)["']?/gi)].map((match) =>+ Number(match[1]),+ );+ const valid = ids.filter((id) => sources[id - 1] || sources[id]);+ if (valid.length === 0) return "";+ return `[ ](#cite=${valid.join(",")})`;+ });+}++export function urlsReferToSameSource(left: string, right: string): boolean {+ try {+ const a = new URL(left);+ const b = new URL(right);+ return (+ a.hostname.replace(/^www\./, "") === b.hostname.replace(/^www\./, "") &&+ a.pathname.replace(/\/$/, "") === b.pathname.replace(/\/$/, "")+ );+ } catch {+ return left === right;+ }+}++export function sourcesForHref(+ href: string | undefined,+ sources: readonly HostedSearchSource[],+): HostedSearchSource[] {+ if (!href) return [];+ const hashIndex = href.indexOf("#cite=");+ const citeRef = hashIndex >= 0 ? href.slice(hashIndex) : href;+ const citeIds = citeRef.match(/^#cite=([\d,]+)$/);+ if (citeIds) {+ const matched: HostedSearchSource[] = [];+ for (const raw of citeIds[1].split(",")) {+ const id = Number(raw);+ const source = sources[id - 1] ?? sources[id];+ if (source) matched.push(source);+ }+ return matched;+ }+ const direct = sources.filter((source) => urlsReferToSameSource(source.url, href));+ if (direct.length > 0) return direct;+ const host = hostedSearchHost(href);+ if (!host) return [];+ return sources.filter((source) => hostedSearchHost(source.url) === host);+}++export function openChatHttpUrl(url: string): void {+ const trimmed = url.trim();+ if (!/^https?:\/\//i.test(trimmed)) return;+ const target = useAppStore.getState().settings?.linkOpenTarget ?? "workpanel";+ if (target === "external") {+ void api.browserOpenExternal(trimmed);+ return;+ }+ useAppStore.getState().openUrlInWorkPanel(trimmed);+}diff --git a/apps/desktop/src/styles/composer-menus.css b/apps/desktop/src/styles/composer-menus.cssindex 920b57860..b5cb4c3c2 100644--- a/apps/desktop/src/styles/composer-menus.css+++ b/apps/desktop/src/styles/composer-menus.css@@ -30,6 +30,11 @@color: color-mix(in oklab, var(--gray-0) 78%, transparent);}+:root[data-theme="dark"] .composer-toolbar .icon-btn.composer-web-search-on,+:root[data-theme="dark"] .composer-toolbar .icon-btn.composer-web-search-on:hover {+ color: #34d399;+}+:root[data-theme="dark"] .empty-hero-icon {color: var(--gray-0);opacity: 1;diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.cssindex a6c1b2c05..d6aa36b8d 100644--- a/apps/desktop/src/styles/composer.css+++ b/apps/desktop/src/styles/composer.css@@ -399,6 +399,18 @@color: var(--ds-text-primary);}+.composer-toolbar .icon-btn.composer-web-search-on,+.composer-toolbar .icon-btn.composer-web-search-on:hover,+.composer-right .icon-btn.composer-web-search-on,+.composer-right .icon-btn.composer-web-search-on:hover {+ color: #059669;+}+:root[data-theme="dark"] .composer-toolbar .icon-btn.composer-web-search-on,+:root[data-theme="dark"] .composer-toolbar .icon-btn.composer-web-search-on:hover,+:root[data-theme="dark"] .composer-right .icon-btn.composer-web-search-on,+:root[data-theme="dark"] .composer-right .icon-btn.composer-web-search-on:hover {+ color: #34d399;+}.icon-btn.active {background: var(--ds-bg-active);color: var(--ds-text-primary);diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.cssindex 38cb624e1..f61992b22 100644--- a/apps/desktop/src/styles/messages.css+++ b/apps/desktop/src/styles/messages.css@@ -2981,3 +2981,189 @@display: inline-flex;color: var(--ds-error);}++.hosted-search-row.open > .tool-activity-header > .tool-activity-caret {+ transform: rotate(90deg);+}+.hosted-search-body {+ min-width: 0;+ max-width: 100%;+ padding: 4px 0 2px 22px;+}+.hosted-search-body[hidden] {+ display: none;+}+.hosted-search-queries,+.hosted-search-sources {+ margin: 0;+ padding: 0;+ list-style: none;+}+.hosted-search-queries {+ margin-bottom: 10px;+ padding-bottom: 8px;+ border-bottom: 1px solid var(--ds-border, color-mix(in oklab, var(--ds-text-primary) 12%, transparent));+}+.hosted-search-sources {+ max-height: 220px;+ overflow: auto;+}+.hosted-search-query,+.hosted-search-source {+ display: flex;+ min-width: 0;+ width: 100%;+ align-items: center;+ gap: 8px;+ padding: 4px 0;+ color: var(--ds-text-secondary);+ font-size: var(--text-sm);+ text-align: left;+}+.hosted-search-query svg {+ flex: none;+ opacity: 0.7;+}+.hosted-search-source:hover {+ color: var(--ds-text-primary);+}+.hosted-search-source-main {+ display: flex;+ min-width: 0;+ flex: 1;+ align-items: baseline;+ gap: 8px;+}+.hosted-search-source-title {+ flex: 1 1 0;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.hosted-search-source-host {+ flex: 0 1 auto;+ max-width: 42%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--ds-text-muted);+}+.hosted-search-more {+ margin-top: 4px;+ color: var(--ds-text-secondary);+ font-size: var(--text-sm);+}+.hosted-search-more:hover {+ color: var(--ds-text-primary);+}+.hosted-search-empty {+ margin: 4px 0 0;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+}+.hosted-search-favicon {+ flex: none;+ border-radius: 3px;+ object-fit: contain;+ background: var(--ds-bg-hover);+}+.hosted-search-favicon-fallback {+ display: inline-block;+ border-radius: 999px;+ background: var(--ds-bg-active);+}+.citation-badge-wrap {+ display: inline-flex;+ margin: 0 0.15em;+ vertical-align: middle;+}+.citation-badge {+ display: inline-flex;+ max-width: 12em;+ align-items: center;+ gap: 4px;+ padding: 1px 6px 1px 4px;+ border-radius: 999px;+ background: var(--ds-bg-hover);+ color: var(--ds-text-secondary);+ font-size: var(--text-xs);+ line-height: 1.4;+ vertical-align: middle;+}+.citation-badge:hover {+ color: var(--ds-text-primary);+}+.citation-badge-label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.citation-badge-extra {+ color: var(--ds-text-muted);+}+.citation-card {+ position: fixed;+ z-index: 40;+ width: 280px;+ padding: 10px 12px;+ border-radius: 12px;+ background: var(--ds-bg-primary);+ opacity: 1;+ backdrop-filter: none;+ box-shadow: 0 10px 32px color-mix(in oklab, black 38%, transparent);+ color: var(--ds-text-primary);+}+:root[data-theme="light"] .citation-card {+ background: #ffffff;+}+:root[data-theme="dark"] .citation-card {+ background: #1f2125;+}+.citation-card-nav {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 6px;+ margin-bottom: 8px;+ color: var(--ds-text-muted);+ font-size: var(--text-xs);+}+.citation-card-nav-btn {+ display: inline-flex;+ color: var(--ds-text-secondary);+}+.citation-card-body {+ display: flex;+ width: 100%;+ min-width: 0;+ align-items: flex-start;+ gap: 10px;+ text-align: left;+}+.citation-card-copy {+ display: flex;+ min-width: 0;+ flex: 1;+ flex-direction: column;+ gap: 2px;+}+.citation-card-publisher {+ color: var(--ds-text-muted);+ font-size: var(--text-xs);+}+.citation-card-title {+ display: -webkit-box;+ overflow: hidden;+ font-size: var(--text-sm);+ line-height: 1.35;+ overflow-wrap: anywhere;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ line-clamp: 2;+}++.citation-card-date {+ color: var(--ds-text-muted);+ font-size: var(--text-xs);+}diff --git a/apps/desktop/src/styles/theme-overrides.css b/apps/desktop/src/styles/theme-overrides.cssindex 8ef838815..3f2e887f6 100644--- a/apps/desktop/src/styles/theme-overrides.css+++ b/apps/desktop/src/styles/theme-overrides.css@@ -63,6 +63,11 @@color: color-mix(in oklab, var(--ds-text-primary) 84%, transparent) !important;}+:root[data-theme="light"] .composer-toolbar .icon-btn.composer-web-search-on,+:root[data-theme="light"] .composer-toolbar .icon-btn.composer-web-search-on:hover {+ color: #059669 !important;+}+:root[data-theme="light"] .composer-input::placeholder,:root[data-theme="light"] .composer-placeholder {/* Gold empty-home placeholder ink (--ds-placeholder-ink). */diff --git a/apps/desktop/test/assistant-turns.test.mjs b/apps/desktop/test/assistant-turns.test.mjsindex 46453fba1..863574d32 100644--- a/apps/desktop/test/assistant-turns.test.mjs+++ b/apps/desktop/test/assistant-turns.test.mjs@@ -530,3 +530,22 @@ test("reuses unchanged activity parts when only the tail thinking token changes"assert.notEqual(sharedThink, firstThink);assert.equal(sharedThink.items[0].message, nextThinking);});++test("surfaces hosted search as an activity row with an icon-bearing message", () => {+ const assistant = message("a1", "assistant", "Here is what I found.", {+ hostedSearch: {+ status: "completed",+ queries: ["pi-desktop web search"],+ sources: [{ url: "https://example.com", title: "Example" }],+ },+ });+ const { entries } = buildTranscriptEntries([+ message("u1", "user", "Search that"),+ assistant,+ ]);+ const turn = entries.find((entry) => entry.kind === "assistant-turn");+ assert.ok(turn);+ const activity = turn.parts.find((part) => part.kind === "activity");+ assert.equal(activity?.items[0]?.kind, "hostedSearch");+ assert.equal(activity.items[0].message.hostedSearch.sources[0].url, "https://example.com");+});diff --git a/apps/desktop/test/hosted-search-ui.test.mjs b/apps/desktop/test/hosted-search-ui.test.mjsnew file mode 100644index 000000000..9c0f4ddda--- /dev/null+++ b/apps/desktop/test/hosted-search-ui.test.mjs@@ -0,0 +1,63 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));+const {+ hostedSearchTitle,+ rewriteInlineCitationMarkup,+ sourcesForHref,+} = await import("../src/lib/hosted-search-ui.ts");++const sources = [+ { url: "https://example.com/a", title: "Alpha" },+ { url: "https://example.com/b", title: "Beta" },+ { url: "https://news.example.com/c" },+ { url: "https://www.bing.com/search?q=tibo", title: "https://www.bing.com/search?q=tibo" },+];++test("rewrites Grok inline citation placeholders into cite links", () => {+ const text = rewriteInlineCitationMarkup(+ "Hello {render_inline_citation(citation_id=4)} world",+ sources,+ );+ assert.equal(text, "Hello [ ](#cite=4) world");+});++test("rewrites space-separated quoted Grok citation placeholders", () => {+ const text = rewriteInlineCitationMarkup(+ '账号是 x.com {render_inline_citation citation_id="4"} 结尾',+ sources,+ );+ assert.equal(text, "账号是 x.com [ ](#cite=4) 结尾");+});+++test("drops unknown citation placeholders", () => {+ const text = rewriteInlineCitationMarkup(+ "Hello {render_inline_citation(citation_id=99)}",+ sources,+ );+ assert.equal(text, "Hello ");+});++test("never uses a raw URL as the visible title", () => {+ assert.equal(hostedSearchTitle(sources[3]), "bing.com");+ assert.equal(hostedSearchTitle(sources[0]), "Alpha");+});++test("never uses a citation index as the visible title", () => {+ assert.equal(+ hostedSearchTitle({ url: "https://www.36kr.com/p/1", title: "5" }),+ "36kr.com",+ );+});+++test("resolves #cite indices as 1-based source rows", () => {+ const matched = sourcesForHref("#cite=4", sources);+ assert.equal(matched[0]?.url, "https://www.bing.com/search?q=tibo");+});diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rsindex 38862f0ee..c26b67302 100644--- a/crates/host-core/src/plugin_sessions.rs+++ b/crates/host-core/src/plugin_sessions.rs@@ -235,6 +235,7 @@ fn parse_message(steering: None,created_at,thinking: None,+ hosted_search: None,status: None,model_id,provider_id,diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 5ab628632..0be59e0e3 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -155,6 +155,8 @@ pub struct UiMessage {#[serde(skip_serializing_if = "Option::is_none")]pub thinking: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]+ pub hosted_search: Option<Value>,+ #[serde(skip_serializing_if = "Option::is_none")]pub status: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub model_id: Option<String>,@@ -337,6 +339,20 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<Stringif let Some(thinking) = &message.thinking {blocks.push(json!({ "type": "thinking", "text": thinking }));}+ if let Some(hosted_search) = &message.hosted_search {+ let mut block = serde_json::Map::new();+ block.insert("type".into(), json!("hostedSearch"));+ if let Some(obj) = hosted_search.as_object() {+ for (key, value) in obj {+ if key != "type" {+ block.insert(key.clone(), value.clone());+ }+ }+ } else {+ block.insert("value".into(), hosted_search.clone());+ }+ blocks.push(Value::Object(block));+ }let text = if message.role == "tool" {let mut block = serde_json::Map::new();block.insert("type".into(), json!("tool_call"));@@ -466,6 +482,9 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {}).collect::<Vec<_>>();let thinking = (!thinking.is_empty()).then(|| thinking.concat());+ let hosted_search = blocks.iter().find(|b| {+ b.get("type").and_then(|t| t.as_str()) == Some("hostedSearch")+ }).cloned();let is_error = record.is_error.then_some(true);let attachments = blocks.iter()@@ -507,6 +526,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {steering,created_at: record.created_at,thinking,+ hosted_search: hosted_search.clone(),status,model_id,provider_id,@@ -555,6 +575,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {steering,created_at: record.created_at,thinking,+ hosted_search: hosted_search.clone(),status,model_id,provider_id,@@ -3413,6 +3434,7 @@ mod tests {steering: None,created_at: ts.into(),thinking: None,+ hosted_search: None,status: None,model_id: None,provider_id: None,@@ -3911,6 +3933,7 @@ mod tests {steering: None,created_at: "2025-05-01T00:00:02Z".into(),thinking: None,+ hosted_search: None,status: Some("complete".into()),model_id: None,provider_id: None,@@ -4339,6 +4362,7 @@ mod tests {steering: None,created_at: "2025-05-01T00:00:01Z".into(),thinking: Some("first plan\nsecond plan".into()),+ hosted_search: None,status: Some("complete".into()),model_id: Some("model-1".into()),provider_id: Some("provider-1".into()),diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 9d3865e29..61c436f16 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -653,6 +653,15 @@ A catalog entry may additionally pin a model-level wire API (for example,through the Responses adapter instead of Chat Completions. Without amodel-level pin the provider-wide style applies unchanged.+Composer native web search follows the **resolved wire API**, not the vendor+label or model id: `anthropic_messages` attaches `web_search_20250305`,+Responses attaches `{ type: "web_search" }`. Chat Completions stays off+except xAI (`vendorKey` xai / `api.x.ai`), which attaches+`search_parameters`. The Composer globe writes `nativeWebSearchEnabled`+(default off). Search results render as a hostedSearch activity row on+the assistant turn and can be expanded to show sources.++This is the **universal escape hatch** guaranteeing market coverage beyond native integrations.### 16.1 Responses stream termination (pi-ai patch)diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.mdindex cda3c60ee..3943fa90a 100644--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md@@ -576,6 +576,9 @@ UI 可能会显示层级提示,但默认情况下不得硬阻止未知模型目录条目还可以额外固定模型级 wire API(例如 `api: "openai-responses"`)。存在时它优先于 provider 级 `apiStyle`,因此 `opencode_go` 下的 responses-only 模型会走 Responses adapter 而非 Chat Completions;没有模型级固定时保持 provider 级风格不变。+Composer 的联网搜索开关按**解析后的线路 API**决定能否挂厂商托管搜索工具,而不是服务显示名或模型 ID:`anthropic_messages` 附加 `web_search_20250305`,Responses 附加 `{ type: "web_search" }`。`chat_completions` 默认不挂,xAI(`vendorKey` xai / `api.x.ai`)除外,走 `search_parameters`。开关写入设置 `nativeWebSearchEnabled`(缺省关闭)。搜索结果作为助手回合的 hostedSearch 活动行展示,可展开看来源。++### 16.1 Responses 流终止(pi-ai 补丁)OpenAI Responses 适配器必须把 `response.completed`(以及diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 76c78cd3e..6df0024cf 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -89,6 +89,16 @@ import type {} from "@pi-desktop/shared";import {addUsage,+ attachNativeWebSearchToPayload,+ extractHostedSearchFromAssistantContent,+ hostedSearchHasContent,+ isHiddenNativeWebToolName,+ mergeHostedSearch,+ parseHostedSearchStreamEvent,+ supportsNativeWebSearch,+++ type HostedSearch,checkpointGeneration,contextCompactionMark,cumulativeDelta,@@ -197,8 +207,8 @@ import {providerRateLimitDelayMs,providerSetupRetryDelayMs,} from "./provider-retry.js";-import { rebuildNodeNetworkTransport } from "./node-proxy.js";+import {createProviderTransportHealth,explainsProviderFetchFailure,@@ -837,6 +847,8 @@ export type AgentRuntimeOptions = {turnId?: string;provider: RuntimeProviderConfig;thinkingLevel: ThinkingLevel;+ /** Attach vendor hosted-search tools for this session when the wire API allows. */+ nativeWebSearch?: boolean;systemPrompt?: string;/** Session-bound workspace root used for path-scoped instruction requests. */projectPath?: string;@@ -889,6 +901,7 @@ export type RuntimeMatchConfig = {mode: Mode;provider: RuntimeProviderConfig;thinkingLevel: ThinkingLevel;+ nativeWebSearch?: boolean;pluginTools?: PluginToolDef[];pluginSkills?: PluginSkillDef[];trustedExtensions?: TrustedExtensionSpec[];@@ -1448,6 +1461,8 @@ export class DesktopAgentRuntime {private mode: Mode;private provider: RuntimeProviderConfig;private thinkingLevel: ThinkingLevel;+ private nativeWebSearch: boolean;+private host: RuntimeHost;private onEvent: (envelope: AgentEventEnvelope) => void;private streamSink: StreamCoalescer;@@ -1650,6 +1665,7 @@ export class DesktopAgentRuntime {this.planningState = proposalKindForMode(this.mode) ? "planning" : "inactive";this.provider = opts.provider;this.thinkingLevel = clampThinkingLevel(opts.provider, opts.thinkingLevel);+ this.nativeWebSearch = opts.nativeWebSearch === true;this.host = opts.host;this.hostCloseUnsubscribe = this.host.onClose?.(() => {this.cleanupActiveToolProgress();@@ -1771,26 +1787,42 @@ Delegation rules:...options,maxRetries: PROVIDER_REQUEST_MAX_RETRIES,sessionId: this.sessionId,+ onPayload: async (payload, payloadModel) => {+ const rewritten = await options?.onPayload?.(payload, payloadModel);+ const current = rewritten ?? payload;+ if (!this.nativeWebSearch) return current;+ return attachNativeWebSearchToPayload(current, {+ api: payloadModel.api,+ apiStyle: this.provider.apiStyle,+ vendorKey: this.provider.vendorKey,+ baseUrl: this.provider.baseUrl ?? payloadModel.baseUrl,+ });+++ },// pi-ai only exposes onResponse after a request succeeds. Capture the// failed response separately so a 429 can honor Retry-After headers,// and capture the transport cause of a rejection while the original// Error still exists (issue #234).- fetch: captureProviderResponse(- options?.fetch,- (response, requestBytes, failure) => {- this.providerResponseStatus = response?.status;- this.providerRequestBytes = requestBytes;- this.providerFetchFailure = failure;- if (failure) this.recoverProviderTransport(failure);- // A gateway 502/503 can also state Retry-After, so keep headers- // for every status whose delay is usable, not only for 429.- this.providerRetryHeaders = carriesRetryDelayHeaders(- response?.status,- )- ? response?.headers- : undefined;- },- ),+ fetch: async (input, init) => {+ const captured = captureProviderResponse(+ options?.fetch,+ (response, requestBytes, failure) => {+ this.providerResponseStatus = response?.status;+ this.providerRequestBytes = requestBytes;+ this.providerFetchFailure = failure;+ if (failure) this.recoverProviderTransport(failure);+ this.providerRetryHeaders = carriesRetryDelayHeaders(+ response?.status,+ )+ ? response?.headers+ : undefined;+ },+ );+ const response = await captured(input, init);+ this.ingestHostedSearchStream(response);+ return response;+ },onResponse: async (response, responseModel) => {this.providerResponseStatus = response.status;await options?.onResponse?.(response, responseModel);@@ -2177,6 +2209,7 @@ Delegation rules:this.mode === config.mode &&this.thinkingLevel ===clampThinkingLevel(config.provider, config.thinkingLevel) &&+ this.nativeWebSearch === (config.nativeWebSearch === true) &¤t === next &&safeJson(this.commandShell) === safeJson(config.commandShell) &&safeJson(this.baseProjectInstructions ?? null) ===@@ -6568,6 +6601,80 @@ Delegation rules:}}++ private nativeWebSearchActive(): boolean {+ return (+ this.nativeWebSearch &&+ supportsNativeWebSearch({+ api: this.model.api,+ apiStyle: this.provider.apiStyle,+ vendorKey: this.provider.vendorKey,+ baseUrl: this.provider.baseUrl ?? this.model.baseUrl,+ })+ );+ }+++ private applyHostedSearch(+ next: Parameters<typeof mergeHostedSearch>[1],+ emit = true,+ ): void {+ if (!this.currentAssistant) return;+ if (!hostedSearchHasContent(next as HostedSearch | undefined) && !this.currentAssistant.hostedSearch) {+ return;+ }+ const hostedSearch = mergeHostedSearch(this.currentAssistant.hostedSearch, next);+ if (!hostedSearch) return;+ this.currentAssistant = { ...this.currentAssistant, hostedSearch };+ if (emit) this.emit({ type: "message_update", message: this.currentAssistant });+ }+++++ private ingestHostedSearchStream(response: Response): void {+ if (!this.nativeWebSearchActive() || !response.body) return;+ let clone: Response;+ try {+ clone = response.clone();+ } catch {+ return;+ }+ void this.readHostedSearchStream(clone);+ }++ private async readHostedSearchStream(response: Response): Promise<void> {+ try {+ const reader = response.body?.getReader();+ if (!reader) return;+ const decoder = new TextDecoder();+ let buffer = "";+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split(/\r?\n/g);+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ const trimmed = line.trim();+ const payload = trimmed.startsWith("data:") ? trimmed.slice(5).trim() : trimmed;+ if (!payload || payload === "[DONE]" || (!payload.startsWith("{") && !payload.startsWith("["))) {+ continue;+ }+ try {+ const parsed = JSON.parse(payload) as unknown;+ const update = parseHostedSearchStreamEvent(parsed);+ if (update) this.applyHostedSearch(update);+ } catch {+ // Ignore partial JSON from the clone parser.+ }+ }+ }+ } catch {+ // Hosted-search metadata is best-effort and must not break the provider stream.+ }+ }+private async handleAgentEvent(event: AgentEvent) {this.forwardAgentEventToExtensions(event);switch (event.type) {@@ -6609,6 +6716,9 @@ Delegation rules:: this.progressTurnRerunInProgress? retryingAssistant?.content ?? "": content.text;+ const initialSearch = extractHostedSearchFromAssistantContent(+ (event.message as { content?: unknown }).content,+ );this.currentAssistant = {id: retryingAssistant?.id ?? randomUUID(),role: "assistant",@@ -6616,6 +6726,11 @@ Delegation rules:...(content.hasThinking && content.thinking? { thinking: content.thinking }: {}),+ ...(initialSearch+ ? { hostedSearch: mergeHostedSearch(retryingAssistant?.hostedSearch, initialSearch) }+ : retryingAssistant?.hostedSearch+ ? { hostedSearch: retryingAssistant.hostedSearch }+ : {}),createdAt: nowIso(),status: "streaming",modelId: this.provider.modelId,@@ -6654,6 +6769,9 @@ Delegation rules:const thinkingDelta = content.hasThinking? cumulativeDelta(previousThinking, content.thinking): { delta: "", reset: false };+ const extractedSearch = extractHostedSearchFromAssistantContent(+ (event.message as { content?: unknown }).content,+ );this.currentAssistant = {...this.currentAssistant,content: nextText,@@ -6662,6 +6780,14 @@ Delegation rules:: content.hasThinking? { thinking: undefined }: {}),+ ...(extractedSearch+ ? {+ hostedSearch: mergeHostedSearch(+ this.currentAssistant.hostedSearch,+ extractedSearch,+ ),+ }+ : {}),status: "streaming",};if (@@ -6905,6 +7031,23 @@ Delegation rules:thinking: nextThinking,}): undefined;+ const endedSearch = mergeHostedSearch(+ this.currentAssistant.hostedSearch,+ extractHostedSearchFromAssistantContent(+ (event.message as { content?: unknown }).content,+ ),+ );+ const hostedSearch = hostedSearchHasContent(endedSearch) && endedSearch+ ? {+ queries: endedSearch.queries,+ sources: endedSearch.sources,+ status: (failed || aborted+ ? endedSearch.sources.length > 0+ ? "completed" as const+ : "failed" as const+ : "completed" as const),+ }+ : undefined;this.currentAssistant = {...this.currentAssistant,content: nextText,@@ -6913,6 +7056,7 @@ Delegation rules:: content.hasThinking? { thinking: undefined }: {}),+ ...(hostedSearch ? { hostedSearch } : {}),status: failed || emptyResponse? "error": aborted@@ -6933,6 +7077,7 @@ Delegation rules:this.activeProviderRetryAttempt = 0;this.streamStartedAt = undefined;this.currentAssistant = undefined;+const canRecoverOverflow =this.compactionEnabled &&overflow &&@@ -6964,6 +7109,22 @@ Delegation rules:break;}case "tool_execution_start": {+ if (this.nativeWebSearchActive() && isHiddenNativeWebToolName(event.toolName)) {+ const startedAt = Date.now();+ this.activeToolCalls.set(event.toolCallId, {+ toolName: event.toolName,+ args: event.args,+ startedAt,+ });+ this.applyHostedSearch(+ mergeHostedSearch(undefined, extractHostedSearchFromAssistantContent({+ type: "toolCall",+ name: event.toolName,+ arguments: event.args,+ })) ?? { status: "searching", queries: [], sources: [] },+ );+ break;+ }const startedAt = Date.now();this.clearAgentActivity();this.activeToolCalls.set(event.toolCallId, {@@ -6990,6 +7151,19 @@ Delegation rules:// The agent issues the follow-up provider request as soon as the tool// results are in, so this is the anchor for the next providerWaitMs.{+ if (this.nativeWebSearchActive() && isHiddenNativeWebToolName(+ this.activeToolCalls.get(event.toolCallId)?.toolName ?? event.toolName,+ )) {+ this.activeToolCalls.delete(event.toolCallId);+ this.applyHostedSearch(+ mergeHostedSearch(undefined, extractHostedSearchFromAssistantContent(event.result)) ?? {+ status: event.isError ? "failed" : "completed",+ queries: [],+ sources: [],+ },+ );+ break;+ }const endedAt = Date.now();const activeTool = this.activeToolCalls.get(event.toolCallId);this.activeToolCalls.delete(event.toolCallId);@@ -7167,6 +7341,7 @@ Delegation rules:this.currentAssistant = undefined;}+/** Keep a pre-flight user message in context so a reused runtime and the* next turn both see it, even though no provider request was made. */private keepPreflightUserMessage(incomingUserMessage: AgentMessage): void {diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex a116af74b..15450f223 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -95,6 +95,7 @@ type RuntimeParams = {/** Durable host turn ID for the prompt currently being executed. */turnId?: string;thinkingLevel?: ThinkingLevel;+ nativeWebSearch?: boolean;provider: RuntimeProviderConfig;commandShell: CommandShellOption;pluginTools?: PluginToolDef[];@@ -327,6 +328,7 @@ async function runtimeFor(mode,provider,thinkingLevel,+ nativeWebSearch: params.nativeWebSearch === true,pluginTools,pluginSkills,trustedExtensions,@@ -382,6 +384,7 @@ async function runtimeFor(provider,commandShell: params.commandShell,thinkingLevel,+ nativeWebSearch: params.nativeWebSearch === true,history,compaction,compactionSettings: params.compactionSettings,diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 85762001d..feea5ea22 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -451,6 +451,21 @@ export const de = {"thinking": "Denken","thinkingShow": "Denken anzeigen","thinkingHide": "Denken ausblenden",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation","untitledTask": "Neue Aufgabe"},"session": {diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex dd72f5410..14a32cfc7 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -458,6 +458,21 @@ export const en = {thinking: "Thinking",thinkingShow: "Show thinking",thinkingHide: "Hide thinking",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation",untitledTask: "New task",},session: {diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 8d06b8730..e1bf53f0e 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -451,6 +451,21 @@ export const es = {"thinking": "Pensamiento","thinkingShow": "Mostrar pensamiento","thinkingHide": "Ocultar pensamiento",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation","untitledTask": "Nueva tarea"},"session": {diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 516921344..99c0a3eda 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -451,6 +451,21 @@ export const fr = {"thinking": "Réflexion","thinkingShow": "Afficher la réflexion","thinkingHide": "Masquer la réflexion",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation","untitledTask": "Nouvelle tâche"},"session": {diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex d7a002902..7b4e4e4f9 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -460,6 +460,21 @@ export const ko = {thinking: "생각 중",thinkingShow: "생각 표시",thinkingHide: "생각 숨기기",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation",untitledTask: "새 작업",},session: {diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex c6bec0655..307d58a48 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -460,6 +460,21 @@ export const tr = {thinking: "Düşünme",thinkingShow: "Düşünmeyi göster",thinkingHide: "Düşünmeyi gizle",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation",untitledTask: "Yeni görev",},session: {diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex aa8cb8357..66bde196f 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -456,6 +456,21 @@ export const zhCN = {thinking: "思考",thinkingShow: "显示思考过程",thinkingHide: "隐藏思考过程",+ webSearch: "联网搜索",+ webSearchOn: "联网搜索已开启",+ webSearchOff: "联网搜索已关闭",+ webSearchUnsupported: "当前线路不支持联网搜索",+ webSearchRunning: "正在联网搜索…",+ webSearchSources: "{{count}} 个来源",+ webSearchSources_other: "{{count}} 个来源",+ webSearchQuery: "搜索了 {{query}}",+ webSearchShow: "显示联网搜索",+ webSearchHide: "隐藏联网搜索",+ webSearchEmpty: "这次搜索没有返回来源。",+ webSearchSummary: "已搜索 {{searchCount}} 次 · {{sourceCount}} 个来源",+ webSearchMore: "查看其余 {{count}} 个来源",+ webSearchCitationPrev: "上一个引用来源",+ webSearchCitationNext: "下一个引用来源",untitledTask: "新建任务",},session: {diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex de0201cae..cb78b7671 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -456,6 +456,21 @@ export const zhTW = {thinking: "思考",thinkingShow: "顯示思考過程",thinkingHide: "隱藏思考過程",+ webSearch: "Web search",+ webSearchOn: "Web search on",+ webSearchOff: "Web search off",+ webSearchUnsupported: "Current API style does not support native web search",+ webSearchRunning: "Searching the web…",+ webSearchSources: "{{count}} source",+ webSearchSources_other: "{{count}} sources",+ webSearchQuery: "Searched {{query}}",+ webSearchShow: "Show web search",+ webSearchHide: "Hide web search",+ webSearchEmpty: "No sources were returned for this search.",+ webSearchSummary: "Searched {{searchCount}} times · {{sourceCount}} sources",+ webSearchMore: "View {{count}} more sources",+ webSearchCitationPrev: "Previous citation",+ webSearchCitationNext: "Next citation",untitledTask: "新建任務",},session: {diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex ceff8bd9a..62a420591 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -56,3 +56,4 @@ export * from "./provider-retry.js";export * from "./message-stream.js";export * from "./session-collaboration.js";export * from "./window-chrome.js";+export * from "./native-web-search.js";diff --git a/packages/shared/src/native-web-search.test.ts b/packages/shared/src/native-web-search.test.tsnew file mode 100644index 000000000..54fac195f--- /dev/null+++ b/packages/shared/src/native-web-search.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it } from "vitest";+import {+ ANTHROPIC_WEB_SEARCH_TOOL_TYPE,+ apiStyleSupportsNativeWebSearch,+ attachNativeWebSearchToPayload,+ extractHostedSearchFromAssistantContent,+ isHiddenNativeWebToolName,+ mergeHostedSearch,+ parseHostedSearchStreamEvent,+ supportsNativeWebSearch,+ wireApiSupportsNativeWebSearch,+} from "./native-web-search.js";+++++describe("native web search detection", () => {+ it("allows Anthropic Messages and OpenAI Responses wire APIs", () => {+ expect(wireApiSupportsNativeWebSearch("anthropic-messages")).toBe(true);+ expect(wireApiSupportsNativeWebSearch("openai-responses")).toBe(true);+ expect(apiStyleSupportsNativeWebSearch("anthropic_messages")).toBe(true);+ expect(apiStyleSupportsNativeWebSearch("responses")).toBe(true);+ });++ it("rejects Chat Completions and unknown custom styles", () => {+ expect(wireApiSupportsNativeWebSearch("openai-completions")).toBe(false);+ expect(apiStyleSupportsNativeWebSearch("chat_completions")).toBe(false);+ expect(apiStyleSupportsNativeWebSearch("opencode_go")).toBe(false);+ expect(apiStyleSupportsNativeWebSearch(undefined)).toBe(false);+ });++ it("does not infer support from a model-shaped name", () => {+ expect(apiStyleSupportsNativeWebSearch("claude-sonnet-4")).toBe(false);+ expect(wireApiSupportsNativeWebSearch("gpt-5")).toBe(false);+ });+});++describe("attachNativeWebSearchToPayload", () => {+ it("appends Anthropic's stable GA web_search tool", () => {+ const next = attachNativeWebSearchToPayload(+ { model: "claude-sonnet-4", tools: [{ name: "Read" }] },+ "anthropic-messages",+ );+ expect(next).toEqual({+ model: "claude-sonnet-4",+ tools: [+ { name: "Read" },+ { type: ANTHROPIC_WEB_SEARCH_TOOL_TYPE, name: "web_search" },+ ],+ });+ });++ it("appends OpenAI Responses web_search without duplicating it", () => {+ const first = attachNativeWebSearchToPayload({ tools: [] }, "openai-responses");+ const second = attachNativeWebSearchToPayload(first, "openai-responses");+ expect(second).toEqual({ tools: [{ type: "web_search" }] });+ });++ it("leaves Chat Completions payloads unchanged", () => {+ const payload = { model: "gpt-4o", tools: [] };+ expect(attachNativeWebSearchToPayload(payload, "openai-completions")).toBe(payload);+ });+});++describe("hidden native web tools", () => {+ it("recognizes leaked vendor search and fetch names", () => {+ expect(isHiddenNativeWebToolName("web_search")).toBe(true);+ expect(isHiddenNativeWebToolName("web_search_20250305")).toBe(true);+ expect(isHiddenNativeWebToolName("web_fetch")).toBe(true);+ expect(isHiddenNativeWebToolName("Read")).toBe(false);+ });+});++describe("extractHostedSearchFromAssistantContent", () => {+ it("reads query and sources from a leaked web_search tool call", () => {+ const search = extractHostedSearchFromAssistantContent([+ {+ type: "toolCall",+ name: "web_search",+ arguments: {+ query: "pi-desktop native search",+ sources: [+ { title: "Docs", url: "https://example.com/docs" },+ { url: "https://example.com/docs" },+ ],+ },+ },+ ]);+ expect(search?.queries).toEqual(["pi-desktop native search"]);+ expect(search?.sources).toEqual([{ url: "https://example.com/docs", title: "Docs" }]);+ expect(search?.status).toBe("completed");+ });++ it("merges later sources onto an in-progress search", () => {+ const merged = mergeHostedSearch(+ { status: "searching", queries: ["rust sqlite"], sources: [] },+ {+ status: "completed",+ sources: [{ url: "https://www.sqlite.org", title: "SQLite" }],+ },+ );+ expect(merged).toEqual({+ status: "completed",+ queries: ["rust sqlite"],+ sources: [{ url: "https://www.sqlite.org", title: "SQLite" }],+ });+ });+});++describe("false positives", () => {+ it("does not treat Playwright or MCP tools as hosted search", () => {+ expect(+ extractHostedSearchFromAssistantContent([+ {+ type: "toolCall",+ name: "mcp_playwright_browser_navigate",+ arguments: { url: "https://cn.bing.com/search?q=tibo" },+ },+ ]),+ ).toBeUndefined();+ });++ it("collapses streaming URL prefixes into one source", () => {+ const merged = mergeHostedSearch(+ { status: "searching", queries: [], sources: [{ url: "https://www.bing.com/search?q=t" }] },+ { status: "completed", sources: [{ url: "https://www.bing.com/search?q=tibo" }] },+ );+ expect(merged?.sources).toEqual([{ url: "https://www.bing.com/search?q=tibo" }]);+ });++ it("parses Grok/OpenAI web_search_call stream events", () => {+ const searching = parseHostedSearchStreamEvent({+ type: "response.output_item.added",+ item: { type: "web_search_call", action: { query: "tibo 重置哥" } },+ });+ expect(searching?.queries).toEqual(["tibo 重置哥"]);+ const cited = parseHostedSearchStreamEvent({+ type: "response.output_text.annotation.added",+ annotation: { type: "url_citation", url: "https://example.com/a", title: "A" },+ });+ expect(cited?.sources).toEqual([{ url: "https://example.com/a", title: "A" }]);+ });+});+describe("xAI Live Search", () => {+ it("supports the xAI vendor even on Chat Completions", () => {+ expect(+ supportsNativeWebSearch({+ api: "openai-completions",+ apiStyle: "chat_completions",+ vendorKey: "xai",+ baseUrl: "https://api.x.ai/v1",+ }),+ ).toBe(true);+ });++ it("drops Grok citation indexes that arrive as source titles", () => {+ const search = parseHostedSearchStreamEvent({+ citations: [{ url: "https://36kr.com/p/1", title: "5" }],+ });+ expect(search?.sources).toEqual([{ url: "https://36kr.com/p/1" }]);+ });++++ it("attaches search_parameters on xAI Completions", () => {+ const next = attachNativeWebSearchToPayload(+ { model: "grok-4" },+ { api: "openai-completions", vendorKey: "xai", baseUrl: "https://api.x.ai/v1" },+ );+ expect(next).toEqual({+ model: "grok-4",+ search_parameters: { mode: "on", return_citations: true },+ });+ });++ it("reads Grok citation URLs from a completions chunk", () => {+ const search = parseHostedSearchStreamEvent({+ citations: ["https://example.com/a", "https://example.com/b"],+ });+ expect(search?.sources).toEqual([+ { url: "https://example.com/a" },+ { url: "https://example.com/b" },+ ]);+ });++ it("reads x_search_call sources like LiveAgent", () => {+ const search = parseHostedSearchStreamEvent({+ type: "response.output_item.done",+ item: {+ type: "x_search_call",+ action: {+ query: "tibo 重置哥",+ sources: [{ url: "https://example.com/tibo", title: "Tibo" }],+ },+ },+ });+ expect(search?.queries).toEqual(["tibo 重置哥"]);+ expect(search?.sources).toEqual([{ url: "https://example.com/tibo", title: "Tibo" }]);+ });+});+diff --git a/packages/shared/src/native-web-search.ts b/packages/shared/src/native-web-search.tsnew file mode 100644index 000000000..7a982ada0--- /dev/null+++ b/packages/shared/src/native-web-search.ts@@ -0,0 +1,556 @@+/**+ * Provider-native (hosted) web search: which wire APIs can carry a vendor+ * server tool, how to attach that tool, and how to recover queries/sources+ * from leaked client tool calls or stream events.+ *+ * Detection is the resolved wire API / apiStyle, never the vendor display+ * name or a model-id substring. Custom Chat Completions stay off unless the+ * target is xAI (`vendorKey` or api.x.ai).+ */++++export type HostedSearchStatus = "searching" | "completed" | "failed";++export type HostedSearchSource = {+ url: string;+ title?: string;+ /** Vendor-supplied publisher/site name when present. Usually absent. */+ publisher?: string;+ /** Vendor-supplied publication date when present. Usually absent. */+ publishedAt?: string;+};++export type HostedSearch = {+ status: HostedSearchStatus;+ queries: string[];+ sources: HostedSearchSource[];+};++// Keep the Anthropic server tool on the stable GA contract. Newer dated+// versions are recognized if already present, but not sent: Claude relays+// reject unsupported tool types with 400 and expose no capability signal.+export const ANTHROPIC_WEB_SEARCH_TOOL_TYPE = "web_search_20250305" as const;+++const NATIVE_WEB_SEARCH_WIRE_APIS = new Set([+ "anthropic-messages",+ "openai-responses",+]);++const NATIVE_WEB_SEARCH_API_STYLES = new Set([+ "anthropic_messages",+ "responses",+]);++const NATIVE_SEARCH_TOOL_NAMES = new Set([+ "websearch",+ "web_search",+ "builtin_web_search",+ "web_search_20250305",+ "web_search_20260209",+ "web_search_20260318",+ "web_search_preview",+ "web_search_call",+ "x_search",+ "x_keyword_search",+ "x_semantic_search",+]);++const NATIVE_FETCH_TOOL_NAMES = new Set([+ "webfetch",+ "web_fetch",+ "builtin_web_fetch",+]);++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function normalizeName(value: string | undefined): string {+ return value?.trim().toLowerCase() ?? "";+}++export function wireApiSupportsNativeWebSearch(api: string | undefined): boolean {+ return NATIVE_WEB_SEARCH_WIRE_APIS.has((api ?? "").trim().toLowerCase());+}++export function apiStyleSupportsNativeWebSearch(+ apiStyle: string | undefined,+): boolean {+ const style = (apiStyle ?? "").trim().toLowerCase();+ if (NATIVE_WEB_SEARCH_API_STYLES.has(style)) return true;+ return wireApiSupportsNativeWebSearch(style);+}+export type NativeWebSearchTarget = {+ api?: string;+ apiStyle?: string;+ vendorKey?: string;+ baseUrl?: string;+};++function hostnameOf(baseUrl: string | undefined): string {+ if (!baseUrl?.trim()) return "";+ try {+ return new URL(baseUrl).hostname.toLowerCase();+ } catch {+ return "";+ }+}++export function isXaiNativeSearchTarget(target: NativeWebSearchTarget | undefined): boolean {+ const vendor = (target?.vendorKey ?? "").trim().toLowerCase();+ if (vendor === "xai" || vendor === "x-ai") return true;+ const host = hostnameOf(target?.baseUrl);+ return host === "api.x.ai" || host.endsWith(".x.ai");+}+++export function supportsNativeWebSearch(target: NativeWebSearchTarget | undefined): boolean {+ if (!target) return false;+ if (wireApiSupportsNativeWebSearch(target.api)) return true;+ if (apiStyleSupportsNativeWebSearch(target.apiStyle)) return true;+ return isXaiNativeSearchTarget(target);+}++export function isNativeWebSearchToolName(toolName: string | undefined): boolean {+ const normalized = normalizeName(toolName);+ if (!normalized) return false;+ if (NATIVE_SEARCH_TOOL_NAMES.has(normalized)) return true;+ return (+ normalized.startsWith("web_search_call") ||+ normalized.startsWith("x_search_call")+ );+}++export function isNativeWebFetchToolName(toolName: string | undefined): boolean {+ const normalized = normalizeName(toolName);+ if (!normalized) return false;+ if (NATIVE_FETCH_TOOL_NAMES.has(normalized)) return true;+ return normalized.startsWith("web_fetch_2") || normalized.startsWith("web_fetch_call");+}++export function isHiddenNativeWebToolName(toolName: string | undefined): boolean {+ return isNativeWebSearchToolName(toolName) || isNativeWebFetchToolName(toolName);+}++function isHttpUrl(value: string): boolean {+ try {+ const url = new URL(value);+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;+ return url.hostname.includes(".");+ } catch {+ return false;+ }+}+function sourceKey(source: HostedSearchSource): string {+ return source.url;+}++/** Drop citation indexes and raw URLs that Grok sometimes ships as `title`. */+function usableSourceTitle(value: string | undefined): string {+ const title = value?.trim() ?? "";+ if (!title || /^https?:\/\//i.test(title) || /^\d+$/.test(title)) return "";+ return title;+}++function collapsePrefixDuplicates(values: string[]): string[] {+ const unique = uniqueStrings(values);+ return unique.filter(+ (value) => !unique.some((other) => other.length > value.length && other.startsWith(value)),+ );+}+++function readString(value: unknown): string {+ return typeof value === "string" ? value.trim() : "";+}++function uniqueStrings(values: string[]): string[] {+ const out: string[] = [];+ for (const value of values) {+ const text = value.trim();+ if (!text || out.includes(text)) continue;+ out.push(text);+ }+ return out;+}++export function hostedSearchHasContent(search: HostedSearch | undefined): boolean {+ if (!search) return false;+ return search.queries.length > 0 || search.sources.length > 0;+}++export function mergeHostedSearch(+ previous: HostedSearch | undefined,+ next: Partial<HostedSearch> | undefined,+): HostedSearch | undefined {+ if (!previous && !next) return undefined;+ const queries = collapsePrefixDuplicates([+ ...(previous?.queries ?? []),+ ...(next?.queries ?? []),+ ]);+ const sourcesByUrl = new Map<string, HostedSearchSource>();+ for (const source of [...(previous?.sources ?? []), ...(next?.sources ?? [])]) {+ if (!source.url || !isHttpUrl(source.url)) continue;+ const existing = sourcesByUrl.get(sourceKey(source));+ sourcesByUrl.set(sourceKey(source), {+ url: source.url,+ title: usableSourceTitle(source.title) || usableSourceTitle(existing?.title),++ publisher: source.publisher?.trim() || existing?.publisher,+ publishedAt: source.publishedAt?.trim() || existing?.publishedAt,+ });+ }+ const sources = collapsePrefixDuplicates([...sourcesByUrl.keys()]).map((url) => {+ const source = sourcesByUrl.get(url)!;+ return {+ url,+ ...(source.title ? { title: source.title } : {}),+ ...(source.publisher ? { publisher: source.publisher } : {}),+ ...(source.publishedAt ? { publishedAt: source.publishedAt } : {}),+ };+ }).slice(0, 20);+ const status = next?.status ?? previous?.status ?? "searching";+ if (queries.length === 0 && sources.length === 0) {+ return status === "searching" ? { status, queries, sources } : undefined;+ }+ return { status, queries, sources };+}++function hasAnthropicWebSearchTool(tool: unknown): boolean {+ if (!isRecord(tool)) return false;+ return (+ tool.name === "web_search" ||+ tool.type === ANTHROPIC_WEB_SEARCH_TOOL_TYPE ||+ tool.type === "web_search_20260209" ||+ tool.type === "web_search_20260318"+ );+}++function hasOpenAIResponsesWebSearchTool(tool: unknown): boolean {+ if (!isRecord(tool)) return false;+ const type = tool.type;+ return (+ type === "web_search" ||+ type === "web_search_2025_08_26" ||+ type === "web_search_preview" ||+ type === "web_search_preview_2025_03_11"+ );+}++function appendUniqueTool(+ payload: Record<string, unknown>,+ tool: Record<string, unknown>,+ matches: (candidate: unknown) => boolean,+): Record<string, unknown> {+ const tools = Array.isArray(payload.tools) ? payload.tools : [];+ if (tools.some(matches)) return payload;+ return { ...payload, tools: [...tools, tool] };+}++function appendXaiLiveSearch(payload: Record<string, unknown>): Record<string, unknown> {+ if (isRecord(payload.search_parameters)) return payload;+ return {+ ...payload,+ search_parameters: {+ mode: "on",+ return_citations: true,+ },+ };+}++/**+ * Attach the vendor hosted-search tool for the resolved wire API / xAI Live Search.+ * Unknown Chat Completions endpoints stay unchanged.+ */+export function attachNativeWebSearchToPayload(+ payload: unknown,+ apiOrTarget: string | NativeWebSearchTarget | undefined,+): unknown {+ const target: NativeWebSearchTarget =+ typeof apiOrTarget === "string" || apiOrTarget === undefined+ ? { api: apiOrTarget }+ : apiOrTarget;+ if (!isRecord(payload) || !supportsNativeWebSearch(target)) return payload;+++ const wire = (target.api ?? "").trim().toLowerCase();+ if (wire === "anthropic-messages" || target.apiStyle === "anthropic_messages") {+ return appendUniqueTool(+ payload,+ { type: ANTHROPIC_WEB_SEARCH_TOOL_TYPE, name: "web_search" },+ hasAnthropicWebSearchTool,+ );+ }+ if (wire === "openai-responses" || target.apiStyle === "responses") {+ return appendUniqueTool(payload, { type: "web_search" }, hasOpenAIResponsesWebSearchTool);+ }+ if (isXaiNativeSearchTarget(target)) {+ if (wire === "openai-responses" || target.apiStyle === "responses") {+ return appendUniqueTool(payload, { type: "web_search" }, hasOpenAIResponsesWebSearchTool);+ }+ return appendXaiLiveSearch(payload);+ }+ return payload;+}++function readQuery(record: Record<string, unknown>): string {+ return (+ readString(record.query) ||+ readString(record.search_query) ||+ readString(record.additionalContext)+ );+}++function collectSources(value: unknown, into: HostedSearchSource[]): void {+ if (typeof value === "string") {+ const url = value.trim();+ if (url && isHttpUrl(url)) into.push({ url });+ return;+ }+ if (Array.isArray(value)) {+ for (const entry of value) collectSources(entry, into);+ return;+ }+ if (!isRecord(value)) return;+ const url = readString(value.url ?? value.uri ?? value.link);+ if (url && isHttpUrl(url)) {+ const title = usableSourceTitle(readString(value.title ?? value.name));+ const publisher = readString(+ value.publisher ?? value.site_name ?? value.siteName,+ );+ const publishedAt = readString(+ value.publishedAt ?? value.published_date ?? value.published_at ?? value.date,+ );+ into.push({+ url,+ ...(title ? { title } : {}),+ ...(publisher ? { publisher } : {}),+ ...(publishedAt ? { publishedAt } : {}),+ });+ }++ for (const key of ["sources", "citations", "results", "output", "groundingChunks"] as const) {+ if (value[key] !== undefined) collectSources(value[key], into);+ }+ if (isRecord(value.web)) collectSources(value.web, into);+ if (isRecord(value.action)) collectSources(value.action, into);+ if (isRecord(value.annotation) && readString(value.annotation.type) === "url_citation") {+ collectSources(value.annotation, into);+ }+}++function collectNamedQueries(record: Record<string, unknown>, into: string[]): void {+ const query = readQuery(record);+ if (query) into.push(query);+ if (Array.isArray(record.queries)) {+ for (const entry of record.queries) {+ const text = readString(entry);+ if (text) into.push(text);+ }+ }+ if (Array.isArray(record.webSearchQueries)) {+ for (const entry of record.webSearchQueries) {+ const text = readString(entry);+ if (text) into.push(text);+ }+ }+ if (isRecord(record.action)) collectNamedQueries(record.action, into);+ else if (typeof record.action === "string") {+ try {+ const parsed = JSON.parse(record.action) as unknown;+ if (isRecord(parsed)) collectNamedQueries(parsed, into);+ } catch {+ /* ignore */+ }+ }+ if (isRecord(record.input)) collectNamedQueries(record.input, into);+ if (isRecord(record.arguments)) collectNamedQueries(record.arguments, into);+}++function extractCitationSearch(raw: Record<string, unknown>): HostedSearch | undefined {+ const sources: HostedSearchSource[] = [];+ collectSources(raw.citations, sources);+ const choices = Array.isArray(raw.choices) ? raw.choices : [];+ for (const choice of choices) {+ if (!isRecord(choice)) continue;+ collectSources(choice.citations, sources);+ if (isRecord(choice.delta)) collectSources(choice.delta.citations, sources);+ if (isRecord(choice.message)) collectSources(choice.message.citations, sources);+ }+ return packSearch([], sources, "completed");+}++function packSearch(+ queries: string[],+ sources: HostedSearchSource[],+ status?: HostedSearchStatus,+): HostedSearch | undefined {+ const uniqueQueries = uniqueStrings(queries);+ const merged = mergeHostedSearch(undefined, {+ status: status ?? (sources.length > 0 ? "completed" : uniqueQueries.length > 0 ? "searching" : undefined),+ queries: uniqueQueries,+ sources,+ });+ if (!merged) return undefined;+ if (!hostedSearchHasContent(merged) && merged.status !== "searching") return undefined;+ return merged;+}++function toolCallName(part: Record<string, unknown>): string {+ return readString(part.name ?? part.toolName);+}++function isSearchContentPart(part: Record<string, unknown>): boolean {+ const type = readString(part.type);+ const name = toolCallName(part);+ if (isHiddenNativeWebToolName(name)) return true;+ if (type === "web_search_call" || type === "x_search_call" || type === "web_search_tool_result") {+ return true;+ }+ if (type === "server_tool_use") return isHiddenNativeWebToolName(name);+ if (type === "url_citation") return true;+ return false;+}++/**+ * Recover hosted-search metadata from a pi-ai assistant `content` array or a+ * leaked client tool-call payload. Only native search/fetch blocks count —+ * MCP, Playwright, and other local tools must not become search queries.+ */+export function extractHostedSearchFromAssistantContent(+ content: unknown,+): HostedSearch | undefined {+ if (isRecord(content) && isSearchContentPart(content)) {+ const queries: string[] = [];+ const sources: HostedSearchSource[] = [];+ collectNamedQueries(content, queries);+ collectSources(content.arguments ?? content.input ?? content.content ?? content, sources);+ return packSearch(queries, sources);+ }+ if (!Array.isArray(content)) return undefined;+ let found: HostedSearch | undefined;+ for (const part of content) {+ if (!isRecord(part)) continue;+ if (Array.isArray(part.citations)) {+ const sources: HostedSearchSource[] = [];+ collectSources(part.citations, sources);+ found = mergeHostedSearch(found, packSearch([], sources, "completed"));+ }+ if (!isSearchContentPart(part)) continue;+ const queries: string[] = [];+ const sources: HostedSearchSource[] = [];+ collectNamedQueries(part, queries);+ collectSources(part.arguments ?? part.input ?? part.content ?? part, sources);+ found = mergeHostedSearch(found, packSearch(queries, sources));+ }+ return found;+}++function isXaiSearchItemType(itemType: string): boolean {+ return (+ itemType === "web_search_call" ||+ itemType === "x_search_call" ||+ itemType === "x_search_call_output"+ );+}++/**+ * Parse one SSE/JSON stream event from OpenAI Responses, xAI, or Anthropic.+ * Unrelated tool traffic returns undefined.+ */+export function parseHostedSearchStreamEvent(raw: unknown): HostedSearch | undefined {+ if (!isRecord(raw)) return undefined;+ const citations = extractCitationSearch(raw);+ const type = readString(raw.type);++ if (type === "response.output_item.added" || type === "response.output_item.done") {+ const item = isRecord(raw.item) ? raw.item : {};+ const itemType = readString(item.type);+ const name = readString(item.name);+ const customSearch =+ itemType === "custom_tool_call" &&+ (name === "x_keyword_search" || name === "x_semantic_search");+ if (isXaiSearchItemType(itemType) || isHiddenNativeWebToolName(name) || customSearch) {+ const queries: string[] = [];+ const sources: HostedSearchSource[] = [];+ collectNamedQueries(item, queries);+ collectSources(item, sources);+ const done = type.endsWith(".done") || itemType.endsWith("_output");+ return mergeHostedSearch(+ citations,+ packSearch(queries, sources, done || sources.length > 0 ? "completed" : "searching"),+ ) ?? citations;+ }+ return citations;+ }++ if (type.startsWith("response.web_search_call.") || type.startsWith("response.x_search_call.")) {+ const suffix = type.split(".").pop() ?? "";+ const failed = /fail|error|cancel/.test(suffix);+ const done = /complete|completed|done/.test(suffix);+ const item = isRecord(raw.item) ? raw.item : raw;+ const queries: string[] = [];+ const sources: HostedSearchSource[] = [];+ if (isRecord(item)) {+ collectNamedQueries(item, queries);+ collectSources(item, sources);+ }+ return mergeHostedSearch(+ citations,+ packSearch(+ queries,+ sources,+ failed ? "failed" : done || sources.length > 0 ? "completed" : "searching",+ ),+ ) ?? citations;+ }++ if (type === "response.output_text.annotation.added") {+ const sources: HostedSearchSource[] = [];+ collectSources(raw, sources);+ return packSearch([], sources, "completed");+ }++ if (type === "content_block_start") {+ const block = isRecord(raw.content_block) ? raw.content_block : {};+ const blockType = readString(block.type);+ const name = readString(block.name);+ if (blockType === "server_tool_use" && isHiddenNativeWebToolName(name)) {+ const queries: string[] = [];+ collectNamedQueries(block, queries);+ return packSearch(queries, [], "searching");+ }+ if (blockType === "web_search_tool_result" || blockType === "web_search_tool_result_error") {+ const sources: HostedSearchSource[] = [];+ collectSources(block.content, sources);+ return packSearch(+ [],+ sources,+ blockType.endsWith("_error") ? "failed" : "completed",+ );+ }+ return undefined;+ }++ if (type === "content_block_delta") {+ const delta = isRecord(raw.delta) ? raw.delta : {};+ if (readString(delta.type) === "citations_delta") {+ const sources: HostedSearchSource[] = [];+ collectSources(delta, sources);+ return packSearch([], sources, "completed") ?? citations;+ }+ }++ return citations;+}++export function normalizeHostedSearchStatus(+ value: string | undefined,+): HostedSearchStatus {+ const normalized = (value ?? "").trim().toLowerCase();+ if (/fail|error|cancel/.test(normalized)) return "failed";+ if (/complete|completed|done|succeeded|finished/.test(normalized)) return "completed";+ return "searching";+}diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 72bd67b4c..a424403ed 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -1,6 +1,7 @@/** Shared public types grouped by the owning application domain. */import type { SessionMessageOrigin } from "../session-collaboration.js";import type { AppError } from "../errors.js";+import type { HostedSearch } from "../native-web-search.js";export type UiMessageRole = "user" | "assistant" | "system" | "tool";@@ -77,6 +78,8 @@ export type UiMessage = {steering?: boolean;/** Model reasoning kept separate from the answer text. */thinking?: string;+ /** Provider-native web search captured for this assistant turn. */+ hostedSearch?: HostedSearch;createdAt: string;status?: "streaming" | "complete" | "error" | "aborted";/** Provider/model that produced this assistant turn, when known. */diff --git a/packages/shared/src/types/sessions.ts b/packages/shared/src/types/sessions.tsindex 812eb9f98..242939c07 100644--- a/packages/shared/src/types/sessions.ts+++ b/packages/shared/src/types/sessions.ts@@ -29,6 +29,8 @@ export type SessionSummary = {providerId?: string;mode: Mode;thinkingLevel: ThinkingLevel;+ /** Composer-native web search for this session; absent means follow settings. */+ nativeWebSearch?: boolean;/** Per-session permission mode; `inherit` follows the global default (D115). */permissionMode: PermissionMode;/** Effective capability for this session's exact provider/model pair. */diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.tsindex 44db7e7da..b1bd6b3b9 100644--- a/packages/shared/src/types/settings.ts+++ b/packages/shared/src/types/settings.ts@@ -84,6 +84,11 @@ export type AppSettings = {* `external`: Open directly in the system's default web browser.*/linkOpenTarget?: LinkOpenTarget;+ /**+ * Attach vendor hosted-search tools when the current wire API supports them.+ * Absent means off.+ */+ nativeWebSearchEnabled?: boolean;/*** Which context figure the composer ring and its summary lead with (D398).* `remaining` (default, absent) counts down from 100%; `used` counts up.