@agent-native/core 0.101.12 → 0.101.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +8 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/cli/create.ts +45 -8
- package/corpus/core/src/client/assistant-ui-recovery.tsx +9 -3
- package/corpus/core/src/client/chat/message-components.tsx +25 -2
- package/corpus/core/src/client/chat/tool-call-display.tsx +6 -9
- package/corpus/core/src/mcp/server.ts +10 -1
- package/corpus/core/src/server/agent-chat/framework-prompts.ts +0 -3
- package/corpus/core/src/server/agent-chat-plugin.ts +2 -58
- package/corpus/core/src/server/prompts/framework-core-compact.ts +0 -1
- package/corpus/core/src/server/prompts/framework-core.ts +0 -30
- package/corpus/core/src/server/prompts/index.ts +1 -4
- package/corpus/templates/chat/app/components/layout/Sidebar.tsx +0 -14
- package/corpus/templates/chat/changelog/2026-07-15-chat-navigation-focuses-on-chat-and-agent.md +6 -0
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +31 -7
- package/dist/cli/create.js.map +1 -1
- package/dist/client/assistant-ui-recovery.d.ts +2 -0
- package/dist/client/assistant-ui-recovery.d.ts.map +1 -1
- package/dist/client/assistant-ui-recovery.js +5 -2
- package/dist/client/assistant-ui-recovery.js.map +1 -1
- package/dist/client/chat/message-components.d.ts +6 -0
- package/dist/client/chat/message-components.d.ts.map +1 -1
- package/dist/client/chat/message-components.js +14 -1
- package/dist/client/chat/message-components.js.map +1 -1
- package/dist/client/chat/tool-call-display.d.ts +1 -1
- package/dist/client/chat/tool-call-display.d.ts.map +1 -1
- package/dist/client/chat/tool-call-display.js +5 -8
- package/dist/client/chat/tool-call-display.js.map +1 -1
- package/dist/collab/awareness.d.ts +2 -2
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +10 -1
- package/dist/mcp/server.js.map +1 -1
- package/dist/resources/handlers.d.ts +2 -2
- package/dist/server/agent-chat/framework-prompts.d.ts.map +1 -1
- package/dist/server/agent-chat/framework-prompts.js +0 -3
- package/dist/server/agent-chat/framework-prompts.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +0 -22
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +2 -51
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/prompts/framework-core-compact.d.ts +0 -1
- package/dist/server/prompts/framework-core-compact.d.ts.map +1 -1
- package/dist/server/prompts/framework-core-compact.js +0 -1
- package/dist/server/prompts/framework-core-compact.js.map +1 -1
- package/dist/server/prompts/framework-core.d.ts +0 -9
- package/dist/server/prompts/framework-core.d.ts.map +1 -1
- package/dist/server/prompts/framework-core.js +0 -29
- package/dist/server/prompts/framework-core.js.map +1 -1
- package/dist/server/prompts/index.d.ts +1 -1
- package/dist/server/prompts/index.d.ts.map +1 -1
- package/dist/server/prompts/index.js +1 -1
- package/dist/server/prompts/index.js.map +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-call-display.js","sourceRoot":"","sources":["../../../src/client/chat/tool-call-display.tsx"],"names":[],"mappings":";AAIA,OAAO,EACL,WAAW,EACX,WAAW,EACX,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,QAAQ,EACR,cAAc,EACd,aAAa,EACb,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,eAAe,EACf,KAAK,GACN,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,EACZ,QAAQ,EACR,SAAS,EACT,WAAW,EACX,eAAe,EACf,MAAM,GACP,MAAM,OAAO,CAAC;AAIf,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO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AK,SAAS,EAAC,MAAM,YAAE,QAAQ,GAAO,GACH,GACpB,IACf,CACP,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,8EAA8E;AAC9E,+DAA+D;AAC/D,OAAO,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["// Owns: tool-payload formatting helpers, ToolCallDisplay, ToolCallFallback,\n// and ReconnectStreamMessage used by AssistantChat.\n\nimport type { ToolCallMessagePartProps } from \"@assistant-ui/react\";\nimport {\n IconLoader2,\n IconCircleX,\n IconCheck,\n IconChevronRight,\n IconCopy,\n IconCode,\n IconBrandSlack,\n IconTerminal2,\n IconDatabase,\n IconSearch,\n IconFileCode,\n IconShieldCheck,\n IconX,\n} from \"@tabler/icons-react\";\nimport React, {\n useState,\n useEffect,\n useCallback,\n useLayoutEffect,\n useRef,\n} from \"react\";\n\nimport type { ActionChatUIConfig } from \"../../action-ui.js\";\nimport type { AgentMcpAppPayload } from \"../../mcp-client/app-result.js\";\nimport { AgentTaskCard } from \"../AgentTaskCard.js\";\nimport { writeClipboardText } from \"../clipboard.js\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"../components/ui/popover.js\";\nimport { ConnectBuilderCard } from \"../ConnectBuilderCard.js\";\nimport { McpAppRenderer } from \"../mcp-apps/McpAppRenderer.js\";\nimport type { ContentPart } from \"../sse-event-processor.js\";\nimport {\n BashCell,\n EditCell,\n WriteCell,\n FilesChangedSummary,\n} from \"../tool-cells/index.js\";\nimport { humanizeToolName } from \"../tool-display.js\";\nimport { cn } from \"../utils.js\";\nimport {\n SmoothMarkdownText,\n HighlightedCodeBlock,\n markdownComponents,\n markdownModule,\n remarkGfmFn,\n markdownUrlTransform,\n} from \"./markdown-renderer.js\";\nimport { resolveToolRenderer } from \"./tool-render-registry.js\";\nimport {\n isBuiltinDataWidgetActionRenderer,\n resolveBuiltinActionChatRenderer,\n resolveBuiltinFallbackToolRenderer,\n} from \"./widgets/builtin-tool-renderers.js\";\n\n// Exported so AssistantChatInner can provide a context value.\nexport const ChatRunningContext = React.createContext(false);\n\n/**\n * Human-in-the-loop approval bridge. `AssistantChatInner` provides a value that\n * re-issues the turn approving a specific paused tool call (opt-in\n * `needsApproval` actions). When null, the Approve button is not rendered.\n * Deny defaults to local-only (the action stays un-run) unless `onDeny` is\n * provided, and \"Always allow\" only renders when `onAlwaysAllow` is provided\n * — both are additive so existing action-approval consumers are unaffected.\n */\nexport type ApprovalContextValue = {\n /** Re-issue the turn so the server runs the approved call. */\n onApprove: (approvalKey: string) => void;\n /**\n * Optional host hook invoked in addition to the local \"denied\" state, e.g.\n * so a Code session can also resolve its own pending approval as denied.\n */\n onDeny?: (approvalKey: string) => void;\n /**\n * Optional host hook that persists this exact call so future occurrences\n * skip the approval gate. When absent, no \"Always allow\" button renders.\n */\n onAlwaysAllow?: (approvalKey: string) => void;\n};\nexport const ApprovalContext = React.createContext<ApprovalContextValue | null>(\n null,\n);\n\nexport const TOOL_LONG_RUNNING_HINT_DELAY_MS = 45_000;\n\nfunction ToolLongRunningHintShell({\n toolName,\n isRunning,\n children,\n}: {\n toolName: string;\n isRunning: boolean;\n children: React.ReactNode;\n}) {\n const [showLongRunningHint, setShowLongRunningHint] = useState(false);\n\n useEffect(() => {\n if (!isRunning) {\n setShowLongRunningHint(false);\n return;\n }\n setShowLongRunningHint(false);\n const timeout = window.setTimeout(() => {\n setShowLongRunningHint(true);\n }, TOOL_LONG_RUNNING_HINT_DELAY_MS);\n return () => window.clearTimeout(timeout);\n }, [isRunning, toolName]);\n\n return (\n <>\n {children}\n {isRunning && showLongRunningHint && (\n <div className=\"mt-0.5 px-2.5 text-[11px] leading-snug text-muted-foreground/80\">\n Still working. Large updates can take a minute or two.\n </div>\n )}\n </>\n );\n}\n\n// ─── Tool-payload formatting ──────────────────────────────────────────────────\n\ntype ToolDetailSection = \"input\" | \"result\";\nexport type ToolDetailPayload = {\n section: ToolDetailSection;\n title: string;\n text: string;\n copyText: string;\n lang: string;\n};\n\nfunction stringifyToolValue(value: unknown, pretty = false): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, pretty ? 2 : 0);\n } catch {\n return String(value ?? \"\");\n }\n}\n\nfunction looksLikeSql(text: string): boolean {\n return /^\\s*(select|with|insert|update|delete|merge|create|alter|drop|explain|declare|begin)\\b/i.test(\n text,\n );\n}\n\nfunction parseJsonText(text: string): unknown | null {\n const trimmed = text.trim();\n if (!trimmed || !/^[{[]/.test(trimmed)) return null;\n try {\n return JSON.parse(trimmed);\n } catch {\n return null;\n }\n}\n\nfunction inferToolTextLanguage(\n text: string,\n key?: string,\n toolName?: string,\n): string {\n const keyName = (key ?? \"\").toLowerCase();\n const tool = (toolName ?? \"\").toLowerCase();\n if (\n keyName === \"code\" &&\n (tool.includes(\"run-code\") || tool.includes(\"run_code\"))\n ) {\n return \"javascript\";\n }\n if (\n keyName === \"sql\" ||\n keyName.endsWith(\"sql\") ||\n keyName === \"query\" ||\n tool.includes(\"bigquery\") ||\n tool.includes(\"db-query\") ||\n looksLikeSql(text)\n ) {\n return \"sql\";\n }\n return parseJsonText(text) ? \"json\" : \"text\";\n}\n\nfunction formatToolTextValue(\n value: unknown,\n key?: string,\n toolName?: string,\n): { text: string; lang: string } {\n if (typeof value === \"string\") {\n const parsed = parseJsonText(value);\n if (parsed) {\n return { text: JSON.stringify(parsed, null, 2), lang: \"json\" };\n }\n return {\n text: value,\n lang: inferToolTextLanguage(value, key, toolName),\n };\n }\n return { text: stringifyToolValue(value, true), lang: \"json\" };\n}\n\nexport function toolInputPayload(\n toolName: string,\n args: Record<string, unknown>,\n): ToolDetailPayload | null {\n const entries = Object.entries(args);\n if (entries.length === 0) return null;\n if (entries.length === 1) {\n const [key, value] = entries[0]!;\n const formatted = formatToolTextValue(value, key, toolName);\n const normalizedKey = key.toLowerCase();\n const keyLabel =\n normalizedKey === \"sql\" || normalizedKey.endsWith(\"sql\") ? \"SQL\" : key;\n return {\n section: \"input\",\n title: `Input - ${keyLabel}`,\n text: formatted.text,\n copyText:\n typeof value === \"string\" ? value : stringifyToolValue(value, true),\n lang: formatted.lang,\n };\n }\n return {\n section: \"input\",\n title: \"Input\",\n text: JSON.stringify(args, null, 2),\n copyText: JSON.stringify(args, null, 2),\n lang: \"json\",\n };\n}\n\nexport function toolResultPayload(\n result: string | undefined,\n): ToolDetailPayload | null {\n if (result === undefined) return null;\n const formatted = formatToolTextValue(result);\n return {\n section: \"result\",\n title: \"Result\",\n text: formatted.text,\n copyText: result,\n lang: formatted.lang,\n };\n}\n\n// ─── Tool icon helpers ────────────────────────────────────────────────────────\n\ntype ToolIconComponent = React.ComponentType<{\n className?: string;\n size?: number | string;\n}>;\n\nfunction resolveToolIcon(toolName: string): ToolIconComponent {\n const name = toolName.toLowerCase();\n if (name.includes(\"slack\")) return IconBrandSlack;\n if (\n name.includes(\"bash\") ||\n name.includes(\"shell\") ||\n name.includes(\"terminal\") ||\n name.includes(\"run-code\") ||\n name.includes(\"exec\")\n ) {\n return IconTerminal2;\n }\n if (\n name.includes(\"sql\") ||\n name.includes(\"bigquery\") ||\n name.includes(\"db-query\") ||\n name.includes(\"query\")\n ) {\n return IconDatabase;\n }\n if (\n name.includes(\"search\") ||\n name.includes(\"find\") ||\n name.includes(\"grep\")\n ) {\n return IconSearch;\n }\n if (\n name.includes(\"file\") ||\n name.includes(\"read\") ||\n name.includes(\"write\") ||\n name.includes(\"edit\")\n ) {\n return IconFileCode;\n }\n return IconCode;\n}\n\n// ─── Simple code viewer (Codex-style gray box) ────────────────────────────────\n\nfunction SimpleCodeViewer({\n text,\n lang,\n className,\n maxHeightClass = \"max-h-56\",\n}: {\n text: string;\n lang: string;\n className?: string;\n maxHeightClass?: string;\n}) {\n return (\n <div\n className={cn(\n \"agent-tool-code overflow-auto rounded-md bg-muted/70 font-mono text-[11px] leading-relaxed text-foreground\",\n maxHeightClass,\n className,\n )}\n >\n {lang !== \"text\" && (\n <div className=\"sticky top-0 z-[1] flex items-center justify-between border-b border-border/40 bg-muted/90 px-2.5 py-1\">\n <span className=\"font-mono text-[10px] uppercase tracking-wide text-muted-foreground/80\">\n {lang}\n </span>\n </div>\n )}\n <HighlightedCodeBlock code={text} lang={lang} />\n </div>\n );\n}\n\nfunction ToolOutputPopover({\n open,\n onOpenChange,\n title,\n payload,\n children,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: string;\n payload: ToolDetailPayload;\n children: React.ReactNode;\n}) {\n const [copied, setCopied] = useState(false);\n const copyResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (copyResetRef.current) clearTimeout(copyResetRef.current);\n };\n }, []);\n\n const copyValue = useCallback(async () => {\n try {\n if (await writeClipboardText(payload.copyText)) {\n setCopied(true);\n if (copyResetRef.current) clearTimeout(copyResetRef.current);\n copyResetRef.current = setTimeout(() => setCopied(false), 1200);\n }\n } catch {\n // Clipboard failures should not interrupt chat rendering.\n }\n }, [payload.copyText]);\n\n return (\n <Popover open={open} onOpenChange={onOpenChange}>\n <PopoverTrigger asChild>{children}</PopoverTrigger>\n <PopoverContent\n align=\"start\"\n side=\"bottom\"\n sideOffset={6}\n collisionPadding={12}\n className=\"flex max-h-[min(calc(100vh-2rem),var(--radix-popover-content-available-height,75vh))] w-[min(calc(100vw-2rem),var(--radix-popover-content-available-width,760px),760px)] flex-col gap-0 overflow-hidden p-0\"\n >\n <div className=\"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3\">\n <div className=\"truncate text-sm font-medium\">{title}</div>\n <button\n type=\"button\"\n onClick={copyValue}\n className=\"inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground\"\n >\n {copied ? <IconCheck size={13} /> : <IconCopy size={13} />}\n {copied ? \"Copied\" : \"Copy\"}\n </button>\n </div>\n <div className=\"min-h-0 flex-1 overflow-hidden p-3\">\n <SimpleCodeViewer\n text={payload.text}\n lang={payload.lang}\n maxHeightClass=\"max-h-[min(70vh,calc(var(--radix-popover-content-available-height,75vh)-4.5rem))]\"\n />\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n\n// ─── Collapsible height animation ─────────────────────────────────────────────\n\nexport function AnimatedCollapse({\n open,\n children,\n}: {\n open: boolean;\n children: React.ReactNode;\n}) {\n const [mounted, setMounted] = useState(open);\n\n useLayoutEffect(() => {\n if (open) setMounted(true);\n }, [open]);\n\n const onTransitionEnd = useCallback(\n (event: React.TransitionEvent<HTMLDivElement>) => {\n if (event.propertyName !== \"grid-template-rows\" || open) return;\n setMounted(false);\n },\n [open],\n );\n\n if (!mounted) return null;\n\n return (\n <div\n className=\"agent-chat-collapse\"\n data-state={open ? \"open\" : \"closed\"}\n aria-hidden={!open}\n onTransitionEnd={onTransitionEnd}\n >\n <div className=\"agent-chat-collapse__content\">{children}</div>\n </div>\n );\n}\n\n// ─── Human-in-the-loop approval affordance ────────────────────────────────────\n\n/**\n * Inline Approve/Deny prompt rendered when a `needsApproval` action paused the\n * turn. Approve re-issues the turn with the call's `approvalKey`; Deny dismisses\n * the prompt locally (the action stays un-run).\n */\nfunction ApprovalAffordance({\n toolName,\n approval,\n}: {\n toolName: string;\n approval: { approvalKey: string; dismissed?: boolean };\n}) {\n const ctx = React.useContext(ApprovalContext);\n const [approved, setApproved] = useState(false);\n const [denied, setDenied] = useState(false);\n\n // Once approved, the turn is re-issued; collapse to a quiet note so the user\n // can't double-fire the approval.\n if (approved) {\n return (\n <div className=\"mt-1.5 text-xs text-muted-foreground\">\n Approved. Re-running {toolName}...\n </div>\n );\n }\n // Deny defaults to local-only (the action simply stays un-run). When the\n // host also provided `onDeny` (e.g. a Code session resolving its own\n // pending approval), it fires alongside the local state.\n if (denied) {\n return (\n <div className=\"mt-1.5 text-xs text-muted-foreground\">\n Denied. {toolName} did not run.\n </div>\n );\n }\n return (\n <div className=\"mt-1.5 flex items-center gap-2 rounded-md border border-border bg-muted/40 px-2.5 py-1.5\">\n <IconShieldCheck className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"mr-auto text-xs text-muted-foreground\">\n Approve to run {toolName}?\n </span>\n {ctx && (\n <button\n type=\"button\"\n onClick={() => {\n setApproved(true);\n ctx.onApprove(approval.approvalKey);\n }}\n className={cn(\n \"inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-medium transition-colors\",\n \"bg-foreground text-background hover:bg-foreground/90\",\n )}\n >\n <IconCheck className=\"h-3.5 w-3.5\" />\n Approve\n </button>\n )}\n {ctx?.onAlwaysAllow && (\n <button\n type=\"button\"\n onClick={() => {\n setApproved(true);\n ctx.onAlwaysAllow?.(approval.approvalKey);\n }}\n title=\"Approve and always allow this exact command\"\n className={cn(\n \"inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs font-medium transition-colors\",\n \"text-foreground hover:bg-muted\",\n )}\n >\n <IconShieldCheck className=\"h-3.5 w-3.5\" />\n Always allow\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => {\n setDenied(true);\n ctx?.onDeny?.(approval.approvalKey);\n }}\n className={cn(\n \"inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs font-medium transition-colors\",\n \"text-foreground hover:bg-muted\",\n )}\n >\n <IconX className=\"h-3.5 w-3.5\" />\n Deny\n </button>\n </div>\n );\n}\n\n// ─── ToolCallDisplay ──────────────────────────────────────────────────────────\n\nexport function ToolCallDisplay({\n toolName,\n argsText,\n args,\n result,\n mcpApp,\n chatUI,\n isRunning,\n structuredMeta,\n approval,\n repeatCount,\n}: {\n toolName: string;\n argsText?: string;\n args: Record<string, unknown>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n chatUI?: ActionChatUIConfig;\n isRunning: boolean;\n structuredMeta?: Record<string, unknown>;\n approval?: { approvalKey: string; dismissed?: boolean };\n repeatCount?: number;\n}) {\n // Delegate to bespoke cells when structured metadata is present.\n // These must be separate components so hook order in ToolCallDisplayGeneric\n // is always stable (no conditional hook calls).\n const toolKind = structuredMeta?.toolKind as string | undefined;\n const wrapToolDisplay = (children: React.ReactNode) => (\n <ToolLongRunningHintShell toolName={toolName} isRunning={isRunning}>\n {children}\n </ToolLongRunningHintShell>\n );\n if (toolKind === \"bash\") {\n return wrapToolDisplay(\n <BashCell\n meta={\n structuredMeta as unknown as Parameters<typeof BashCell>[0][\"meta\"]\n }\n output={result}\n isRunning={isRunning}\n />,\n );\n }\n if (toolKind === \"edit\") {\n return wrapToolDisplay(\n <EditCell\n meta={\n structuredMeta as unknown as Parameters<typeof EditCell>[0][\"meta\"]\n }\n isRunning={isRunning}\n />,\n );\n }\n if (toolKind === \"write\") {\n return wrapToolDisplay(\n <WriteCell\n meta={\n structuredMeta as unknown as Parameters<typeof WriteCell>[0][\"meta\"]\n }\n isRunning={isRunning}\n />,\n );\n }\n return wrapToolDisplay(\n <ToolCallDisplayGeneric\n toolName={toolName}\n argsText={argsText}\n args={args}\n result={result}\n mcpApp={mcpApp}\n chatUI={chatUI}\n isRunning={isRunning}\n approval={approval}\n repeatCount={repeatCount}\n />,\n );\n}\n\nfunction ToolCallDisplayGeneric({\n toolName,\n argsText,\n args,\n result,\n mcpApp,\n chatUI,\n isRunning,\n approval,\n repeatCount,\n}: {\n toolName: string;\n argsText?: string;\n args: Record<string, unknown>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n chatUI?: ActionChatUIConfig;\n isRunning: boolean;\n approval?: { approvalKey: string; dismissed?: boolean };\n repeatCount?: number;\n}) {\n const streamRef = useRef<HTMLDivElement>(null);\n\n const isAgentCall = toolName.startsWith(\"agent:\");\n const [expanded, setExpanded] = useState(isAgentCall);\n const [outputOpen, setOutputOpen] = useState(false);\n const agentName = isAgentCall ? toolName.slice(6) : null;\n const isAgentError = isAgentCall && result === \"Error calling agent\";\n const agentStreamText = isAgentCall ? (argsText ?? \"\") : \"\";\n const hasStreamText = agentStreamText.length > 0;\n const hasArgs = !isAgentCall && Object.keys(args).length > 0;\n\n // NOTE: All hooks must be above any conditional returns\n useEffect(() => {\n if (isAgentCall && isRunning && streamRef.current) {\n streamRef.current.scrollTop = streamRef.current.scrollHeight;\n }\n }, [agentStreamText, isAgentCall, isRunning]);\n\n // Render connect-builder as ConnectBuilderCard once the result is available\n if (toolName === \"connect-builder\" && result) {\n try {\n const parsed = JSON.parse(result);\n if (parsed?.kind === \"connect-builder-card\") {\n return (\n <ConnectBuilderCard\n configured={!!parsed.configured}\n builderEnabled={parsed.builderEnabled !== false}\n // Ignore saved cliAuthUrl values from older tool results. They\n // contain signed callback state and can expire while a chat sits\n // open; the card's hook fetches a fresh signed URL on mount/click.\n connectUrl={parsed.connectUrl || \"\"}\n orgName={parsed.orgName ?? null}\n prompt={typeof parsed.prompt === \"string\" ? parsed.prompt : \"\"}\n />\n );\n }\n } catch {\n // fall through to default pill rendering\n }\n }\n\n // Render agent-teams spawn as AgentTaskCard once the result is available\n if (\n toolName === \"agent-teams\" &&\n (args as Record<string, string>)?.action === \"spawn\" &&\n result\n ) {\n try {\n const parsed = JSON.parse(result);\n if (parsed.taskId && parsed.threadId) {\n return (\n <AgentTaskCard\n taskId={parsed.taskId}\n threadId={parsed.threadId}\n description={\n parsed.description ||\n (args as Record<string, string>)?.task ||\n \"Sub-agent task\"\n }\n onOpen={(tid) => {\n window.dispatchEvent(\n new CustomEvent(\"agent-task-open\", {\n detail: {\n threadId: tid,\n description:\n parsed.description ||\n (args as Record<string, string>)?.task ||\n \"\",\n name: parsed.name || \"\",\n },\n }),\n );\n }}\n />\n );\n }\n } catch {\n // Fall through to default pill rendering\n }\n }\n\n const parsedResult = result ? parseJsonText(result) : null;\n const nativeToolContext = {\n toolName,\n args,\n resultText: result,\n resultJson: parsedResult,\n isRunning,\n chatUI,\n };\n const skipRegistryRenderer =\n !isAgentCall && isBuiltinDataWidgetActionRenderer(nativeToolContext);\n const NativeToolRenderer = isAgentCall\n ? null\n : (resolveBuiltinActionChatRenderer(nativeToolContext) ??\n (skipRegistryRenderer ? null : resolveToolRenderer(nativeToolContext)) ??\n resolveBuiltinFallbackToolRenderer(nativeToolContext));\n if (NativeToolRenderer) {\n return <NativeToolRenderer context={nativeToolContext} />;\n }\n\n const inputPayload = hasArgs ? toolInputPayload(toolName, args) : null;\n const resultPayload = toolResultPayload(result);\n\n const displayName = isAgentCall\n ? isRunning\n ? `Asking ${agentName}...`\n : isAgentError\n ? `Error asking ${agentName}`\n : `Asked ${agentName}`\n : humanizeToolName(toolName);\n\n const canExpand = isAgentCall\n ? hasStreamText\n : hasArgs || result !== undefined;\n const isExpanded = isAgentCall ? hasStreamText && expanded : expanded;\n const ToolIcon = resolveToolIcon(toolName);\n const outputTitle = `Raw ${toolName} tool call output`;\n\n return (\n <div className=\"group/tool my-0.5 w-full overflow-hidden\">\n {mcpApp && <McpAppRenderer app={mcpApp} className=\"mb-1.5\" />}\n <button\n type=\"button\"\n onClick={() => canExpand && setExpanded(!isExpanded)}\n aria-expanded={canExpand ? isExpanded : undefined}\n className={cn(\n \"flex w-full items-center gap-1.5 rounded-md py-0.5 text-left text-[13px] text-muted-foreground transition-colors\",\n canExpand && \"hover:text-foreground\",\n isRunning && \"text-muted-foreground\",\n )}\n >\n <span className=\"relative flex size-4 shrink-0 items-center justify-center\">\n {isRunning ? (\n <IconLoader2 className=\"size-3.5 animate-spin\" />\n ) : isAgentError ? (\n <IconCircleX className=\"size-3.5 text-destructive\" />\n ) : (\n <>\n <ToolIcon\n className={cn(\n \"size-3.5 transition-opacity\",\n canExpand && \"group-hover/tool:opacity-0\",\n )}\n />\n {canExpand && (\n <IconChevronRight\n className={cn(\n \"absolute size-3.5 opacity-0 transition-[opacity,transform] group-hover/tool:opacity-100\",\n isExpanded && \"rotate-90\",\n )}\n />\n )}\n </>\n )}\n </span>\n <span className=\"min-w-0 truncate font-normal\">{displayName}</span>\n {repeatCount && repeatCount > 1 && (\n <span\n className=\"shrink-0 rounded border border-border/60 px-1.5 py-0.5 text-[10px] leading-none text-muted-foreground\"\n title={`Repeated ${repeatCount} times`}\n >\n {repeatCount}x\n </span>\n )}\n </button>\n <AnimatedCollapse open={isExpanded && isAgentCall && hasStreamText}>\n <div\n ref={streamRef}\n className=\"mt-1 rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground break-words max-h-48 overflow-y-auto agent-markdown prose prose-sm prose-invert max-w-none\"\n >\n {markdownModule?.default && remarkGfmFn ? (\n <markdownModule.default\n remarkPlugins={[remarkGfmFn]}\n components={markdownComponents}\n urlTransform={markdownUrlTransform}\n >\n {agentStreamText}\n </markdownModule.default>\n ) : (\n <span style={{ whiteSpace: \"pre-wrap\" }}>{agentStreamText}</span>\n )}\n </div>\n </AnimatedCollapse>\n <AnimatedCollapse\n open={isExpanded && !isAgentCall && (hasArgs || result !== undefined)}\n >\n <div className=\"mt-1 space-y-2 pl-5\">\n {inputPayload && (\n <SimpleCodeViewer\n text={inputPayload.text}\n lang={inputPayload.lang}\n />\n )}\n {resultPayload && (\n <ToolOutputPopover\n open={outputOpen}\n onOpenChange={setOutputOpen}\n title={outputTitle}\n payload={resultPayload}\n >\n <button\n type=\"button\"\n aria-label={`View ${toolName} output`}\n className=\"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground\"\n >\n <IconCode className=\"size-3.5\" />\n </button>\n </ToolOutputPopover>\n )}\n </div>\n </AnimatedCollapse>\n {approval && (\n <ApprovalAffordance toolName={toolName} approval={approval} />\n )}\n </div>\n );\n}\n\n// ─── ToolCallFallback ──────────────────────────────────────────────────────────\n\nexport function ToolCallFallback({\n toolName,\n args,\n argsText,\n result,\n ...rest\n}: ToolCallMessagePartProps & {\n mcpApp?: AgentMcpAppPayload;\n chatUI?: ActionChatUIConfig;\n structuredMeta?: Record<string, unknown>;\n activity?: boolean;\n approval?: { approvalKey: string; dismissed?: boolean };\n repeatCount?: number;\n}) {\n const chatRunning = React.useContext(ChatRunningContext);\n const isRunning =\n result === undefined && (chatRunning || rest.activity === true);\n return (\n <ToolCallDisplay\n toolName={toolName}\n args={args as Record<string, unknown>}\n argsText={argsText}\n result={\n typeof result === \"string\"\n ? result\n : result !== undefined\n ? JSON.stringify(result)\n : undefined\n }\n mcpApp={rest.mcpApp}\n chatUI={rest.chatUI}\n structuredMeta={rest.structuredMeta}\n isRunning={isRunning}\n approval={rest.approval}\n repeatCount={rest.repeatCount}\n />\n );\n}\n\n// ─── ReconnectStreamMessage ────────────────────────────────────────────────────\n// Renders the agent's in-progress response during reconnection (outside\n// assistant-ui's runtime). Uses the same visual styling as normal messages.\n\nexport function ReconnectStreamMessage({\n content,\n}: {\n content: ContentPart[];\n}) {\n const chatRunning = React.useContext(ChatRunningContext);\n const latestReasoningPartIndex = content.reduce(\n (latestIndex, part, index) =>\n part.type === \"reasoning\" ? index : latestIndex,\n -1,\n );\n const streamingTextPartIndex =\n content.at(-1)?.type === \"text\" ? content.length - 1 : -1;\n const streamingReasoningPartIndex =\n content.at(-1)?.type === \"reasoning\" ? content.length - 1 : -1;\n\n return (\n <div className=\"flex justify-start\">\n <div className=\"w-full max-w-[95%] text-sm leading-relaxed text-foreground space-y-1\">\n {content.map((part, i) => {\n if (part.type === \"text\") {\n const partStreaming = chatRunning && i === streamingTextPartIndex;\n return (\n <SmoothMarkdownText\n key={`reconnect-text-${i}`}\n text={part.text}\n streaming={partStreaming}\n resetKey={`reconnect-text-${i}`}\n statusType={partStreaming ? \"running\" : \"complete\"}\n />\n );\n }\n if (part.type === \"reasoning\") {\n return (\n <ReasoningCell\n key={`reconnect-reasoning-${i}`}\n text={part.text}\n isStreaming={chatRunning && i === streamingReasoningPartIndex}\n defaultOpen={i === latestReasoningPartIndex}\n collapseWhenReplaced={i < latestReasoningPartIndex}\n />\n );\n }\n if (part.type === \"tool-call\") {\n return (\n <ToolCallDisplay\n key={`reconnect-tool-${i}`}\n toolName={part.toolName}\n argsText={part.argsText}\n args={part.args}\n result={part.result}\n mcpApp={part.mcpApp}\n chatUI={part.chatUI}\n structuredMeta={part.structuredMeta}\n isRunning={\n part.result === undefined &&\n (chatRunning || part.activity === true)\n }\n approval={part.approval}\n repeatCount={part.repeatCount}\n />\n );\n }\n return null;\n })}\n </div>\n </div>\n );\n}\n\n// ─── Reasoning / Thinking cell ────────────────────────────────────────────────\n\n/**\n * Completed reasoning and tool calls share one outer \"Worked for…\"\n * disclosure. Reasoning cells inside it render their prose directly so\n * opening that summary never reveals a redundant second disclosure.\n */\nconst WorkSummaryContentContext = React.createContext(false);\n\nexport function ReasoningCell({\n text,\n isStreaming = false,\n defaultOpen,\n autoCollapse = false,\n collapseWhenReplaced = false,\n durationMs,\n}: {\n text: string;\n isStreaming?: boolean;\n defaultOpen?: boolean;\n /** Animate closed when a live reasoning segment finishes during a run. */\n autoCollapse?: boolean;\n /** Animate closed when a newer reasoning segment replaces this one. */\n collapseWhenReplaced?: boolean;\n /**\n * Elapsed thinking time in ms, once known. Only meaningful once streaming\n * has finished — callers that track live timing (see ReasoningMessagePart)\n * pass this so the label can read \"Thought for Xs\" instead of \"Thought\".\n * Historical messages with no live timing simply omit it.\n */\n durationMs?: number | null;\n}) {\n const embeddedInWorkSummary = React.useContext(WorkSummaryContentContext);\n const [open, setOpen] = useState(defaultOpen ?? true);\n const wasStreamingRef = useRef(isStreaming);\n const wasReplacedRef = useRef(collapseWhenReplaced);\n const trimmed = text.trim();\n\n useEffect(() => {\n if (autoCollapse && wasStreamingRef.current && !isStreaming) {\n setOpen(false);\n }\n wasStreamingRef.current = isStreaming;\n }, [autoCollapse, isStreaming]);\n\n useEffect(() => {\n if (collapseWhenReplaced && !wasReplacedRef.current) {\n setOpen(false);\n }\n wasReplacedRef.current = collapseWhenReplaced;\n }, [collapseWhenReplaced]);\n\n if (!trimmed && !isStreaming) return null;\n\n if (embeddedInWorkSummary) {\n return (\n <div className=\"pb-1 pl-5 text-[13px] leading-relaxed text-muted-foreground whitespace-pre-wrap\">\n {trimmed || (isStreaming ? \"…\" : \"\")}\n </div>\n );\n }\n\n const label = isStreaming\n ? \"Thinking\"\n : durationMs != null\n ? `Thought for ${formatWorkedDuration(durationMs)}`\n : \"Thought\";\n // Only clamp to a scroll-free \"tail\" view while actively streaming and\n // expanded — once the run finishes the full text is shown, unclamped.\n const showTail = isStreaming && open;\n\n return (\n <div className=\"my-0.5 w-full\">\n <button\n type=\"button\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n className=\"flex items-center gap-1.5 py-0.5 text-[13px] text-muted-foreground transition-colors hover:text-foreground\"\n >\n <IconChevronRight\n className={cn(\n \"size-3.5 shrink-0 transition-transform\",\n open && \"rotate-90\",\n )}\n />\n {isStreaming ? (\n <span className=\"agent-thinking-indicator__text\">{label}</span>\n ) : (\n <span>{label}</span>\n )}\n </button>\n <AnimatedCollapse open={open}>\n <div className={cn(\"pl-5 pb-1\", showTail && \"reasoning-cell-tail\")}>\n <div className=\"text-[13px] leading-relaxed text-muted-foreground whitespace-pre-wrap\">\n {trimmed || (isStreaming ? \"…\" : \"\")}\n </div>\n </div>\n </AnimatedCollapse>\n </div>\n );\n}\n\n// ─── Worked-for duration helpers ──────────────────────────────────────────────\n\nexport function formatWorkedDuration(ms: number): string {\n const totalSeconds = Math.max(0, Math.round(ms / 1000));\n if (totalSeconds < 60) {\n return totalSeconds <= 1 ? \"1s\" : `${totalSeconds}s`;\n }\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n if (minutes < 60) {\n if (seconds === 0) return `${minutes}m`;\n return `${minutes}m ${seconds}s`;\n }\n const hours = Math.floor(minutes / 60);\n const remMinutes = minutes % 60;\n if (remMinutes === 0) return `${hours}h`;\n return `${hours}h ${remMinutes}m`;\n}\n\nexport function WorkedForSummary({\n durationMs,\n autoCollapse = false,\n children,\n}: {\n durationMs?: number | null;\n /** When true, start open then animate closed (post-run collapse). */\n autoCollapse?: boolean;\n children: React.ReactNode;\n}) {\n const [open, setOpen] = useState(autoCollapse);\n const didAutoCollapseRef = useRef(false);\n\n useEffect(() => {\n if (!autoCollapse || didAutoCollapseRef.current) return;\n didAutoCollapseRef.current = true;\n const frame = requestAnimationFrame(() => {\n setOpen(false);\n });\n return () => cancelAnimationFrame(frame);\n }, [autoCollapse]);\n\n const label =\n durationMs != null && durationMs >= 1000\n ? `Worked for ${formatWorkedDuration(durationMs)}`\n : \"Worked\";\n\n return (\n <div className=\"my-1 w-full\">\n <button\n type=\"button\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n className=\"flex items-center gap-1.5 py-0.5 text-[13px] text-muted-foreground transition-colors hover:text-foreground\"\n >\n <span>{label}</span>\n <IconChevronRight\n className={cn(\n \"size-3.5 shrink-0 transition-transform\",\n open && \"rotate-90\",\n )}\n />\n </button>\n <AnimatedCollapse open={open}>\n <WorkSummaryContentContext.Provider value>\n <div className=\"pt-1\">{children}</div>\n </WorkSummaryContentContext.Provider>\n </AnimatedCollapse>\n </div>\n );\n}\n\n// ─── Re-export for AssistantMessage ───────────────────────────────────────────\n// AssistantMessage in AssistantChat.tsx uses FilesChangedSummary directly, so\n// re-export it so AssistantChat.tsx can import from one place.\nexport { FilesChangedSummary };\n"]}
|
|
1
|
+
{"version":3,"file":"tool-call-display.js","sourceRoot":"","sources":["../../../src/client/chat/tool-call-display.tsx"],"names":[],"mappings":";AAIA,OAAO,EACL,WAAW,EACX,WAAW,EACX,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,QAAQ,EACR,cAAc,EACd,aAAa,EACb,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,eAAe,EACf,KAAK,GACN,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,EACZ,QAAQ,EACR,SAAS,EACT,WAAW,EACX,eAAe,EACf,MAAM,GACP,MAAM,OAAO,CAAC;AAIf,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EACL,OAAO,EACP,cAAc,EACd,cAAc,GACf,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D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uEAAuE;IACvE,2EAA2E;IAC3E,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAExC,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,YAAY;YAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;IAEnB,MAAM,KAAK,GACT,UAAU,IAAI,IAAI,IAAI,UAAU,IAAI,IAAI;QACtC,CAAC,CAAC,cAAc,oBAAoB,CAAC,UAAU,CAAC,EAAE;QAClD,CAAC,CAAC,QAAQ,CAAC;IAEf,OAAO,CACL,eAAK,SAAS,EAAC,aAAa,aAC1B,kBACE,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,mBAClB,IAAI,EACnB,SAAS,EAAC,4GAA4G,aAEtH,yBAAO,KAAK,GAAQ,EACpB,KAAC,gBAAgB,IACf,SAAS,EAAE,EAAE,CACX,wCAAwC,EACxC,IAAI,IAAI,WAAW,CACpB,GACD,IACK,EACT,KAAC,gBAAgB,IAAC,IAAI,EAAE,IAAI,YAC1B,KAAC,yBAAyB,CAAC,QAAQ,IAAC,KAAK,kBACvC,cAAK,SAAS,EAAC,MAAM,YAAE,QAAQ,GAAO,GACH,GACpB,IACf,CACP,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,8EAA8E;AAC9E,+DAA+D;AAC/D,OAAO,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["// Owns: tool-payload formatting helpers, ToolCallDisplay, ToolCallFallback,\n// and ReconnectStreamMessage used by AssistantChat.\n\nimport type { ToolCallMessagePartProps } from \"@assistant-ui/react\";\nimport {\n IconLoader2,\n IconCircleX,\n IconCheck,\n IconChevronRight,\n IconCopy,\n IconCode,\n IconBrandSlack,\n IconTerminal2,\n IconDatabase,\n IconSearch,\n IconFileCode,\n IconShieldCheck,\n IconX,\n} from \"@tabler/icons-react\";\nimport React, {\n useState,\n useEffect,\n useCallback,\n useLayoutEffect,\n useRef,\n} from \"react\";\n\nimport type { ActionChatUIConfig } from \"../../action-ui.js\";\nimport type { AgentMcpAppPayload } from \"../../mcp-client/app-result.js\";\nimport { AgentTaskCard } from \"../AgentTaskCard.js\";\nimport { writeClipboardText } from \"../clipboard.js\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"../components/ui/popover.js\";\nimport { ConnectBuilderCard } from \"../ConnectBuilderCard.js\";\nimport { McpAppRenderer } from \"../mcp-apps/McpAppRenderer.js\";\nimport type { ContentPart } from \"../sse-event-processor.js\";\nimport {\n BashCell,\n EditCell,\n WriteCell,\n FilesChangedSummary,\n} from \"../tool-cells/index.js\";\nimport { humanizeToolName } from \"../tool-display.js\";\nimport { cn } from \"../utils.js\";\nimport {\n SmoothMarkdownText,\n HighlightedCodeBlock,\n markdownComponents,\n markdownModule,\n remarkGfmFn,\n markdownUrlTransform,\n} from \"./markdown-renderer.js\";\nimport { resolveToolRenderer } from \"./tool-render-registry.js\";\nimport {\n isBuiltinDataWidgetActionRenderer,\n resolveBuiltinActionChatRenderer,\n resolveBuiltinFallbackToolRenderer,\n} from \"./widgets/builtin-tool-renderers.js\";\n\n// Exported so AssistantChatInner can provide a context value.\nexport const ChatRunningContext = React.createContext(false);\n\n/**\n * Human-in-the-loop approval bridge. `AssistantChatInner` provides a value that\n * re-issues the turn approving a specific paused tool call (opt-in\n * `needsApproval` actions). When null, the Approve button is not rendered.\n * Deny defaults to local-only (the action stays un-run) unless `onDeny` is\n * provided, and \"Always allow\" only renders when `onAlwaysAllow` is provided\n * — both are additive so existing action-approval consumers are unaffected.\n */\nexport type ApprovalContextValue = {\n /** Re-issue the turn so the server runs the approved call. */\n onApprove: (approvalKey: string) => void;\n /**\n * Optional host hook invoked in addition to the local \"denied\" state, e.g.\n * so a Code session can also resolve its own pending approval as denied.\n */\n onDeny?: (approvalKey: string) => void;\n /**\n * Optional host hook that persists this exact call so future occurrences\n * skip the approval gate. When absent, no \"Always allow\" button renders.\n */\n onAlwaysAllow?: (approvalKey: string) => void;\n};\nexport const ApprovalContext = React.createContext<ApprovalContextValue | null>(\n null,\n);\n\nexport const TOOL_LONG_RUNNING_HINT_DELAY_MS = 45_000;\n\nfunction ToolLongRunningHintShell({\n toolName,\n isRunning,\n children,\n}: {\n toolName: string;\n isRunning: boolean;\n children: React.ReactNode;\n}) {\n const [showLongRunningHint, setShowLongRunningHint] = useState(false);\n\n useEffect(() => {\n if (!isRunning) {\n setShowLongRunningHint(false);\n return;\n }\n setShowLongRunningHint(false);\n const timeout = window.setTimeout(() => {\n setShowLongRunningHint(true);\n }, TOOL_LONG_RUNNING_HINT_DELAY_MS);\n return () => window.clearTimeout(timeout);\n }, [isRunning, toolName]);\n\n return (\n <>\n {children}\n {isRunning && showLongRunningHint && (\n <div className=\"mt-0.5 px-2.5 text-[11px] leading-snug text-muted-foreground/80\">\n Still working. Large updates can take a minute or two.\n </div>\n )}\n </>\n );\n}\n\n// ─── Tool-payload formatting ──────────────────────────────────────────────────\n\ntype ToolDetailSection = \"input\" | \"result\";\nexport type ToolDetailPayload = {\n section: ToolDetailSection;\n title: string;\n text: string;\n copyText: string;\n lang: string;\n};\n\nfunction stringifyToolValue(value: unknown, pretty = false): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, pretty ? 2 : 0);\n } catch {\n return String(value ?? \"\");\n }\n}\n\nfunction looksLikeSql(text: string): boolean {\n return /^\\s*(select|with|insert|update|delete|merge|create|alter|drop|explain|declare|begin)\\b/i.test(\n text,\n );\n}\n\nfunction parseJsonText(text: string): unknown | null {\n const trimmed = text.trim();\n if (!trimmed || !/^[{[]/.test(trimmed)) return null;\n try {\n return JSON.parse(trimmed);\n } catch {\n return null;\n }\n}\n\nfunction inferToolTextLanguage(\n text: string,\n key?: string,\n toolName?: string,\n): string {\n const keyName = (key ?? \"\").toLowerCase();\n const tool = (toolName ?? \"\").toLowerCase();\n if (\n keyName === \"code\" &&\n (tool.includes(\"run-code\") || tool.includes(\"run_code\"))\n ) {\n return \"javascript\";\n }\n if (\n keyName === \"sql\" ||\n keyName.endsWith(\"sql\") ||\n keyName === \"query\" ||\n tool.includes(\"bigquery\") ||\n tool.includes(\"db-query\") ||\n looksLikeSql(text)\n ) {\n return \"sql\";\n }\n return parseJsonText(text) ? \"json\" : \"text\";\n}\n\nfunction formatToolTextValue(\n value: unknown,\n key?: string,\n toolName?: string,\n): { text: string; lang: string } {\n if (typeof value === \"string\") {\n const parsed = parseJsonText(value);\n if (parsed) {\n return { text: JSON.stringify(parsed, null, 2), lang: \"json\" };\n }\n return {\n text: value,\n lang: inferToolTextLanguage(value, key, toolName),\n };\n }\n return { text: stringifyToolValue(value, true), lang: \"json\" };\n}\n\nexport function toolInputPayload(\n toolName: string,\n args: Record<string, unknown>,\n): ToolDetailPayload | null {\n const entries = Object.entries(args);\n if (entries.length === 0) return null;\n if (entries.length === 1) {\n const [key, value] = entries[0]!;\n const formatted = formatToolTextValue(value, key, toolName);\n const normalizedKey = key.toLowerCase();\n const keyLabel =\n normalizedKey === \"sql\" || normalizedKey.endsWith(\"sql\") ? \"SQL\" : key;\n return {\n section: \"input\",\n title: `Input - ${keyLabel}`,\n text: formatted.text,\n copyText:\n typeof value === \"string\" ? value : stringifyToolValue(value, true),\n lang: formatted.lang,\n };\n }\n return {\n section: \"input\",\n title: \"Input\",\n text: JSON.stringify(args, null, 2),\n copyText: JSON.stringify(args, null, 2),\n lang: \"json\",\n };\n}\n\nexport function toolResultPayload(\n result: string | undefined,\n): ToolDetailPayload | null {\n if (result === undefined) return null;\n const formatted = formatToolTextValue(result);\n return {\n section: \"result\",\n title: \"Result\",\n text: formatted.text,\n copyText: result,\n lang: formatted.lang,\n };\n}\n\n// ─── Tool icon helpers ────────────────────────────────────────────────────────\n\ntype ToolIconComponent = React.ComponentType<{\n className?: string;\n size?: number | string;\n}>;\n\nfunction resolveToolIcon(toolName: string): ToolIconComponent {\n const name = toolName.toLowerCase();\n if (name.includes(\"slack\")) return IconBrandSlack;\n if (\n name.includes(\"bash\") ||\n name.includes(\"shell\") ||\n name.includes(\"terminal\") ||\n name.includes(\"run-code\") ||\n name.includes(\"exec\")\n ) {\n return IconTerminal2;\n }\n if (\n name.includes(\"sql\") ||\n name.includes(\"bigquery\") ||\n name.includes(\"db-query\") ||\n name.includes(\"query\")\n ) {\n return IconDatabase;\n }\n if (\n name.includes(\"search\") ||\n name.includes(\"find\") ||\n name.includes(\"grep\")\n ) {\n return IconSearch;\n }\n if (\n name.includes(\"file\") ||\n name.includes(\"read\") ||\n name.includes(\"write\") ||\n name.includes(\"edit\")\n ) {\n return IconFileCode;\n }\n return IconCode;\n}\n\n// ─── Simple code viewer (Codex-style gray box) ────────────────────────────────\n\nfunction SimpleCodeViewer({\n text,\n lang,\n className,\n maxHeightClass = \"max-h-56\",\n}: {\n text: string;\n lang: string;\n className?: string;\n maxHeightClass?: string;\n}) {\n return (\n <div\n className={cn(\n \"agent-tool-code overflow-auto rounded-md bg-muted/70 font-mono text-[11px] leading-relaxed text-foreground\",\n maxHeightClass,\n className,\n )}\n >\n {lang !== \"text\" && (\n <div className=\"sticky top-0 z-[1] flex items-center justify-between border-b border-border/40 bg-muted/90 px-2.5 py-1\">\n <span className=\"font-mono text-[10px] uppercase tracking-wide text-muted-foreground/80\">\n {lang}\n </span>\n </div>\n )}\n <HighlightedCodeBlock code={text} lang={lang} />\n </div>\n );\n}\n\nfunction ToolOutputPopover({\n open,\n onOpenChange,\n title,\n payload,\n children,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: string;\n payload: ToolDetailPayload;\n children: React.ReactNode;\n}) {\n const [copied, setCopied] = useState(false);\n const copyResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (copyResetRef.current) clearTimeout(copyResetRef.current);\n };\n }, []);\n\n const copyValue = useCallback(async () => {\n try {\n if (await writeClipboardText(payload.copyText)) {\n setCopied(true);\n if (copyResetRef.current) clearTimeout(copyResetRef.current);\n copyResetRef.current = setTimeout(() => setCopied(false), 1200);\n }\n } catch {\n // Clipboard failures should not interrupt chat rendering.\n }\n }, [payload.copyText]);\n\n return (\n <Popover open={open} onOpenChange={onOpenChange}>\n <PopoverTrigger asChild>{children}</PopoverTrigger>\n <PopoverContent\n align=\"start\"\n side=\"bottom\"\n sideOffset={6}\n collisionPadding={12}\n className=\"flex max-h-[min(calc(100vh-2rem),var(--radix-popover-content-available-height,75vh))] w-[min(calc(100vw-2rem),var(--radix-popover-content-available-width,760px),760px)] flex-col gap-0 overflow-hidden p-0\"\n >\n <div className=\"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3\">\n <div className=\"truncate text-sm font-medium\">{title}</div>\n <button\n type=\"button\"\n onClick={copyValue}\n className=\"inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground\"\n >\n {copied ? <IconCheck size={13} /> : <IconCopy size={13} />}\n {copied ? \"Copied\" : \"Copy\"}\n </button>\n </div>\n <div className=\"min-h-0 flex-1 overflow-hidden p-3\">\n <SimpleCodeViewer\n text={payload.text}\n lang={payload.lang}\n maxHeightClass=\"max-h-[min(70vh,calc(var(--radix-popover-content-available-height,75vh)-4.5rem))]\"\n />\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n\n// ─── Collapsible height animation ─────────────────────────────────────────────\n\nexport function AnimatedCollapse({\n open,\n children,\n}: {\n open: boolean;\n children: React.ReactNode;\n}) {\n const [mounted, setMounted] = useState(open);\n\n useLayoutEffect(() => {\n if (open) setMounted(true);\n }, [open]);\n\n const onTransitionEnd = useCallback(\n (event: React.TransitionEvent<HTMLDivElement>) => {\n if (event.propertyName !== \"grid-template-rows\" || open) return;\n setMounted(false);\n },\n [open],\n );\n\n if (!mounted) return null;\n\n return (\n <div\n className=\"agent-chat-collapse\"\n data-state={open ? \"open\" : \"closed\"}\n aria-hidden={!open}\n onTransitionEnd={onTransitionEnd}\n >\n <div className=\"agent-chat-collapse__content\">{children}</div>\n </div>\n );\n}\n\n// ─── Human-in-the-loop approval affordance ────────────────────────────────────\n\n/**\n * Inline Approve/Deny prompt rendered when a `needsApproval` action paused the\n * turn. Approve re-issues the turn with the call's `approvalKey`; Deny dismisses\n * the prompt locally (the action stays un-run).\n */\nfunction ApprovalAffordance({\n toolName,\n approval,\n}: {\n toolName: string;\n approval: { approvalKey: string; dismissed?: boolean };\n}) {\n const ctx = React.useContext(ApprovalContext);\n const [approved, setApproved] = useState(false);\n const [denied, setDenied] = useState(false);\n\n // Once approved, the turn is re-issued; collapse to a quiet note so the user\n // can't double-fire the approval.\n if (approved) {\n return (\n <div className=\"mt-1.5 text-xs text-muted-foreground\">\n Approved. Re-running {toolName}...\n </div>\n );\n }\n // Deny defaults to local-only (the action simply stays un-run). When the\n // host also provided `onDeny` (e.g. a Code session resolving its own\n // pending approval), it fires alongside the local state.\n if (denied) {\n return (\n <div className=\"mt-1.5 text-xs text-muted-foreground\">\n Denied. {toolName} did not run.\n </div>\n );\n }\n return (\n <div className=\"mt-1.5 flex items-center gap-2 rounded-md border border-border bg-muted/40 px-2.5 py-1.5\">\n <IconShieldCheck className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"mr-auto text-xs text-muted-foreground\">\n Approve to run {toolName}?\n </span>\n {ctx && (\n <button\n type=\"button\"\n onClick={() => {\n setApproved(true);\n ctx.onApprove(approval.approvalKey);\n }}\n className={cn(\n \"inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-medium transition-colors\",\n \"bg-foreground text-background hover:bg-foreground/90\",\n )}\n >\n <IconCheck className=\"h-3.5 w-3.5\" />\n Approve\n </button>\n )}\n {ctx?.onAlwaysAllow && (\n <button\n type=\"button\"\n onClick={() => {\n setApproved(true);\n ctx.onAlwaysAllow?.(approval.approvalKey);\n }}\n title=\"Approve and always allow this exact command\"\n className={cn(\n \"inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs font-medium transition-colors\",\n \"text-foreground hover:bg-muted\",\n )}\n >\n <IconShieldCheck className=\"h-3.5 w-3.5\" />\n Always allow\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => {\n setDenied(true);\n ctx?.onDeny?.(approval.approvalKey);\n }}\n className={cn(\n \"inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs font-medium transition-colors\",\n \"text-foreground hover:bg-muted\",\n )}\n >\n <IconX className=\"h-3.5 w-3.5\" />\n Deny\n </button>\n </div>\n );\n}\n\n// ─── ToolCallDisplay ──────────────────────────────────────────────────────────\n\nexport function ToolCallDisplay({\n toolName,\n argsText,\n args,\n result,\n mcpApp,\n chatUI,\n isRunning,\n structuredMeta,\n approval,\n repeatCount,\n}: {\n toolName: string;\n argsText?: string;\n args: Record<string, unknown>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n chatUI?: ActionChatUIConfig;\n isRunning: boolean;\n structuredMeta?: Record<string, unknown>;\n approval?: { approvalKey: string; dismissed?: boolean };\n repeatCount?: number;\n}) {\n // Delegate to bespoke cells when structured metadata is present.\n // These must be separate components so hook order in ToolCallDisplayGeneric\n // is always stable (no conditional hook calls).\n const toolKind = structuredMeta?.toolKind as string | undefined;\n const wrapToolDisplay = (children: React.ReactNode) => (\n <ToolLongRunningHintShell toolName={toolName} isRunning={isRunning}>\n {children}\n </ToolLongRunningHintShell>\n );\n if (toolKind === \"bash\") {\n return wrapToolDisplay(\n <BashCell\n meta={\n structuredMeta as unknown as Parameters<typeof BashCell>[0][\"meta\"]\n }\n output={result}\n isRunning={isRunning}\n />,\n );\n }\n if (toolKind === \"edit\") {\n return wrapToolDisplay(\n <EditCell\n meta={\n structuredMeta as unknown as Parameters<typeof EditCell>[0][\"meta\"]\n }\n isRunning={isRunning}\n />,\n );\n }\n if (toolKind === \"write\") {\n return wrapToolDisplay(\n <WriteCell\n meta={\n structuredMeta as unknown as Parameters<typeof WriteCell>[0][\"meta\"]\n }\n isRunning={isRunning}\n />,\n );\n }\n return wrapToolDisplay(\n <ToolCallDisplayGeneric\n toolName={toolName}\n argsText={argsText}\n args={args}\n result={result}\n mcpApp={mcpApp}\n chatUI={chatUI}\n isRunning={isRunning}\n approval={approval}\n repeatCount={repeatCount}\n />,\n );\n}\n\nfunction ToolCallDisplayGeneric({\n toolName,\n argsText,\n args,\n result,\n mcpApp,\n chatUI,\n isRunning,\n approval,\n repeatCount,\n}: {\n toolName: string;\n argsText?: string;\n args: Record<string, unknown>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n chatUI?: ActionChatUIConfig;\n isRunning: boolean;\n approval?: { approvalKey: string; dismissed?: boolean };\n repeatCount?: number;\n}) {\n const streamRef = useRef<HTMLDivElement>(null);\n\n const isAgentCall = toolName.startsWith(\"agent:\");\n const [expanded, setExpanded] = useState(isAgentCall);\n const [outputOpen, setOutputOpen] = useState(false);\n const agentName = isAgentCall ? toolName.slice(6) : null;\n const isAgentError = isAgentCall && result === \"Error calling agent\";\n const agentStreamText = isAgentCall ? (argsText ?? \"\") : \"\";\n const hasStreamText = agentStreamText.length > 0;\n const hasArgs = !isAgentCall && Object.keys(args).length > 0;\n\n // NOTE: All hooks must be above any conditional returns\n useEffect(() => {\n if (isAgentCall && isRunning && streamRef.current) {\n streamRef.current.scrollTop = streamRef.current.scrollHeight;\n }\n }, [agentStreamText, isAgentCall, isRunning]);\n\n // Render connect-builder as ConnectBuilderCard once the result is available\n if (toolName === \"connect-builder\" && result) {\n try {\n const parsed = JSON.parse(result);\n if (parsed?.kind === \"connect-builder-card\") {\n return (\n <ConnectBuilderCard\n configured={!!parsed.configured}\n builderEnabled={parsed.builderEnabled !== false}\n // Ignore saved cliAuthUrl values from older tool results. They\n // contain signed callback state and can expire while a chat sits\n // open; the card's hook fetches a fresh signed URL on mount/click.\n connectUrl={parsed.connectUrl || \"\"}\n orgName={parsed.orgName ?? null}\n prompt={typeof parsed.prompt === \"string\" ? parsed.prompt : \"\"}\n />\n );\n }\n } catch {\n // fall through to default pill rendering\n }\n }\n\n // Render agent-teams spawn as AgentTaskCard once the result is available\n if (\n toolName === \"agent-teams\" &&\n (args as Record<string, string>)?.action === \"spawn\" &&\n result\n ) {\n try {\n const parsed = JSON.parse(result);\n if (parsed.taskId && parsed.threadId) {\n return (\n <AgentTaskCard\n taskId={parsed.taskId}\n threadId={parsed.threadId}\n description={\n parsed.description ||\n (args as Record<string, string>)?.task ||\n \"Sub-agent task\"\n }\n onOpen={(tid) => {\n window.dispatchEvent(\n new CustomEvent(\"agent-task-open\", {\n detail: {\n threadId: tid,\n description:\n parsed.description ||\n (args as Record<string, string>)?.task ||\n \"\",\n name: parsed.name || \"\",\n },\n }),\n );\n }}\n />\n );\n }\n } catch {\n // Fall through to default pill rendering\n }\n }\n\n const parsedResult = result ? parseJsonText(result) : null;\n const nativeToolContext = {\n toolName,\n args,\n resultText: result,\n resultJson: parsedResult,\n isRunning,\n chatUI,\n };\n const skipRegistryRenderer =\n !isAgentCall && isBuiltinDataWidgetActionRenderer(nativeToolContext);\n const NativeToolRenderer = isAgentCall\n ? null\n : (resolveBuiltinActionChatRenderer(nativeToolContext) ??\n (skipRegistryRenderer ? null : resolveToolRenderer(nativeToolContext)) ??\n resolveBuiltinFallbackToolRenderer(nativeToolContext));\n if (NativeToolRenderer) {\n return <NativeToolRenderer context={nativeToolContext} />;\n }\n\n const inputPayload = hasArgs ? toolInputPayload(toolName, args) : null;\n const resultPayload = toolResultPayload(result);\n\n const displayName = isAgentCall\n ? isRunning\n ? `Asking ${agentName}...`\n : isAgentError\n ? `Error asking ${agentName}`\n : `Asked ${agentName}`\n : humanizeToolName(toolName);\n\n const canExpand = isAgentCall\n ? hasStreamText\n : hasArgs || result !== undefined;\n const isExpanded = isAgentCall ? hasStreamText && expanded : expanded;\n const ToolIcon = resolveToolIcon(toolName);\n const outputTitle = `Raw ${toolName} tool call output`;\n\n return (\n <div className=\"group/tool my-0.5 w-full overflow-hidden\">\n {mcpApp && <McpAppRenderer app={mcpApp} className=\"mb-1.5\" />}\n <button\n type=\"button\"\n onClick={() => canExpand && setExpanded(!isExpanded)}\n aria-expanded={canExpand ? isExpanded : undefined}\n className={cn(\n \"flex w-full items-center gap-1.5 rounded-md py-0.5 text-left text-[13px] text-muted-foreground transition-colors\",\n canExpand && \"hover:text-foreground\",\n isRunning && \"text-muted-foreground\",\n )}\n >\n <span className=\"relative flex size-4 shrink-0 items-center justify-center\">\n {isRunning ? (\n <IconLoader2 className=\"size-3.5 animate-spin\" />\n ) : isAgentError ? (\n <IconCircleX className=\"size-3.5 text-destructive\" />\n ) : (\n <>\n <ToolIcon\n className={cn(\n \"size-3.5 transition-opacity\",\n canExpand && \"group-hover/tool:opacity-0\",\n )}\n />\n {canExpand && (\n <IconChevronRight\n className={cn(\n \"absolute size-3.5 opacity-0 transition-[opacity,transform] group-hover/tool:opacity-100\",\n isExpanded && \"rotate-90\",\n )}\n />\n )}\n </>\n )}\n </span>\n <span className=\"min-w-0 truncate font-normal\">{displayName}</span>\n {repeatCount && repeatCount > 1 && (\n <span\n className=\"shrink-0 rounded border border-border/60 px-1.5 py-0.5 text-[10px] leading-none text-muted-foreground\"\n title={`Repeated ${repeatCount} times`}\n >\n {repeatCount}x\n </span>\n )}\n </button>\n <AnimatedCollapse open={isExpanded && isAgentCall && hasStreamText}>\n <div\n ref={streamRef}\n className=\"mt-1 rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground break-words max-h-48 overflow-y-auto agent-markdown prose prose-sm prose-invert max-w-none\"\n >\n {markdownModule?.default && remarkGfmFn ? (\n <markdownModule.default\n remarkPlugins={[remarkGfmFn]}\n components={markdownComponents}\n urlTransform={markdownUrlTransform}\n >\n {agentStreamText}\n </markdownModule.default>\n ) : (\n <span style={{ whiteSpace: \"pre-wrap\" }}>{agentStreamText}</span>\n )}\n </div>\n </AnimatedCollapse>\n <AnimatedCollapse\n open={isExpanded && !isAgentCall && (hasArgs || result !== undefined)}\n >\n <div className=\"mt-1 space-y-2 pl-5\">\n {inputPayload && (\n <SimpleCodeViewer\n text={inputPayload.text}\n lang={inputPayload.lang}\n />\n )}\n {resultPayload && (\n <ToolOutputPopover\n open={outputOpen}\n onOpenChange={setOutputOpen}\n title={outputTitle}\n payload={resultPayload}\n >\n <button\n type=\"button\"\n aria-label={`View ${toolName} output`}\n className=\"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground\"\n >\n <IconCode className=\"size-3.5\" />\n </button>\n </ToolOutputPopover>\n )}\n </div>\n </AnimatedCollapse>\n {approval && (\n <ApprovalAffordance toolName={toolName} approval={approval} />\n )}\n </div>\n );\n}\n\n// ─── ToolCallFallback ──────────────────────────────────────────────────────────\n\nexport function ToolCallFallback({\n toolName,\n args,\n argsText,\n result,\n ...rest\n}: ToolCallMessagePartProps & {\n mcpApp?: AgentMcpAppPayload;\n chatUI?: ActionChatUIConfig;\n structuredMeta?: Record<string, unknown>;\n activity?: boolean;\n approval?: { approvalKey: string; dismissed?: boolean };\n repeatCount?: number;\n}) {\n const chatRunning = React.useContext(ChatRunningContext);\n const isRunning =\n result === undefined && (chatRunning || rest.activity === true);\n return (\n <ToolCallDisplay\n toolName={toolName}\n args={args as Record<string, unknown>}\n argsText={argsText}\n result={\n typeof result === \"string\"\n ? result\n : result !== undefined\n ? JSON.stringify(result)\n : undefined\n }\n mcpApp={rest.mcpApp}\n chatUI={rest.chatUI}\n structuredMeta={rest.structuredMeta}\n isRunning={isRunning}\n approval={rest.approval}\n repeatCount={rest.repeatCount}\n />\n );\n}\n\n// ─── ReconnectStreamMessage ────────────────────────────────────────────────────\n// Renders the agent's in-progress response during reconnection (outside\n// assistant-ui's runtime). Uses the same visual styling as normal messages.\n\nexport function ReconnectStreamMessage({\n content,\n}: {\n content: ContentPart[];\n}) {\n const chatRunning = React.useContext(ChatRunningContext);\n const latestReasoningPartIndex = content.reduce(\n (latestIndex, part, index) =>\n part.type === \"reasoning\" ? index : latestIndex,\n -1,\n );\n const streamingTextPartIndex =\n content.at(-1)?.type === \"text\" ? content.length - 1 : -1;\n const streamingReasoningPartIndex =\n content.at(-1)?.type === \"reasoning\" ? content.length - 1 : -1;\n\n return (\n <div className=\"flex justify-start\">\n <div className=\"w-full max-w-[95%] text-sm leading-relaxed text-foreground space-y-1\">\n {content.map((part, i) => {\n if (part.type === \"text\") {\n const partStreaming = chatRunning && i === streamingTextPartIndex;\n return (\n <SmoothMarkdownText\n key={`reconnect-text-${i}`}\n text={part.text}\n streaming={partStreaming}\n resetKey={`reconnect-text-${i}`}\n statusType={partStreaming ? \"running\" : \"complete\"}\n />\n );\n }\n if (part.type === \"reasoning\") {\n return (\n <ReasoningCell\n key={`reconnect-reasoning-${i}`}\n text={part.text}\n isStreaming={chatRunning && i === streamingReasoningPartIndex}\n defaultOpen={i === latestReasoningPartIndex}\n collapseWhenReplaced={i < latestReasoningPartIndex}\n />\n );\n }\n if (part.type === \"tool-call\") {\n return (\n <ToolCallDisplay\n key={`reconnect-tool-${i}`}\n toolName={part.toolName}\n argsText={part.argsText}\n args={part.args}\n result={part.result}\n mcpApp={part.mcpApp}\n chatUI={part.chatUI}\n structuredMeta={part.structuredMeta}\n isRunning={\n part.result === undefined &&\n (chatRunning || part.activity === true)\n }\n approval={part.approval}\n repeatCount={part.repeatCount}\n />\n );\n }\n return null;\n })}\n </div>\n </div>\n );\n}\n\n// ─── Reasoning / Thinking cell ────────────────────────────────────────────────\n\n/**\n * Completed reasoning and tool calls share one outer \"Worked for…\"\n * disclosure. Reasoning cells inside it render their prose directly so\n * opening that summary never reveals a redundant second disclosure.\n */\nconst WorkSummaryContentContext = React.createContext(false);\n\nexport function ReasoningCell({\n text,\n isStreaming = false,\n defaultOpen,\n autoCollapse = false,\n collapseWhenReplaced = false,\n durationMs,\n}: {\n text: string;\n isStreaming?: boolean;\n defaultOpen?: boolean;\n /** Animate closed when a live reasoning segment finishes during a run. */\n autoCollapse?: boolean;\n /** Animate closed when a newer reasoning segment replaces this one. */\n collapseWhenReplaced?: boolean;\n /**\n * Elapsed thinking time in ms, once known. Only meaningful once streaming\n * has finished — callers that track live timing (see ReasoningMessagePart)\n * pass this so the label can read \"Thought for Xs\" instead of \"Thought\".\n * Historical messages with no live timing simply omit it.\n */\n durationMs?: number | null;\n}) {\n const embeddedInWorkSummary = React.useContext(WorkSummaryContentContext);\n const [open, setOpen] = useState(defaultOpen ?? true);\n const wasStreamingRef = useRef(isStreaming);\n const wasReplacedRef = useRef(collapseWhenReplaced);\n const trimmed = text.trim();\n\n useEffect(() => {\n if (autoCollapse && wasStreamingRef.current && !isStreaming) {\n setOpen(false);\n }\n wasStreamingRef.current = isStreaming;\n }, [autoCollapse, isStreaming]);\n\n useEffect(() => {\n if (collapseWhenReplaced && !wasReplacedRef.current) {\n setOpen(false);\n }\n wasReplacedRef.current = collapseWhenReplaced;\n }, [collapseWhenReplaced]);\n\n if (!trimmed && !isStreaming) return null;\n\n if (embeddedInWorkSummary) {\n return (\n <div className=\"pb-1 pl-5 text-[13px] leading-relaxed text-muted-foreground whitespace-pre-wrap\">\n {trimmed || (isStreaming ? \"…\" : \"\")}\n </div>\n );\n }\n\n const label = isStreaming\n ? \"Thinking\"\n : durationMs != null\n ? `Thought for ${formatWorkedDuration(durationMs)}`\n : \"Thought\";\n // Only clamp to a scroll-free \"tail\" view while actively streaming and\n // expanded — once the run finishes the full text is shown, unclamped.\n const showTail = isStreaming && open;\n\n return (\n <div className=\"my-0.5 w-full\">\n <button\n type=\"button\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n className=\"flex items-center gap-1.5 py-0.5 text-[13px] text-muted-foreground transition-colors hover:text-foreground\"\n >\n <IconChevronRight\n className={cn(\n \"size-3.5 shrink-0 transition-transform\",\n open && \"rotate-90\",\n )}\n />\n {isStreaming ? (\n <span className=\"agent-thinking-indicator__text\">{label}</span>\n ) : (\n <span>{label}</span>\n )}\n </button>\n <AnimatedCollapse open={open}>\n <div className={cn(\"pl-5 pb-1\", showTail && \"reasoning-cell-tail\")}>\n <div className=\"text-[13px] leading-relaxed text-muted-foreground whitespace-pre-wrap\">\n {trimmed || (isStreaming ? \"…\" : \"\")}\n </div>\n </div>\n </AnimatedCollapse>\n </div>\n );\n}\n\n// ─── Worked-for duration helpers ──────────────────────────────────────────────\n\nexport function formatWorkedDuration(ms: number): string {\n const totalSeconds = Math.max(0, Math.round(ms / 1000));\n if (totalSeconds < 60) {\n return totalSeconds <= 1 ? \"1s\" : `${totalSeconds}s`;\n }\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n if (minutes < 60) {\n if (seconds === 0) return `${minutes}m`;\n return `${minutes}m ${seconds}s`;\n }\n const hours = Math.floor(minutes / 60);\n const remMinutes = minutes % 60;\n if (remMinutes === 0) return `${hours}h`;\n return `${hours}h ${remMinutes}m`;\n}\n\nexport function WorkedForSummary({\n durationMs,\n autoCollapse = false,\n children,\n}: {\n durationMs?: number | null;\n /** When true, close the summary after a run has completed. */\n autoCollapse?: boolean;\n children: React.ReactNode;\n}) {\n // Start closed so a remounted completed message never flashes its work\n // details open while auto-collapse settles. If the summary was already\n // open when autoCollapse changes, AnimatedCollapse still animates it shut.\n const [open, setOpen] = useState(false);\n\n useEffect(() => {\n if (autoCollapse) setOpen(false);\n }, [autoCollapse]);\n\n const label =\n durationMs != null && durationMs >= 1000\n ? `Worked for ${formatWorkedDuration(durationMs)}`\n : \"Worked\";\n\n return (\n <div className=\"my-1 w-full\">\n <button\n type=\"button\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n className=\"flex items-center gap-1.5 py-0.5 text-[13px] text-muted-foreground transition-colors hover:text-foreground\"\n >\n <span>{label}</span>\n <IconChevronRight\n className={cn(\n \"size-3.5 shrink-0 transition-transform\",\n open && \"rotate-90\",\n )}\n />\n </button>\n <AnimatedCollapse open={open}>\n <WorkSummaryContentContext.Provider value>\n <div className=\"pt-1\">{children}</div>\n </WorkSummaryContentContext.Provider>\n </AnimatedCollapse>\n </div>\n );\n}\n\n// ─── Re-export for AssistantMessage ───────────────────────────────────────────\n// AssistantMessage in AssistantChat.tsx uses FilesChangedSummary directly, so\n// re-export it so AssistantChat.tsx can import from one place.\nexport { FilesChangedSummary };\n"]}
|
|
@@ -62,11 +62,11 @@ export declare const postAwareness: import("h3").EventHandlerWithFetch<import("h
|
|
|
62
62
|
error: string;
|
|
63
63
|
states?: undefined;
|
|
64
64
|
} | {
|
|
65
|
-
error?: undefined;
|
|
66
65
|
states: {
|
|
67
66
|
clientId: number;
|
|
68
67
|
state: string;
|
|
69
68
|
}[];
|
|
69
|
+
error?: undefined;
|
|
70
70
|
}>>;
|
|
71
71
|
/**
|
|
72
72
|
* GET /_agent-native/collab/:docId/users
|
|
@@ -77,10 +77,10 @@ export declare const getActiveUsers: import("h3").EventHandlerWithFetch<import("
|
|
|
77
77
|
error: string;
|
|
78
78
|
users?: undefined;
|
|
79
79
|
} | {
|
|
80
|
-
error?: undefined;
|
|
81
80
|
users: {
|
|
82
81
|
clientId: number;
|
|
83
82
|
lastSeen: number;
|
|
84
83
|
}[];
|
|
84
|
+
error?: undefined;
|
|
85
85
|
}>>;
|
|
86
86
|
//# sourceMappingURL=awareness.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"awareness.d.ts","sourceRoot":"","sources":["../../src/collab/awareness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAgB3C,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;CAClB;AAOD,eAAO,MAAM,sBAAsB,EAAG,kBAA2B,CAAC;AAElE,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,WAAW,CAAC;IACpB,IAAI,EAAE,kBAAkB,CAAC;IACzB,KAAK,EAAE,MAAM,CA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CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,EAClD,KAAK,CAAC,EAAE,cAAc,GACrB,IAAI,CAgBN;AAoBD,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,SAAS,GAAE,MAAmB,GAC7B,IAAI,CAON;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE1E;AAiBD,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAO1E;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,GAAG,IAAI,CAOnE;AAkCD;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa;;;;;kBAwDa,MAAM;eAAS,MAAM;;;GAoB1D,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,cAAc;;;;;kBAYM,MAAM;kBAAY,MAAM;;;GAMvD,CAAC"}
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
* Body: { json: any, fieldName?: string, type?: "map"|"array", requestSource?: string }
|
|
14
14
|
*/
|
|
15
15
|
export declare const postCollabJson: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
|
|
16
|
-
error: string;
|
|
17
16
|
ok?: undefined;
|
|
17
|
+
error: string;
|
|
18
18
|
} | {
|
|
19
19
|
error?: undefined;
|
|
20
20
|
ok: boolean;
|
package/dist/mcp/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAalC,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,SAA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B,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,SAAS,EACjB,WAAW,SAAmB,GAC7B,IAAI,CAiBN"}
|
package/dist/mcp/server.js
CHANGED
|
@@ -223,8 +223,17 @@ export async function handleMcpRequest(event, config) {
|
|
|
223
223
|
// must fail closed rather than trust a spoofable owner-email header that
|
|
224
224
|
// `fullSurface` would otherwise escalate to the full mutating surface.
|
|
225
225
|
const requestMeta = deriveRequestMeta(event);
|
|
226
|
+
const hasLocalOwnerHint = Boolean(ownerEmailHeader?.trim());
|
|
226
227
|
const authResult = await verifyAuth(authHeader, ownerEmailHeader, {
|
|
227
|
-
|
|
228
|
+
// A bare localhost URL is still a protected MCP resource. This lets
|
|
229
|
+
// OAuth-native hosts (Kiro, Claude Code, etc.) receive the standard 401
|
|
230
|
+
// challenge and open browser approval instead of silently getting the
|
|
231
|
+
// sparse anonymous dev surface. The stdio proxy remains zero-config for
|
|
232
|
+
// local installs because it forwards an owner hint; an explicit opt-in is
|
|
233
|
+
// available for local diagnostics.
|
|
234
|
+
allowDevOpen: isLoopbackRequest(event) &&
|
|
235
|
+
isLoopbackOrigin(requestMeta.origin) &&
|
|
236
|
+
(hasLocalOwnerHint || process.env.AGENT_NATIVE_MCP_DEV_OPEN === "1"),
|
|
228
237
|
resourceUrl: getMcpOAuthAudiences(event),
|
|
229
238
|
});
|
|
230
239
|
if (!authResult.authed) {
|
package/dist/mcp/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAw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,CACrD,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,QAAQ,CACtB,QAAa,EACb,MAAiB,EACjB,WAAW,GAAG,gBAAgB;IAE9B,MAAM,UAAU,GACd,WAAW,KAAK,gBAAgB;QAC9B,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC;QACzB,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC;IAC1C,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjD,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;IAEH,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CAChJ,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\n\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport {\n buildMcpOAuthChallenge,\n getMcpOAuthAudiences,\n getMcpOAuthIssuer,\n getMcpOAuthProtectedResourceMetadataUrl,\n getMcpOAuthResource,\n} from \"./oauth-route.js\";\nimport {\n MCP_PUBLIC_ROUTE_PREFIX,\n MCP_ROUTE_PREFIXES,\n joinMcpRoute,\n} from \"./route-paths.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const inlineAppsHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-inline-apps\",\n )?.toLowerCase();\n const inlineAppsRequested =\n inlineAppsHeader === \"1\" ||\n inlineAppsHeader === \"true\" ||\n inlineAppsHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n ...(inlineAppsRequested ? { inlineMcpApps: true } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}${MCP_PUBLIC_ROUTE_PREFIX}`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n/**\n * Build an actionable JSON body for the 401 response. OAuth-capable clients\n * follow the `WWW-Authenticate` header automatically, but the JSON body is what\n * a human or a coding agent reads when a tool call comes back unauthorized — so\n * spell out the exact remediation: the `agent-native connect <url>` command and\n * the authorize/metadata URL. Keeping the legacy `error: \"Unauthorized\"` field\n * means existing clients that only check that field still work.\n */\nfunction buildUnauthorizedBody(event: H3Event): {\n error: string;\n message: string;\n authenticate: {\n command?: string;\n firstTimeCommand?: string;\n authorizeUrl?: string;\n resourceMetadataUrl?: string;\n mcpUrl?: string;\n };\n} {\n const issuer = getMcpOAuthIssuer(event);\n const mcpUrl = getMcpOAuthResource(event);\n const resourceMetadataUrl = getMcpOAuthProtectedResourceMetadataUrl(event);\n const command = issuer\n ? `npx -y @agent-native/core@latest reconnect ${issuer}`\n : undefined;\n const firstTimeCommand = issuer\n ? `npx @agent-native/core@latest connect ${issuer}`\n : undefined;\n const authorizeUrl = issuer\n ? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/authorize`\n : undefined;\n const message = command\n ? `Authentication required. Run \\`${command}\\` to re-authenticate this ` +\n `MCP connector without reinstalling it (or, in a Claude Code host, ` +\n `run /mcp and choose Authenticate), then retry. For first-time ` +\n `setup, run \\`${firstTimeCommand}\\`.`\n : \"Authentication required. Authenticate the MCP connector in your host, \" +\n \"then retry.\";\n return {\n error: \"Unauthorized\",\n message,\n authenticate: {\n ...(command ? { command } : {}),\n ...(firstTimeCommand ? { firstTimeCommand } : {}),\n ...(authorizeUrl ? { authorizeUrl } : {}),\n ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),\n ...(mcpUrl ? { mcpUrl } : {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<\n Response | string | { error: string } | Record<string, unknown> | undefined\n> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthAudiences(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return buildUnauthorizedBody(event);\n }\n\n // Stateless mode: only POST is meaningful. A stateless, per-request transport\n // on serverless cannot keep the standalone GET SSE stream (server->client\n // channel) alive across invocations — once the function returns and freezes,\n // that stream dies and the client reports \"session expired\" / \"not\n // connected\". The spec lets a server that offers no GET stream answer 405, so\n // the client falls back to plain POST request/response. Reject GET here\n // instead of letting the SDK open a doomed stream.\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Optional diagnostics for host capability negotiation. Keep disabled by\n // default because initialize payloads can include client-specific metadata.\n if (process.env.MCP_DEBUG_INIT && body) {\n const msgs = Array.isArray(body) ? body : [body];\n const init = msgs.find(\n (m): m is { params?: { capabilities?: unknown; clientInfo?: unknown } } =>\n typeof m === \"object\" &&\n m !== null &&\n (m as { method?: unknown }).method === \"initialize\",\n );\n if (init) {\n console.error(\n \"[MCP_DEBUG_INIT] clientInfo=\",\n JSON.stringify(init.params?.clientInfo),\n \"capabilities=\",\n JSON.stringify(init.params?.capabilities),\n );\n }\n }\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n inlineMcpApps:\n requestMeta.inlineMcpApps === true &&\n authResult.identity?.firstPartyMcp === true\n ? true\n : undefined,\n // When the caller minted their token with --full-catalog (catalog_scope:\n // \"full\" JWT claim), bypass the connector-catalog tier filter.\n ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n // Return JSON request/response instead of SSE. A stateless serverless\n // instance can freeze right after returning a streaming Response, before\n // the deferred SSE result event is flushed — the client then never gets\n // the tools/call result and reports \"session expired\". JSON mode awaits\n // the result inside the request lifecycle and returns it as one body.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n // JSON request/response (not SSE) — see the Node fast-path note above.\n // This is the serverless-safe framing: the result is computed and returned\n // within the request, never pushed onto a stream after the instance froze.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoints: `/mcp` (public) and `/_agent-native/mcp` (compatibility).\n * A custom route prefix only mounts that custom endpoint.\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions, JSON\n * request/response (no SSE), and no standalone GET stream, so it survives\n * serverless instances that freeze between invocations (SSE framing there\n * drops the result and clients report \"session expired\"). Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n const routePaths =\n routePrefix === \"/_agent-native\"\n ? [...MCP_ROUTE_PREFIXES]\n : [joinMcpRoute(routePrefix, \"/mcp\")];\n const handler = defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n });\n\n for (const routePath of routePaths) {\n getH3App(nitroApp).use(routePath, handler);\n }\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePaths.join(\" and \")} (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GAInB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,uCAAuC,EACvC,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,GACb,MAAM,kBAAkB,CAAC;AAE1B,6EAA6E;AAC7E,4EAA4E;AAC5E,yDAAyD;AACzD,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AAGF,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,KAAc;IAInC,MAAM,CAAC,GAAG,KAAY,CAAC;IACvB,MAAM,OAAO,GAA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kB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjD,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;IAEH,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CAChJ,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\n\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport {\n buildMcpOAuthChallenge,\n getMcpOAuthAudiences,\n getMcpOAuthIssuer,\n getMcpOAuthProtectedResourceMetadataUrl,\n getMcpOAuthResource,\n} from \"./oauth-route.js\";\nimport {\n MCP_PUBLIC_ROUTE_PREFIX,\n MCP_ROUTE_PREFIXES,\n joinMcpRoute,\n} from \"./route-paths.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const inlineAppsHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-inline-apps\",\n )?.toLowerCase();\n const inlineAppsRequested =\n inlineAppsHeader === \"1\" ||\n inlineAppsHeader === \"true\" ||\n inlineAppsHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n ...(inlineAppsRequested ? { inlineMcpApps: true } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}${MCP_PUBLIC_ROUTE_PREFIX}`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n/**\n * Build an actionable JSON body for the 401 response. OAuth-capable clients\n * follow the `WWW-Authenticate` header automatically, but the JSON body is what\n * a human or a coding agent reads when a tool call comes back unauthorized — so\n * spell out the exact remediation: the `agent-native connect <url>` command and\n * the authorize/metadata URL. Keeping the legacy `error: \"Unauthorized\"` field\n * means existing clients that only check that field still work.\n */\nfunction buildUnauthorizedBody(event: H3Event): {\n error: string;\n message: string;\n authenticate: {\n command?: string;\n firstTimeCommand?: string;\n authorizeUrl?: string;\n resourceMetadataUrl?: string;\n mcpUrl?: string;\n };\n} {\n const issuer = getMcpOAuthIssuer(event);\n const mcpUrl = getMcpOAuthResource(event);\n const resourceMetadataUrl = getMcpOAuthProtectedResourceMetadataUrl(event);\n const command = issuer\n ? `npx -y @agent-native/core@latest reconnect ${issuer}`\n : undefined;\n const firstTimeCommand = issuer\n ? `npx @agent-native/core@latest connect ${issuer}`\n : undefined;\n const authorizeUrl = issuer\n ? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/authorize`\n : undefined;\n const message = command\n ? `Authentication required. Run \\`${command}\\` to re-authenticate this ` +\n `MCP connector without reinstalling it (or, in a Claude Code host, ` +\n `run /mcp and choose Authenticate), then retry. For first-time ` +\n `setup, run \\`${firstTimeCommand}\\`.`\n : \"Authentication required. Authenticate the MCP connector in your host, \" +\n \"then retry.\";\n return {\n error: \"Unauthorized\",\n message,\n authenticate: {\n ...(command ? { command } : {}),\n ...(firstTimeCommand ? { firstTimeCommand } : {}),\n ...(authorizeUrl ? { authorizeUrl } : {}),\n ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),\n ...(mcpUrl ? { mcpUrl } : {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<\n Response | string | { error: string } | Record<string, unknown> | undefined\n> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const hasLocalOwnerHint = Boolean(ownerEmailHeader?.trim());\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n // A bare localhost URL is still a protected MCP resource. This lets\n // OAuth-native hosts (Kiro, Claude Code, etc.) receive the standard 401\n // challenge and open browser approval instead of silently getting the\n // sparse anonymous dev surface. The stdio proxy remains zero-config for\n // local installs because it forwards an owner hint; an explicit opt-in is\n // available for local diagnostics.\n allowDevOpen:\n isLoopbackRequest(event) &&\n isLoopbackOrigin(requestMeta.origin) &&\n (hasLocalOwnerHint || process.env.AGENT_NATIVE_MCP_DEV_OPEN === \"1\"),\n resourceUrl: getMcpOAuthAudiences(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return buildUnauthorizedBody(event);\n }\n\n // Stateless mode: only POST is meaningful. A stateless, per-request transport\n // on serverless cannot keep the standalone GET SSE stream (server->client\n // channel) alive across invocations — once the function returns and freezes,\n // that stream dies and the client reports \"session expired\" / \"not\n // connected\". The spec lets a server that offers no GET stream answer 405, so\n // the client falls back to plain POST request/response. Reject GET here\n // instead of letting the SDK open a doomed stream.\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Optional diagnostics for host capability negotiation. Keep disabled by\n // default because initialize payloads can include client-specific metadata.\n if (process.env.MCP_DEBUG_INIT && body) {\n const msgs = Array.isArray(body) ? body : [body];\n const init = msgs.find(\n (m): m is { params?: { capabilities?: unknown; clientInfo?: unknown } } =>\n typeof m === \"object\" &&\n m !== null &&\n (m as { method?: unknown }).method === \"initialize\",\n );\n if (init) {\n console.error(\n \"[MCP_DEBUG_INIT] clientInfo=\",\n JSON.stringify(init.params?.clientInfo),\n \"capabilities=\",\n JSON.stringify(init.params?.capabilities),\n );\n }\n }\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n inlineMcpApps:\n requestMeta.inlineMcpApps === true &&\n authResult.identity?.firstPartyMcp === true\n ? true\n : undefined,\n // When the caller minted their token with --full-catalog (catalog_scope:\n // \"full\" JWT claim), bypass the connector-catalog tier filter.\n ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n // Return JSON request/response instead of SSE. A stateless serverless\n // instance can freeze right after returning a streaming Response, before\n // the deferred SSE result event is flushed — the client then never gets\n // the tools/call result and reports \"session expired\". JSON mode awaits\n // the result inside the request lifecycle and returns it as one body.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n // JSON request/response (not SSE) — see the Node fast-path note above.\n // This is the serverless-safe framing: the result is computed and returned\n // within the request, never pushed onto a stream after the instance froze.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoints: `/mcp` (public) and `/_agent-native/mcp` (compatibility).\n * A custom route prefix only mounts that custom endpoint.\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions, JSON\n * request/response (no SSE), and no standalone GET stream, so it survives\n * serverless instances that freeze between invocations (SSE framing there\n * drops the result and clients report \"session expired\"). Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n const routePaths =\n routePrefix === \"/_agent-native\"\n ? [...MCP_ROUTE_PREFIXES]\n : [joinMcpRoute(routePrefix, \"/mcp\")];\n const handler = defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n });\n\n for (const routePath of routePaths) {\n getH3App(nitroApp).use(routePath, handler);\n }\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePaths.join(\" and \")} (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
|
@@ -52,8 +52,8 @@ export declare function handleDeleteResource(event: any): Promise<{
|
|
|
52
52
|
error: string;
|
|
53
53
|
ok?: undefined;
|
|
54
54
|
} | {
|
|
55
|
-
ok: boolean;
|
|
56
55
|
error?: undefined;
|
|
56
|
+
ok: boolean;
|
|
57
57
|
}>;
|
|
58
58
|
/** POST /_agent-native/resources/upload — upload a file as a resource */
|
|
59
59
|
export declare function handleUploadResource(event: any): Promise<import("./store.js").Resource | {
|
|
@@ -74,10 +74,10 @@ export declare function handleUploadResource(event: any): Promise<import("./stor
|
|
|
74
74
|
runId: string | null;
|
|
75
75
|
expiresAt: number | null;
|
|
76
76
|
metadata: string | null;
|
|
77
|
+
error?: undefined;
|
|
77
78
|
url: string;
|
|
78
79
|
provider: string;
|
|
79
80
|
storageSetupRequired?: undefined;
|
|
80
|
-
error?: undefined;
|
|
81
81
|
} | {
|
|
82
82
|
error: string;
|
|
83
83
|
storageSetupRequired: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-prompts.d.ts","sourceRoot":"","sources":["../../../src/server/agent-chat/framework-prompts.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,EAGL,KAAK,cAAc,EACpB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EACL,6BAA6B,EAE9B,MAAM,oBAAoB,CAAC;AAY5B;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,CAAC,EAAE,cAAc,EACzB,OAAO,C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C,CAUjB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EACrC,IAAI,GAAE,KAAK,GAAG,MAAe,EAC7B,gBAAgB,CAAC,EAAE,MAAM,EAAE,GAC1B,MAAM,CA6ER;AAoBD,wBAAgB,6BAA6B,CAC3C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACpC,MAAM,EAAE,CAEV;AAED,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACpC,MAAM,CAgCR;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAA;CAAE,CAAC,GACtE,OAAO,CAAC,IAAI,CAAC,CAqCf"}
|
|
@@ -22,9 +22,6 @@ const MAX_ACTION_SUMMARY_DESCRIPTION_CHARS = 140;
|
|
|
22
22
|
* prompt strings used at request time.
|
|
23
23
|
*/
|
|
24
24
|
export function buildFrameworkPrompts(examples, options) {
|
|
25
|
-
// Note: FIRST_SESSION_PERSONALIZATION is NOT appended here — it is injected
|
|
26
|
-
// at per-request prompt-assembly time only for new threads (no prior messages).
|
|
27
|
-
// This prevents the ~1.5KB block from appearing on every request forever.
|
|
28
25
|
const FRAMEWORK_CORE = buildFrameworkCore(examples, options);
|
|
29
26
|
const FRAMEWORK_CORE_COMPACT = buildFrameworkCoreCompact(examples, options);
|
|
30
27
|
const extensionToolsEnabled = options?.extensionTools !== false;
|