svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
- className
- )}
- {...props}
- />
- )
-}
-
-export {
- Avatar,
- AvatarImage,
- AvatarFallback,
- AvatarBadge,
- AvatarGroup,
- AvatarGroupCount,
-}
diff --git a/demo/chat-ui/src/components/ui/button.tsx b/demo/chat-ui/src/components/ui/button.tsx
deleted file mode 100644
index 4d38506c..00000000
--- a/demo/chat-ui/src/components/ui/button.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import * as React from "react"
-import { cva, type VariantProps } from "class-variance-authority"
-import { Slot } from "radix-ui"
-
-import { cn } from "@/lib/utils"
-
-const buttonVariants = cva(
- "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- {
- variants: {
- variant: {
- default: "bg-primary text-primary-foreground hover:bg-primary/90",
- destructive:
- "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
- outline:
- "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
- secondary:
- "bg-secondary text-secondary-foreground hover:bg-secondary/80",
- ghost:
- "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
- link: "text-primary underline-offset-4 hover:underline",
- },
- size: {
- default: "h-9 px-4 py-2 has-[>svg]:px-3",
- xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
- sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
- lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
- icon: "size-9",
- "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
- "icon-sm": "size-8",
- "icon-lg": "size-10",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
-
-function Button({
- className,
- variant = "default",
- size = "default",
- asChild = false,
- ...props
-}: React.ComponentProps<"button"> &
- VariantProps
& {
- asChild?: boolean
- }) {
- const Comp = asChild ? Slot.Root : "button"
-
- return (
-
- )
-}
-
-export { Button, buttonVariants }
diff --git a/demo/chat-ui/src/components/ui/collapsible.tsx b/demo/chat-ui/src/components/ui/collapsible.tsx
deleted file mode 100644
index 63fc8eff..00000000
--- a/demo/chat-ui/src/components/ui/collapsible.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { Collapsible as CollapsiblePrimitive } from "radix-ui"
-
-function Collapsible({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function CollapsibleTrigger({
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function CollapsibleContent({
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-export { Collapsible, CollapsibleTrigger, CollapsibleContent }
diff --git a/demo/chat-ui/src/components/ui/dialog.tsx b/demo/chat-ui/src/components/ui/dialog.tsx
deleted file mode 100644
index e5f0a96d..00000000
--- a/demo/chat-ui/src/components/ui/dialog.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import * as React from "react"
-import { XIcon } from "lucide-react"
-import { Dialog as DialogPrimitive } from "radix-ui"
-
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-
-function Dialog({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function DialogTrigger({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function DialogPortal({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function DialogClose({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function DialogOverlay({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function DialogContent({
- className,
- children,
- showCloseButton = true,
- ...props
-}: React.ComponentProps & {
- showCloseButton?: boolean
-}) {
- return (
-
-
-
- {children}
- {showCloseButton && (
-
-
- Close
-
- )}
-
-
- )
-}
-
-function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function DialogFooter({
- className,
- showCloseButton = false,
- children,
- ...props
-}: React.ComponentProps<"div"> & {
- showCloseButton?: boolean
-}) {
- return (
-
- {children}
- {showCloseButton && (
-
- Close
-
- )}
-
- )
-}
-
-function DialogTitle({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function DialogDescription({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-export {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogOverlay,
- DialogPortal,
- DialogTitle,
- DialogTrigger,
-}
diff --git a/demo/chat-ui/src/components/ui/input.tsx b/demo/chat-ui/src/components/ui/input.tsx
deleted file mode 100644
index f1124aea..00000000
--- a/demo/chat-ui/src/components/ui/input.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-
-function Input({ className, type, ...props }: React.ComponentProps<"input">) {
- return (
-
- )
-}
-
-export { Input }
diff --git a/demo/chat-ui/src/components/ui/separator.tsx b/demo/chat-ui/src/components/ui/separator.tsx
deleted file mode 100644
index db91e97a..00000000
--- a/demo/chat-ui/src/components/ui/separator.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import * as React from "react"
-import { Separator as SeparatorPrimitive } from "radix-ui"
-
-import { cn } from "@/lib/utils"
-
-function Separator({
- className,
- orientation = "horizontal",
- decorative = true,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-export { Separator }
diff --git a/demo/chat-ui/src/components/ui/sheet.tsx b/demo/chat-ui/src/components/ui/sheet.tsx
deleted file mode 100644
index cb53bb28..00000000
--- a/demo/chat-ui/src/components/ui/sheet.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-"use client"
-
-import * as React from "react"
-import { XIcon } from "lucide-react"
-import { Dialog as SheetPrimitive } from "radix-ui"
-
-import { cn } from "@/lib/utils"
-
-function Sheet({ ...props }: React.ComponentProps) {
- return
-}
-
-function SheetTrigger({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function SheetClose({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function SheetPortal({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function SheetOverlay({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function SheetContent({
- className,
- children,
- side = "right",
- showCloseButton = true,
- ...props
-}: React.ComponentProps & {
- side?: "top" | "right" | "bottom" | "left"
- showCloseButton?: boolean
-}) {
- return (
-
-
-
- {children}
- {showCloseButton && (
-
-
- Close
-
- )}
-
-
- )
-}
-
-function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SheetTitle({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function SheetDescription({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-export {
- Sheet,
- SheetTrigger,
- SheetClose,
- SheetContent,
- SheetHeader,
- SheetFooter,
- SheetTitle,
- SheetDescription,
-}
diff --git a/demo/chat-ui/src/components/ui/sidebar.tsx b/demo/chat-ui/src/components/ui/sidebar.tsx
deleted file mode 100644
index 35ec0ca6..00000000
--- a/demo/chat-ui/src/components/ui/sidebar.tsx
+++ /dev/null
@@ -1,724 +0,0 @@
-import * as React from "react"
-import { cva, type VariantProps } from "class-variance-authority"
-import { PanelLeftIcon } from "lucide-react"
-import { Slot } from "radix-ui"
-
-import { useIsMobile } from "@/hooks/use-mobile"
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Separator } from "@/components/ui/separator"
-import {
- Sheet,
- SheetContent,
- SheetDescription,
- SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet"
-import { Skeleton } from "@/components/ui/skeleton"
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip"
-
-const SIDEBAR_COOKIE_NAME = "sidebar_state"
-const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
-const SIDEBAR_WIDTH = "16rem"
-const SIDEBAR_WIDTH_MOBILE = "18rem"
-const SIDEBAR_WIDTH_ICON = "3rem"
-const SIDEBAR_KEYBOARD_SHORTCUT = "b"
-
-type SidebarContextProps = {
- state: "expanded" | "collapsed"
- open: boolean
- setOpen: (open: boolean) => void
- openMobile: boolean
- setOpenMobile: (open: boolean) => void
- isMobile: boolean
- toggleSidebar: () => void
-}
-
-const SidebarContext = React.createContext(null)
-
-function useSidebar() {
- const context = React.useContext(SidebarContext)
- if (!context) {
- throw new Error("useSidebar must be used within a SidebarProvider.")
- }
-
- return context
-}
-
-function SidebarProvider({
- defaultOpen = true,
- open: openProp,
- onOpenChange: setOpenProp,
- className,
- style,
- children,
- ...props
-}: React.ComponentProps<"div"> & {
- defaultOpen?: boolean
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}) {
- const isMobile = useIsMobile()
- const [openMobile, setOpenMobile] = React.useState(false)
-
- // This is the internal state of the sidebar.
- // We use openProp and setOpenProp for control from outside the component.
- const [_open, _setOpen] = React.useState(defaultOpen)
- const open = openProp ?? _open
- const setOpen = React.useCallback(
- (value: boolean | ((value: boolean) => boolean)) => {
- const openState = typeof value === "function" ? value(open) : value
- if (setOpenProp) {
- setOpenProp(openState)
- } else {
- _setOpen(openState)
- }
-
- // This sets the cookie to keep the sidebar state.
- document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
- },
- [setOpenProp, open]
- )
-
- // Helper to toggle the sidebar.
- const toggleSidebar = React.useCallback(() => {
- return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
- }, [isMobile, setOpen, setOpenMobile])
-
- // Adds a keyboard shortcut to toggle the sidebar.
- React.useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- if (
- event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
- (event.metaKey || event.ctrlKey)
- ) {
- event.preventDefault()
- toggleSidebar()
- }
- }
-
- window.addEventListener("keydown", handleKeyDown)
- return () => window.removeEventListener("keydown", handleKeyDown)
- }, [toggleSidebar])
-
- // We add a state so that we can do data-state="expanded" or "collapsed".
- // This makes it easier to style the sidebar with Tailwind classes.
- const state = open ? "expanded" : "collapsed"
-
- const contextValue = React.useMemo(
- () => ({
- state,
- open,
- setOpen,
- isMobile,
- openMobile,
- setOpenMobile,
- toggleSidebar,
- }),
- [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
- )
-
- return (
-
-
-
- {children}
-
-
-
- )
-}
-
-function Sidebar({
- side = "left",
- variant = "sidebar",
- collapsible = "offcanvas",
- className,
- children,
- ...props
-}: React.ComponentProps<"div"> & {
- side?: "left" | "right"
- variant?: "sidebar" | "floating" | "inset"
- collapsible?: "offcanvas" | "icon" | "none"
-}) {
- const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
-
- if (collapsible === "none") {
- return (
-
- {children}
-
- )
- }
-
- if (isMobile) {
- return (
-
-
-
- Sidebar
- Displays the mobile sidebar.
-
- {children}
-
-
- )
- }
-
- return (
-
- {/* This is what handles the sidebar gap on desktop */}
-
-
-
- )
-}
-
-function SidebarTrigger({
- className,
- onClick,
- ...props
-}: React.ComponentProps) {
- const { toggleSidebar } = useSidebar()
-
- return (
- {
- onClick?.(event)
- toggleSidebar()
- }}
- {...props}
- >
-
- Toggle Sidebar
-
- )
-}
-
-function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
- const { toggleSidebar } = useSidebar()
-
- return (
-
- )
-}
-
-function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
- return (
-
- )
-}
-
-function SidebarInput({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SidebarSeparator({
- className,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SidebarGroupLabel({
- className,
- asChild = false,
- ...props
-}: React.ComponentProps<"div"> & { asChild?: boolean }) {
- const Comp = asChild ? Slot.Root : "div"
-
- return (
- svg]:size-4 [&>svg]:shrink-0",
- "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
- className
- )}
- {...props}
- />
- )
-}
-
-function SidebarGroupAction({
- className,
- asChild = false,
- ...props
-}: React.ComponentProps<"button"> & { asChild?: boolean }) {
- const Comp = asChild ? Slot.Root : "button"
-
- return (
- svg]:size-4 [&>svg]:shrink-0",
- // Increases the hit area of the button on mobile.
- "after:absolute after:-inset-2 md:after:hidden",
- "group-data-[collapsible=icon]:hidden",
- className
- )}
- {...props}
- />
- )
-}
-
-function SidebarGroupContent({
- className,
- ...props
-}: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
- return (
-
- )
-}
-
-function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
- return (
-
- )
-}
-
-const sidebarMenuButtonVariants = cva(
- "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
- {
- variants: {
- variant: {
- default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
- outline:
- "bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
- },
- size: {
- default: "h-8 text-sm",
- sm: "h-7 text-xs",
- lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
-
-function SidebarMenuButton({
- asChild = false,
- isActive = false,
- variant = "default",
- size = "default",
- tooltip,
- className,
- ...props
-}: React.ComponentProps<"button"> & {
- asChild?: boolean
- isActive?: boolean
- tooltip?: string | React.ComponentProps
-} & VariantProps) {
- const Comp = asChild ? Slot.Root : "button"
- const { isMobile, state } = useSidebar()
-
- const button = (
-
- )
-
- if (!tooltip) {
- return button
- }
-
- if (typeof tooltip === "string") {
- tooltip = {
- children: tooltip,
- }
- }
-
- return (
-
- {button}
-
-
- )
-}
-
-function SidebarMenuAction({
- className,
- asChild = false,
- showOnHover = false,
- ...props
-}: React.ComponentProps<"button"> & {
- asChild?: boolean
- showOnHover?: boolean
-}) {
- const Comp = asChild ? Slot.Root : "button"
-
- return (
- svg]:size-4 [&>svg]:shrink-0",
- // Increases the hit area of the button on mobile.
- "after:absolute after:-inset-2 md:after:hidden",
- "peer-data-[size=sm]/menu-button:top-1",
- "peer-data-[size=default]/menu-button:top-1.5",
- "peer-data-[size=lg]/menu-button:top-2.5",
- "group-data-[collapsible=icon]:hidden",
- showOnHover &&
- "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground data-[state=open]:opacity-100 md:opacity-0",
- className
- )}
- {...props}
- />
- )
-}
-
-function SidebarMenuBadge({
- className,
- ...props
-}: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-function SidebarMenuSkeleton({
- className,
- showIcon = false,
- ...props
-}: React.ComponentProps<"div"> & {
- showIcon?: boolean
-}) {
- // Random width between 50 to 90%.
- const width = React.useMemo(() => {
- return `${Math.floor(Math.random() * 40) + 50}%`
- }, [])
-
- return (
-
- {showIcon && (
-
- )}
-
-
- )
-}
-
-function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
- return (
-
- )
-}
-
-function SidebarMenuSubItem({
- className,
- ...props
-}: React.ComponentProps<"li">) {
- return (
-
- )
-}
-
-function SidebarMenuSubButton({
- asChild = false,
- size = "md",
- isActive = false,
- className,
- ...props
-}: React.ComponentProps<"a"> & {
- asChild?: boolean
- size?: "sm" | "md"
- isActive?: boolean
-}) {
- const Comp = asChild ? Slot.Root : "a"
-
- return (
- span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
- "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
- size === "sm" && "text-xs",
- size === "md" && "text-sm",
- "group-data-[collapsible=icon]:hidden",
- className
- )}
- {...props}
- />
- )
-}
-
-export {
- Sidebar,
- SidebarContent,
- SidebarFooter,
- SidebarGroup,
- SidebarGroupAction,
- SidebarGroupContent,
- SidebarGroupLabel,
- SidebarHeader,
- SidebarInput,
- SidebarInset,
- SidebarMenu,
- SidebarMenuAction,
- SidebarMenuBadge,
- SidebarMenuButton,
- SidebarMenuItem,
- SidebarMenuSkeleton,
- SidebarMenuSub,
- SidebarMenuSubButton,
- SidebarMenuSubItem,
- SidebarProvider,
- SidebarRail,
- SidebarSeparator,
- SidebarTrigger,
- useSidebar,
-}
diff --git a/demo/chat-ui/src/components/ui/skeleton.tsx b/demo/chat-ui/src/components/ui/skeleton.tsx
deleted file mode 100644
index 3ec6be77..00000000
--- a/demo/chat-ui/src/components/ui/skeleton.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { cn } from "@/lib/utils"
-
-function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
- return (
-
- )
-}
-
-export { Skeleton }
diff --git a/demo/chat-ui/src/components/ui/tooltip.tsx b/demo/chat-ui/src/components/ui/tooltip.tsx
deleted file mode 100644
index d4d22540..00000000
--- a/demo/chat-ui/src/components/ui/tooltip.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import * as React from "react"
-import { Tooltip as TooltipPrimitive } from "radix-ui"
-
-import { cn } from "@/lib/utils"
-
-function TooltipProvider({
- delayDuration = 0,
- ...props
-}: React.ComponentProps) {
- return (
-
- )
-}
-
-function Tooltip({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function TooltipTrigger({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function TooltipContent({
- className,
- sideOffset = 0,
- children,
- ...props
-}: React.ComponentProps) {
- return (
-
-
- {children}
-
-
-
- )
-}
-
-export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/demo/chat-ui/src/hooks/use-mobile.ts b/demo/chat-ui/src/hooks/use-mobile.ts
deleted file mode 100644
index 2b0fe1df..00000000
--- a/demo/chat-ui/src/hooks/use-mobile.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as React from "react"
-
-const MOBILE_BREAKPOINT = 768
-
-export function useIsMobile() {
- const [isMobile, setIsMobile] = React.useState(undefined)
-
- React.useEffect(() => {
- const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
- const onChange = () => {
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
- }
- mql.addEventListener("change", onChange)
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
- return () => mql.removeEventListener("change", onChange)
- }, [])
-
- return !!isMobile
-}
diff --git a/demo/chat-ui/src/index.css b/demo/chat-ui/src/index.css
deleted file mode 100644
index 085a3331..00000000
--- a/demo/chat-ui/src/index.css
+++ /dev/null
@@ -1,1094 +0,0 @@
-@import "tailwindcss";
-@import "tw-shimmer";
-
-/*
- ---break---
- */
-
-@custom-variant data-open (&:where([data-state="open"], [data-open]:not([data-open="false"])));
-
-/*
- ---break---
- */
-
-@custom-variant data-closed (&:where([data-state="closed"], [data-closed]:not([data-closed="false"])));
-
-/*
- ---break---
- */
-@theme inline {
- @keyframes collapsible-down {
- from {
- height: 0;
- }
-
- to {
- height: var(--radix-collapsible-content-height, var(--collapsible-panel-height, auto));
- }
- }
-
- @keyframes collapsible-up {
- from {
- height: var(--radix-collapsible-content-height, var(--collapsible-panel-height, auto));
- }
-
- to {
- height: 0;
- }
- }
-
- --color-sidebar: var(--sidebar);
- --color-sidebar-foreground: var(--sidebar-foreground);
- --color-sidebar-primary: var(--sidebar-primary);
- --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
- --color-sidebar-accent: var(--sidebar-accent);
- --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
- --color-sidebar-border: var(--sidebar-border);
- --color-sidebar-ring: var(--sidebar-ring);
- --color-aui-warning: var(--aui-warning);
- --color-aui-success: var(--aui-success);
-}
-
-/*
- ---break---
- */
-.dark {
- --sidebar: hsl(240 5.9% 10%);
- --sidebar-foreground: hsl(240 4.8% 95.9%);
- --sidebar-primary: hsl(224.3 76.3% 48%);
- --sidebar-primary-foreground: hsl(0 0% 100%);
- --sidebar-accent: hsl(240 3.7% 15.9%);
- --sidebar-accent-foreground: hsl(240 4.8% 95.9%);
- --sidebar-border: hsl(240 3.7% 15.9%);
- --sidebar-ring: hsl(217.2 91.2% 59.8%);
- --aui-success: oklch(0.72 0.17 149);
- --aui-warning: oklch(0.8 0.17 75);
-}
-
-/*
- * The shadcn colour palette, "neutral", exactly as https://ui.shadcn.com/r/colors/neutral.json
- * publishes it for Tailwind v4. Generated rather than typed, and placed after the blocks the
- * shadcn CLI wrote above so that these oklch values win over the hsl sidebar defaults it emitted.
- *
- * It is here rather than produced by `shadcn init` because init cannot run non-interactively
- * against a components.json that already exists, and this project's components.json was written
- * by hand. Refreshing it means re-fetching that URL, not editing the numbers.
- */
-
-:root {
- --background: oklch(1 0 0);
- --foreground: oklch(0.145 0 0);
- --card: oklch(1 0 0);
- --card-foreground: oklch(0.145 0 0);
- --popover: oklch(1 0 0);
- --popover-foreground: oklch(0.145 0 0);
- --primary: oklch(0.205 0 0);
- --primary-foreground: oklch(0.985 0 0);
- --secondary: oklch(0.97 0 0);
- --secondary-foreground: oklch(0.205 0 0);
- --muted: oklch(0.97 0 0);
- --muted-foreground: oklch(0.556 0 0);
- --accent: oklch(0.97 0 0);
- --accent-foreground: oklch(0.205 0 0);
- --destructive: oklch(0.577 0.245 27.325);
- --border: oklch(0.922 0 0);
- --input: oklch(0.922 0 0);
- --ring: oklch(0.708 0 0);
- --chart-1: oklch(0.87 0 0);
- --chart-2: oklch(0.556 0 0);
- --chart-3: oklch(0.439 0 0);
- --chart-4: oklch(0.371 0 0);
- --chart-5: oklch(0.269 0 0);
- --radius: 0.625rem;
- --sidebar: oklch(0.985 0 0);
- --sidebar-foreground: oklch(0.145 0 0);
- --sidebar-primary: oklch(0.205 0 0);
- --sidebar-primary-foreground: oklch(0.985 0 0);
- --sidebar-accent: oklch(0.97 0 0);
- --sidebar-accent-foreground: oklch(0.205 0 0);
- --sidebar-border: oklch(0.922 0 0);
- --sidebar-ring: oklch(0.708 0 0);
- --aui-success: oklch(0.6 0.15 149);
- --aui-warning: oklch(0.68 0.16 70);
-}
-
-/*
- * Dark follows the system unless a `.dark` class overrides it. The class form is what shadcn's own
- * components assume, and the media query is what makes the page respect the operating system with
- * no toggle to build.
- */
-@media (prefers-color-scheme: dark) {
- :root:not(.light) {
- --background: oklch(0.145 0 0);
- --foreground: oklch(0.985 0 0);
- --card: oklch(0.205 0 0);
- --card-foreground: oklch(0.985 0 0);
- --popover: oklch(0.205 0 0);
- --popover-foreground: oklch(0.985 0 0);
- --primary: oklch(0.922 0 0);
- --primary-foreground: oklch(0.205 0 0);
- --secondary: oklch(0.269 0 0);
- --secondary-foreground: oklch(0.985 0 0);
- --muted: oklch(0.269 0 0);
- --muted-foreground: oklch(0.708 0 0);
- --accent: oklch(0.269 0 0);
- --accent-foreground: oklch(0.985 0 0);
- --destructive: oklch(0.704 0.191 22.216);
- --border: oklch(1 0 0 / 10%);
- --input: oklch(1 0 0 / 15%);
- --ring: oklch(0.556 0 0);
- --chart-1: oklch(0.87 0 0);
- --chart-2: oklch(0.556 0 0);
- --chart-3: oklch(0.439 0 0);
- --chart-4: oklch(0.371 0 0);
- --chart-5: oklch(0.269 0 0);
- --sidebar: oklch(0.205 0 0);
- --sidebar-foreground: oklch(0.985 0 0);
- --sidebar-primary: oklch(0.488 0.243 264.376);
- --sidebar-primary-foreground: oklch(0.985 0 0);
- --sidebar-accent: oklch(0.269 0 0);
- --sidebar-accent-foreground: oklch(0.985 0 0);
- --sidebar-border: oklch(1 0 0 / 10%);
- --sidebar-ring: oklch(0.556 0 0);
- }
-}
-
-.dark {
- --background: oklch(0.145 0 0);
- --foreground: oklch(0.985 0 0);
- --card: oklch(0.205 0 0);
- --card-foreground: oklch(0.985 0 0);
- --popover: oklch(0.205 0 0);
- --popover-foreground: oklch(0.985 0 0);
- --primary: oklch(0.922 0 0);
- --primary-foreground: oklch(0.205 0 0);
- --secondary: oklch(0.269 0 0);
- --secondary-foreground: oklch(0.985 0 0);
- --muted: oklch(0.269 0 0);
- --muted-foreground: oklch(0.708 0 0);
- --accent: oklch(0.269 0 0);
- --accent-foreground: oklch(0.985 0 0);
- --destructive: oklch(0.704 0.191 22.216);
- --border: oklch(1 0 0 / 10%);
- --input: oklch(1 0 0 / 15%);
- --ring: oklch(0.556 0 0);
- --chart-1: oklch(0.87 0 0);
- --chart-2: oklch(0.556 0 0);
- --chart-3: oklch(0.439 0 0);
- --chart-4: oklch(0.371 0 0);
- --chart-5: oklch(0.269 0 0);
- --sidebar: oklch(0.205 0 0);
- --sidebar-foreground: oklch(0.985 0 0);
- --sidebar-primary: oklch(0.488 0.243 264.376);
- --sidebar-primary-foreground: oklch(0.985 0 0);
- --sidebar-accent: oklch(0.269 0 0);
- --sidebar-accent-foreground: oklch(0.985 0 0);
- --sidebar-border: oklch(1 0 0 / 10%);
- --sidebar-ring: oklch(0.556 0 0);
-}
-
-@theme inline {
- --color-background: var(--background);
- --color-foreground: var(--foreground);
- --color-card: var(--card);
- --color-card-foreground: var(--card-foreground);
- --color-popover: var(--popover);
- --color-popover-foreground: var(--popover-foreground);
- --color-primary: var(--primary);
- --color-primary-foreground: var(--primary-foreground);
- --color-secondary: var(--secondary);
- --color-secondary-foreground: var(--secondary-foreground);
- --color-muted: var(--muted);
- --color-muted-foreground: var(--muted-foreground);
- --color-accent: var(--accent);
- --color-accent-foreground: var(--accent-foreground);
- --color-destructive: var(--destructive);
- --color-border: var(--border);
- --color-input: var(--input);
- --color-ring: var(--ring);
- --color-chart-1: var(--chart-1);
- --color-chart-2: var(--chart-2);
- --color-chart-3: var(--chart-3);
- --color-chart-4: var(--chart-4);
- --color-chart-5: var(--chart-5);
- --radius-sm: calc(var(--radius) - 4px);
- --radius-md: calc(var(--radius) - 2px);
- --radius-lg: var(--radius);
- --radius-xl: calc(var(--radius) + 4px);
-}
-
-@layer base {
- * {
- @apply border-border outline-ring/50;
- }
-
- body {
- @apply bg-background text-foreground;
- }
-}
-
-[data-aui] {
- box-sizing: border-box;
-}
-
-[data-aui="header"] {
- margin: 0;
- font-size: 1.25rem;
- font-weight: 600;
- letter-spacing: -0.01em;
- line-height: 1.2;
-}
-
-[data-aui="text"] {
- line-height: 1.5;
-}
-
-[data-aui="caption"] {
- margin: 0;
- font-size: 0.75rem;
- line-height: 1.4;
- color: color-mix(in oklab, currentColor 62%, transparent);
-}
-
-[data-aui="text"][data-aui-size="sm"],
-[data-aui="header"][data-aui-size="sm"] {
- font-size: 0.75rem;
-}
-
-[data-aui="text"][data-aui-size="md"],
-[data-aui="header"][data-aui-size="md"] {
- font-size: 0.875rem;
-}
-
-[data-aui="text"][data-aui-size="lg"],
-[data-aui="header"][data-aui-size="lg"] {
- font-size: 1.125rem;
-}
-
-[data-aui="text"][data-aui-size="xl"],
-[data-aui="header"][data-aui-size="xl"] {
- font-size: 1.25rem;
-}
-
-[data-aui="text"][data-aui-size="2xl"],
-[data-aui="header"][data-aui-size="2xl"] {
- font-size: 1.5rem;
- font-weight: 600;
- letter-spacing: -0.02em;
-}
-
-[data-aui="text"][data-aui-size="3xl"],
-[data-aui="header"][data-aui-size="3xl"] {
- font-size: 2.25rem;
- font-weight: 600;
- letter-spacing: -0.02em;
-}
-
-[data-aui="text"][data-aui-weight="normal"] {
- font-weight: 400;
-}
-
-[data-aui="text"][data-aui-weight="medium"] {
- font-weight: 500;
-}
-
-[data-aui="text"][data-aui-weight="semibold"] {
- font-weight: 600;
-}
-
-[data-aui="text"][data-aui-weight="bold"] {
- font-weight: 700;
-}
-
-[data-aui="text"][data-aui-color="emphasis"] {
- color: var(--foreground);
-}
-
-[data-aui="text"][data-aui-color="secondary"] {
- color: color-mix(in oklab, currentColor 62%, transparent);
-}
-
-[data-aui="text"][data-aui-color="alpha-70"] {
- color: color-mix(in oklab, var(--foreground) 70%, transparent);
-}
-
-[data-aui="text"][data-aui-color="white"] {
- color: white;
-}
-
-[data-aui="text"][data-aui-color="white-70"] {
- color: color-mix(in oklab, white 70%, transparent);
-}
-
-[data-aui="text"][data-aui-color="white-50"] {
- color: color-mix(in oklab, white 50%, transparent);
-}
-
-[data-aui="fact"] {
- margin: 0;
-}
-
-[data-aui="fact-label"] {
- margin: 0;
- font-size: 0.6875rem;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: color-mix(in oklab, currentColor 62%, transparent);
-}
-
-[data-aui="fact-value"] {
- margin: 0;
- font-size: 0.875rem;
- font-variant-numeric: tabular-nums;
-}
-
-[data-aui="button"],
-[data-aui="card-confirm"],
-[data-aui="card-cancel"] {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 0.25rem;
- height: var(--aui-control-height, 2.5rem);
- padding: 0 var(--aui-button-padding-x, 1.25rem);
- border-radius: calc(var(--radius) - 2px);
- font-size: var(--aui-control-font-size, 0.875rem);
- font-weight: 500;
- border: 1px solid transparent;
- cursor: pointer;
- background-color: var(--secondary);
- color: var(--secondary-foreground);
- transition: background-color 0.15s ease;
- white-space: nowrap;
- flex-shrink: 0;
-}
-
-[data-aui="button"]:focus-visible,
-[data-aui="card-confirm"]:focus-visible,
-[data-aui="card-cancel"]:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 2px;
-}
-
-[data-aui="button"][data-aui-style="primary"],
-[data-aui="card-confirm"] {
- background-color: var(--primary);
- color: var(--primary-foreground);
-}
-
-[data-aui="button"][data-aui-style="primary"]:hover,
-[data-aui="card-confirm"]:hover {
- background-color: color-mix(in oklab, var(--primary) 90%, transparent);
-}
-
-[data-aui="button"][data-aui-style="secondary"] {
- background-color: var(--secondary);
- color: var(--secondary-foreground);
-}
-
-[data-aui="button"][data-aui-style="secondary"]:hover {
- background-color: color-mix(in oklab, var(--secondary) 90%, transparent);
-}
-
-[data-aui="button"][data-aui-style="outline"] {
- background-color: transparent;
- color: var(--foreground);
- border-color: color-mix(in oklab, var(--border) 60%, transparent);
-}
-
-[data-aui="button"][data-aui-style="outline"]:hover {
- background-color: var(--accent);
- color: var(--accent-foreground);
-}
-
-[data-aui="button"][data-aui-style="ghost"],
-[data-aui="card-cancel"] {
- background-color: transparent;
- color: var(--foreground);
-}
-
-[data-aui="button"][data-aui-style="ghost"]:hover,
-[data-aui="card-cancel"]:hover {
- background-color: var(--accent);
- color: var(--accent-foreground);
-}
-
-[data-aui="button"][data-aui-style="danger"] {
- background-color: var(--destructive);
- color: var(--primary-foreground);
-}
-
-[data-aui="button"][data-aui-style="danger"]:hover {
- background-color: color-mix(in oklab, var(--destructive) 90%, transparent);
-}
-
-[data-aui="button"][data-aui-block] {
- width: 100%;
-}
-
-[data-aui="select"],
-[data-aui="input"],
-[data-aui="datepicker"] {
- display: block;
- width: 100%;
- min-width: 0;
- height: var(--aui-control-height, 2.5rem);
- padding: 0 var(--aui-field-padding-x, 0.875rem);
- border-radius: calc(var(--radius) - 2px);
- border: 1px solid var(--input);
- background-color: transparent;
- font-size: var(--aui-control-font-size, 0.875rem);
- color: var(--foreground);
-}
-
-[data-aui="datepicker"] {
- max-width: 100%;
-}
-
-[data-aui="input"][data-aui-multiline] {
- height: auto;
- min-height: 2.5rem;
- padding: 0.625rem var(--aui-field-padding-x, 0.875rem);
- line-height: 1.5;
- resize: vertical;
-}
-
-[data-aui="input"]::placeholder {
- color: color-mix(in oklab, currentColor 45%, transparent);
-}
-
-[data-aui="select"]:focus-visible,
-[data-aui="input"]:focus-visible,
-[data-aui="datepicker"]:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 2px;
-}
-
-[data-aui="checkbox"] {
- display: inline-flex;
- align-items: center;
- gap: 0.5rem;
- cursor: pointer;
-}
-
-[data-aui="radiogroup-option"] {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- cursor: pointer;
-}
-
-[data-aui="checkbox"] input,
-[data-aui="radiogroup-option"] input {
- accent-color: var(--primary);
- width: 1rem;
- height: 1rem;
- margin: 0;
- cursor: pointer;
-}
-
-[data-aui="checkbox"] input:focus-visible,
-[data-aui="radiogroup-option"] input:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 2px;
-}
-
-[data-aui="radiogroup"] {
- border: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
- gap: 0.25rem;
-}
-
-[data-aui="root"] {
- display: flex;
- flex-direction: column;
- gap: 0.875rem;
- margin-block: 0.875rem;
-}
-
-[data-aui="root"]:empty {
- display: none;
-}
-
-[data-aui="card"] {
- display: flex;
- flex-direction: column;
- gap: 0.875rem;
- padding: var(--aui-card-padding, 0);
-}
-
-[data-aui="card"][data-aui-surface],
-[data-aui="carousel"] [data-aui="card"] {
- --aui-card-padding: 1.25rem;
- background-color: var(--card);
- color: var(--card-foreground);
- border: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
- border-radius: var(--radius);
- box-shadow: none;
-}
-
-[data-aui="card-title"] {
- margin: 0;
- font-size: 0.9375rem;
- font-weight: 600;
-}
-
-[data-aui="card-footer"] {
- display: flex;
- justify-content: flex-end;
- gap: 0.5rem;
- padding-top: 0.75rem;
- border-top: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
-}
-
-[data-aui-padding="0"] {
- padding: 0;
-}
-
-[data-aui-padding="1"] {
- padding: calc(1 * 4px);
-}
-
-[data-aui-padding="2"] {
- padding: calc(2 * 4px);
-}
-
-[data-aui-padding="3"] {
- padding: calc(3 * 4px);
-}
-
-[data-aui-padding="4"] {
- padding: calc(4 * 4px);
-}
-
-[data-aui-padding="5"] {
- padding: calc(5 * 4px);
-}
-
-[data-aui-padding="6"] {
- padding: calc(6 * 4px);
-}
-
-[data-aui-padding="7"] {
- padding: calc(7 * 4px);
-}
-
-[data-aui-padding="8"] {
- padding: calc(8 * 4px);
-}
-
-[data-aui="row"] {
- display: flex;
- flex-direction: row;
- gap: 0.5rem;
-}
-
-[data-aui="col"] {
- display: flex;
- flex-direction: column;
- gap: 0.625rem;
-}
-
-[data-aui="form"] {
- display: flex;
- flex-direction: column;
- gap: 0.75rem;
- margin: 0;
-}
-
-[data-aui="spacer"] {
- flex: 1;
-}
-
-[data-aui="row"][data-aui-align="start"],
-[data-aui="col"][data-aui-align="start"] {
- align-items: flex-start;
-}
-
-[data-aui="row"][data-aui-align="center"],
-[data-aui="col"][data-aui-align="center"] {
- align-items: center;
-}
-
-[data-aui="row"][data-aui-align="end"],
-[data-aui="col"][data-aui-align="end"] {
- align-items: flex-end;
-}
-
-[data-aui="row"][data-aui-justify="start"] {
- justify-content: flex-start;
-}
-
-[data-aui="row"][data-aui-justify="center"] {
- justify-content: center;
-}
-
-[data-aui="row"][data-aui-justify="end"] {
- justify-content: flex-end;
-}
-
-[data-aui="row"][data-aui-justify="between"] {
- justify-content: space-between;
-}
-
-[data-aui-gap="0"] {
- gap: 0;
-}
-
-[data-aui-gap="1"] {
- gap: calc(1 * 4px);
-}
-
-[data-aui-gap="2"] {
- gap: calc(2 * 4px);
-}
-
-[data-aui-gap="3"] {
- gap: calc(3 * 4px);
-}
-
-[data-aui-gap="4"] {
- gap: calc(4 * 4px);
-}
-
-[data-aui-gap="5"] {
- gap: calc(5 * 4px);
-}
-
-[data-aui-gap="6"] {
- gap: calc(6 * 4px);
-}
-
-[data-aui-gap="7"] {
- gap: calc(7 * 4px);
-}
-
-[data-aui-gap="8"] {
- gap: calc(8 * 4px);
-}
-
-[data-aui="box"] {
- display: block;
-}
-
-[data-aui="icon"] {
- display: inline-block;
- vertical-align: -0.125em;
- flex-shrink: 0;
-}
-
-[data-aui="alert"] {
- border-width: 1px;
- border-style: solid;
- border-radius: var(--radius);
- padding: 0.75rem 0.875rem;
-}
-
-[data-aui="alert"][data-aui-tone="info"] {
- border-color: color-mix(in oklab, var(--primary) 45%, transparent);
- background-color: color-mix(in oklab, var(--primary) 8%, transparent);
-}
-
-[data-aui="alert"][data-aui-tone="success"] {
- border-color: color-mix(in oklab, var(--aui-success) 45%, transparent);
- background-color: color-mix(in oklab, var(--aui-success) 8%, transparent);
-}
-
-[data-aui="alert"][data-aui-tone="warning"] {
- border-color: color-mix(in oklab, var(--aui-warning) 45%, transparent);
- background-color: color-mix(in oklab, var(--aui-warning) 8%, transparent);
-}
-
-[data-aui="alert"][data-aui-tone="danger"] {
- border-color: color-mix(in oklab, var(--destructive) 45%, transparent);
- background-color: color-mix(in oklab, var(--destructive) 8%, transparent);
-}
-
-[data-aui="alert-title"] {
- margin: 0 0 0.25rem 0;
- font-weight: 500;
-}
-
-[data-aui="alert-desc"] {
- margin: 0;
- color: color-mix(in oklab, currentColor 62%, transparent);
- font-size: 0.8125rem;
-}
-
-[data-aui="table"] {
- width: 100%;
- border-collapse: collapse;
-}
-
-[data-aui="table-col"] {
- text-align: left;
- font-size: 0.75rem;
- font-weight: 500;
- color: color-mix(in oklab, currentColor 62%, transparent);
- padding: 0.5rem 0.75rem;
- border-bottom: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
-}
-
-[data-aui="table"] td {
- font-size: 0.875rem;
- padding: 0.5rem 0.75rem;
- text-align: left;
- font-variant-numeric: tabular-nums;
-}
-
-[data-aui="table"] tbody tr:not(:last-child) td {
- border-bottom: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
-}
-
-[data-aui="chart"] {
- display: block;
- width: 100%;
- height: 3rem;
- color: var(--chart-1);
-}
-
-[data-aui="chart"] polyline,
-[data-aui="chart"] polygon {
- stroke-width: 1.5;
-}
-
-[data-aui="chart"][data-aui-color] [data-aui="chart-series"]:only-child {
- color: inherit;
-}
-
-[data-aui="chart"][data-aui-color="emphasis"] {
- color: var(--foreground);
-}
-
-[data-aui="chart"][data-aui-color="secondary"] {
- color: color-mix(in oklab, currentColor 62%, transparent);
-}
-
-[data-aui="chart"][data-aui-color="alpha-70"] {
- color: color-mix(in oklab, var(--foreground) 70%, transparent);
-}
-
-[data-aui="chart"][data-aui-color="white"] {
- color: white;
-}
-
-[data-aui="chart"][data-aui-color="white-70"] {
- color: color-mix(in oklab, white 70%, transparent);
-}
-
-[data-aui="chart"][data-aui-color="white-50"] {
- color: color-mix(in oklab, white 50%, transparent);
-}
-
-[data-aui="chart-frame"] {
- display: grid;
- grid-template-columns: auto 1fr;
- gap: 0.25rem;
-}
-
-[data-aui="chart-frame"]>[data-aui="chart-ticks"] {
- grid-column: 1;
- grid-row: 1;
- display: flex;
- flex-direction: column;
- justify-content: space-between;
- text-align: right;
-}
-
-[data-aui="chart-frame"]>[data-aui="chart-ticks"],
-[data-aui="chart-frame"]>[data-aui="chart-xlabels"] {
- font-size: 0.6875rem;
- color: var(--muted-foreground);
-}
-
-[data-aui="chart-frame"]>svg[data-aui="chart"] {
- grid-column: 2;
- grid-row: 1;
- height: 6.5rem;
-}
-
-[data-aui="chart-frame"]>[data-aui="chart-xlabels"] {
- grid-column: 2;
- grid-row: 2;
- display: flex;
- justify-content: space-between;
-}
-
-[data-aui="chart-frame"]>[data-aui="chart-legend"] {
- grid-column: 1 / -1;
- grid-row: 3;
- display: flex;
- gap: 0.75rem;
- font-size: 0.75rem;
- color: var(--muted-foreground);
-}
-
-[data-aui="chart-legend-item"] {
- display: inline-flex;
- align-items: center;
- gap: 0.25rem;
-}
-
-[data-aui="chart-legend-swatch"] {
- display: inline-block;
- width: 0.625rem;
- height: 0.625rem;
- border-radius: calc(var(--radius) - 4px);
- background-color: currentColor;
-}
-
-[data-aui="chart-series"][data-aui-series="0"],
-[data-aui="chart-legend-item"][data-aui-series="0"] {
- color: var(--chart-1);
-}
-
-[data-aui="chart-series"][data-aui-series="1"],
-[data-aui="chart-legend-item"][data-aui-series="1"] {
- color: var(--chart-2);
-}
-
-[data-aui="chart-series"][data-aui-series="2"],
-[data-aui="chart-legend-item"][data-aui-series="2"] {
- color: var(--chart-3);
-}
-
-[data-aui="chart-series"][data-aui-series="3"],
-[data-aui="chart-legend-item"][data-aui-series="3"] {
- color: var(--chart-4);
-}
-
-[data-aui="chart-series"][data-aui-series="4"],
-[data-aui="chart-legend-item"][data-aui-series="4"] {
- color: var(--chart-5);
-}
-
-[data-aui="carousel"] {
- display: flex;
- overflow-x: auto;
- scroll-snap-type: x mandatory;
- scroll-behavior: smooth;
- gap: 0.75rem;
- padding-bottom: 0.5rem;
- scrollbar-width: thin;
-}
-
-[data-aui="carousel"]:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 2px;
-}
-
-[data-aui="carousel-slide"] {
- scroll-snap-align: start;
- flex: 0 0 auto;
- min-width: 14rem;
-}
-
-/*
- ---break---
- */
-@media (prefers-reduced-motion: reduce) {
- [data-aui="carousel"] {
- scroll-behavior: auto;
- }
-}
-
-[data-aui="listview"] {
- list-style: none;
- margin: 0;
- padding: 0;
-}
-
-[data-aui="listview-item"]+[data-aui="listview-item"] {
- border-top: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
-}
-
-[data-aui="listview-item-trigger"] {
- padding: 0.75rem 0.875rem;
- border-radius: calc(var(--radius) - 2px);
- cursor: pointer;
-}
-
-[data-aui="listview-item-trigger"]:hover {
- background-color: color-mix(in oklab, var(--muted) 50%, transparent);
-}
-
-[data-aui="listview-item-trigger"]:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 2px;
-}
-
-[data-aui="divider"] {
- border: none;
- border-top: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
- margin: 0.75rem 0;
-}
-
-[data-aui="divider"][data-aui-flush] {
- margin: 0;
-}
-
-[data-aui="card"]>[data-aui="divider"] {
- margin: 0;
-}
-
-[data-aui="image"] {
- max-width: 100%;
- display: block;
- border-radius: calc(var(--radius) - 2px);
-}
-
-[data-aui="image"][data-aui-size="sm"] {
- max-width: 8rem;
-}
-
-[data-aui="image"][data-aui-size="md"] {
- max-width: 16rem;
-}
-
-[data-aui="image"][data-aui-size="lg"] {
- max-width: 24rem;
-}
-
-[data-aui="image"][data-aui-round] {
- width: 2.5rem;
- height: 2.5rem;
- border-radius: 9999px;
- object-fit: cover;
- aspect-ratio: 1 / 1;
-}
-
-[data-aui="image"][data-aui-round][data-aui-size="sm"] {
- width: 2rem;
- height: 2rem;
-}
-
-[data-aui="image"][data-aui-round][data-aui-size="md"] {
- width: 2.5rem;
- height: 2.5rem;
-}
-
-[data-aui="image"][data-aui-round][data-aui-size="lg"] {
- width: 3.25rem;
- height: 3.25rem;
-}
-
-[data-aui="markdown"] {
- font-size: 0.875rem;
- line-height: 1.6;
-}
-
-[data-aui="markdown"] p {
- margin: 0 0 0.5rem 0;
-}
-
-[data-aui="markdown"] p:last-child {
- margin-bottom: 0;
-}
-
-[data-aui="markdown"] a {
- color: var(--primary);
- text-decoration: underline;
- text-underline-offset: 2px;
-}
-
-[data-aui="markdown"] code {
- font-size: 0.8125em;
- background-color: color-mix(in oklab, var(--muted) 60%, transparent);
- padding: 0.125rem 0.375rem;
- border-radius: calc(var(--radius) - 4px);
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
-}
-
-[data-aui="markdown"] pre {
- background-color: color-mix(in oklab, var(--muted) 60%, transparent);
- padding: 0.75rem;
- border-radius: calc(var(--radius) - 2px);
- overflow-x: auto;
-}
-
-[data-aui="markdown"] pre code {
- background-color: transparent;
- padding: 0;
-}
-
-[data-aui="markdown"] ul,
-[data-aui="markdown"] ol {
- padding-left: 1.25rem;
-}
-
-[data-aui="markdown"] ol {
- list-style-type: decimal;
-}
-
-[data-aui="markdown"] ul {
- list-style-type: disc;
-}
-
-[data-aui="markdown"] li {
- margin: 0.25rem 0;
-}
-
-[data-aui="markdown"] h1,
-[data-aui="markdown"] h2,
-[data-aui="markdown"] h3 {
- margin: 0.75em 0 0.25em;
- font-weight: 600;
-}
-
-[data-aui="markdown"] h1 {
- font-size: 1.125em;
-}
-
-[data-aui="markdown"] h2 {
- font-size: 1.0625em;
-}
-
-[data-aui="markdown"] h3 {
- font-size: 1em;
-}
-
-[data-aui="markdown"] blockquote {
- border-left: 2px solid color-mix(in oklab, var(--border) 60%, transparent);
- padding-left: 0.75rem;
- color: color-mix(in oklab, currentColor 62%, transparent);
- margin: 0.5em 0;
-}
-
-[data-aui="badge"] {
- display: inline-flex;
- align-items: center;
- gap: 0.25rem;
- border-radius: 9999px;
- padding: 0.125rem 0.5rem;
- font-size: 0.75rem;
- font-weight: 500;
- line-height: 1.4;
- font-variant-numeric: tabular-nums;
- background-color: var(--muted);
- color: color-mix(in oklab, currentColor 62%, transparent);
- flex-shrink: 0;
- white-space: nowrap;
-}
-
-[data-aui="badge"][data-aui-variant="info"] {
- background-color: color-mix(in oklab, var(--primary) 15%, transparent);
- color: var(--primary);
-}
-
-[data-aui="badge"][data-aui-variant="success"] {
- background-color: color-mix(in oklab, var(--aui-success) 15%, transparent);
- color: var(--aui-success);
-}
-
-[data-aui="badge"][data-aui-variant="warning"] {
- background-color: color-mix(in oklab, var(--aui-warning) 15%, transparent);
- color: var(--aui-warning);
-}
-
-[data-aui="badge"][data-aui-variant="danger"] {
- background-color: color-mix(in oklab, var(--destructive) 15%, transparent);
- color: var(--destructive);
-}
\ No newline at end of file
diff --git a/demo/chat-ui/src/lib/utils.ts b/demo/chat-ui/src/lib/utils.ts
deleted file mode 100644
index bd0c391d..00000000
--- a/demo/chat-ui/src/lib/utils.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
-
-export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
-}
diff --git a/demo/chat-ui/src/main.tsx b/demo/chat-ui/src/main.tsx
deleted file mode 100644
index 2d79d5fa..00000000
--- a/demo/chat-ui/src/main.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { StrictMode } from "react";
-import { createRoot } from "react-dom/client";
-import { App } from "./App";
-import "./index.css";
-
-createRoot(document.getElementById("root")!).render(
-
-
- ,
-);
diff --git a/demo/chat-ui/src/runtime/AgentCoreRuntime.test.ts b/demo/chat-ui/src/runtime/AgentCoreRuntime.test.ts
deleted file mode 100644
index e7c6c8d3..00000000
--- a/demo/chat-ui/src/runtime/AgentCoreRuntime.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { sourceContent } from "./AgentCoreRuntime.ts";
-import type { SourcePart } from "./transport.ts";
-
-const document: SourcePart = {
- id: "card-42",
- sourceType: "document",
- title: "Spirit CT900 owner's manual, p.27",
- locator: "p.27",
- url: null,
- mediaType: "text/plain",
- origin: "knowledge",
- callId: "call-1",
-};
-
-describe("sourceContent", () => {
- it("maps a document source onto assistant-ui's document variant", () => {
- // A card has no URL, so the document variant is the only honest one: the url variant would
- // draw a link the caller could click, and there is nothing behind it.
- expect(sourceContent(document)).toEqual({
- type: "source",
- sourceType: "document",
- id: "card-42",
- title: "Spirit CT900 owner's manual, p.27",
- mediaType: "text/plain",
- parentId: "call-1",
- providerMetadata: { agentcore: { origin: "knowledge", locator: "p.27" } },
- });
- });
-
- it("maps a url source onto the url variant", () => {
- const part = sourceContent({
- ...document,
- sourceType: "url",
- url: "https://example.com/support",
- title: "Spirit Fitness support",
- origin: "web-search",
- });
-
- expect(part).toMatchObject({
- type: "source",
- sourceType: "url",
- url: "https://example.com/support",
- title: "Spirit Fitness support",
- });
- });
-
- it("falls back to the document variant when a url source arrives with no link", () => {
- // The host promises a link on a url source. A missing one is a host bug, and a url part with an
- // empty href renders a dead chip, so this degrades to the shape that needs no link.
- const part = sourceContent({ ...document, sourceType: "url", url: null });
-
- expect(part).toMatchObject({ type: "source", sourceType: "document" });
- });
-});
diff --git a/demo/chat-ui/src/runtime/AgentCoreRuntime.ts b/demo/chat-ui/src/runtime/AgentCoreRuntime.ts
deleted file mode 100644
index 01afa547..00000000
--- a/demo/chat-ui/src/runtime/AgentCoreRuntime.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-import {
- useLocalRuntime,
- type ChatModelAdapter,
- type ChatModelRunResult,
- type MessageTiming,
- type ThreadMessage,
-} from "@assistant-ui/react";
-import { useRef } from "react";
-import {
- runTurn,
- wireMessages,
- type Session,
- type SourcePart,
- type ToolPart,
- type TurnState,
- type WireMessage,
-} from "./transport.ts";
-
-/**
- * The bridge between assistant-ui and AgentCore's OpenAI-compatible endpoint.
- *
- * AgentCore keeps the transcript on the server and names the call in the `X-AgentCore-Session`
- * header. assistant-ui, like every OpenAI client, is stateless and sends the whole message list
- * instead. Holding the session id here — in the browser, for the life of the tab — is what
- * reconciles the two, and it is what saves AgentCore from needing a server-side map from chat
- * thread to call.
- *
- * Everything that touches the wire lives in {@link ./transport.ts}, where it is tested. This file
- * is the React shape around it and nothing else.
- */
-
-/**
- * Flattens one assistant-ui message into the single string the OpenAI shape carries.
- *
- * AgentCore's endpoint reads text and no other content part, so anything else in the message — an
- * image, a tool call — has nothing to map onto and is left out rather than sent as `[object
- * Object]`.
- */
-function flatten(message: ThreadMessage): WireMessage {
- const text = message.content
- .filter((part): part is { type: "text"; text: string } => part.type === "text")
- .map((part) => part.text)
- .join("");
-
- return { role: message.role, content: text };
-}
-
-/**
- * Measures one turn, in the shape `message.metadata.timing` is read back in.
- *
- * `useLocalRuntime` does not time turns for you — assistant-ui ships `useStreamingTiming` for that,
- * but only external-store adapters call it. A chat model adapter reports its own timing instead,
- * which is what this does. The field semantics follow assistant-ui's own tracker: `streamStartTime`
- * is epoch milliseconds while `firstTokenTime` and `totalStreamTime` are milliseconds *since* it,
- * and the token count is the same length/4 estimate, so a reader cannot tell the two apart.
- */
-function newTurnClock() {
- const startTime = Date.now();
- let firstTokenTime: number | undefined;
- let length = 0;
- let totalChunks = 0;
- let toolCallCount = 0;
-
- return {
- observe(state: TurnState) {
- // Growth, not arrival: the endpoint re-sends the whole text every frame, so an unchanged
- // length means nothing was added and must not count as a chunk.
- if (state.text.length > length) {
- firstTokenTime ??= Date.now() - startTime;
- length = state.text.length;
- totalChunks += 1;
- }
- // The wire now reports every tool the host ran, drawing tools included, so this is the count
- // itself rather than the drawings it used to be estimated from.
- toolCallCount = state.tools.length;
- },
-
- finish(): MessageTiming {
- const totalStreamTime = Date.now() - startTime;
- const tokenCount = Math.ceil(length / 4);
-
- return {
- streamStartTime: startTime,
- totalStreamTime,
- totalChunks,
- toolCallCount,
- ...(firstTokenTime !== undefined && { firstTokenTime }),
- ...(tokenCount > 0 && { tokenCount }),
- ...(totalStreamTime > 0 &&
- tokenCount > 0 && {
- tokensPerSecond: tokenCount / (totalStreamTime / 1000),
- }),
- };
- },
- };
-}
-
-/**
- * Turns one reported tool into the content part assistant-ui draws it as.
- *
- * `result` is left off entirely while the tool is still running, because that absence is what the
- * kit reads as "running" — an empty string there would draw a finished tool that answered nothing.
- */
-function toolContent(tool: ToolPart) {
- return {
- type: "tool-call" as const,
- toolCallId: tool.callId,
- toolName: tool.name,
- args: tool.arguments,
- argsText: JSON.stringify(tool.arguments, null, 2),
- ...(tool.result !== undefined
- ? { result: tool.result, isError: tool.failed === true }
- : {}),
- };
-}
-
-/**
- * Turns one cited source into the content part assistant-ui draws it as.
- *
- * The two variants are not interchangeable. `url` renders a clickable chip and needs a real href;
- * `document` renders a badge and needs a title and a media type. A knowledge card has no URL, so it
- * is always a document, and a `url` source that arrives without its link degrades to one rather
- * than drawing a chip that goes nowhere.
- *
- * `parentId` is the tool call that cited it, which is how assistant-ui ties a source to the step
- * that found it. `providerMetadata` carries what is ours and not assistant-ui's: which producer
- * cited it, and where inside the source it sits.
- */
-export function sourceContent(source: SourcePart) {
- const shared = {
- type: "source" as const,
- id: source.id,
- title: source.title,
- parentId: source.callId,
- providerMetadata: {
- agentcore: { origin: source.origin, locator: source.locator },
- },
- };
-
- if (source.sourceType === "url" && source.url) {
- return { ...shared, sourceType: "url" as const, url: source.url };
- }
-
- return {
- ...shared,
- sourceType: "document" as const,
- mediaType: source.mediaType,
- };
-}
-
-/**
- * Reads back the name the host stored one message under, if this one carries it.
- *
- * Only a reply ever does. The caller's own messages already travel under names this browser gave
- * them, and the host keeps those, so they need no translation.
- */
-function hostMessageId(message: ThreadMessage): string | undefined {
- const custom = message.metadata?.custom as { hostMessageId?: unknown } | undefined;
- return typeof custom?.hostMessageId === "string" ? custom.hostMessageId : undefined;
-}
-
-/**
- * Binds assistant-ui to one AgentCore endpoint.
- *
- * @param endpoint The route the host mapped the text endpoint on.
- * @returns The runtime to hand to `AssistantRuntimeProvider`.
- */
-export function useAgentCoreRuntime(endpoint: string) {
- // A ref and not state: changing the session must never re-render, and the value has to be the
- // current one by the time the next turn reads it rather than on the next paint.
- const session = useRef({ current: null });
-
- const adapter: ChatModelAdapter = {
- async *run({ messages, abortSignal }) {
- // assistant-ui hands over the path from the root to the message being sent, so the last entry
- // is what the caller just said and the one before it is what that hangs off. On an edit the
- // parent is the message BEFORE the one replaced, which is exactly what this picks up, and the
- // abandoned branch is not in this list at all.
- const parent = messages.at(-2);
-
- const turn = runTurn({
- endpoint,
- session: session.current,
- messages: wireMessages(messages.map(flatten)),
- abortSignal,
- fetch: (url, init) => fetch(url, init),
- origin: {
- message_id: messages.at(-1)?.id,
-
- // Null at the root of the call, which is what an edit of the first message asks for. A
- // parent the host does not know is sent under this browser's own name and simply matches
- // nothing there, which the host reads as a plain new turn.
- parent_id: parent ? (hostMessageId(parent) ?? parent.id) : null,
- },
- });
-
- const clock = newTurnClock();
- let content: ChatModelRunResult["content"] = [];
- let stage: ChatModelRunResult["metadata"] = undefined;
-
- for await (const state of turn) {
- clock.observe(state);
-
- // `metadata.custom` is the one slot on a message that is the app's to define. Nothing on
- // screen reads the stage or `isTerminal` — the caller is never shown which stage answered
- // them — but both stay here because they cost one field each and the alternative is
- // re-plumbing the runtime the day something does want them.
- stage = {
- custom: {
- stage: state.stage,
- isTerminal: state.isTerminal,
- // Absent today. Carried anyway so a live handoff is a server change on its own.
- speaker: state.speaker,
-
- // The host's own name for this reply, kept ON the message rather than in a map beside
- // it. The adapter never learns the id assistant-ui gives the message it is producing, so
- // there is nothing to key a map on — and metadata rides the message through a branch
- // switch and through the reload that restores it, which a map in a ref would not.
- hostMessageId: state.replyMessageId,
- },
- };
-
- // Every yield replaces the message content rather than adding to it, so each one repeats
- // everything drawn so far. Drop the repeat and a later text-only yield erases the drawing.
- // Tools first, and then the words: the host runs every tool before it speaks, so this is
- // the order the turn actually happened in.
- // Sources sit between the tools and the words: they are what the tools found, and the
- // caller should read the answer last. Every yield replaces the whole content, so a source
- // dropped from one yield would be erased from the message rather than merely not added.
- content = [
- ...state.tools.map(toolContent),
- ...state.sources.map(sourceContent),
- ...(state.text.length > 0
- ? [{ type: "text" as const, text: state.text }]
- : []),
- ...state.data.map((part) => ({
- type: "data" as const,
- name: part.name,
- data: part.data,
- })),
- ];
- yield { content, metadata: stage };
- }
-
- // A final yield carrying the same content, so the timing lands on the finished message
- // without blanking what was already drawn — `content` is optional on the result, but
- // omitting it here would make this yield the message's last word on its own content.
- yield { content, metadata: { ...stage, timing: clock.finish() } };
- },
- };
-
- return useLocalRuntime(adapter);
-}
diff --git a/demo/chat-ui/src/runtime/LocalThreadListAdapter.test.ts b/demo/chat-ui/src/runtime/LocalThreadListAdapter.test.ts
deleted file mode 100644
index d04c4d58..00000000
--- a/demo/chat-ui/src/runtime/LocalThreadListAdapter.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import assert from "node:assert/strict";
-import { describe, it } from "vitest";
-import { browserStorage } from "./LocalThreadListAdapter.ts";
-
-/** The smallest thing that behaves like `window.localStorage` for these tests. */
-function fakeStore(): Storage {
- const map = new Map();
-
- return {
- get length() {
- return map.size;
- },
- clear: () => map.clear(),
- getItem: (key: string) => map.get(key) ?? null,
- key: (index: number) => [...map.keys()][index] ?? null,
- removeItem: (key: string) => void map.delete(key),
- setItem: (key: string, value: string) => void map.set(key, value),
- };
-}
-
-describe("browserStorage", () => {
- it("round-trips a value", async () => {
- const storage = browserStorage(fakeStore());
-
- await storage.setItem("thread", "{}");
-
- assert.equal(await storage.getItem("thread"), "{}");
- });
-
- it("resolves null for a key that was never written", async () => {
- const storage = browserStorage(fakeStore());
-
- assert.equal(await storage.getItem("absent"), null);
- });
-
- it("removes a value", async () => {
- const storage = browserStorage(fakeStore());
- await storage.setItem("thread", "{}");
-
- await storage.removeItem("thread");
-
- assert.equal(await storage.getItem("thread"), null);
- });
-
- it("rejects rather than throwing when the store refuses a write", async () => {
- // What a browser in private mode does once its quota is refused. The adapter above us awaits
- // every call, so a synchronous throw here would escape as an unhandled error instead of a
- // rejected promise it can catch.
- const refusing = {
- ...fakeStore(),
- setItem: () => {
- throw new Error("QuotaExceededError");
- },
- } as Storage;
-
- await assert.rejects(() => browserStorage(refusing).setItem("thread", "{}"));
- });
-});
diff --git a/demo/chat-ui/src/runtime/LocalThreadListAdapter.ts b/demo/chat-ui/src/runtime/LocalThreadListAdapter.ts
deleted file mode 100644
index 5ea4300c..00000000
--- a/demo/chat-ui/src/runtime/LocalThreadListAdapter.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { createLocalStorageAdapter } from "@assistant-ui/core/react";
-import type { RemoteThreadListAdapter } from "@assistant-ui/react";
-
-/**
- * The thread list, stored in the browser and nowhere else.
- *
- * This file is a stub with a real seam behind it. AgentCore's server knows one call per
- * `X-AgentCore-Session` header and nothing about threads, and it has no notion of a caller to scope
- * threads to — the header names a call, not a person. Until it does, the list lives here.
- *
- * That the browser outlives the server's calls is safe, and only because of what `transport.ts`
- * already does: a turn answered `session_not_found` clears the id and retries with the whole
- * message list. A thread restored from storage after the server forgot its call heals on its next
- * turn rather than failing.
- *
- * The adapter itself is upstream's. `createLocalStorageAdapter` implements every method the thread
- * list needs and handles the exported-message-repository round trip, which is the fiddly part and
- * the part least worth writing twice. What is ours is the store beneath it and the name above it.
- *
- * When .NET grows a thread API, {@link localThreadListAdapter} is the one export that changes.
- * Nothing else in this application knows where threads come from.
- */
-
-/** Everything under this prefix in `localStorage` belongs to the thread list. */
-const StoragePrefix = "agentcore-threads";
-
-/**
- * Wraps a synchronous web {@link Storage} as the asynchronous store the adapter wants.
- *
- * The promises are what earn this function its existence. `createLocalStorageAdapter` awaits every
- * call, so a `localStorage` that throws — a browser in private mode, once it refuses the quota —
- * has to arrive as a rejection it can catch rather than as a synchronous throw escaping mid-await.
- *
- * @param store The browser store to read and write through.
- * @returns The same store, with each operation deferred into a promise.
- */
-export function browserStorage(store: Storage) {
- return {
- getItem: async (key: string) => store.getItem(key),
- setItem: async (key: string, value: string) => store.setItem(key, value),
- removeItem: async (key: string) => store.removeItem(key),
- };
-}
-
-/**
- * The thread list this application runs on.
- *
- * Built on first use rather than at module scope. The tests run under Node, which has no `window`,
- * and they import {@link browserStorage} from this same module — a `window.localStorage` read while
- * the module was evaluating would throw before a single test ran.
- *
- * @returns The adapter, the same instance on every call.
- */
-let adapter: RemoteThreadListAdapter | undefined;
-
-export function localThreadListAdapter(): RemoteThreadListAdapter {
- adapter ??= createLocalStorageAdapter({
- storage: browserStorage(window.localStorage),
- prefix: StoragePrefix,
- });
-
- return adapter;
-}
diff --git a/demo/chat-ui/src/runtime/transport.test.ts b/demo/chat-ui/src/runtime/transport.test.ts
deleted file mode 100644
index b8396689..00000000
--- a/demo/chat-ui/src/runtime/transport.test.ts
+++ /dev/null
@@ -1,548 +0,0 @@
-import assert from "node:assert/strict";
-import { describe, expect, it, test } from "vitest";
-import {
- SessionHeader,
- foldSource,
- readEvent,
- runTurn,
- splitEvents,
- wireMessages,
- type FetchLike,
- type Session,
-} from "./transport.ts";
-
-/**
- * What the browser does over the wire.
- *
- * No network and no browser: every test drives `runTurn` with a fetch of its own, so the failures
- * these cover — a half-read event, a session id kept past the end of its call, a 404 for a call the
- * host forgot — are reproduced exactly rather than waited for.
- */
-
-// -------------------------------------------------------------------------------------------------
-// Fakes.
-// -------------------------------------------------------------------------------------------------
-
-/** One recorded request. */
-type Sent = { session: string | null; body: unknown };
-
-/** Builds a response whose body arrives in exactly the pieces given. */
-function streaming(pieces: string[], headers: Record = {}): Response {
- const body = new ReadableStream({
- start(controller) {
- const encoder = new TextEncoder();
- for (const piece of pieces) {
- controller.enqueue(encoder.encode(piece));
- }
- controller.close();
- },
- });
-
- return new Response(body, { status: 200, headers });
-}
-
-/** Builds one refusal in the shape the endpoint writes. */
-function refusal(status: number, message: string, code?: string): Response {
- return new Response(JSON.stringify({ error: { message, code } }), {
- status,
- headers: { "Content-Type": "application/json" },
- });
-}
-
-/** A fetch that answers from a script and records what it was asked. */
-function scripted(responses: Response[]): { fetch: FetchLike; sent: Sent[] } {
- const sent: Sent[] = [];
- let index = 0;
-
- const fetch: FetchLike = (_url, init) => {
- const headers = (init.headers ?? {}) as Record;
- sent.push({
- session: headers[SessionHeader] ?? null,
- body: JSON.parse(String(init.body)),
- });
-
- const response = responses[index++];
- assert.ok(response, `the test scripted ${responses.length} answers and got one more request.`);
- return Promise.resolve(response);
- };
-
- return { fetch, sent };
-}
-
-/** One data event. */
-function event(payload: unknown): string {
- return `data: ${JSON.stringify(payload)}\n\n`;
-}
-
-/** One chunk that carries text. */
-function delta(text: string): string {
- return event({ choices: [{ delta: { content: text }, finish_reason: null }] });
-}
-
-/** Runs one turn to the end and collects every yield. */
-async function collect(
- responses: Response[],
- session: Session,
- messages: { role: string; content: string }[] = [{ role: "user", content: "hi" }],
-): Promise<{ yields: string[]; sent: Sent[] }> {
- const { fetch, sent } = scripted(responses);
- const yields: string[] = [];
-
- for await (const state of runTurn({
- endpoint: "/v1/chat/completions",
- session,
- messages: wireMessages(messages),
- abortSignal: new AbortController().signal,
- fetch,
- })) {
- yields.push(state.text);
- }
-
- return { yields, sent };
-}
-
-// -------------------------------------------------------------------------------------------------
-// The event reader. These are the pieces that a chunk boundary can break.
-// -------------------------------------------------------------------------------------------------
-
-test("splitEvents keeps an incomplete event back for the next read", () => {
- const { events, rest } = splitEvents("data: one\n\ndata: tw");
-
- assert.deepEqual(events, ["data: one"]);
- assert.equal(rest, "data: tw");
-});
-
-test("splitEvents returns nothing when no event is complete yet", () => {
- const { events, rest } = splitEvents("data: par");
-
- assert.deepEqual(events, []);
- assert.equal(rest, "data: par");
-});
-
-test("readEvent ignores the terminator", () => {
- assert.equal(readEvent("data: [DONE]"), null);
-});
-
-test("readEvent ignores a line that is not data", () => {
- assert.equal(readEvent(": keep-alive"), null);
-});
-
-// -------------------------------------------------------------------------------------------------
-// The request body.
-// -------------------------------------------------------------------------------------------------
-
-test("wireMessages drops a message left with no text", () => {
- const wire = wireMessages([
- { role: "user", content: "hello" },
- { role: "assistant", content: "" },
- ]);
-
- assert.deepEqual(wire, [{ role: "user", content: "hello" }]);
-});
-
-// -------------------------------------------------------------------------------------------------
-// The session, which is the whole reason this file exists.
-// -------------------------------------------------------------------------------------------------
-
-test("the first turn names no session and keeps the one the host answers with", async () => {
- const session: Session = { current: null };
-
- const { sent } = await collect(
- [streaming([delta("hi")], { [SessionHeader]: "call-1" })],
- session,
- );
-
- assert.equal(sent[0]!.session, null, "a first turn must not name a call that does not exist.");
- assert.equal(session.current, "call-1");
-});
-
-test("the next turn sends the session back", async () => {
- const session: Session = { current: "call-1" };
-
- const { sent } = await collect([streaming([delta("again")])], session);
-
- assert.equal(sent[0]!.session, "call-1");
-});
-
-test("a terminal turn lets the call go, so the next one opens a new call", async () => {
- // Holding the id past the end of a call answers the next message with a 409, and the UI would
- // show a chat that refuses everything from then on.
- const session: Session = { current: null };
-
- await collect(
- [
- streaming(
- [
- delta("goodbye"),
- event({ choices: [{ delta: {}, finish_reason: "stop" }], agentcore: { is_terminal: true } }),
- ],
- { [SessionHeader]: "call-1" },
- ),
- ],
- session,
- );
-
- assert.equal(session.current, null);
-});
-
-test("a non-terminal turn keeps the call", async () => {
- const session: Session = { current: null };
-
- await collect(
- [
- streaming(
- [
- delta("still here"),
- event({ choices: [{ delta: {}, finish_reason: "stop" }], agentcore: { is_terminal: false } }),
- ],
- { [SessionHeader]: "call-1" },
- ),
- ],
- session,
- );
-
- assert.equal(session.current, "call-1");
-});
-
-test("a call the host has forgotten is started again rather than failing the turn", async () => {
- // The default session store does not survive a restart, so this is what every open tab sees the
- // first time somebody redeploys.
- const session: Session = { current: "gone" };
-
- const { yields, sent } = await collect(
- [
- refusal(404, "no call named 'gone' is open on this host.", "session_not_found"),
- streaming([delta("fresh start")], { [SessionHeader]: "call-2" }),
- ],
- session,
- );
-
- assert.equal(sent.length, 2);
- assert.equal(sent[0]!.session, "gone");
- assert.equal(sent[1]!.session, null, "the retry must not name the call that is gone.");
- assert.equal(session.current, "call-2");
- assert.deepEqual(yields, ["fresh start"]);
-});
-
-test("a 404 that is not a lost session is not retried", async () => {
- const session: Session = { current: "call-1" };
-
- await assert.rejects(
- () => collect([refusal(404, "the route is not mapped here.")], session),
- /the route is not mapped here/,
- );
-});
-
-test("a refused turn surfaces what the host said", async () => {
- const session: Session = { current: "call-1" };
-
- await assert.rejects(
- () => collect([refusal(409, "this call is finished.", "turn_refused")], session),
- /this call is finished/,
- );
-});
-
-// -------------------------------------------------------------------------------------------------
-// The reply.
-// -------------------------------------------------------------------------------------------------
-
-test("the reply grows with each piece", async () => {
- const session: Session = { current: null };
-
- const { yields } = await collect(
- [streaming([delta("Hel"), delta("lo "), delta("there")])],
- session,
- );
-
- assert.deepEqual(yields, ["Hel", "Hello ", "Hello there"]);
-});
-
-test("an event split across two reads is still read once, whole", async () => {
- // The regression this catches loses whole words silently, and only under load: the split happens
- // wherever the network happened to break the stream.
- const session: Session = { current: null };
- const whole = delta("split me");
- const at = Math.floor(whole.length / 2);
-
- const { yields } = await collect(
- [streaming([whole.slice(0, at), whole.slice(at)])],
- session,
- );
-
- assert.deepEqual(yields, ["split me"]);
-});
-
-test("two events arriving in one read are both read", async () => {
- const session: Session = { current: null };
-
- const { yields } = await collect([streaming([delta("one") + delta("two")])], session);
-
- assert.deepEqual(yields, ["one", "onetwo"]);
-});
-
-test("the terminator ends the stream without becoming text", async () => {
- const session: Session = { current: null };
-
- const { yields } = await collect([streaming([delta("done"), "data: [DONE]\n\n"])], session);
-
- assert.deepEqual(yields, ["done"]);
-});
-
-test("a chunk that carries no text yields nothing", async () => {
- const session: Session = { current: null };
-
- const { yields } = await collect(
- [streaming([event({ choices: [{ delta: { role: "assistant" } }] }), delta("after")])],
- session,
- );
-
- assert.deepEqual(yields, ["after"]);
-});
-
-test("runTurn yields data parts alongside the text", async () => {
- const events = [
- 'data: {"choices":[{"delta":{"content":"here it is"}}]}\n\n',
- 'data: {"agentcore_data":{"name":"chart","data":{"title":"Q3"}}}\n\n',
- "data: [DONE]\n\n",
- ];
-
- const session: Session = { current: null };
- const states = [];
- for await (const state of runTurn({
- endpoint: "/v1/chat/completions",
- session,
- messages: [{ role: "user", content: "chart it" }],
- abortSignal: new AbortController().signal,
- fetch: scripted([streaming(events)]).fetch,
- })) {
- states.push(state);
- }
-
- const last = states[states.length - 1];
- assert.equal(last.text, "here it is");
- assert.deepEqual(last.data, [{ name: "chart", data: { title: "Q3" } }]);
-});
-
-test("a data part survives a later text-only yield", async () => {
- // The runtime replaces message content on every yield, so a state that forgot the drawing would
- // blank it from the screen the moment the model spoke again.
- const events = [
- 'data: {"agentcore_data":{"name":"chart","data":{"title":"Q3"}}}\n\n',
- 'data: {"choices":[{"delta":{"content":"and that is why"}}]}\n\n',
- "data: [DONE]\n\n",
- ];
-
- const session: Session = { current: null };
- const states = [];
- for await (const state of runTurn({
- endpoint: "/v1/chat/completions",
- session,
- messages: [{ role: "user", content: "chart it" }],
- abortSignal: new AbortController().signal,
- fetch: scripted([streaming(events)]).fetch,
- })) {
- states.push(state);
- }
-
- const last = states[states.length - 1];
- assert.equal(last.text, "and that is why");
- assert.deepEqual(last.data, [{ name: "chart", data: { title: "Q3" } }]);
-});
-
-// -------------------------------------------------------------------------------------------------
-// Tool calls. The host runs the tool, so both halves arrive as facts and neither asks for anything.
-// -------------------------------------------------------------------------------------------------
-
-/** Runs one turn over the events given and answers every state it yielded. */
-async function states(events: string[]) {
- const collected = [];
- for await (const state of runTurn({
- endpoint: "/v1/chat/completions",
- session: { current: null },
- messages: [{ role: "user", content: "look it up" }],
- abortSignal: new AbortController().signal,
- fetch: scripted([streaming(events)]).fetch,
- })) {
- collected.push(state);
- }
-
- return collected;
-}
-
-test("runTurn yields a tool call before its result arrives", async () => {
- // The point of showing a tool at all is showing it while it runs, so the call half must reach the
- // screen on its own rather than waiting to be paired with a result.
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"call","arguments":{"what":"revenue"}}}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.deepEqual(last.tools, [
- { callId: "c1", name: "read_records", arguments: { what: "revenue" } },
- ]);
-});
-
-test("runTurn keeps a tool answer that is an object as an object", async () => {
- // The host writes the answer as JSON rather than as text, so that the quotes inside it are not
- // escaped and the panel can lay it out. A result read as a string would print those escapes raw.
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"call","arguments":{}}}\n\n',
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"result","result":{"entities":["it\'s"]},"failed":false}}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.deepEqual(last.tools[0].result, { entities: ["it's"] });
-});
-
-test("runTurn folds a tool result onto the call it answers", async () => {
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"call","arguments":{"what":"revenue"}}}\n\n',
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"result","result":"42 rows","failed":false}}\n\n',
- 'data: {"choices":[{"delta":{"content":"there are 42."}}]}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.equal(last.text, "there are 42.");
- assert.deepEqual(last.tools, [
- {
- callId: "c1",
- name: "read_records",
- arguments: { what: "revenue" },
- result: "42 rows",
- failed: false,
- },
- ]);
-});
-
-test("runTurn keeps a failed tool marked as failed", async () => {
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"call","arguments":{}}}\n\n',
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"result","result":"the table is gone","failed":true}}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.equal(last.tools[0]?.failed, true);
- assert.equal(last.tools[0]?.result, "the table is gone");
-});
-
-test("runTurn keeps two tool calls apart and pairs each with its own result", async () => {
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"call","arguments":{}}}\n\n',
- 'data: {"agentcore_tool":{"call_id":"c2","name":"aggregate_records","phase":"call","arguments":{}}}\n\n',
- 'data: {"agentcore_tool":{"call_id":"c2","name":"aggregate_records","phase":"result","result":"second","failed":false}}\n\n',
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"result","result":"first","failed":false}}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.deepEqual(
- last.tools.map((tool) => [tool.callId, tool.result]),
- [
- ["c1", "first"],
- ["c2", "second"],
- ],
- );
-});
-
-test("a tool survives a later text-only yield", async () => {
- // Same rule as a drawing: the runtime replaces message content on every yield, so a state that
- // forgot the tool would blank it the moment the model spoke.
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c1","name":"read_records","phase":"call","arguments":{}}}\n\n',
- 'data: {"choices":[{"delta":{"content":"one moment"}}]}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.equal(last.text, "one moment");
- assert.equal(last.tools.length, 1);
-});
-
-test("a result for a call that never arrived is kept rather than dropped", async () => {
- // It should not happen. If it ever does, showing the answer with no question beats showing
- // nothing at all and leaving the caller wondering what the wait was for.
- const collected = await states([
- 'data: {"agentcore_tool":{"call_id":"c9","name":"read_records","phase":"result","result":"orphan","failed":false}}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- const last = collected[collected.length - 1];
- assert.deepEqual(last.tools, [
- { callId: "c9", name: "read_records", arguments: {}, result: "orphan", failed: false },
- ]);
-});
-
-test("a turn that calls no tool yields an empty tool list", async () => {
- const collected = await states([
- 'data: {"choices":[{"delta":{"content":"hello"}}]}\n\n',
- "data: [DONE]\n\n",
- ]);
-
- assert.deepEqual(collected[collected.length - 1].tools, []);
-});
-
-// -------------------------------------------------------------------------------------------------
-// Sources. The host cites them, the browser folds them, and nothing draws them yet.
-// -------------------------------------------------------------------------------------------------
-
-describe("foldSource", () => {
- const frame = {
- call_id: "call-1",
- id: "card-42",
- source_type: "document",
- title: "Spirit CT900 owner's manual",
- locator: "p.27",
- url: null,
- media_type: "text/plain",
- origin: "knowledge",
- };
-
- it("reads one source off the wire", () => {
- const [source] = foldSource([], frame);
-
- expect(source).toEqual({
- id: "card-42",
- sourceType: "document",
- title: "Spirit CT900 owner's manual",
- locator: "p.27",
- url: null,
- mediaType: "text/plain",
- origin: "knowledge",
- callId: "call-1",
- });
- });
-
- it("shows one chip when the same id is cited twice", () => {
- // Two searches in one turn can return the same card. Two identical chips are noise.
- const once = foldSource([], frame);
- const twice = foldSource(once, { ...frame, title: "second" });
-
- expect(twice).toHaveLength(1);
- expect(twice[0]?.title).toBe("second");
- });
-
- it("drops a frame with no id, because nothing can be kept in step without one", () => {
- expect(foldSource([], { ...frame, id: undefined })).toHaveLength(0);
- });
-
- it("treats an unknown source_type as a document, which needs no link", () => {
- const [source] = foldSource([], { ...frame, source_type: "wat" });
-
- expect(source?.sourceType).toBe("document");
- });
-
- it("keeps a url source's link", () => {
- const [source] = foldSource([], {
- ...frame,
- source_type: "url",
- url: "https://example.com/support",
- });
-
- expect(source?.sourceType).toBe("url");
- expect(source?.url).toBe("https://example.com/support");
- });
-});
diff --git a/demo/chat-ui/src/runtime/transport.ts b/demo/chat-ui/src/runtime/transport.ts
deleted file mode 100644
index 6ccf3447..00000000
--- a/demo/chat-ui/src/runtime/transport.ts
+++ /dev/null
@@ -1,517 +0,0 @@
-/**
- * Everything the chat UI does over the wire, with no React and no assistant-ui in sight.
- *
- * This file is separate from {@link ./AgentCoreRuntime.ts} so it can be tested. The parts that are
- * easy to get wrong here — a server-sent event split across two reads, a session id that outlives
- * the call it names, a 404 for a call the host forgot — all fail in ways a browser shows as a chat
- * that simply stops working, with nothing in any log. The hook is a thin wrapper over this.
- */
-
-/** The header that names the call, on the request and on the answer. */
-export const SessionHeader = "X-AgentCore-Session";
-
-/**
- * The header naming the stage the turn speaks in.
- *
- * It arrives with the response headers, before the first token, which is the only reason the stage
- * can be shown while the turn is still running: the `agentcore` block that carries `stage_after`
- * rides the *last* chunk, so it says where the machine ended up, never where it is.
- */
-export const StageHeader = "X-AgentCore-Stage";
-
-/** The prefix every server-sent event carries. */
-const DataPrefix = "data: ";
-
-/** The event that closes a stream. */
-const DoneEvent = "[DONE]";
-
-/** One message, in the only shape AgentCore's endpoint reads. */
-export type WireMessage = {
- readonly role: string;
- readonly content: string;
-};
-
-/**
- * Who produced a message, when that is not simply "the agent".
- *
- * Nothing sends this yet. It is declared here so the browser already has somewhere to put a human
- * rep the day AgentCore can hand a conversation to one: the wire, the runtime and the message
- * metadata are the three places that would otherwise all need changing at once, under time
- * pressure, while a customer is waiting on the other end of a live handoff.
- *
- * The contract AgentCore would emit, beside the OpenAI shape and alongside `agentcore`:
- *
- * "agentcore_speaker": { "kind": "human", "name": "Dana R.", "detail": "Support" }
- */
-export type Speaker = {
- /** `agent` is the model, `human` a real person, `system` the host speaking for itself. */
- readonly kind: "agent" | "human" | "system";
- readonly name: string;
- /** A role, team, or anything else worth showing under the name. Optional. */
- readonly detail?: string;
-};
-
-/** One thing the host asked the browser to draw. */
-export type RenderPart = {
- readonly name: string;
- readonly data: unknown;
-};
-
-/**
- * One source the host cited, as the browser holds it.
- *
- * Producer-neutral by design: `origin` names what produced it — `knowledge` today — so a later web
- * search or parts lookup arrives on the same field and draws with the same component.
- */
-export type SourcePart = {
- readonly id: string;
- readonly sourceType: "document" | "url";
- readonly title: string;
- /** Where inside the source it sits, such as `p.27`. Empty when the producer has none. */
- readonly locator: string;
- /** The link to open, or `null` when there is nothing to open. A document has none. */
- readonly url: string | null;
- readonly mediaType: string;
- /** What produced it, such as `knowledge`. */
- readonly origin: string;
- /** The tool call it was cited under. */
- readonly callId: string;
-};
-
-/** One source as the wire spells it. Every field is optional: the browser never trusts the host's shape. */
-export type SourceFrame = {
- call_id?: string;
- id?: string;
- source_type?: string;
- title?: string;
- locator?: string;
- url?: string | null;
- media_type?: string;
- origin?: string;
-};
-
-/** Anything `JSON.parse` can produce. */
-export type JsonValue =
- | string
- | number
- | boolean
- | null
- | readonly JsonValue[]
- | { readonly [key: string]: JsonValue };
-
-/** A JSON object, which is the only shape a tool's arguments ever take. */
-export type JsonObject = { readonly [key: string]: JsonValue };
-
-/**
- * One tool the host ran, with its result once it has one.
- *
- * Both halves of a call arrive as separate chunks and are folded together here, because the screen
- * wants one row per tool that fills in, and not two rows that have to be matched up by whoever draws
- * them. A part with no `result` yet is a tool still running.
- *
- * This is a *report* and never a request. AgentCore owns the tool loop, so nothing the browser does
- * with this can make a tool run, and the OpenAI `tool_calls` field — which does mean "you run this"
- * — is deliberately not what carries it.
- */
-export type ToolPart = {
- readonly callId: string;
- readonly name: string;
- readonly arguments: JsonObject;
- /** What the tool answered, in whatever shape it answered in. Absent while it is still running. */
- readonly result?: unknown;
- /** Whether the tool failed. Absent while it is still running. */
- readonly failed?: boolean;
-};
-
-/** Everything one turn has produced so far. */
-export type TurnState = {
- readonly text: string;
- readonly data: readonly RenderPart[];
- /** Every tool this turn has called, in call order, each with its result once it has one. */
- readonly tools: readonly ToolPart[];
- /** Every source this turn cited, in cite order. */
- readonly sources: readonly SourcePart[];
- /** The stage the pipeline is in: the turn's own stage, then the stage it moved to at the end. */
- readonly stage: string | null;
- /** Whether the stage the turn moved to ends the call. Only ever true on the final state. */
- readonly isTerminal: boolean;
- /** Who is speaking, when the host says. `null` means the agent, which is the only case today. */
- readonly speaker: Speaker | null;
- /** What the host called this reply, once it says. Null until the final chunk carries it. */
- readonly replyMessageId: string | null;
-};
-
-/** The id of the open call, held for the life of the tab. */
-export type Session = {
- current: string | null;
-};
-
-/** The part of `fetch` this module uses, so a test can hand it one that reaches no network. */
-export type FetchLike = (url: string, init: RequestInit) => Promise;
-
-/** Where the caller says a turn's words hang, in the conversation it draws. */
-export type TurnOrigin = {
- /** What this client calls the message it is sending. */
- readonly message_id?: string;
- /**
- * What this client calls the message the new one hangs off, or null at the root of the call.
- *
- * The host withdraws everything the call said after this message before it runs the turn. On an
- * ordinary send that is the last thing the call said, so nothing goes; it is an edit exactly when
- * the parent is further back, and then the answers to the replaced question stop reaching the
- * model.
- */
- readonly parent_id?: string | null;
-};
-
-/** What one turn needs to run. */
-export type TurnOptions = {
- readonly endpoint: string;
- readonly session: Session;
- readonly messages: readonly WireMessage[];
- readonly abortSignal: AbortSignal;
- readonly fetch: FetchLike;
- /** Omitted by a caller that does not track its messages by name. */
- readonly origin?: TurnOrigin;
-};
-
-/** What the endpoint adds beside the OpenAI shape on the last chunk of a stream. */
-type TurnInfo = {
- session?: string;
- stage_before?: string;
- stage_after?: string;
- is_terminal?: boolean;
- /**
- * What the host called the reply it just wrote.
- *
- * Needed because the message an edit hangs off is usually a reply, and a reply has no name until
- * the host writes it — so this client cannot invent one and has to be told.
- */
- message_id?: string;
-};
-
-/** One half of one tool call, as the endpoint writes it. */
-type ToolFrame = {
- call_id?: string;
- name?: string;
- phase?: string;
- /** Typed rather than `unknown` because it comes off `JSON.parse` of a field the host writes as an object. */
- arguments?: JsonObject;
- /** The host writes the answer as JSON, so this is an object as often as it is a string. */
- result?: unknown;
- failed?: boolean;
-};
-
-/** One chunk of a streamed answer. */
-type StreamChunk = {
- choices?: { delta?: { content?: string }; finish_reason?: string | null }[];
- agentcore?: TurnInfo;
- agentcore_tool?: ToolFrame;
- agentcore_data?: RenderPart;
- agentcore_source?: SourceFrame;
- agentcore_speaker?: Speaker;
-};
-
-/** The body of one refusal. */
-type WireError = {
- error?: { message?: string; code?: string };
-};
-
-/**
- * Drops everything the endpoint cannot read.
- *
- * AgentCore's endpoint reads text and no other content part, and answers a request with no user
- * text at all with a 400. A message left empty by that filter would be one of those, so it goes.
- */
-export function wireMessages(
- messages: readonly { role: string; content: string }[],
-): WireMessage[] {
- return messages
- .map((message) => ({ role: message.role, content: message.content }))
- .filter((message) => message.content.length > 0);
-}
-
-/**
- * Splits whatever has arrived into whole events and whatever is still incomplete.
- *
- * An event ends at a blank line and a read can end anywhere, so the tail of a read is very often
- * half an event. Returning it rather than parsing it is the whole job.
- *
- * @param buffer Everything read and not yet parsed.
- * @returns The complete events, and the remainder to prepend to the next read.
- */
-export function splitEvents(buffer: string): { events: string[]; rest: string } {
- const parts = buffer.split("\n\n");
- const rest = parts.pop() ?? "";
- return { events: parts, rest };
-}
-
-/**
- * Reads one event.
- *
- * @param event One event, as it arrived.
- * @returns The chunk, or `null` for the terminator and for anything that is not a data line.
- */
-export function readEvent(event: string): StreamChunk | null {
- const line = event.trim();
- if (!line.startsWith(DataPrefix)) {
- return null;
- }
-
- const payload = line.slice(DataPrefix.length);
- if (payload === DoneEvent) {
- return null;
- }
-
- return JSON.parse(payload) as StreamChunk;
-}
-
-/** Reads the failure the endpoint wrote, or falls back to the status line. */
-async function failureOf(response: Response): Promise<{ message: string; code?: string }> {
- try {
- const body = (await response.json()) as WireError;
- if (body.error?.message) {
- return { message: body.error.message, code: body.error.code };
- }
- } catch {
- // A body that is not the documented shape tells us nothing the status line does not.
- }
-
- return { message: `the request failed with status ${response.status}.` };
-}
-
-/** Posts one turn. */
-function post(options: TurnOptions, session: string | null): Promise {
- const headers: Record = { "Content-Type": "application/json" };
- if (session) {
- headers[SessionHeader] = session;
- }
-
- return options.fetch(options.endpoint, {
- method: "POST",
- headers,
- body: JSON.stringify({
- messages: options.messages,
- stream: true,
- ...(options.origin ? { agentcore: options.origin } : {}),
- }),
- signal: options.abortSignal,
- });
-}
-
-/**
- * Folds one tool frame into the list the state carries.
- *
- * @param tools What the turn has called so far.
- * @param frame The half that just arrived.
- * @returns A new list. Never the one passed in: the state yielded before this is read after it, so
- * a list mutated in place would change under a consumer that already has it.
- */
-export function foldTool(
- tools: readonly ToolPart[],
- frame: ToolFrame,
-): readonly ToolPart[] {
- const callId = frame.call_id;
- if (!callId) {
- return tools;
- }
-
- const name = frame.name ?? callId;
-
- if (frame.phase !== "result") {
- return [...tools, { callId, name, arguments: frame.arguments ?? {} }];
- }
-
- const answered: ToolPart = {
- callId,
- name,
- arguments: {},
- result: frame.result ?? "",
- failed: frame.failed ?? false,
- };
-
- const index = tools.findIndex((tool) => tool.callId === callId);
- if (index < 0) {
- // A result with no call before it should not happen. Showing the answer with no question still
- // beats showing nothing and leaving the caller wondering what the wait was for.
- return [...tools, answered];
- }
-
- const merged = [...tools];
- merged[index] = { ...tools[index], ...answered, arguments: tools[index].arguments };
- return merged;
-}
-
-/**
- * Folds one wire frame into the sources held so far.
- *
- * Keyed by id, last write winning in the place the first took: the host already de-duplicates
- * within a turn, and this holds the line for a stream that reconnects mid-turn.
- */
-export function foldSource(
- sources: readonly SourcePart[],
- frame: SourceFrame,
-): readonly SourcePart[] {
- const id = frame.id;
- if (!id) {
- return sources;
- }
-
- const part: SourcePart = {
- id,
- sourceType: frame.source_type === "url" ? "url" : "document",
- title: frame.title ?? id,
- locator: frame.locator ?? "",
- url: frame.url ?? null,
- mediaType: frame.media_type ?? "text/plain",
- origin: frame.origin ?? "",
- callId: frame.call_id ?? "",
- };
-
- const at = sources.findIndex((existing) => existing.id === id);
- if (at < 0) {
- return [...sources, part];
- }
-
- const next = [...sources];
- next[at] = part;
- return next;
-}
-
-/**
- * Runs one turn and yields the reply as it grows.
- *
- * Each yield is the whole reply so far rather than the newest piece, because that is what the
- * runtime above renders.
- *
- * @param options What the turn needs.
- * @returns The reply, yielded once per piece that carries text or something to draw.
- * @throws Error The host refused the turn, or answered with no body.
- */
-export async function* runTurn(options: TurnOptions): AsyncGenerator {
- const { session } = options;
-
- let response = await post(options, session.current);
-
- // The store does not survive a restart of the host, so an id from before one names a call that is
- // gone. Starting a new call is what the caller wanted; failing the turn over an id they never saw
- // is not.
- if (response.status === 404) {
- const failure = await failureOf(response);
- if (failure.code !== "session_not_found") {
- throw new Error(failure.message);
- }
-
- session.current = null;
- response = await post(options, null);
- }
-
- if (!response.ok) {
- throw new Error((await failureOf(response)).message);
- }
-
- // The answer names the call whether it started one or continued one, and the header arrives
- // before the first token does.
- const named = response.headers.get(SessionHeader);
- if (named) {
- session.current = named;
- }
-
- if (!response.body) {
- throw new Error("the host answered with no body, so there is nothing to read.");
- }
-
- // Named before the first token, so the very first yield already knows the stage.
- let stage = response.headers.get(StageHeader);
- let isTerminal = false;
- let speaker: Speaker | null = null;
- let replyMessageId: string | null = null;
-
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
- let pending = "";
- let text = "";
- let data: RenderPart[] = [];
- let tools: readonly ToolPart[] = [];
- let sources: readonly SourcePart[] = [];
-
- try {
- for (; ;) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
-
- pending += value;
-
- const { events, rest } = splitEvents(pending);
- pending = rest;
-
- for (const event of events) {
- const chunk = readEvent(event);
- if (!chunk) {
- continue;
- }
-
- // The last chunk of a finished call carries is_terminal. Holding on to the id past that
- // point would answer the next message with a 409, so the call is let go and the next turn
- // opens a new one.
- if (chunk.agentcore?.is_terminal) {
- session.current = null;
- }
-
- // The last chunk is the first place that knows where the machine moved to.
- // Sticky: a handoff names the speaker once, and every chunk after it belongs to them.
- speaker = chunk.agentcore_speaker ?? speaker;
-
- const state = () => ({
- text,
- data,
- tools,
- sources,
- stage,
- isTerminal,
- speaker,
- replyMessageId,
- });
-
- const info = chunk.agentcore;
- if (info) {
- stage = info.stage_after ?? stage;
- isTerminal = info.is_terminal ?? isTerminal;
- replyMessageId = info.message_id ?? replyMessageId;
- yield state();
- }
-
- const rendered = chunk.agentcore_data;
- if (rendered) {
- // A new array each time: the yielded state is read after the yield, so the consumer must
- // never see a list this loop keeps changing underneath it.
- data = [...data, rendered];
- yield state();
- }
-
- const tool = chunk.agentcore_tool;
- if (tool) {
- tools = foldTool(tools, tool);
- yield state();
- }
-
- const source = chunk.agentcore_source;
- if (source) {
- sources = foldSource(sources, source);
- yield state();
- }
-
- const delta = chunk.choices?.[0]?.delta?.content;
- if (delta) {
- text += delta;
- yield state();
- }
- }
- }
- } finally {
- reader.cancel().catch(() => {
- // The turn is over either way, and a reader that will not close is not worth a failure.
- });
- }
-}
diff --git a/demo/chat-ui/src/vite-env.d.ts b/demo/chat-ui/src/vite-env.d.ts
deleted file mode 100644
index 11f02fe2..00000000
--- a/demo/chat-ui/src/vite-env.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-///
diff --git a/demo/chat-ui/src/widget-main.tsx b/demo/chat-ui/src/widget-main.tsx
deleted file mode 100644
index e143447e..00000000
--- a/demo/chat-ui/src/widget-main.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { StrictMode } from "react";
-import { createRoot } from "react-dom/client";
-import { Widget } from "./Widget";
-import "./index.css";
-
-createRoot(document.getElementById("root")!).render(
-
-
- ,
-);
diff --git a/demo/chat-ui/tsconfig.app.json b/demo/chat-ui/tsconfig.app.json
deleted file mode 100644
index c461d319..00000000
--- a/demo/chat-ui/tsconfig.app.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "lib": [
- "ES2022",
- "DOM",
- "DOM.Iterable"
- ],
- "module": "ESNext",
- "moduleResolution": "bundler",
- "jsx": "react-jsx",
- "strict": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true,
- "noUncheckedSideEffectImports": true,
- "isolatedModules": true,
- "verbatimModuleSyntax": true,
- "moduleDetection": "force",
- "skipLibCheck": true,
- "noEmit": true,
- "baseUrl": ".",
- "paths": {
- "@/*": [
- "./src/*"
- ]
- },
- // Node runs the tests straight from source with no bundler, and its resolver wants the real
- // file name. The app never emits, so the extension costs nothing here.
- "allowImportingTsExtensions": true,
- "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
- },
- "include": [
- "src"
- ],
- "exclude": [
- "src/**/*.test.tsx",
- "src/**/*.test.ts"
- ]
-}
\ No newline at end of file
diff --git a/demo/chat-ui/tsconfig.json b/demo/chat-ui/tsconfig.json
deleted file mode 100644
index 1389c679..00000000
--- a/demo/chat-ui/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "files": [],
- "references": [
- { "path": "./tsconfig.app.json" },
- { "path": "./tsconfig.test.json" },
- { "path": "./tsconfig.node.json" }
- ],
- // Not used for compilation — this is a solution file and `files` is empty. It is here so the
- // shadcn CLI can resolve `@/components` when it vendors assistant-ui's files: the CLI reads the
- // root tsconfig alone, and without this it writes them to a literal `@/` directory.
- "compilerOptions": {
- "baseUrl": ".",
- "paths": {
- "@/*": ["./src/*"]
- }
- }
-}
diff --git a/demo/chat-ui/tsconfig.node.json b/demo/chat-ui/tsconfig.node.json
deleted file mode 100644
index e7bd9ac9..00000000
--- a/demo/chat-ui/tsconfig.node.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2023",
- "lib": ["ES2023"],
- "module": "ESNext",
- "moduleResolution": "bundler",
- "strict": true,
- "isolatedModules": true,
- "verbatimModuleSyntax": true,
- "moduleDetection": "force",
- "skipLibCheck": true,
- "noEmit": true,
- "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
- },
- "include": ["vite.config.ts"]
-}
diff --git a/demo/chat-ui/tsconfig.test.json b/demo/chat-ui/tsconfig.test.json
deleted file mode 100644
index 9457c4ef..00000000
--- a/demo/chat-ui/tsconfig.test.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2023",
- "lib": [
- "ES2023",
- "DOM"
- ],
- "module": "ESNext",
- "moduleResolution": "bundler",
- // The renderer tests mount React, so this project compiles JSX and resolves the same "@"
- // alias the app and the vendored components use.
- "jsx": "react-jsx",
- "baseUrl": ".",
- "paths": {
- "@/*": [
- "./src/*"
- ]
- },
- "types": [
- "node"
- ],
- "strict": true,
- "isolatedModules": true,
- "verbatimModuleSyntax": true,
- "moduleDetection": "force",
- "skipLibCheck": true,
- "noEmit": true,
- "allowImportingTsExtensions": true,
- "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.test.tsbuildinfo"
- },
- "include": [
- "src/runtime/transport.ts",
- "src/**/*.test.ts",
- "src/**/*.test.tsx"
- ]
-}
\ No newline at end of file
diff --git a/demo/chat-ui/vite.config.ts b/demo/chat-ui/vite.config.ts
deleted file mode 100644
index a0d4b927..00000000
--- a/demo/chat-ui/vite.config.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-///
-import tailwindcss from "@tailwindcss/vite";
-import react from "@vitejs/plugin-react";
-import { fileURLToPath, URL } from "node:url";
-import { defineConfig } from "vite";
-import { resolve } from "node:path";
-
-// The build writes into the demo host's wwwroot, which serves it as static files at /chat.
-export default defineConfig({
- plugins: [react(), tailwindcss()],
- base: "/chat/",
- // The vendored components under src/components are assistant-ui's own and import through this
- // alias. It is not a style preference: rewriting their imports would make every future
- // `shadcn add` a merge instead of an overwrite.
- resolve: {
- alias: {
- "@": fileURLToPath(new URL("./src", import.meta.url)),
- },
- },
- build: {
- outDir: "../AgentCore.Demo/wwwroot/chat",
- emptyOutDir: true,
- rollupOptions: {
- // Two pages, one bundle of shared chunks. `index` is the full app at /chat; `widget` is the
- // embeddable bubble at /chat/widget.html, framed by public/embed.js.
- input: {
- index: resolve(__dirname, "index.html"),
- widget: resolve(__dirname, "widget.html"),
- },
- },
- },
- // Vitest reads this block, so the runner needs no config file of its own.
- test: {
- // The renderer tests mount React, so they need a DOM. The old `node --test` runner could not
- // even load a .tsx file.
- environment: "happy-dom",
- include: ["src/**/*.test.{ts,tsx}"],
- },
- server: {
- // The dev server serves the UI and forwards the API to the running host, so `npm run dev` and
- // `dotnet run` together give hot reload against a real turn loop.
- proxy: {
- "/v1": "http://127.0.0.1:5199",
- },
- },
-});
diff --git a/demo/chat-ui/widget.html b/demo/chat-ui/widget.html
deleted file mode 100644
index 6bf80519..00000000
--- a/demo/chat-ui/widget.html
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
- SpiritAI
-
-
-
-
-
-
-
diff --git a/src/AgentCore.Application/AgentCore.Application.csproj b/src/AgentCore.Application/AgentCore.Application.csproj
index 0b947998..598d11cd 100644
--- a/src/AgentCore.Application/AgentCore.Application.csproj
+++ b/src/AgentCore.Application/AgentCore.Application.csproj
@@ -4,6 +4,11 @@
true
Orchestration, configuration compilation, and every port interface.
agent;ai;voice;chat;orchestration
+
+ $(NoWarn);NU5104
@@ -16,6 +21,7 @@
+
diff --git a/src/AgentCore.Application/Audit/QueuedAuditSink.cs b/src/AgentCore.Application/Audit/QueuedAuditSink.cs
index eae033de..ad2d0738 100644
--- a/src/AgentCore.Application/Audit/QueuedAuditSink.cs
+++ b/src/AgentCore.Application/Audit/QueuedAuditSink.cs
@@ -80,7 +80,7 @@ public QueuedAuditSink(
SingleWriter = false,
});
- _writer = Task.Run(WriteAsync);
+ _writer = Task.Run(WriteAsync, CancellationToken.None);
}
///
@@ -153,7 +153,7 @@ private async Task DrainedAsync()
{
try
{
- await _writer.WaitAsync(DisposeTimeout).ConfigureAwait(false);
+ await _writer.WaitAsync(DisposeTimeout, CancellationToken.None).ConfigureAwait(false);
return true;
}
#pragma warning disable CA1031 // A drain that failed has already reported itself, and disposal never throws.
@@ -171,7 +171,7 @@ private async Task WriteAsync()
{
List batch = new(_batchSize);
- while (await _queue.Reader.WaitToReadAsync().ConfigureAwait(false))
+ while (await _queue.Reader.WaitToReadAsync(CancellationToken.None).ConfigureAwait(false))
{
// Everything waiting goes in one batch, so the store pays one round trip for a burst
// rather than one for each event of it.
diff --git a/src/AgentCore.Application/Call/.editorconfig b/src/AgentCore.Application/Call/.editorconfig
deleted file mode 100644
index 5f2976f4..00000000
--- a/src/AgentCore.Application/Call/.editorconfig
+++ /dev/null
@@ -1,8 +0,0 @@
-[*.cs]
-
-# CA1716: "Rename namespace AgentCore.Application.Call so that it no longer conflicts with the
-# reserved language keyword 'Call'." This assembly does not target VB.NET or other languages that
-# reserve the word, and the namespace name is deliberate: task 0 of the call-transport-seam plan
-# renamed the call's text pipe out of Speech and into Call, matching the folder, and every later
-# task in that plan depends on this name.
-dotnet_diagnostic.CA1716.severity = none
diff --git a/src/AgentCore.Application/Call/CallChannel.cs b/src/AgentCore.Application/Calls/CallChannel.cs
similarity index 98%
rename from src/AgentCore.Application/Call/CallChannel.cs
rename to src/AgentCore.Application/Calls/CallChannel.cs
index c2a90c26..104d6384 100644
--- a/src/AgentCore.Application/Call/CallChannel.cs
+++ b/src/AgentCore.Application/Calls/CallChannel.cs
@@ -1,6 +1,6 @@
using AgentCore.Application.Ports;
-namespace AgentCore.Application.Call;
+namespace AgentCore.Application.Calls;
///
/// The two halves of one call, opened together and disposed together.
diff --git a/src/AgentCore.Application/Call/CallChannelContext.cs b/src/AgentCore.Application/Calls/CallChannelContext.cs
similarity index 93%
rename from src/AgentCore.Application/Call/CallChannelContext.cs
rename to src/AgentCore.Application/Calls/CallChannelContext.cs
index c6102a36..e863df44 100644
--- a/src/AgentCore.Application/Call/CallChannelContext.cs
+++ b/src/AgentCore.Application/Calls/CallChannelContext.cs
@@ -1,4 +1,4 @@
-namespace AgentCore.Application.Call;
+namespace AgentCore.Application.Calls;
/// What one call needs to open its channel.
/// The AgentCore call id, which the channel must not invent for itself.
diff --git a/src/AgentCore.Application/Call/CallInput.cs b/src/AgentCore.Application/Calls/CallInput.cs
similarity index 98%
rename from src/AgentCore.Application/Call/CallInput.cs
rename to src/AgentCore.Application/Calls/CallInput.cs
index 576a3163..5121e606 100644
--- a/src/AgentCore.Application/Call/CallInput.cs
+++ b/src/AgentCore.Application/Calls/CallInput.cs
@@ -1,4 +1,4 @@
-namespace AgentCore.Application.Call;
+namespace AgentCore.Application.Calls;
///
/// One thing the caller did, in the order it happened.
diff --git a/src/AgentCore.Application/Calls/CallRecord.cs b/src/AgentCore.Application/Calls/CallRecord.cs
index f8d7ac25..9065706e 100644
--- a/src/AgentCore.Application/Calls/CallRecord.cs
+++ b/src/AgentCore.Application/Calls/CallRecord.cs
@@ -18,6 +18,11 @@ namespace AgentCore.Application.Calls;
/// under a build that writes it. Read by GetAsync and CreateAsync only: a listing does
/// not need it and does not pay for it.
///
+///
+/// The ordinal the call's next appended row takes. Read by GetAsync and CreateAsync
+/// only, on the same terms as : a listing leaves it at its default 0 rather
+/// than paying to read it.
+///
public sealed record CallRecord(
string CallId,
string? Title,
@@ -26,4 +31,5 @@ public sealed record CallRecord(
JsonElement? Custom,
DateTimeOffset CreatedAt,
DateTimeOffset? LastMessageAt,
- CallSessionState? State = null);
+ CallSessionState? State = null,
+ int NextOrdinal = 0);
diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Calls/CallSessionState.cs
index 274d6a73..4bdb5368 100644
--- a/src/AgentCore.Application/Calls/CallSessionState.cs
+++ b/src/AgentCore.Application/Calls/CallSessionState.cs
@@ -1,4 +1,5 @@
using System.Collections.ObjectModel;
+using System.Text.Json;
using System.Text.Json.Nodes;
namespace AgentCore.Application.Calls;
@@ -14,15 +15,16 @@ public sealed record CallSessionState
private static readonly IReadOnlyDictionary NoClarifications =
ReadOnlyDictionary.Empty;
+ /// The providers of a call whose document declares no harness switch.
+ private static readonly IReadOnlyDictionary NoProviders =
+ ReadOnlyDictionary.Empty;
+
/// The shape this version of the library writes.
public const int CurrentVersion = 1;
/// Gets the shape this blob was written in.
public int Version { get; init; } = CurrentVersion;
- /// Gets the next free ordinal of the call.
- public int NextOrdinal { get; init; }
-
/// Gets the index the call's next turn takes.
public int NextTurnIndex { get; init; }
@@ -40,4 +42,19 @@ public sealed record CallSessionState
/// nothing has asked about is absent.
///
public IReadOnlyDictionary Clarifications { get; init; } = NoClarifications;
+
+ ///
+ /// Gets the MAF provider state a harness switch (todos: , mode: , memory: ,
+ /// files: , background: ) held, keyed by that provider's state key. A document with
+ /// no harness switch holds none. Absent in an old blob, which restores its stage and slots as before.
+ ///
+ public IReadOnlyDictionary Providers { get; init; } = NoProviders;
+
+ ///
+ /// Gets the opaque workflow session of a graph row's call, carrying the harness providers'
+ /// checkpointed state across turns. Only a graph row whose document declares a harness switch
+ /// writes one; rows 1 and 2 keep provider state in , and any other call
+ /// keeps neither. Absent in an old blob, which resumes with a fresh session.
+ ///
+ public JsonElement? WorkflowState { get; init; }
}
diff --git a/src/AgentCore.Application/Call/CallSpeechPairing.cs b/src/AgentCore.Application/Calls/CallSpeechPairing.cs
similarity index 99%
rename from src/AgentCore.Application/Call/CallSpeechPairing.cs
rename to src/AgentCore.Application/Calls/CallSpeechPairing.cs
index 17e07cc0..38a30b13 100644
--- a/src/AgentCore.Application/Call/CallSpeechPairing.cs
+++ b/src/AgentCore.Application/Calls/CallSpeechPairing.cs
@@ -2,7 +2,7 @@
using AgentCore.Application.Configuration.Schema;
using AgentCore.Application.Ports;
-namespace AgentCore.Application.Call;
+namespace AgentCore.Application.Calls;
///
/// Refuses a document whose call transport and speech vendors cannot coexist.
diff --git a/src/AgentCore.Application/Calls/ChatCallTitler.cs b/src/AgentCore.Application/Calls/ChatCallTitler.cs
index 5078d367..4d7e21df 100644
--- a/src/AgentCore.Application/Calls/ChatCallTitler.cs
+++ b/src/AgentCore.Application/Calls/ChatCallTitler.cs
@@ -20,11 +20,18 @@ public sealed class ChatCallTitler(ICallStore calls, IChatClient client) : ICall
+ "Reply with the title alone.";
///
- public async IAsyncEnumerable GenerateAsync(
- string callId, [EnumeratorCancellation] CancellationToken cancellationToken = default)
+ public IAsyncEnumerable GenerateAsync(
+ string callId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(callId);
+ return GenerateCoreAsync(callId, cancellationToken);
+ }
+
+ /// Reads the call's messages and streams the title writes.
+ private async IAsyncEnumerable GenerateCoreAsync(
+ string callId, [EnumeratorCancellation] CancellationToken cancellationToken)
+ {
var rows = await calls.ReadAsync(callId, cancellationToken).ConfigureAwait(false);
if (rows.Count == 0)
@@ -40,14 +47,23 @@ public async IAsyncEnumerable GenerateAsync(
}
///
- public async IAsyncEnumerable GenerateFromAsync(
+ public IAsyncEnumerable GenerateFromAsync(
string callId,
IReadOnlyList messages,
- [EnumeratorCancellation] CancellationToken cancellationToken = default)
+ CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(callId);
ArgumentNullException.ThrowIfNull(messages);
+ return GenerateFromCoreAsync(callId, messages, cancellationToken);
+ }
+
+ /// Streams the title of caller-supplied messages once the call proves to exist.
+ private async IAsyncEnumerable GenerateFromCoreAsync(
+ string callId,
+ IReadOnlyList messages,
+ [EnumeratorCancellation] CancellationToken cancellationToken)
+ {
if (messages.Count == 0)
{
yield break;
diff --git a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs
index 05f6550e..7590d1f2 100644
--- a/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs
+++ b/src/AgentCore.Application/Calls/Memory/InMemoryCallStore.cs
@@ -17,8 +17,14 @@ public sealed class InMemoryCallStore : ICallStore
/// The resume blob of each call, beside the row rather than on it.
private readonly Dictionary _state = [];
+ /// The next free ordinal of each call. Never rewound, even when its words are.
+ private readonly Dictionary _nextOrdinal = [];
+
private readonly HashSet<(string CallId, string PrincipalKey)> _claims = [];
+ /// One serialized agent session per continuation id, beside the calls.
+ private readonly Dictionary _continuations = [];
+
private readonly TimeProvider _time;
/// Creates the store.
@@ -39,7 +45,11 @@ public ValueTask CreateAsync(string callId, CancellationToken cancel
_calls[callId] = existing;
}
- return ValueTask.FromResult(existing with { State = _state.GetValueOrDefault(callId) });
+ return ValueTask.FromResult(existing with
+ {
+ State = _state.GetValueOrDefault(callId),
+ NextOrdinal = _nextOrdinal.GetValueOrDefault(callId),
+ });
}
}
@@ -51,7 +61,14 @@ public ValueTask CreateAsync(string callId, CancellationToken cancel
lock (_lock)
{
var call = _calls.GetValueOrDefault(callId);
- return ValueTask.FromResult(call is null ? null : call with { State = _state.GetValueOrDefault(callId) });
+
+ return ValueTask.FromResult(call is null
+ ? null
+ : call with
+ {
+ State = _state.GetValueOrDefault(callId),
+ NextOrdinal = _nextOrdinal.GetValueOrDefault(callId),
+ });
}
}
@@ -132,13 +149,17 @@ public ValueTask DeleteAsync(string callId, CancellationToken cancellationToken
{
ArgumentNullException.ThrowIfNull(callId);
- lock (_lock)
- {
- _calls.Remove(callId);
- _claims.RemoveWhere(claim => claim.CallId == callId);
- _state.Remove(callId);
- RemoveWords(callId);
- }
+ _calls.Remove(callId);
+
+ _claims.RemoveWhere(claim => claim.CallId == callId);
+
+ _state.Remove(callId);
+
+ _nextOrdinal.Remove(callId);
+
+ _continuations.Remove(callId);
+
+ RemoveWords(callId);
return default;
}
@@ -168,8 +189,15 @@ public ValueTask SweepAsync(
foreach (var callId in going)
{
_calls.Remove(callId);
+
_claims.RemoveWhere(claim => claim.CallId == callId);
+
_state.Remove(callId);
+
+ _nextOrdinal.Remove(callId);
+
+ _continuations.Remove(callId);
+
RemoveWords(callId);
}
@@ -209,48 +237,74 @@ public ValueTask DetachPrincipalAsync(
}
///
- public ValueTask AppendAsync(
- IReadOnlyList messages,
+ public ValueTask> AppendAsync(
+ string callId,
+ IReadOnlyList messages,
CallSessionState? state = null,
CancellationToken cancellationToken = default)
{
+ ArgumentNullException.ThrowIfNull(callId);
ArgumentNullException.ThrowIfNull(messages);
+ if (messages.Count == 0)
+ {
+ return ValueTask.FromResult>([]);
+ }
+
lock (_lock)
{
- var now = _time.GetUtcNow();
+ if (!_calls.TryGetValue(callId, out var call))
+ {
+ throw new InvalidOperationException($"Store 0 holds no call '{callId}' to append words to.");
+ }
- foreach (var message in messages)
+ var fallbackTurnIndex = _state.GetValueOrDefault(callId)?.NextTurnIndex ?? 0;
+ var first = _nextOrdinal.GetValueOrDefault(callId);
+
+ var rows = new List(messages.Count);
+ for (var index = 0; index < messages.Count; index++)
{
- _rows.Add((message.CallId, message.Ordinal), message);
+ var draft = messages[index];
+ CallMessage row = new(
+ callId, first + index, draft.TurnIndex ?? fallbackTurnIndex, draft.Content, draft.MessageId);
- if (_calls.TryGetValue(message.CallId, out var call))
- {
- _calls[message.CallId] = call with { LastMessageAt = now };
- }
+ rows.Add(row);
+ _rows.Add((row.CallId, row.Ordinal), row);
}
- if (state is not null && messages.Count > 0)
+ _nextOrdinal[callId] = first + messages.Count;
+
+ var now = _time.GetUtcNow();
+ _calls[callId] = call with { LastMessageAt = now };
+
+ if (state is not null)
{
- _state[messages[0].CallId] = state;
+ _state[callId] = state;
}
- }
- return default;
+ return ValueTask.FromResult>(rows);
+ }
}
///
public ValueTask RewriteAsync(
- string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default)
+ string callId, string messageId, ChatMessage content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(callId);
+ ArgumentException.ThrowIfNullOrEmpty(messageId);
ArgumentNullException.ThrowIfNull(content);
lock (_lock)
{
- if (_rows.TryGetValue((callId, ordinal), out var row))
+ foreach (var pair in _rows)
{
- _rows[(callId, ordinal)] = row with { Content = content };
+ if (pair.Key.CallId != callId || pair.Value.MessageId != messageId)
+ {
+ continue;
+ }
+
+ _rows[pair.Key] = pair.Value with { Content = content };
+ break;
}
}
@@ -305,6 +359,44 @@ public ValueTask EraseAsync(string callId, CancellationToken cancellationTo
}
}
+ ///
+ public ValueTask SaveContinuationAsync(string continuationId, JsonElement envelope, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(continuationId);
+
+ lock (_lock)
+ {
+ _continuations[continuationId] = envelope.Clone();
+ }
+
+ return default;
+ }
+
+ ///
+ public ValueTask GetContinuationAsync(string continuationId, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(continuationId);
+
+ lock (_lock)
+ {
+ return ValueTask.FromResult(
+ _continuations.TryGetValue(continuationId, out var envelope) ? envelope : null);
+ }
+ }
+
+ ///
+ public ValueTask DeleteContinuationAsync(string continuationId, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(continuationId);
+
+ lock (_lock)
+ {
+ _continuations.Remove(continuationId);
+ }
+
+ return default;
+ }
+
private static DateTimeOffset SortValue(CallRecord call) => call.LastMessageAt ?? call.CreatedAt;
private int RemoveWords(string callId)
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs
new file mode 100644
index 00000000..0d26529f
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentApproval.cs
@@ -0,0 +1,94 @@
+using AgentCore.Application.Configuration.Schema;
+using AgentCore.Application.Runtime.Harness;
+using Microsoft.Agents.AI;
+using Microsoft.Extensions.AI;
+
+namespace AgentCore.Application.Configuration.Compilation;
+
+///
+/// One agent's approval: block: the standing rules that answer an approval request before
+/// it surfaces. Everything a rule does not name still asks.
+///
+internal static class AgentApproval
+{
+ /// Composes one agent's auto-approval patterns.
+ /// The agents.defaults section, or .
+ /// The agent to resolve.
+ ///
+ /// The agent's own auto: when it declares one, else the defaults', else empty. One key,
+ /// so key-by-key inheritance is a single fallback, the same as knowledge: and
+ /// compaction: .
+ ///
+ public static IReadOnlyList Compose(AgentDefaults? defaults, AgentConfiguration agent)
+ {
+ ArgumentNullException.ThrowIfNull(agent);
+
+ return agent.Approval?.Auto ?? defaults?.Approval?.Auto ?? [];
+ }
+
+ /// Whether auto-approves .
+ /// One auto: entry: a tool name, or a prefix with a trailing * .
+ /// The called tool's name.
+ ///
+ /// An ordinal prefix match for a trailing-* pattern, else an ordinal exact match. A
+ /// * anywhere else is literal, so it matches nothing a document can call.
+ ///
+ public static bool Matches(string pattern, string toolName)
+ {
+ ArgumentNullException.ThrowIfNull(pattern);
+ ArgumentNullException.ThrowIfNull(toolName);
+
+ return pattern.EndsWith('*')
+ ? toolName.StartsWith(pattern[..^1], StringComparison.Ordinal)
+ : toolName == pattern;
+ }
+
+ /// Reads the state keys an agent's approval surface needs persisted across resume.
+ /// The agents.defaults section, or .
+ /// The agent being compiled.
+ /// The tools the agent offers the model, if any.
+ ///
+ /// The pending queue and the standing-rule keys when the agent may surface an approval —
+ /// through auto: , which adds the approval layer, or through an approval-required tool —
+ /// else empty. An absent key is never kept, so both ride together.
+ ///
+ public static IReadOnlyList StateKeysFor(
+ AgentDefaults? defaults, AgentConfiguration item, IEnumerable? tools)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+
+ if (Compose(defaults, item).Count == 0
+ && tools?.OfType().Any() != true)
+ {
+ return [];
+ }
+
+ return [PendingApprovalQueue.PendingStateKey, PendingApprovalQueue.StandingStateKey];
+ }
+
+ ///
+ /// Bakes one agent's auto: into its pipeline as UseToolApproval rules. No
+ /// patterns, no layer — the document pays nothing for approval it never declares.
+ ///
+ /// The compiled agent.
+ /// The agents.defaults section, or .
+ /// The agent being compiled.
+ /// The approval-wrapped agent, or unchanged.
+ public static AIAgent Apply(AIAgent agent, AgentDefaults? defaults, AgentConfiguration item)
+ {
+ ArgumentNullException.ThrowIfNull(agent);
+ ArgumentNullException.ThrowIfNull(item);
+
+ if (Compose(defaults, item) is not { Count: > 0 } auto)
+ {
+ return agent;
+ }
+
+ return new AIAgentBuilder(agent)
+ .UseToolApproval(new ToolApprovalAgentOptions { AutoApprovalRules = auto.Select(ToRule).ToList() })
+ .Build();
+ }
+
+ private static Func> ToRule(string pattern)
+ => context => ValueTask.FromResult(Matches(pattern, context.FunctionCallContent.Name));
+}
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs
index f5238c9d..ac91f2f5 100644
--- a/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentCompilationContext.cs
@@ -1,4 +1,3 @@
-using System.Text.Json.Nodes;
using AgentCore.Application.Configuration.Validation;
using AgentCore.Application.Evaluation;
using AgentCore.Application.Knowledge;
@@ -49,11 +48,6 @@ public AgentCompilationContext(IChatClientFactory chatClients)
///
public ICallStore? CallStore { get; init; }
- ///
- /// Gets or sets the source of the state a guarded graph edge reads.
- ///
- public Func>? StateSnapshot { get; init; }
-
///
/// Gets or sets the store every agent's knowledge: block reads through.
///
@@ -74,4 +68,10 @@ public AgentCompilationContext(IChatClientFactory chatClients)
/// Gets or sets where the compiled agents write their own diagnostics, or .
///
public ILoggerFactory? Loggers { get; init; }
+
+ ///
+ /// Gets or sets the root a memory: block's files are kept under, or
+ /// when the host bound no workspace root.
+ ///
+ public string? WorkspaceRoot { get; init; }
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs
index c66b36d6..f0e109d6 100644
--- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs
@@ -2,8 +2,8 @@
using AgentCore.Application.Configuration.Schema;
using AgentCore.Application.Knowledge;
using AgentCore.Application.Ports;
-using AgentCore.Application.Runtime;
using AgentCore.Application.Runtime.Compaction;
+using AgentCore.Application.Runtime.Turn;
using AgentCore.Application.Skills;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Compaction;
@@ -22,13 +22,16 @@ internal static class AgentContextProviderCompiler
/// ambiguity wiring (§8), the same for every agent — built once by the caller rather than
/// re-derived per agent.
///
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
public static List Build(
AgentDefaults? defaults,
AgentConfiguration item,
AgentCompilationContext context,
string pointer,
ResolvedClarification clarification,
- KnowledgeScopeConfiguration? scope)
+ KnowledgeScopeConfiguration? scope,
+ Func resolve,
+ ICollection? background = null)
{
List providers = [new TurnContextProvider()];
@@ -68,6 +71,7 @@ public static List Build(
loggerFactory: context.Loggers));
#pragma warning restore MAAI001
}
+ AgentHarnessProviders.Add(providers, defaults, item, context, pointer, resolve, background);
if (AgentKnowledge.Compose(defaults, item) is not { } composed)
{
@@ -98,4 +102,5 @@ public static List Build(
return providers;
}
+#pragma warning restore MAAI001
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs
index 03daff39..5912c115 100644
--- a/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentDelegationTool.cs
@@ -1,6 +1,7 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using AgentCore.Application.Configuration.Schema;
+using AgentCore.Application.Runtime;
using AgentCore.Application.Tools;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
@@ -23,35 +24,57 @@ internal static AIFunction Create(ToolConfiguration tool, AIAgent inner)
{
// The document names the function and describes it, because the calling model reads both to
// decide when to delegate. Without a description it falls back to the inner agent's own.
+ // AsAIFunction is the schema donor only — the wrapper below runs the agent directly, so
+ // its name, description and parameters stay exactly what the model was built against.
var function = inner.AsAIFunction(new AIFunctionFactoryOptions
{
Name = tool.Id,
Description = tool.Description ?? inner.Description,
});
- return tool.Parameters is { } parameters
- ? new DeclaredSchemaFunction(function, parameters)
- : function;
+ return new DeclaredSchemaFunction(function, tool.Parameters, tool.Id, inner);
}
///
- /// Advertises the parameters: the document declares, over a function that takes one string.
+ /// Advertises the parameters: the document declares, over a function that takes one
+ /// string — or the inner function as-is when the document declares none — and runs the
+ /// inner agent directly instead of the framework's delegation machinery, so the nested run
+ /// carries the turn on its own options like every other run.
///
private sealed class DeclaredSchemaFunction : DelegatingAIFunction
{
private readonly JsonElement _schema;
- private readonly string _argument;
- internal DeclaredSchemaFunction(AIFunction inner, JsonNode parameters)
+ private readonly string? _argument;
+
+ private readonly string _toolId;
+
+ private readonly AIAgent _inner;
+
+ internal DeclaredSchemaFunction(AIFunction inner, JsonNode? parameters, string toolId, AIAgent innerAgent)
: base(inner)
{
- using var document = JsonDocument.Parse(parameters.ToJsonString());
- _schema = document.RootElement.Clone();
+ ArgumentNullException.ThrowIfNull(toolId);
- _argument = FirstProperty(inner.JsonSchema) ?? DefaultArgument;
+ _toolId = toolId;
+ _inner = innerAgent ?? throw new ArgumentNullException(nameof(innerAgent));
+
+ if (parameters is null)
+ {
+ _schema = inner.JsonSchema;
+ _argument = null;
+ }
+ else
+ {
+ using var document = JsonDocument.Parse(parameters.ToJsonString());
+
+ _schema = document.RootElement.Clone();
+ _argument = FirstProperty(inner.JsonSchema) ?? DefaultArgument;
+ }
}
- public override JsonElement JsonSchema => _schema;
+ public override JsonElement JsonSchema
+ => _schema;
protected override ValueTask InvokeCoreAsync(
AIFunctionArguments arguments,
@@ -59,21 +82,41 @@ internal DeclaredSchemaFunction(AIFunction inner, JsonNode parameters)
{
ArgumentNullException.ThrowIfNull(arguments);
- var payload = ToolArgumentJson.ToJsonObject(arguments);
+ var parent = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var turn) && turn is TurnInvocation p
+ ? p
+ : null;
- AIFunctionArguments forwarded = new(new Dictionary(StringComparer.Ordinal)
- {
- [_argument] = payload.ToJsonString(),
- })
- {
- Services = arguments.Services,
- Context = arguments.Context,
- };
+ // Schemaless the donor advertises one query string; declared, the payload the
+ // document shaped. Either way the nested agent reads words, not arguments.
+ string query = _argument is null
+ && arguments.TryGetValue(DefaultArgument, out var bare)
+ && BareText(bare) is { } text
+ ? text
+ : ToolArgumentJson.ToJsonObject(arguments).ToJsonString();
+
+ // Decided here where the parent turn is in hand: the nested run neither latches
+ // the holder (K42) nor records, and only the run under this tool is offered its
+ // tools. Without a turn the nested run is bare, as before.
+ var nested = parent is not null
+ ? parent with { Clarifications = null, Nested = true }
+ : null;
+
+ var offered = parent?.ToolsFor == _toolId ? parent?.Tools : null;
- return InnerFunction.InvokeAsync(forwarded, cancellationToken);
+ return DelegatedAgentRun.RunAsync(_inner, query, nested, offered, cancellationToken);
}
- /// Reads the name of the first declared property of one JSON Schema object.
+ private static string? BareText(object? value)
+ => value switch
+ {
+ string text => text,
+ JsonElement { ValueKind: JsonValueKind.String } element => element.GetString(),
+ _ => null,
+ };
+
+ ///
+ /// Reads the name of the first declared property of one JSON Schema object.
+ ///
private static string? FirstProperty(JsonElement schema)
{
if (schema.ValueKind is not JsonValueKind.Object
@@ -83,12 +126,8 @@ internal DeclaredSchemaFunction(AIFunction inner, JsonNode parameters)
return null;
}
- foreach (var property in properties.EnumerateObject())
- {
- return property.Name;
- }
-
- return null;
+ return properties.EnumerateObject().Select(property => property.Name).FirstOrDefault();
}
+
}
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs
new file mode 100644
index 00000000..2b0feac7
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarness.cs
@@ -0,0 +1,27 @@
+using AgentCore.Application.Configuration.Schema;
+
+namespace AgentCore.Application.Configuration.Compilation;
+
+/// One agent's harness switches, fully resolved.
+/// Whether the agent gets the todo tools.
+/// Whether the agent gets the mode tools.
+public sealed record ResolvedHarness(bool Todos, bool Mode);
+
+///
+/// Composes one agent's harness switches (todos: , mode: ) from
+/// agents.defaults and the agent's own keys, key by key.
+///
+public static class AgentHarness
+{
+ /// Composes one agent's resolved harness switches.
+ /// The agents.defaults section, or .
+ /// The agent to resolve.
+ public static ResolvedHarness Compose(AgentDefaults? defaults, AgentConfiguration agent)
+ {
+ ArgumentNullException.ThrowIfNull(agent);
+
+ return new ResolvedHarness(
+ agent.Todos ?? defaults?.Todos ?? false,
+ agent.Mode ?? defaults?.Mode ?? false);
+ }
+}
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs
new file mode 100644
index 00000000..a7563f25
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentHarnessProviders.cs
@@ -0,0 +1,417 @@
+using System.Text.RegularExpressions;
+using AgentCore.Application.Configuration.Parsing;
+using AgentCore.Application.Configuration.Schema;
+using AgentCore.Application.Runtime.Harness;
+using AgentCore.Application.Runtime.Turn;
+using Microsoft.Agents.AI;
+using Microsoft.Agents.AI.Tools.Shell;
+
+namespace AgentCore.Application.Configuration.Compilation;
+
+///
+/// The context providers behind one agent's harness switches (todos: , mode: ,
+/// memory: , files: , shell: , background: ), added into the provider list
+/// builds.
+///
+internal static class AgentHarnessProviders
+{
+ ///
+ /// MAF's default , with its persistence claim
+ /// replaced: the default tells the model these files "persist beyond the current conversation",
+ /// which is false here — FileMemoryProvider 's working folder is the call's workspace,
+ /// deleted at EndCall . Every other sentence, including how to use the tools, is unchanged.
+ ///
+ private const string MemoryInstructions =
+ "## File Based Memory\n"
+ + "You have access to a file-based memory system via the `file_memory_*` tools for storing and retrieving information across interactions.\n"
+ + "These files act as your working memory for this call: they live in this call's workspace and are deleted when the call ends,\n"
+ + "so anything you write now stays available for the rest of this call, but not after it ends.\n"
+ + "Use these tools to store plans, memories, processing results, or downloaded data.\n\n"
+ + "- Use descriptive file names (e.g., \"projectarchitecture.md\", \"userpreferences.md\").\n"
+ + "- Include a description when writing a file to help with future discovery.\n"
+ + "- Before starting new tasks, use file_memory_ls and file_memory_grep to check for relevant existing memories to avoid duplicate work.\n"
+ + "- Keep memories up-to-date by overwriting files when information changes, or by using file_memory_replace and file_memory_replace_lines to make small edits.\n"
+ + "- When you receive large amounts of data (e.g., downloaded web pages, API responses, research results),\n"
+ + " write them to files if they will be required later, so that they are not lost when older context is compacted or truncated.\n"
+ + " This ensures important data remains accessible across long-running sessions.";
+
+ ///
+ /// MAF's default , with its persistence claim
+ /// replaced: the default tells the model these files "persist beyond the current session" and
+ /// "may be shared across sessions or agents", which is false here — CallFilesProvider
+ /// resolves to the call's workspace, deleted at EndCall . Every other sentence, including
+ /// how to use the tools, is unchanged.
+ ///
+ private const string FilesInstructions =
+ "## File Access\n"
+ + "You have access to a shared file storage area via the `file_access_*` tools for reading, writing, and managing files.\n"
+ + "These files live in this call's workspace: they exist only for the duration of this call and are deleted when the call ends.\n"
+ + "Use these tools to read input data provided by the user, write output artifacts, and manage any files the user has asked you to work with.\n\n"
+ + "- Never delete or overwrite existing files unless the user has explicitly asked you to do so.\n"
+ + "- Files may be organized into subdirectories. Use `file_access_ls` to explore the tree level by level,\n"
+ + " or `file_access_grep` to search file contents recursively across the whole store.\n"
+ + "- To make small edits to an existing file, prefer `file_access_replace` (substring replacement) or\n"
+ + " `file_access_replace_lines` (whole-line replacement) over rewriting the whole file.\n"
+ + "- To change part of a file, find the line numbers with `file_access_grep`, read the range around them\n"
+ + " with `file_access_read_lines`, then edit with `file_access_replace_lines`. Reading the whole file\n"
+ + " first is rarely necessary.";
+
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
+
+ /// Adds this agent's harness providers, in declaration order: todos, mode, memory, files, shell, background.
+ /// The provider list under construction.
+ /// The agents.defaults section, or .
+ /// The agent being compiled.
+ /// The compile-time seams, including the bound workspace root.
+ /// This agent's JSON pointer, for a memory: , files: , shell: , or background: failure.
+ /// Resolves an agents.items id to its compiled agent, or when undeclared.
+ /// Collects the built background providers, so the call can release their sessions when it ends.
+ public static void Add(
+ List providers,
+ AgentDefaults? defaults,
+ AgentConfiguration item,
+ AgentCompilationContext context,
+ string pointer,
+ Func resolve,
+ ICollection? background = null)
+ {
+ var harness = AgentHarness.Compose(defaults, item);
+
+ if (harness.Todos)
+ {
+ providers.Add(new TodoProvider());
+ }
+
+ if (harness.Mode)
+ {
+ providers.Add(new AgentModeProvider());
+ }
+
+ if (item.Memory is { Store: AgentFileStoreKind.Workspace })
+ {
+ providers.Add(BuildMemoryProvider(item, context, pointer));
+ }
+
+ if (item.Files is { Store: AgentFileStoreKind.Workspace } files)
+ {
+ providers.Add(BuildFilesProvider(item, files, context, pointer));
+ }
+
+ if (item.Shell is { } shell)
+ {
+ var options = BuildShellOptions(item, shell, context, pointer);
+ providers.Add(new CallShellProvider(options));
+ providers.Add(new CallShellEnvironmentProvider(options));
+ }
+
+ if (item.Background.Count > 0)
+ {
+ var provider = BuildBackgroundProvider(item, pointer, resolve);
+ providers.Add(provider);
+ background?.Add(provider);
+ }
+ }
+#pragma warning restore MAAI001
+
+#pragma warning disable MAAI001 // The loop family is evaluation-only in Microsoft.Agents.AI 1.21.0.
+
+ ///
+ /// Wraps one compiled agent in its loop: block: a over the
+ /// until: evaluators in document order, capped at maxRounds: . No block, no wrap.
+ ///
+ /// The compiled agent.
+ /// The agents.defaults section, or .
+ /// The agent being compiled.
+ /// This agent's JSON pointer, for a loop: failure.
+ /// The loop-wrapped agent, or unchanged.
+ public static AIAgent ApplyLoop(AIAgent agent, AgentDefaults? defaults, AgentConfiguration item, string pointer)
+ {
+ ArgumentNullException.ThrowIfNull(agent);
+ ArgumentNullException.ThrowIfNull(item);
+
+ if (item.Loop is not { } loop)
+ {
+ return agent;
+ }
+
+ if (loop.Until is not { Count: > 0 })
+ {
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "loop"),
+ $"the agent '{item.Id}' declares a loop: block with no until: entries, so the loop would "
+ + "run exactly once and maxRounds: would never apply. Name what ends the loop, or remove "
+ + "the loop: block.");
+ }
+
+ var harness = AgentHarness.Compose(defaults, item);
+ List evaluators = new(loop.Until.Count);
+
+ for (var index = 0; index < loop.Until.Count; index++)
+ {
+ var untilPointer = ConfigurationError.AppendPointer(
+ ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "loop"), "until"), index);
+
+ var until = loop.Until[index];
+
+ if (until.Todos is not null)
+ {
+ if (!harness.Todos)
+ {
+ throw ConfigurationCompiler.Fail(
+ untilPointer,
+ $"the agent '{item.Id}' declares loop: until: todos: and no todos: switch, so the "
+ + "evaluator would fault every turn resolving its provider. Set todos: true, or "
+ + "remove the entry.");
+ }
+
+ evaluators.Add(new TodoCompletionLoopEvaluator(new TodoCompletionLoopEvaluatorOptions()));
+ }
+
+ if (until.Background is not null)
+ {
+ if (item.Background.Count == 0)
+ {
+ throw ConfigurationCompiler.Fail(
+ untilPointer,
+ $"the agent '{item.Id}' declares loop: until: background: and no background: children, "
+ + "so the evaluator would fault every turn resolving its provider. Name the children, "
+ + "or remove the entry.");
+ }
+
+ evaluators.Add(new BackgroundTaskCompletionLoopEvaluator(new BackgroundTaskCompletionLoopEvaluatorOptions()));
+ }
+ }
+
+ // Every iteration's text reaches the stream; there are no per-iteration entries (decision 14).
+ return new LoopAgent(agent, evaluators, new LoopAgentOptions { MaxIterations = loop.MaxRounds });
+ }
+
+#pragma warning restore MAAI001
+
+#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0.
+
+ ///
+ /// The state keys of the harness providers among — never the
+ /// history provider's key, which is the transcript and belongs to store 1.
+ ///
+ internal static IReadOnlySet StateKeysOf(IEnumerable providers)
+ {
+ HashSet keys = new(StringComparer.Ordinal);
+
+ foreach (var provider in providers)
+ {
+ if (provider is not (TodoProvider or AgentModeProvider or FileMemoryProvider or FileAccessProvider or BackgroundAgentsProvider))
+ {
+ continue;
+ }
+
+ foreach (var key in provider.StateKeys)
+ {
+ keys.Add(key);
+ }
+ }
+
+ return keys;
+ }
+
+#pragma warning restore MAAI001
+
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
+
+ private static BackgroundAgentsProvider BuildBackgroundProvider(
+ AgentConfiguration item,
+ string pointer,
+ Func resolve)
+ {
+ if (item.Background.Contains(item.Id, StringComparer.Ordinal))
+ {
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "background"),
+ $"the agent '{item.Id}' names itself in background:, so it would start itself as its own child. "
+ + "Remove it from the list, or point at another agent.");
+ }
+
+ List children = new(item.Background.Count);
+ for (var index = 0; index < item.Background.Count; index++)
+ {
+ var childPointer = ConfigurationError.AppendPointer(
+ ConfigurationError.AppendPointer(pointer, "background"), index);
+
+ var childId = item.Background[index];
+
+ children.Add(resolve(childId)
+ ?? throw ConfigurationCompiler.Fail(
+ childPointer,
+ $"the agent '{childId}' is not declared in agents.items"));
+ }
+
+ try
+ {
+ // Children run with their own compiled tools, which carry no approval-required tool
+ // today — every harness tool runs with approval off — so a child never stalls waiting
+ // for an approval the parent would only see as a completed task with empty output.
+ return new BackgroundAgentsProvider(children);
+ }
+ catch (ArgumentException exception)
+ {
+ // The provider keys children by name case-insensitively, so two ids that differ only
+ // by case collide here rather than at either declaration.
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "background"),
+ $"the agent '{item.Id}' declares background: children whose names collide: {exception.Message}");
+ }
+ }
+
+#pragma warning restore MAAI001
+
+ private static FileMemoryProvider BuildMemoryProvider(
+ AgentConfiguration item, AgentCompilationContext context, string pointer)
+ {
+ if (context.WorkspaceRoot is not { } root)
+ {
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "memory"),
+ $"the agent '{item.Id}' declares a memory: block and this host bound no workspace "
+ + "root, so there is nowhere to keep the files. Call options.UseWorkspace(...) with "
+ + "the folder, or remove the memory: block.");
+ }
+
+ try
+ {
+
+#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0.
+ return new FileMemoryProvider(
+ new FileSystemAgentFileStore(root),
+ InitializeWorkingFolder,
+ new FileMemoryProviderOptions { Instructions = MemoryInstructions });
+#pragma warning restore MAAI001
+
+ }
+ catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
+ {
+ // FileSystemAgentFileStore's constructor creates the root eagerly, and this compiles
+ // before CallSessionStartup's own guarded create — so a bad root fails here first, and
+ // must fail with the same named cause an operator gets from that later guard.
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "memory"),
+ $"the agent '{item.Id}' declares a memory: block and the workspace root '{root}' "
+ + $"could not be created: {exception.Message} Check the path passed to "
+ + "options.UseWorkspace(...), and that the process has permission to create it.");
+ }
+ }
+
+#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0.
+
+ private static CallFilesProvider BuildFilesProvider(
+ AgentConfiguration item,
+ AgentFilesConfiguration files,
+ AgentCompilationContext context,
+ string pointer)
+ {
+ if (context.WorkspaceRoot is null)
+ {
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "files"),
+ $"the agent '{item.Id}' declares a files: block and this host bound no workspace "
+ + "root, so there is nowhere to keep the files. Call options.UseWorkspace(...) with "
+ + "the folder, or remove the files: block.");
+ }
+
+ return new CallFilesProvider(
+ context.WorkspaceRoot,
+ new FileAccessProviderOptions
+ {
+ DisableWriteTools = !files.Write,
+ DisableReadOnlyToolApproval = true,
+ DisableWriteToolApproval = true,
+ Instructions = FilesInstructions,
+ });
+ }
+
+#pragma warning restore MAAI001
+
+ private static CallShellOptions BuildShellOptions(
+ AgentConfiguration item,
+ ShellConfiguration shell,
+ AgentCompilationContext context, string pointer)
+ {
+ if (context.WorkspaceRoot is null)
+ {
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(pointer, "shell"),
+ $"the agent '{item.Id}' declares a shell: block and this host bound no workspace "
+ + "root, so the shell has no working directory. Call options.UseWorkspace(...) with "
+ + "the folder, or remove the shell: block.");
+ }
+
+ var policy = shell.Policy is { } declared ? BuildPolicy(item, declared, pointer) : null;
+
+ var timeout = shell.TimeoutSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : (TimeSpan?)null;
+
+ return new CallShellOptions(shell.Kind, policy, timeout);
+ }
+
+ private static ShellPolicy BuildPolicy(
+ AgentConfiguration item,
+ ShellPolicyConfiguration policy,
+ string pointer)
+ {
+ // ShellPolicy treats a supplied-but-empty allow list as deny-all (it denies any command that
+ // matches none of the allow patterns, and an empty list matches nothing), so an agent that
+ // declares no allow: must reach the executor with allowList: null, not an empty collection.
+ var allow = policy.Allow.Count == 0 ? null : policy.Allow;
+
+ try
+ {
+ return new ShellPolicy(denyList: policy.Deny, allowList: allow);
+ }
+ catch (ArgumentException exception)
+ {
+ // ShellPolicy compiles every pattern into a Regex eagerly in its own constructor, so a
+ // bad pattern in either list throws here, at compile time, rather than at the model's
+ // first command.
+ var bad = policy.Deny.Concat(allow ?? [])
+ .FirstOrDefault(pattern => !IsValidRegex(pattern));
+
+ throw ConfigurationCompiler.Fail(
+ ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "shell"), "policy"),
+ $"the agent '{item.Id}' declares a shell: policy whose pattern '{bad}' is not a "
+ + $"valid regex: {exception.Message}");
+ }
+ }
+
+ private static bool IsValidRegex(string pattern)
+ {
+ try
+ {
+ _ = new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(1));
+ return true;
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+ }
+
+#pragma warning disable MAAI001 // File-store types are evaluation-only in Microsoft.Agents.AI 1.21.0.
+
+ ///
+ /// Builds the state a new session starts with: its working
+ /// folder set to the id of the call running the turn, so it reads and writes under
+ /// <root>/<callId>/ — the folder the host creates and deletes with the call.
+ ///
+ private static FileMemoryState InitializeWorkingFolder(AgentSession? session)
+ {
+ if (TurnRegistry.For(session)?.CallId is not { } callId)
+ {
+ throw new InvalidOperationException(
+ "A memory: block's FileMemoryProvider needs the running call's id, and no turn is "
+ + "filed for this session. The provider's working folder is bound only while "
+ + "a turn runs through a CallSession. Run the agent through a CallSession.");
+ }
+
+ return new FileMemoryState { WorkingFolder = callId };
+ }
+
+#pragma warning restore MAAI001
+}
diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs
index b787ab31..a987955f 100644
--- a/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/AgentToolCompiler.cs
@@ -69,9 +69,9 @@ internal static class AgentToolCompiler
return tools.Count == 0 ? null : tools;
}
- /// Adds one tool, unless it is a hosted search this agent's model cannot run.
+ /// Adds one tool, unless it is a hosted marker its agent's model cannot run.
///
- /// Tested by type and not by the builtin name, so a hosted search tool a host supplies through
+ /// Tested by type and not by the builtin name, so a hosted marker a host supplies through
/// its own IToolSource is covered by the same rule.
///
private static void Add(
@@ -82,11 +82,19 @@ private static void Add(
ModelReference? model,
AgentCompilationContext context)
{
- if (tool is HostedWebSearchTool && !context.ChatClients.SupportsHostedWebSearch(model))
+ if (tool is HostedWebSearchTool or HostedCodeInterpreterTool)
{
- var logger = context.Loggers?.CreateLogger(typeof(AgentToolCompiler)) ?? NullLogger.Instance;
- var modelDescription = model is { Ref.Length: > 0 } ? $"the model '{model.Ref}'" : "this agent's default model";
- Log.HostedWebSearchDropped(logger, agentId, toolId, modelDescription);
+ if (context.ChatClients.ResolveHostedTool(tool, model) is not { } resolved)
+ {
+ var logger = context.Loggers?.CreateLogger(typeof(AgentToolCompiler)) ?? NullLogger.Instance;
+ var modelDescription = model is { Ref.Length: > 0 } ? $"the model '{model.Ref}'" : "this agent's default model";
+
+ Log.HostedToolDropped(logger, agentId, toolId, tool.GetType().Name, modelDescription);
+
+ return;
+ }
+
+ tools.Add(resolved);
return;
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs b/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs
index c8bf05bb..c318e4cd 100644
--- a/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/CompileTableRow.cs
@@ -17,24 +17,31 @@ internal abstract class CompileTableRow
/// Rows 1 and 2 ride the session. A graph run rides the request messages.
internal virtual bool SessionCarriesHistory => false;
- /// Builds the entry agent of one document, and the stage table when the row has one.
- /// The loaded document. It already selected this row.
+ /// Builds the entry agent of one entry, and the stage table when the row has one.
+ /// The loaded document.
+ /// The entry key. Graph rows build workflows under it.
+ /// The entry being compiled. It already selected this row.
+ /// The JSON Pointer to the entry, /entries/<name> .
/// The compiled agents.items entries, keyed by id.
/// The seams the document names.
/// The agent a turn runs, and the agent id each policy.stages entry names.
- /// The document does not compile through this row.
+ /// The entry does not compile through this row.
internal abstract (AIAgent Entry, Dictionary Stages) BuildEntry(
AgentCoreConfiguration configuration,
+ string entryName,
+ EntryConfiguration entry,
+ string entryPointer,
Dictionary agents,
AgentCompilationContext context);
/// Names the agents whose reply the caller actually hears.
/// The loaded document.
+ /// The entry being compiled.
///
/// The agents.items ids that answer the caller, or when the last
/// thing the run produced is the answer.
///
- internal virtual HashSet? SpokenAuthors(AgentCoreConfiguration configuration) => null;
+ internal virtual HashSet? SpokenAuthors(AgentCoreConfiguration configuration, EntryConfiguration entry) => null;
private protected static Dictionary NoStages() => new(StringComparer.Ordinal);
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs
index d2351f59..b3218c15 100644
--- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgent.cs
@@ -8,7 +8,7 @@
namespace AgentCore.Application.Configuration.Compilation;
///
-/// One document, compiled to the row that it selected.
+/// One entry, compiled to the row that it selected.
///
public sealed class CompiledAgent
{
@@ -18,8 +18,13 @@ public sealed class CompiledAgent
private readonly Dictionary _turnByAgentId;
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
internal CompiledAgent(
AgentCoreConfiguration configuration,
+ string entryName,
+ PolicyConfiguration? policy,
+ string fallbackReply,
+ string refusalReply,
CompileTableRow row,
ICallStore calls,
AIAgent entry,
@@ -27,16 +32,27 @@ internal CompiledAgent(
Dictionary agentIdByStage,
IReadOnlySet? spokenBy,
AgentCoreChatHistoryProvider history,
+ IReadOnlySet harnessStateKeys,
+ IReadOnlyList backgroundProviders,
Func turnLayers)
{
+ ArgumentException.ThrowIfNullOrEmpty(entryName);
+ ArgumentNullException.ThrowIfNull(fallbackReply);
+ ArgumentNullException.ThrowIfNull(refusalReply);
+
Configuration = configuration;
+ EntryName = entryName;
+ Policy = policy;
+ FallbackReply = fallbackReply;
+ RefusalReply = refusalReply;
Shape = row.Shape;
SessionCarriesHistory = row.SessionCarriesHistory;
Agent = entry;
CallStore = calls;
SpokenBy = spokenBy;
History = history;
-
+ HarnessStateKeys = harnessStateKeys;
+ BackgroundProviders = backgroundProviders;
_byAgentId = byAgentId;
_agentIdByStage = agentIdByStage;
@@ -48,6 +64,7 @@ internal CompiledAgent(
_turnByAgentId[id] = turnLayers(agent);
}
}
+#pragma warning restore MAAI001
///
/// Gets whether the row answers its runs out of store 1 on its own session, rather than the
@@ -58,11 +75,23 @@ internal CompiledAgent(
/// Gets the document this agent was compiled from.
public AgentCoreConfiguration Configuration { get; }
- /// Gets the row of the compile table this document selected.
+ /// Gets the entry key this agent was compiled from. It is the agent's name.
+ public string EntryName { get; }
+
+ /// Gets this entry's stage machine, or when the entry holds none.
+ public PolicyConfiguration? Policy { get; }
+
+ /// Gets the resolved line the caller hears when a turn fails.
+ public string FallbackReply { get; }
+
+ /// Gets the resolved line the caller hears when the agent refuses to answer.
+ public string RefusalReply { get; }
+
+ /// Gets the row of the compile table this entry selected.
public CompiledAgentShape Shape { get; }
- /// Gets the name of the document.
- public string Name => Configuration.Name;
+ /// Gets the name of the entry.
+ public string Name => EntryName;
///
/// Gets the agent a turn runs.
@@ -81,6 +110,20 @@ internal CompiledAgent(
/// Gets the store this agent's calls and every word of them are kept in.
internal ICallStore CallStore { get; }
+ ///
+ /// Gets the union of every harness provider's state keys, over every agent this document
+ /// compiled — never the history provider's key. Empty when the document names no harness
+ /// switch. This is what a call's Providers keeps beside its stage and its slots.
+ ///
+ internal IReadOnlySet HarnessStateKeys { get; }
+
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
+ ///
+ /// Gets every background provider this document compiled, over every agent. The call releases
+ /// each one's session when it ends, so children still running cannot outlive it.
+ ///
+ internal IReadOnlyList BackgroundProviders { get; }
+#pragma warning restore MAAI001
///
/// Gets the agent a turn runs, with the turn-disposition layers on it.
@@ -129,10 +172,10 @@ internal CompiledAgent(
/// The machine, in the initial stage.
public StagePolicy CreatePolicy(IGuardEvaluator guards)
{
- if (Configuration.Policy is not { } policy)
+ if (Policy is not { } policy)
{
throw new InvalidOperationException(
- $"The document '{Name}' declares no policy, so it has no stage machine.");
+ $"The entry '{EntryName}' declares no policy, so it has no stage machine.");
}
return new StagePolicy(policy, guards);
diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs
index 816fb228..3687a2bd 100644
--- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentRegistry.cs
@@ -1,30 +1,22 @@
+using AgentCore.Application.Configuration.Parsing;
using AgentCore.Application.Configuration.Schema;
namespace AgentCore.Application.Configuration.Compilation;
///
-/// Holds each compiled agent for the life of the process.
+/// Holds each compiled entry for the life of the process.
///
-///
-///
-/// T44 closed by measurement: a fan-out of 26 simultaneous runs is clean against one shared
-/// ChatClientAgent , against one shared AsAIAgent() wrapper, and against one wrapper for
-/// each call, with a worst-case first text of 26.5 ms to 27.6 ms across the three shapes. Nothing
-/// serializes inside the wrapper, so sharing one agent costs nothing and compiling one for each call
-/// buys nothing.
-///
-///
-/// Register this registry as a singleton. Every call asks it for the agent, and it compiles once.
-/// exists so a test can prove that.
-///
-///
public sealed class CompiledAgentRegistry
{
- private readonly Dictionary _compiled = [];
+ internal readonly record struct EntryKey(AgentCoreConfiguration Configuration, string Entry);
+
+ private readonly Dictionary _compiled = [];
+
private readonly Lock _gate = new();
+
private int _compileCount;
- /// Gets how many times this registry ran the compile table.
+ /// Gets how many entries this registry has compiled.
public int CompileCount
{
get
@@ -36,27 +28,96 @@ public int CompileCount
}
}
- /// Gets the compiled agent for one document, compiling it the first time only.
+ /// Gets the compiled agent for one entry, compiling it the first time only.
/// The loaded document.
+ /// The entry key.
/// The seams the document names. It is read on the first call only.
- /// The one compiled agent for that document.
- public CompiledAgent GetOrCompile(AgentCoreConfiguration configuration, AgentCompilationContext context)
+ /// The one compiled agent for that entry.
+ /// The entry name is not declared.
+ public CompiledAgent GetOrCompile(
+ AgentCoreConfiguration configuration,
+ string entryName,
+ AgentCompilationContext context)
{
ArgumentNullException.ThrowIfNull(configuration);
+ ArgumentNullException.ThrowIfNull(entryName);
ArgumentNullException.ThrowIfNull(context);
lock (_gate)
{
- if (_compiled.TryGetValue(configuration, out var existing))
+ ThrowWhenUnknownEntry(configuration, entryName);
+
+ var key = new EntryKey(configuration, entryName);
+ if (_compiled.TryGetValue(key, out var existing))
{
return existing;
}
// The compile runs inside the lock, so 26 simultaneous callers still compile once.
- var compiled = ConfigurationCompiler.Compile(configuration, context);
- _compileCount++;
- _compiled[configuration] = compiled;
+ CacheAllLocked(configuration, context);
+ return _compiled[key];
+ }
+ }
+
+ /// Compiles every entry of one document, so boot fails fast on a bad entry.
+ /// The loaded document.
+ /// The seams the document names. It is read on the first call only.
+ /// The compiled agents, keyed by entry name.
+ public IReadOnlyDictionary EnsureAll(
+ AgentCoreConfiguration configuration,
+ AgentCompilationContext context)
+ {
+ ArgumentNullException.ThrowIfNull(configuration);
+ ArgumentNullException.ThrowIfNull(context);
+
+ lock (_gate)
+ {
+ CacheAllLocked(configuration, context);
+
+ Dictionary compiled = new(StringComparer.Ordinal);
+ foreach (var name in configuration.Entries.Keys)
+ {
+ compiled[name] = _compiled[new EntryKey(configuration, name)];
+ }
+
return compiled;
}
}
+
+ private void CacheAllLocked(AgentCoreConfiguration configuration, AgentCompilationContext context)
+ {
+ var missing = false;
+ foreach (var name in configuration.Entries.Keys)
+ {
+ if (!_compiled.ContainsKey(new EntryKey(configuration, name)))
+ {
+ missing = true;
+ break;
+ }
+ }
+
+ if (!missing)
+ {
+ return;
+ }
+
+ var compiled = ConfigurationCompiler.CompileAll(configuration, context);
+ foreach (var (name, agent) in compiled)
+ {
+ if (_compiled.TryAdd(new EntryKey(configuration, name), agent))
+ {
+ _compileCount++;
+ }
+ }
+ }
+
+ private static void ThrowWhenUnknownEntry(AgentCoreConfiguration configuration, string entryName)
+ {
+ if (!configuration.Entries.ContainsKey(entryName))
+ {
+ throw ConfigurationCompiler.Fail(
+ "/entries",
+ $"the entry '{entryName}' is not declared. Valid entries: {string.Join(", ", configuration.Entries.Keys)}.");
+ }
+ }
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentShape.cs b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentShape.cs
index 93054c60..1383a1ed 100644
--- a/src/AgentCore.Application/Configuration/Compilation/CompiledAgentShape.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/CompiledAgentShape.cs
@@ -1,23 +1,19 @@
namespace AgentCore.Application.Configuration.Compilation;
///
-/// The row of the compile table in section 8.2 that one document selects.
+/// The row of the compile table in section 8.2 that one entry selects.
///
-///
-/// The compiler is a table, not a heuristic. A document selects exactly one row, and a document that
-/// selects none, or that holds both policy: and graph: , fails to load.
-///
public enum CompiledAgentShape
{
- /// One agents.items entry, no policy: , no graph: . It builds a ChatClientAgent .
+ /// The entry holds agent: . It builds a ChatClientAgent .
SingleAgent,
- /// agents: plus policy: . The machine picks a stage each turn, and the stage names one agent.
+ /// The entry holds policy: . The machine picks a stage each turn, and the stage names one agent.
Policy,
- /// graph: with pattern: . It builds one of the four AgentWorkflowBuilder shapes.
+ /// The entry holds graph: with pattern: . It builds one of the four AgentWorkflowBuilder shapes.
PatternGraph,
- /// graph: with nodes: and edges: . It builds a WorkflowBuilder graph.
+ /// The entry holds graph: with nodes: and edges: . It builds a WorkflowBuilder graph.
ExplicitGraph,
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs
index b73dfe23..c39e92c4 100644
--- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs
@@ -2,10 +2,8 @@
using AgentCore.Application.Configuration.Parsing;
using AgentCore.Application.Configuration.Schema;
using AgentCore.Application.Evaluation;
-using AgentCore.Application.Knowledge;
using AgentCore.Application.Ports;
using AgentCore.Application.Runtime;
-using AgentCore.Application.Skills;
using AgentCore.Application.Transcript;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
@@ -16,13 +14,13 @@ namespace AgentCore.Application.Configuration.Compilation;
///
///
///
-/// The document holds AgentCore builds
+/// The entry holds AgentCore builds
/// -
-///
one agents.items entry, no policy: , no graph:
+/// agent:
/// : ChatClientAgent , with no runtime
///
/// -
-///
agents: plus policy:
+/// policy:
/// : the machine picks a stage each turn, and the stage names one agent. Runtime is Stateless
///
/// -
@@ -34,13 +32,14 @@ namespace AgentCore.Application.Configuration.Compilation;
///
: WorkflowBuilder , agents bound as executors, then AsAIAgent()
///
/// -
-///
both policy: and graph:
+/// two of agent: , policy: , graph: , or none of them
/// a load-time error
///
///
///
-/// Each row is a . This class selects the row and builds what every
-/// row shares: the agents.items entries, their tools, and the turn-disposition layers.
+/// Each entry selects one row, and each row is a . This class selects
+/// the row each entry picks and builds what every entry shares: the agents.items entries,
+/// their tools, and the per-entry turn-disposition layers.
///
///
/// Every failure here reports through and carries a JSON
@@ -49,37 +48,41 @@ namespace AgentCore.Application.Configuration.Compilation;
///
public static class ConfigurationCompiler
{
- /// Picks the row of the compile table one document selects.
- /// The loaded document.
+ /// Picks the row of the compile table one entry selects.
+ /// The entry being compiled.
+ /// The JSON Pointer to the entry, /entries/<name> .
/// The row.
- /// The document selects no row, or selects two.
- public static CompiledAgentShape SelectShape(AgentCoreConfiguration configuration)
- => SelectRow(configuration).Shape;
-
- internal static CompileTableRow SelectRow(AgentCoreConfiguration configuration)
+ /// The entry selects no row, or selects two.
+ internal static CompileTableRow SelectEntryRow(EntryConfiguration entry, string entryPointer)
{
- ArgumentNullException.ThrowIfNull(configuration);
+ ArgumentNullException.ThrowIfNull(entry);
+ ArgumentException.ThrowIfNullOrEmpty(entryPointer);
+
+ var hasAgent = entry.Agent is not null;
+ var hasPolicy = entry.Policy is not null;
+ var hasGraph = entry.Graph is not null;
+ var selected = (hasAgent ? 1 : 0) + (hasPolicy ? 1 : 0) + (hasGraph ? 1 : 0);
- // Row 5. A document holds policy: or graph:, never both.
- if (configuration.Policy is not null && configuration.Graph is not null)
+ if (selected > 1)
{
throw Fail(
- ConfigurationError.RootPointer,
- "the document holds both policy: and graph:. Row 5 of the section 8.2 compile table "
- + "rejects that: a stage machine and a workflow graph are two runtimes, and one document "
- + "selects one row. Keep policy: for a call that walks stages, and graph: for a run that "
- + "needs checkpointing, a request port, or a parallel fan-out with a join.");
+ entryPointer,
+ "the entry holds two of agent:, policy:, and graph:. The section 8.2 compile table "
+ + "takes exactly one: agent: for one agent answering directly, policy: for a call that "
+ + "walks stages, and graph: for a run that needs checkpointing, a request port, or a "
+ + "parallel fan-out with a join.");
}
- if (configuration.Graph is { } graph)
+ if (hasGraph)
{
- // Row 3 and row 4.
+ var graph = entry.Graph!;
+ var graphPointer = ConfigurationError.AppendPointer(entryPointer, "graph");
var hasPattern = graph.Pattern is not null;
var hasNodes = graph.Nodes.Count > 0 || graph.Edges.Count > 0;
if (hasPattern && hasNodes)
{
- throw Fail("/graph", "the graph holds both pattern: and nodes:. It holds one or the other.");
+ throw Fail(graphPointer, "the graph holds both pattern: and nodes:. It holds one or the other.");
}
if (hasPattern)
@@ -92,106 +95,132 @@ internal static CompileTableRow SelectRow(AgentCoreConfiguration configuration)
return ExplicitGraphRow.Instance;
}
- throw Fail("/graph", "the graph declares neither pattern: nor nodes: and edges:.");
+ throw Fail(graphPointer, "the graph declares neither pattern: nor nodes: and edges:.");
}
- if (configuration.Policy is not null)
+ if (hasPolicy)
{
- // Row 2.
- if (configuration.Agents is null || configuration.Agents.Items.Count == 0)
- {
- throw Fail("/policy", "the document declares policy: and no agents:. Each stage names one agent.");
- }
-
return PolicyRow.Instance;
}
- // Row 1.
- if (configuration.Agents is not { } agents || agents.Items.Count == 0)
+ if (hasAgent)
{
- throw Fail(
- ConfigurationError.RootPointer,
- "the document declares no agents:, no policy:, and no graph:, so it compiles to nothing.");
- }
+ if (entry.Agent!.Length == 0)
+ {
+ throw Fail(
+ ConfigurationError.AppendPointer(entryPointer, "agent"),
+ "the entry holds an empty agent:. It names one agents.items id.");
+ }
- if (agents.Items.Count > 1)
- {
- throw Fail(
- "/agents/items",
- $"the document declares {agents.Items.Count} agents and neither policy: nor graph:, so "
- + "nothing picks between them. Row 1 of the section 8.2 compile table takes exactly one agent.");
+ return SingleAgentRow.Instance;
}
- return SingleAgentRow.Instance;
+ throw Fail(
+ entryPointer,
+ "the entry holds none of agent:, policy:, and graph:, so it compiles to nothing.");
}
- /// Compiles one document through the row it selects.
+ /// Compiles one document into one agent per entry.
/// The loaded document.
/// The seams the document names.
- /// The compiled agent. It is a process singleton: see T44.
- /// The document does not compile.
- public static CompiledAgent Compile(AgentCoreConfiguration configuration, AgentCompilationContext context)
+ /// The compiled agents, keyed by entry name. Each is a process singleton: see T44.
+ /// An entry does not compile.
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
+ public static IReadOnlyDictionary CompileAll(
+ AgentCoreConfiguration configuration,
+ AgentCompilationContext context)
{
ArgumentNullException.ThrowIfNull(configuration);
ArgumentNullException.ThrowIfNull(context);
- var row = SelectRow(configuration);
-
ICallStore calls = context.CallStore ?? new InMemoryCallStore();
AgentCoreChatHistoryProvider history = new(calls);
- var agents = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null);
+ Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders)> built = new(StringComparer.Ordinal);
+
+ Dictionary compiled = new(StringComparer.Ordinal);
+
+ foreach (var (entryName, entry) in configuration.Entries)
+ {
+ var entryPointer = ConfigurationError.AppendPointer("/entries", entryName);
+ var row = SelectEntryRow(entry, entryPointer);
- var (entry, stages) = row.BuildEntry(configuration, agents, context);
+ var shape = row.Shape;
+ var key = shape == CompiledAgentShape.SingleAgent || shape == CompiledAgentShape.Policy ? "session" : shape.ToString();
+ if (!built.TryGetValue(key, out var shared))
+ {
+ shared = BuildAgents(configuration, context, row.SessionCarriesHistory ? history : null);
+ built[key] = shared;
+ }
- var spokenBy = row.SpokenAuthors(configuration);
+ var (entryAgent, stages) = row.BuildEntry(configuration, entryName, entry, entryPointer, shared.Agents, context);
+
+ var spokenBy = row.SpokenAuthors(configuration, entry);
+
+ var fallbackReply = entry.FallbackReply ?? configuration.FallbackReply;
+ var refusalReply = entry.RefusalReply ?? configuration.RefusalReply;
+
+ compiled[entryName] = new CompiledAgent(
+ configuration,
+ entryName,
+ entry.Policy,
+ fallbackReply,
+ refusalReply,
+ row,
+ calls,
+ entryAgent,
+ shared.Agents,
+ stages,
+ spokenBy,
+ history,
+ shared.HarnessStateKeys,
+ shared.BackgroundProviders,
+ inner => WithTurnDisposition(inner, fallbackReply, refusalReply, context.Moderation, spokenBy));
+ }
- return new CompiledAgent(
- configuration,
- row,
- calls,
- entry,
- agents,
- stages,
- spokenBy,
- history,
- inner => WithTurnDisposition(inner, configuration, context.Moderation, spokenBy));
+ return compiled;
}
+#pragma warning restore MAAI001
/// Puts the two turn-disposition layers on one agent a turn runs.
- /// The compiled agent of one row, or of one policy: stage.
- /// The document. It names the fallback line and the refusal line.
+ /// The compiled agent of one entry, or of one policy: stage.
+ /// The resolved line the caller hears when a turn fails.
+ /// The resolved line the caller hears when the agent refuses to answer.
/// The endpoint seam, or to moderate nothing.
/// The agents whose reply the caller hears, or for all.
/// The agent the turn loop runs.
private static AIAgent WithTurnDisposition(
AIAgent agent,
- AgentCoreConfiguration configuration,
+ string fallbackReply,
+ string refusalReply,
PromptModerator? moderation,
IReadOnlySet? spokenBy)
{
- AIAgent layered = new FallbackAgent(agent, configuration.FallbackReply, spokenBy);
+ AIAgent layered = new FallbackAgent(agent, fallbackReply, spokenBy);
return moderation is null
? layered
- : new ModerationAgent(layered, moderation, configuration.RefusalReply, ModerationAgent.DefaultTimeout);
+ : new ModerationAgent(layered, moderation, refusalReply, ModerationAgent.DefaultTimeout);
}
+#pragma warning disable MAAI001 // BackgroundAgentsProvider is evaluation-only in Microsoft.Agents.AI 1.21.0.
/// Builds one ChatClientAgent for each agents.items entry.
/// The loaded document.
/// The seams the document names.
/// Store 1, or to leave the framework default in place.
- /// The agents, keyed by id.
- private static Dictionary BuildAgents(
+ /// The agents keyed by id, the union of every harness provider's state keys, and every background provider for the call-end release.
+ private static (Dictionary Agents, IReadOnlySet HarnessStateKeys, List BackgroundProviders) BuildAgents(
AgentCoreConfiguration configuration,
AgentCompilationContext context,
AgentCoreChatHistoryProvider? history)
{
Dictionary agents = new(StringComparer.Ordinal);
+ HashSet harnessStateKeys = new(StringComparer.Ordinal);
+ List backgroundProviders = [];
if (configuration.Agents is not { } section)
{
- return agents;
+ return (agents, harnessStateKeys, backgroundProviders);
}
var clarification = ResolvedClarification.From(configuration);
@@ -224,7 +253,7 @@ private static Dictionary BuildAgents(
Resolve(item.Id);
}
- return agents;
+ return (agents, harnessStateKeys, backgroundProviders);
AIAgent? Resolve(string id)
{
@@ -253,24 +282,35 @@ private static Dictionary BuildAgents(
}
path.Add(id);
+
+ var compiledTools = AgentToolCompiler.Build(
+ item, item.Model ?? section.Defaults?.Model, tools, context, pointer, Resolve);
+
+ var providers = AgentContextProviderCompiler.Build(
+ section.Defaults,
+ item,
+ context,
+ pointer,
+ clarification,
+ configuration.Providers?.Knowledge?.Scope,
+ Resolve,
+ backgroundProviders);
+ harnessStateKeys.UnionWith(AgentHarnessProviders.StateKeysOf(providers));
+ harnessStateKeys.UnionWith(AgentApproval.StateKeysFor(section.Defaults, item, compiledTools));
+
var built = new ChatClientAgent(
WithToolFailureAuditing(context.ChatClients.GetChatClient(item.Model ?? section.Defaults?.Model)),
new ChatClientAgentOptions
{
Name = item.Id,
+ Description = item.Description,
ChatOptions = new ChatOptions
{
Instructions = AgentInstructions.Compose(section.Defaults, item),
- Tools = AgentToolCompiler.Build(item, item.Model ?? section.Defaults?.Model, tools, context, pointer, Resolve),
+ Tools = compiledTools,
},
ChatHistoryProvider = history,
- AIContextProviders = AgentContextProviderCompiler.Build(
- section.Defaults,
- item,
- context,
- pointer,
- clarification,
- configuration.Providers?.Knowledge?.Scope),
+ AIContextProviders = providers,
});
path.RemoveAt(path.Count - 1);
@@ -278,10 +318,13 @@ private static Dictionary BuildAgents(
.UseOpenTelemetry(configure: static agent => agent.EnableSensitiveData = false)
.Build();
- agents[id] = instrumented;
- return instrumented;
+ var approved = AgentApproval.Apply(instrumented, section.Defaults, item);
+ var looped = AgentHarnessProviders.ApplyLoop(approved, section.Defaults, item, pointer);
+ agents[id] = looped;
+ return looped;
}
}
+#pragma warning restore MAAI001
/// Puts the auditing function-invocation loop into the pipeline of one agent.
private static AuditingFunctionInvokingChatClient WithToolFailureAuditing(IChatClient model)
diff --git a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs
index 6c9ddd69..1044751f 100644
--- a/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/ExplicitGraphRow.cs
@@ -1,4 +1,3 @@
-using System.Text.Json.Nodes;
using AgentCore.Application.Configuration.Parsing;
using AgentCore.Application.Configuration.Schema;
using AgentCore.Application.Runtime;
@@ -8,8 +7,8 @@
namespace AgentCore.Application.Configuration.Compilation;
///
-/// Row 4: graph: with nodes: and edges: . It builds a WorkflowBuilder ,
-/// binds the agents as executors, then AsAIAgent() .
+/// Row 4: the entry holds graph: with nodes: and edges: . It builds a
+/// WorkflowBuilder , binds the agents as executors, then AsAIAgent() .
///
internal sealed class ExplicitGraphRow : CompileTableRow
{
@@ -19,10 +18,16 @@ internal sealed class ExplicitGraphRow : CompileTableRow
internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
AgentCoreConfiguration configuration,
+ string entryName,
+ EntryConfiguration entry,
+ string entryPointer,
Dictionary agents,
AgentCompilationContext context)
{
- var graph = configuration.Graph!;
+ var graph = entry.Graph!;
+ var graphPointer = ConfigurationError.AppendPointer(entryPointer, "graph");
+ var nodesPointer = ConfigurationError.AppendPointer(graphPointer, "nodes");
+ var edgesPointer = ConfigurationError.AppendPointer(graphPointer, "edges");
Dictionary nodes = new(StringComparer.Ordinal);
List starts = [];
@@ -31,7 +36,7 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
for (var index = 0; index < graph.Nodes.Count; index++)
{
var node = graph.Nodes[index];
- var pointer = ConfigurationError.AppendPointer("/graph/nodes", index);
+ var pointer = ConfigurationError.AppendPointer(nodesPointer, index);
if (node.Agent is not { } agentId || !agents.TryGetValue(agentId, out var agent))
{
@@ -66,17 +71,21 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
if (starts.Count != 1)
{
throw ConfigurationCompiler.Fail(
- "/graph/nodes",
+ nodesPointer,
$"the graph declares {starts.Count} start nodes. Check 7 of section 8.5 needs exactly one.");
}
- WorkflowBuilder builder = new(nodes[starts[0].Id]);
- Func>? guardedState = null;
+ var stateEntry = ExecutorBindingExtensions.BindExecutor(new GraphStateEntry());
+
+ WorkflowBuilder builder = new(stateEntry);
+ builder = builder.AddEdge(stateEntry, nodes[starts[0].Id]);
+
+ var guarded = false;
for (var index = 0; index < graph.Edges.Count; index++)
{
var edge = graph.Edges[index];
- var pointer = ConfigurationError.AppendPointer("/graph/edges", index);
+ var pointer = ConfigurationError.AppendPointer(edgesPointer, index);
if (!nodes.TryGetValue(edge.From, out var from))
{
@@ -98,24 +107,33 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
continue;
}
- if (context.Guards is not { } evaluator || context.StateSnapshot is not { } snapshot)
+ if (context.Guards is not { } evaluator)
{
throw ConfigurationCompiler.Fail(
ConfigurationError.AppendPointer(pointer, "when"),
- $"the edge carries a guard, and the compilation context binds {Missing(context)}. Bind "
- + "both: AgentCompilationContext.Guards runs the rule, and "
- + "AgentCompilationContext.StateSnapshot reads the state of the call that runs now. "
- + "AddAgentCore binds them to GuardEvaluator and to CallStateScope.Snapshot. A guarded "
- + "edge that silently became unconditional is exactly the silent graph failure "
- + "section 8.2 refuses to ship.");
+ "the edge carries a guard, and the compilation context binds no guard evaluator. Bind "
+ + "AgentCompilationContext.Guards, which runs the rule. AddAgentCore binds it to "
+ + "GuardEvaluator. A guarded edge that silently became unconditional is exactly "
+ + "the silent graph failure section 8.2 refuses to ship.");
}
-
- // The predicate captures no state of its own. The compiled graph is a process singleton
- // under T44, so it asks the context for the state of the call that runs now. object, not
- // List: the guard reads state, so every message on the edge takes the same
- // answer and the turn token is not filtered out.
- builder = builder.AddEdge(from, to, _ => evaluator.Evaluate(guard, snapshot()));
- guardedState = snapshot;
+
+ // One gate per guarded edge, holding the run until its guard is true. The gate is a
+ // workflow executor rather than an edge predicate because the predicate only ever sees
+ // the edge message: per-call state reaches the gate through the run, filed by the
+ // graph-state entry. object, not List: the guard reads state, so every
+ // message on the edge takes the same answer and the turn token is not filtered out.
+ var gate = new FunctionExecutor(
+ $"agentcore-gate-{index}",
+ (message, gateContext, gateToken) => GraphGuardGate.RouteAsync(
+ message, gateContext, guard, evaluator, gateToken),
+ null,
+ [typeof(object)],
+ null,
+ true);
+
+ builder = builder.AddEdge(from, gate);
+ builder = builder.AddEdge(gate, to);
+ guarded = true;
}
if (outputs.Count > 0)
@@ -123,21 +141,22 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
builder = builder.WithOutputFrom([.. outputs]);
}
- var compiled = builder.WithName(configuration.Name)
+ var compiled = builder.WithName(entryName)
.Build()
- .AsAIAgent(name: configuration.Name);
+ .AsAIAgent(name: entryName);
+
+ AIAgent withOutputCheck = new RequireOutputAgent(compiled, entryName);
- AIAgent withOutputCheck = new RequireOutputAgent(compiled, configuration.Name);
return (
- guardedState is null ? withOutputCheck : new RequireStateAgent(withOutputCheck, guardedState),
+ guarded ? new GraphStateAgent(withOutputCheck, entryName) : withOutputCheck,
NoStages());
}
/// An explicit graph answers from its output: true nodes.
- internal override HashSet? SpokenAuthors(AgentCoreConfiguration configuration)
+ internal override HashSet? SpokenAuthors(AgentCoreConfiguration configuration, EntryConfiguration entry)
{
HashSet outputs = new(StringComparer.Ordinal);
- foreach (var node in configuration.Graph!.Nodes)
+ foreach (var node in entry.Graph!.Nodes)
{
if (node.Output && node.Agent is { } agentId)
{
@@ -147,14 +166,4 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
return outputs.Count == 0 ? null : outputs;
}
-
- /// Names the seams a guarded edge needs and the context left unbound.
- /// The seams the document names.
- /// The phrase the failure message carries.
- private static string Missing(AgentCompilationContext context) => (context.Guards, context.StateSnapshot) switch
- {
- (null, null) => "no guard evaluator and no state source",
- (null, _) => "no guard evaluator",
- _ => "no state source",
- };
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs b/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs
new file mode 100644
index 00000000..f3b60a04
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Compilation/GraphGuardGate.cs
@@ -0,0 +1,52 @@
+using System.Text.Json.Nodes;
+using AgentCore.Application.Configuration.Schema;
+using AgentCore.Application.Configuration.Validation;
+using Microsoft.Agents.AI.Workflows;
+
+namespace AgentCore.Application.Configuration.Compilation;
+
+internal static class GraphGuardGate
+{
+ /// The reason a gate reports when the run carries no state.
+ internal const string NoStateMessage =
+ "A guarded graph edge asked for the state of the running call, and the run carries none. "
+ + "Row 4 of the section 8.2 compile table reads the state of one call, and the graph-state "
+ + "wrapper files it from the turn before the run starts. Run the graph through a CallSession, "
+ + "which files the turn on the run's session. This throws and does not answer false, because "
+ + "a guarded edge that quietly became unconditional is the silent graph failure section 8.2 "
+ + "refuses to ship.";
+
+ /// Forwards one edge message past a guarded edge, or holds it when the guard is false.
+ /// The message that reached the edge, forwarded unchanged.
+ /// The run the edge belongs to, carrying the filed snapshot.
+ /// The edge's when: guard.
+ /// The shared evaluator that runs the rule.
+ /// Cancels the read.
+ /// The run carries no state.
+ internal static async ValueTask RouteAsync(
+ object? message,
+ IWorkflowContext context,
+ GuardReference guard,
+ IGuardEvaluator evaluator,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ ArgumentNullException.ThrowIfNull(guard);
+ ArgumentNullException.ThrowIfNull(evaluator);
+
+ var snapshot = await context
+ .ReadStateAsync>(
+ GraphStateEntry.SlotsKey, GraphStateEntry.StateScope, cancellationToken)
+ .ConfigureAwait(false);
+
+ if (snapshot is null)
+ {
+ throw new InvalidOperationException(NoStateMessage);
+ }
+
+ if (evaluator.Evaluate(guard, snapshot))
+ {
+ await context.SendMessageAsync(message!, cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs b/src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs
new file mode 100644
index 00000000..72dc7fd8
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Compilation/GraphStateCarrier.cs
@@ -0,0 +1,44 @@
+using System.Text.Json.Nodes;
+using Microsoft.Extensions.AI;
+
+namespace AgentCore.Application.Configuration.Compilation;
+
+internal static class GraphStateCarrier
+{
+ /// The message key the snapshot rides under.
+ internal const string ArgumentsKey = "urn:agentcore:graph-state";
+
+ /// Builds the carrier heading one run's request messages.
+ /// Every declared slot and the three reserved slots, read at run start.
+ /// A content-free message only the graph-state entry reads.
+ internal static ChatMessage Build(IReadOnlyDictionary snapshot)
+ {
+ ArgumentNullException.ThrowIfNull(snapshot);
+
+ return new ChatMessage(ChatRole.System, string.Empty)
+ {
+ AdditionalProperties = new AdditionalPropertiesDictionary { [ArgumentsKey] = snapshot },
+ };
+ }
+
+ /// Takes the snapshot off the head of one run's request, when it carries one.
+ /// The run's accumulated messages, oldest first.
+ /// The snapshot, without the carrier around it.
+ /// Whether a carrier headed the messages. The carrier is removed either way it answers.
+ internal static bool TryTake(List messages, out IReadOnlyDictionary? snapshot)
+ {
+ ArgumentNullException.ThrowIfNull(messages);
+
+ snapshot = null;
+ if (messages.Count == 0
+ || messages[0].AdditionalProperties?.TryGetValue(ArgumentsKey, out var filed) != true
+ || filed is not IReadOnlyDictionary carried)
+ {
+ return false;
+ }
+
+ messages.RemoveAt(0);
+ snapshot = carried;
+ return true;
+ }
+}
diff --git a/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs b/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs
new file mode 100644
index 00000000..4dc1e0fd
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Compilation/GraphStateEntry.cs
@@ -0,0 +1,39 @@
+using Microsoft.Agents.AI.Workflows;
+using Microsoft.Extensions.AI;
+
+namespace AgentCore.Application.Configuration.Compilation;
+
+internal sealed class GraphStateEntry : ChatProtocolExecutor
+{
+ /// The workflow scope the snapshot is filed under. Named, because the default
+ /// scope belongs to each executor alone and a gate would read its own empty one.
+ internal const string StateScope = "graph-state";
+
+ /// The workflow state key the snapshot is filed under.
+ internal const string SlotsKey = "slots";
+
+ /// Creates the entry of one compiled graph.
+ internal GraphStateEntry()
+ : base("agentcore-graph-entry", new ChatProtocolExecutorOptions { AutoSendTurnToken = true }, true)
+ {
+ }
+
+ ///
+ protected override async ValueTask TakeTurnAsync(
+ List messages,
+ IWorkflowContext context,
+ bool? emitEvents,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(messages);
+ ArgumentNullException.ThrowIfNull(context);
+
+ if (GraphStateCarrier.TryTake(messages, out var snapshot) && snapshot is not null)
+ {
+ await context.QueueStateUpdateAsync(SlotsKey, snapshot, StateScope, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ await context.SendMessageAsync(messages, cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs b/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs
index 6fa20ff5..5b4ee85e 100644
--- a/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/PatternGraphRow.cs
@@ -6,8 +6,9 @@
namespace AgentCore.Application.Configuration.Compilation;
///
-/// Row 3: graph: with pattern: . It builds AgentWorkflowBuilder.BuildSequential ,
-/// BuildConcurrent , CreateHandoffBuilderWith , or CreateGroupChatBuilderWith .
+/// Row 3: the entry holds graph: with pattern: . It builds
+/// AgentWorkflowBuilder.BuildSequential , BuildConcurrent ,
+/// CreateHandoffBuilderWith , or CreateGroupChatBuilderWith .
///
internal sealed class PatternGraphRow : CompileTableRow
{
@@ -17,10 +18,15 @@ internal sealed class PatternGraphRow : CompileTableRow
internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
AgentCoreConfiguration configuration,
+ string entryName,
+ EntryConfiguration entry,
+ string entryPointer,
Dictionary agents,
AgentCompilationContext context)
{
- var graph = configuration.Graph!;
+ var graph = entry.Graph!;
+ var graphPointer = ConfigurationError.AppendPointer(entryPointer, "graph");
+ var agentsPointer = ConfigurationError.AppendPointer(graphPointer, "agents");
List participants = [];
for (var index = 0; index < graph.Agents.Count; index++)
@@ -29,7 +35,7 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
if (!agents.TryGetValue(id, out var agent))
{
throw ConfigurationCompiler.Fail(
- ConfigurationError.AppendPointer("/graph/agents", index),
+ ConfigurationError.AppendPointer(agentsPointer, index),
$"the graph names the agent '{id}', which agents.items does not declare.");
}
@@ -38,18 +44,18 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
if (participants.Count == 0)
{
- throw ConfigurationCompiler.Fail("/graph/agents", "a pattern graph names no agent.");
+ throw ConfigurationCompiler.Fail(agentsPointer, "a pattern graph names no agent.");
}
var workflow = graph.Pattern switch
{
- GraphPattern.Sequential => AgentWorkflowBuilder.BuildSequential(configuration.Name, participants),
- GraphPattern.Concurrent => AgentWorkflowBuilder.BuildConcurrent(configuration.Name, participants, aggregator: null),
- GraphPattern.Handoff => BuildHandoff(configuration.Name, participants),
- _ => BuildGroupChat(configuration.Name, participants),
+ GraphPattern.Sequential => AgentWorkflowBuilder.BuildSequential(entryName, participants),
+ GraphPattern.Concurrent => AgentWorkflowBuilder.BuildConcurrent(entryName, participants, aggregator: null),
+ GraphPattern.Handoff => BuildHandoff(entryName, participants),
+ _ => BuildGroupChat(entryName, participants),
};
- return (workflow.AsAIAgent(name: configuration.Name), NoStages());
+ return (workflow.AsAIAgent(name: entryName), NoStages());
}
///
@@ -57,8 +63,8 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
/// participant, and handoff and group chat both end wherever the conversation took them, so on
/// those patterns any participant may legitimately speak last and no filter applies.
///
- internal override HashSet? SpokenAuthors(AgentCoreConfiguration configuration)
- => configuration.Graph is { Pattern: GraphPattern.Sequential, Agents.Count: > 0 } graph
+ internal override HashSet? SpokenAuthors(AgentCoreConfiguration configuration, EntryConfiguration entry)
+ => entry.Graph is { Pattern: GraphPattern.Sequential, Agents.Count: > 0 } graph
? new HashSet(StringComparer.Ordinal) { graph.Agents[^1] }
: null;
diff --git a/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs b/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs
index f0521dd7..3cbda430 100644
--- a/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/PolicyRow.cs
@@ -5,7 +5,7 @@
namespace AgentCore.Application.Configuration.Compilation;
///
-/// Row 2: agents: plus policy: . The machine picks a stage each turn, the stage names
+/// Row 2: the entry holds policy: . The machine picks a stage each turn, the stage names
/// one agent, and that agent's run answers the caller. Runtime is Stateless .
///
internal sealed class PolicyRow : CompileTableRow
@@ -21,15 +21,22 @@ internal sealed class PolicyRow : CompileTableRow
internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
AgentCoreConfiguration configuration,
+ string entryName,
+ EntryConfiguration entry,
+ string entryPointer,
Dictionary agents,
AgentCompilationContext context)
{
- var policy = configuration.Policy!;
+ var policy = entry.Policy!;
+ var policyPointer = ConfigurationError.AppendPointer(entryPointer, "policy");
+ var initialPointer = ConfigurationError.AppendPointer(policyPointer, "initial");
Dictionary stages = new(StringComparer.Ordinal);
for (var index = 0; index < policy.Stages.Count; index++)
{
var stage = policy.Stages[index];
+ var stagePointer = ConfigurationError.AppendPointer(
+ ConfigurationError.AppendPointer(policyPointer, "stages"), index);
if (stage.Agent is not { } agentId)
{
stages[stage.Id] = NoAgentId;
@@ -39,8 +46,7 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
if (!agents.ContainsKey(agentId))
{
throw ConfigurationCompiler.Fail(
- ConfigurationError.AppendPointer(
- ConfigurationError.AppendPointer("/policy/stages", index), "agent"),
+ ConfigurationError.AppendPointer(stagePointer, "agent"),
$"the stage '{stage.Id}' names the agent '{agentId}', which agents.items does not declare.");
}
@@ -50,14 +56,14 @@ internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
if (!stages.TryGetValue(policy.Initial, out var initialAgent))
{
throw ConfigurationCompiler.Fail(
- "/policy/initial",
+ initialPointer,
$"the initial stage '{policy.Initial}' is not declared in policy.stages.");
}
if (initialAgent.Length == 0)
{
throw ConfigurationCompiler.Fail(
- "/policy/initial",
+ initialPointer,
$"the initial stage '{policy.Initial}' names no agent, so no turn can run.");
}
diff --git a/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs b/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs
index d2d305e6..02e26d52 100644
--- a/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs
+++ b/src/AgentCore.Application/Configuration/Compilation/SingleAgentRow.cs
@@ -1,10 +1,11 @@
+using AgentCore.Application.Configuration.Parsing;
using AgentCore.Application.Configuration.Schema;
using Microsoft.Agents.AI;
namespace AgentCore.Application.Configuration.Compilation;
///
-/// Row 1: one agents.items entry, no policy: , no graph: . The one agent is the
+/// Row 1: the entry holds agent: . The named agents.items entry is the
/// entry, and its run's own last message is the reply.
///
internal sealed class SingleAgentRow : CompileTableRow
@@ -17,7 +18,28 @@ internal sealed class SingleAgentRow : CompileTableRow
internal override (AIAgent Entry, Dictionary Stages) BuildEntry(
AgentCoreConfiguration configuration,
+ string entryName,
+ EntryConfiguration entry,
+ string entryPointer,
Dictionary agents,
AgentCompilationContext context)
- => (agents[configuration.Agents!.Items[0].Id], NoStages());
+ {
+ var agentPointer = ConfigurationError.AppendPointer(entryPointer, "agent");
+
+ if (entry.Agent is not { Length: > 0 } agentId)
+ {
+ throw ConfigurationCompiler.Fail(
+ agentPointer,
+ $"the entry '{entryName}' names no agent, so nothing runs.");
+ }
+
+ if (!agents.TryGetValue(agentId, out var agent))
+ {
+ throw ConfigurationCompiler.Fail(
+ agentPointer,
+ $"the entry '{entryName}' names the agent '{agentId}', which agents.items does not declare.");
+ }
+
+ return (agent, NoStages());
+ }
}
diff --git a/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs b/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs
index a5c2f8d7..bd134d32 100644
--- a/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs
+++ b/src/AgentCore.Application/Configuration/Parsing/ConfigurationSchemaValidator.cs
@@ -193,11 +193,12 @@ private static bool Speculative(EvaluationResults node)
? $"this key is written exactly '{only[0]}', and nothing else"
: "the value is not the one this key holds",
- "pattern" => Keyword(node, "pattern")?.GetValue() is not { } pattern
- ? "the value is not written in the form this key requires"
- : pattern == @"\S"
- ? "the text holds no words, and this key needs some"
- : $"the text is not written in the form this key requires: {pattern}",
+ "pattern" => Keyword(node, "pattern")?.GetValue() switch
+ {
+ null => "the value is not written in the form this key requires",
+ @"\S" => "the text holds no words, and this key needs some",
+ var form => $"the text is not written in the form this key requires: {form}",
+ },
"minLength" or "maxLength" => Bound(message) is { } length
? $"the text holds too {length.Way} characters, and this key takes at {length.Limit}"
@@ -342,9 +343,15 @@ private static List Alternatives(EvaluationResults node)
/// The text the library wrote.
/// Which way the bound runs and what it is, or when the message does not carry one.
private static (string Way, string Limit)? Bound(string message)
- => BoundPattern().Match(message) is { Success: true } bound
- ? (bound.Groups[1].Value == "least" ? "few" : "many", $"{bound.Groups[1].Value} {bound.Groups[2].Value}")
- : null;
+ {
+ if (BoundPattern().Match(message) is not { Success: true } bound)
+ {
+ return null;
+ }
+
+ var way = bound.Groups[1].Value == "least" ? "few" : "many";
+ return (way, $"{bound.Groups[1].Value} {bound.Groups[2].Value}");
+ }
private static string ReadResource()
{
diff --git a/src/AgentCore.Application/Configuration/Schema/AgentCoreConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentCoreConfiguration.cs
index 8c8e5950..42779493 100644
--- a/src/AgentCore.Application/Configuration/Schema/AgentCoreConfiguration.cs
+++ b/src/AgentCore.Application/Configuration/Schema/AgentCoreConfiguration.cs
@@ -26,54 +26,18 @@ public sealed record AgentCoreConfiguration
public const string SupportedApiVersion = "agentcore/v1";
/// The spoken fallback used when the document names none.
- ///
- /// Section 8.7 asks for a spoken fallback and names no text. This sentence is short, it is
- /// speakable, and it asks the caller to go on, so the call survives the turn that failed.
- ///
public const string DefaultFallbackReply = "I am sorry. I could not finish that. Please say it again.";
/// The spoken refusal used when the document names none.
- ///
- /// The sentence is short and it is speakable, and it does not ask the caller to say the request
- /// again. does ask, and after a refusal that invites the
- /// harmful request a second time.
- ///
public const string DefaultRefusalReply = "I am sorry. I cannot help with that request.";
/// Gets the document version. It is always .
public required string ApiVersion { get; init; }
- /// Gets the name of the configured agent.
- public required string Name { get; init; }
-
/// Gets the line the caller hears when a turn fails.
- ///
- /// Section 8.7 names two failures that end a turn with a spoken fallback: a run that returns no
- /// text after 40 tool rounds, and a tool that fails four times in a row. The key sits at the root
- /// of the document because every shape speaks it: a single agent, a policy: document, and
- /// a graph: document all end a failed turn the same way. It defaults to
- /// , and a document may not set an empty line.
- ///
public string FallbackReply { get; init; } = DefaultFallbackReply;
/// Gets the line the caller hears when the agent refuses to answer.
- ///
- ///
- /// Content moderation reads the caller's spoken input before the model runs, and the agent
- /// refuses the turn when the endpoint flags it. The key sits at the root of the document beside
- /// , because every shape speaks it: a single agent, a
- /// policy: document, and a graph: document all refuse the same way. It defaults to
- /// , and a document may not set an empty line.
- ///
- ///
- /// cannot serve here, for two reasons. First, its default text is
- /// "I am sorry. I could not finish that. Please say it again." Spoken after a refusal, that line
- /// invites the caller to repeat the harmful request. Second, section 8.7 makes
- /// the line for a turn that FAILED: a run that returns no text after
- /// 40 tool rounds, or a tool that failed four times. A refusal is not a failure, because the
- /// model was never asked.
- ///
- ///
public string RefusalReply { get; init; } = DefaultRefusalReply;
/// Gets the declared state slots, keyed by slot name.
@@ -89,21 +53,13 @@ public sealed record AgentCoreConfiguration
public IReadOnlyList Tools { get; init; } = [];
/// Gets the declared MCP servers, in document order.
- ///
- /// One entry becomes many tools, whose names and schemas are only known once the server answers,
- /// which is why they are not tools: entries. The ids they serve under are ordinary tool
- /// ids, so an agent's tools: list references them like any other.
- ///
public IReadOnlyList Mcp { get; init; } = [];
- /// Gets the agent section, or when the document declares none.
- public AgentsConfiguration? Agents { get; init; }
-
- /// Gets the stage machine, or when the document declares none.
- public PolicyConfiguration? Policy { get; init; }
+ /// Gets the shared agent pool.
+ public required AgentsConfiguration Agents { get; init; }
- /// Gets the workflow graph, or when the document declares none.
- public GraphConfiguration? Graph { get; init; }
+ /// Gets the named entries, keyed by entry name. The key is the agent name.
+ public required IReadOnlyDictionary Entries { get; init; }
/// Gets the adapter settings, or when the document declares none.
public ProvidersConfiguration? Providers { get; init; }
diff --git a/src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs
new file mode 100644
index 00000000..6e1716ad
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Schema/AgentLoopConfiguration.cs
@@ -0,0 +1,27 @@
+namespace AgentCore.Application.Configuration.Schema;
+
+///
+/// The options one loop.until: entry carries. Empty today: the entry names the condition by
+/// its key. A condition that ever takes options adds members here.
+///
+public sealed record LoopConditionOptions { }
+
+/// One loop.until: entry. Exactly one member is set.
+public sealed record LoopUntilConfiguration
+{
+ /// Gets the condition that the todo list drains to empty. Set, or .
+ public LoopConditionOptions? Todos { get; init; }
+
+ /// Gets the condition that every background task finishes. Set, or .
+ public LoopConditionOptions? Background { get; init; }
+}
+
+/// One agent's loop: block: how many model rounds the agent owns may run, and when none stays.
+public sealed record LoopConfiguration
+{
+ /// Gets the most rounds the loop may run, or for the framework default.
+ public int? MaxRounds { get; init; }
+
+ /// Gets the conditions that end the loop early, in document order, or for none.
+ public IReadOnlyList? Until { get; init; }
+}
\ No newline at end of file
diff --git a/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs
new file mode 100644
index 00000000..4b9247a1
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Schema/AgentMemoryConfiguration.cs
@@ -0,0 +1,34 @@
+namespace AgentCore.Application.Configuration.Schema;
+
+/// The stores an agentic file block may name.
+public enum AgentFileStoreKind
+{
+ ///
+ /// The host-created per-call directory: AgentCoreOptions.WorkspaceRoot/<callId>/ ,
+ /// created with the call and deleted with it. The one store no process decides for a caller.
+ ///
+ Workspace,
+}
+
+///
+/// One agent's memory: block: the file_memory_* tools over a store. The provider
+/// keeps its working folder in the session state (§3.5), so a resumed call reads the same files.
+///
+public sealed record AgentMemoryConfiguration
+{
+ /// Gets the store the file-memory tools reach.
+ public required AgentFileStoreKind Store { get; init; }
+}
+
+///
+/// One agent's files: block: the file_access_* tools over a store. Today every
+/// file_access_* tool is approval-required by default, reads included (§3.6).
+///
+public sealed record AgentFilesConfiguration
+{
+ /// Gets the store the file-access tools reach.
+ public required AgentFileStoreKind Store { get; init; }
+
+ /// Gets whether the write tools are enabled. write: false leaves read, read_lines, ls, grep.
+ public bool Write { get; init; } = true;
+}
\ No newline at end of file
diff --git a/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs
new file mode 100644
index 00000000..9f76730f
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Schema/AgentShellConfiguration.cs
@@ -0,0 +1,40 @@
+namespace AgentCore.Application.Configuration.Schema;
+
+/// The executors a shell: block may name.
+public enum ShellKind
+{
+ /// A throwaway container: network "none", read-only root, nobody user (§3.6).
+ Docker,
+
+ /// The process's own executable environment, confined to the workspace directory.
+ Local,
+}
+
+///
+/// One agent's shell policy: the regexes that refuse a command before it dispatches. A guardrail
+/// for the model, not a security boundary — the executor confinement is the boundary.
+///
+public sealed record ShellPolicyConfiguration
+{
+ /// Gets the patterns whose match refuses a command.
+ public IReadOnlyList Deny { get; init; } = [];
+
+ /// Gets the patterns an allowed command must match.
+ public IReadOnlyList Allow { get; init; } = [];
+}
+
+/// One agent's shell: block: one executor per call, removed with it (§4.4).
+public sealed record ShellConfiguration
+{
+ ///
+ /// Gets the executor kind. Deliberately required: where a shell runs is the consumer's call, so
+ /// no default exists here (§4.5.1).
+ ///
+ public required ShellKind Kind { get; init; }
+
+ /// Gets the command policy, or for none.
+ public ShellPolicyConfiguration? Policy { get; init; }
+
+ /// Gets how long one command may run, or for the executor default.
+ public int? TimeoutSeconds { get; init; }
+}
\ No newline at end of file
diff --git a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs
index f2948f57..4926a495 100644
--- a/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs
+++ b/src/AgentCore.Application/Configuration/Schema/AgentsConfiguration.cs
@@ -50,6 +50,15 @@ public sealed record AgentDefaults
/// Gets the shared compaction: block, or when the document declares none.
public CompactionConfiguration? Compaction { get; init; }
+
+ /// Gets whether agents inherit the todo tools, or to name nothing.
+ public bool? Todos { get; init; }
+
+ /// Gets whether agents inherit the mode tools, or to name nothing.
+ public bool? Mode { get; init; }
+
+ /// Gets the shared approval: block, or when the document declares none.
+ public ApprovalConfiguration? Approval { get; init; }
}
///
@@ -60,6 +69,12 @@ public sealed record AgentConfiguration
/// Gets the agent id. A stage or a graph node names this id.
public required string Id { get; init; }
+ ///
+ /// Gets the one-line summary a parent sees when this agent is listed as a background child,
+ /// or to list the id alone.
+ ///
+ public string? Description { get; init; }
+
/// Gets the instruction delta this agent appends below the shared prefix.
public string? Instructions { get; init; }
@@ -77,6 +92,33 @@ public sealed record AgentConfiguration
/// Gets this agent's compaction: block, or to inherit key by key.
public CompactionConfiguration? Compaction { get; init; }
+
+ /// Gets whether this agent gets the todo tools, or to inherit.
+ public bool? Todos { get; init; }
+
+ /// Gets whether this agent gets the mode tools, or to inherit.
+ public bool? Mode { get; init; }
+
+ /// Gets this agent's memory: block, or for none.
+ public AgentMemoryConfiguration? Memory { get; init; }
+
+ /// Gets this agent's files: block, or for none.
+ public AgentFilesConfiguration? Files { get; init; }
+
+ ///
+ /// Gets this agent's shell: block, or for none. One executor per
+ /// call, never a process singleton.
+ ///
+ public ShellConfiguration? Shell { get; init; }
+
+ /// Gets this agent's approval: block, or to inherit key by key.
+ public ApprovalConfiguration? Approval { get; init; }
+
+ /// Gets the ids of the background children this agent may start. Same list as agents.items .
+ public IReadOnlyList Background { get; init; } = [];
+
+ /// Gets this agent's loop: block, or for none.
+ public LoopConfiguration? Loop { get; init; }
}
///
diff --git a/src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs
new file mode 100644
index 00000000..beae44bf
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Schema/ApprovalConfiguration.cs
@@ -0,0 +1,14 @@
+namespace AgentCore.Application.Configuration.Schema;
+
+///
+/// One agent's approval: block: the standing rules that answer an approval request before it
+/// surfaces. Everything a rule does not name still asks.
+///
+public sealed record ApprovalConfiguration
+{
+ ///
+ /// Gets the tool-name patterns a request never surfaces for. A pattern names one tool exactly,
+ /// or a prefix with a trailing * .
+ ///
+ public IReadOnlyList Auto { get; init; } = [];
+}
\ No newline at end of file
diff --git a/src/AgentCore.Application/Configuration/Schema/EntryConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/EntryConfiguration.cs
new file mode 100644
index 00000000..695fc198
--- /dev/null
+++ b/src/AgentCore.Application/Configuration/Schema/EntryConfiguration.cs
@@ -0,0 +1,22 @@
+namespace AgentCore.Application.Configuration.Schema;
+
+///
+/// One named entry. The entry key is the agent name.
+///
+public sealed record EntryConfiguration
+{
+ /// Gets the id of the agent in the shared pool, or .
+ public string? Agent { get; init; }
+
+ /// Gets the stage machine, or when the entry declares none.
+ public PolicyConfiguration? Policy { get; init; }
+
+ /// Gets the workflow graph, or when the entry declares none.
+ public GraphConfiguration? Graph { get; init; }
+
+ /// Gets the entry override for the spoken fallback, or to inherit the root line.
+ public string? FallbackReply { get; init; }
+
+ /// Gets the entry override for the spoken refusal, or to inherit the root line.
+ public string? RefusalReply { get; init; }
+}
diff --git a/src/AgentCore.Application/Configuration/Schema/GraphConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/GraphConfiguration.cs
index ab65da0c..12f03c61 100644
--- a/src/AgentCore.Application/Configuration/Schema/GraphConfiguration.cs
+++ b/src/AgentCore.Application/Configuration/Schema/GraphConfiguration.cs
@@ -62,12 +62,12 @@ public sealed record GraphEdgeConfiguration
}
///
-/// The graph: section. It holds either a pattern or a node and edge list, never both.
+/// An entry's graph: block. It holds either a pattern or a node and edge list, never both.
///
///
/// Section 8.2 compiles the first form through AgentWorkflowBuilder and the second through
-/// WorkflowBuilder and AsAIAgent() . A document that holds both policy: and
-/// graph: is a load-time error.
+/// WorkflowBuilder and AsAIAgent() . An entry that holds more than one of
+/// agent: , policy: , and graph: is a load-time error.
///
public sealed record GraphConfiguration
{
diff --git a/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs
index 46e4da97..886f077a 100644
--- a/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs
+++ b/src/AgentCore.Application/Configuration/Schema/LlmProviderConfiguration.cs
@@ -25,4 +25,10 @@ public sealed record LlmProviderConfiguration
/// vendor's adapter decide.
///
public bool? WebSearch { get; init; }
+
+ ///
+ /// Gets whether this entry may run hosted code execution, or to let the
+ /// vendor's adapter decide.
+ ///
+ public bool? CodeExecute { get; init; }
}
diff --git a/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs
index 26b9850c..06b678b8 100644
--- a/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs
+++ b/src/AgentCore.Application/Configuration/Schema/PolicyConfiguration.cs
@@ -44,7 +44,7 @@ public sealed record StageConfiguration
}
///
-/// The policy: section: a stage machine over string stages, run by Stateless .
+/// An entry's policy: block: a stage machine over string stages, run by Stateless .
///
public sealed record PolicyConfiguration
{
diff --git a/src/AgentCore.Application/Configuration/Schema/ToolConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ToolConfiguration.cs
index 49718752..1cdad795 100644
--- a/src/AgentCore.Application/Configuration/Schema/ToolConfiguration.cs
+++ b/src/AgentCore.Application/Configuration/Schema/ToolConfiguration.cs
@@ -21,9 +21,9 @@ public enum ToolKind
///
///
/// This is agent-as-tool, and it is not handoff. The outer agent sees one function, calls it,
- /// and keeps control. The inner agent runs its own tool-calling loop and returns text. Handoff
- /// transfers control instead, and graph: with pattern: handoff already carries it,
- /// so the two do not overlap. Check 8 of section 8.5 walks the edges this kind declares.
+ /// and keeps control. Handoff transfers control instead, and an entry's graph: with
+ /// pattern: handoff already carries it, so the two do not overlap. Check 8 of section 8.5
+ /// walks the edges this kind declares.
///
Agent,
}
@@ -78,18 +78,9 @@ public sealed record ToolConfiguration
/// Gets the HTTP call. It is set when the kind is .
public HttpRequestConfiguration? Request { get; init; }
- /// Gets the model this tool runs on, or to use the host default.
- ///
- /// Only a uses: naming a shipped agent reads this. Drawing on the primary reply model is
- /// wasted money, so a document points the inner call at a cheaper entry of
- /// providers.llm[].as . A kind with no model of its own ignores it.
- ///
+ /// Reserved. No kind: builtin tool reads it; setting it fails the load.
public ModelReference? Model { get; init; }
- /// Gets the round cap of a shipped agent, or to use its own default.
- ///
- /// It counts model round trips inside the tool, and it is not the section 8.7 budget of the
- /// calling agent, which is 40 and counts this whole tool as one round.
- ///
+ /// Reserved. No kind: builtin tool reads it; setting it fails the load.
public int? MaxRounds { get; init; }
}
diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json
index 5636e7b2..00f85e2f 100644
--- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json
+++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json
@@ -6,7 +6,8 @@
"type": "object",
"required": [
"apiVersion",
- "name"
+ "agents",
+ "entries"
],
"additionalProperties": false,
"properties": {
@@ -14,22 +15,17 @@
"const": "agentcore/v1",
"description": "The only version this schema accepts."
},
- "name": {
- "type": "string",
- "minLength": 1,
- "description": "The name of the configured agent."
- },
"fallbackReply": {
"type": "string",
"minLength": 1,
"pattern": "\\S",
- "description": "Section 8.7: the line the caller hears when a turn fails. It sits at the root because every document shape speaks it. The default is the sentence AgentCore ships."
+ "description": "Section 8.7: the line the caller hears when a turn fails. The root default; an entry may override it. The default is the sentence AgentCore ships."
},
"refusalReply": {
"type": "string",
"minLength": 1,
"pattern": "\\S",
- "description": "The line the caller hears when the agent refuses to answer. Content moderation reads the caller's spoken input before the model runs, and the agent refuses the turn when the endpoint flags it. It sits at the root beside fallbackReply because every document shape speaks it. The key is optional, and the default is the sentence AgentCore ships. fallbackReply cannot serve here: its default asks the caller to say it again, which invites the harmful request a second time, and section 8.7 gives fallbackReply to a turn that failed, while a refusal never asks the model at all."
+ "description": "The line the caller hears when the agent refuses to answer. Content moderation reads the caller's spoken input before the model runs, and the agent refuses the turn when the endpoint flags it. The root default beside fallbackReply; an entry may override it. The key is optional, and the default is the sentence AgentCore ships. fallbackReply cannot serve here: its default asks the caller to say it again, which invites the harmful request a second time, and section 8.7 gives fallbackReply to a turn that failed, while a refusal never asks the model at all."
},
"state": {
"type": "object",
@@ -70,11 +66,15 @@
"agents": {
"$ref": "#/$defs/agents"
},
- "policy": {
- "$ref": "#/$defs/policy"
- },
- "graph": {
- "$ref": "#/$defs/graph"
+ "entries": {
+ "type": "object",
+ "minProperties": 1,
+ "propertyNames": {
+ "$ref": "#/$defs/identifier"
+ },
+ "additionalProperties": {
+ "$ref": "#/$defs/entry"
+ }
},
"providers": {
"$ref": "#/$defs/providers"
@@ -86,16 +86,6 @@
"$ref": "#/$defs/titler"
}
},
- "dependentSchemas": {
- "graph": {
- "description": "Section 8.2: a document that holds both policy and graph is a load-time error.",
- "not": {
- "required": [
- "policy"
- ]
- }
- }
- },
"$defs": {
"identifier": {
"type": "string",
@@ -331,12 +321,12 @@
},
"model": {
"$ref": "#/$defs/modelRef",
- "description": "kind: builtin naming a shipped agent. The model that inner agent runs on. Omitted, the host default applies."
+ "description": "kind: builtin. Reserved: setting it fails the load. No built-in tool reads it."
},
"maxRounds": {
"type": "integer",
"minimum": 1,
- "description": "kind: builtin naming a shipped agent. The round cap inside that tool, not the calling agent's turn budget."
+ "description": "kind: builtin. Reserved: setting it fails the load. No built-in tool reads it."
}
},
"allOf": [
@@ -430,7 +420,7 @@
"model": false,
"maxRounds": false
},
- "$comment": "Only the kind: builtin path reads model and maxRounds (ShippedAgentBuilder). A kind: agent tool takes its model from its agents.items entry, and http and binding call no model at all, so either key there would be accepted and then ignored."
+ "$comment": "model and maxRounds are rejected everywhere they appear (check 1): no tool kind reads them. A kind: agent tool takes its model from its agents.items entry."
}
}
]
@@ -661,6 +651,18 @@
},
"compaction": {
"$ref": "#/$defs/compaction"
+ },
+ "todos": {
+ "type": "boolean",
+ "description": "Whether agents inherit the todos tools."
+ },
+ "mode": {
+ "type": "boolean",
+ "description": "Whether agents inherit the mode tools."
+ },
+ "approval": {
+ "$ref": "#/$defs/approval",
+ "description": "The standing approval rules every agent inherits."
}
}
},
@@ -707,6 +709,10 @@
"id": {
"$ref": "#/$defs/identifier"
},
+ "description": {
+ "type": "string",
+ "description": "One line a parent sees beside this agent's id in its background-agent list."
+ },
"instructions": {
"type": "string"
},
@@ -719,6 +725,38 @@
"compaction": {
"$ref": "#/$defs/compaction"
},
+ "todos": {
+ "type": "boolean",
+ "description": "The agent gets the todos tools (TodoProvider)."
+ },
+ "mode": {
+ "type": "boolean",
+ "description": "The agent gets the mode tools (AgentModeProvider)."
+ },
+ "memory": {
+ "$ref": "#/$defs/memory",
+ "description": "The file-memory tools over a store."
+ },
+ "files": {
+ "$ref": "#/$defs/files",
+ "description": "The file-access tools over a store."
+ },
+ "shell": {
+ "$ref": "#/$defs/shell",
+ "description": "One shell executor per call."
+ },
+ "approval": {
+ "$ref": "#/$defs/approval",
+ "description": "The standing approval rules; everything else still asks."
+ },
+ "background": {
+ "$ref": "#/$defs/background",
+ "description": "The background children this agent may start."
+ },
+ "loop": {
+ "$ref": "#/$defs/loop",
+ "description": "How the agent's own loop runs."
+ },
"tools": {
"type": "array",
"items": {
@@ -759,6 +797,195 @@
"foldResultChars": { "type": "integer", "minimum": 1 }
}
},
+ "agentStore": {
+ "type": "string",
+ "enum": [
+ "workspace"
+ ],
+ "description": "The host-created per-call directory, deleted with the call. The only store today."
+ },
+ "approval": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "auto": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/toolPattern"
+ }
+ }
+ }
+ },
+ "background": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "$ref": "#/$defs/identifier"
+ },
+ "description": "The ids of the background children this agent may start. Same list as agents.items."
+ },
+ "files": {
+ "type": "object",
+ "required": [
+ "store"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "store": {
+ "$ref": "#/$defs/agentStore"
+ },
+ "write": {
+ "type": "boolean",
+ "default": true,
+ "description": "false leaves the read tools only."
+ }
+ }
+ },
+ "loop": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "maxRounds": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "until": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/$defs/loopUntil"
+ },
+ "description": "The conditions that end the loop early, in document order."
+ }
+ }
+ },
+ "loopUntil": {
+ "type": "object",
+ "additionalProperties": false,
+ "minProperties": 1,
+ "maxProperties": 1,
+ "description": "Exactly one condition per entry.",
+ "properties": {
+ "todos": {
+ "type": "object",
+ "description": "The todo list drains to empty."
+ },
+ "background": {
+ "type": "object",
+ "description": "Every background task finishes."
+ }
+ }
+ },
+ "memory": {
+ "type": "object",
+ "required": [
+ "store"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "store": {
+ "$ref": "#/$defs/agentStore"
+ }
+ }
+ },
+ "shell": {
+ "type": "object",
+ "required": [
+ "kind"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "$ref": "#/$defs/shellKind"
+ },
+ "policy": {
+ "$ref": "#/$defs/shellPolicy"
+ },
+ "timeoutSeconds": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "shellKind": {
+ "type": "string",
+ "enum": [
+ "docker",
+ "local"
+ ],
+ "description": "Where a shell runs is the consumer's call, so the document names one: there is no default."
+ },
+ "shellPattern": {
+ "type": "string",
+ "minLength": 1,
+ "description": "A pattern the executor policy compiles. A guardrail for the model, not a security boundary."
+ },
+ "shellPolicy": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "deny": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/shellPattern"
+ }
+ },
+ "allow": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/shellPattern"
+ }
+ }
+ }
+ },
+ "toolPattern": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Names one tool exactly, or a prefix with a trailing *."
+ },
+ "entry": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "agent": {
+ "type": "string",
+ "minLength": 1
+ },
+ "policy": {
+ "$ref": "#/$defs/policy"
+ },
+ "graph": {
+ "$ref": "#/$defs/graph"
+ },
+ "fallbackReply": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "\\S"
+ },
+ "refusalReply": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "\\S"
+ }
+ },
+ "oneOf": [
+ {
+ "required": [
+ "agent"
+ ]
+ },
+ {
+ "required": [
+ "policy"
+ ]
+ },
+ {
+ "required": [
+ "graph"
+ ]
+ }
+ ]
+ },
"policy": {
"type": "object",
"required": [
@@ -1016,6 +1243,10 @@
"webSearch": {
"type": "boolean",
"description": "Whether this entry may run a hosted web search. An opt-out: omitted or true lets the vendor's adapter decide, false vetoes it even on a model the adapter thinks is capable."
+ },
+ "codeExecute": {
+ "type": "boolean",
+ "description": "Whether this entry may run hosted code execution. An opt-out: omitted or true lets the vendor's adapter decide, false vetoes it even on a model the adapter thinks is capable."
}
}
},
diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs
index 7e337529..e15e42a4 100644
--- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs
+++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs
@@ -19,6 +19,9 @@ public static class ConfigurationValidator
///
private const int MaxIntervalSeconds = int.MaxValue / 1000;
+ /// The increment: field of a counter slot. Named once, so the check below and the two maps under it cannot drift apart.
+ private const string IncrementField = "increment";
+
/// Runs checks 2 to 8 and returns everything they find.
/// The bound document.
/// Every error and every partial-coverage warning.
@@ -28,6 +31,7 @@ public static ConfigurationValidationResult Evaluate(AgentCoreConfiguration conf
var declaredToolIds = configuration.Tools.Select(static tool => tool.Id).ToHashSet(StringComparer.Ordinal);
var toolErrors = new List();
+
CheckToolReferences(configuration, declaredToolIds, toolErrors);
if (toolErrors.Count == 0)
@@ -70,7 +74,7 @@ public static ConfigurationValidationResult EvaluateStructure(AgentCoreConfigura
var errors = new List();
var warnings = new List();
var names = DeclaredNames.From(configuration);
-
+ CheckEntryShapes(configuration, names, errors);
CheckReferences(configuration, names, errors);
ReasoningTemperatureCheck.Run(configuration, errors);
CheckSlotWriters(configuration, errors);
@@ -176,6 +180,76 @@ public static void ValidateSkillToolNames(AgentCoreConfiguration configuration)
}
}
+ // ---------------------------------------------------------------------------------------------
+ // Check 2, entry shapes: each entry holds exactly one of agent:/policy:/graph:.
+ // ---------------------------------------------------------------------------------------------
+ private static void CheckEntryShapes(AgentCoreConfiguration configuration, DeclaredNames names, List errors)
+ {
+ if (configuration.Agents.Items.Count == 0)
+ {
+ errors.Add(Reference(
+ "/agents/items",
+ "the document declares no agents:, so no entry can resolve an agent."));
+ }
+
+ if (configuration.Entries.Count == 0)
+ {
+ errors.Add(Reference(
+ "/entries",
+ "the document declares no entries:, so it compiles to nothing."));
+ return;
+ }
+
+ foreach (var (name, entry) in configuration.Entries)
+ {
+ var pointer = Pointer.Entry(name);
+ var shapes = (entry.Agent is null ? 0 : 1) + (entry.Policy is null ? 0 : 1) + (entry.Graph is null ? 0 : 1);
+
+ if (shapes == 0)
+ {
+ errors.Add(Reference(
+ pointer,
+ $"the entry '{name}' declares none of agent:, policy:, or graph:. It holds exactly one."));
+ }
+ else if (shapes > 1)
+ {
+ errors.Add(Reference(
+ pointer,
+ $"the entry '{name}' declares more than one of agent:, policy:, and graph:. It holds exactly one."));
+ }
+
+ if (entry.Agent is { } agentId)
+ {
+ if (string.IsNullOrWhiteSpace(agentId))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "agent"),
+ $"the entry '{name}' names an empty agent:. It names one id from agents.items."));
+ }
+ else if (!names.Agents.Contains(agentId))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "agent"),
+ $"the agent '{agentId}' is not declared in agents.items"));
+ }
+ }
+
+ if (entry.FallbackReply is { } fallback && string.IsNullOrWhiteSpace(fallback))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "fallbackReply"),
+ $"the entry '{name}' sets a blank fallbackReply, so a failed turn would speak nothing."));
+ }
+
+ if (entry.RefusalReply is { } refusal && string.IsNullOrWhiteSpace(refusal))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "refusalReply"),
+ $"the entry '{name}' sets a blank refusalReply, so a refused turn would speak nothing."));
+ }
+ }
+ }
+
// ---------------------------------------------------------------------------------------------
// Check 2: reference resolution.
// ---------------------------------------------------------------------------------------------
@@ -209,8 +283,8 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar
AddUnknownModel(titler.Model, "/titler/model/ref", names, errors);
}
- var items = configuration.Agents?.Items ?? [];
- if (configuration.Agents?.Defaults is { } defaults)
+ var items = configuration.Agents.Items;
+ if (configuration.Agents.Defaults is { } defaults)
{
AddUnknownModel(defaults.Model, "/agents/defaults/model/ref", names, errors);
}
@@ -218,90 +292,116 @@ private static void CheckReferences(AgentCoreConfiguration configuration, Declar
for (var index = 0; index < items.Count; index++)
{
var agent = items[index];
+
AddUnknownModel(
agent.Model,
ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Pointer.Agent(index), "model"), "ref"),
names,
errors);
- }
- if (configuration.Policy is { } policy)
- {
- if (!names.Stages.Contains(policy.Initial))
+ for (var child = 0; child < agent.Background.Count; child++)
{
- errors.Add(Reference("/policy/initial", $"the stage '{policy.Initial}' is not declared in policy.stages"));
+ var childId = agent.Background[child];
+
+ if (!names.Agents.Contains(childId))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(
+ ConfigurationError.AppendPointer(Pointer.Agent(index), "background"), child),
+ $"the agent '{childId}' is not declared in agents.items"));
+ }
}
+ }
- for (var index = 0; index < policy.Stages.Count; index++)
+ foreach (var (name, entry) in configuration.Entries)
+ {
+ if (entry.Policy is { } policy)
{
- var stage = policy.Stages[index];
- if (stage.Agent is { } agentId && !names.Agents.Contains(agentId))
+ var stages = names.Stages[name];
+
+ if (!stages.Contains(policy.Initial))
{
errors.Add(Reference(
- ConfigurationError.AppendPointer(Pointer.Stage(index), "agent"),
- $"the agent '{agentId}' is not declared in agents.items"));
+ ConfigurationError.AppendPointer(Pointer.Policy(name), "initial"),
+ $"the stage '{policy.Initial}' is not declared in policy.stages in entry '{name}'"));
}
- for (var exit = 0; exit < stage.To.Count; exit++)
+ for (var index = 0; index < policy.Stages.Count; index++)
{
- var transition = stage.To[exit];
- var pointer = Pointer.Transition(index, exit);
- if (!names.Stages.Contains(transition.Stage))
+ var stage = policy.Stages[index];
+
+ if (stage.Agent is { } agentId && !names.Agents.Contains(agentId))
{
errors.Add(Reference(
- ConfigurationError.AppendPointer(pointer, "stage"),
- $"the stage '{transition.Stage}' is not declared in policy.stages"));
+ ConfigurationError.AppendPointer(Pointer.Stage(name, index), "agent"),
+ $"the agent '{agentId}' is not declared in agents.items"));
}
- AddUnknownGuard(transition.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors);
+ for (var exit = 0; exit < stage.To.Count; exit++)
+ {
+ var transition = stage.To[exit];
+ var pointer = Pointer.Transition(name, index, exit);
+
+ if (!stages.Contains(transition.Stage))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "stage"),
+ $"the stage '{transition.Stage}' is not declared in policy.stages in entry '{name}'"));
+ }
+
+ AddUnknownGuard(transition.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors);
+ }
}
}
- }
- if (configuration.Graph is not { } graph)
- {
- return;
- }
-
- for (var index = 0; index < graph.Agents.Count; index++)
- {
- if (!names.Agents.Contains(graph.Agents[index]))
+ if (entry.Graph is not { } graph)
{
- errors.Add(Reference(
- ConfigurationError.AppendPointer("/graph/agents", index),
- $"the agent '{graph.Agents[index]}' is not declared in agents.items"));
+ continue;
}
- }
- for (var index = 0; index < graph.Nodes.Count; index++)
- {
- if (graph.Nodes[index].Agent is { } agentId && !names.Agents.Contains(agentId))
+ var nodes = names.Nodes[name];
+
+ for (var index = 0; index < graph.Agents.Count; index++)
{
- errors.Add(Reference(
- ConfigurationError.AppendPointer(Pointer.Node(index), "agent"),
- $"the agent '{agentId}' is not declared in agents.items"));
+ if (!names.Agents.Contains(graph.Agents[index]))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(Pointer.GraphAgents(name), index),
+ $"the agent '{graph.Agents[index]}' is not declared in agents.items"));
+ }
}
- }
- for (var index = 0; index < graph.Edges.Count; index++)
- {
- var edge = graph.Edges[index];
- var pointer = Pointer.Edge(index);
- if (!names.Nodes.Contains(edge.From))
+ for (var index = 0; index < graph.Nodes.Count; index++)
{
- errors.Add(Reference(
- ConfigurationError.AppendPointer(pointer, "from"),
- $"the node '{edge.From}' is not declared in graph.nodes"));
+ if (graph.Nodes[index].Agent is { } nodeAgent && !names.Agents.Contains(nodeAgent))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(Pointer.Node(name, index), "agent"),
+ $"the agent '{nodeAgent}' is not declared in agents.items"));
+ }
}
- if (!names.Nodes.Contains(edge.To))
+ for (var index = 0; index < graph.Edges.Count; index++)
{
- errors.Add(Reference(
- ConfigurationError.AppendPointer(pointer, "to"),
- $"the node '{edge.To}' is not declared in graph.nodes"));
- }
+ var edge = graph.Edges[index];
+ var pointer = Pointer.Edge(name, index);
+
+ if (!nodes.Contains(edge.From))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "from"),
+ $"the node '{edge.From}' is not declared in graph.nodes in entry '{name}'"));
+ }
- AddUnknownGuard(edge.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors);
+ if (!nodes.Contains(edge.To))
+ {
+ errors.Add(Reference(
+ ConfigurationError.AppendPointer(pointer, "to"),
+ $"the node '{edge.To}' is not declared in graph.nodes in entry '{name}'"));
+ }
+
+ AddUnknownGuard(edge.When, ConfigurationError.AppendPointer(pointer, "when"), names, errors);
+ }
}
}
@@ -343,7 +443,7 @@ private static void CheckToolReferences(AgentCoreConfiguration configuration, IR
}
}
- var items = configuration.Agents?.Items ?? [];
+ var items = configuration.Agents.Items;
for (var index = 0; index < items.Count; index++)
{
var agent = items[index];
@@ -369,11 +469,12 @@ private static void CheckSkillReferences(
List errors)
{
var served = string.Join(", ", servedSkillNames.Order(StringComparer.Ordinal));
- var items = configuration.Agents?.Items ?? [];
+ var items = configuration.Agents.Items;
for (var index = 0; index < items.Count; index++)
{
var agent = items[index];
+
for (var slot = 0; slot < agent.Skills.Count; slot++)
{
if (servedSkillNames.Contains(agent.Skills[slot]))
@@ -395,7 +496,7 @@ private static void CheckSkillReferences(
/// The list every failure is added to.
private static void CheckSkillToolNames(AgentCoreConfiguration configuration, List errors)
{
- var items = configuration.Agents?.Items ?? [];
+ var items = configuration.Agents.Items;
if (!items.Any(agent => agent.Skills.Count > 0))
{
return;
@@ -523,7 +624,7 @@ private static void CheckKnowledgeScopeSlots(
}
// A wildcard without fromState is a supported shape: the deployment resolves its own facets
- // and opens them as the host ambient, which the store still widens. See
+ // and passes them as the call's scope, which the store still widens. See
// StateKnowledgeScope.Compose and KnowledgeStartup's K19 branch. Only the reverse is refused.
if (scope.FromState.Count == 0)
{
@@ -540,27 +641,21 @@ private static void CheckKnowledgeScopeSlots(
}
else
{
- foreach (var facet in widened.Facets)
+ foreach (var facet in widened.Facets.Where(facet => !scope.FromState.Contains(facet, StringComparer.Ordinal)))
{
- if (!scope.FromState.Contains(facet, StringComparer.Ordinal))
- {
- errors.Add(Reference(
- Pointer.WildcardFacets,
- $"wildcard.facets names '{facet}' and fromState does not. The scope filter only "
- + $"ever puts a condition on a fromState facet, so there is no condition on "
- + $"'{facet}' for the wildcard to widen."));
- }
+ errors.Add(Reference(
+ Pointer.WildcardFacets,
+ $"wildcard.facets names '{facet}' and fromState does not. The scope filter only "
+ + $"ever puts a condition on a fromState facet, so there is no condition on "
+ + $"'{facet}' for the wildcard to widen."));
}
- foreach (var name in scope.FromState)
+ foreach (var name in scope.FromState.Where(name => !widened.Facets.Contains(name, StringComparer.Ordinal)))
{
- if (!widened.Facets.Contains(name, StringComparer.Ordinal))
- {
- errors.Add(Reference(
- Pointer.WildcardFacets,
- $"fromState names '{name}' and wildcard.facets does not, so an unfilled '{name}' "
- + "would be searched for the literal wildcard rather than widened by it."));
- }
+ errors.Add(Reference(
+ Pointer.WildcardFacets,
+ $"fromState names '{name}' and wildcard.facets does not, so an unfilled '{name}' "
+ + "would be searched for the literal wildcard rather than widened by it."));
}
}
@@ -730,7 +825,7 @@ private static void CheckSlotWriters(AgentCoreConfiguration configuration, List<
$"the slot has zero writers: writer: {WriterName(slot.Writer)} fills the slot from '{owner}:', and the slot declares none"));
}
- foreach (var field in new[] { "from", "increment", "value" })
+ foreach (var field in new[] { "from", IncrementField, "value" })
{
if (string.Equals(field, owner, StringComparison.Ordinal) || FieldValue(slot, field) is null)
{
@@ -748,7 +843,7 @@ private static void CheckSlotWriters(AgentCoreConfiguration configuration, List<
=> writer switch
{
StateWriter.Tool => "from",
- StateWriter.Counter => "increment",
+ StateWriter.Counter => IncrementField,
StateWriter.Const => "value",
_ => null,
};
@@ -766,7 +861,7 @@ private static string WriterName(StateWriter writer)
=> field switch
{
"from" => slot.From,
- "increment" => slot.Increment,
+ IncrementField => slot.Increment,
_ => slot.Value,
};
@@ -784,35 +879,37 @@ private static void CheckGuardRules(AgentCoreConfiguration configuration, List !GuardOperators.IsAllowed(name)))
{
- if (!GuardOperators.IsAllowed(name))
- {
- errors.Add(Operators(pointer, GuardOperators.DescribeRejection(name)));
- }
+ errors.Add(Operators(pointer, GuardOperators.DescribeRejection(name)));
}
if (facts.HasDoubleNegationSugar)
@@ -835,12 +929,10 @@ private static void CheckOneRule(AgentCoreConfiguration configuration, JsonNode
errors.Add(Operators(pointer, GuardOperators.DoubleNegationSugarRejection));
}
- foreach (var slot in facts.Variables)
+ foreach (var slot in facts.Variables.Where(slot =>
+ !configuration.State.ContainsKey(slot) && !ReservedStateSlots.Contains(slot)))
{
- if (!configuration.State.ContainsKey(slot) && !ReservedStateSlots.Contains(slot))
- {
- errors.Add(Operators(pointer, $"the rule reads the slot '{slot}', and state: does not declare it"));
- }
+ errors.Add(Operators(pointer, $"the rule reads the slot '{slot}', and state: does not declare it"));
}
foreach (var comparison in facts.NumericComparisons)
@@ -861,67 +953,72 @@ private static void CheckExclusivity(AgentCoreConfiguration configuration, List<
{
var evaluator = new GuardEvaluator(configuration.Guards);
- if (configuration.Policy is { } policy)
+ foreach (var (name, entry) in configuration.Entries)
{
- for (var index = 0; index < policy.Stages.Count; index++)
+ if (entry.Policy is { } policy)
{
- var stage = policy.Stages[index];
- var exits = new List(stage.To.Count);
- for (var exit = 0; exit < stage.To.Count; exit++)
+ for (var index = 0; index < policy.Stages.Count; index++)
{
- var transition = stage.To[exit];
- var pointer = Pointer.Transition(index, exit);
- exits.Add(new SiblingExit(
- DescribeExit(transition.When, "exit", transition.Stage),
- transition.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"),
- transition.When));
+ var stage = policy.Stages[index];
+ var exits = new List(stage.To.Count);
+
+ for (var exit = 0; exit < stage.To.Count; exit++)
+ {
+ var transition = stage.To[exit];
+ var pointer = Pointer.Transition(name, index, exit);
+
+ exits.Add(new SiblingExit(
+ DescribeExit(transition.When, "exit", transition.Stage),
+ transition.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"),
+ transition.When));
+ }
+
+ var pinned = new Dictionary(StringComparer.Ordinal)
+ {
+ [ReservedStateSlots.Stage] = JsonValue.Create(stage.Id),
+ };
+
+ GuardExclusivityCheck.Run(
+ exits,
+ ConfigurationError.AppendPointer(Pointer.Stage(name, index), "to"),
+ $"the stage '{stage.Id}'",
+ evaluator,
+ configuration.State,
+ pinned,
+ errors,
+ warnings);
}
+ }
- var pinned = new Dictionary(StringComparer.Ordinal)
+ if (entry.Graph is not { } graph || graph.Edges.Count == 0)
+ {
+ continue;
+ }
+
+ foreach (var group in graph.Edges.Select(static (edge, index) => (edge, index)).GroupBy(static pair => pair.edge.From, StringComparer.Ordinal))
+ {
+ var exits = new List();
+
+ foreach (var pair in group)
{
- // The exits of one stage run inside that stage, so the reserved slot is known.
- [ReservedStateSlots.Stage] = JsonValue.Create(stage.Id),
- };
+ var pointer = Pointer.Edge(name, pair.index);
+ exits.Add(new SiblingExit(
+ DescribeExit(pair.edge.When, "edge", pair.edge.To),
+ pair.edge.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"),
+ pair.edge.When));
+ }
GuardExclusivityCheck.Run(
exits,
- ConfigurationError.AppendPointer(Pointer.Stage(index), "to"),
- $"the stage '{stage.Id}'",
+ Pointer.GraphEdges(name),
+ $"the node '{group.Key}'",
evaluator,
configuration.State,
- pinned,
+ new Dictionary(StringComparer.Ordinal),
errors,
warnings);
}
}
-
- if (configuration.Graph is not { } graph || graph.Edges.Count == 0)
- {
- return;
- }
-
- foreach (var group in graph.Edges.Select(static (edge, index) => (edge, index)).GroupBy(static pair => pair.edge.From, StringComparer.Ordinal))
- {
- var exits = new List();
- foreach (var pair in group)
- {
- var pointer = Pointer.Edge(pair.index);
- exits.Add(new SiblingExit(
- DescribeExit(pair.edge.When, "edge", pair.edge.To),
- pair.edge.When is null ? pointer : ConfigurationError.AppendPointer(pointer, "when"),
- pair.edge.When));
- }
-
- GuardExclusivityCheck.Run(
- exits,
- "/graph/edges",
- $"the node '{group.Key}'",
- evaluator,
- configuration.State,
- new Dictionary(StringComparer.Ordinal),
- errors,
- warnings);
- }
}
private static string DescribeExit(GuardReference? guard, string kind, string target)
@@ -937,115 +1034,119 @@ private static string DescribeExit(GuardReference? guard, string kind, string ta
// ---------------------------------------------------------------------------------------------
private static void CheckReachability(AgentCoreConfiguration configuration, List errors)
{
- if (configuration.Policy is { } policy)
+ foreach (var (name, entry) in configuration.Entries)
{
- var edges = new Dictionary>(StringComparer.Ordinal);
- foreach (var stage in policy.Stages)
- {
- edges[stage.Id] = [.. stage.To.Select(static transition => transition.Stage)];
- }
-
- var reachable = Reach(policy.Initial, edges);
-
- for (var index = 0; index < policy.Stages.Count; index++)
+ if (entry.Policy is { } policy)
{
- var stage = policy.Stages[index];
- if (!reachable.Contains(stage.Id))
+ var edges = new Dictionary>(StringComparer.Ordinal);
+ foreach (var stage in policy.Stages)
{
- errors.Add(Reachability(
- Pointer.Stage(index),
- $"the stage '{stage.Id}' is unreachable from the initial stage '{policy.Initial}'"));
+ edges[stage.Id] = [.. stage.To.Select(static transition => transition.Stage)];
}
- if (!stage.Terminal && stage.To.Count == 0)
+ var reachable = Reach(policy.Initial, edges);
+
+ for (var index = 0; index < policy.Stages.Count; index++)
{
- errors.Add(Reachability(
- Pointer.Stage(index),
- $"the stage '{stage.Id}' is not terminal and has no exit"));
+ var stage = policy.Stages[index];
+ if (!reachable.Contains(stage.Id))
+ {
+ errors.Add(Reachability(
+ Pointer.Stage(name, index),
+ $"the stage '{stage.Id}' is unreachable from the initial stage '{policy.Initial}' in entry '{name}'"));
+ }
+
+ if (!stage.Terminal && stage.To.Count == 0)
+ {
+ errors.Add(Reachability(
+ Pointer.Stage(name, index),
+ $"the stage '{stage.Id}' is not terminal and has no exit"));
+ }
}
}
- }
- if (configuration.Graph is not { } graph || graph.Nodes.Count == 0)
- {
- return;
- }
+ if (entry.Graph is not { } graph || graph.Nodes.Count == 0)
+ {
+ continue;
+ }
- var starts = graph.Nodes.Where(static node => node.Start).Select(static node => node.Id).ToList();
- if (starts.Count != 1)
- {
- // Check 7 reports the start-node count. Reachability has no root to walk from.
- return;
- }
+ var starts = graph.Nodes.Where(static node => node.Start).Select(static node => node.Id).ToList();
+ if (starts.Count != 1)
+ {
+ continue;
+ }
- var forward = BuildAdjacency(graph);
- var live = Reach(starts[0], forward);
+ var forward = BuildAdjacency(graph);
+ var live = Reach(starts[0], forward);
- for (var index = 0; index < graph.Nodes.Count; index++)
- {
- if (!live.Contains(graph.Nodes[index].Id))
+ for (var index = 0; index < graph.Nodes.Count; index++)
{
- errors.Add(Reachability(
- Pointer.Node(index),
- $"the node '{graph.Nodes[index].Id}' is unreachable from the start node '{starts[0]}'"));
+ if (!live.Contains(graph.Nodes[index].Id))
+ {
+ errors.Add(Reachability(
+ Pointer.Node(name, index),
+ $"the node '{graph.Nodes[index].Id}' is unreachable from the start node '{starts[0]}' in entry '{name}'"));
+ }
}
}
}
- // ---------------------------------------------------------------------------------------------
- // Check 7: graph well-formedness.
// ---------------------------------------------------------------------------------------------
private static void CheckGraphWellFormedness(AgentCoreConfiguration configuration, List errors)
{
- if (configuration.Graph is not { } graph || graph.Nodes.Count == 0)
+ foreach (var (name, entry) in configuration.Entries)
{
- return;
- }
+ if (entry.Graph is not { } graph || graph.Nodes.Count == 0)
+ {
+ continue;
+ }
- var starts = graph.Nodes.Count(static node => node.Start);
- if (starts != 1)
- {
- errors.Add(WellFormedness(
- "/graph/nodes",
- string.Create(CultureInfo.InvariantCulture, $"the graph declares {starts} start nodes, and check 7 needs exactly one")));
- }
+ var starts = graph.Nodes.Count(static node => node.Start);
+ if (starts != 1)
+ {
+ errors.Add(WellFormedness(
+ Pointer.GraphNodes(name),
+ string.Create(CultureInfo.InvariantCulture, $"the graph in entry '{name}' declares {starts} start nodes, and check 7 needs exactly one")));
+ }
- var outgoing = new HashSet(StringComparer.Ordinal);
- var incoming = new HashSet(StringComparer.Ordinal);
- foreach (var edge in graph.Edges)
- {
- outgoing.Add(edge.From);
- incoming.Add(edge.To);
- }
+ var outgoing = new HashSet(StringComparer.Ordinal);
+ var incoming = new HashSet(StringComparer.Ordinal);
- for (var index = 0; index < graph.Nodes.Count; index++)
- {
- var node = graph.Nodes[index];
- if (!outgoing.Contains(node.Id) && !incoming.Contains(node.Id))
+ foreach (var edge in graph.Edges)
{
- errors.Add(WellFormedness(
- Pointer.Node(index),
- $"the node '{node.Id}' is an orphan: no edge reaches it and no edge leaves it"));
+ outgoing.Add(edge.From);
+ incoming.Add(edge.To);
}
- }
- var outputs = graph.Nodes.Where(static node => node.Output).Select(static node => node.Id).ToHashSet(StringComparer.Ordinal);
- if (outputs.Count == 0)
- {
- errors.Add(WellFormedness("/graph/nodes", "the graph declares no output node, so no path reaches an output"));
- return;
- }
+ for (var index = 0; index < graph.Nodes.Count; index++)
+ {
+ var node = graph.Nodes[index];
+ if (!outgoing.Contains(node.Id) && !incoming.Contains(node.Id))
+ {
+ errors.Add(WellFormedness(
+ Pointer.Node(name, index),
+ $"the node '{node.Id}' is an orphan: no edge reaches it and no edge leaves it"));
+ }
+ }
- var forward = BuildAdjacency(graph);
- for (var index = 0; index < graph.Nodes.Count; index++)
- {
- var node = graph.Nodes[index];
- var reachable = Reach(node.Id, forward);
- if (!reachable.Overlaps(outputs))
+ var outputs = graph.Nodes.Where(static node => node.Output).Select(static node => node.Id).ToHashSet(StringComparer.Ordinal);
+ if (outputs.Count == 0)
{
- errors.Add(WellFormedness(
- Pointer.Node(index),
- $"no path from the node '{node.Id}' reaches an output node"));
+ errors.Add(WellFormedness(Pointer.GraphNodes(name), "the graph declares no output node, so no path reaches an output"));
+ continue;
+ }
+
+ var forward = BuildAdjacency(graph);
+ for (var index = 0; index < graph.Nodes.Count; index++)
+ {
+ var node = graph.Nodes[index];
+ var reachable = Reach(node.Id, forward);
+ if (!reachable.Overlaps(outputs))
+ {
+ errors.Add(WellFormedness(
+ Pointer.Node(name, index),
+ $"no path from the node '{node.Id}' reaches an output node"));
+ }
}
}
}
@@ -1055,7 +1156,7 @@ private static void CheckGraphWellFormedness(AgentCoreConfiguration configuratio
// ---------------------------------------------------------------------------------------------
private static void CheckDelegationCycles(AgentCoreConfiguration configuration, List errors)
{
- var items = configuration.Agents?.Items ?? [];
+ var items = configuration.Agents.Items;
if (items.Count == 0)
{
return;
@@ -1068,10 +1169,12 @@ private static void CheckDelegationCycles(AgentCoreConfiguration configuration,
// built-in and 'binds:' names a host delegate, so neither ever names an agent, and a tool id
// that matches an agent id is a coincidence.
var edges = new Dictionary>(StringComparer.Ordinal);
+
for (var index = 0; index < items.Count; index++)
{
var agent = items[index];
var outgoing = new List<(string, int, int)>();
+
for (var slot = 0; slot < agent.Tools.Count; slot++)
{
if (!tools.TryGetValue(agent.Tools[slot], out var tool))
@@ -1254,24 +1357,28 @@ private sealed class DeclaredNames
public required HashSet Guards { get; init; }
- public required HashSet Stages { get; init; }
+ public required HashSet Models { get; init; }
- public required HashSet Nodes { get; init; }
+ public required Dictionary> Stages { get; init; }
- public required HashSet Models { get; init; }
+ public required Dictionary> Nodes { get; init; }
public static DeclaredNames From(AgentCoreConfiguration configuration)
=> new()
{
- Agents = (configuration.Agents?.Items ?? [])
+ Agents = configuration.Agents.Items
.Select(static agent => agent.Id).ToHashSet(StringComparer.Ordinal),
Guards = configuration.Guards.Keys.ToHashSet(StringComparer.Ordinal),
- Stages = (configuration.Policy?.Stages ?? [])
- .Select(static stage => stage.Id).ToHashSet(StringComparer.Ordinal),
- Nodes = (configuration.Graph?.Nodes ?? [])
- .Select(static node => node.Id).ToHashSet(StringComparer.Ordinal),
-
- // An absent providers: section, or an absent providers.llm, declares no model name.
+ Stages = configuration.Entries.ToDictionary(
+ static entry => entry.Key,
+ entry => (entry.Value.Policy?.Stages ?? [])
+ .Select(static stage => stage.Id).ToHashSet(StringComparer.Ordinal),
+ StringComparer.Ordinal),
+ Nodes = configuration.Entries.ToDictionary(
+ static entry => entry.Key,
+ entry => (entry.Value.Graph?.Nodes ?? [])
+ .Select(static node => node.Id).ToHashSet(StringComparer.Ordinal),
+ StringComparer.Ordinal),
Models = (configuration.Providers?.Llm ?? [])
.Select(static provider => provider.As).ToHashSet(StringComparer.Ordinal),
};
@@ -1301,13 +1408,25 @@ private static class Pointer
public static string Mcp(int index) => ConfigurationError.AppendPointer("/mcp", index);
- public static string Stage(int index) => ConfigurationError.AppendPointer("/policy/stages", index);
+ public static string Entry(string name) => ConfigurationError.AppendPointer("/entries", name);
+
+ public static string Policy(string name) => ConfigurationError.AppendPointer(Entry(name), "policy");
+
+ public static string Graph(string name) => ConfigurationError.AppendPointer(Entry(name), "graph");
+
+ public static string GraphAgents(string name) => ConfigurationError.AppendPointer(Graph(name), "agents");
+
+ public static string GraphNodes(string name) => ConfigurationError.AppendPointer(Graph(name), "nodes");
+
+ public static string GraphEdges(string name) => ConfigurationError.AppendPointer(Graph(name), "edges");
+
+ public static string Stage(string name, int index) => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Policy(name), "stages"), index);
- public static string Transition(int stage, int exit)
- => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Stage(stage), "to"), exit);
+ public static string Transition(string name, int stage, int exit)
+ => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Stage(name, stage), "to"), exit);
- public static string Node(int index) => ConfigurationError.AppendPointer("/graph/nodes", index);
+ public static string Node(string name, int index) => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Graph(name), "nodes"), index);
- public static string Edge(int index) => ConfigurationError.AppendPointer("/graph/edges", index);
+ public static string Edge(string name, int index) => ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Graph(name), "edges"), index);
}
}
diff --git a/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs b/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs
index 326c5f5f..01f4d707 100644
--- a/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs
+++ b/src/AgentCore.Application/Configuration/Validation/ReasoningTemperatureCheck.cs
@@ -24,6 +24,9 @@ internal static class ReasoningTemperatureCheck
{
/// The one temperature a reasoning entry accepts.
private const double ReasoningTemperature = 1;
+
+ /// The tolerance around that still counts as equal.
+ private const double TemperatureTolerance = 1e-9;
/// The one reasoningEffort value that leaves temperature free.
private const string NoReasoning = "none";
@@ -42,9 +45,9 @@ public static void Run(AgentCoreConfiguration configuration, List errors)
{
if (model?.Temperature is not { } temperature
- || temperature == ReasoningTemperature
+ || Math.Abs(temperature - ReasoningTemperature) < TemperatureTolerance
|| !reasoning.TryGetValue(model.Ref, out var effort))
{
return;
diff --git a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs
index f7f879c3..71636fea 100644
--- a/src/AgentCore.Application/Configuration/Validation/StateDomain.cs
+++ b/src/AgentCore.Application/Configuration/Validation/StateDomain.cs
@@ -86,6 +86,12 @@ public static long CountPoints(IReadOnlyList domains)
{
ArgumentNullException.ThrowIfNull(domains);
+ return EnumerateCore(domains);
+ }
+
+ /// Walks every point of the product. The caller checks the arguments.
+ private static IEnumerable> EnumerateCore(IReadOnlyList domains)
+ {
if (domains.Count == 0)
{
yield return new Dictionary(StringComparer.Ordinal);
@@ -125,8 +131,19 @@ public static long CountPoints(IReadOnlyList domains)
{
ArgumentNullException.ThrowIfNull(domains);
+ return SampleCore(domains, count);
+ }
+
+ /// Samples the product with the fixed seed. The caller checks the arguments.
+ [System.Diagnostics.CodeAnalysis.SuppressMessage(
+ "Security",
+ "S2245",
+ Justification = "Fixed-seed sampling of validation points. Repeatability is required; not a security use.")]
+ private static IEnumerable> SampleCore(IReadOnlyList domains, int count)
+ {
// The seed is fixed so that a failing build fails the same way twice.
var random = new Random(SampleSeed);
+
var cursor = new int[domains.Count];
for (var taken = 0; taken < count; taken++)
diff --git a/src/AgentCore.Application/Diagnostics/Log.cs b/src/AgentCore.Application/Diagnostics/Log.cs
index 5645fdc5..f01ae6da 100644
--- a/src/AgentCore.Application/Diagnostics/Log.cs
+++ b/src/AgentCore.Application/Diagnostics/Log.cs
@@ -219,10 +219,11 @@ public static partial void KnowledgeScopeComposed(
+ "knowledge base holds nothing and the call continues.")]
public static partial void KnowledgeProbeFailed(ILogger logger, string agent, string facet, Exception exception);
- /// An agent declared a hosted-search tool, and its model reports no hosted web search.
+ /// An agent declared a hosted tool, and its model reports it cannot run it.
/// The logger of the compiler.
/// The id of the agent that declared the tool.
/// The id of the tool that was dropped.
+ /// The marker type, such as HostedWebSearchTool , so the reader knows which hosted capability was missing.
///
/// A phrase naming the model, such as "the model 'reply'" or "this agent's default
/// model" when the agent names none. Built at the call site so this message never renders an
@@ -231,9 +232,52 @@ public static partial void KnowledgeScopeComposed(
[LoggerMessage(
EventId = 18,
Level = LogLevel.Warning,
- Message = "The agent '{AgentId}' declares the tool '{ToolId}', which asks the model provider "
- + "to run a web search, and {Model} reports no hosted web search, so the tool was not "
- + "added. Point this agent at a model whose vendor runs a hosted web search, or remove "
+ Message = "The agent '{AgentId}' declares the tool '{ToolId}' of type '{Marker}', which asks the model provider "
+ + "to run it hosted, and {Model} reports it cannot, so the tool was not "
+ + "added. Point this agent at a model whose vendor runs it hosted, or remove "
+ "the tool from this agent.")]
- public static partial void HostedWebSearchDropped(ILogger logger, string agentId, string toolId, string model);
+ public static partial void HostedToolDropped(ILogger logger, string agentId, string toolId, string marker, string model);
+
+ /// Store 1 could not be read as a turn opened, so the turn ran on the words already held.
+ /// The logger of the session.
+ /// The id of the call.
+ /// The zero-based index of the turn that was opening.
+ /// The cause.
+ [LoggerMessage(
+ EventId = 19,
+ Level = LogLevel.Warning,
+ Message = "The transcript store could not be read as turn {TurnIndex} of call {CallId} opened. "
+ + "The turn runs on the words the session already holds; a message appended outside a "
+ + "turn since the last read is not among them.")]
+ public static partial void TranscriptResyncFailed(ILogger logger, string callId, int turnIndex, Exception exception);
+
+ /// A call's workspace folder could not be deleted when the call ended.
+ /// The logger of the session.
+ /// The folder that could not be deleted.
+ /// The cause.
+ [LoggerMessage(
+ EventId = 20,
+ Level = LogLevel.Warning,
+ Message = "Could not delete the call workspace at '{Path}'.")]
+ public static partial void WorkspaceDeleteFailed(ILogger logger, string path, Exception exception);
+
+ /// A call's shell executor could not be disposed when the call ended.
+ /// The logger of the session.
+ /// The call's workspace folder, whose shell failed to dispose.
+ /// The cause.
+ [LoggerMessage(
+ EventId = 21,
+ Level = LogLevel.Warning,
+ Message = "Could not dispose a shell: executor of the call at workspace '{Workspace}'.")]
+ public static partial void ShellDisposeFailed(ILogger logger, string workspace, Exception exception);
+
+ /// A call's background agent sessions could not be released when the call ended.
+ /// The logger of the session.
+ /// The id of the call whose children were being released.
+ /// The cause.
+ [LoggerMessage(
+ EventId = 22,
+ Level = LogLevel.Warning,
+ Message = "Could not release the background agent sessions of the call '{CallId}'.")]
+ public static partial void BackgroundReleaseFailed(ILogger logger, string callId, Exception exception);
}
diff --git a/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs b/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs
index ec7d850d..f510758c 100644
--- a/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs
+++ b/src/AgentCore.Application/Evaluation/RetrievedDocumentsContext.cs
@@ -1,4 +1,5 @@
using Microsoft.Extensions.AI.Evaluation;
+using System.Runtime.CompilerServices;
namespace AgentCore.Application.Evaluation;
@@ -15,7 +16,7 @@ public sealed class RetrievedDocumentsContext : EvaluationContext
/// The document ids the search returned, best first.
/// Either list is .
public RetrievedDocumentsContext(IEnumerable expected, IEnumerable retrieved)
- : this(Materialize(expected, nameof(expected)), Materialize(retrieved, nameof(retrieved)))
+ : this(Materialize(expected), Materialize(retrieved))
{
}
@@ -37,9 +38,15 @@ private static string Describe(string[] expected, string[] retrieved)
private static string Join(string[] ids) => ids.Length == 0 ? "none" : string.Join(", ", ids);
- private static string[] Materialize(IEnumerable ids, string parameterName)
+ private static string[] Materialize(
+ IEnumerable ids,
+ [CallerArgumentExpression(nameof(ids))] string parameterName = "")
{
- ArgumentNullException.ThrowIfNull(ids, parameterName);
+ if (ids is null)
+ {
+ throw new ArgumentNullException(parameterName);
+ }
+
return [.. ids];
}
}
diff --git a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs
index 4535de6b..dd2e1b4e 100644
--- a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs
+++ b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs
@@ -10,14 +10,17 @@ namespace AgentCore.Application.Knowledge;
///
internal sealed class FacetFilterProvider(
AIContextProvider innerProvider,
- IReadOnlyList facets)
+ IReadOnlyList? facets,
+ KnowledgeSearch.Core core)
: AIContextProvider
{
private readonly AIContextProvider _inner = innerProvider
?? throw new ArgumentNullException(nameof(innerProvider));
- private readonly IReadOnlyList _facets = facets
- ?? throw new ArgumentNullException(nameof(facets));
+ private readonly IReadOnlyList? _facets = facets;
+
+ private readonly KnowledgeSearch.Core _core = core
+ ?? throw new ArgumentNullException(nameof(core));
///
public override IReadOnlyList StateKeys => _inner.StateKeys;
@@ -34,8 +37,12 @@ internal sealed class FacetFilterProvider(
///
protected override async ValueTask InvokingCoreAsync(
- InvokingContext context, CancellationToken cancellationToken)
+ InvokingContext context, CancellationToken cancellationToken = default)
{
+ HashSet? existing = context.AIContext.Tools is { } input
+ ? [.. input]
+ : null;
+
var provided = await _inner.InvokingAsync(context, cancellationToken).ConfigureAwait(false);
if (provided.Tools is not { } tools)
@@ -47,8 +54,8 @@ protected override async ValueTask InvokingCoreAsync(
foreach (var tool in tools)
{
- wrapped.Add(tool is AIFunction function
- ? new FacetFilteredSearch(function, _facets)
+ wrapped.Add(tool is AIFunction function && existing?.Contains(tool) is not true
+ ? new FacetFilteredSearch(function, _facets, _core)
: tool);
}
@@ -59,6 +66,6 @@ protected override async ValueTask InvokingCoreAsync(
///
protected override ValueTask InvokedCoreAsync(
- InvokedContext context, CancellationToken cancellationToken)
+ InvokedContext context, CancellationToken cancellationToken = default)
=> _inner.InvokedAsync(context, cancellationToken);
}
diff --git a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs
index a738efe5..70917f98 100644
--- a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs
+++ b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs
@@ -1,8 +1,10 @@
using System.Text.Json;
using AgentCore.Application.Configuration.Schema;
+using AgentCore.Application.Runtime;
using Microsoft.Extensions.AI;
+using Microsoft.Agents.AI;
namespace AgentCore.Application.Knowledge;
@@ -11,24 +13,31 @@ namespace AgentCore.Application.Knowledge;
///
internal sealed class FacetFilteredSearch : DelegatingAIFunction
{
- private readonly IReadOnlyList _facets;
+ private readonly IReadOnlyList? _facets;
+
+ private readonly KnowledgeSearch.Core _core;
private readonly JsonElement _schema;
/// Wraps one search function.
- /// The function the framework built.
- /// What scope.filterable declared, in document order.
+ /// The function the framework built: the schema donor, never invoked.
+ /// What scope.filterable declared, in document order — or null when it declared none.
+ /// The search bound to this agent's store and wiring.
/// A required argument is .
internal FacetFilteredSearch(
AIFunction innerFunction,
- IReadOnlyList facets)
+ IReadOnlyList? facets,
+ KnowledgeSearch.Core core)
: base(innerFunction)
{
ArgumentNullException.ThrowIfNull(innerFunction);
- ArgumentNullException.ThrowIfNull(facets);
+ ArgumentNullException.ThrowIfNull(core);
_facets = facets;
- _schema = FacetFilterSchema.Extend(innerFunction.JsonSchema, facets);
+ _core = core;
+ _schema = facets is { Count: > 0 }
+ ? FacetFilterSchema.Extend(innerFunction.JsonSchema, facets)
+ : innerFunction.JsonSchema;
}
///
@@ -40,35 +49,50 @@ internal FacetFilteredSearch(
{
ArgumentNullException.ThrowIfNull(arguments);
- var named = FacetFilterReader.Read(arguments, _facets);
+ var named = _facets is { Count: > 0 }
+ ? FacetFilterReader.Read(arguments, _facets)
+ : null;
- using var scope = named.Count > 0 ? ToolFacetScope.Open(named) : null;
+ var turn = arguments.TryGetValue(TurnInvocation.ArgumentsKey, out var filed) && filed is TurnInvocation invocation
+ ? invocation
+ : null;
- return await base.InvokeCoreAsync(Forwarded(arguments), cancellationToken).ConfigureAwait(false);
- }
+ // The donor's own declaration names the question: the model was built against it.
+ var question = FirstQueryArgument(InnerFunction.JsonSchema) is { } name
+ && arguments.TryGetValue(name, out var asked)
+ ? QueryText(asked)
+ : null;
- /// The arguments without the one this wrapper owns.
- private static AIFunctionArguments Forwarded(AIFunctionArguments arguments)
- {
- if (!arguments.ContainsKey(FacetFilterSchema.ArgumentName))
+ if (question is null)
{
- return arguments;
+ throw new InvalidOperationException(
+ "The knowledge search was called without a search question, so there is nothing to look up.");
}
- Dictionary kept = new(StringComparer.Ordinal);
+ IReadOnlyList results =
+ await _core(question, named?.Count > 0 ? named : null, turn, cancellationToken).ConfigureAwait(false);
+
+ return results;
+ }
- foreach (var (name, value) in arguments)
+ /// Reads the donor's question argument name off its own schema.
+ private static string? FirstQueryArgument(JsonElement schema)
+ {
+ if (schema.ValueKind is not JsonValueKind.Object
+ || !schema.TryGetProperty("properties", out var properties)
+ || properties.ValueKind is not JsonValueKind.Object)
{
- if (!string.Equals(name, FacetFilterSchema.ArgumentName, StringComparison.Ordinal))
- {
- kept[name] = value;
- }
+ return null;
}
- return new AIFunctionArguments(kept)
+ return properties.EnumerateObject().Select(property => property.Name).FirstOrDefault();
+ }
+
+ private static string? QueryText(object? value)
+ => value switch
{
- Services = arguments.Services,
- Context = arguments.Context,
+ string text => text,
+ JsonElement { ValueKind: JsonValueKind.String } element => element.GetString(),
+ _ => null,
};
- }
}
diff --git a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs
index c8cbc965..cb51e1aa 100644
--- a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs
+++ b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs
@@ -65,7 +65,7 @@ public static KnowledgeAuditRecord For(
Scope = scope?.Facets ?? EmptyScope,
ScopeOrigins = scope?.Origins ?? EmptyOrigins,
LatencyMs = latencyMs,
- Cards = [.. cards.Select(CardEntry.For)],
+ Cards = [.. cards.Select(CardEntry.From)],
Failure = failure?.ToString(),
};
}
@@ -149,7 +149,7 @@ internal sealed record CardEntry
/// Reads one card into its audit entry.
/// The card to record.
/// The entry.
- internal static CardEntry For(KnowledgeCard card) => new()
+ internal static CardEntry From(KnowledgeCard card) => new()
{
CardId = card.CardId,
Score = card.Score,
diff --git a/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs
new file mode 100644
index 00000000..072af390
--- /dev/null
+++ b/src/AgentCore.Application/Knowledge/KnowledgePrefetchProvider.cs
@@ -0,0 +1,63 @@
+using Microsoft.Agents.AI;
+using Microsoft.Extensions.Logging;
+using AgentCore.Application.Runtime.Turn;
+
+namespace AgentCore.Application.Knowledge;
+
+// The prefetch half of one agent's knowledge block: runs the framework's own search provider
+// per invocation, bound to that invocation's turn. A shared provider cannot serve prefetch —
+// the framework invokes its search as (query, cancellation) with no turn — so this builds a
+// provider per call around the same options, closing over the turn the session filed. State
+// keys and post-invocation storage forward to the shared template: accumulation lives in
+// the session store, not on any instance, so a fresh provider per call loses nothing.
+internal sealed class KnowledgePrefetchProvider(
+ AIContextProvider template,
+ TextSearchProviderOptions options,
+ ILoggerFactory? loggers,
+ KnowledgeSearch.Core core)
+ : AIContextProvider
+{
+ private readonly AIContextProvider _template = template
+ ?? throw new ArgumentNullException(nameof(template));
+
+ private readonly TextSearchProviderOptions _options = options
+ ?? throw new ArgumentNullException(nameof(options));
+
+ private readonly ILoggerFactory? _loggers = loggers;
+
+ private readonly KnowledgeSearch.Core _core = core
+ ?? throw new ArgumentNullException(nameof(core));
+
+ ///
+ public override IReadOnlyList StateKeys => _template.StateKeys;
+
+ ///
+ public override object? GetService(Type serviceType, object? serviceKey = null)
+ {
+ ArgumentNullException.ThrowIfNull(serviceType);
+
+ return serviceType.IsInstanceOfType(this) && serviceKey is null
+ ? this
+ : _template.GetService(serviceType, serviceKey);
+ }
+
+ ///
+ protected override async ValueTask InvokingCoreAsync(
+ InvokingContext context, CancellationToken cancellationToken = default)
+ {
+ var turn = TurnRegistry.For(context.Session);
+
+ AIContextProvider inner = new TextSearchProvider(
+ async (query, token) =>
+ (IEnumerable)await _core(query, null, turn, token).ConfigureAwait(false),
+ _options,
+ _loggers);
+
+ return await inner.InvokingAsync(context, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ protected override ValueTask InvokedCoreAsync(
+ InvokedContext context, CancellationToken cancellationToken = default)
+ => _template.InvokedAsync(context, cancellationToken);
+}
diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs
index 107b74c7..6a791d2f 100644
--- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs
+++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs
@@ -23,6 +23,8 @@ internal static class KnowledgeProbe
/// The live scope the main search just ran under.
/// The id of the agent that asked, for the log line.
/// The search text the framework composed.
+ /// The call's ambiguity holder, or inside a nested tool call.
+ /// Whether this row's session carries the caller's own history.
/// Where the probe's own log events go.
/// The caller's own token — cancelling this is the caller hanging up, not a timeout.
/// What the probe found: its note, or the "holds nothing" notice.
@@ -32,12 +34,15 @@ internal static class KnowledgeProbe
KnowledgeScope scope,
string agent,
string query,
+ Clarifications? clarifications,
+ bool carriesHistory,
ILogger logger,
CancellationToken cancellationToken)
{
- // K42: a nested tool call strips the holder from the ambient, so a delegated run's own search
- // cannot latch, count or record — but a scoped run still owes the caller the notice.
- if (TurnAmbients.Current?.Clarifications is not { } clarifications)
+ // K42: a nested tool call runs with the holder stripped from its invocation, so a delegated
+ // run's own search cannot latch, count or record — but a scoped run still owes the caller
+ // the notice.
+ if (clarifications is null)
{
return [KnowledgeNotices.Of(KnowledgeNotices.Empty)];
}
@@ -83,28 +88,26 @@ internal static class KnowledgeProbe
// in the same turn would re-run the search and advance probeAsks a second time.
clarifications.Update(facet, s => s.ProbeAsks++);
- using CancellationTokenSource timeout =
- new(TimeSpan.FromSeconds(ambiguity.ProbeDeadlineSeconds));
- using var deadline =
- CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
+ using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(ambiguity.ProbeDeadlineSeconds));
+
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
IReadOnlyList probeCards;
+
try
{
- using var narrowed = KnowledgeScopeScope.Open(WithoutFacet(scope, facet));
-
+ var narrowedScope = WithoutFacet(scope, facet);
var started = Stopwatch.GetTimestamp();
- probeCards = await port.SearchAsync(query, deadline.Token).ConfigureAwait(false);
+
+ probeCards = await port.SearchAsync(query, narrowedScope, deadline.Token).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
- // Filed while the narrowed scope is still open, so the record names the scope this
- // second store call actually ran under. Without it an operator sizing store load
- // sees one record per turn for two calls.
var record = KnowledgeSearchRecord.Of(
agent,
knowledge,
query,
+ narrowedScope,
probeCards,
Stopwatch.GetElapsedTime(started).TotalMilliseconds,
failure: null).ForLog();
@@ -131,7 +134,7 @@ internal static class KnowledgeProbe
return Publish(probe, KnowledgeNotices.Empty);
}
- return Name(probeCards, template, ambiguity, wiring, wildcardValue, facet, agent, logger, clarifications, probe);
+ return Name(probeCards, template, ambiguity, wiring, wildcardValue, facet, agent, logger, clarifications, carriesHistory, probe);
}
finally
{
@@ -171,6 +174,7 @@ internal static class KnowledgeProbe
string agent,
ILogger logger,
Clarifications clarifications,
+ bool carriesHistory,
Clarifications.Probe probe)
{
// §8 step 5: the value at the facet's payload path is a string or a list of strings alike —
@@ -179,16 +183,9 @@ internal static class KnowledgeProbe
var path = template.Resolve(facet);
SortedSet union = new(StringComparer.Ordinal);
- foreach (var card in probeCards)
- {
- foreach (var value in FacetValues(card, path))
- {
- if (!string.Equals(value, wildcardValue, StringComparison.Ordinal))
- {
- union.Add(value);
- }
- }
- }
+ union.UnionWith(probeCards
+ .SelectMany(card => FacetValues(card, path))
+ .Where(value => !string.Equals(value, wildcardValue, StringComparison.Ordinal)));
Log.KnowledgeProbeRan(logger, agent, facet, union.Count);
@@ -201,11 +198,12 @@ internal static class KnowledgeProbe
// message.
var wouldName = Clarifications.LastNamed.For(union, ambiguity.MaxCandidates);
var candidates = union.ToList();
-
+
// K39, drawn for the record rather than for the message: on a graph row AgentCore cannot know
// whether the participant's own tool result ever reached the caller, so the note still goes
- // out, but the record of what was named — which arms K21's tie-break — does not.
- var carriesHistory = TurnAmbients.Current?.Context?.CarriesHistory ?? false;
+ // out, but the record of what was named — which arms K21's tie-break — does not. The flag
+ // arrives as a parameter because the probe runs inside a search delegate that is never
+ // handed a session to compare.
// Whether the note repeats what was last named, and the record that follows from it, are one
// transition under one lock acquisition. Deciding from an earlier Read() and writing after
diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs
index 79423574..b479e81a 100644
--- a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs
+++ b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs
@@ -1,11 +1,6 @@
-using System.Diagnostics;
using AgentCore.Application.Configuration.Compilation;
using AgentCore.Application.Configuration.Schema;
-using AgentCore.Application.Diagnostics;
using AgentCore.Application.Ports;
-using AgentCore.Application.Runtime;
-using AgentCore.Application.State;
-using AgentCore.Domain.Knowledge;
using Microsoft.Agents.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
@@ -17,11 +12,6 @@ namespace AgentCore.Application.Knowledge;
///
internal static class KnowledgeProviderFactory
{
- ///
- /// The scope an agent that declares scoped: false searches under.
- ///
- private static readonly KnowledgeScope WholeCorpus =
- new() { Facets = new Dictionary(StringComparer.Ordinal) };
/// Builds the provider one agent binds.
/// The store every agent shares.
@@ -31,8 +21,8 @@ internal static class KnowledgeProviderFactory
///
/// Where the retrieval record and the framework's own provider log go, or
/// when the host wired none. Ruling 21: this is the one reachable observability seam — the audit
- /// sink is not, because AuditEvent requires a call id and a sequence number that no
- /// ambient carries down here.
+ /// sink is not, because AuditEvent requires a call id and a sequence number that this
+ /// seam doesn't carry down here.
///
/// The document's providers.knowledge.scope block, or .
/// The provider to hang on that agent.
@@ -65,156 +55,24 @@ internal static AIContextProvider Create(
RecentMessageMemoryLimit = 4,
};
- AIContextProvider provider = new TextSearchProvider(SearchAsync, options, loggers);
+ KnowledgeSearch.Core core = KnowledgeSearch.Bind(port, knowledge, agent, citations, logger);
- return knowledge.Mode == KnowledgeMode.Tool && scope?.Filterable is { Count: > 0 } filterable
- ? new FacetFilterProvider(provider, filterable)
- : provider;
+ // The template's own delegate never runs: tool-mode searches go through the
+ // invocation-bound wrapper, prefetch through per-invocation providers. It fails
+ // loudly if either path ever leaks through.
+ AIContextProvider template = new TextSearchProvider(UnreachableSearch, options, loggers);
- async Task> SearchAsync(
- string query, CancellationToken cancellationToken)
+ if (knowledge.Mode != KnowledgeMode.Tool)
{
- // An ambient with no facets filters nothing, so it is the absent ambient in disguise.
- // The shared store can only fail closed when EVERY agent is scoped, so in a mixed
- // deployment this is the only check standing between a scoped agent and every
- // customer's cards.
- if (knowledge.Scoped && KnowledgeScopeScope.Current is not { Facets.Count: > 0 })
- {
- return [KnowledgeNotices.Of(KnowledgeNotices.NoScope)];
- }
-
- var composed = knowledge.Scoped ? KnowledgeScopeScope.Current! : WholeCorpus;
-
- var (narrowed, byTool) = ToolFacetOverlay.Apply(composed, ToolFacetScope.Current);
-
- var started = Stopwatch.GetTimestamp();
-
- double? searched = null;
-
- try
- {
- var under = narrowed;
- var (cards, latency) = await Under(narrowed).ConfigureAwait(false);
- searched = latency;
-
- if (cards.Count == 0 && byTool)
- {
- under = composed;
- (cards, _) = await Under(composed).ConfigureAwait(false);
- }
-
- using var tail = KnowledgeScopeScope.Open(under);
-
- if (cards.Count == 0
- && knowledge.Mode == KnowledgeMode.Tool
- && under.Facets.Count > 0)
- {
- return await KnowledgeProbe
- .RunAsync(port, knowledge, under, agent, query, logger, cancellationToken)
- .ConfigureAwait(false);
- }
-
- var shown = Kept(cards, knowledge);
- Cite(shown, knowledge, citations);
-
- return Map(shown, knowledge, citations);
- }
- catch (Exception failure) when (!KnowledgeCancellation.ByCaller(failure, cancellationToken))
- {
- var latency = searched ?? Stopwatch.GetElapsedTime(started).TotalMilliseconds;
- var record = KnowledgeSearchRecord
- .Of(agent, knowledge, query, [], latency, failure)
- .ForLog();
-
- Log.KnowledgeRetrievalFailed(logger, agent, record, failure);
-
- return [KnowledgeNotices.Of(KnowledgeNotices.Unreachable)];
- }
-
- async Task<(IReadOnlyList Cards, double LatencyMs)> Under(KnowledgeScope open)
- {
- using var held = KnowledgeScopeScope.Open(open);
-
- var cards = await port.SearchAsync(query, cancellationToken).ConfigureAwait(false);
-
- var latency = Stopwatch.GetElapsedTime(started).TotalMilliseconds;
-
- if (logger.IsEnabled(LogLevel.Debug))
- {
- var record = KnowledgeSearchRecord
- .Of(agent, knowledge, query, cards, latency, failure: null)
- .ForLog();
-
- Log.KnowledgeRetrieved(logger, agent, cards.Count, record);
- }
-
- return (cards, latency);
- }
+ return new KnowledgePrefetchProvider(template, options, loggers, core);
}
- }
- /// Cites what this search read, for the caller's screen.
- /// The cards the agent is actually shown, after cuts the search down to the agent's limit: — not everything the store returned.
- /// The agent's resolved knowledge: block.
- /// The wording providers.knowledge.citation named.
- private static void Cite(
- IReadOnlyList cards,
- ResolvedKnowledge knowledge,
- IKnowledgeCitationFormatter citations)
- {
- if (!knowledge.Citations || CallSourceScope.Current is not { } port)
- {
- return;
- }
-
- foreach (var card in cards)
- {
- if (KnowledgeSourceMapper.ToSource(card, citations) is { } source)
- {
- port.Publish(source);
- }
- }
- }
-
- /// Cuts one search down to the agent's limit: .
- /// What the store returned, best first, links last.
- /// The agent's resolved knowledge: block.
- /// The cards this agent is shown.
- private static List Kept(IReadOnlyList cards, ResolvedKnowledge knowledge)
- {
- List kept = [];
- var ranked = 0;
-
- foreach (var card in cards)
- {
- if (!card.ViaLink && ranked++ >= knowledge.Limit)
- {
- continue;
- }
-
- kept.Add(card);
- }
-
- return kept;
+ return new FacetFilterProvider(template, scope?.Filterable, core);
}
- /// Maps the cards this agent is shown into what the framework injects.
- /// The cards already cut down to the agent's limit: .
- /// The agent's resolved knowledge: block.
- /// The wording each card's source label is written in.
- /// The results the framework injects.
- private static List Map(
- IReadOnlyList cards,
- ResolvedKnowledge knowledge,
- IKnowledgeCitationFormatter citations)
- {
- List mapped = [];
-
- foreach (var card in cards)
- {
- mapped.Add(KnowledgeCardMapper.ToResult(card, knowledge.Citations, citations));
- }
-
- return mapped;
- }
+ private static Task> UnreachableSearch(
+ string query, CancellationToken cancellationToken)
+ => Task.FromException>(
+ new InvalidOperationException(
+ "A knowledge search ran outside its turn. Searches run through the turn's own provider or tool."));
}
diff --git a/src/AgentCore.Application/Ports/KnowledgeRetrievalPortExtensions.cs b/src/AgentCore.Application/Knowledge/KnowledgeRetrievalPortExtensions.cs
similarity index 92%
rename from src/AgentCore.Application/Ports/KnowledgeRetrievalPortExtensions.cs
rename to src/AgentCore.Application/Knowledge/KnowledgeRetrievalPortExtensions.cs
index 1aab5823..a3000947 100644
--- a/src/AgentCore.Application/Ports/KnowledgeRetrievalPortExtensions.cs
+++ b/src/AgentCore.Application/Knowledge/KnowledgeRetrievalPortExtensions.cs
@@ -1,4 +1,6 @@
-namespace AgentCore.Application.Ports;
+using AgentCore.Application.Ports;
+
+namespace AgentCore.Application.Knowledge;
///
/// Typed helpers over .
diff --git a/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs b/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs
new file mode 100644
index 00000000..4d4f66a5
--- /dev/null
+++ b/src/AgentCore.Application/Knowledge/KnowledgeSearch.cs
@@ -0,0 +1,205 @@
+using System.Diagnostics;
+using AgentCore.Application.Configuration.Compilation;
+using AgentCore.Application.Configuration.Schema;
+using AgentCore.Application.Runtime.Turn;
+using AgentCore.Application.Diagnostics;
+using AgentCore.Application.Ports;
+using AgentCore.Application.Runtime;
+using AgentCore.Domain.Knowledge;
+using Microsoft.Agents.AI;
+using Microsoft.Extensions.Logging;
+
+namespace AgentCore.Application.Knowledge;
+
+// One search against the store with everything the turn hands it, as explicit values: the
+// scope to read under, the tool-call facets to overlay, and the turn's own probe, history
+// flag and citation port. The framework invokes the search in two shapes — a tool call
+// carrying arguments, and a prefetch carrying only a session — and both bind those shapes
+// to these values before calling here, so this core never reads the flow.
+internal static class KnowledgeSearch
+{
+ /// Searches with an explicit scope, facets and turn.
+ internal delegate Task> Core(
+ string query,
+ IReadOnlyDictionary? facets,
+ TurnInvocation? turn,
+ CancellationToken cancellationToken);
+
+ /// The scope an agent that declares scoped: false searches under.
+ internal static readonly KnowledgeScope WholeCorpus =
+ new() { Facets = new Dictionary(StringComparer.Ordinal) };
+
+ /// Binds the core to one agent's port, wiring and loggers.
+ internal static Core Bind(
+ IKnowledgeRetrievalPort port,
+ ResolvedKnowledge knowledge,
+ string agent,
+ IKnowledgeCitationFormatter citations,
+ ILogger logger)
+ {
+ ArgumentNullException.ThrowIfNull(port);
+ ArgumentNullException.ThrowIfNull(knowledge);
+ ArgumentNullException.ThrowIfNull(agent);
+ ArgumentNullException.ThrowIfNull(citations);
+ ArgumentNullException.ThrowIfNull(logger);
+
+ return (query, facets, turn, cancellationToken) => RunAsync(
+ port, knowledge, agent, query, facets, turn, citations, logger, cancellationToken);
+ }
+
+ private static async Task> RunAsync(
+ IKnowledgeRetrievalPort port,
+ ResolvedKnowledge knowledge,
+ string agent,
+ string query,
+ IReadOnlyDictionary? facets,
+ TurnInvocation? turn,
+ IKnowledgeCitationFormatter citations,
+ ILogger logger,
+ CancellationToken cancellationToken)
+ {
+ // No scope filters nothing, so it is the absent scope in disguise. The shared store
+ // can only fail closed when EVERY agent is scoped, so in a mixed deployment this is
+ // the only check standing between a scoped agent and every customer's cards. A null
+ // turn — a framework-driven sub-run (graph node, background child) the loop never
+ // invoked — searches the whole corpus unscoped and names NoScope scoped: loud, never
+ // a leak.
+ var composed = knowledge.Scoped ? turn?.Knowledge : WholeCorpus;
+
+ if (knowledge.Scoped && composed is not { Facets.Count: > 0 })
+ {
+ return [KnowledgeNotices.Of(KnowledgeNotices.NoScope)];
+ }
+
+ var scope = composed ?? WholeCorpus;
+
+ var (narrowed, byTool) = ToolFacetOverlay.Apply(scope, facets);
+
+ var started = Stopwatch.GetTimestamp();
+
+ double? searched = null;
+ var under = narrowed;
+
+ try
+ {
+ var (cards, latency) = await Under(narrowed).ConfigureAwait(false);
+ searched = latency;
+
+ if (cards.Count == 0 && byTool)
+ {
+ under = scope;
+ (cards, _) = await Under(scope).ConfigureAwait(false);
+ }
+
+ if (cards.Count == 0
+ && knowledge.Mode == KnowledgeMode.Tool
+ && under.Facets.Count > 0)
+ {
+ return await KnowledgeProbe
+ .RunAsync(port, knowledge, under, agent, query, turn?.Clarifications, turn?.CarriesHistory ?? false, logger, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ var shown = Kept(cards, knowledge);
+ Cite(shown, knowledge, citations, turn?.Sources);
+
+ return Map(shown, knowledge, citations);
+ }
+ catch (Exception failure) when (!KnowledgeCancellation.ByCaller(failure, cancellationToken))
+ {
+ var latency = searched ?? Stopwatch.GetElapsedTime(started).TotalMilliseconds;
+ var record = KnowledgeSearchRecord
+ .Of(agent, knowledge, query, under, [], latency, failure)
+ .ForLog();
+
+ Log.KnowledgeRetrievalFailed(logger, agent, record, failure);
+
+ return [KnowledgeNotices.Of(KnowledgeNotices.Unreachable)];
+ }
+
+ async Task<(IReadOnlyList Cards, double LatencyMs)> Under(KnowledgeScope open)
+ {
+ var cards = await port.SearchAsync(query, open, cancellationToken).ConfigureAwait(false);
+
+ var latency = Stopwatch.GetElapsedTime(started).TotalMilliseconds;
+
+ if (logger.IsEnabled(LogLevel.Debug))
+ {
+ var record = KnowledgeSearchRecord
+ .Of(agent, knowledge, query, open, cards, latency, failure: null)
+ .ForLog();
+
+ Log.KnowledgeRetrieved(logger, agent, cards.Count, record);
+ }
+
+ return (cards, latency);
+ }
+ }
+
+ /// Cuts one search down to the agent's limit: .
+ /// What the store returned, best first, links last.
+ /// The agent's resolved knowledge: block.
+ /// The cards this agent is shown.
+ private static List Kept(IReadOnlyList cards, ResolvedKnowledge knowledge)
+ {
+ List kept = [];
+ var ranked = 0;
+
+ foreach (var card in cards)
+ {
+ if (!card.ViaLink && ranked++ >= knowledge.Limit)
+ {
+ continue;
+ }
+
+ kept.Add(card);
+ }
+
+ return kept;
+ }
+
+ /// Cites what this search read, for the caller's screen.
+ /// The cards the agent is actually shown, after cuts the search down to the agent's limit: — not everything the store returned.
+ /// The agent's resolved knowledge: block.
+ /// The wording providers.knowledge.citation named.
+ /// What the turn cites into, or outside a turn.
+ private static void Cite(
+ IReadOnlyList cards,
+ ResolvedKnowledge knowledge,
+ IKnowledgeCitationFormatter citations,
+ TurnSources? port)
+ {
+ if (!knowledge.Citations || port is null)
+ {
+ return;
+ }
+
+ foreach (var card in cards)
+ {
+ if (KnowledgeSourceMapper.ToSource(card, citations) is { } source)
+ {
+ port.Publish(source);
+ }
+ }
+ }
+
+ /// Maps the cards this agent is shown into what the framework injects.
+ /// The cards already cut down to the agent's limit: .
+ /// The agent's resolved knowledge: block.
+ /// The wording each card's source label is written in.
+ /// The results the framework injects.
+ private static List Map(
+ IReadOnlyList cards,
+ ResolvedKnowledge knowledge,
+ IKnowledgeCitationFormatter citations)
+ {
+ List mapped = [];
+
+ foreach (var card in cards)
+ {
+ mapped.Add(KnowledgeCardMapper.ToResult(card, knowledge.Citations, citations));
+ }
+
+ return mapped;
+ }
+}
diff --git a/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs
index f1bc3f14..14b177ed 100644
--- a/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs
+++ b/src/AgentCore.Application/Knowledge/KnowledgeSearchRecord.cs
@@ -1,5 +1,4 @@
using AgentCore.Application.Configuration.Compilation;
-using AgentCore.Application.Runtime;
using AgentCore.Domain.Knowledge;
namespace AgentCore.Application.Knowledge;
@@ -13,19 +12,16 @@ internal static class KnowledgeSearchRecord
/// The id of the agent that asked.
/// The agent's resolved knowledge: block.
/// The search text the framework composed.
+ /// The scope the store call ran under.
/// What the store returned, or empty when it threw.
/// How long that one store call took, in milliseconds.
/// What the port threw, or when it answered.
/// The record.
- ///
- /// The scope comes from the live ambient, so a caller has to build this while the scope the call
- /// ran under is still open. The probe's second search opens a narrowed scope of its own, and its
- /// record is meant to name that one rather than the scope the main search used.
- ///
internal static KnowledgeAuditRecord Of(
string agent,
ResolvedKnowledge knowledge,
string query,
+ KnowledgeScope? scope,
IReadOnlyList cards,
double latencyMs,
Exception? failure)
@@ -34,7 +30,7 @@ internal static KnowledgeAuditRecord Of(
agent,
knowledge.Mode,
query,
- KnowledgeScopeScope.Current,
+ scope,
cards,
latencyMs,
failure);
diff --git a/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs b/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs
index d4ea3092..1d689d66 100644
--- a/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs
+++ b/src/AgentCore.Application/Knowledge/StateKnowledgeScope.cs
@@ -10,13 +10,13 @@ namespace AgentCore.Application.Knowledge;
///
internal static class StateKnowledgeScope
{
- /// Composes the turn's scope from the host's ambient and the call's state.
+ /// Composes the turn's scope from the host's scope and the call's state.
/// The state of the call, as it stands at the start of this turn.
/// The document's providers.knowledge.scope block, or null.
- /// What the host opened for this turn, or null when it opened nothing.
- /// The scope, or unchanged when this document composes none.
+ /// What the host set for this call, or null when it set nothing.
+ /// The scope, or unchanged when this document composes none.
internal static KnowledgeScope? Compose(
- StateDocument state, KnowledgeScopeConfiguration? scope, KnowledgeScope? ambient)
+ StateDocument state, KnowledgeScopeConfiguration? scope, KnowledgeScope? hostScope)
{
ArgumentNullException.ThrowIfNull(state);
@@ -26,15 +26,15 @@ internal static class StateKnowledgeScope
// scope — including its absence, which still fails closed — is what the turn sees.
if (scope?.Wildcard is not { } wildcard || scope.FromState.Count == 0)
{
- return ambient;
+ return hostScope;
}
Dictionary facets = new(StringComparer.Ordinal);
Dictionary origins = new(StringComparer.Ordinal);
- if (ambient is not null)
+ if (hostScope is not null)
{
- foreach (var (key, value) in ambient.Facets)
+ foreach (var (key, value) in hostScope.Facets)
{
facets[key] = value;
origins[key] = KnowledgeFacetOrigin.Host;
diff --git a/src/AgentCore.Application/Knowledge/ToolFacetScope.cs b/src/AgentCore.Application/Knowledge/ToolFacetScope.cs
deleted file mode 100644
index d46fa58e..00000000
--- a/src/AgentCore.Application/Knowledge/ToolFacetScope.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-namespace AgentCore.Application.Knowledge;
-
-///
-/// Carries the facets a search tool's argument named down to the search itself.
-///
-internal static class ToolFacetScope
-{
- private static readonly AsyncLocal?> Named = new();
-
- /// Gets what a tool argument named on this flow, or when none did.
- internal static IReadOnlyDictionary? Current => Named.Value;
-
- /// Opens one set of named facets over this flow.
- /// The facet key to stored value.
- /// A handle that puts back what was open before.
- /// is .
- internal static IDisposable Open(IReadOnlyDictionary facets)
- {
- ArgumentNullException.ThrowIfNull(facets);
-
- var before = Named.Value;
- Named.Value = facets;
-
- return new Handle(before);
- }
-
- private sealed class Handle(IReadOnlyDictionary? before) : IDisposable
- {
- private bool _closed;
-
- public void Dispose()
- {
- if (_closed)
- {
- return;
- }
-
- _closed = true;
- Named.Value = before;
- }
- }
-}
diff --git a/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs b/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs
index a209302a..1800c28c 100644
--- a/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs
+++ b/src/AgentCore.Application/Llm/CompositeChatClientFactory.cs
@@ -12,33 +12,18 @@ namespace AgentCore.Application.Llm;
/// The one a config-driven host binds. It routes each
/// providers.llm[] entry to the whose kind matches.
///
-///
-///
-/// The compile table asks for the client behind an as name and never reads a vendor name.
-/// This class holds the vendor-neutral half of that mapping: the as map, the default entry,
-/// and the two client caches, vendor and shaped. The vendor half lives in the adapters, one for
-/// each kind , so the document alone decides which vendor answers which reference.
-///
-///
-/// Every client is built while runs. A kind no adapter serves and a
-/// credential that does not resolve both stop the host at startup, and not on the first call. An
-/// agent that reached the telephone and then found no model is the silent failure the startup checks
-/// exist to stop.
-///
-///
-/// One vendor client is built for each as name and then shared, because a chat client is
-/// thread-safe and a call costs a connection pool. A reference that also sets
-/// takes a thin wrapper over that same vendor client, so the
-/// document keeps its setting and the pool stays one.
-///
-///
public sealed class CompositeChatClientFactory : IChatClientFactory, IDisposable
{
private readonly Dictionary _entries = new(StringComparer.Ordinal);
+
+ private readonly Dictionary _adapters = new(StringComparer.Ordinal);
+
private readonly Dictionary _vendor = new(StringComparer.Ordinal);
+
private readonly ConcurrentDictionary _shaped = new(StringComparer.Ordinal);
- private readonly Dictionary _capable = new(StringComparer.Ordinal);
+
private LlmProviderConfiguration? _default;
+
private int _disposed;
private CompositeChatClientFactory()
@@ -85,10 +70,11 @@ public static async ValueTask CreateAsync(
$"two entries answer to the name '{entry.As}', so a model reference names two models.");
}
+ factory._adapters[entry.As] = adapter;
+
factory._vendor[entry.As] = await adapter
.CreateClientAsync(entry, secrets, cancellationToken)
.ConfigureAwait(false);
- factory._capable[entry.As] = adapter.SupportsHostedWebSearch(entry);
factory._default ??= entry;
}
@@ -127,11 +113,20 @@ public IChatClient GetChatClient(ModelReference? model)
}
///
- public bool SupportsHostedWebSearch(ModelReference? model)
+ public AITool? ResolveHostedTool(AITool marker, ModelReference? model)
{
+ ArgumentNullException.ThrowIfNull(marker);
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) == 1, this);
- return _capable.TryGetValue(model?.Ref ?? _default?.As ?? string.Empty, out var capable) && capable;
+ var entry = model is null
+ ? _default
+ : _entries.TryGetValue(model.Ref, out var named) ? named : null;
+ if (entry is null || !_adapters.TryGetValue(entry.As, out var adapter))
+ {
+ return null;
+ }
+
+ return adapter.ResolveHostedTool(marker, entry);
}
/// Releases every client the adapters built.
diff --git a/src/AgentCore.Application/Policy/StagePolicy.cs b/src/AgentCore.Application/Policy/StagePolicy.cs
index 80239024..1e625d31 100644
--- a/src/AgentCore.Application/Policy/StagePolicy.cs
+++ b/src/AgentCore.Application/Policy/StagePolicy.cs
@@ -24,8 +24,8 @@ public sealed class StagePolicy
private string _stage;
- /// Builds the machine one configuration declares.
- /// The policy: section.
+ /// Builds the machine one entry's policy: block declares.
+ /// The entry's policy: block.
/// The evaluator that runs each exit guard.
/// The initial stage is not declared.
public StagePolicy(PolicyConfiguration policy, IGuardEvaluator guards)
@@ -69,11 +69,11 @@ public StagePolicy(PolicyConfiguration policy, IGuardEvaluator guards)
}
}
- /// Gets the policy: section this machine was built from.
+ /// Gets the entry's policy: block this machine was built from.
public PolicyConfiguration Configuration => _policy;
/// Gets the id of the stage the machine holds.
- public string Stage => _machine.State;
+ public string Stage => _stage;
/// Gets the stage the machine holds.
public StageConfiguration CurrentStage => _stages[_machine.State];
diff --git a/src/AgentCore.Application/Ports/ICallAdapter.cs b/src/AgentCore.Application/Ports/ICallAdapter.cs
index c3deb4d0..9c364f8c 100644
--- a/src/AgentCore.Application/Ports/ICallAdapter.cs
+++ b/src/AgentCore.Application/Ports/ICallAdapter.cs
@@ -24,7 +24,7 @@ public interface ICallAdapter : IVendorAdapter
/// means the vendor performs recognition and synthesis itself — the
/// Telnyx Conversation Relay does — so both speech roles,
/// providers.speech.stt.kind and providers.speech.tts.kind , must name that same
- /// vendor, and enforces it.
+ /// vendor, and enforces it.
///
///
/// means the frames carry audio and a separate speech vendor turns it
diff --git a/src/AgentCore.Application/Ports/ICallChannelFactory.cs b/src/AgentCore.Application/Ports/ICallChannelFactory.cs
index b3e5ebae..30e998c8 100644
--- a/src/AgentCore.Application/Ports/ICallChannelFactory.cs
+++ b/src/AgentCore.Application/Ports/ICallChannelFactory.cs
@@ -1,4 +1,4 @@
-using AgentCore.Application.Call;
+using AgentCore.Application.Calls;
namespace AgentCore.Application.Ports;
diff --git a/src/AgentCore.Application/Ports/ICallInputPort.cs b/src/AgentCore.Application/Ports/ICallInputPort.cs
index 02a84af3..752e2c44 100644
--- a/src/AgentCore.Application/Ports/ICallInputPort.cs
+++ b/src/AgentCore.Application/Ports/ICallInputPort.cs
@@ -1,4 +1,4 @@
-using AgentCore.Application.Call;
+using AgentCore.Application.Calls;
namespace AgentCore.Application.Ports;
diff --git a/src/AgentCore.Application/Ports/ICallOutputPort.cs b/src/AgentCore.Application/Ports/ICallOutputPort.cs
index c492db25..27cb8027 100644
--- a/src/AgentCore.Application/Ports/ICallOutputPort.cs
+++ b/src/AgentCore.Application/Ports/ICallOutputPort.cs
@@ -1,4 +1,4 @@
-using AgentCore.Application.Call;
+using AgentCore.Application.Calls;
namespace AgentCore.Application.Ports;
diff --git a/src/AgentCore.Application/Ports/ICallSessionRegistry.cs b/src/AgentCore.Application/Ports/ICallSessionRegistry.cs
new file mode 100644
index 00000000..139fe4ea
--- /dev/null
+++ b/src/AgentCore.Application/Ports/ICallSessionRegistry.cs
@@ -0,0 +1,16 @@
+namespace AgentCore.Application.Ports;
+
+///
+/// Finds the session store of one entry.
+///
+public interface ICallSessionRegistry
+{
+ /// Gets the names of the entries the document declares.
+ IReadOnlyCollection Entries { get; }
+
+ /// Reads one entry's session store.
+ /// The entry key, as the document declares it.
+ /// The store for that entry.
+ /// The entry is not declared.
+ ICallSessions ForSessions(string entry);
+}
diff --git a/src/AgentCore.Application/Ports/ICallSessions.cs b/src/AgentCore.Application/Ports/ICallSessions.cs
index 845746f2..c0ef9136 100644
--- a/src/AgentCore.Application/Ports/ICallSessions.cs
+++ b/src/AgentCore.Application/Ports/ICallSessions.cs
@@ -39,7 +39,8 @@ public interface ICallSessions
/// turn still in flight, and the session is the only thing that can wait for those writes — once
/// it is dropped nothing can, and the durable record loses the turn the caller just had with no
/// error anywhere to say so. Every way a session ends comes through here, expiry included, so
- /// no path can be written that skips the wait.
+ /// no path can be written that skips the wait. An implementation must also dispose the session:
+ /// it owns processes (a call's shell: executors) that a dropped reference would leak.
///
ValueTask CloseAsync(string callId, CancellationToken cancellationToken = default);
}
diff --git a/src/AgentCore.Application/Ports/ICallStore.cs b/src/AgentCore.Application/Ports/ICallStore.cs
index b1da3e1f..f384ccdc 100644
--- a/src/AgentCore.Application/Ports/ICallStore.cs
+++ b/src/AgentCore.Application/Ports/ICallStore.cs
@@ -64,6 +64,7 @@ ValueTask ListAsync(
ValueTask DeleteAsync(string callId, CancellationToken cancellationToken = default);
/// Writes a turn's new messages, and the state the session holds after them.
+ /// The call every message in belongs to.
/// The rows to write, oldest first.
///
/// What the session holds after this turn, or to leave the stored state
@@ -73,25 +74,67 @@ ValueTask ListAsync(
/// it to ride with, so there is nothing to write it beside.
///
/// Cancels the write.
- ValueTask AppendAsync(
- IReadOnlyList messages,
+ ///
+ /// The rows as written, in the order given, each with its ordinal and its turn index.
+ ///
+ ///
+ /// The store numbers every row from the call's own counter, in one atomic step, so two writers on
+ /// two machines never collide on an ordinal — one from the call's live session, the other from a
+ /// host appending outside any turn.
+ ///
+ ///
+ /// The call named by does not exist. A row is never written against a
+ /// call that has no row of its own.
+ ///
+ ValueTask> AppendAsync(
+ string callId,
+ IReadOnlyList messages,
CallSessionState? state = null,
CancellationToken cancellationToken = default);
+ ///
+ /// Appends one message to a call from outside any turn. The store numbers the row and stamps it
+ /// with the turn the call takes next. Works whether or not a session for the call is live.
+ ///
+ /// The call to append to.
+ /// The message to append.
+ /// Cancels the write.
+ /// The row as written: its ordinal, its turn index, and its id.
+ async ValueTask AppendMessageAsync(
+ string callId,
+ ChatMessage message,
+ CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(message);
+
+ var messageId = string.IsNullOrEmpty(message.MessageId) ? CallMessageIds.New() : message.MessageId;
+ CallMessageDraft draft = new(TurnIndex: null, message, messageId);
+
+ var rows = await AppendAsync(callId, [draft], state: null, cancellationToken).ConfigureAwait(false);
+ return rows[0];
+ }
+
/// Rewrites one already-written message in place, on a barge-in.
/// The call the message belongs to.
- /// The message's position within the call.
+ ///
+ /// The message to rewrite, by name rather than by ordinal: the session's in-memory ordinal is
+ /// still provisional while a turn runs, but the message id is fixed the moment the row is cut.
+ ///
/// What the caller actually heard.
/// Cancels the write.
ValueTask RewriteAsync(
- string callId, int ordinal, ChatMessage content, CancellationToken cancellationToken = default);
+ string callId,
+ string messageId,
+ ChatMessage content,
+ CancellationToken cancellationToken = default);
/// Reads one whole call's words, oldest message first.
/// The call to read.
/// Cancels the read.
/// Every message of the call, or an empty list when it holds none.
ValueTask> ReadAsync(
- string callId, CancellationToken cancellationToken = default);
+ string callId,
+ CancellationToken cancellationToken = default);
/// Withdraws the tail of a call's words, from one ordinal onward.
/// The call to cut.
@@ -99,7 +142,9 @@ ValueTask> ReadAsync(
/// Cancels the delete.
/// How many messages went.
ValueTask TruncateAsync(
- string callId, int fromOrdinal, CancellationToken cancellationToken = default);
+ string callId,
+ int fromOrdinal,
+ CancellationToken cancellationToken = default);
/// Erases one call's words, and leaves its row in the listing.
/// The call to quieten.
@@ -120,7 +165,9 @@ ValueTask TruncateAsync(
/// Cancels the sweep between batches, and inside one.
/// How many calls went, over every batch.
ValueTask SweepAsync(
- TimeSpan retention, int batchSize = 500, CancellationToken cancellationToken = default);
+ TimeSpan retention,
+ int batchSize = 500,
+ CancellationToken cancellationToken = default);
/// Gives a principal a claim on a call.
/// The call to claim.
@@ -128,12 +175,45 @@ ValueTask SweepAsync(
/// What the key is to this call. AgentCore assigns its values no meaning.
/// Cancels the write.
ValueTask AttachPrincipalAsync(
- string callId, string principalKey, string role, CancellationToken cancellationToken = default);
+ string callId,
+ string principalKey,
+ string role,
+ CancellationToken cancellationToken = default);
/// Takes a principal's claim off a call.
/// The call to unclaim.
/// The key to remove.
/// Cancels the delete.
ValueTask DetachPrincipalAsync(
- string callId, string principalKey, CancellationToken cancellationToken = default);
+ string callId,
+ string principalKey,
+ CancellationToken cancellationToken = default);
+
+ /// Files one session envelope under one continuation id, replacing any envelope already there.
+ /// The continuation id: a conversation id or a response id.
+ /// The serialized session, as the agent wrote it.
+ /// Cancels the write.
+ ///
+ /// The continuation names a call whose words live in store 1, so the map lives in this store:
+ /// a resume must never find the key without the words.
+ ///
+ ValueTask SaveContinuationAsync(
+ string continuationId,
+ JsonElement envelope,
+ CancellationToken cancellationToken = default);
+
+ /// Reads the envelope one continuation id names.
+ /// The continuation id to look up.
+ /// Cancels the read.
+ /// The envelope, or when nothing is filed under that id.
+ ValueTask GetContinuationAsync(
+ string continuationId,
+ CancellationToken cancellationToken = default);
+
+ /// Withdraws whatever one continuation id names, if anything.
+ /// The continuation id to forget.
+ /// Cancels the delete.
+ ValueTask DeleteContinuationAsync(
+ string continuationId,
+ CancellationToken cancellationToken = default);
}
diff --git a/src/AgentCore.Application/Ports/IChatClientAdapter.cs b/src/AgentCore.Application/Ports/IChatClientAdapter.cs
index c2736509..21907ecd 100644
--- a/src/AgentCore.Application/Ports/IChatClientAdapter.cs
+++ b/src/AgentCore.Application/Ports/IChatClientAdapter.cs
@@ -18,8 +18,9 @@ ValueTask CreateClientAsync(
ISecretResolverPort? secrets,
CancellationToken cancellationToken = default);
- /// Whether this vendor runs a hosted web search for one entry.
+ /// Resolves a hosted tool marker for one entry, tuning it for this vendor.
+ /// The marker the document declared, such as a hosted search or code execution tool.
/// The providers.llm[] entry this adapter serves.
- /// when the vendor runs the search itself.
- bool SupportsHostedWebSearch(LlmProviderConfiguration entry) => false;
+ /// The tool to hand the model, or when this vendor does not run it.
+ AITool? ResolveHostedTool(AITool marker, LlmProviderConfiguration entry) => null;
}
diff --git a/src/AgentCore.Application/Ports/IChatClientFactory.cs b/src/AgentCore.Application/Ports/IChatClientFactory.cs
index abcc2603..f87dbf1e 100644
--- a/src/AgentCore.Application/Ports/IChatClientFactory.cs
+++ b/src/AgentCore.Application/Ports/IChatClientFactory.cs
@@ -16,8 +16,9 @@ public interface IChatClientFactory
/// The chat client. The compiler never disposes it.
IChatClient GetChatClient(ModelReference? model);
- /// Whether the vendor behind one model reference runs a hosted web search.
+ /// Resolves a hosted tool marker for one model reference.
+ /// The marker the document declared.
/// The reference, or for the factory's default entry.
- /// when the vendor runs the search itself.
- bool SupportsHostedWebSearch(ModelReference? model) => false;
+ /// The tool to hand the model, or when the vendor behind it does not run it.
+ AITool? ResolveHostedTool(AITool marker, ModelReference? model) => null;
}
diff --git a/src/AgentCore.Application/Ports/IConversationPort.cs b/src/AgentCore.Application/Ports/IConversationPort.cs
index 0cc76d21..8f6fbd09 100644
--- a/src/AgentCore.Application/Ports/IConversationPort.cs
+++ b/src/AgentCore.Application/Ports/IConversationPort.cs
@@ -1,4 +1,5 @@
using AgentCore.Domain;
+using AgentCore.Domain.Knowledge;
using Microsoft.Extensions.AI;
namespace AgentCore.Application.Ports;
@@ -6,30 +7,6 @@ namespace AgentCore.Application.Ports;
///
/// The inbound seam of one call: start or continue a turn, stream the reply, cancel it.
///
-///
-///
-/// Decision D4 puts one inbound port in front of the turn loop, and section 7 names it. Two adapters
-/// drive it. The Telnyx Conversation Relay shim drives it first, and the
-/// /v1/chat/completions SSE endpoint drives it second. Both read the same contract, so D8
-/// holds: the core never learns a vendor frame schema.
-///
-///
-/// The relay frames themselves stay in the adapter. RelayFrame and RelayToken of
-/// section 7.1 are a wire format, and nothing of that shape appears here. The shim reads a
-/// prompt frame and calls ; it reads an interrupt
-/// frame and calls ; it writes each update back as one RelayToken .
-///
-///
-/// Cancelling has two shapes, because the two adapters mean different things by it. The SSE endpoint
-/// cancels with the token when the client disconnects, and the turn simply stops. The relay cancels
-/// with when the caller speaks over the reply, and the turn ends with a
-/// record of what the caller heard. A token carries no record, so barge-in needs its own call.
-///
-///
-/// One port serves one call, and one call runs one turn at a time. A second turn started while one
-/// runs throws rather than corrupting the state of the call.
-///
-///
public interface IConversationPort
{
/// Gets the id of the call.
@@ -41,6 +18,10 @@ public interface IConversationPort
/// Gets whether the call reached a terminal stage. A document with no policy never does.
bool IsComplete { get; }
+ /// Gets or sets the knowledge scope the host opened for this call, or null for none.
+ /// Set it before the run: every turn composes its own scope from it. It outlives turns by construction — one call hears one customer.
+ KnowledgeScope? Scope { get; set; }
+
/// Gets the turn that finished last, or before the first turn ends.
TurnResult? LastTurn { get; }
@@ -53,6 +34,15 @@ public interface IConversationPort
///
Task RunTurnAsync(string userInput, CancellationToken cancellationToken = default);
+ /// Runs one turn end to end from a message the caller built, and returns what it did.
+ /// What the caller said or answered: words, an approval answer, or both.
+ /// Cancels the model calls.
+ /// The finished turn. Its reply is empty while approval requests are pending.
+ ///
+ /// The call already ended, or another turn of this call is still running.
+ ///
+ Task RunTurnMessageAsync(ChatMessage userInput, CancellationToken cancellationToken);
+
/// Runs one turn and streams the reply as it arrives.
/// What the caller said.
/// Cancels the model calls.
@@ -69,6 +59,17 @@ IAsyncEnumerable RunTurnStreamingAsync(
string userInput,
CancellationToken cancellationToken = default);
+ /// Runs one turn from a message the caller built and streams the reply as it arrives.
+ /// What the caller said or answered: words, an approval answer, or both.
+ /// Cancels the model calls.
+ /// The reply, one update at a time. Every update carries content.
+ ///
+ /// The call already ended, or another turn of this call is still running.
+ ///
+ IAsyncEnumerable RunTurnMessageStreamingAsync(
+ ChatMessage userInput,
+ CancellationToken cancellationToken);
+
/// Ends the running turn where the caller cut the reply off.
/// The text the caller actually heard.
/// How much of the reply played, as the relay reported it.
diff --git a/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs b/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs
index 10b3c043..ef8988c1 100644
--- a/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs
+++ b/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs
@@ -16,9 +16,11 @@ public interface IKnowledgeRetrievalPort
/// Finds the cards that answer one query.
/// What the caller asked, in their own words.
/// Cancels the search.
+ /// What the caller may see, or when the caller is unscoped.
/// The cards, best first. It is empty when nothing clears the score floor.
ValueTask> SearchAsync(
string query,
+ KnowledgeScope? scope = null,
CancellationToken cancellationToken = default);
/// Asks this store for a capability it may also serve.
diff --git a/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs b/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs
index 67ef2d4e..c66821f2 100644
--- a/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs
+++ b/src/AgentCore.Application/Ports/IKnowledgeStoreAdapter.cs
@@ -24,8 +24,8 @@ public interface IKnowledgeStoreAdapter : IVendorAdapter
///
///
/// Whether every agent reading this store declares scoped: true . The store is shared
- /// across every agent that reads it, so an adapter that fails closed with no ambient
- /// KnowledgeScope open is only correct when ALL of them want scoping -- one store cannot
+ /// across every agent that reads it, so an adapter that fails closed with no
+ /// KnowledgeScope passed is only correct when ALL of them want scoping -- one store cannot
/// enforce a scope for one agent while staying open for another. A mixed deployment passes
/// here, and the per-agent gate then lives in the caller instead of the
/// store.
diff --git a/src/AgentCore.Application/Ports/ISpeechAdapter.cs b/src/AgentCore.Application/Ports/ISpeechAdapter.cs
index facdc9bc..4e89e045 100644
--- a/src/AgentCore.Application/Ports/ISpeechAdapter.cs
+++ b/src/AgentCore.Application/Ports/ISpeechAdapter.cs
@@ -25,7 +25,7 @@ namespace AgentCore.Application.Ports;
///
/// So each role's kind is a naming field, not a selecting one: it answers "which
/// vendor did the document mean", and nothing here turns that answer into a constructed adapter.
-/// is what reads the names today, and only to check them
+/// is what reads the names today, and only to check them
/// against providers.call.kind — because a transport whose frames already carry text, such as
/// the relay this solution ships, is itself the recognizer and the synthesizer, so once the names
/// agree there is nothing left to build. stays the seam's
@@ -40,7 +40,7 @@ namespace AgentCore.Application.Ports;
/// frames already carry text must further be named by both speech roles, because such a
/// vendor performs recognition and synthesis itself and a document naming it for the pipe and
/// something else for the ears or the mouth describes a deployment that cannot exist.
-/// is what enforces that, while the host starts and before any
+/// is what enforces that, while the host starts and before any
/// route is mapped, because the agreement is a fact about the document rather than about a route.
///
///
diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt
index 62ff50a4..1aa679d1 100644
--- a/src/AgentCore.Application/PublicAPI.Unshipped.txt
+++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt
@@ -12,52 +12,25 @@ AgentCore.Application.Audit.QueuedAuditSink.DisposeAsync() -> System.Threading.T
AgentCore.Application.Audit.QueuedAuditSink.FlushAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask
AgentCore.Application.Audit.QueuedAuditSink.QueuedAuditSink(AgentCore.Application.Ports.IAuditSinkPort! inner, Microsoft.Extensions.Logging.ILogger? logger = null, int capacity = 10000, int batchSize = 100) -> void
AgentCore.Application.Audit.QueuedAuditSink.Store.get -> AgentCore.Application.Ports.IAuditSinkPort!
-AgentCore.Application.Call.CallChannel
-AgentCore.Application.Call.CallChannel.$() -> AgentCore.Application.Call.CallChannel!
-AgentCore.Application.Call.CallChannel.CallChannel(AgentCore.Application.Ports.ICallInputPort! Input, AgentCore.Application.Ports.ICallOutputPort! Output) -> void
-AgentCore.Application.Call.CallChannel.Deconstruct(out AgentCore.Application.Ports.ICallInputPort! Input, out AgentCore.Application.Ports.ICallOutputPort! Output) -> void
-AgentCore.Application.Call.CallChannel.DisposeAsync() -> System.Threading.Tasks.ValueTask
-AgentCore.Application.Call.CallChannel.Equals(AgentCore.Application.Call.CallChannel? other) -> bool
-AgentCore.Application.Call.CallChannel.Input.get -> AgentCore.Application.Ports.ICallInputPort!
-AgentCore.Application.Call.CallChannel.Input.init -> void
-AgentCore.Application.Call.CallChannel.Output.get -> AgentCore.Application.Ports.ICallOutputPort!
-AgentCore.Application.Call.CallChannel.Output.init -> void
-AgentCore.Application.Call.CallChannelContext
-AgentCore.Application.Call.CallChannelContext.$() -> AgentCore.Application.Call.CallChannelContext!
-AgentCore.Application.Call.CallChannelContext.CallChannelContext(string! CallId, System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void
-AgentCore.Application.Call.CallChannelContext.CallId.get -> string!
-AgentCore.Application.Call.CallChannelContext.CallId.init -> void
-AgentCore.Application.Call.CallChannelContext.CustomParameters.get -> System.Collections.Generic.IReadOnlyDictionary?
-AgentCore.Application.Call.CallChannelContext.CustomParameters.init -> void
-AgentCore.Application.Call.CallChannelContext.Deconstruct(out string! CallId, out System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void
-AgentCore.Application.Call.CallChannelContext.Equals(AgentCore.Application.Call.CallChannelContext? other) -> bool
-AgentCore.Application.Call.CallInput
-AgentCore.Application.Call.CallInput.Barge
-AgentCore.Application.Call.CallInput.Barge.Barge(string! HeardText, System.TimeSpan PlayedDuration) -> void
-AgentCore.Application.Call.CallInput.Barge.Deconstruct(out string! HeardText, out System.TimeSpan PlayedDuration) -> void
-AgentCore.Application.Call.CallInput.Barge.Equals(AgentCore.Application.Call.CallInput.Barge? other) -> bool
-AgentCore.Application.Call.CallInput.Barge.HeardText.get -> string!
-AgentCore.Application.Call.CallInput.Barge.HeardText.init -> void
-AgentCore.Application.Call.CallInput.Barge.PlayedDuration.get -> System.TimeSpan
-AgentCore.Application.Call.CallInput.Barge.PlayedDuration.init -> void
-AgentCore.Application.Call.CallInput.CallInput(AgentCore.Application.Call.CallInput! original) -> void
-AgentCore.Application.Call.CallInput.Keypress
-AgentCore.Application.Call.CallInput.Keypress.Deconstruct(out string! Key) -> void
-AgentCore.Application.Call.CallInput.Keypress.Equals(AgentCore.Application.Call.CallInput.Keypress? other) -> bool
-AgentCore.Application.Call.CallInput.Keypress.Key.get -> string!
-AgentCore.Application.Call.CallInput.Keypress.Key.init -> void
-AgentCore.Application.Call.CallInput.Keypress.Keypress(string! Key) -> void
-AgentCore.Application.Call.CallInput.Utterance
-AgentCore.Application.Call.CallInput.Utterance.Deconstruct(out string! Text, out string! Language, out bool IsFinal) -> void
-AgentCore.Application.Call.CallInput.Utterance.Equals(AgentCore.Application.Call.CallInput.Utterance? other) -> bool
-AgentCore.Application.Call.CallInput.Utterance.IsFinal.get -> bool
-AgentCore.Application.Call.CallInput.Utterance.IsFinal.init -> void
-AgentCore.Application.Call.CallInput.Utterance.Language.get -> string!
-AgentCore.Application.Call.CallInput.Utterance.Language.init -> void
-AgentCore.Application.Call.CallInput.Utterance.Text.get -> string!
-AgentCore.Application.Call.CallInput.Utterance.Text.init -> void
-AgentCore.Application.Call.CallInput.Utterance.Utterance(string! Text, string! Language, bool IsFinal) -> void
-AgentCore.Application.Call.CallSpeechPairing
+AgentCore.Application.Calls.CallChannel
+AgentCore.Application.Calls.CallChannel.$() -> AgentCore.Application.Calls.CallChannel!
+AgentCore.Application.Calls.CallChannel.CallChannel(AgentCore.Application.Ports.ICallInputPort! Input, AgentCore.Application.Ports.ICallOutputPort! Output) -> void
+AgentCore.Application.Calls.CallChannel.Deconstruct(out AgentCore.Application.Ports.ICallInputPort! Input, out AgentCore.Application.Ports.ICallOutputPort! Output) -> void
+AgentCore.Application.Calls.CallChannel.DisposeAsync() -> System.Threading.Tasks.ValueTask
+AgentCore.Application.Calls.CallChannel.Equals(AgentCore.Application.Calls.CallChannel? other) -> bool
+AgentCore.Application.Calls.CallChannel.Input.get -> AgentCore.Application.Ports.ICallInputPort!
+AgentCore.Application.Calls.CallChannel.Input.init -> void
+AgentCore.Application.Calls.CallChannel.Output.get -> AgentCore.Application.Ports.ICallOutputPort!
+AgentCore.Application.Calls.CallChannel.Output.init -> void
+AgentCore.Application.Calls.CallChannelContext
+AgentCore.Application.Calls.CallChannelContext.$() -> AgentCore.Application.Calls.CallChannelContext!
+AgentCore.Application.Calls.CallChannelContext.CallChannelContext(string! CallId, System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void
+AgentCore.Application.Calls.CallChannelContext.CallId.get -> string!
+AgentCore.Application.Calls.CallChannelContext.CallId.init -> void
+AgentCore.Application.Calls.CallChannelContext.CustomParameters.get -> System.Collections.Generic.IReadOnlyDictionary?
+AgentCore.Application.Calls.CallChannelContext.CustomParameters.init -> void
+AgentCore.Application.Calls.CallChannelContext.Deconstruct(out string! CallId, out System.Collections.Generic.IReadOnlyDictionary? CustomParameters) -> void
+AgentCore.Application.Calls.CallChannelContext.Equals(AgentCore.Application.Calls.CallChannelContext? other) -> bool
AgentCore.Application.Calls.CallClarificationState
AgentCore.Application.Calls.CallClarificationState.$() -> AgentCore.Application.Calls.CallClarificationState!
AgentCore.Application.Calls.CallClarificationState.CallClarificationState() -> void
@@ -65,6 +38,32 @@ AgentCore.Application.Calls.CallClarificationState.Equals(AgentCore.Application.
AgentCore.Application.Calls.CallClarificationState.ProbeAsks.get -> int
AgentCore.Application.Calls.CallClarificationState.ProbeAsks.init -> void
AgentCore.Application.Calls.CallCursor
+AgentCore.Application.Calls.CallInput
+AgentCore.Application.Calls.CallInput.Barge
+AgentCore.Application.Calls.CallInput.Barge.Barge(string! HeardText, System.TimeSpan PlayedDuration) -> void
+AgentCore.Application.Calls.CallInput.Barge.Deconstruct(out string! HeardText, out System.TimeSpan PlayedDuration) -> void
+AgentCore.Application.Calls.CallInput.Barge.Equals(AgentCore.Application.Calls.CallInput.Barge? other) -> bool
+AgentCore.Application.Calls.CallInput.Barge.HeardText.get -> string!
+AgentCore.Application.Calls.CallInput.Barge.HeardText.init -> void
+AgentCore.Application.Calls.CallInput.Barge.PlayedDuration.get -> System.TimeSpan
+AgentCore.Application.Calls.CallInput.Barge.PlayedDuration.init -> void
+AgentCore.Application.Calls.CallInput.CallInput(AgentCore.Application.Calls.CallInput! original) -> void
+AgentCore.Application.Calls.CallInput.Keypress
+AgentCore.Application.Calls.CallInput.Keypress.Deconstruct(out string! Key) -> void
+AgentCore.Application.Calls.CallInput.Keypress.Equals(AgentCore.Application.Calls.CallInput.Keypress? other) -> bool
+AgentCore.Application.Calls.CallInput.Keypress.Key.get -> string!
+AgentCore.Application.Calls.CallInput.Keypress.Key.init -> void
+AgentCore.Application.Calls.CallInput.Keypress.Keypress(string! Key) -> void
+AgentCore.Application.Calls.CallInput.Utterance
+AgentCore.Application.Calls.CallInput.Utterance.Deconstruct(out string! Text, out string! Language, out bool IsFinal) -> void
+AgentCore.Application.Calls.CallInput.Utterance.Equals(AgentCore.Application.Calls.CallInput.Utterance? other) -> bool
+AgentCore.Application.Calls.CallInput.Utterance.IsFinal.get -> bool
+AgentCore.Application.Calls.CallInput.Utterance.IsFinal.init -> void
+AgentCore.Application.Calls.CallInput.Utterance.Language.get -> string!
+AgentCore.Application.Calls.CallInput.Utterance.Language.init -> void
+AgentCore.Application.Calls.CallInput.Utterance.Text.get -> string!
+AgentCore.Application.Calls.CallInput.Utterance.Text.init -> void
+AgentCore.Application.Calls.CallInput.Utterance.Utterance(string! Text, string! Language, bool IsFinal) -> void
AgentCore.Application.Calls.CallPage
AgentCore.Application.Calls.CallPage.$() -> AgentCore.Application.Calls.CallPage!
AgentCore.Application.Calls.CallPage.CallPage(System.Collections.Generic.IReadOnlyList! Calls, string? NextCursor) -> void
@@ -78,17 +77,19 @@ AgentCore.Application.Calls.CallRecord
AgentCore.Application.Calls.CallRecord.$() -> AgentCore.Application.Calls.CallRecord!
AgentCore.Application.Calls.CallRecord.CallId.get -> string!
AgentCore.Application.Calls.CallRecord.CallId.init -> void
-AgentCore.Application.Calls.CallRecord.CallRecord(string! CallId, string? Title, AgentCore.Application.Calls.CallStatus Status, string? ExternalId, System.Text.Json.JsonElement? Custom, System.DateTimeOffset CreatedAt, System.DateTimeOffset? LastMessageAt, AgentCore.Application.Calls.CallSessionState? State = null) -> void
+AgentCore.Application.Calls.CallRecord.CallRecord(string! CallId, string? Title, AgentCore.Application.Calls.CallStatus Status, string? ExternalId, System.Text.Json.JsonElement? Custom, System.DateTimeOffset CreatedAt, System.DateTimeOffset? LastMessageAt, AgentCore.Application.Calls.CallSessionState? State = null, int NextOrdinal = 0) -> void
AgentCore.Application.Calls.CallRecord.CreatedAt.get -> System.DateTimeOffset
AgentCore.Application.Calls.CallRecord.CreatedAt.init -> void
AgentCore.Application.Calls.CallRecord.Custom.get -> System.Text.Json.JsonElement?
AgentCore.Application.Calls.CallRecord.Custom.init -> void
-AgentCore.Application.Calls.CallRecord.Deconstruct(out string! CallId, out string? Title, out AgentCore.Application.Calls.CallStatus Status, out string? ExternalId, out System.Text.Json.JsonElement? Custom, out System.DateTimeOffset CreatedAt, out System.DateTimeOffset? LastMessageAt, out AgentCore.Application.Calls.CallSessionState? State) -> void
+AgentCore.Application.Calls.CallRecord.Deconstruct(out string! CallId, out string? Title, out AgentCore.Application.Calls.CallStatus Status, out string? ExternalId, out System.Text.Json.JsonElement? Custom, out System.DateTimeOffset CreatedAt, out System.DateTimeOffset? LastMessageAt, out AgentCore.Application.Calls.CallSessionState? State, out int NextOrdinal) -> void
AgentCore.Application.Calls.CallRecord.Equals(AgentCore.Application.Calls.CallRecord? other) -> bool
AgentCore.Application.Calls.CallRecord.ExternalId.get -> string?
AgentCore.Application.Calls.CallRecord.ExternalId.init -> void
AgentCore.Application.Calls.CallRecord.LastMessageAt.get -> System.DateTimeOffset?
AgentCore.Application.Calls.CallRecord.LastMessageAt.init -> void
+AgentCore.Application.Calls.CallRecord.NextOrdinal.get -> int
+AgentCore.Application.Calls.CallRecord.NextOrdinal.init -> void
AgentCore.Application.Calls.CallRecord.State.get -> AgentCore.Application.Calls.CallSessionState?
AgentCore.Application.Calls.CallRecord.State.init -> void
AgentCore.Application.Calls.CallRecord.Status.get -> AgentCore.Application.Calls.CallStatus
@@ -103,16 +104,19 @@ AgentCore.Application.Calls.CallSessionState.Clarifications.init -> void
AgentCore.Application.Calls.CallSessionState.Equals(AgentCore.Application.Calls.CallSessionState? other) -> bool
AgentCore.Application.Calls.CallSessionState.IsComplete.get -> bool
AgentCore.Application.Calls.CallSessionState.IsComplete.init -> void
-AgentCore.Application.Calls.CallSessionState.NextOrdinal.get -> int
-AgentCore.Application.Calls.CallSessionState.NextOrdinal.init -> void
AgentCore.Application.Calls.CallSessionState.NextTurnIndex.get -> int
AgentCore.Application.Calls.CallSessionState.NextTurnIndex.init -> void
+AgentCore.Application.Calls.CallSessionState.Providers.get -> System.Collections.Generic.IReadOnlyDictionary!
+AgentCore.Application.Calls.CallSessionState.Providers.init -> void
AgentCore.Application.Calls.CallSessionState.Slots.get -> System.Collections.Generic.IReadOnlyDictionary!
AgentCore.Application.Calls.CallSessionState.Slots.init -> void
AgentCore.Application.Calls.CallSessionState.Stage.get -> string!
AgentCore.Application.Calls.CallSessionState.Stage.init -> void
AgentCore.Application.Calls.CallSessionState.Version.get -> int
AgentCore.Application.Calls.CallSessionState.Version.init -> void
+AgentCore.Application.Calls.CallSessionState.WorkflowState.get -> System.Text.Json.JsonElement?
+AgentCore.Application.Calls.CallSessionState.WorkflowState.init -> void
+AgentCore.Application.Calls.CallSpeechPairing
AgentCore.Application.Calls.CallStateJson
AgentCore.Application.Calls.CallStatus
AgentCore.Application.Calls.CallStatus.Archived = 1 -> AgentCore.Application.Calls.CallStatus
@@ -123,18 +127,21 @@ AgentCore.Application.Calls.ChatCallTitler.ChatCallTitler(AgentCore.Application.
AgentCore.Application.Calls.ChatCallTitler.GenerateAsync(string! callId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable!
AgentCore.Application.Calls.ChatCallTitler.GenerateFromAsync(string! callId, System.Collections.Generic.IReadOnlyList! messages, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable!
AgentCore.Application.Calls.Memory.InMemoryCallStore
-AgentCore.Application.Calls.Memory.InMemoryCallStore.AppendAsync(System.Collections.Generic.IReadOnlyList! messages, AgentCore.Application.Calls.CallSessionState? state = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask
+AgentCore.Application.Calls.Memory.InMemoryCallStore.AppendAsync(string! callId, System.Collections.Generic.IReadOnlyList