From b7e5964fc1ed920c2dea2fe7bf6ec815416783a4 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Fri, 20 Nov 2026 17:39:57 +0100 Subject: [PATCH 1/6] feat(router): agentdir, the one reader and writer of the agent directory format Parse reads a directory from the files a client sent: agent.yaml, instructions.md, guardrail.md, skills, knowledge, knowledge/urls.yaml, simulations and the UI files agent.yaml names. It decides which of the files are the directory, so every client's send of one folder reads and hashes the same. Unknown and retired keys and wrong types are refused, every problem at once, each with its file, line and column. Render writes a directory back as canonical files a sync reads again, and says what it could not write. The grammar and the ui: compiler are the Go SDK's, ported with its tests and the JavaScript SDK's refusals. --- .../internal/agentdir/a2ui/basic_catalog.json | 1375 +++++++++++++++++ .../internal/agentdir/a2ui/generate.sh | 45 + .../internal/agentdir/a2ui/main.swift | 20 + .../internal/agentdir/a2ui/protocol.md | 19 + .../internal/agentdir/a2ui/writing.md | 8 + acceleration/internal/agentdir/agentdir.go | 290 ++++ acceleration/internal/agentdir/content.go | 312 ++++ acceleration/internal/agentdir/parse_test.go | 639 ++++++++ acceleration/internal/agentdir/render.go | 390 +++++ acceleration/internal/agentdir/render_test.go | 356 +++++ acceleration/internal/agentdir/settings.go | 424 +++++ acceleration/internal/agentdir/ui.go | 712 +++++++++ acceleration/internal/agentdir/ui_a2ui.go | 574 +++++++ acceleration/internal/agentdir/ui_test.go | 383 +++++ acceleration/internal/agentdir/yaml.go | 285 ++++ 15 files changed, 5832 insertions(+) create mode 100644 acceleration/internal/agentdir/a2ui/basic_catalog.json create mode 100755 acceleration/internal/agentdir/a2ui/generate.sh create mode 100644 acceleration/internal/agentdir/a2ui/main.swift create mode 100644 acceleration/internal/agentdir/a2ui/protocol.md create mode 100644 acceleration/internal/agentdir/a2ui/writing.md create mode 100644 acceleration/internal/agentdir/agentdir.go create mode 100644 acceleration/internal/agentdir/content.go create mode 100644 acceleration/internal/agentdir/parse_test.go create mode 100644 acceleration/internal/agentdir/render.go create mode 100644 acceleration/internal/agentdir/render_test.go create mode 100644 acceleration/internal/agentdir/settings.go create mode 100644 acceleration/internal/agentdir/ui.go create mode 100644 acceleration/internal/agentdir/ui_a2ui.go create mode 100644 acceleration/internal/agentdir/ui_test.go create mode 100644 acceleration/internal/agentdir/yaml.go diff --git a/acceleration/internal/agentdir/a2ui/basic_catalog.json b/acceleration/internal/agentdir/a2ui/basic_catalog.json new file mode 100644 index 0000000000..4bc2575986 --- /dev/null +++ b/acceleration/internal/agentdir/a2ui/basic_catalog.json @@ -0,0 +1,1375 @@ +{ + "$defs" : { + "anyComponent" : { + "discriminator" : { + "propertyName" : "component" + }, + "oneOf" : [ + { + "$ref" : "#/components/AudioPlayer" + }, + { + "$ref" : "#/components/Button" + }, + { + "$ref" : "#/components/Card" + }, + { + "$ref" : "#/components/CheckBox" + }, + { + "$ref" : "#/components/ChoicePicker" + }, + { + "$ref" : "#/components/Column" + }, + { + "$ref" : "#/components/DateTimeInput" + }, + { + "$ref" : "#/components/Divider" + }, + { + "$ref" : "#/components/Icon" + }, + { + "$ref" : "#/components/Image" + }, + { + "$ref" : "#/components/List" + }, + { + "$ref" : "#/components/Modal" + }, + { + "$ref" : "#/components/Row" + }, + { + "$ref" : "#/components/Slider" + }, + { + "$ref" : "#/components/Tabs" + }, + { + "$ref" : "#/components/Text" + }, + { + "$ref" : "#/components/TextField" + }, + { + "$ref" : "#/components/Video" + } + ] + }, + "anyFunction" : { + "oneOf" : [ + { + "$ref" : "#/functions/and" + }, + { + "$ref" : "#/functions/email" + }, + { + "$ref" : "#/functions/formatCurrency" + }, + { + "$ref" : "#/functions/formatDate" + }, + { + "$ref" : "#/functions/formatNumber" + }, + { + "$ref" : "#/functions/formatString" + }, + { + "$ref" : "#/functions/length" + }, + { + "$ref" : "#/functions/not" + }, + { + "$ref" : "#/functions/numeric" + }, + { + "$ref" : "#/functions/openUrl" + }, + { + "$ref" : "#/functions/or" + }, + { + "$ref" : "#/functions/pluralize" + }, + { + "$ref" : "#/functions/regex" + }, + { + "$ref" : "#/functions/required" + } + ] + } + }, + "$id" : "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json", + "$schema" : "https://json-schema.org/draft/2020-12/schema", + "catalogId" : "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json", + "components" : { + "AudioPlayer" : { + "description" : "A player for audio content from a URL.", + "properties" : { + "component" : { + "const" : "AudioPlayer" + }, + "description" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "A description of the audio, such as a title or summary." + }, + "url" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The URL of the audio to be played." + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "url" + ], + "type" : "object" + }, + "Button" : { + "description" : "A clickable button that dispatches an action. Supports 'primary' and 'borderless' variants.", + "properties" : { + "action" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/Action" + }, + "checks" : { + "description" : "Checks that must pass for the button to be enabled.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/CheckRule" + }, + "type" : "array" + }, + "child" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ComponentId", + "description" : "The ID of the child component. Use a 'Text' component for a labeled button. Only use an 'Icon' if the requirements explicitly ask for an icon-only button." + }, + "component" : { + "const" : "Button" + }, + "variant" : { + "default" : "default", + "description" : "A hint for the button style. 'primary' indicates the main call to action; 'borderless' renders the child like a link.", + "enum" : [ + "default", + "primary", + "borderless" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "action", + "child", + "component" + ], + "type" : "object" + }, + "Card" : { + "description" : "A container with card-like styling.", + "properties" : { + "child" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ComponentId", + "description" : "The ID of the single child component to be rendered inside the card. To display multiple elements, wrap them in a layout component and pass that container's ID here." + }, + "component" : { + "const" : "Card" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "child", + "component" + ], + "type" : "object" + }, + "CheckBox" : { + "description" : "A checkbox with a label and a boolean value.", + "properties" : { + "checks" : { + "description" : "Checks that are evaluated whenever the value changes.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/CheckRule" + }, + "type" : "array" + }, + "component" : { + "const" : "CheckBox" + }, + "label" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The text to display next to the checkbox." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicBoolean", + "description" : "The current state of the checkbox (true for checked, false for unchecked)." + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "label", + "value" + ], + "type" : "object" + }, + "ChoicePicker" : { + "description" : "A component that allows selecting one or more options from a list.", + "properties" : { + "checks" : { + "description" : "Checks that are evaluated whenever the value changes.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/CheckRule" + }, + "type" : "array" + }, + "component" : { + "const" : "ChoicePicker" + }, + "displayStyle" : { + "default" : "checkbox", + "description" : "The display style of the component.", + "enum" : [ + "checkbox", + "chips" + ], + "type" : "string" + }, + "filterable" : { + "default" : false, + "description" : "If true, displays a search input to filter the options.", + "type" : "boolean" + }, + "label" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The label for the group of options." + }, + "options" : { + "description" : "The list of available options to choose from.", + "items" : { + "additionalProperties" : false, + "properties" : { + "label" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The text to display for this option." + }, + "value" : { + "description" : "The stable value associated with this option.", + "type" : "string" + } + }, + "required" : [ + "label", + "value" + ], + "type" : "object" + }, + "type" : "array" + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicStringList", + "description" : "The list of currently selected values. Bind this to a string array in the data model." + }, + "variant" : { + "default" : "mutuallyExclusive", + "description" : "A hint for how the choice picker should be displayed and behave.", + "enum" : [ + "multipleSelection", + "mutuallyExclusive" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "options", + "value" + ], + "type" : "object" + }, + "Column" : { + "description" : "A layout component that arranges its children vertically. To create a grid layout, nest Rows within this Column.", + "properties" : { + "align" : { + "default" : "stretch", + "description" : "Defines the alignment of children along the cross axis (horizontally).", + "enum" : [ + "start", + "center", + "end", + "stretch" + ], + "type" : "string" + }, + "children" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ChildList", + "description" : "Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID." + }, + "component" : { + "const" : "Column" + }, + "justify" : { + "default" : "start", + "description" : "Defines the arrangement of children along the main axis (vertically).", + "enum" : [ + "center", + "end", + "spaceAround", + "spaceBetween", + "spaceEvenly", + "start", + "stretch" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "children", + "component" + ], + "type" : "object" + }, + "DateTimeInput" : { + "description" : "An input for date and/or time.", + "properties" : { + "checks" : { + "description" : "Checks that are evaluated whenever the value changes.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/CheckRule" + }, + "type" : "array" + }, + "component" : { + "const" : "DateTimeInput" + }, + "enableDate" : { + "default" : false, + "description" : "If true, allows the user to select a date.", + "type" : "boolean" + }, + "enableTime" : { + "default" : false, + "description" : "If true, allows the user to select a time.", + "type" : "boolean" + }, + "label" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The text label for the input field." + }, + "max" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The maximum allowed date/time in ISO 8601 format." + }, + "min" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The minimum allowed date/time in ISO 8601 format." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The selected date and/or time value in ISO 8601 format. If not yet set, initialize with an empty string." + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "value" + ], + "type" : "object" + }, + "Divider" : { + "description" : "A horizontal or vertical dividing line.", + "properties" : { + "axis" : { + "default" : "horizontal", + "description" : "The orientation of the divider.", + "enum" : [ + "horizontal", + "vertical" + ], + "type" : "string" + }, + "component" : { + "const" : "Divider" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component" + ], + "type" : "object" + }, + "Icon" : { + "description" : "Displays a system-provided icon from a predefined list.", + "properties" : { + "component" : { + "const" : "Icon" + }, + "name" : { + "description" : "The name of the icon to display.", + "oneOf" : [ + { + "enum" : [ + "accountCircle", + "add", + "arrowBack", + "arrowForward", + "attachFile", + "calendarToday", + "call", + "camera", + "check", + "close", + "delete", + "download", + "edit", + "error", + "event", + "fastForward", + "favorite", + "favoriteOff", + "folder", + "help", + "home", + "info", + "locationOn", + "lock", + "lockOpen", + "mail", + "menu", + "moreHoriz", + "moreVert", + "notifications", + "notificationsOff", + "pause", + "payment", + "person", + "phone", + "photo", + "play", + "print", + "refresh", + "rewind", + "search", + "send", + "settings", + "share", + "shoppingCart", + "skipNext", + "skipPrevious", + "star", + "starHalf", + "starOff", + "stop", + "upload", + "visibility", + "visibilityOff", + "volumeDown", + "volumeMute", + "volumeOff", + "volumeUp", + "warning" + ], + "type" : "string" + }, + { + "additionalProperties" : false, + "properties" : { + "svgPath" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString" + } + }, + "required" : [ + "svgPath" + ], + "type" : "object" + }, + { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DataBinding" + } + ] + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "name" + ], + "type" : "object" + }, + "Image" : { + "description" : "Displays an image from a URL.", + "properties" : { + "component" : { + "const" : "Image" + }, + "description" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "Accessibility text for the image." + }, + "fit" : { + "default" : "fill", + "description" : "Specifies how the image should be resized to fit its container.", + "enum" : [ + "contain", + "cover", + "fill", + "none", + "scaleDown" + ], + "type" : "string" + }, + "url" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The URL of the image to display." + }, + "variant" : { + "default" : "mediumFeature", + "description" : "A hint for the image size and style.", + "enum" : [ + "icon", + "avatar", + "smallFeature", + "mediumFeature", + "largeFeature", + "header" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "url" + ], + "type" : "object" + }, + "List" : { + "description" : "A list of components. Vertical lists grow with their content; horizontal lists scroll.", + "properties" : { + "align" : { + "default" : "stretch", + "description" : "Defines the alignment of children along the cross axis.", + "enum" : [ + "start", + "center", + "end", + "stretch" + ], + "type" : "string" + }, + "children" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ChildList", + "description" : "Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list." + }, + "component" : { + "const" : "List" + }, + "direction" : { + "default" : "vertical", + "description" : "The direction in which the list items are laid out.", + "enum" : [ + "vertical", + "horizontal" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "children", + "component" + ], + "type" : "object" + }, + "Modal" : { + "description" : "A dialog that appears over the main content, triggered by a component in the main content.", + "properties" : { + "component" : { + "const" : "Modal" + }, + "content" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ComponentId", + "description" : "The ID of the component to be displayed inside the modal." + }, + "trigger" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ComponentId", + "description" : "The ID of the component that opens the modal when interacted with (e.g., a button)." + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "content", + "trigger" + ], + "type" : "object" + }, + "Row" : { + "description" : "A layout component that arranges its children horizontally. To create a grid layout, nest Columns within this Row.", + "properties" : { + "align" : { + "default" : "stretch", + "description" : "Defines the alignment of children along the cross axis (vertically).", + "enum" : [ + "start", + "center", + "end", + "stretch" + ], + "type" : "string" + }, + "children" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ChildList", + "description" : "Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID." + }, + "component" : { + "const" : "Row" + }, + "justify" : { + "default" : "start", + "description" : "Defines the arrangement of children along the main axis (horizontally).", + "enum" : [ + "center", + "end", + "spaceAround", + "spaceBetween", + "spaceEvenly", + "start", + "stretch" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "children", + "component" + ], + "type" : "object" + }, + "Slider" : { + "description" : "A slider for selecting a numeric value within a range.", + "properties" : { + "checks" : { + "description" : "Checks that are evaluated whenever the value changes.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/CheckRule" + }, + "type" : "array" + }, + "component" : { + "const" : "Slider" + }, + "label" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The label for the slider." + }, + "max" : { + "description" : "The maximum value of the slider.", + "type" : "number" + }, + "min" : { + "default" : 0, + "description" : "The minimum value of the slider.", + "type" : "number" + }, + "steps" : { + "description" : "The number of discrete divisions in the slider range.", + "minimum" : 1, + "type" : "integer" + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber", + "description" : "The current value of the slider." + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "max", + "value" + ], + "type" : "object" + }, + "Tabs" : { + "description" : "A set of tabs, each with a title and child component.", + "properties" : { + "component" : { + "const" : "Tabs" + }, + "tabs" : { + "description" : "An array of objects, where each object defines a tab with a title and a child component.", + "items" : { + "additionalProperties" : false, + "properties" : { + "child" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/ComponentId", + "description" : "The ID of the child component." + }, + "title" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The tab title." + } + }, + "required" : [ + "child", + "title" + ], + "type" : "object" + }, + "minItems" : 1, + "type" : "array" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "tabs" + ], + "type" : "object" + }, + "Text" : { + "description" : "Displays text. Simple Markdown formatting is supported.", + "properties" : { + "component" : { + "const" : "Text" + }, + "text" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The text content to display. While simple Markdown formatting is supported (i.e. without HTML, images, or links), utilizing dedicated UI components is generally preferred for a richer and more structured presentation." + }, + "variant" : { + "default" : "body", + "description" : "A hint for the base text style.", + "enum" : [ + "caption", + "body" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "text" + ], + "type" : "object" + }, + "TextField" : { + "description" : "A field for user text input.", + "properties" : { + "checks" : { + "description" : "Checks that are evaluated whenever the value changes.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/CheckRule" + }, + "type" : "array" + }, + "component" : { + "const" : "TextField" + }, + "label" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The text label for the input field." + }, + "placeholder" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The placeholder text for the input field." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The value of the text field." + }, + "variant" : { + "default" : "shortText", + "description" : "The type of input field to display.", + "enum" : [ + "longText", + "number", + "shortText", + "obscured" + ], + "type" : "string" + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "label" + ], + "type" : "object" + }, + "Video" : { + "description" : "Displays a video from a URL.", + "properties" : { + "component" : { + "const" : "Video" + }, + "posterUrl" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The URL of the poster image to display before the video plays." + }, + "url" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The URL of the video to display." + }, + "weight" : { + "description" : "The relative weight of this component within a Row or Column, similar to the CSS 'flex-grow' property. This may ONLY be set when the component is a direct descendant of a Row or Column.", + "type" : "number" + } + }, + "required" : [ + "component", + "url" + ], + "type" : "object" + } + }, + "description" : "Unified catalog of basic A2UI components and functions.", + "functions" : { + "and" : { + "allowedCallers" : "rendererOnly", + "description" : "Performs a logical AND operation on a list of boolean values.", + "properties" : { + "@call" : { + "const" : "and" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "values" : { + "description" : "The list of boolean values to evaluate.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicBoolean" + }, + "minItems" : 2, + "type" : "array" + } + }, + "required" : [ + "values" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "boolean", + "type" : "object" + }, + "email" : { + "allowedCallers" : "rendererOnly", + "description" : "Checks that the value is a valid email address.", + "properties" : { + "@call" : { + "const" : "email" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString" + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "validationResult", + "type" : "object" + }, + "formatCurrency" : { + "allowedCallers" : "rendererOnly", + "description" : "Formats a number as a currency string.", + "properties" : { + "@call" : { + "const" : "formatCurrency" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "currency" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The ISO 4217 currency code (e.g., 'USD', 'EUR')." + }, + "decimals" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber", + "description" : "Optional. The number of decimal places to show." + }, + "grouping" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicBoolean", + "description" : "Optional. If true, uses locale-specific grouping separators. Defaults to true." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber", + "description" : "The monetary amount." + } + }, + "required" : [ + "currency", + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "string", + "type" : "object" + }, + "formatDate" : { + "allowedCallers" : "rendererOnly", + "description" : "Formats a timestamp into a string using a Unicode TR35 date pattern.", + "properties" : { + "@call" : { + "const" : "formatDate" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "format" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "A Unicode TR35 date pattern string, e.g. 'MMM dd, yyyy'." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicValue", + "description" : "The date to format." + } + }, + "required" : [ + "format", + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "string", + "type" : "object" + }, + "formatNumber" : { + "allowedCallers" : "rendererOnly", + "description" : "Formats a number with the specified grouping and decimal precision.", + "properties" : { + "@call" : { + "const" : "formatNumber" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "decimals" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber", + "description" : "Optional. The number of decimal places to show." + }, + "grouping" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicBoolean", + "description" : "Optional. If true, uses locale-specific grouping separators. Defaults to true." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber", + "description" : "The number to format." + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "string", + "type" : "object" + }, + "formatString" : { + "allowedCallers" : "rendererOnly", + "description" : "Performs string interpolation of data model values and other functions in the catalog functions list and returns the resulting string. The value string can contain interpolated expressions in the `${expression}` format. Supported expression types include: JSON Pointer paths to the data model (e.g., `${/absolute/path}` or `${relative/path}`), and renderer-side function calls (e.g., `${now()}`). Function arguments must be named (e.g., `${formatDate(value:${/currentDate}, format:'MM-dd')}`). To include a literal `${` sequence, escape it as `\\${`.", + "properties" : { + "@call" : { + "const" : "formatString" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString" + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "string", + "type" : "object" + }, + "length" : { + "allowedCallers" : "rendererOnly", + "description" : "Checks string length constraints.", + "properties" : { + "@call" : { + "const" : "length" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "max" : { + "description" : "The maximum allowed length.", + "minimum" : 0, + "type" : "integer" + }, + "min" : { + "description" : "The minimum allowed length.", + "minimum" : 0, + "type" : "integer" + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString" + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "validationResult", + "type" : "object" + }, + "not" : { + "allowedCallers" : "rendererOnly", + "description" : "Performs a logical NOT operation on a boolean value.", + "properties" : { + "@call" : { + "const" : "not" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicBoolean", + "description" : "The boolean value to negate." + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "boolean", + "type" : "object" + }, + "numeric" : { + "allowedCallers" : "rendererOnly", + "description" : "Checks numeric range constraints.", + "properties" : { + "@call" : { + "const" : "numeric" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "max" : { + "description" : "The maximum allowed value.", + "type" : "number" + }, + "min" : { + "description" : "The minimum allowed value.", + "type" : "number" + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber" + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "validationResult", + "type" : "object" + }, + "openUrl" : { + "allowedCallers" : "rendererOnly", + "description" : "Opens the specified URL in a browser or handler (requires user activation). This function has no return value.", + "properties" : { + "@call" : { + "const" : "openUrl" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "url" : { + "description" : "The URL to open.", + "oneOf" : [ + { + "format" : "uri", + "type" : "string" + }, + { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DataBinding" + }, + { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/FunctionCall" + } + ] + } + }, + "required" : [ + "url" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "requiresUserActivation" : true, + "returnType" : "void", + "type" : "object" + }, + "or" : { + "allowedCallers" : "rendererOnly", + "description" : "Performs a logical OR operation on a list of boolean values.", + "properties" : { + "@call" : { + "const" : "or" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "values" : { + "description" : "The list of boolean values to evaluate.", + "items" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicBoolean" + }, + "minItems" : 2, + "type" : "array" + } + }, + "required" : [ + "values" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "boolean", + "type" : "object" + }, + "pluralize" : { + "allowedCallers" : "rendererOnly", + "description" : "Returns a localized string based on the Common Locale Data Repository (CLDR) plural category of the count (zero, one, two, few, many, other). Requires an 'other' fallback. For English, just use 'one' and 'other'.", + "properties" : { + "@call" : { + "const" : "pluralize" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "few" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "String for the 'few' category." + }, + "many" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "String for the 'many' category." + }, + "one" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "String for the 'one' category." + }, + "other" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "The default/fallback string." + }, + "two" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "String for the 'two' category." + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicNumber", + "description" : "The numeric value used to determine the plural category." + }, + "zero" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString", + "description" : "String for the 'zero' category." + } + }, + "required" : [ + "other", + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "string", + "type" : "object" + }, + "regex" : { + "allowedCallers" : "rendererOnly", + "description" : "Checks that the value matches a regular expression string.", + "properties" : { + "@call" : { + "const" : "regex" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "pattern" : { + "description" : "The regex pattern to match against.", + "type" : "string" + }, + "value" : { + "$ref" : "https://a2ui.org/specification/v1_0/common_types.json#/$defs/DynamicString" + } + }, + "required" : [ + "pattern", + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "validationResult", + "type" : "object" + }, + "required" : { + "allowedCallers" : "rendererOnly", + "description" : "Checks that the value is not null, undefined, or empty.", + "properties" : { + "@call" : { + "const" : "required" + }, + "args" : { + "additionalProperties" : false, + "properties" : { + "value" : { + "description" : "The value to check." + } + }, + "required" : [ + "value" + ], + "type" : "object" + } + }, + "required" : [ + "@call", + "args" + ], + "returnType" : "validationResult", + "type" : "object" + } + }, + "instructions" : "For layout, use the Row and Column components to organize other components.\n\n## Catalog Guidelines\n\n1. String Concatenation & Formatting: A2UI does not support binary operators like '+' or formatting symbols. To concatenate strings or dynamically inject data bindings into text, you must use the catalog function `formatString(value)` where the value string contains placeholders formatted as `${expression}`:\n formatString(\"Hello ${/user/name}\")\n\n2. Strict Hierarchy: You must strictly adhere to the requested component nesting and hierarchy. If the prompt specifies that a component is 'inside' or 'contained in' another component, you MUST place it as a child of that specific component, not as a sibling or in a different container.\n\n3. Validation Checks: When components support validation checks, specify any custom error messages directly as the 'message' inside the check. Do NOT create separate text-display components to display validation errors.\n\n4. Text Hierarchy: The Text component only offers the 'body' and 'caption' variants. Use Markdown headings ('#' to '####') inside the text for visual hierarchy.\n\n5. Component Ids: Every surface must contain exactly one component with the id 'root'. Children are always referenced by id; components are never nested inline.", + "protocolVersion" : "1.0", + "title" : "A2UI Basic Catalog" +} diff --git a/acceleration/internal/agentdir/a2ui/generate.sh b/acceleration/internal/agentdir/a2ui/generate.sh new file mode 100755 index 0000000000..0917645abb --- /dev/null +++ b/acceleration/internal/agentdir/a2ui/generate.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Writes basic_catalog.json and protocol.md, the A2UI basic catalog and protocol the router compiles +# `ui:` with when its format is a2ui, from the A2UI renderer of stream-chat-swift, so the agent is +# told what the apps render: +# +# acceleration/internal/agentdir/a2ui/generate.sh [stream-chat-swift checkout] +# +# The checkout defaults to one beside this repository. Only StreamChatA2UI's own code is built, for +# this Mac, into the same module as main.swift, as the catalog's serializer and the prompt aren't +# public. +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +sdk="$(cd "${1:-$here/../../../../../stream-chat-swift}" && pwd)" +if [[ ! -d "$sdk/Sources/StreamChatA2UI" ]]; then + echo "$sdk has no Sources/StreamChatA2UI: check out its develop branch, or a release with it." >&2 + exit 1 +fi + +package="${TMPDIR:-/tmp}/go-sdk-a2ui-catalog" +mkdir -p "$package/Sources/a2ui-catalog" +ln -sfn "$here/main.swift" "$package/Sources/a2ui-catalog/main.swift" +ln -sfn "$sdk/Sources/StreamChatA2UI" "$package/Sources/a2ui-catalog/StreamChatA2UI" +cat > "$package/Package.swift" <<'SWIFT' +// swift-tools-version:6.0 +import PackageDescription + +let package = Package( + name: "GoSDKA2UICatalog", + defaultLocalization: "en", + platforms: [.macOS(.v14)], + targets: [ + .executableTarget(name: "a2ui-catalog", exclude: ["StreamChatA2UI/AIUI", "StreamChatA2UI/Info.plist"]) + ] +) +SWIFT + +swift build --package-path "$package" -c release >&2 +bin="$(swift build --package-path "$package" -c release --show-bin-path)" +# Each file is replaced only once it is written, so a failed run keeps the old one. +"$bin/a2ui-catalog" > "$here/basic_catalog.json.new" +"$bin/a2ui-catalog" protocol > "$here/protocol.md.new" +mv "$here/basic_catalog.json.new" "$here/basic_catalog.json" +mv "$here/protocol.md.new" "$here/protocol.md" +echo "from stream-chat-swift $(git -C "$sdk" rev-parse --short HEAD)" >&2 diff --git a/acceleration/internal/agentdir/a2ui/main.swift b/acceleration/internal/agentdir/a2ui/main.swift new file mode 100644 index 0000000000..8a6d597a73 --- /dev/null +++ b/acceleration/internal/agentdir/a2ui/main.swift @@ -0,0 +1,20 @@ +import Foundation + +// Built into one module with StreamChatA2UI's code, whose catalog serializer and prompt aren't +// public. `generate.sh` runs it: +// +// a2ui-catalog the basic catalog as the renderer serializes it, its guidelines in +// `instructions` +// a2ui-catalog protocol what the renderer tells a model about A2UI's messages +// +// The Go SDK compiles agent.yaml's `ui:` with both when its format is a2ui. + +if CommandLine.arguments.dropFirst().first == "protocol" { + print(A2UIPromptBuilder.protocolOverview) + exit(0) +} +let schema = BasicCatalog.catalog.toJsonSchema() +let options: JSONSerialization.WritingOptions = [.sortedKeys, .withoutEscapingSlashes, .prettyPrinted] +let data = try JSONSerialization.data(withJSONObject: schema, options: options) +FileHandle.standardOutput.write(data) +FileHandle.standardOutput.write(Data("\n".utf8)) diff --git a/acceleration/internal/agentdir/a2ui/protocol.md b/acceleration/internal/agentdir/a2ui/protocol.md new file mode 100644 index 0000000000..613df96ebf --- /dev/null +++ b/acceleration/internal/agentdir/a2ui/protocol.md @@ -0,0 +1,19 @@ +# Generating user interfaces with A2UI v1.0 + +You render user interfaces by emitting A2UI messages. Every message is a JSON object with a `"version": "1.0"` field plus exactly one of these keys: + +- `createSurface`: creates a surface. Requires `surfaceId`, and accepts `catalogId`, `sendDataModel`, `components` and `dataModel` so a complete UI can be sent in one message. +- `updateComponents`: adds or replaces components of an existing surface. Requires `surfaceId` and `components`. +- `updateDataModel`: writes to the surface data model. Requires `surfaceId` and `value`, and accepts a JSON Pointer `path`. Setting `value` to `null` deletes the entry at `path`. +- `deleteSurface`: removes a surface. Requires `surfaceId`. +- `callRendererFunction`: asks the renderer to run one of its functions. +- `agentFunctionResponse`: answers a `callAgentFunction` request from the renderer. + +Rules: + +1. Components are a flat adjacency list. Each component has a unique `id`, a `component` type, and its properties inline. Exactly one component must have the id `root`. An id is an identifier: letters, digits and underscores, not starting with a digit, such as `saturday_plan` (never `saturday-plan`). +2. Children are referenced by id, never nested inline. Use an array of ids, or `{"componentId": "...", "path": "/items"}` to repeat a template for every item of a data model list. +3. Any property may be a literal, a data binding `{"@path": "/a/b"}` or a function call `{"@call": "name", "args": {...}}`. Inside a list template, paths without a leading slash resolve relative to the current item, and `{"@call": "@index"}` returns the item's position. A literal object key that starts with `@` is written with `@@`, so `"@@type"` means `"@type"`. +4. Put content that changes in the data model and bind to it, so you can update values with `updateDataModel` instead of resending components. +5. Interactive components declare an `action`, which either dispatches an event to you (`{"event": {"name": "...", "context": {...}}}`) or runs a renderer function (`{"functionCall": {"@call": "openUrl", "args": {"url": "..."}}}`). +6. Surface ids must be unique for the lifetime of the renderer. Creating a surface that already exists is an error: delete it first, or send `updateComponents` and `updateDataModel` to change it. diff --git a/acceleration/internal/agentdir/a2ui/writing.md b/acceleration/internal/agentdir/a2ui/writing.md new file mode 100644 index 0000000000..e4fcf1d4ed --- /dev/null +++ b/acceleration/internal/agentdir/a2ui/writing.md @@ -0,0 +1,8 @@ +### Writing UI in A2UI + +Write a reply's UI in one fenced block whose info string is `ui:a2ui@1.0`, after one short sentence saying what it shows, which is what people read wherever the UI can't show. In the block, write A2UI messages, one JSON object per line, and nothing else: + +1. First a `createSurface` with a `surfaceId` new to this reply, the `catalogId` `getstream.io:app-catalog`, and the `dataModel` the UI's inputs start from. +2. Then `updateComponents` messages for that surface with a few components each, `root` first, so the UI shows as you write it. + +A reply's UI is shown as you wrote it: never write `callRendererFunction` or `agentFunctionResponse`, and never change an earlier reply's UI, but write a new one. What the person does in it comes back as their next message, which says what the button they tapped says. Give every event action a `userMessage` saying what it asks of you, such as "Update the plan", which comes back with it, and a `context` with what you need to know, bound to the data model. diff --git a/acceleration/internal/agentdir/agentdir.go b/acceleration/internal/agentdir/agentdir.go new file mode 100644 index 0000000000..3699bd98b7 --- /dev/null +++ b/acceleration/internal/agentdir/agentdir.go @@ -0,0 +1,290 @@ +// Package agentdir is the agent directory format: what agent.yaml and the files beside it +// say, read from raw files and written back as them. +// +// agent.yaml +// instructions.md +// guardrail.md +// skills/think.md +// skills/pdf/SKILL.md +// skills/pdf/scripts/fill.py +// knowledge/pricing.md +// knowledge/urls.yaml +// simulations/lunch.yaml +// ui/components.json +// ui/blueprints.yaml +// +// It is the one reader and the one writer of the format: every client sends the files as +// they are, and Parse decides what they mean. +package agentdir + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "maps" + "path" + "slices" + "strings" + "time" + "unicode/utf8" +) + +// What an agent directory calls its files. +const ( + AgentFile = "agent.yaml" + InstructionsFile = "instructions.md" + GuardrailFile = "guardrail.md" + SkillFile = "SKILL.md" + SkillsDir = "skills" + KnowledgeDir = "knowledge" + KnowledgeURLsFile = KnowledgeDir + "/urls.yaml" + SimulationsDir = "simulations" + UIComponentsFile = "ui/components.json" + UIBlueprintsFile = "ui/blueprints.yaml" +) + +// What one directory may hold. +const ( + // MaxBytes is all its files together: what one knowledge ingest takes (api.MaxKnowledgeBody), + // since the knowledge is most of a directory. + MaxBytes = 8 << 20 + // MaxFileBytes is one file: what all of one skill's files may hold (api.maxSkillBytes). + MaxFileBytes = 1 << 20 + // MaxFiles is how many files a client may send: sixteen skills at the 64 files a skill may + // bring. The API holds a request to it. + MaxFiles = 1024 + // maxUIFileBytes is a UI catalog or its blueprints, which the model reads on every turn. + maxUIFileBytes = 512 << 10 +) + +// File is one file of an agent directory. +type File struct { + // Path is relative to the directory, with forward slashes. + Path string + Content string +} + +// Problem is one thing wrong with a directory, at its place in a file. +type Problem struct { + File string + // Line and Column count from 1. Both are zero when the problem is the file as a whole. + Line int + Column int + Message string +} + +func (p Problem) String() string { + if p.Line == 0 { + return p.File + ": " + p.Message + } + return fmt.Sprintf("%s:%d:%d: %s", p.File, p.Line, p.Column, p.Message) +} + +// Problems is everything wrong with a directory, in the order it was found. +type Problems []Problem + +func (p Problems) Error() string { + texts := make([]string, len(p)) + for i, problem := range p { + texts[i] = problem.String() + } + return strings.Join(texts, "; ") +} + +// Directory is what an agent directory says. +type Directory struct { + Settings Settings + Instructions string + // Guardrail is guardrail.md, whole: the router's guardrail package reads it. + Guardrail string + // UI is agent.yaml's ui key with the files it names, or nil without one. + UI *UI + Skills []Skill + // Knowledge are the readable files under knowledge/, in path order. + Knowledge []Document + KnowledgeURLs []KnowledgeURL + // Simulations is nil when the directory has no simulations/*.yaml, which leaves the stored + // ones alone, and empty when its files declare none, which deletes them. + Simulations []Simulation + // Files are the files the directory was read from, in path order: what its hash is of. + Files []File + // Ignored are the files sent that are no part of the format, by path. + Ignored []string + + declaration *reader +} + +// Skill is a skill file, or a skill folder's SKILL.md with the files beside it. +type Skill struct { + Name string + Description string + Instructions string + Deadline time.Duration + CaptureVideo bool + // Files are the rest of a skill folder, by path relative to it. + Files map[string]string +} + +// Document is one file of knowledge/, by its path relative to it. +type Document struct { + Source string + Text string +} + +// KnowledgeURL is one page of knowledge/urls.yaml. +type KnowledgeURL struct { + URL string + Title string + Description string + RefreshHours int +} + +// Simulation is one conversation a simulations/*.yaml file declares. +type Simulation struct { + Name string + Scenario string + Assertion string + Mode string + Variations int + MaxTurns int + CallerTarget string + JudgeTarget string + CallerSTT string + CallerTTS string + CallerVoice string + Tags map[string]string +} + +// knowledgeExtensions are what a knowledge directory is read from: a model looks things up in +// prose, not in a binary. +var knowledgeExtensions = []string{".md", ".mdx", ".txt", ".rst", ".yaml", ".yml"} + +// UIVersion is the version of what the ui: compiler writes. It is part of the hash of a +// directory that has a ui key, so a directory is synced again, and its UI instructions +// compiled again, by a router whose compiler writes something else: add one to it with any +// change to what compileUIPrompt or the A2UI catalog produces. +const UIVersion = "1" + +// Hash is the fingerprint of files and of whatever is synced beside them: the SHA-256, in +// hex, of every part in turn as its length in bytes in decimal, a colon and the part. The +// parts are each file's path and then its content, in path order by byte, and then each of +// beside. The length is what keeps one part from running into the next. +func Hash(files []File, beside ...string) string { + sorted := slices.SortedFunc(slices.Values(files), func(a, b File) int { return strings.Compare(a.Path, b.Path) }) + hasher := sha256.New() + part := func(text string) { fmt.Fprintf(hasher, "%d:%s", len(text), text) } + for _, file := range sorted { + part(file.Path) + part(file.Content) + } + for _, more := range beside { + part(more) + } + return hex.EncodeToString(hasher.Sum(nil)) +} + +// Parse reads a directory from the files a client sent. Everything wrong with it is reported +// at once, as Problems, and the directory is returned beside them whenever there is an +// agent.yaml to read, so a caller can go on to say what else is wrong with it. +// +// A client sends what it finds and Parse decides what is the directory: a hidden file is +// skipped, a file that is no part of the format is left out and listed in Ignored, and the +// limits and the hash are of the files that are left. +func Parse(files []File) (*Directory, error) { + var problems Problems + fail := func(file, format string, args ...any) { + problems = append(problems, Problem{File: file, Message: fmt.Sprintf(format, args...)}) + } + + held := map[string]string{} + for _, file := range files { + switch _, twice := held[file.Path]; { + case !ValidPath(file.Path): + fail(file.Path, "is not a path inside the directory: use forward slashes, and no .. or leading /") + case hidden(file.Path): + case twice: + fail(file.Path, "is sent twice") + default: + held[file.Path] = file.Content + } + } + declaration, declared := held[AgentFile] + if !declared { + return nil, append(problems, Problem{File: AgentFile, Message: "is missing, and it is what makes a directory an agent"}) + } + + used := map[string]bool{} + text := func(file string) (string, bool) { + content, ok := held[file] + if !ok { + return "", false + } + if !used[file] && len(content) > MaxFileBytes { + fail(file, "holds %d bytes, and a file holds at most %d", len(content), MaxFileBytes) + } + used[file] = true + if !utf8.ValidString(content) { + fail(file, "is not text") + return "", false + } + return content, true + } + paths := slices.Sorted(maps.Keys(held)) + + directory := &Directory{declaration: &reader{file: AgentFile, problems: &problems}} + text(AgentFile) + directory.Settings = directory.declaration.settings(declaration) + instructions, _ := text(InstructionsFile) + guardrail, _ := text(GuardrailFile) + directory.Instructions, directory.Guardrail = strings.TrimSpace(instructions), strings.TrimSpace(guardrail) + directory.Skills = readSkills(paths, text, &problems) + directory.Knowledge = readKnowledge(paths, text) + if pages, ok := text(KnowledgeURLsFile); ok { + directory.KnowledgeURLs = (&reader{file: KnowledgeURLsFile, problems: &problems}).knowledgeURLs(pages) + } + directory.Simulations = readSimulations(paths, text, &problems) + if directory.Settings.UI != nil { + directory.UI = readUI(*directory.Settings.UI, directory.declaration, text, &problems) + } + + total := 0 + for _, file := range paths { + if !used[file] { + directory.Ignored = append(directory.Ignored, file) + continue + } + directory.Files = append(directory.Files, File{Path: file, Content: held[file]}) + total += len(held[file]) + } + if total > MaxBytes { + fail(AgentFile, "the directory holds %d bytes, and one holds at most %d", total, MaxBytes) + } + if len(problems) > 0 { + return directory, problems + } + return directory, nil +} + +// Locate is where agent.yaml says the setting a dotted path names, such as greeting.mode or +// chat_channels[1].answer, or the nearest setting above it the file does say. +func (d *Directory) Locate(setting string) (line, column int) { + return d.declaration.locate(setting) +} + +// ValidPath reports whether a slash path names a file inside the folder it is relative to. +func ValidPath(file string) bool { + return file != "" && !path.IsAbs(file) && path.Clean(file) == file && file != ".." && + !strings.HasPrefix(file, "../") && !strings.Contains(file, `\`) +} + +// hidden reports whether a file is left behind wherever it is: dot files such as .DS_Store +// and .agent_sync, the __pycache__ that running a skill's scripts locally leaves, and +// node_modules. +func hidden(file string) bool { + for segment := range strings.SplitSeq(file, "/") { + if strings.HasPrefix(segment, ".") || segment == "__pycache__" || segment == "node_modules" { + return true + } + } + return false +} diff --git a/acceleration/internal/agentdir/content.go b/acceleration/internal/agentdir/content.go new file mode 100644 index 0000000000..7554792289 --- /dev/null +++ b/acceleration/internal/agentdir/content.go @@ -0,0 +1,312 @@ +package agentdir + +import ( + "errors" + "fmt" + "path" + "slices" + "strconv" + "strings" + "time" + "unicode/utf8" + + "gopkg.in/yaml.v3" +) + +// readSkills reads skills/: a skill is either a markdown file, or a folder holding a SKILL.md +// and whatever files it comes with, nested as deep as they are. +func readSkills(paths []string, text func(string) (string, bool), problems *Problems) []Skill { + var skills []Skill + declared, named := map[string]string{}, map[string]string{} + folders := map[string]bool{} + for _, file := range paths { + rest, inside := strings.CutPrefix(file, SkillsDir+"/") + if !inside { + continue + } + name, _, folder := strings.Cut(rest, "/") + switch { + case folder && folders[name]: + continue + case folder: + folders[name] = true + file = SkillsDir + "/" + name + "/" + SkillFile + case path.Ext(name) == ".md": + name = strings.TrimSuffix(name, ".md") + default: + continue + } + + content, ok := text(file) + if !ok { + if folder { + *problems = append(*problems, Problem{File: file, Message: "is missing, so " + SkillsDir + "/" + name + " is not a skill"}) + } + continue + } + if first, taken := declared[name]; taken { + *problems = append(*problems, Problem{File: file, Message: fmt.Sprintf("skill %q is also %s", name, first)}) + continue + } + declared[name] = file + + skill := parseSkill(name, file, content, problems) + // A sync finds a skill by its name, which the frontmatter may give in place of the file's. + if first, taken := named[skill.Name]; taken { + *problems = append(*problems, Problem{File: file, Line: 1, Column: 1, + Message: fmt.Sprintf("skill %q is also declared in %s", skill.Name, first)}) + } + named[skill.Name] = file + if folder { + prefix := SkillsDir + "/" + name + "/" + for _, beside := range paths { + relative, within := strings.CutPrefix(beside, prefix) + if !within || relative == SkillFile { + continue + } + if content, ok := text(beside); ok { + if skill.Files == nil { + skill.Files = map[string]string{} + } + skill.Files[relative] = content + } + } + } + skills = append(skills, skill) + } + return skills +} + +// parseSkill reads a skill file: frontmatter between --- lines, then the instructions. +// +// The frontmatter is read a line at a time, as a key and its value, and not as YAML. The keys +// read are name, description, capture_video and deadline; any other is left alone, since a +// skill written for another harness brings keys of its own. +func parseSkill(name, file, content string, problems *Problems) Skill { + skill := Skill{Name: name} + fail := func(line int, format string, args ...any) { + *problems = append(*problems, Problem{File: file, Line: line, Column: 1, Message: fmt.Sprintf(format, args...)}) + } + + frontmatter, body, first := cutFrontmatter(content) + for index, line := range strings.Split(frontmatter, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + key, value, ok := strings.Cut(line, ":") + if !ok { + fail(first+index, "%q is not a key and a value", line) + continue + } + value = unquoted(strings.TrimSpace(value)) + switch strings.TrimSpace(key) { + case "name": + skill.Name = value + case "description": + skill.Description = value + case "capture_video": + if value != "true" && value != "false" { + fail(first+index, "capture_video must be true or false") + } + skill.CaptureVideo = value == "true" + case "deadline": + deadline, err := parseDeadline(value) + if err != nil { + fail(first+index, "%q is not a deadline: write a duration such as 30s or 2m", value) + } + skill.Deadline = deadline + } + } + + skill.Instructions = strings.TrimSpace(body) + if skill.Description == "" { + fail(1, "a skill needs a description, since it is all the fast model sees") + } + if skill.Instructions == "" { + fail(1, "a skill needs instructions, since they are what the subagent answers under") + } + return skill +} + +// parseDeadline takes a Go duration, and a bare number as seconds. +func parseDeadline(value string) (time.Duration, error) { + deadline, err := time.ParseDuration(value) + if seconds, bare := strconv.ParseFloat(value, 64); bare == nil { + deadline, err = time.Duration(seconds*float64(time.Second)), nil + } + if err == nil && deadline < 0 { + err = errors.New("a deadline is not negative") + } + return deadline, err +} + +// unquoted is a frontmatter value without the pair of quotes around it, if it has one. +func unquoted(value string) string { + if len(value) >= 2 && (value[0] == '"' || value[0] == '\'') && value[len(value)-1] == value[0] { + return value[1 : len(value)-1] + } + return value +} + +// cutFrontmatter separates a leading --- block from the body, and says which line of the file +// the block's first line is. The block ends at the next line that is --- alone, and the body +// is everything after that line, as written. +func cutFrontmatter(content string) (frontmatter, body string, line int) { + trimmed := strings.TrimLeft(content, "\ufeff \t\r\n") + opening, rest, found := strings.Cut(trimmed, "\n") + if !found || strings.TrimRight(opening, " \t\r") != "---" { + return "", content, 0 + } + line = 2 + strings.Count(content[:len(content)-len(trimmed)], "\n") + for at := 0; at < len(rest); { + end := strings.IndexByte(rest[at:], '\n') + next := len(rest) + if end >= 0 { + next = at + end + 1 + } + if strings.TrimRight(rest[at:next], " \t\r\n") == "---" { + return rest[:at], rest[next:], line + } + at = next + } + return "", content, 0 +} + +// readKnowledge reads the readable files under knowledge/ that hold anything. The urls.yaml +// at its root declares pages and is not itself looked things up in; deeper, a urls.yaml is a +// document like any other. +func readKnowledge(paths []string, text func(string) (string, bool)) []Document { + var documents []Document + for _, file := range paths { + source, inside := strings.CutPrefix(file, KnowledgeDir+"/") + if !inside || !knowledgePath(source) { + continue + } + if content, ok := text(file); ok && strings.TrimSpace(content) != "" { + documents = append(documents, Document{Source: source, Text: content}) + } + } + return documents +} + +// KnowledgeFile reports whether knowledge/ holds a document under source: a path inside it +// with an extension that is read, holding text that says something. +func KnowledgeFile(source, content string) bool { + return knowledgePath(source) && utf8.ValidString(content) && strings.TrimSpace(content) != "" +} + +func knowledgePath(source string) bool { + return ValidPath(source) && !hidden(source) && KnowledgeDir+"/"+source != KnowledgeURLsFile && + slices.Contains(knowledgeExtensions, strings.ToLower(path.Ext(source))) +} + +// knowledgeURLs reads knowledge/urls.yaml: a list of pages, each the url on its own or a +// mapping naming it alongside what it is. +func (r *reader) knowledgeURLs(content string) []KnowledgeURL { + root := r.document(content) + if root == nil { + return nil + } + var pages []KnowledgeURL + r.each(root, func(item *yaml.Node) { + if null(item) { + return + } + var page KnowledgeURL + where := item + if item = resolved(item); item.Kind == yaml.ScalarNode { + page.URL = item.Value + } else if !r.mapping(item, "a page", + field{"url", func(value *yaml.Node) { where = value; r.text(&page.URL)(value) }}, + field{"title", r.text(&page.Title)}, + field{"description", r.text(&page.Description)}, + field{"refresh_hours", func(value *yaml.Node) { + r.integer(&page.RefreshHours)(value) + if page.RefreshHours < 1 { + r.fail(value, "is how many hours between reads, so it is at least 1; leave it out for never") + } + }}) { + return + } + if !strings.HasPrefix(page.URL, "http://") && !strings.HasPrefix(page.URL, "https://") { + r.fail(where, "%q is not an http or https url", page.URL) + } + pages = append(pages, page) + }) + return pages +} + +// readSimulations reads every .yaml and .yml file directly in simulations/, each a list of +// simulations, in file order. A name two simulations share is refused, since a sync finds a +// simulation by its name. +func readSimulations(paths []string, text func(string) (string, bool), problems *Problems) []Simulation { + var simulations []Simulation + named := map[string]string{} + for _, file := range paths { + name, inside := strings.CutPrefix(file, SimulationsDir+"/") + extension := strings.ToLower(path.Ext(file)) + if !inside || strings.Contains(name, "/") || (extension != ".yaml" && extension != ".yml") { + continue + } + content, ok := text(file) + if !ok { + continue + } + if simulations == nil { + simulations = []Simulation{} + } + r := &reader{file: file, problems: problems} + root := r.document(content) + if root == nil { + continue + } + r.each(root, func(item *yaml.Node) { + if null(item) { + return + } + var simulation Simulation + at := map[string]*yaml.Node{} + keep := func(key string, read func(*yaml.Node)) field { + return field{key, func(value *yaml.Node) { at[key] = value; read(value) }} + } + if !r.mapping(item, "a simulation", + keep("name", r.text(&simulation.Name)), + keep("scenario", r.text(&simulation.Scenario)), + keep("assertion", r.text(&simulation.Assertion)), + keep("mode", r.text(&simulation.Mode)), + field{"variations", r.integer(&simulation.Variations)}, + field{"max_turns", r.integer(&simulation.MaxTurns)}, + field{"caller_target", r.text(&simulation.CallerTarget)}, + field{"judge_target", r.text(&simulation.JudgeTarget)}, + field{"caller_stt", r.text(&simulation.CallerSTT)}, + field{"caller_tts", r.text(&simulation.CallerTTS)}, + field{"caller_voice", r.text(&simulation.CallerVoice)}, + field{"tags", r.labels(&simulation.Tags)}) { + return + } + where := func(key string) *yaml.Node { + if node := at[key]; node != nil { + return node + } + return item + } + switch { + case simulation.Name == "": + r.fail(where("name"), "a simulation needs a name") + case simulation.Scenario == "": + r.fail(where("scenario"), "simulation %q needs a scenario", simulation.Name) + case simulation.Assertion == "": + r.fail(where("assertion"), "simulation %q needs an assertion", simulation.Name) + case simulation.Mode != "" && simulation.Mode != "text" && simulation.Mode != "audio": + r.fail(where("mode"), "simulation %q is text or audio, not %q", simulation.Name, simulation.Mode) + } + if first, taken := named[simulation.Name]; taken && simulation.Name != "" { + r.fail(where("name"), "simulation %q is also declared in %s", simulation.Name, first) + } + named[simulation.Name] = file + simulations = append(simulations, simulation) + }) + } + return simulations +} diff --git a/acceleration/internal/agentdir/parse_test.go b/acceleration/internal/agentdir/parse_test.go new file mode 100644 index 0000000000..10076dd946 --- /dev/null +++ b/acceleration/internal/agentdir/parse_test.go @@ -0,0 +1,639 @@ +package agentdir + +import ( + "strings" + "testing" + "time" + + "github.com/stretchr/testify/suite" +) + +type ParseSuite struct { + suite.Suite +} + +func TestParseSuite(t *testing.T) { + suite.Run(t, new(ParseSuite)) +} + +// files is a directory by path, with an agent.yaml naming it unless the test gives one. +func files(held map[string]string) []File { + if _, declared := held[AgentFile]; !declared { + held[AgentFile] = "name: jean\n" + } + listed := make([]File, 0, len(held)) + for path, content := range held { + listed = append(listed, File{Path: path, Content: content}) + } + return listed +} + +func (s *ParseSuite) parse(held map[string]string) *Directory { + directory, err := Parse(files(held)) + s.Require().NoError(err) + return directory +} + +func (s *ParseSuite) settings(declaration string) Settings { + return s.parse(map[string]string{AgentFile: declaration}).Settings +} + +// refused parses a directory that must not read, and returns the one problem it has. +func (s *ParseSuite) refused(held map[string]string) Problem { + _, err := Parse(files(held)) + var problems Problems + s.Require().ErrorAs(err, &problems) + s.Require().Len(problems, 1, "%v", problems) + return problems[0] +} + +// refusedAt holds a refusal to its place in agent.yaml and to what it says. +func (s *ParseSuite) refusedAt(declaration string, line, column int, says string) { + problem := s.refused(map[string]string{AgentFile: declaration}) + s.Equal(AgentFile, problem.File) + s.Equal([]int{line, column}, []int{problem.Line, problem.Column}, problem.Message) + s.Contains(problem.Message, says) +} + +func (s *ParseSuite) TestADirectoryIsReadAsInstructionsSkillsAndKnowledge() { + directory := s.parse(map[string]string{ + "instructions.md": "\nYou are Jean.\n\n", + "guardrail.md": "---\ntype: llm\n---\nNo medical advice.\n", + "skills/think.md": "---\ndescription: Work it out\ndeadline: 2m\n---\nReason it through.\n", + "knowledge/pricing.md": "# Pricing\n", + "knowledge/empty.md": " \n", + "knowledge/diagram.png": "\x89PNG", + }) + + s.Equal("jean", directory.Settings.Name) + s.Equal("You are Jean.", directory.Instructions) + s.Equal("---\ntype: llm\n---\nNo medical advice.", directory.Guardrail) + s.Equal([]Skill{{Name: "think", Description: "Work it out", Instructions: "Reason it through.", Deadline: 2 * time.Minute}}, directory.Skills) + s.Equal([]Document{{Source: "pricing.md", Text: "# Pricing\n"}}, directory.Knowledge) + s.Equal([]string{"knowledge/diagram.png"}, directory.Ignored, "a file a model cannot look things up in is left out, and said to be") +} + +func (s *ParseSuite) TestADirectoryWithoutADeclarationIsNotAnAgent() { + _, err := Parse([]File{{Path: "instructions.md", Content: "You are Jean."}}) + + var problems Problems + s.Require().ErrorAs(err, &problems) + s.Equal(AgentFile, problems[0].File) + s.Contains(problems[0].Message, "what makes a directory an agent") +} + +func (s *ParseSuite) TestTheDeclarationSaysWhatTheAgentRunsOn() { + settings := s.settings(`name: jean +mode: text +region: eu +stt: deepgram/nova-3 +tts: tts-fast +sts: "" +voice: custom:Jean +llm: llm-fast +harness: default +role: agent_moderator +subagent: llm-thinking +search: search-fast +image: image-fast +greeting: {text: "Hi.", mode: variation} +sandbox: daytona +sandbox_options: + image: python:3.12-slim + setup: [pip install pandas] + timeout: 90s + cpu: 2 + network: true +keyterms: [Stream, 10DLC] +tags: {team: support} +video: {source: screen, max_frames: 4} +dispatch: {incoming_call: enabled} +scheduling: {enabled: true, max_tasks_per_user: 10, default_timezone: Europe/Amsterdam} +chat_channels: + - type: team + answer: mentioned +agents: + - {config: billing, tool: ask_billing, timeout_ms: 5000, max_tool_rounds: -1} +channels: + whatsapp: {number: "+15551230000"} + identity: link +`) + + s.Equal("text", settings.Mode) + s.Equal("eu", settings.Region) + s.Equal("custom:Jean", settings.Voice) + s.Require().NotNil(settings.STS, "an empty sts turns it off, which is not saying nothing") + s.Empty(*settings.STS) + s.Equal("image-fast", *settings.Image) + s.Equal(&Greeting{Text: "Hi.", Mode: "variation"}, settings.Greeting) + s.Equal(&SandboxOptions{Image: "python:3.12-slim", Setup: []string{"pip install pandas"}, Timeout: 90 * time.Second, CPU: 2, Network: true}, settings.SandboxOptions) + s.Equal([]string{"Stream", "10DLC"}, settings.Keyterms) + s.Equal(map[string]string{"team": "support"}, settings.Tags) + s.Equal(&Video{Source: "screen", MaxFrames: 4}, settings.Video) + s.Equal(&Dispatch{IncomingCall: "enabled"}, settings.Dispatch) + s.Equal(10, *settings.Scheduling.MaxTasksPerUser) + s.Equal([]ChatChannel{{Type: "team", Answer: "mentioned"}}, *settings.ChatChannels) + s.Equal([]ChildAgent{{Config: "billing", Tool: "ask_billing", TimeoutMs: 5000, MaxToolRounds: -1}}, *settings.Agents) + s.Equal(&Channels{WhatsApp: "+15551230000", Identity: "link"}, settings.Channels) +} + +func (s *ParseSuite) TestAGreetingIsItsTextAloneOrAMappingWithItsMode() { + s.Equal(&Greeting{Text: "Hi, how can I help?"}, s.settings("name: jean\ngreeting: Hi, how can I help?\n").Greeting) + s.Equal(&Greeting{Text: "Hi.", Mode: "exact"}, s.settings("name: jean\ngreeting:\n text: Hi.\n mode: exact\n").Greeting) +} + +func (s *ParseSuite) TestASettingTheFileLeavesOutIsLeftAlone() { + settings := s.settings("name: jean\nsts:\nconnectors:\n") + + s.Nil(settings.STS, "a key with nothing after it says nothing") + s.Nil(settings.Image) + s.Nil(settings.Connectors) + s.Nil(settings.Tools) + s.Nil(settings.Calls) + s.Nil(settings.FloorControl) + s.Nil(settings.UI) +} + +func (s *ParseSuite) TestADeclarationKeyNobodyKnowsIsRefusedWhereItIs() { + s.refusedAt("name: jean\nllmm: llm-fast\n", 2, 1, `"llmm" is not something agent.yaml says`) +} + +func (s *ParseSuite) TestAKeyNobodyKnowsIsNotToldTheRetiredKeysAreValid() { + problem := s.refused(map[string]string{AgentFile: "name: jean\nvoise: aurora\n"}) + + s.True(strings.HasSuffix(problem.Message, ", dispatch, ui, app are"), problem.Message) + for _, gone := range []string{"plugins", "plugin_events", "mcp_servers"} { + s.NotContains(problem.Message, gone) + } +} + +func (s *ParseSuite) TestANestedKeyNobodyKnowsIsRefusedWhereItIs() { + s.refusedAt("name: jean\ngreeting:\n text: Hi.\n tone: warm\n", 4, 3, `"tone" is not something greeting says; text, mode are`) +} + +func (s *ParseSuite) TestAKeyWrittenTwiceIsRefused() { + s.refusedAt("name: jean\nllm: a\nllm: b\n", 3, 1, "llm is written twice") +} + +func (s *ParseSuite) TestAValueOfTheWrongTypeIsRefusedWhereItIs() { + s.refusedAt("name: jean\nllm:\n model: llm-fast\n", 3, 3, "llm: must be text, not a mapping") + s.refusedAt("name: jean\nkeyterms: Stream\n", 2, 11, "keyterms: must be a list") + s.refusedAt("name: jean\nscheduling:\n enabled: maybe\n", 3, 12, "scheduling: enabled: must be true or false") + s.refusedAt("name: jean\nscheduling:\n max_tasks_per_user: many\n", 3, 23, "must be a whole number") + s.refusedAt("name: jean\ngreeting: [Hi.]\n", 2, 11, "greeting: must be a mapping") +} + +func (s *ParseSuite) TestEveryProblemIsReportedAtOnce() { + _, err := Parse(files(map[string]string{ + AgentFile: "name: jean\nllmm: x\nvideo: {max_frames: 12}\n", + "skills/think.md": "Reason it through.\n", + "knowledge/urls.yaml": "- ftp://example.com\n", + })) + + var problems Problems + s.Require().ErrorAs(err, &problems) + found := map[string]bool{} + for _, problem := range problems { + found[problem.File] = true + } + s.Equal(map[string]bool{AgentFile: true, "skills/think.md": true, "knowledge/urls.yaml": true}, found) + s.Len(problems, 4, "%v", problems) +} + +func (s *ParseSuite) TestADeclarationThatIsNotYAMLNamesTheLine() { + problem := s.refused(map[string]string{AgentFile: "name: jean\ngreeting: {text: Hi\n"}) + + s.Equal(AgentFile, problem.File) + s.Positive(problem.Line) +} + +func (s *ParseSuite) TestPluginsAreRefusedWithAPointerToConnectors() { + s.refusedAt("name: jean\nplugins:\n - name: github\n", 3, 3, "plugins: no longer read: plugins were replaced by connectors") + s.refusedAt("name: jean\nplugin_events: [{name: push}]\n", 2, 16, "plugins were replaced by connectors") + s.refusedAt("name: jean\nplugins: github\n", 2, 10, "no longer read") +} + +func (s *ParseSuite) TestMCPServersAreRefusedWithAPointerToACustomConnector() { + s.refusedAt("name: jean\nmcp_servers:\n - url: https://mcp.example.com\n", 3, 3, "a server named by URL is now a custom connector") +} + +func (s *ParseSuite) TestEmptyPluginKeysLoadAsTheyDidBefore() { + settings := s.settings("name: jean\nplugins: []\nplugin_events:\nmcp_servers: []\n") + + s.Equal("jean", settings.Name) +} + +func (s *ParseSuite) TestTheToolSettingsOfBeforeGroupsAreRefusedSayingWhereTheyWent() { + s.refusedAt("name: jean\ntools:\n progressive: true\n", 3, 3, "progressive: true is now loading: summary") +} + +func (s *ParseSuite) TestAToolGroupIsReadWithItsLoadingAndRetention() { + settings := s.settings("name: jean\ntools:\n - {name: booking, loading: summary, tools: [lookup_booking], output_retention: 30d}\n") + + s.Equal([]ToolGroup{{Name: "booking", Loading: "summary", Tools: []string{"lookup_booking"}, OutputRetention: "30d"}}, *settings.Tools) +} + +func (s *ParseSuite) TestAToolGroupThatSaysTooLittleOrTooMuchIsRefused() { + s.refusedAt("name: jean\ntools:\n - tools: [lookup]\n", 3, 5, "a tool group needs a name") + s.refusedAt("name: jean\ntools:\n - name: booking\n", 3, 5, `tool group "booking" names no tools`) + s.refusedAt("name: jean\ntools:\n - {name: booking, tools: [lookup], loading: lazy}\n", 3, 47, `is full, summary, deferred, not "lazy"`) + s.refusedAt("name: jean\ntools:\n - {name: booking, tools: [lookup], progressive: true}\n", 3, 38, `"progressive" is not something a tool group says`) +} + +func (s *ParseSuite) TestAnEmptyToolListIsNotTheSameAsNone() { + s.Equal([]ToolGroup{}, *s.settings("name: jean\ntools: []\n").Tools) +} + +func (s *ParseSuite) TestTheFloorControlIsReadAsWritten() { + chosen := s.settings("name: jean\nfloor_control:\n model: stream/chorus-asr\n max_wait_ms: 800\n").FloorControl + s.Equal("stream/chorus-asr", *chosen.Model) + s.Equal(800, *chosen.MaxWaitMs) + + empty := s.settings("name: jean\nfloor_control: {}\n").FloorControl + s.Require().NotNil(empty, "an empty mapping is no choice again, which is not saying nothing") + s.Nil(empty.Model) + s.Nil(empty.MaxWaitMs) +} + +func (s *ParseSuite) TestAFloorControlThatIsNotAMappingOfModelAndWaitIsRefused() { + s.refusedAt("name: jean\nfloor_control: stream/chorus-asr\n", 2, 16, "floor_control: must be a mapping") + s.refusedAt("name: jean\nfloor_control: {mode: fast}\n", 2, 17, `"mode" is not something floor_control says; model, max_wait_ms are`) + s.refusedAt("name: jean\nfloor_control: {model: 5}\n", 2, 24, "must be a string, such as stream/chorus-asr") + s.refusedAt("name: jean\nfloor_control: {max_wait_ms: soon}\n", 2, 30, "must be a whole number") +} + +func (s *ParseSuite) TestTheApplicationsOwnSectionIsLeftToIt() { + settings := s.settings("name: jean\napp:\n anything: [goes, {here: true}]\n") + + s.Equal("jean", settings.Name) +} + +func (s *ParseSuite) TestAVideoFrameCountOutsideOneToEightIsRefused() { + s.Equal(1, s.settings("name: jean\nvideo: {source: screen}\n").Video.MaxFrames) + s.Equal(1, s.settings("name: jean\nvideo: {max_frames: 0}\n").Video.MaxFrames, "zero reads as one") + s.refusedAt("name: jean\nvideo: {max_frames: 9}\n", 2, 21, "must be an integer from 1 to 8") +} + +func (s *ParseSuite) TestASandboxTimeoutThatIsNotADurationUpToThirtyMinutesIsRefused() { + s.refusedAt("name: jean\nsandbox_options: {timeout: 45m}\n", 2, 28, `must be a duration up to 30m, such as 90s, not "45m"`) + s.refusedAt("name: jean\nsandbox_options: {timeout: soon}\n", 2, 28, "must be a duration") +} + +func (s *ParseSuite) TestAConnectorNamedAloneIsEveryToolOfASessionBinding() { + connectors := *s.settings("name: jean\nconnectors:\n - github\n").Connectors + + s.Equal([]Connector{{Name: "github"}}, connectors) +} + +func (s *ParseSuite) TestAConnectorWrittenOutSaysWhatItBinds() { + connectors := *s.settings(`name: jean +connectors: + - name: tickets + connector: linear + tools: [search, "linear_*"] + connection: Support workspace + required: true + sandbox: true + require_approval: ["create_*"] + loading: deferred + output_retention: 12h +`).Connectors + + s.Require().Len(connectors, 1) + bound := connectors[0] + s.Equal("linear", bound.Connector) + s.Equal([]string{"search", "linear_*"}, *bound.Tools) + s.Equal("Support workspace", *bound.Connection) + s.True(*bound.Required) + s.True(bound.Sandbox) + s.Equal([]string{"create_*"}, *bound.RequireApproval) + s.Equal("deferred", bound.Loading) + s.Equal("12h", bound.OutputRetention) +} + +func (s *ParseSuite) TestAnEmptyConnectorListIsNotTheSameAsNone() { + s.Equal([]Connector{}, *s.settings("name: jean\nconnectors: []\n").Connectors) +} + +func (s *ParseSuite) TestANullOrCommentedOutConnectorEntryIsRefused() { + s.refusedAt("name: jean\nconnectors:\n - github\n -\n", 4, 4, "a connector needs a name") + s.refusedAt("name: jean\nconnectors:\n - # github\n", 3, 4, "a connector needs a name") +} + +func (s *ParseSuite) TestAConnectorThatSaysTooLittleOrTooMuchIsRefused() { + s.refusedAt("name: jean\nconnectors:\n - connector: linear\n", 3, 5, "a connector needs a name") + s.refusedAt("name: jean\nconnectors:\n - {name: linear, connection: \"\"}\n", 3, 32, "connection: must be a connection id or label") + s.refusedAt("name: jean\nconnectors:\n - {name: linear, tools: []}\n", 3, 27, "tools: [] grants nothing; leave tools out for every tool") + s.refusedAt("name: jean\nconnectors:\n - {name: linear, sandbox: sometimes}\n", 3, 29, "sandbox: must be true or false") + s.refusedAt("name: jean\nconnectors:\n - name: linear\n scopes: [read]\n", 4, 5, `"scopes" is not something a connector says; name, connector, tools`) + s.refusedAt("name: jean\nconnectors:\n - {name: linear, loading: lazy}\n", 3, 29, `is full, summary, deferred, not "lazy"`) + s.refusedAt("name: jean\nconnectors: github\n", 2, 13, "connectors: must be a list") +} + +func (s *ParseSuite) TestASkillFolderBringsItsNestedFiles() { + directory := s.parse(map[string]string{ + "skills/pdf/SKILL.md": "---\nname: fill-pdf\ndescription: \"Fill a form\"\ncapture_video: true\nlicense: MIT\n# a comment\n---\nRun the script.\n", + "skills/pdf/scripts/fill.py": "print('filled')\n", + "skills/pdf/reference/forms.md": "# Forms\n", + "skills/pdf/.DS_Store": "\x00", + "skills/pdf/__pycache__/fill.pyc": "\x00", + "skills/pdf/node_modules/x/index.js": "x", + "skills/notes.txt": "not a skill", + }) + + s.Require().Len(directory.Skills, 1) + skill := directory.Skills[0] + s.Equal("fill-pdf", skill.Name, "the frontmatter's name wins over the folder's") + s.Equal("Fill a form", skill.Description) + s.True(skill.CaptureVideo) + s.Equal(map[string]string{"scripts/fill.py": "print('filled')\n", "reference/forms.md": "# Forms\n"}, skill.Files) + s.Equal([]string{"skills/notes.txt"}, directory.Ignored) +} + +func (s *ParseSuite) TestASkillDeadlineIsADurationOrSeconds() { + skill := func(deadline string) Skill { + return s.parse(map[string]string{"skills/think.md": "---\ndescription: Work it out\ndeadline: " + deadline + "\n---\nReason.\n"}).Skills[0] + } + + s.Equal(30*time.Second, skill("30s").Deadline) + s.Equal(90*time.Second, skill("1.5m").Deadline) + s.Equal(45*time.Second, skill("45").Deadline) + s.Equal(60500*time.Millisecond, skill("1m500ms").Deadline) +} + +func (s *ParseSuite) TestASkillThatSaysTooLittleIsRefusedInItsFile() { + missing := s.refused(map[string]string{"skills/think.md": "Reason it through.\n"}) + s.Equal("skills/think.md", missing.File) + s.Contains(missing.Message, "a skill needs a description") + + empty := s.refused(map[string]string{"skills/think.md": "---\ndescription: Work it out\n---\n"}) + s.Contains(empty.Message, "a skill needs instructions") +} + +func (s *ParseSuite) TestASkillFrontmatterProblemNamesItsLine() { + deadline := s.refused(map[string]string{"skills/think.md": "---\ndescription: Work it out\ndeadline: soon\n---\nReason.\n"}) + s.Equal([]int{3, 1}, []int{deadline.Line, deadline.Column}) + s.Contains(deadline.Message, `"soon" is not a deadline`) + + for _, deadline := range []string{"broken1sjunk", "-1s", "-5", "1s junk", "1m2"} { + refused := s.refused(map[string]string{"skills/think.md": "---\ndescription: Work it out\ndeadline: " + deadline + "\n---\nReason.\n"}) + s.Contains(refused.Message, "is not a deadline", deadline) + } + + video := s.refused(map[string]string{"skills/think.md": "---\ndescription: Work it out\ncapture_video: yes\n---\nReason.\n"}) + s.Equal(3, video.Line) + s.Contains(video.Message, "capture_video must be true or false") + + loose := s.refused(map[string]string{"skills/think.md": "\n---\ndescription: Work it out\njust words\n---\nReason.\n"}) + s.Equal(4, loose.Line) + s.Contains(loose.Message, "is not a key and a value") +} + +func (s *ParseSuite) TestASkillFolderWithoutASkillFileIsRefused() { + problem := s.refused(map[string]string{"skills/pdf/scripts/fill.py": "print()\n"}) + + s.Equal("skills/pdf/SKILL.md", problem.File) + s.Contains(problem.Message, "skills/pdf is not a skill") +} + +func (s *ParseSuite) TestASkillThatIsBothAFileAndAFolderIsRefused() { + problem := s.refused(map[string]string{ + "skills/pdf.md": "---\ndescription: Fill a form\n---\nRun it.\n", + "skills/pdf/SKILL.md": "---\ndescription: Fill a form\n---\nRun it.\n", + }) + + s.Contains(problem.Message, `skill "pdf" is also skills/pdf.md`) +} + +func (s *ParseSuite) TestASkillFileThatIsNotTextIsRefused() { + problem := s.refused(map[string]string{ + "skills/pdf/SKILL.md": "---\ndescription: Fill a form\n---\nRun it.\n", + "skills/pdf/form.pdf": "%PDF\xff\xfe", + }) + + s.Equal("skills/pdf/form.pdf", problem.File) + s.Contains(problem.Message, "is not text") +} + +func (s *ParseSuite) TestNestedKnowledgeKeepsThePathItWasFoundAt() { + directory := s.parse(map[string]string{ + "knowledge/plans/pro.md": "Pro.\n", + "knowledge/plans/urls.yaml": "- not a declaration here\n", + "knowledge/Notes.TXT": "Notes.\n", + "knowledge/.hidden.md": "secret\n", + }) + + s.Equal([]Document{ + {Source: "Notes.TXT", Text: "Notes.\n"}, + {Source: "plans/pro.md", Text: "Pro.\n"}, + {Source: "plans/urls.yaml", Text: "- not a declaration here\n"}, + }, directory.Knowledge) + s.Empty(directory.Ignored, "a hidden file is skipped without a word") +} + +func (s *ParseSuite) TestDeclaredPagesAreReadWithoutBeingKnowledge() { + directory := s.parse(map[string]string{"knowledge/urls.yaml": `- https://example.com/pricing +- +- url: https://example.com/plans + title: Plans + description: What each plan includes. + refresh_hours: 24 +`}) + + s.Equal([]KnowledgeURL{ + {URL: "https://example.com/pricing"}, + {URL: "https://example.com/plans", Title: "Plans", Description: "What each plan includes.", RefreshHours: 24}, + }, directory.KnowledgeURLs) + s.Empty(directory.Knowledge) +} + +func (s *ParseSuite) TestAPageThatCannotBeFetchedOrDescribedIsRefusedOnItsLine() { + page := func(declared string) Problem { + problem := s.refused(map[string]string{"knowledge/urls.yaml": declared}) + s.Equal("knowledge/urls.yaml", problem.File) + return problem + } + + scheme := page("- https://example.com\n- ftp://example.com/file\n") + s.Equal([]int{2, 3}, []int{scheme.Line, scheme.Column}) + s.Contains(scheme.Message, `"ftp://example.com/file" is not an http or https url`) + + unknown := page("- url: https://example.com\n tittle: Plans\n") + s.Equal([]int{2, 3}, []int{unknown.Line, unknown.Column}) + s.Contains(unknown.Message, `"tittle" is not something a page says; url, title, description, refresh_hours are`) + + hours := page("- url: https://example.com\n refresh_hours: 0\n") + s.Equal(2, hours.Line) + s.Contains(hours.Message, "so it is at least 1; leave it out for never") + + s.Contains(page("- [https://example.com]\n").Message, "must be a mapping") +} + +func (s *ParseSuite) TestEachSimulationFileIsAListReadInFileOrder() { + directory := s.parse(map[string]string{ + "simulations/b.yml": "- name: refund\n scenario: Ask for a refund.\n assertion: A refund is offered.\n", + "simulations/a.yaml": "- name: lunch\n scenario: >\n Order a turkey club,\n then swap it.\n assertion: One veggie wrap.\n mode: audio\n variations: 3\n max_turns: 8\n caller_voice: aurora\n tags: {suite: smoke}\n-\n", + "simulations/nested/c.yaml": "- name: deep\n", + "simulations/README.md": "notes", + }) + + s.Equal([]Simulation{ + {Name: "lunch", Scenario: "Order a turkey club, then swap it.\n", Assertion: "One veggie wrap.", Mode: "audio", Variations: 3, MaxTurns: 8, CallerVoice: "aurora", Tags: map[string]string{"suite": "smoke"}}, + {Name: "refund", Scenario: "Ask for a refund.", Assertion: "A refund is offered."}, + }, directory.Simulations) +} + +func (s *ParseSuite) TestASimulationsFileThatDeclaresNoneIsNotTheSameAsNoFile() { + s.Nil(s.parse(map[string]string{}).Simulations, "no file leaves the stored simulations alone") + + declared := s.parse(map[string]string{"simulations/none.yaml": "[]\n"}).Simulations + s.NotNil(declared, "a file that lists none deletes them") + s.Empty(declared) +} + +func (s *ParseSuite) TestASimulationThatSaysTooLittleIsRefusedOnItsLine() { + simulation := func(declared string) Problem { + problem := s.refused(map[string]string{"simulations/lunch.yaml": declared}) + s.Equal("simulations/lunch.yaml", problem.File) + return problem + } + + unnamed := simulation("- name: first\n scenario: Ask.\n assertion: Answered.\n- scenario: Ask.\n assertion: Answered.\n") + s.Equal([]int{4, 3}, []int{unnamed.Line, unnamed.Column}) + s.Contains(unnamed.Message, "a simulation needs a name") + + s.Contains(simulation("- name: lunch\n assertion: Answered.\n").Message, `simulation "lunch" needs a scenario`) + s.Contains(simulation("- name: lunch\n scenario: Ask.\n").Message, `simulation "lunch" needs an assertion`) + + mode := simulation("- name: lunch\n scenario: Ask.\n assertion: Answered.\n mode: video\n") + s.Equal([]int{4, 9}, []int{mode.Line, mode.Column}) + s.Contains(mode.Message, `simulation "lunch" is text or audio, not "video"`) + + unknown := simulation("- name: lunch\n scenario: Ask.\n assertion: Answered.\n turns: 4\n") + s.Equal([]int{4, 3}, []int{unknown.Line, unknown.Column}) + s.Contains(unknown.Message, `"turns" is not something a simulation says`) +} + +func (s *ParseSuite) TestASimulationNameTwoFilesShareIsRefused() { + problem := s.refused(map[string]string{ + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n", + "simulations/b.yaml": "- name: lunch\n scenario: Ask again.\n assertion: Answered.\n", + }) + + s.Equal("simulations/b.yaml", problem.File) + s.Equal([]int{1, 9}, []int{problem.Line, problem.Column}) + s.Contains(problem.Message, `simulation "lunch" is also declared in simulations/a.yaml`) +} + +func (s *ParseSuite) TestAPathThatLeavesTheDirectoryIsRefused() { + for _, path := range []string{"../agent.yaml", "/etc/passwd", "skills/../../x.md", `skills\think.md`, "knowledge//a.md", ""} { + _, err := Parse([]File{{Path: AgentFile, Content: "name: jean\n"}, {Path: path, Content: "x"}}) + + var problems Problems + s.Require().ErrorAs(err, &problems, path) + s.Equal(path, problems[0].File) + s.Contains(problems[0].Message, "is not a path inside the directory") + } +} + +func (s *ParseSuite) TestAFileSentTwiceIsRefused() { + _, err := Parse([]File{{Path: AgentFile, Content: "name: jean\n"}, {Path: AgentFile, Content: "name: joan\n"}}) + + s.ErrorContains(err, "agent.yaml: is sent twice") +} + +func (s *ParseSuite) TestAFileOverTheSizeAFileMayHaveIsRefused() { + problem := s.refused(map[string]string{"knowledge/big.md": strings.Repeat("a", MaxFileBytes+1)}) + + s.Equal("knowledge/big.md", problem.File) + s.Contains(problem.Message, "a file holds at most 1048576") + + beside := s.parse(map[string]string{"build/app.js": strings.Repeat("a", MaxFileBytes+1)}) + s.Equal([]string{"build/app.js"}, beside.Ignored, "a file that is no part of the directory is not held to its limits") +} + +func (s *ParseSuite) TestADirectoryOverTheSizeOneMayHaveIsRefused() { + held := map[string]string{} + for _, name := range []string{"a", "b", "c", "d", "e", "f", "g", "h", "i"} { + held["knowledge/"+name+".md"] = strings.Repeat("a", MaxFileBytes) + } + + s.Contains(s.refused(held).Message, "one holds at most 8388608") +} + +func (s *ParseSuite) TestTheHashIsOfTheFilesWhateverOrderTheyComeIn() { + one := []File{{Path: "agent.yaml", Content: "name: jean\n"}, {Path: "instructions.md", Content: "You are Jean."}} + other := []File{one[1], one[0]} + + s.Equal(Hash(one), Hash(other)) + // Worked out apart from Hash: sha256 of "10:agent.yaml11:name: jean\n15:instructions.md13:You are Jean.". + s.Equal("109673bcfd26cdcb63ce006ccac2c90af08d13cbc25d11ee36f4c0243f5831d5", Hash(one)) + s.NotEqual(Hash(one), Hash([]File{one[0], {Path: "instructions.md", Content: "You are Joan."}})) + s.NotEqual(Hash([]File{{Path: "a", Content: "bc"}}), Hash([]File{{Path: "ab", Content: "c"}}), "a path does not run into its content") + s.NotEqual(Hash([]File{{Path: "a", Content: "b\x00c\x00d"}}), Hash([]File{{Path: "a", Content: "b"}, {Path: "c", Content: "d"}}), + "nor one file into the next, whatever bytes it holds") + s.NotEqual(Hash(one, "ui", "1"), Hash(one, "ui1"), "nor what is synced beside the files") +} + +func (s *ParseSuite) TestASettingIsLocatedWhereTheFileSaysIt() { + directory := s.parse(map[string]string{AgentFile: "name: jean\ngreeting:\n mode: sung\nchat_channels:\n - type: team\n - type: support\n answer: sometimes\n"}) + + line, column := directory.Locate("greeting.mode") + s.Equal([]int{3, 9}, []int{line, column}) + line, column = directory.Locate("chat_channels[1].answer") + s.Equal([]int{7, 13}, []int{line, column}) + line, column = directory.Locate("greeting.text") + s.Equal([]int{2, 1}, []int{line, column}, "a setting the file leaves out is found at the one above it") + line, column = directory.Locate("left_out_connectors[0].name") + s.Equal([]int{1, 1}, []int{line, column}) +} + +func (s *ParseSuite) TestTheDirectoryIsTheFilesOfTheFormatWhateverElseIsSent() { + alone := s.parse(map[string]string{"instructions.md": "Be brief.\n", "skills/think.md": "---\ndescription: Think\n---\nReason.\n"}) + among := s.parse(map[string]string{ + "instructions.md": "Be brief.\n", "skills/think.md": "---\ndescription: Think\n---\nReason.\n", + "README.md": "# Jean\n", "src/main.go": "package main\n", ".agent_sync": "{}", "node_modules/x/index.js": "x", + }) + + s.Equal(alone.Files, among.Files) + s.Equal([]string{"agent.yaml", "instructions.md", "skills/think.md"}, []string{among.Files[0].Path, among.Files[1].Path, among.Files[2].Path}) + s.Equal(Hash(alone.Files), Hash(among.Files), "so every client hashes one folder the same, whatever it sends beside it") + s.Equal([]string{"README.md", "src/main.go"}, among.Ignored) +} + +func (s *ParseSuite) TestTheDirectoryComesBackBesideItsProblemsSoMoreCanBeSaidOfIt() { + directory, err := Parse(files(map[string]string{AgentFile: "name: jean\nmode: banana\nllmm: llm-fast\n"})) + + s.Require().Error(err) + s.Require().NotNil(directory) + s.Equal("banana", directory.Settings.Mode) +} + +func (s *ParseSuite) TestTwoSkillsOneNameAreRefused() { + problem := s.refused(map[string]string{ + "skills/a.md": "---\nname: refund\ndescription: One\n---\nRead the policy.\n", + "skills/b/SKILL.md": "---\nname: refund\ndescription: Two\n---\nRead the policy.\n", + }) + + s.Equal("skills/b/SKILL.md", problem.File) + s.Contains(problem.Message, `skill "refund" is also declared in skills/a.md`) +} + +func (s *ParseSuite) TestASkillsBodyAndValuesAreReadAsWritten() { + skill := s.parse(map[string]string{ + "skills/think.md": "---\ndescription: Say \"hello\"\nname: 'think'\n---\n- First.\n- Second.\n", + }).Skills[0] + + s.Equal(`Say "hello"`, skill.Description, "a quote that closes the value is part of it unless one opens it") + s.Equal("think", skill.Name) + s.Equal("- First.\n- Second.", skill.Instructions, "the body starts after the --- line, bullets and all") +} + +func (s *ParseSuite) TestFrontmatterEndsAtALineThatIsThreeDashesAlone() { + skill := s.parse(map[string]string{ + "skills/think.md": "---\ndescription: Think --- carefully\n---\n---\nAfter a rule.\n", + }).Skills[0] + + s.Equal("Think --- carefully", skill.Description) + s.Equal("---\nAfter a rule.", skill.Instructions) +} diff --git a/acceleration/internal/agentdir/render.go b/acceleration/internal/agentdir/render.go new file mode 100644 index 0000000000..33201f9d6c --- /dev/null +++ b/acceleration/internal/agentdir/render.go @@ -0,0 +1,390 @@ +package agentdir + +import ( + "bytes" + "fmt" + "maps" + "regexp" + "slices" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +// Render writes a directory as its files, in path order. The output is canonical: agent.yaml's +// keys in the order Settings has them, what is empty left out, a connector that says only its +// name written as the name alone, and UI files at their default paths. Parse reads back what +// was rendered, apart from Description and Ignored, which are not written, and from what +// unwritten says, each a sentence about something the format cannot hold as it is. +func Render(directory *Directory) (files []File, unwritten []string) { + settings := directory.Settings + if directory.UI != nil { + ui := directory.UI.Settings + ui.Components, ui.Blueprints = "", "" + settings.UI = &ui + } + files = []File{{AgentFile, encode(settingsNode(settings))}} + add := func(file, content string) { + if content != "" { + files = append(files, File{file, content}) + } + } + add(InstructionsFile, ended(directory.Instructions)) + add(GuardrailFile, ended(directory.Guardrail)) + if directory.UI != nil { + add(UIComponentsFile, directory.UI.Components) + add(UIBlueprintsFile, directory.UI.Blueprints) + } + folders := map[string]bool{} + for _, skill := range directory.Skills { + // A folder of its own on every file system, ones that fold case included. + folder := skill.Name + for number := 1; !skillFolderName.MatchString(folder) || folders[strings.ToLower(folder)]; number++ { + folder = fmt.Sprintf("skill-%d", number) + } + folders[strings.ToLower(folder)] = true + at := SkillsDir + "/" + folder + "/" + add(at+SkillFile, skillFile(skill, folder != skill.Name)) + // Frontmatter is read a line at a time, so a value is one line. + if strings.ContainsAny(skill.Name+skill.Description, "\r\n") { + unwritten = append(unwritten, fmt.Sprintf("The skill %s has a name or a description over several lines, which a "+ + "SKILL.md's frontmatter cannot hold, so it is written on one line.", oneLine(skill.Name))) + } + for _, file := range slices.Sorted(maps.Keys(skill.Files)) { + if file == SkillFile || !ValidPath(file) || hidden(file) { + unwritten = append(unwritten, fmt.Sprintf("The skill %s has a file called %s, which a skill folder cannot "+ + "hold, so it is left out and a sync of these files removes it.", oneLine(skill.Name), file)) + continue + } + add(at+file, skill.Files[file]) + } + } + for _, document := range directory.Knowledge { + add(KnowledgeDir+"/"+document.Source, document.Text) + } + if len(directory.KnowledgeURLs) > 0 { + pages := sequence() + for _, page := range directory.KnowledgeURLs { + if page.Title == "" && page.Description == "" && page.RefreshHours == 0 { + pages.Content = append(pages.Content, scalar(page.URL)) + continue + } + pages.Content = append(pages.Content, mapping( + pair{"url", scalar(page.URL)}, pair{"title", text(page.Title)}, + pair{"description", text(page.Description)}, pair{"refresh_hours", number(page.RefreshHours)})) + } + add(KnowledgeURLsFile, encode(pages)) + } + if len(directory.Simulations) > 0 { + simulations := sequence() + for _, simulation := range directory.Simulations { + simulations.Content = append(simulations.Content, mapping( + pair{"name", scalar(simulation.Name)}, pair{"scenario", scalar(simulation.Scenario)}, + pair{"assertion", scalar(simulation.Assertion)}, pair{"mode", text(simulation.Mode)}, + pair{"variations", number(simulation.Variations)}, pair{"max_turns", number(simulation.MaxTurns)}, + pair{"caller_target", text(simulation.CallerTarget)}, pair{"judge_target", text(simulation.JudgeTarget)}, + pair{"caller_stt", text(simulation.CallerSTT)}, pair{"caller_tts", text(simulation.CallerTTS)}, + pair{"caller_voice", text(simulation.CallerVoice)}, pair{"tags", labels(simulation.Tags)})) + } + add(SimulationsDir+"/simulations.yaml", encode(simulations)) + } + slices.SortFunc(files, func(a, b File) int { return strings.Compare(a.Path, b.Path) }) + return files, unwritten +} + +// skillFolderName is a skill name that is also a folder name on every file system. +var skillFolderName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$`) + +// skillFile writes a SKILL.md. Its frontmatter is read a line at a time, as a key and its +// value, so a value is written on one line, in quotes when it would otherwise read back as +// something else. The instructions follow the closing --- as they are. +func skillFile(skill Skill, named bool) string { + var file strings.Builder + file.WriteString("---\n") + if named { + file.WriteString("name: " + frontmatterValue(skill.Name) + "\n") + } + file.WriteString("description: " + frontmatterValue(skill.Description) + "\n") + if skill.Deadline > 0 { + file.WriteString("deadline: " + Duration(skill.Deadline) + "\n") + } + if skill.CaptureVideo { + file.WriteString("capture_video: true\n") + } + file.WriteString("---\n" + ended(skill.Instructions)) + return file.String() +} + +// frontmatterValue is a value as unquoted reads it back: quoted when it has space at an end, +// or a pair of quotes around it that would be taken off. +func frontmatterValue(value string) string { + value = strings.NewReplacer("\r\n", " ", "\n", " ", "\r", " ").Replace(value) + if value != strings.TrimSpace(value) || unquoted(value) != value { + return `"` + value + `"` + } + return value +} + +func oneLine(text string) string { + return strings.Join(strings.Fields(text), " ") +} + +// Duration writes a duration the way a person would: 30m, not 30m0s. +func Duration(duration time.Duration) string { + written := duration.String() + if strings.HasSuffix(written, "m0s") { + written = strings.TrimSuffix(written, "0s") + } + if strings.HasSuffix(written, "h0m") { + written = strings.TrimSuffix(written, "0m") + } + return written +} + +func settingsNode(s Settings) *yaml.Node { + root := mapping( + pair{"name", text(s.Name)}, pair{"mode", text(s.Mode)}, pair{"region", text(s.Region)}, + pair{"stt", text(s.STT)}, pair{"tts", text(s.TTS)}, pair{"sts", optional(s.STS)}, + pair{"voice", text(s.Voice)}, pair{"llm", text(s.LLM)}, pair{"harness", text(s.Harness)}, + pair{"role", text(s.Role)}, pair{"subagent", text(s.Subagent)}, pair{"search", text(s.Search)}, + pair{"image", optional(s.Image)}, + ) + set := func(key string, value *yaml.Node) { + if value != nil { + root.Content = append(root.Content, scalar(key), value) + } + } + if s.Greeting != nil { + set("greeting", mapping(pair{"text", scalar(s.Greeting.Text)}, pair{"mode", text(s.Greeting.Mode)})) + } + set("sandbox", text(s.Sandbox)) + if options := s.SandboxOptions; options != nil { + var timeout *yaml.Node + if options.Timeout > 0 { + timeout = scalar(Duration(options.Timeout)) + } + set("sandbox_options", filled(mapping( + pair{"image", text(options.Image)}, pair{"setup", list(options.Setup)}, pair{"timeout", timeout}, + pair{"cpu", number(options.CPU)}, pair{"memory_gb", number(options.MemoryGB)}, + pair{"disk_gb", number(options.DiskGB)}, pair{"network", flag(options.Network)}, + pair{"allowed_domains", list(options.AllowedDomains)}, + pair{"network_allow_list", list(options.NetworkAllowList)}))) + } + if s.Connectors != nil { + connectors := sequence() + for _, connector := range *s.Connectors { + entry := mapping( + pair{"name", scalar(connector.Name)}, pair{"connector", text(connector.Connector)}, + pair{"tools", optionalList(connector.Tools)}, pair{"connection", optional(connector.Connection)}, + pair{"required", optionalFlag(connector.Required)}, pair{"sandbox", flag(connector.Sandbox)}, + pair{"require_approval", optionalList(connector.RequireApproval)}, + pair{"loading", text(connector.Loading)}, pair{"output_retention", text(connector.OutputRetention)}) + if len(entry.Content) == 2 { + entry = scalar(connector.Name) + } + connectors.Content = append(connectors.Content, entry) + } + set("connectors", connectors) + } + if s.Tools != nil { + groups := sequence() + for _, group := range *s.Tools { + groups.Content = append(groups.Content, mapping( + pair{"name", scalar(group.Name)}, pair{"loading", text(group.Loading)}, + pair{"tools", list(group.Tools)}, pair{"output_retention", text(group.OutputRetention)})) + } + set("tools", groups) + } + if channels := s.Channels; channels != nil { + line := func(number string) *yaml.Node { return filled(mapping(pair{"number", text(number)})) } + set("channels", filled(mapping( + pair{"whatsapp", line(channels.WhatsApp)}, pair{"sms", line(channels.SMS)}, + pair{"imessage", line(channels.IMessage)}, pair{"identity", text(channels.Identity)}))) + } + if s.ChatChannels != nil { + channels := sequence() + for _, channel := range *s.ChatChannels { + channels.Content = append(channels.Content, mapping(pair{"type", scalar(channel.Type)}, pair{"answer", text(channel.Answer)})) + } + set("chat_channels", channels) + } + if scheduling := s.Scheduling; scheduling != nil { + var maximum *yaml.Node + if scheduling.MaxTasksPerUser != nil { + maximum = scalar(*scheduling.MaxTasksPerUser) + } + set("scheduling", filled(mapping( + pair{"enabled", optionalFlag(scheduling.Enabled)}, pair{"max_tasks_per_user", maximum}, + pair{"default_timezone", text(scheduling.DefaultTimezone)}))) + } + if calls := s.Calls; calls != nil { + var destinations *yaml.Node + if len(calls.Transfer.Destinations) > 0 { + destinations = sequence() + for _, destination := range calls.Transfer.Destinations { + destinations.Content = append(destinations.Content, mapping( + pair{"name", scalar(destination.Name)}, pair{"number", scalar(destination.Number)}, + pair{"when", text(destination.When)}, pair{"warm", flag(destination.Warm)})) + } + } + set("calls", filled(mapping( + pair{"end_call", filled(mapping(pair{"enabled", optionalFlag(calls.EndCall.Enabled)}, pair{"when", text(calls.EndCall.When)}))}, + pair{"press", filled(mapping(pair{"enabled", optionalFlag(calls.Press.Enabled)}))}, + pair{"transfer", filled(mapping(pair{"enabled", optionalFlag(calls.Transfer.Enabled)}, pair{"destinations", destinations}))}))) + } + if floor := s.FloorControl; floor != nil { + var wait *yaml.Node + if floor.MaxWaitMs != nil { + wait = scalar(*floor.MaxWaitMs) + } + set("floor_control", mapping(pair{"model", optional(floor.Model)}, pair{"max_wait_ms", wait})) + } + if s.Agents != nil { + agents := sequence() + for _, agent := range *s.Agents { + agents.Content = append(agents.Content, mapping( + pair{"config", scalar(agent.Config)}, pair{"tool", scalar(agent.Tool)}, + pair{"description", text(agent.Description)}, pair{"timeout_ms", number(agent.TimeoutMs)}, + pair{"max_tool_rounds", number(agent.MaxToolRounds)})) + } + set("agents", agents) + } + set("keyterms", list(s.Keyterms)) + set("tags", labels(s.Tags)) + if video := s.Video; video != nil { + frames := video.MaxFrames + if frames == 1 { + frames = 0 + } + set("video", filled(mapping(pair{"source", text(video.Source)}, pair{"max_frames", number(frames)}))) + } + if dispatch := s.Dispatch; dispatch != nil { + set("dispatch", filled(mapping(pair{"incoming_call", text(dispatch.IncomingCall)}, pair{"text", text(dispatch.Text)}))) + } + if ui := s.UI; ui != nil { + set("ui", mapping( + pair{"format", text(ui.Format)}, pair{"keep", list(ui.Keep)}, pair{"patch_mode", flag(ui.PatchMode)}, + pair{"voice_ui", flag(ui.VoiceUI)}, pair{"rules", list(ui.Rules)})) + } + return root +} + +// pair is one key of a mapping being written. A nil value leaves the key out. +type pair struct { + key string + value *yaml.Node +} + +func mapping(pairs ...pair) *yaml.Node { + node := &yaml.Node{Kind: yaml.MappingNode} + for _, pair := range pairs { + if pair.value != nil { + node.Content = append(node.Content, scalar(pair.key), pair.value) + } + } + return node +} + +// filled is a mapping that says something, or nil for one with no keys. +func filled(node *yaml.Node) *yaml.Node { + if len(node.Content) == 0 { + return nil + } + return node +} + +func sequence() *yaml.Node { + return &yaml.Node{Kind: yaml.SequenceNode} +} + +// scalar is a value as YAML writes it, quoted where it would otherwise read as something else. +func scalar(value any) *yaml.Node { + node := &yaml.Node{} + if err := node.Encode(value); err != nil { + panic(fmt.Sprintf("agentdir: encoding %v: %v", value, err)) + } + return node +} + +func text(value string) *yaml.Node { + if value == "" { + return nil + } + return scalar(value) +} + +func optional(value *string) *yaml.Node { + if value == nil { + return nil + } + return scalar(*value) +} + +func number(value int) *yaml.Node { + if value == 0 { + return nil + } + return scalar(value) +} + +func flag(value bool) *yaml.Node { + if !value { + return nil + } + return scalar(value) +} + +func optionalFlag(value *bool) *yaml.Node { + if value == nil { + return nil + } + return scalar(*value) +} + +func list(values []string) *yaml.Node { + if len(values) == 0 { + return nil + } + return optionalList(&values) +} + +func optionalList(values *[]string) *yaml.Node { + if values == nil { + return nil + } + node := sequence() + for _, value := range *values { + node.Content = append(node.Content, scalar(value)) + } + return node +} + +func labels(values map[string]string) *yaml.Node { + if len(values) == 0 { + return nil + } + node := &yaml.Node{Kind: yaml.MappingNode} + for _, key := range slices.Sorted(maps.Keys(values)) { + node.Content = append(node.Content, scalar(key), scalar(values[key])) + } + return node +} + +func encode(node *yaml.Node) string { + var written bytes.Buffer + encoder := yaml.NewEncoder(&written) + encoder.SetIndent(2) + if err := encoder.Encode(node); err != nil { + panic(fmt.Sprintf("agentdir: writing yaml: %v", err)) + } + return written.String() +} + +// ended is text with the one newline a file ends with, or empty for none. +func ended(text string) string { + if text == "" { + return "" + } + return text + "\n" +} diff --git a/acceleration/internal/agentdir/render_test.go b/acceleration/internal/agentdir/render_test.go new file mode 100644 index 0000000000..c74c1e7674 --- /dev/null +++ b/acceleration/internal/agentdir/render_test.go @@ -0,0 +1,356 @@ +package agentdir + +import ( + "strings" + "testing" + "time" + + "github.com/stretchr/testify/suite" +) + +type RenderSuite struct { + suite.Suite +} + +func TestRenderSuite(t *testing.T) { + suite.Run(t, new(RenderSuite)) +} + +// frontDesk is an agent that sets everything agent.yaml can say. +func frontDesk() *Directory { + yes, no := true, false + sts, image, connection := "", "image-fast", "conn_42" + model, wait, tasks := "stream/chorus-asr", 800, 10 + return &Directory{ + Settings: Settings{ + Name: "front-desk", Mode: "voice", Region: "eu", STT: "deepgram/nova-3", TTS: "elevenlabs/eleven_flash_v2_5", + STS: &sts, Voice: "custom:Jean", LLM: "llm-fast", Role: "agent_moderator", Subagent: "llm-thinking", + Search: "search-fast", Image: &image, + Greeting: &Greeting{Text: "Hi, how can I help?", Mode: "variation"}, + Sandbox: "daytona", + SandboxOptions: &SandboxOptions{ + Image: "python:3.12-slim", Setup: []string{"pip install pandas", "apt-get install -y jq"}, + Timeout: 90 * time.Second, CPU: 2, MemoryGB: 4, AllowedDomains: []string{"api.example.com"}, + }, + Connectors: &[]Connector{ + {Name: "github"}, + { + Name: "tickets", Connector: "linear", Tools: &[]string{"search", "linear_*"}, Connection: &connection, + Required: &yes, Sandbox: true, RequireApproval: &[]string{"create_*"}, Loading: "deferred", OutputRetention: "12h", + }, + }, + Tools: &[]ToolGroup{{Name: "booking", Loading: "summary", Tools: []string{"lookup_booking", "cancel_booking"}, OutputRetention: "30d"}}, + Channels: &Channels{WhatsApp: "+15551230000", SMS: "+15551230001", Identity: "link"}, + ChatChannels: &[]ChatChannel{{Type: "team", Answer: "mentioned"}, {Type: "support"}}, + Scheduling: &Scheduling{Enabled: &yes, MaxTasksPerUser: &tasks, DefaultTimezone: "Europe/Amsterdam"}, + Calls: &Calls{ + EndCall: EndCall{Enabled: &yes, When: "The caller says goodbye."}, + Press: CallTool{Enabled: &no}, + Transfer: Transfer{Destinations: []TransferDestination{ + {Name: "billing", Number: "+15551234567", When: "Questions about an invoice: refunds, too.", Warm: true}, + {Name: "sales", Number: "+15557654321"}, + }}, + }, + FloorControl: &FloorControl{Model: &model, MaxWaitMs: &wait}, + Agents: &[]ChildAgent{{Config: "billing", Tool: "ask_billing", Description: "Invoices.", TimeoutMs: 5000, MaxToolRounds: -1}}, + Keyterms: []string{"Stream", "getstream.io", "10DLC"}, + Tags: map[string]string{"team": "yes", "agent": "front-desk"}, + Video: &Video{Source: "screen", MaxFrames: 4}, + Dispatch: &Dispatch{IncomingCall: "enabled"}, + }, + Instructions: "You answer the phone.", + Guardrail: "---\ntype: llm\n---\nNo medical advice.", + UI: &UI{ + Settings: UISettings{Format: "openui", Keep: []string{"CardHeader"}, VoiceUI: true, Rules: []string{"Be brief."}}, + Blueprints: "- name: booking\n when: booking a table\n order: [CardHeader]\n", + }, + Skills: []Skill{ + {Name: "refunds", Description: "Work out a refund", Instructions: "Read the policy.", Deadline: 2 * time.Minute, + CaptureVideo: true, Files: map[string]string{"scripts/total.py": "print(1)\n"}}, + {Name: "what is owed?", Description: "Add it up", Instructions: "Sum the invoices."}, + }, + Knowledge: []Document{{Source: "plans/pro.md", Text: "Pro costs more.\n"}}, + KnowledgeURLs: []KnowledgeURL{{URL: "https://example.com/pricing"}, {URL: "https://example.com/plans", Title: "Plans", RefreshHours: 24}}, + Simulations: []Simulation{ + {Name: "lunch", Scenario: "Order a turkey club,\nthen swap it.", Assertion: "One veggie wrap.", Mode: "audio", Variations: 3, Tags: map[string]string{"suite": "smoke"}}, + }, + } +} + +// Written by hand: Settings' key order, what is empty left out, a connector that says only its +// name as the name alone, and quotes only where YAML would read the text as something else. +const frontDeskYAML = `name: front-desk +mode: voice +region: eu +stt: deepgram/nova-3 +tts: elevenlabs/eleven_flash_v2_5 +sts: "" +voice: custom:Jean +llm: llm-fast +role: agent_moderator +subagent: llm-thinking +search: search-fast +image: image-fast +greeting: + text: Hi, how can I help? + mode: variation +sandbox: daytona +sandbox_options: + image: python:3.12-slim + setup: + - pip install pandas + - apt-get install -y jq + timeout: 1m30s + cpu: 2 + memory_gb: 4 + allowed_domains: + - api.example.com +connectors: + - github + - name: tickets + connector: linear + tools: + - search + - linear_* + connection: conn_42 + required: true + sandbox: true + require_approval: + - create_* + loading: deferred + output_retention: 12h +tools: + - name: booking + loading: summary + tools: + - lookup_booking + - cancel_booking + output_retention: 30d +channels: + whatsapp: + number: "+15551230000" + sms: + number: "+15551230001" + identity: link +chat_channels: + - type: team + answer: mentioned + - type: support +scheduling: + enabled: true + max_tasks_per_user: 10 + default_timezone: Europe/Amsterdam +calls: + end_call: + enabled: true + when: The caller says goodbye. + press: + enabled: false + transfer: + destinations: + - name: billing + number: "+15551234567" + when: 'Questions about an invoice: refunds, too.' + warm: true + - name: sales + number: "+15557654321" +floor_control: + model: stream/chorus-asr + max_wait_ms: 800 +agents: + - config: billing + tool: ask_billing + description: Invoices. + timeout_ms: 5000 + max_tool_rounds: -1 +keyterms: + - Stream + - getstream.io + - 10DLC +tags: + agent: front-desk + team: "yes" +video: + source: screen + max_frames: 4 +dispatch: + incoming_call: enabled +ui: + format: openui + keep: + - CardHeader + voice_ui: true + rules: + - Be brief. +` + +func (s *RenderSuite) rendered(directory *Directory) map[string]string { + held := map[string]string{} + files, unwritten := Render(directory) + s.Empty(unwritten) + for _, file := range files { + held[file.Path] = file.Content + } + return held +} + +func (s *RenderSuite) TestAConfiguredAgentIsWrittenAsTheDirectoryASyncReads() { + held := s.rendered(frontDesk()) + + s.Equal(frontDeskYAML, held[AgentFile]) + s.Equal("You answer the phone.\n", held["instructions.md"]) + s.Equal("---\ntype: llm\n---\nNo medical advice.\n", held["guardrail.md"]) + s.Equal("---\ndescription: Work out a refund\ndeadline: 2m\ncapture_video: true\n---\nRead the policy.\n", held["skills/refunds/SKILL.md"]) + s.Equal("print(1)\n", held["skills/refunds/scripts/total.py"]) + s.Equal("---\nname: what is owed?\ndescription: Add it up\n---\nSum the invoices.\n", held["skills/skill-1/SKILL.md"], + "a name that is no folder name is said in the frontmatter") + s.Equal("Pro costs more.\n", held["knowledge/plans/pro.md"]) + s.Equal("- https://example.com/pricing\n- url: https://example.com/plans\n title: Plans\n refresh_hours: 24\n", held["knowledge/urls.yaml"]) + s.Equal("- name: lunch\n scenario: |-\n Order a turkey club,\n then swap it.\n assertion: One veggie wrap.\n mode: audio\n variations: 3\n tags:\n suite: smoke\n", held["simulations/simulations.yaml"]) + s.Equal("- name: booking\n when: booking a table\n order: [CardHeader]\n", held["ui/blueprints.yaml"]) + s.Len(held, 10, "nothing else is written") +} + +func (s *RenderSuite) TestTheFilesComeInPathOrder() { + var paths []string + files, _ := Render(frontDesk()) + for _, file := range files { + paths = append(paths, file.Path) + } + + s.IsIncreasing(paths) +} + +func (s *RenderSuite) TestAnAgentThatSetsNothingIsItsNameAlone() { + held := s.rendered(&Directory{Settings: Settings{Name: "support", Mode: "voice", Calls: &Calls{}, Video: &Video{MaxFrames: 1}}}) + + s.Equal(map[string]string{AgentFile: "name: support\nmode: voice\n"}, held) +} + +func (s *RenderSuite) TestAnEmptyListOrMappingThatMeansSomethingIsWritten() { + held := s.rendered(&Directory{ + Settings: Settings{Name: "support", Connectors: &[]Connector{}, FloorControl: &FloorControl{}}, + UI: &UI{}, + }) + + s.Equal("name: support\nconnectors: []\nfloor_control: {}\nui: {}\n", held[AgentFile]) +} + +func (s *RenderSuite) TestTextYAMLWouldReadAsSomethingElseIsQuoted() { + for _, text := range []string{"yes", "No", "true", "null", "~", "123", "1e3", "+15551234567", "- item", "a: b", "a #b", "#b", "*anchor", "[x]", "{x}", " lead", "trail ", "two\nlines", ""} { + held := s.rendered(&Directory{Settings: Settings{Name: "support", Greeting: &Greeting{Text: text}}}) + + read, err := Parse([]File{{Path: AgentFile, Content: held[AgentFile]}}) + s.Require().NoError(err, held[AgentFile]) + s.Equal(text, read.Settings.Greeting.Text, held[AgentFile]) + } +} + +func (s *RenderSuite) TestADurationIsWrittenAsAPersonWould() { + s.Equal("30m", Duration(30*time.Minute)) + s.Equal("30s", Duration(30*time.Second)) + s.Equal("1m30s", Duration(90*time.Second)) + s.Equal("1.5s", Duration(1500*time.Millisecond)) + s.Equal("2h", Duration(2*time.Hour)) +} + +func (s *RenderSuite) TestWhatIsRenderedReadsBackAsWhatItWas() { + written := frontDesk() + + files, _ := Render(written) + read, err := Parse(files) + s.Require().NoError(err) + + s.Equal(files, read.Files, "every file written is one the directory is read from") + read.Settings.UI, read.declaration, read.Files = nil, nil, nil + read.UI.Instructions = "" + s.Equal(written, read) +} + +func (s *RenderSuite) TestRenderingWhatWasReadTwiceChangesNothing() { + once, _ := Render(frontDesk()) + read, err := Parse(once) + s.Require().NoError(err) + read.Settings.UI = nil + + again, _ := Render(read) + s.Equal(once, again) +} + +// skillOf writes one skill and reads it back. +func (s *RenderSuite) skillOf(skill Skill) Skill { + files, _ := Render(&Directory{Settings: Settings{Name: "support"}, Skills: []Skill{skill}}) + read, err := Parse(files) + s.Require().NoError(err, "%v", files) + s.Require().Len(read.Skills, 1) + return read.Skills[0] +} + +func (s *RenderSuite) TestASkillsInstructionsReadBackAsTheyWereWrittenWhateverTheyStartWith() { + for _, instructions := range []string{ + "- Read the policy.\n- Then answer.", + "---\n\nA rule, then the steps.", + "--flag is how the script is run.", + "Steps\n---\nOne.", + } { + skill := Skill{Name: "refunds", Description: "Work out a refund", Instructions: instructions} + + s.Equal(skill, s.skillOf(skill)) + } +} + +func (s *RenderSuite) TestASkillsDescriptionReadsBackAsItWasWrittenWhateverQuotesItHolds() { + for _, description := range []string{ + `Say "hello"`, `"Quoted whole"`, `'single'`, `It's the customer's`, ` padded `, `"`, `a: b # c`, `ends with a quote"`, + } { + skill := Skill{Name: "what is owed?", Description: description, Instructions: "Sum the invoices."} + + s.Equal(skill, s.skillOf(skill), description) + } +} + +func (s *RenderSuite) TestASkillDescriptionOverSeveralLinesIsWrittenOnOneAndSaidToBe() { + files, unwritten := Render(&Directory{Settings: Settings{Name: "support"}, Skills: []Skill{ + {Name: "refunds", Description: "Work out a refund.\nAsk first.", Instructions: "Read the policy."}, + }}) + + s.Equal([]string{"The skill refunds has a name or a description over several lines, which a SKILL.md's frontmatter cannot hold, so it is written on one line."}, unwritten) + read, err := Parse(files) + s.Require().NoError(err) + s.Equal("Work out a refund. Ask first.", read.Skills[0].Description) +} + +func (s *RenderSuite) TestSkillFilesAFolderCannotHoldAreLeftOutAndSaidToBe() { + files, unwritten := Render(&Directory{Settings: Settings{Name: "support"}, Skills: []Skill{{ + Name: "pdf", Description: "Fill a form", Instructions: "Run it.", + Files: map[string]string{"SKILL.md": "another", ".hidden.md": "x", "__pycache__/x.md": "x", "../up.md": "x", "fill.py": "print()\n"}, + }}}) + + var paths []string + for _, file := range files { + paths = append(paths, file.Path) + } + s.Equal([]string{"agent.yaml", "skills/pdf/SKILL.md", "skills/pdf/fill.py"}, paths) + s.Len(unwritten, 4, "%v", unwritten) + s.Contains(unwritten[0], "The skill pdf has a file called ../up.md, which a skill folder cannot hold") + read, err := Parse(files) + s.Require().NoError(err, "what is written is a directory a sync reads") + s.Equal(map[string]string{"fill.py": "print()\n"}, read.Skills[0].Files) +} + +func (s *RenderSuite) TestSkillsWhoseNamesWouldShareAFolderEachGetTheirOwn() { + skill := func(name string) Skill { return Skill{Name: name, Description: "d", Instructions: "i"} } + written := []Skill{skill("Alpha"), skill("alpha"), skill("a b"), skill("skill-1"), skill("c d")} + + files, unwritten := Render(&Directory{Settings: Settings{Name: "support"}, Skills: written}) + + s.Empty(unwritten) + folded := map[string]bool{} + for _, file := range files[1:] { + s.False(folded[strings.ToLower(file.Path)], "%s is written twice on a file system that folds case", file.Path) + folded[strings.ToLower(file.Path)] = true + } + read, err := Parse(files) + s.Require().NoError(err) + s.ElementsMatch(written, read.Skills, "every skill reads back under its own name") +} diff --git a/acceleration/internal/agentdir/settings.go b/acceleration/internal/agentdir/settings.go new file mode 100644 index 0000000000..4ea73b0c20 --- /dev/null +++ b/acceleration/internal/agentdir/settings.go @@ -0,0 +1,424 @@ +package agentdir + +import ( + "slices" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +// Settings is what agent.yaml declares: what the agent is run with. A setting the file +// leaves out is empty or nil here, and leaves whatever the stored config has. +type Settings struct { + Name string + // Description is for whoever reads the file. Nothing is stored of it. + Description string + Mode string + Region string + STT string + TTS string + // STS and Image are nil when the file says nothing, and empty when it turns them off. + STS *string + Voice string + LLM string + Harness string + Role string + Subagent string + Search string + Image *string + Greeting *Greeting + Sandbox string + SandboxOptions *SandboxOptions + // Connectors, Tools, ChatChannels and Agents are nil when the file says nothing, which + // leaves the stored ones, and empty when it lists none, which removes them. + Connectors *[]Connector + Tools *[]ToolGroup + Channels *Channels + ChatChannels *[]ChatChannel + Scheduling *Scheduling + Calls *Calls + FloorControl *FloorControl + Agents *[]ChildAgent + Keyterms []string + Tags map[string]string + Video *Video + Dispatch *Dispatch + UI *UISettings +} + +type Greeting struct { + Text string + Mode string +} + +type SandboxOptions struct { + Image string + Setup []string + Timeout time.Duration + CPU int + MemoryGB int + DiskGB int + Network bool + AllowedDomains []string + NetworkAllowList []string +} + +// Connector is one connector the agent binds: the alias alone, or a mapping naming it. +type Connector struct { + Name string + // Connector is the connector id. Empty means the name. + Connector string + // Tools are names or patterns. Nil is every tool. + Tools *[]string + // Connection is an id or a label of one of the app's connections. Nil is a session binding. + Connection *string + Required *bool + Sandbox bool + RequireApproval *[]string + Loading string + OutputRetention string +} + +type ToolGroup struct { + Name string + Loading string + Tools []string + OutputRetention string +} + +type Channels struct { + WhatsApp string + SMS string + IMessage string + Identity string +} + +type ChatChannel struct { + Type string + Answer string +} + +type Scheduling struct { + Enabled *bool + MaxTasksPerUser *int + DefaultTimezone string +} + +type Calls struct { + EndCall EndCall + Press CallTool + Transfer Transfer +} + +type CallTool struct { + Enabled *bool +} + +type EndCall struct { + Enabled *bool + When string +} + +type Transfer struct { + Enabled *bool + Destinations []TransferDestination +} + +type TransferDestination struct { + Name string + Number string + When string + Warm bool +} + +type FloorControl struct { + Model *string + MaxWaitMs *int +} + +type ChildAgent struct { + Config string + Tool string + Description string + TimeoutMs int + MaxToolRounds int +} + +type Video struct { + Source string + MaxFrames int +} + +type Dispatch struct { + IncomingCall string + Text string +} + +// retired are the keys agent.yaml no longer reads, each with what replaced it. One that +// declares nothing, a null or an empty list, is let through: it never did anything. +var retired = map[string]string{ + "plugins": "plugins were replaced by connectors, so name the provider under connectors", + "plugin_events": "plugins were replaced by connectors, so name the provider under connectors", + "mcp_servers": "a server named by URL is now a custom connector, so create one for its URL and name it under connectors", +} + +var toolLoadings = []string{"full", "summary", "deferred"} + +// settings reads agent.yaml. +func (r *reader) settings(content string) Settings { + var s Settings + root := r.document(content) + if root == nil { + return s + } + refused := func(key string) field { + return field{key, func(value *yaml.Node) { + if list := resolved(value); list.Kind != yaml.SequenceNode || len(list.Content) > 0 { + r.fail(value, "no longer read: %s", retired[key]) + } + }} + } + r.mapping(root, AgentFile, + field{"name", r.text(&s.Name)}, + field{"description", r.text(&s.Description)}, + field{"mode", r.text(&s.Mode)}, + field{"region", r.text(&s.Region)}, + field{"stt", r.text(&s.STT)}, + field{"tts", r.text(&s.TTS)}, + field{"sts", r.optionalText(&s.STS)}, + field{"voice", r.text(&s.Voice)}, + field{"llm", r.text(&s.LLM)}, + field{"harness", r.text(&s.Harness)}, + field{"role", r.text(&s.Role)}, + field{"subagent", r.text(&s.Subagent)}, + field{"search", r.text(&s.Search)}, + field{"image", r.optionalText(&s.Image)}, + field{"greeting", func(value *yaml.Node) { + s.Greeting = &Greeting{} + // The text alone, as the getstream CLI has always read it, or a mapping with its mode. + if resolved(value).Kind == yaml.ScalarNode { + s.Greeting.Text = resolved(value).Value + return + } + r.mapping(value, "greeting", field{"text", r.text(&s.Greeting.Text)}, field{"mode", r.text(&s.Greeting.Mode)}) + }}, + field{"sandbox", r.text(&s.Sandbox)}, + field{"sandbox_options", func(value *yaml.Node) { s.SandboxOptions = r.sandboxOptions(value) }}, + field{"connectors", func(value *yaml.Node) { + connectors := []Connector{} + if r.each(value, func(item *yaml.Node) { connectors = append(connectors, r.connector(item)) }) { + s.Connectors = &connectors + } + }}, + field{"tools", func(value *yaml.Node) { s.Tools = r.toolGroups(value) }}, + field{"channels", func(value *yaml.Node) { + s.Channels = &Channels{} + line := func(into *string) func(*yaml.Node) { + return func(value *yaml.Node) { r.mapping(value, "a channel", field{"number", r.text(into)}) } + } + r.mapping(value, "channels", + field{"whatsapp", line(&s.Channels.WhatsApp)}, + field{"sms", line(&s.Channels.SMS)}, + field{"imessage", line(&s.Channels.IMessage)}, + field{"identity", r.text(&s.Channels.Identity)}) + }}, + field{"chat_channels", func(value *yaml.Node) { + channels := []ChatChannel{} + if r.each(value, func(item *yaml.Node) { + var channel ChatChannel + r.mapping(item, "a chat channel", field{"type", r.text(&channel.Type)}, field{"answer", r.text(&channel.Answer)}) + channels = append(channels, channel) + }) { + s.ChatChannels = &channels + } + }}, + field{"scheduling", func(value *yaml.Node) { + s.Scheduling = &Scheduling{} + r.mapping(value, "scheduling", + field{"enabled", r.optionalBoolean(&s.Scheduling.Enabled)}, + field{"max_tasks_per_user", r.optionalInteger(&s.Scheduling.MaxTasksPerUser)}, + field{"default_timezone", r.text(&s.Scheduling.DefaultTimezone)}) + }}, + field{"calls", func(value *yaml.Node) { s.Calls = r.calls(value) }}, + field{"floor_control", func(value *yaml.Node) { + s.FloorControl = &FloorControl{} + r.mapping(value, "floor_control", + field{"model", func(value *yaml.Node) { + if value.Kind != yaml.ScalarNode || value.ShortTag() != "!!str" { + r.fail(value, "must be a string, such as stream/chorus-asr") + return + } + s.FloorControl.Model = &value.Value + }}, + field{"max_wait_ms", r.optionalInteger(&s.FloorControl.MaxWaitMs)}) + }}, + field{"agents", func(value *yaml.Node) { + agents := []ChildAgent{} + if r.each(value, func(item *yaml.Node) { + var agent ChildAgent + r.mapping(item, "an agent", + field{"config", r.text(&agent.Config)}, + field{"tool", r.text(&agent.Tool)}, + field{"description", r.text(&agent.Description)}, + field{"timeout_ms", r.integer(&agent.TimeoutMs)}, + field{"max_tool_rounds", r.integer(&agent.MaxToolRounds)}) + agents = append(agents, agent) + }) { + s.Agents = &agents + } + }}, + field{"keyterms", r.list(&s.Keyterms)}, + field{"tags", r.labels(&s.Tags)}, + field{"video", func(value *yaml.Node) { + s.Video = &Video{MaxFrames: 1} + r.mapping(value, "video", + field{"source", r.text(&s.Video.Source)}, + field{"max_frames", func(value *yaml.Node) { + r.integer(&s.Video.MaxFrames)(value) + // Zero reads as one. + s.Video.MaxFrames = max(s.Video.MaxFrames, 1) + if s.Video.MaxFrames < 1 || s.Video.MaxFrames > 8 { + r.fail(value, "must be an integer from 1 to 8") + } + }}) + }}, + field{"dispatch", func(value *yaml.Node) { + s.Dispatch = &Dispatch{} + r.mapping(value, "dispatch", + field{"incoming_call", r.text(&s.Dispatch.IncomingCall)}, + field{"text", r.text(&s.Dispatch.Text)}) + }}, + field{"ui", func(value *yaml.Node) { s.UI = r.uiSettings(value) }}, + // The application's own section, which nothing here reads. + field{"app", func(*yaml.Node) {}}, + refused("plugins"), refused("plugin_events"), refused("mcp_servers"), + ) + return s +} + +func (r *reader) sandboxOptions(node *yaml.Node) *SandboxOptions { + options := &SandboxOptions{} + r.mapping(node, "sandbox_options", + field{"image", r.text(&options.Image)}, + field{"setup", r.list(&options.Setup)}, + field{"timeout", func(value *yaml.Node) { + timeout, err := time.ParseDuration(value.Value) + if err != nil || timeout <= 0 || timeout > 30*time.Minute { + r.fail(value, "must be a duration up to 30m, such as 90s, not %q", value.Value) + return + } + options.Timeout = timeout + }}, + field{"cpu", r.integer(&options.CPU)}, + field{"memory_gb", r.integer(&options.MemoryGB)}, + field{"disk_gb", r.integer(&options.DiskGB)}, + field{"network", r.boolean(&options.Network)}, + field{"allowed_domains", r.list(&options.AllowedDomains)}, + field{"network_allow_list", r.list(&options.NetworkAllowList)}) + return options +} + +func (r *reader) connector(node *yaml.Node) Connector { + var connector Connector + switch node = resolved(node); { + case null(node): + case node.Kind == yaml.ScalarNode: + connector.Name = node.Value + default: + r.mapping(node, "a connector", + field{"name", r.text(&connector.Name)}, + field{"connector", r.text(&connector.Connector)}, + field{"tools", func(value *yaml.Node) { + r.optionalList(&connector.Tools)(value) + if connector.Tools != nil && len(*connector.Tools) == 0 { + r.fail(value, "[] grants nothing; leave tools out for every tool") + } + }}, + field{"connection", func(value *yaml.Node) { + r.optionalText(&connector.Connection)(value) + if connector.Connection != nil && *connector.Connection == "" { + r.fail(value, "must be a connection id or label") + } + }}, + field{"required", r.optionalBoolean(&connector.Required)}, + field{"sandbox", r.boolean(&connector.Sandbox)}, + field{"require_approval", r.optionalList(&connector.RequireApproval)}, + field{"loading", r.loading(&connector.Loading)}, + field{"output_retention", r.text(&connector.OutputRetention)}) + } + if connector.Name == "" { + r.fail(node, "a connector needs a name") + } + return connector +} + +func (r *reader) loading(into *string) func(*yaml.Node) { + return func(value *yaml.Node) { + r.text(into)(value) + if *into != "" && !slices.Contains(toolLoadings, *into) { + r.fail(value, "is %s, not %q", strings.Join(toolLoadings, ", "), *into) + } + } +} + +// toolGroups reads the tools list. The mapping tools was before groups is refused with where +// each of its settings went. +func (r *reader) toolGroups(node *yaml.Node) *[]ToolGroup { + if resolved(node).Kind == yaml.MappingNode { + r.fail(node, "is a list of groups, each with a name and its tools, such as "+ + "- {name: booking, loading: full, tools: [lookup_booking]}; progressive: true is now "+ + "loading: summary, and output_retention moves onto each group and connector") + return nil + } + groups := []ToolGroup{} + if !r.each(node, func(item *yaml.Node) { + var group ToolGroup + if !r.mapping(item, "a tool group", + field{"name", r.text(&group.Name)}, + field{"loading", r.loading(&group.Loading)}, + field{"tools", r.list(&group.Tools)}, + field{"output_retention", r.text(&group.OutputRetention)}) { + return + } + switch { + case group.Name == "": + r.fail(item, "a tool group needs a name") + case len(group.Tools) == 0: + r.fail(item, "tool group %q names no tools", group.Name) + } + groups = append(groups, group) + }) { + return nil + } + return &groups +} + +func (r *reader) calls(node *yaml.Node) *Calls { + calls := &Calls{} + r.mapping(node, "calls", + field{"end_call", func(value *yaml.Node) { + r.mapping(value, "end_call", + field{"enabled", r.optionalBoolean(&calls.EndCall.Enabled)}, + field{"when", r.text(&calls.EndCall.When)}) + }}, + field{"press", func(value *yaml.Node) { + r.mapping(value, "press", field{"enabled", r.optionalBoolean(&calls.Press.Enabled)}) + }}, + field{"transfer", func(value *yaml.Node) { + r.mapping(value, "transfer", + field{"enabled", r.optionalBoolean(&calls.Transfer.Enabled)}, + field{"destinations", func(value *yaml.Node) { + r.each(value, func(item *yaml.Node) { + var destination TransferDestination + r.mapping(item, "a destination", + field{"name", r.text(&destination.Name)}, + field{"number", r.text(&destination.Number)}, + field{"when", r.text(&destination.When)}, + field{"warm", r.boolean(&destination.Warm)}) + calls.Transfer.Destinations = append(calls.Transfer.Destinations, destination) + }) + }}) + }}) + return calls +} diff --git a/acceleration/internal/agentdir/ui.go b/acceleration/internal/agentdir/ui.go new file mode 100644 index 0000000000..bfc9ef45a4 --- /dev/null +++ b/acceleration/internal/agentdir/ui.go @@ -0,0 +1,712 @@ +package agentdir + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + + "gopkg.in/yaml.v3" +) + +var ( + uiPortableName = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) + uiIdentPattern = regexp.MustCompile(`^\$?[A-Za-z_][A-Za-z0-9_]*$`) + uiRefPattern = regexp.MustCompile(`\$?[A-Za-z_][A-Za-z0-9_]*`) +) + +// UI is agent.yaml's ui key with the files it names. +type UI struct { + Settings UISettings + // Components and Blueprints are the two files as written, empty without one. + Components string + Blueprints string + // Instructions is what the three compile to: what teaches the model to answer with UI. + Instructions string +} + +// UISettings is agent.yaml's ui key: the catalog an agent draws with, its own components and +// its layout recipes. +type UISettings struct { + // Format is openui, the default, or a2ui. + Format string + // Keep restricts the built-in catalog to the named components. In OpenUI their required + // child types come along; in A2UI it names the basic catalog's components and functions, + // and nothing else is offered. + Keep []string + // Components is the path of a portable UIComponents.json. Empty is ui/components.json + // when the directory has one. + Components string + // Blueprints is the path of a YAML list of layout recipes. Empty is ui/blueprints.yaml + // when the directory has one. + Blueprints string + // PatchMode has a turn that refines the last UI send only the statements that changed. + PatchMode bool + // VoiceUI streams UI beside a spoken answer on a call. + VoiceUI bool + // Rules are brand or interaction rules appended to what the model is told. + Rules []string +} + +func (r *reader) uiSettings(node *yaml.Node) *UISettings { + settings := &UISettings{} + var format, patch *yaml.Node + r.mapping(node, "ui", + field{"format", func(value *yaml.Node) { format = value; r.text(&settings.Format)(value) }}, + field{"keep", r.list(&settings.Keep)}, + field{"components", r.text(&settings.Components)}, + field{"blueprints", r.text(&settings.Blueprints)}, + field{"patch_mode", func(value *yaml.Node) { patch = value; r.boolean(&settings.PatchMode)(value) }}, + field{"voice_ui", r.boolean(&settings.VoiceUI)}, + field{"rules", r.list(&settings.Rules)}) + if settings.Format != "" && settings.Format != "openui" && settings.Format != "a2ui" { + r.fail(format, "ui.format must be openui or a2ui, not %q", settings.Format) + } + // The router and the apps merge only OpenUI patches; an A2UI reply writes a new surface. + if settings.Format == "a2ui" && settings.PatchMode { + r.fail(patch, "ui.patch_mode is for openui: an A2UI reply writes its UI on a new surface") + } + return settings +} + +// UIPortableComponent is one custom component in ui/components.json. +type UIPortableComponent struct { + Name string `json:"name"` + Description string `json:"description"` + Parameters UIPortableParameters `json:"parameters"` + Events []UIPortableEvent `json:"events"` + Slots []string `json:"slots,omitempty"` +} + +type UIPortableParameters struct { + Type string `json:"type"` + Properties map[string]UIPortableProperty `json:"properties"` + Required []string `json:"required"` + Order []string `json:"x-order"` +} + +type UIPortableProperty struct { + Type string `json:"type"` + Format string `json:"format,omitempty"` + Description string `json:"description,omitempty"` + Enum []string `json:"enum,omitempty"` + // Items is an array's item schema, which the apps read and the prompt leaves out: the + // signature says only `array`. + Items json.RawMessage `json:"items,omitempty"` +} + +type UIPortableEvent struct { + Name string `json:"name"` + Description string `json:"description"` +} + +// UIBlueprint is a canonical component layout recipe in ui/blueprints.yaml. +type UIBlueprint struct { + Name string + When string + Order []string + Rules []string + Example string +} + +type uiBuiltin struct { + Name string + Signature string + MaxArgs int + Deps []string +} + +var uiBuiltins = []uiBuiltin{ + {Name: "Card", Signature: "Card(children: Component[], sources?: {title: string, sourceName: string, url?: string}[]) — Root vertical card container.", MaxArgs: 2}, + {Name: "CardHeader", Signature: "CardHeader(title?: string, subtitle?: string) — Primary card heading and subtitle.", MaxArgs: 2}, + {Name: "InlineHeader", Signature: "InlineHeader(heading: string, description?: string) — Compact section label.", MaxArgs: 2}, + {Name: "TextContent", Signature: `TextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Markdown-capable text block.`, MaxArgs: 2}, + {Name: "Callout", Signature: `Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Highlighted status callout.`, MaxArgs: 4}, + {Name: "Separator", Signature: `Separator(orientation?: "horizontal" | "vertical") — Hairline divider.`, MaxArgs: 2}, + {Name: "TagBlock", Signature: `TagBlock(tags: string[], size?: "sm" | "md" | "lg") — Compact pill row (at most 3 tags).`, MaxArgs: 2}, + {Name: "EntityList", Signature: `EntityList(rows: {left: string, right: string}[], size?: "small" | "default") — Key/value summary rows.`, MaxArgs: 4}, + {Name: "Table", Signature: "Table(columns: Col[]) — Column-oriented read-only data table.", MaxArgs: 1, Deps: []string{"Col"}}, + {Name: "Col", Signature: `Col(label: string, data: (string | number)[], type?: "string" | "number") — Table column.`, MaxArgs: 3}, + {Name: "BarChart", Signature: `BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Categorical bar chart.`, MaxArgs: 6, Deps: []string{"Series"}}, + {Name: "Series", Signature: "Series(category: string, values: number[]) — Named chart data series.", MaxArgs: 2}, + {Name: "PieChart", Signature: `PieChart(labels: string[], values: number[], variant?: "pie" | "donut", appearance?: "circular" | "semiCircular") — Proportional or semicircular gauge chart.`, MaxArgs: 4}, + {Name: "Tabs", Signature: "Tabs(items: TabItem[]) — Multi-view tab container.", MaxArgs: 1, Deps: []string{"TabItem"}}, + {Name: "TabItem", Signature: "TabItem(value: string, trigger: string, content: Component[]) — One tab panel.", MaxArgs: 3}, + {Name: "Steps", Signature: "Steps(items: StepsItem[]) — Sequential timeline steps.", MaxArgs: 1, Deps: []string{"StepsItem"}}, + {Name: "StepsItem", Signature: "StepsItem(title: string, details: string) — Single step entry.", MaxArgs: 2}, + {Name: "ListBlock", Signature: `ListBlock(items: ListItem[], variant?: "number" | "image", size?: "default" | "small") — Structured list.`, MaxArgs: 3, Deps: []string{"ListItem"}}, + {Name: "ListItem", Signature: "ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: ActionExpression) — Clickable list row.", MaxArgs: 5}, + {Name: "Form", Signature: "Form(name: string, buttons: Buttons, fields?: FormControl[]) — Interactive form with explicit Buttons.", MaxArgs: 3, Deps: []string{"FormControl", "Buttons", "Button"}}, + {Name: "FormControl", Signature: "FormControl(label: string, input: Component, hint?: string) — Labeled form field.", MaxArgs: 3}, + {Name: "Select", Signature: "Select(name: string, items: SelectItem[], placeholder?: string, rules?: object, value?: $binding) — Dropdown selector.", MaxArgs: 6, Deps: []string{"SelectItem"}}, + {Name: "SelectItem", Signature: "SelectItem(value: string, label: string) — Option inside Select.", MaxArgs: 2}, + {Name: "Chips", Signature: `Chips(name: string, type?: "single" | "multiple", items?: ChipItem[], rules?: object, defaultValue?: string | string[]) — Selectable pill group.`, MaxArgs: 5, Deps: []string{"ChipItem"}}, + {Name: "ChipItem", Signature: "ChipItem(value: string, label: string) — Single chip option.", MaxArgs: 4}, + {Name: "OptionCards", Signature: `OptionCards(name: string, type?: "single" | "multiple", items?: OptionCard[], rules?: object, defaultValue?: string | string[]) — Selectable card grid.`, MaxArgs: 5, Deps: []string{"OptionCard"}}, + {Name: "OptionCard", Signature: "OptionCard(value: string, title: string, subtitle?: string) — Single option card.", MaxArgs: 5}, + {Name: "DatePicker", Signature: `DatePicker(name: string, mode?: "single" | "range", rules?: object, value?: $binding) — Date selector.`, MaxArgs: 4}, + {Name: "Slider", Signature: `Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[]) — Numeric range slider.`, MaxArgs: 9}, + {Name: "Buttons", Signature: `Buttons(buttons: Button[], direction?: "row" | "column") — Action button group.`, MaxArgs: 2, Deps: []string{"Button"}}, + {Name: "Button", Signature: `Button(label: string, action?: ActionExpression, variant?: "primary" | "secondary" | "tertiary") — Interactive trigger button.`, MaxArgs: 5}, + {Name: "FollowUpBlock", Signature: "FollowUpBlock(items: FollowUpItem[]) — Suggested next turns at the bottom of a card.", MaxArgs: 1, Deps: []string{"FollowUpItem"}}, + {Name: "FollowUpItem", Signature: "FollowUpItem(text: string) — Single tappable follow-up prompt.", MaxArgs: 1}, +} + +// readUI reads the files agent.yaml's ui key names and compiles the three into what the model +// is told. A problem with what they add up to, such as an example that uses a component the +// catalog lacks, is reported at the ui key. +func readUI(settings UISettings, declaration *reader, text func(string) (string, bool), problems *Problems) *UI { + ui := &UI{Settings: settings} + read := func(named, fallback string) (file, content string) { + file = named + if file == "" { + file = fallback + } + content, found := text(file) + switch { + case !found && named == "": + return "", "" + case !found: + line, column := declaration.locate("ui") + *problems = append(*problems, Problem{File: AgentFile, Line: line, Column: column, + Message: fmt.Sprintf("ui names %s, which is not a text file in the directory", file)}) + return "", "" + case len(content) > maxUIFileBytes: + *problems = append(*problems, Problem{File: file, + Message: fmt.Sprintf("holds %d bytes, and a UI file holds at most %d", len(content), maxUIFileBytes)}) + return "", "" + } + return file, content + } + before := len(*problems) + + var components []UIPortableComponent + if file, content := read(settings.Components, UIComponentsFile); file != "" { + ui.Components = content + decoder := json.NewDecoder(strings.NewReader(content)) + decoder.DisallowUnknownFields() + err := decoder.Decode(&components) + if err == nil { + err = validateUIComponents(components, settings.Format) + } + if err != nil { + line, column := jsonPosition(content, err) + *problems = append(*problems, Problem{File: file, Line: line, Column: column, Message: err.Error()}) + } + } + var blueprints []UIBlueprint + if file, content := read(settings.Blueprints, UIBlueprintsFile); file != "" { + ui.Blueprints = content + blueprints = (&reader{file: file, problems: problems}).blueprints(content) + } + if len(*problems) > before { + return ui + } + + instructions, err := compileUIPrompt(settings, components, blueprints) + if err != nil { + line, column := declaration.locate("ui") + *problems = append(*problems, Problem{File: AgentFile, Line: line, Column: column, Message: err.Error()}) + } + ui.Instructions = instructions + return ui +} + +// jsonPosition is where a JSON file stopped reading, or its first character for a problem +// that is not about its syntax. +func jsonPosition(content string, err error) (line, column int) { + var syntax *json.SyntaxError + var mistyped *json.UnmarshalTypeError + offset := 0 + switch { + case errors.As(err, &syntax): + offset = int(syntax.Offset) + case errors.As(err, &mistyped): + offset = int(mistyped.Offset) + } + read := content[:min(offset, len(content))] + return 1 + strings.Count(read, "\n"), 1 + len(read) - (strings.LastIndex(read, "\n") + 1) +} + +// blueprints reads ui/blueprints.yaml: a list of layout recipes. +func (r *reader) blueprints(content string) []UIBlueprint { + root := r.document(content) + if root == nil { + return nil + } + var blueprints []UIBlueprint + seen := map[string]int{} + r.each(root, func(item *yaml.Node) { + if null(item) { + return + } + var blueprint UIBlueprint + name := item + if !r.mapping(item, "a blueprint", + field{"name", func(value *yaml.Node) { name = value; r.text(&blueprint.Name)(value) }}, + field{"when", r.text(&blueprint.When)}, + field{"order", r.list(&blueprint.Order)}, + field{"rules", r.list(&blueprint.Rules)}, + field{"example", r.text(&blueprint.Example)}) { + return + } + switch { + case strings.TrimSpace(blueprint.Name) == "": + r.fail(item, "a blueprint needs a name") + case strings.TrimSpace(blueprint.When) == "": + r.fail(item, "blueprint %q needs a when condition", blueprint.Name) + case len(blueprint.Order) == 0: + r.fail(item, "blueprint %q needs an order list", blueprint.Name) + } + if line, declared := seen[blueprint.Name]; declared { + r.fail(name, "blueprint %q was already declared on line %d", blueprint.Name, line) + } + seen[blueprint.Name] = name.Line + blueprints = append(blueprints, blueprint) + }) + return blueprints +} + +func validateUIComponents(components []UIPortableComponent, format string) error { + builtins := make(map[string]struct{}, len(uiBuiltins)) + if format == "a2ui" { + for name := range a2uiBasic.Components { + builtins[name] = struct{}{} + } + // A2UI reserves Surface for the surface itself. + builtins["Surface"] = struct{}{} + } else { + for _, b := range uiBuiltins { + builtins[b.Name] = struct{}{} + } + } + seen := make(map[string]struct{}, len(components)) + for _, comp := range components { + if !uiPortableName.MatchString(comp.Name) { + return fmt.Errorf("component %q must be snake_case", comp.Name) + } + pascal := uiPascalName(comp.Name) + if _, exists := builtins[pascal]; exists { + return fmt.Errorf("component %q (%s) collides with a built-in component", comp.Name, pascal) + } + if _, exists := seen[pascal]; exists { + return fmt.Errorf("duplicate component %q", comp.Name) + } + seen[pascal] = struct{}{} + if strings.TrimSpace(comp.Description) == "" { + return fmt.Errorf("component %q needs a description", comp.Name) + } + if len(comp.Parameters.Properties) > 0 && len(comp.Parameters.Order) != len(comp.Parameters.Properties) { + return fmt.Errorf("component %q parameters.x-order must list all %d properties", + comp.Name, len(comp.Parameters.Properties)) + } + for _, key := range comp.Parameters.Order { + if _, ok := comp.Parameters.Properties[key]; !ok { + return fmt.Errorf("component %q x-order names unknown property %q", comp.Name, key) + } + } + // An A2UI property is a key of the component's JSON object, which the renderers refuse + // unless it is an identifier. + if format == "a2ui" { + for _, key := range comp.Parameters.Order { + if !a2uiIdentifier.MatchString(key) { + return fmt.Errorf("component %q property %q must be an identifier: letters, digits and _, not starting with a digit", comp.Name, key) + } + } + } + } + return nil +} + +func compileUIPrompt(settings UISettings, components []UIPortableComponent, blueprints []UIBlueprint) (string, error) { + if settings.Format == "a2ui" { + return compileA2UIPrompt(settings, components, blueprints) + } + byName := make(map[string]uiBuiltin, len(uiBuiltins)) + for _, b := range uiBuiltins { + byName[b.Name] = b + } + customArity := make(map[string]int, len(components)) + for _, c := range components { + customArity[uiPascalName(c.Name)] = len(c.Parameters.Order) + len(c.Slots) + } + + included := map[string]bool{"Card": true} + if len(settings.Keep) == 0 { + for _, b := range uiBuiltins { + included[b.Name] = true + } + } else { + var queue []string + for _, name := range settings.Keep { + if _, isCustom := customArity[name]; isCustom { + continue + } + if _, ok := byName[name]; !ok { + return "", fmt.Errorf("ui.keep names unknown component %q", name) + } + if !included[name] { + included[name] = true + queue = append(queue, name) + } + } + for len(queue) > 0 { + curr := queue[0] + queue = queue[1:] + for _, dep := range byName[curr].Deps { + if !included[dep] { + included[dep] = true + queue = append(queue, dep) + } + } + } + } + + arity := make(map[string]int, len(included)+len(customArity)) + var selected []uiBuiltin + for _, b := range uiBuiltins { + if included[b.Name] { + selected = append(selected, b) + arity[b.Name] = b.MaxArgs + } + } + for k, v := range customArity { + arity[k] = v + } + + for _, bp := range blueprints { + if bp.Example != "" { + if problems := checkOpenUIProgram(extractUIFence(bp.Example, "openui-lang"), arity); len(problems) > 0 { + return "", fmt.Errorf("blueprint %q example is invalid: %s", bp.Name, strings.Join(problems, "; ")) + } + } + } + + var b strings.Builder + writeUIOpening(&b, "openui-lang", settings.VoiceUI) + + b.WriteString("### Syntax & Streaming Invariants\n") + b.WriteString("1. Put `root = Card([...])` on the FIRST line so the card shell streams immediately.\n") + b.WriteString("2. Every statement is `identifier = Expression` on its own line; arguments are strictly POSITIONAL (`TypeName(arg1, arg2)` — never `key: value`).\n") + b.WriteString("3. Every defined identifier other than `root` and `$state` variables must be referenced from `root`.\n") + b.WriteString("4. Never fabricate image URLs; use custom components or icons when no verified URL is in context.\n") + if settings.PatchMode { + b.WriteString("5. When refining an existing UI from the immediately preceding turn (e.g. updating a time slot, party size, or filter), emit only the changed statements inside a ```openui-patch fenced block (`$party = 4`, or `oldSection = null` to remove).\n") + } + + b.WriteString("\n### Allowed Component Signatures\n") + for _, def := range selected { + b.WriteString("- ") + b.WriteString(def.Signature) + b.WriteByte('\n') + } + for _, comp := range components { + b.WriteString("- ") + b.WriteString(formatPortableSignature(comp)) + b.WriteByte('\n') + } + + if len(blueprints) > 0 { + b.WriteString(uiBlueprintsHeading) + for _, bp := range blueprints { + b.WriteString(fmt.Sprintf("- **%s** (when %s): `Card([%s])`", bp.Name, strings.TrimSpace(bp.When), strings.Join(bp.Order, " -> "))) + if len(bp.Rules) > 0 { + b.WriteString(" — ") + b.WriteString(strings.Join(bp.Rules, "; ")) + } + b.WriteByte('\n') + if bp.Example != "" { + b.WriteString("\n```openui-lang\n") + b.WriteString(strings.TrimSpace(extractUIFence(bp.Example, "openui-lang"))) + b.WriteString("\n```\n") + } + } + } + + writeUIRules(&b, settings.Rules) + + return strings.TrimSpace(b.String()), nil +} + +const uiBlueprintsHeading = "\n### Canonical Layout Blueprints (Predictability Rules)\n" + + "Match similar prompts to the exact component sequence below so repeated asks produce a consistent layout:\n" + +// writeUIOpening starts the section with when to answer with UI, in a block fenced with fence. +func writeUIOpening(b *strings.Builder, fence string, voiceUI bool) { + b.WriteString("## Interactive UI Generation\n\n") + if voiceUI { + b.WriteString("When an answer benefits from interactive UI, first speak or write one concise sentence summarizing the key takeaway, then emit the UI in a single ```" + fence + " fenced block. Never read component names or UI syntax aloud.\n\n") + } else { + b.WriteString("When an answer benefits from interactive UI, first write one short sentence summarizing what the card shows, then write the whole UI in one ```" + fence + " fenced block. On a voice call without a screen, speak concisely with no UI block.\n\n") + } +} + +func writeUIRules(b *strings.Builder, rules []string) { + if len(rules) == 0 { + return + } + b.WriteString("\n### Brand & Design Rules\n") + for _, rule := range rules { + b.WriteString("- ") + b.WriteString(strings.TrimSpace(rule)) + b.WriteByte('\n') + } +} + +func uiPascalName(snake string) string { + var out strings.Builder + for part := range strings.SplitSeq(snake, "_") { + if part != "" { + out.WriteString(strings.ToUpper(part[:1]) + part[1:]) + } + } + return out.String() +} + +func formatPortableSignature(comp UIPortableComponent) string { + required := make(map[string]bool, len(comp.Parameters.Required)) + for _, r := range comp.Parameters.Required { + required[r] = true + } + var params []string + for _, key := range comp.Parameters.Order { + prop := comp.Parameters.Properties[key] + opt := "?" + if required[key] { + opt = "" + } + typ := prop.Type + if len(prop.Enum) > 0 { + quoted := make([]string, len(prop.Enum)) + for i, e := range prop.Enum { + quoted[i] = strconv.Quote(e) + } + typ = strings.Join(quoted, " | ") + } + params = append(params, fmt.Sprintf("%s%s: %s", key, opt, typ)) + } + for _, slot := range comp.Slots { + params = append(params, fmt.Sprintf("%s?: Component[]", slot)) + } + details := []string{strings.TrimSpace(comp.Description)} + for _, ev := range comp.Events { + if strings.TrimSpace(ev.Description) != "" { + details = append(details, strings.TrimSpace(ev.Description)) + } + } + return fmt.Sprintf("%s(%s) — %s", uiPascalName(comp.Name), strings.Join(params, ", "), strings.Join(details, " ")) +} + +// extractUIFence is the program in an example's block fenced with fence, or the example itself +// when it has none. +func extractUIFence(example, fence string) string { + if _, after, ok := strings.Cut(example, "```"+fence+"\n"); ok { + if body, _, closed := strings.Cut(after, "\n```"); closed { + return body + } + } + return example +} + +func checkOpenUIProgram(program string, knownArity map[string]int) []string { + trimmed := strings.TrimSpace(program) + if trimmed == "" { + return []string{"program is empty"} + } + var stmts []string + var current strings.Builder + var quote byte + escaped := false + depth := 0 + for line := range strings.SplitSeq(trimmed, "\n") { + if quote == 0 && depth == 0 { + clean := strings.TrimSpace(line) + if clean == "" || strings.HasPrefix(clean, "//") || strings.HasPrefix(clean, "#") { + continue + } + } + if current.Len() > 0 { + current.WriteByte('\n') + } + current.WriteString(line) + for i := 0; i < len(line); i++ { + ch := line[i] + if escaped { + escaped = false + continue + } + if quote != 0 { + if ch == '\\' { + escaped = true + } else if ch == quote { + quote = 0 + } + continue + } + if ch == '/' && i+1 < len(line) && line[i+1] == '/' { + break + } + switch ch { + case '"', '\'': + quote = ch + case '(', '[', '{': + depth++ + case ')', ']', '}': + depth-- + if depth < 0 { + return []string{"unmatched closing bracket"} + } + } + } + if quote == 0 && depth == 0 { + if s := strings.TrimSpace(current.String()); s != "" { + stmts = append(stmts, s) + } + current.Reset() + } + } + if quote != 0 || depth != 0 { + return []string{"unclosed string or bracket"} + } + + defined := map[string]string{} + var order []string + for _, stmt := range stmts { + lhs, rhs, ok := splitUIAssign(stmt) + if !ok { + return []string{fmt.Sprintf("invalid statement %q", stmt)} + } + defined[lhs] = rhs + order = append(order, lhs) + } + if _, ok := defined["root"]; !ok { + return []string{"root is not defined"} + } + var problems []string + used := map[string]bool{"root": true} + for _, lhs := range order { + stripped := stripUIStrings(defined[lhs]) + for _, span := range uiRefPattern.FindAllStringIndex(stripped, -1) { + tok := stripped[span[0]:span[1]] + if span[0] > 0 && (stripped[span[0]-1] == '@' || stripped[span[0]-1] == '.') { + continue + } + if strings.HasPrefix(strings.TrimLeft(stripped[span[1]:], " \t"), ":") { + continue + } + if slices.Contains([]string{"true", "false", "null", "Action", "Query", "Mutation"}, tok) { + continue + } + if span[1] < len(stripped) && stripped[span[1]] == '(' { + if maxArgs, ok := knownArity[tok]; ok { + if count := countUIArgs(stripped[span[1]:]); count > maxArgs { + problems = append(problems, fmt.Sprintf("%s passed %d arguments, max is %d", tok, count, maxArgs)) + } + } else { + problems = append(problems, fmt.Sprintf("unknown component %s", tok)) + } + continue + } + if _, ok := defined[tok]; ok { + used[tok] = true + } else { + problems = append(problems, fmt.Sprintf("%s is referenced but not defined", tok)) + } + } + } + for _, lhs := range order { + if lhs != "root" && !strings.HasPrefix(lhs, "$") && !used[lhs] { + problems = append(problems, fmt.Sprintf("%s is defined but never referenced", lhs)) + } + } + return problems +} + +func splitUIAssign(stmt string) (string, string, bool) { + for i := 0; i < len(stmt); i++ { + if stmt[i] != '=' { + continue + } + if i > 0 && (stmt[i-1] == '!' || stmt[i-1] == '<' || stmt[i-1] == '>' || stmt[i-1] == '=') { + continue + } + if i+1 < len(stmt) && stmt[i+1] == '=' { + i++ + continue + } + lhs := strings.TrimSpace(stmt[:i]) + if !uiIdentPattern.MatchString(lhs) { + return "", "", false + } + return lhs, strings.TrimSpace(stmt[i+1:]), true + } + return "", "", false +} + +func stripUIStrings(s string) string { + var out strings.Builder + var quote byte + escaped := false + for i := 0; i < len(s); i++ { + ch := s[i] + if escaped { + escaped = false + continue + } + if quote != 0 { + if ch == '\\' { + escaped = true + } else if ch == quote { + quote = 0 + out.WriteByte('"') + } + continue + } + if ch == '"' || ch == '\'' { + quote = ch + out.WriteByte('"') + continue + } + out.WriteByte(ch) + } + return out.String() +} + +func countUIArgs(callSuffix string) int { + if callSuffix == "" || callSuffix[0] != '(' { + return 0 + } + depth := 0 + commas := 0 + hasContent := false + for i := 0; i < len(callSuffix); i++ { + ch := callSuffix[i] + switch ch { + case '(', '[', '{': + if depth == 1 { + hasContent = true + } + depth++ + case ')', ']', '}': + depth-- + if depth == 0 { + if !hasContent { + return 0 + } + return commas + 1 + } + case ',': + if depth == 1 { + commas++ + } + default: + if depth == 1 && ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n' { + hasContent = true + } + } + } + return 0 +} diff --git a/acceleration/internal/agentdir/ui_a2ui.go b/acceleration/internal/agentdir/ui_a2ui.go new file mode 100644 index 0000000000..76243832a9 --- /dev/null +++ b/acceleration/internal/agentdir/ui_a2ui.go @@ -0,0 +1,574 @@ +package agentdir + +import ( + "bytes" + _ "embed" + "encoding/json" + "fmt" + "maps" + "regexp" + "slices" + "strings" +) + +// The A2UI basic catalog and protocol as stream-chat-swift's renderer has them, which +// a2ui/generate.sh writes, so the agent is told what the apps draw. writing.md is the renderer's +// own section on how a reply carries its UI (A2UIInstructions), which isn't public to generate. +var ( + //go:embed a2ui/basic_catalog.json + a2uiBasicCatalogJSON []byte + //go:embed a2ui/protocol.md + a2uiProtocol string + //go:embed a2ui/writing.md + a2uiWriting string +) + +const ( + a2uiFence = "ui:a2ui@1.0" + // a2uiCatalogID is the id the apps' A2UI renderers give the basic catalog with the app's + // components beside its own (A2UIRenderer.defaultCatalogId in stream-chat-swift). + a2uiCatalogID = "getstream.io:app-catalog" + // a2uiMaxNesting is how deep a renderer draws components (A2UIProtocol.maxNestingDepth). + a2uiMaxNesting = 50 +) + +var a2uiIdentifier = regexp.MustCompile(`^[\p{L}_][\p{L}\p{N}_]*$`) + +var a2uiMessageKinds = []string{ + "createSurface", "updateComponents", "updateDataModel", "deleteSurface", + "callRendererFunction", "agentFunctionResponse", +} + +type a2uiCatalog struct { + Schema string `json:"$schema"` + Title string `json:"title"` + Description string `json:"description"` + Instructions string `json:"instructions"` + Components map[string]json.RawMessage `json:"components"` + Functions map[string]json.RawMessage `json:"functions"` +} + +var a2uiBasic = func() a2uiCatalog { + var catalog a2uiCatalog + if err := json.Unmarshal(a2uiBasicCatalogJSON, &catalog); err != nil { + panic(fmt.Sprintf("agentdir: a2ui/basic_catalog.json: %v", err)) + } + return catalog +}() + +// compileA2UIPrompt writes what the model is told to write UI in A2UI with: the renderer's +// protocol and guidelines, then the catalog it draws with, the basic catalog's components and +// functions that keep names beside the app's own, as the renderer serializes it. +func compileA2UIPrompt(settings UISettings, components []UIPortableComponent, blueprints []UIBlueprint) (string, error) { + custom := make(map[string]json.RawMessage, len(components)) + for _, comp := range components { + schema, err := a2uiComponentSchema(comp) + if err != nil { + return "", err + } + custom[uiPascalName(comp.Name)] = schema + } + + catalogComponents := make(map[string]json.RawMessage) + catalogFunctions := make(map[string]json.RawMessage) + if len(settings.Keep) == 0 { + maps.Copy(catalogComponents, a2uiBasic.Components) + maps.Copy(catalogFunctions, a2uiBasic.Functions) + } + for _, name := range settings.Keep { + if schema, ok := a2uiBasic.Components[name]; ok { + catalogComponents[name] = schema + } else if schema, ok := a2uiBasic.Functions[name]; ok { + catalogFunctions[name] = schema + } else if _, ok := custom[name]; !ok { + return "", fmt.Errorf("ui.keep names %q, which is neither a component nor a function of the A2UI basic catalog", name) + } + } + maps.Copy(catalogComponents, custom) + + for _, bp := range blueprints { + if bp.Example == "" { + continue + } + if problems := checkA2UIProgram(extractUIFence(bp.Example, a2uiFence), catalogComponents); len(problems) > 0 { + return "", fmt.Errorf("blueprint %q example is invalid: %s", bp.Name, strings.Join(problems, "; ")) + } + } + + document, err := a2uiCatalogDocument(catalogComponents, catalogFunctions) + if err != nil { + return "", err + } + + var b strings.Builder + writeUIOpening(&b, a2uiFence, settings.VoiceUI) + b.WriteString(strings.TrimSpace(a2uiWriting)) + b.WriteString("\n\n") + b.WriteString(a2uiSubsection(a2uiProtocol)) + b.WriteString("\n\n") + b.WriteString(a2uiSubsection(a2uiBasic.Instructions)) + b.WriteString("\n\n### The catalog `" + a2uiCatalogID + "`\n\n```json\n") + b.Write(document) + b.WriteString("\n```\n") + + if len(blueprints) > 0 { + b.WriteString(uiBlueprintsHeading) + for _, bp := range blueprints { + fmt.Fprintf(&b, "- **%s** (when %s): a Column of `%s`", bp.Name, strings.TrimSpace(bp.When), strings.Join(bp.Order, " -> ")) + if len(bp.Rules) > 0 { + b.WriteString(" — ") + b.WriteString(strings.Join(bp.Rules, "; ")) + } + b.WriteByte('\n') + if bp.Example != "" { + b.WriteString("\n```" + a2uiFence + "\n") + b.WriteString(strings.TrimSpace(extractUIFence(bp.Example, a2uiFence))) + b.WriteString("\n```\n") + } + } + } + + writeUIRules(&b, settings.Rules) + + return strings.TrimSpace(b.String()), nil +} + +// a2uiSubsection nests the renderer's text under the section's own heading. +func a2uiSubsection(text string) string { + lines := strings.Split(strings.TrimSpace(text), "\n") + for i, line := range lines { + if rest, ok := strings.CutPrefix(line, "## "); ok { + lines[i] = "### " + rest + } else if rest, ok := strings.CutPrefix(line, "# "); ok { + lines[i] = "### " + rest + } + } + return strings.Join(lines, "\n") +} + +// a2uiComponentSchema is an app component as the renderer has it in its catalog +// (PortableComponent in stream-chat-swift): its parameters are its properties, and what its +// events do joins its description, as the component reports them itself. +func a2uiComponentSchema(comp UIPortableComponent) (json.RawMessage, error) { + properties := map[string]any{"component": map[string]string{"const": uiPascalName(comp.Name)}} + for key, prop := range comp.Parameters.Properties { + schema := map[string]any{} + if prop.Type != "" { + schema["type"] = prop.Type + } + if prop.Format != "" { + schema["format"] = prop.Format + } + if prop.Description != "" { + schema["description"] = prop.Description + } + if len(prop.Enum) > 0 { + schema["enum"] = prop.Enum + } + if len(prop.Items) > 0 { + // Decoded with its numbers as written, and written again with its keys sorted as the + // rest of the catalog is. + var items any + decoder := json.NewDecoder(bytes.NewReader(prop.Items)) + decoder.UseNumber() + if err := decoder.Decode(&items); err != nil { + return nil, fmt.Errorf("component %q property %q items: %w", comp.Name, key, err) + } + schema["items"] = items + } + properties[key] = schema + } + required := append([]string{"component"}, comp.Parameters.Required...) + slices.Sort(required) + + var notes []string + for _, text := range append([]string{comp.Description}, eventDescriptions(comp.Events)...) { + if sentence := a2uiSentence(text); sentence != "" { + notes = append(notes, sentence) + } + } + return marshalA2UI(map[string]any{ + "description": strings.Join(notes, " "), + "properties": properties, + "required": required, + "type": "object", + }) +} + +func eventDescriptions(events []UIPortableEvent) []string { + described := make([]string, 0, len(events)) + for _, event := range events { + described = append(described, event.Description) + } + return described +} + +func a2uiSentence(text string) string { + trimmed := strings.TrimSpace(text) + if trimmed == "" || strings.ContainsAny(trimmed[len(trimmed)-1:], ".!?") { + return trimmed + } + return trimmed + "." +} + +// a2uiCatalogDocument is the catalog as the renderer serializes it, keys sorted, on one line. +func a2uiCatalogDocument(components, functions map[string]json.RawMessage) ([]byte, error) { + componentRefs := make([]map[string]string, 0, len(components)) + for _, name := range slices.Sorted(maps.Keys(components)) { + componentRefs = append(componentRefs, map[string]string{"$ref": "#/components/" + name}) + } + functionRefs := make([]map[string]string, 0, len(functions)) + for _, name := range slices.Sorted(maps.Keys(functions)) { + functionRefs = append(functionRefs, map[string]string{"$ref": "#/functions/" + name}) + } + document := map[string]any{ + "$defs": map[string]any{ + "anyComponent": map[string]any{ + "discriminator": map[string]string{"propertyName": "component"}, + "oneOf": componentRefs, + }, + "anyFunction": map[string]any{"oneOf": functionRefs}, + }, + "$id": a2uiCatalogID, + "$schema": a2uiBasic.Schema, + "catalogId": a2uiCatalogID, + "description": a2uiBasic.Description, + "protocolVersion": "1.0", + "title": a2uiBasic.Title, + } + if len(components) > 0 { + document["components"] = components + } + if len(functions) > 0 { + document["functions"] = functions + } + return marshalA2UI(document) +} + +// marshalA2UI writes JSON as the renderer does, without escaping <, > and &. +func marshalA2UI(value any) ([]byte, error) { + var out bytes.Buffer + encoder := json.NewEncoder(&out) + encoder.SetEscapeHTML(false) + if err := encoder.Encode(value); err != nil { + return nil, fmt.Errorf("writing the A2UI catalog: %w", err) + } + return bytes.TrimSuffix(out.Bytes(), []byte("\n")), nil +} + +// checkA2UIProgram is what is wrong with the A2UI messages of an example for a renderer with +// catalog, as stream-chat-swift's A2UIProgram finds it: messages it can't read, components it +// doesn't have, and references that lead nowhere. An example teaches the model, so it has to +// render as written. +func checkA2UIProgram(text string, catalog map[string]json.RawMessage) []string { + var problems []string + surfaces := map[string]map[string]map[string]any{} + var order []string + for _, raw := range a2uiMessages(text) { + var message map[string]any + decoder := json.NewDecoder(strings.NewReader(raw)) + decoder.UseNumber() + if err := decoder.Decode(&message); err != nil { + problems = append(problems, "this isn't JSON: "+truncate(raw, 80)) + continue + } + kind, body, problem := a2uiMessageOf(message) + if problem != "" { + problems = append(problems, problem) + continue + } + surfaceID, _ := body["surfaceId"].(string) + switch kind { + case "createSurface": + components, more := a2uiComponentsOf(body, surfaceID) + problems = append(problems, more...) + if catalogID, ok := body["catalogId"].(string); ok && catalogID != a2uiCatalogID { + problems = append(problems, fmt.Sprintf("surface %s names the catalog %s, not %s", surfaceID, catalogID, a2uiCatalogID)) + } + surfaces[surfaceID] = components + order = append(order, surfaceID) + case "updateComponents": + existing, created := surfaces[surfaceID] + if !created { + problems = append(problems, fmt.Sprintf("surface %s gets components before it is created", surfaceID)) + continue + } + components, more := a2uiComponentsOf(body, surfaceID) + problems = append(problems, more...) + maps.Copy(existing, components) + case "updateDataModel": + if _, created := surfaces[surfaceID]; !created { + problems = append(problems, fmt.Sprintf("surface %s gets data before it is created", surfaceID)) + } + case "deleteSurface": + default: + problems = append(problems, "a reply's UI calls no functions") + } + } + if len(order) == 0 { + problems = append(problems, "nothing renders: there is no createSurface") + } + for _, surfaceID := range order { + problems = append(problems, a2uiSurfaceProblems(surfaces[surfaceID], surfaceID, catalog)...) + } + return problems +} + +// a2uiMessages splits text into the JSON objects in it, as the renderer reads a reply's block. +func a2uiMessages(text string) []string { + var messages []string + depth, start := 0, 0 + inString, escaped := false, false + for i := 0; i < len(text); i++ { + c := text[i] + if inString { + switch { + case escaped: + escaped = false + case c == '\\': + escaped = true + case c == '"': + inString = false + } + continue + } + switch c { + case '"': + inString = depth > 0 + case '{': + if depth == 0 { + start = i + } + depth++ + case '}': + if depth > 0 { + depth-- + if depth == 0 { + messages = append(messages, text[start:i+1]) + } + } + } + } + return messages +} + +func a2uiMessageOf(message map[string]any) (kind string, body map[string]any, problem string) { + if version, _ := message["version"].(string); version != "1.0" { + return "", nil, `a message needs "version": "1.0"` + } + for key := range message { + if key == "version" { + continue + } + if !slices.Contains(a2uiMessageKinds, key) || kind != "" { + return "", nil, fmt.Sprintf("a message has exactly one of %s", strings.Join(a2uiMessageKinds, ", ")) + } + kind = key + } + if kind == "" { + return "", nil, fmt.Sprintf("a message has exactly one of %s", strings.Join(a2uiMessageKinds, ", ")) + } + body, ok := message[kind].(map[string]any) + if !ok { + return "", nil, fmt.Sprintf("%s is an object", kind) + } + if surfaceID, _ := body["surfaceId"].(string); surfaceID == "" && kind != "callRendererFunction" && kind != "agentFunctionResponse" { + return "", nil, fmt.Sprintf("%s needs a surfaceId", kind) + } + return kind, body, "" +} + +// a2uiComponentsOf is a message's components by id, and the problems with them. +func a2uiComponentsOf(body map[string]any, surfaceID string) (map[string]map[string]any, []string) { + listed, _ := body["components"].([]any) + components := make(map[string]map[string]any, len(listed)) + var problems []string + var repeated []string + for _, item := range listed { + component, _ := item.(map[string]any) + id, _ := component["id"].(string) + if _, typed := component["component"].(string); id == "" || !typed { + problems = append(problems, fmt.Sprintf("surface %s has a component without an id and a component type", surfaceID)) + continue + } + if _, seen := components[id]; seen && !slices.Contains(repeated, id) { + repeated = append(repeated, id) + } + components[id] = component + } + for _, id := range repeated { + problems = append(problems, fmt.Sprintf("surface %s defines %s more than once in one message", surfaceID, id)) + } + return components, problems +} + +func a2uiSurfaceProblems(components map[string]map[string]any, surfaceID string, catalog map[string]json.RawMessage) []string { + var problems []string + references := map[string][]string{} + for _, id := range slices.Sorted(maps.Keys(components)) { + component := components[id] + kind, _ := component["component"].(string) + if !a2uiIdentifier.MatchString(id) { + problems = append(problems, fmt.Sprintf("%s isn't an identifier: use letters, digits and _, not starting with a digit", id)) + } + raw, known := catalog[kind] + if !known { + problems = append(problems, fmt.Sprintf("%s is a %s, which the catalog doesn't have", id, kind)) + continue + } + var schema struct { + Properties map[string]map[string]any `json:"properties"` + Required []string `json:"required"` + } + if err := json.Unmarshal(raw, &schema); err != nil { + problems = append(problems, fmt.Sprintf("the catalog's %s can't be read: %v", kind, err)) + continue + } + for _, name := range schema.Required { + if _, given := component[name]; !given && name != "component" { + problems = append(problems, fmt.Sprintf("%s is a %s without its %s", id, kind, name)) + } + } + for _, key := range slices.Sorted(maps.Keys(component)) { + switch key { + case "id", "component", "catalogId", "checks", "weight": + continue + } + if _, has := schema.Properties[key]; !has { + problems = append(problems, fmt.Sprintf("%s is a %s, which has no %s", id, kind, key)) + } + } + var held []string + for _, key := range slices.Sorted(maps.Keys(schema.Properties)) { + held = append(held, a2uiReferences(component[key], schema.Properties[key])...) + } + references[id] = held + } + for _, id := range slices.Sorted(maps.Keys(references)) { + for _, child := range references[id] { + if _, defined := components[child]; !defined { + problems = append(problems, fmt.Sprintf("%s holds %s, which is not defined", id, child)) + } + } + } + if _, rooted := components["root"]; !rooted { + return append(problems, fmt.Sprintf("surface %s has no component with the id root", surfaceID)) + } + reached := map[string]bool{} + next := []string{"root"} + for len(next) > 0 { + id := next[len(next)-1] + next = next[:len(next)-1] + if reached[id] { + continue + } + reached[id] = true + next = append(next, references[id]...) + } + for _, id := range slices.Sorted(maps.Keys(components)) { + if !reached[id] { + problems = append(problems, fmt.Sprintf("%s is defined but nothing holds it", id)) + } + } + return append(problems, a2uiNestingProblems(references, surfaceID)...) +} + +// a2uiReferences is the ids of the components value holds, by what schema says it is: a +// ComponentId, a ChildList of ids or a template, or an array or object of them. +func a2uiReferences(value any, schema map[string]any) []string { + if ref, ok := schema["$ref"].(string); ok { + if strings.HasSuffix(ref, "/ComponentId") { + if id, ok := value.(string); ok { + return []string{id} + } + return nil + } + if strings.HasSuffix(ref, "/ChildList") { + switch list := value.(type) { + case []any: + ids := make([]string, 0, len(list)) + for _, item := range list { + id, ok := item.(string) + if !ok { + return nil + } + ids = append(ids, id) + } + return ids + case map[string]any: + if id, ok := list["componentId"].(string); ok { + return []string{id} + } + } + return nil + } + } + if items, ok := schema["items"].(map[string]any); ok { + if array, ok := value.([]any); ok { + var ids []string + for _, item := range array { + ids = append(ids, a2uiReferences(item, items)...) + } + return ids + } + } + if properties, ok := schema["properties"].(map[string]any); ok { + if object, ok := value.(map[string]any); ok { + var ids []string + for _, key := range slices.Sorted(maps.Keys(properties)) { + if property, ok := properties[key].(map[string]any); ok { + ids = append(ids, a2uiReferences(object[key], property)...) + } + } + return ids + } + } + return nil +} + +// a2uiNestingProblems finds a component that holds itself, which never finishes rendering, and +// a tree deeper than a renderer draws. +func a2uiNestingProblems(references map[string][]string, surfaceID string) []string { + var problems []string + depths := map[string]int{} + visiting := map[string]bool{} + reportedCycle := false + var depth func(id string) int + depth = func(id string) int { + if known, ok := depths[id]; ok { + return known + } + if visiting[id] { + if !reportedCycle { + problems = append(problems, fmt.Sprintf("%s holds itself through its children, so it never finishes rendering", id)) + reportedCycle = true + } + return 0 + } + visiting[id] = true + deepest := 0 + for _, child := range references[id] { + if _, holds := references[child]; holds { + deepest = max(deepest, depth(child)) + } + } + delete(visiting, id) + depths[id] = deepest + 1 + return deepest + 1 + } + if _, rooted := references["root"]; rooted && depth("root") > a2uiMaxNesting { + problems = append(problems, fmt.Sprintf("surface %s nests components deeper than %d levels", surfaceID, a2uiMaxNesting)) + } + for _, id := range slices.Sorted(maps.Keys(references)) { + depth(id) + } + return problems +} + +func truncate(text string, limit int) string { + runes := []rune(text) + if len(runes) <= limit { + return text + } + return string(runes[:limit]) +} diff --git a/acceleration/internal/agentdir/ui_test.go b/acceleration/internal/agentdir/ui_test.go new file mode 100644 index 0000000000..d027385440 --- /dev/null +++ b/acceleration/internal/agentdir/ui_test.go @@ -0,0 +1,383 @@ +package agentdir + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/suite" +) + +type UISuite struct { + suite.Suite +} + +func TestUISuite(t *testing.T) { + suite.Run(t, new(UISuite)) +} + +// sharedFixtures are the directories every SDK that still compiles ui: itself is held to, and +// what each compiles to. +var sharedFixtures = filepath.Join("..", "..", "..", "sdks", "testdata", "ui") + +// compiled reads a directory with a ui key and returns what it compiles to. +func (s *UISuite) compiled(held map[string]string) *UI { + directory, err := Parse(files(held)) + s.Require().NoError(err) + s.Require().NotNil(directory.UI) + return directory.UI +} + +func (s *UISuite) refused(held map[string]string) Problem { + _, err := Parse(files(held)) + var problems Problems + s.Require().ErrorAs(err, &problems) + s.Require().Len(problems, 1, "%v", problems) + return problems[0] +} + +// onDisk is a fixture directory as the files a client sends. +func (s *UISuite) onDisk(root string) []File { + var read []File + s.Require().NoError(filepath.WalkDir(root, func(file string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + content, err := os.ReadFile(file) + relative, _ := filepath.Rel(root, file) + read = append(read, File{Path: filepath.ToSlash(relative), Content: string(content)}) + return err + })) + return read +} + +func (s *UISuite) TestACatalogAndBlueprintsCompileIntoWhatTheModelIsTold() { + ui := s.compiled(map[string]string{ + AgentFile: `name: concierge +llm: llm-fast +ui: + format: openui + keep: [CardHeader, Form, Chips, FollowUpBlock] + patch_mode: true + voice_ui: true + rules: + - Always pair RestaurantCard with AvailabilityGauge when wait time is known. +`, + UIComponentsFile: `[ + { + "name": "restaurant_card", + "description": "Venue header card with rating and price tier.", + "parameters": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "cuisine": { "type": "string" }, + "rating": { "type": "number" } + }, + "required": ["name", "cuisine", "rating"], + "x-order": ["name", "cuisine", "rating"] + }, + "events": [{ "name": "inspect", "description": "Tapping shows the tasting menu." }] + }, + { + "name": "availability_gauge", + "description": "Radial occupancy and wait-time gauge.", + "parameters": { + "type": "object", + "properties": { + "occupancy_pct": { "type": "number" }, + "wait_label": { "type": "string" } + }, + "required": ["occupancy_pct", "wait_label"], + "x-order": ["occupancy_pct", "wait_label"] + }, + "events": [] + } +]`, + UIBlueprintsFile: `- name: restaurant_booking + when: recommending or booking a restaurant + order: [RestaurantCard, AvailabilityGauge, Form, FollowUpBlock] + example: | + $slot = "19:15" + root = Card([venue, gauge, reserve, next]) + venue = RestaurantCard("Kaneo Cliffside", "Macedonian Grill", 4.9) + gauge = AvailabilityGauge(86, "12m wait") + reserve = Form("book", btns, [slotField]) + slotField = FormControl("Time", Chips("slot", "single", [ChipItem("19:15", "19:15")])) + btns = Buttons([Button("Confirm", @ToAssistant("Confirm", {slot: $slot}), "primary")]) + next = FollowUpBlock([FollowUpItem("See tasting menu")]) +`, + }) + + s.Contains(ui.Instructions, "RestaurantCard(name: string, cuisine: string, rating: number)") + s.Contains(ui.Instructions, "**restaurant_booking**") + s.Contains(ui.Instructions, "openui-patch") + s.NotContains(ui.Instructions, "BarChart(") + s.Contains(ui.Components, "restaurant_card", "the files are kept as written, for an export to write back") + s.Contains(ui.Blueprints, "restaurant_booking") +} + +func (s *UISuite) TestAnArrayPropertyWithAnItemSchemaReadsAsAnArray() { + ui := s.compiled(map[string]string{ + AgentFile: "name: concierge\nui:\n format: openui\n", + UIComponentsFile: `[ + { + "name": "seat_selector", + "description": "Pick a table by zone.", + "parameters": { + "type": "object", + "properties": { + "tables": { + "type": "array", + "items": { + "type": "object", + "properties": { "id": { "type": "string" }, "seats": { "type": "number" } }, + "required": ["id", "seats"], + "x-order": ["id", "seats"] + } + } + }, + "required": ["tables"], + "x-order": ["tables"] + }, + "events": [{ "name": "select_table", "description": "Tapping a table asks for it." }] + } +]`, + }) + + s.Contains(ui.Instructions, "SeatSelector(tables: array) — Pick a table by zone.") +} + +func (s *UISuite) TestAFoldedBlueprintWhenStaysOnOneLine() { + ui := s.compiled(map[string]string{ + AgentFile: "name: concierge\nui:\n format: openui\n", + UIBlueprintsFile: "- name: booking\n when: >\n booking a table\n for tonight\n order: [CardHeader]\n", + }) + + s.Contains(ui.Instructions, "- **booking** (when booking a table for tonight): `Card([CardHeader])`") +} + +func (s *UISuite) TestUIFilesAreReadFromThePathsTheKeyNames() { + ui := s.compiled(map[string]string{ + AgentFile: "name: concierge\nui:\n blueprints: design/recipes.yaml\n", + "design/recipes.yaml": "- name: booking\n when: booking\n order: [CardHeader]\n", + }) + + s.Contains(ui.Instructions, "**booking**") +} + +func (s *UISuite) TestAUIFileTheDirectoryDoesNotHoldIsRefusedAtTheKey() { + problem := s.refused(map[string]string{AgentFile: "name: concierge\nui:\n components: design/missing.json\n"}) + + s.Equal(AgentFile, problem.File) + s.Equal([]int{2, 1}, []int{problem.Line, problem.Column}) + s.Contains(problem.Message, "ui names design/missing.json, which is not a text file in the directory") +} + +func (s *UISuite) TestAUIKeyNobodyKnowsIsRefusedWhereItIs() { + problem := s.refused(map[string]string{AgentFile: "name: concierge\nui:\n bogus_flag: true\n"}) + + s.Equal([]int{3, 3}, []int{problem.Line, problem.Column}) + s.Contains(problem.Message, `"bogus_flag" is not something ui says; format, keep, components, blueprints, patch_mode, voice_ui, rules are`) +} + +func (s *UISuite) TestABlueprintDeclaredTwiceIsRefusedWhereItIs() { + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui:\n format: openui\n", + UIBlueprintsFile: "- name: booking\n when: booking\n order: [CardHeader]\n- name: booking\n when: again\n order: [CardHeader]\n", + }) + + s.Equal(UIBlueprintsFile, problem.File) + s.Equal([]int{4, 9}, []int{problem.Line, problem.Column}) + s.Contains(problem.Message, `blueprint "booking" was already declared on line 1`) +} + +func (s *UISuite) TestABlueprintThatSaysTooLittleIsRefused() { + blueprint := func(declared string) string { + return s.refused(map[string]string{AgentFile: "name: concierge\nui: {}\n", UIBlueprintsFile: declared}).Message + } + + s.Contains(blueprint("- when: booking\n order: [CardHeader]\n"), "a blueprint needs a name") + s.Contains(blueprint("- name: booking\n order: [CardHeader]\n"), `blueprint "booking" needs a when condition`) + s.Contains(blueprint("- name: booking\n when: booking\n"), `blueprint "booking" needs an order list`) + s.Contains(blueprint("- name: booking\n when: booking\n order: [CardHeader]\n layout: wide\n"), `"layout" is not something a blueprint says`) +} + +func (s *UISuite) TestTheSharedFixtureCompilesToItsInstructions() { + golden, err := os.ReadFile(filepath.Join(sharedFixtures, "concierge.instructions.txt")) + s.Require().NoError(err) + + directory, err := Parse(s.onDisk(filepath.Join(sharedFixtures, "concierge"))) + s.Require().NoError(err) + // The router tells the model the two joined so (session.Spec.prompt). + s.Equal(string(golden), directory.Instructions+"\n\n"+directory.UI.Instructions+"\n") +} + +func (s *UISuite) TestTheSharedA2UIFixtureCompilesToItsInstructions() { + golden, err := os.ReadFile(filepath.Join(sharedFixtures, "concierge-a2ui.instructions.txt")) + s.Require().NoError(err) + + directory, err := Parse(s.onDisk(filepath.Join(sharedFixtures, "concierge-a2ui"))) + s.Require().NoError(err) + s.Equal(string(golden), directory.Instructions+"\n\n"+directory.UI.Instructions+"\n") +} + +func (s *UISuite) TestABareUIKeyTeachesNothing() { + bare, err := Parse(files(map[string]string{AgentFile: "name: concierge\nui:\n"})) + s.Require().NoError(err) + s.Nil(bare.UI) + + commented, err := Parse(files(map[string]string{AgentFile: "name: concierge\nui:\n # nothing yet\n"})) + s.Require().NoError(err) + s.Nil(commented.UI) +} + +func (s *UISuite) TestTheA2UICatalogIsTheOneTheSwiftRendererWritesForTheSameComponents() { + // swift_assistant's a2ui/instructions.md is written by stream-chat-swift's A2UI renderer + // from its UIComponents.json and keep list, so this holds the catalog an agent is told + // about to the one the apps draw, and fails when a2ui/basic_catalog.json is older than the + // renderer that wrote it (regenerate both). + app := filepath.Join("..", "..", "..", "examples", "voice_agents", "swift_assistant") + raw, err := os.ReadFile(filepath.Join(app, "a2ui", "prompt.json")) + s.Require().NoError(err) + var prompt struct { + Keep []string `json:"keep"` + } + s.Require().NoError(json.Unmarshal(raw, &prompt)) + components, err := os.ReadFile(filepath.Join(app, "app", "SwiftAssistant", "UIComponents.json")) + s.Require().NoError(err) + written, err := os.ReadFile(filepath.Join(app, "a2ui", "instructions.md")) + s.Require().NoError(err) + + ui := s.compiled(map[string]string{ + AgentFile: "name: concierge\nui:\n format: a2ui\n keep: [" + strings.Join(prompt.Keep, ", ") + "]\n", + UIComponentsFile: string(components), + }) + + want, got := a2uiCatalogLine(string(written)), a2uiCatalogLine(ui.Instructions) + s.Require().NotEmpty(want, "the renderer's prompt has a catalog line") + s.Require().NotEmpty(got, "the compiled prompt has a catalog line") + s.Equal(want, got) +} + +func (s *UISuite) TestTheA2UICatalogIsTheOneTheGoSDKStillCompilesWith() { + // The Go SDK compiles ui: for the program holding a directory until its parser goes + // (AI-3441), from its own copy of these files: regenerate both, or the two tell the model + // different things. + for _, name := range []string{"basic_catalog.json", "protocol.md", "writing.md"} { + ours, err := os.ReadFile(filepath.Join("a2ui", name)) + s.Require().NoError(err) + theirs, err := os.ReadFile(filepath.Join("..", "..", "..", "sdks", "go", "agents", "a2ui", name)) + s.Require().NoError(err) + s.Equal(string(theirs), string(ours), name) + } +} + +// a2uiCatalogLine is the catalog document in instructions, as one line of JSON. +func a2uiCatalogLine(instructions string) string { + _, after, _ := strings.Cut(instructions, "The catalog `"+a2uiCatalogID+"`\n\n```json\n") + line, _, _ := strings.Cut(after, "\n") + return line +} + +func (s *UISuite) TestAFormatThatIsNeitherOpenUINorA2UIIsRefused() { + problem := s.refused(map[string]string{AgentFile: "name: concierge\nui:\n format: html\n"}) + + s.Equal([]int{3, 11}, []int{problem.Line, problem.Column}) + s.Contains(problem.Message, `ui.format must be openui or a2ui, not "html"`) +} + +func (s *UISuite) TestPatchModeIsRefusedForA2UISinceOnlyOpenUIPatchesAreMerged() { + problem := s.refused(map[string]string{AgentFile: "name: concierge\nui:\n format: a2ui\n patch_mode: true\n"}) + + s.Equal(4, problem.Line) + s.Contains(problem.Message, "ui.patch_mode is for openui") +} + +func (s *UISuite) TestAnA2UIExampleHoldingAComponentItNeverDefinesIsRefused() { + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui:\n format: a2ui\n", + UIBlueprintsFile: `- name: booking + when: booking a table + order: [Text] + example: | + {"version":"1.0","createSurface":{"surfaceId":"booking","catalogId":"getstream.io:app-catalog","components":[{"id":"root","component":"Column","children":["title","later"]},{"id":"title","component":"Text","text":"## Tonight"}]}} +`, + }) + + s.Contains(problem.Message, `blueprint "booking" example is invalid: root holds later, which is not defined`) +} + +func (s *UISuite) TestAnA2UIExampleUsingAComponentKeepLeftOutIsRefused() { + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui:\n format: a2ui\n keep: [Text, Column]\n", + UIBlueprintsFile: `- name: booking + when: booking a table + order: [Text, Button] + example: | + {"version":"1.0","createSurface":{"surfaceId":"booking","catalogId":"getstream.io:app-catalog","components":[{"id":"root","component":"Column","children":["book"]},{"id":"book","component":"Button","child":"label","action":{"event":{"name":"book"}}},{"id":"label","component":"Text","text":"Book"}]}} +`, + }) + + s.Contains(problem.Message, "book is a Button, which the catalog doesn't have") +} + +func (s *UISuite) TestKeepNamingAComponentTheCatalogDoesNotHaveIsRefusedAtTheKey() { + a2ui := s.refused(map[string]string{AgentFile: "name: concierge\nui:\n format: a2ui\n keep: [Text, CardHeader]\n"}) + s.Equal([]int{2, 1}, []int{a2ui.Line, a2ui.Column}) + s.Contains(a2ui.Message, `ui.keep names "CardHeader", which is neither a component nor a function of the A2UI basic catalog`) + + openui := s.refused(map[string]string{AgentFile: "name: concierge\nui:\n keep: [Hologram]\n"}) + s.Contains(openui.Message, `ui.keep names unknown component "Hologram"`) +} + +func (s *UISuite) TestAnAppComponentNamedLikeABuiltInOneIsRefused() { + // Column is A2UI's own, which OpenUI does not have. + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui:\n format: a2ui\n", + UIComponentsFile: `[ + {"name": "column", "description": "A brand column.", "parameters": {"type": "object", "properties": {}, "x-order": []}} +]`, + }) + + s.Equal(UIComponentsFile, problem.File) + s.Contains(problem.Message, `component "column" (Column) collides with a built-in component`) +} + +func (s *UISuite) TestAComponentFieldNobodyReadsIsRefused() { + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui:\n format: openui\n", + UIComponentsFile: `[ + { + "name": "loyalty_badge", + "description": "The guest's loyalty tier.", + "parameters": { "type": "object", "properties": { "tier": { "type": "string", "default": "gold" } }, "x-order": ["tier"] } + } +]`, + }) + + s.Contains(problem.Message, `unknown field "default"`) +} + +func (s *UISuite) TestAComponentsFileThatIsNotJSONNamesWhereItStops() { + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui: {}\n", + UIComponentsFile: "[\n {\"name\": \"badge\",\n oops\n]", + }) + + s.Equal(UIComponentsFile, problem.File) + s.Equal(3, problem.Line) +} + +func (s *UISuite) TestAUIFileOverTheSizeOneMayHaveIsRefused() { + problem := s.refused(map[string]string{ + AgentFile: "name: concierge\nui: {}\n", + UIBlueprintsFile: "# " + strings.Repeat("a", maxUIFileBytes) + "\n", + }) + + s.Equal(UIBlueprintsFile, problem.File) + s.Contains(problem.Message, "a UI file holds at most 524288") +} diff --git a/acceleration/internal/agentdir/yaml.go b/acceleration/internal/agentdir/yaml.go new file mode 100644 index 0000000000..bb0fa0ee44 --- /dev/null +++ b/acceleration/internal/agentdir/yaml.go @@ -0,0 +1,285 @@ +package agentdir + +import ( + "fmt" + "strconv" + "strings" + + "gopkg.in/yaml.v3" +) + +// reader reads one YAML file, reporting each thing wrong with it at its line and column +// rather than stopping at the first. +type reader struct { + file string + problems *Problems + root *yaml.Node +} + +func (r *reader) fail(node *yaml.Node, format string, args ...any) { + *r.problems = append(*r.problems, Problem{ + File: r.file, Line: node.Line, Column: node.Column, Message: fmt.Sprintf(format, args...), + }) +} + +// document parses the file and returns what it holds, or nil when it holds nothing or does +// not parse. +func (r *reader) document(content string) *yaml.Node { + var document yaml.Node + if err := yaml.Unmarshal([]byte(content), &document); err != nil { + line, message := 1, strings.TrimPrefix(err.Error(), "yaml: ") + if rest, found := strings.CutPrefix(message, "line "); found { + if number, text, cut := strings.Cut(rest, ": "); cut { + if parsed, err := strconv.Atoi(number); err == nil { + line, message = parsed, text + } + } + } + *r.problems = append(*r.problems, Problem{File: r.file, Line: line, Column: 1, Message: message}) + return nil + } + if len(document.Content) == 0 || null(document.Content[0]) { + return nil + } + r.root = document.Content[0] + return r.root +} + +// field is one key a mapping may hold, and what reads its value. +type field struct { + name string + read func(value *yaml.Node) +} + +// mapping reads a mapping's keys, each by its field. A key no field names is refused, and so +// is one written twice. A key whose value is null reads as one left out. +func (r *reader) mapping(node *yaml.Node, what string, fields ...field) bool { + node = resolved(node) + if node.Kind != yaml.MappingNode { + r.fail(node, "must be a mapping") + return false + } + seen := map[string]bool{} + for i := 0; i+1 < len(node.Content); i += 2 { + key, value := node.Content[i], node.Content[i+1] + if seen[key.Value] { + r.fail(key, "%s is written twice", key.Value) + continue + } + seen[key.Value] = true + known := false + for _, field := range fields { + if field.name == key.Value { + known = true + if !null(value) { + before := len(*r.problems) + field.read(value) + for i := before; i < len(*r.problems); i++ { + (*r.problems)[i].Message = key.Value + ": " + (*r.problems)[i].Message + } + } + } + } + if !known { + // A retired key is read only to be refused, so it is not one the mapping says. + var names []string + for _, field := range fields { + if _, gone := retired[field.name]; !gone { + names = append(names, field.name) + } + } + r.fail(key, "%q is not something %s says; %s are", key.Value, what, strings.Join(names, ", ")) + } + } + return true +} + +// each reads the entries of a list. +func (r *reader) each(node *yaml.Node, read func(item *yaml.Node)) bool { + node = resolved(node) + if node.Kind != yaml.SequenceNode { + r.fail(node, "must be a list") + return false + } + for _, item := range node.Content { + read(item) + } + return true +} + +func (r *reader) text(into *string) func(*yaml.Node) { + return func(node *yaml.Node) { + node = resolved(node) + if node.Kind != yaml.ScalarNode { + r.fail(node, "must be text, not a %s", kind(node)) + return + } + *into = node.Value + } +} + +func (r *reader) optionalText(into **string) func(*yaml.Node) { + return func(node *yaml.Node) { + var value string + before := len(*r.problems) + r.text(&value)(node) + if len(*r.problems) == before { + *into = &value + } + } +} + +func (r *reader) integer(into *int) func(*yaml.Node) { + return func(node *yaml.Node) { + node = resolved(node) + value, err := strconv.Atoi(node.Value) + if node.Kind != yaml.ScalarNode || node.ShortTag() != "!!int" || err != nil { + r.fail(node, "must be a whole number") + return + } + *into = value + } +} + +func (r *reader) optionalInteger(into **int) func(*yaml.Node) { + return func(node *yaml.Node) { + var value int + before := len(*r.problems) + r.integer(&value)(node) + if len(*r.problems) == before { + *into = &value + } + } +} + +func (r *reader) boolean(into *bool) func(*yaml.Node) { + return func(node *yaml.Node) { + node = resolved(node) + if node.Kind != yaml.ScalarNode || node.ShortTag() != "!!bool" { + r.fail(node, "must be true or false") + return + } + *into = node.Value == "true" + } +} + +func (r *reader) optionalBoolean(into **bool) func(*yaml.Node) { + return func(node *yaml.Node) { + var value bool + before := len(*r.problems) + r.boolean(&value)(node) + if len(*r.problems) == before { + *into = &value + } + } +} + +// list reads a list of text, which is empty rather than nil when the file lists none. +func (r *reader) list(into *[]string) func(*yaml.Node) { + return func(node *yaml.Node) { + values := []string{} + if r.each(node, func(item *yaml.Node) { + var value string + r.text(&value)(item) + values = append(values, value) + }) { + *into = values + } + } +} + +func (r *reader) optionalList(into **[]string) func(*yaml.Node) { + return func(node *yaml.Node) { + var values []string + r.list(&values)(node) + if values != nil { + *into = &values + } + } +} + +// labels reads a mapping of text to text, such as tags. +func (r *reader) labels(into *map[string]string) func(*yaml.Node) { + return func(node *yaml.Node) { + node = resolved(node) + if node.Kind != yaml.MappingNode { + r.fail(node, "must be a mapping of names to values") + return + } + values := map[string]string{} + for i := 0; i+1 < len(node.Content); i += 2 { + var value string + r.text(&value)(node.Content[i+1]) + values[node.Content[i].Value] = value + } + *into = values + } +} + +// locate is where the file says the value a dotted path names, or the nearest value above it. +func (r *reader) locate(setting string) (line, column int) { + node := r.root + if node == nil { + return 1, 1 + } + for _, step := range strings.FieldsFunc(setting, func(char rune) bool { return char == '.' || char == '[' || char == ']' }) { + next := child(resolved(node), step) + if next == nil { + break + } + node = next + } + return node.Line, node.Column +} + +// child is the value of a mapping's key called step, or the entry of a list at index step. +// A mapping or a list under a key is found at the key, which is where a reader looks for it. +func child(node *yaml.Node, step string) *yaml.Node { + if index, err := strconv.Atoi(step); err == nil { + if node.Kind == yaml.SequenceNode && index < len(node.Content) { + return node.Content[index] + } + return nil + } + if node.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(node.Content); i += 2 { + if node.Content[i].Value == step { + if value := node.Content[i+1]; value.Kind == yaml.ScalarNode { + return value + } + return positioned(node.Content[i+1], node.Content[i]) + } + } + return nil +} + +// positioned is a value with the position of its key, which is where a mapping or a list +// under a key is named. +func positioned(value, key *yaml.Node) *yaml.Node { + copied := *value + copied.Line, copied.Column = key.Line, key.Column + return &copied +} + +func resolved(node *yaml.Node) *yaml.Node { + if node.Kind == yaml.AliasNode && node.Alias != nil { + return node.Alias + } + return node +} + +func null(node *yaml.Node) bool { + return node.Kind == yaml.ScalarNode && node.ShortTag() == "!!null" +} + +func kind(node *yaml.Node) string { + switch node.Kind { + case yaml.MappingNode: + return "mapping" + case yaml.SequenceNode: + return "list" + } + return "value" +} From 83a361446bc876983c4cc26ad424ef578ab79f2b Mon Sep 17 00:00:00 2001 From: thesyncim Date: Fri, 20 Nov 2026 17:39:57 +0100 Subject: [PATCH 2/6] feat(router): sync an agent directory from its files, and export it POST /v1/agents/sync/files takes the files of an agent's folder and reads them with agentdir, so every client's directory means the same thing. A directory that does not read is a 400 invalid_agent_directory whose problems name the file, line and column of each: what does not parse, what the schema refuses and what the router cannot run, together and bounded. The router finds a connector's connection among the app's own by id or label, keeps the left-out behaviour, compiles ui: into ui_instructions and takes the hash from the files it used. What a program sets in code beside the directory goes in the same request and wins over the files. dry_run answers what would be stored, refuses what the sync would, the money for its knowledge included, and writes nothing. It shares its implementation with POST /v1/agents/sync, whose request is unchanged. GET /v1/agents/configs/{id}/directory writes a stored agent back as its canonical files, with what a directory cannot say in not_exported. agent_configs.ui_source keeps what ui_instructions was compiled from until somebody writes others, so the ui key and its files are exported. A sync checks everything a write would refuse before the first write, two skills of one name included. Its answer lists the skills, knowledge documents, knowledge urls and simulations it creates, updates or deletes as changes, and an unsynced_changes refusal carries what it would write over as conflicts, with the last_change to send back as base_change. --- .github/workflows/ci-go.yml | 16 + acceleration/api/openapi.yaml | 306 ++++- acceleration/internal/api/admission_test.go | 20 + acceleration/internal/api/apierror.go | 31 +- acceleration/internal/api/config_patch.go | 1 + acceleration/internal/api/configs.go | 5 +- acceleration/internal/api/directory.go | 1024 +++++++++++++++ acceleration/internal/api/directory_test.go | 1151 +++++++++++++++++ acceleration/internal/api/knowledge.go | 68 +- acceleration/internal/api/openapi.go | 2 + acceleration/internal/api/server.go | 44 +- acceleration/internal/api/sync.go | 365 ++++-- acceleration/internal/api/sync_conflict.go | 138 +- acceleration/internal/knowledge/urls/urls.go | 18 +- acceleration/internal/store/agents.go | 2 +- acceleration/internal/store/connections.go | 18 + acceleration/internal/store/models.go | 16 + acceleration/internal/store/simulations.go | 6 +- .../20270105090000_agent_config_ui_source.sql | 25 + 19 files changed, 3064 insertions(+), 192 deletions(-) create mode 100644 acceleration/internal/api/directory.go create mode 100644 acceleration/internal/api/directory_test.go create mode 100644 acceleration/migrations/20270105090000_agent_config_ui_source.sql diff --git a/.github/workflows/ci-go.yml b/.github/workflows/ci-go.yml index 3c402aab30..6fa67232fe 100644 --- a/.github/workflows/ci-go.yml +++ b/.github/workflows/ci-go.yml @@ -29,7 +29,15 @@ on: - 'go.work' - 'go.work.sum' - '.github/workflows/ci-go.yml' + # What the router's ui_test.go holds its UI compiler and its A2UI catalog to. + - 'sdks/testdata/ui/**' + - 'examples/voice_agents/swift_assistant/a2ui/prompt.json' + - 'examples/voice_agents/swift_assistant/app/SwiftAssistant/UIComponents.json' - '!**/*.md' + # Markdown the router embeds or its ui_test.go reads: they must stay after the *.md + # exclusion, which would otherwise drop them. + - 'acceleration/internal/agentdir/a2ui/*.md' + - 'examples/voice_agents/swift_assistant/a2ui/instructions.md' pull_request: branches: [ "**" ] # A draft runs nothing: CI starts when the pull request is marked ready (ready_for_review) @@ -57,7 +65,15 @@ on: - 'go.work' - 'go.work.sum' - '.github/workflows/ci-go.yml' + # What the router's ui_test.go holds its UI compiler and its A2UI catalog to. + - 'sdks/testdata/ui/**' + - 'examples/voice_agents/swift_assistant/a2ui/prompt.json' + - 'examples/voice_agents/swift_assistant/app/SwiftAssistant/UIComponents.json' - '!**/*.md' + # Markdown the router embeds or its ui_test.go reads: they must stay after the *.md + # exclusion, which would otherwise drop them. + - 'acceleration/internal/agentdir/a2ui/*.md' + - 'examples/voice_agents/swift_assistant/a2ui/instructions.md' permissions: contents: read diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 73cb7d92ba..8e5d30cb76 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -1039,6 +1039,27 @@ components: - fixed - session type: string + AgentDirectory: + description: 'An agent config as the directory it is synced from: agent.yaml, instructions.md, guardrail.md, its skills, its knowledge, its simulations and its UI files.' + properties: + files: + description: The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they store the agent as it is. + items: + $ref: '#/components/schemas/DirectoryFile' + type: array + name: + description: What the agent is called, as agent.yaml names it. + type: string + not_exported: + description: 'What this agent holds that its directory cannot say and a sync of these files would change, each in a sentence: a connector binding''s events, policy or timeout, a connector that grants no tools, a knowledge document that is not a text file, UI instructions no directory''s files were compiled into. Empty when a sync of these files leaves the agent as it is.' + items: + type: string + type: array + required: + - name + - files + - not_exported + type: object AgentDispatch: description: What the agent leaves to the customer's own server, which waits on /v1/dispatch. Omitted settings are disabled. properties: @@ -4963,6 +4984,45 @@ components: - completed - failed type: string + DirectoryFile: + description: One file of an agent directory, as a sync takes it and an export writes it. + properties: + content: + description: The file, whole, as text. + type: string + path: + description: 'Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, skills/.md or skills//SKILL.md with the files beside it, knowledge/, knowledge/urls.yaml, simulations/.yaml, ui/components.json, ui/blueprints.yaml.' + example: skills/refunds/SKILL.md + maxLength: 512 + minLength: 1 + type: string + required: + - path + - content + type: object + DirectoryProblem: + description: One thing wrong with an agent directory, at its place in a file, so an editor can point at it. + properties: + column: + description: The column, counted from 1. Left out with line. + example: 3 + format: int64 + type: integer + file: + description: The file's path in the directory. + example: agent.yaml + type: string + line: + description: The line, counted from 1. Left out when the problem is the file as a whole. + example: 12 + format: int64 + type: integer + message: + type: string + required: + - file + - message + type: object DispatchSetting: description: Whether this kind of work is left to the customer's own dispatch worker. enum: @@ -5061,18 +5121,35 @@ components: ErrorDetail: properties: code: - description: 'What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody''s edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection''s messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config''s tool groups names, and the message names it), insufficient_credits (a 402: the organization''s credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization''s spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization''s own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent''s limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant''s expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization''s tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization''s sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token''s usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller''s app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer''s own key here, and the message names the ones that are), campaign_locked (a 409: the campaign''s state does not allow the change, such as a launched campaign''s sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session''s questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know.' + description: 'What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody''s edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection''s messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config''s tool groups names, and the message names it), insufficient_credits (a 402: the organization''s credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization''s spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization''s own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent''s limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant''s expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization''s tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization''s sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token''s usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller''s app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer''s own key here, and the message names the ones that are), campaign_locked (a 409: the campaign''s state does not allow the change, such as a launched campaign''s sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session''s questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know.' type: string + conflicts: + description: What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. + items: + $ref: '#/components/schemas/SyncConflict' + type: array doc_url: description: Where the code is explained. format: uri type: string + last_change: + description: 'The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen.' + type: string limit: description: 'Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config''s sandbox. More may be added.' type: string message: description: What went wrong, for a person to read. Its wording may change; branch on code. type: string + problems: + description: What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. + items: + $ref: '#/components/schemas/DirectoryProblem' + type: array + problems_omitted: + description: 'How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed.' + format: int64 + type: integer type: $ref: '#/components/schemas/ErrorType' required: @@ -10521,6 +10598,83 @@ components: - reason - suspended_by type: object + SyncAgentFilesRequest: + description: |- + An agent directory as its files, which the router reads, so every client's directory means the same thing. The fields from instructions down are what a program sets in code beside the directory: each wins over what the files say, and is part of the hash. + + A request sends at most 1024 files, and the directory among them holds at most 1048576 bytes a file and 8388608 bytes in all. + + The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the part. The parts are, for every file of the directory in path order by byte, its path and its content; then, for each field from instructions down that is sent, its name and its value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags. for each tag in key order; skills with the number of skills in decimal, then for each skill in name order skills..description, .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files. for each file in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of the router's UI compiler, so a router that compiles ui differently syncs the directory again. A file sent that is no part of the directory is no part of the hash, so every client's sync of one folder has one hash. While a connector is left out sync_hash is another hash, so the sync that finds its connection is not taken for the one that left it out. + + What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. calls is always written whole: a call tool the file does not name goes back to its default. keyterms and tags are left as stored when the file has none, an empty list or mapping included, so a file cannot clear them. instructions, guardrail, the skills the config names, its UI instructions and its knowledge base are the directory's: a file taken out is taken out of the agent. simulations are left alone without a simulations file, and are exactly what the files declare with one. + properties: + base_change: + description: 'As base_change of POST /v1/agents/sync: the newest change the caller has already seen.' + type: string + check_changes: + description: 'As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over a setting somebody changed since the last one.' + type: boolean + dry_run: + description: 'Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes for what it would write over, the money for writing its knowledge included. What only the writes can tell is not told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. unchanged is true when the hash matches and a sync would do nothing.' + type: boolean + files: + description: 'The files of the agent''s folder, as they are on disk. A client sends what it finds and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no part of the limits or the hash.' + items: + $ref: '#/components/schemas/DirectoryFile' + maxItems: 1024 + type: array + greeting: + $ref: '#/components/schemas/Greeting' + description: In place of agent.yaml's greeting. + guardrail: + description: The guardrail a program gives in code, in place of guardrail.md. + type: string + harness: + $ref: '#/components/schemas/Harness' + description: In place of agent.yaml's harness. + instructions: + description: The system prompt a program gives in code, in place of instructions.md. + type: string + llm: + description: In place of agent.yaml's llm. + type: string + name: + description: What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the agent. + type: string + sandbox: + $ref: '#/components/schemas/Sandbox' + description: In place of agent.yaml's sandbox. + skills: + description: The skills a program writes in code, in place of every skill under skills/. An empty list names none. + items: + $ref: '#/components/schemas/SkillRequest' + type: array + sts: + description: In place of agent.yaml's sts. + type: string + stt: + description: In place of agent.yaml's stt. + type: string + subagent: + description: In place of agent.yaml's subagent. + type: string + tags: + additionalProperties: + type: string + description: 'Labels added to agent.yaml''s tags, winning where both name a key: what an SDK''s cost tracking writes.' + type: object + tts: + description: In place of agent.yaml's tts. + type: string + video: + $ref: '#/components/schemas/SessionVideo' + description: In place of agent.yaml's video. + voice: + description: In place of agent.yaml's voice. + type: string + required: + - files + type: object SyncAgentRequest: description: An agent directory as it is on disk. Everything after the simulations is what the directory's declaration decides rather than what it holds, and a setting left out leaves whatever is stored, so a model chosen in the dashboard survives a sync that says nothing about it. properties: @@ -10685,6 +10839,11 @@ components: type: object SyncAgentResult: properties: + changes: + description: 'What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it leaves as it is is not listed, and nothing is for a sync that found the hash unchanged.' + items: + $ref: '#/components/schemas/SyncChange' + type: array config: $ref: '#/components/schemas/AgentConfig' unchanged: @@ -10700,6 +10859,47 @@ components: - unchanged - config type: object + SyncChange: + description: One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes. + properties: + action: + enum: + - created + - updated + - deleted + type: string + name: + description: 'Which one: a skill''s name, a knowledge document''s source, a knowledge url''s url, a simulation''s name.' + type: string + resource_type: + description: What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. + enum: + - skill + - knowledge + - knowledge_url + - simulation + type: string + required: + - resource_type + - name + - action + type: object + SyncConflict: + description: One thing a sync would write over that somebody changed since the last sync. + properties: + name: + description: 'Which one: the field of an agent_config, such as llm or instructions; a skill''s name; a knowledge document''s source; a knowledge url''s url.' + type: string + removed: + description: True for a knowledge document the directory no longer has, which the sync would delete. + type: boolean + resource_type: + $ref: '#/components/schemas/AuditResourceType' + description: 'What was changed, as GET /v1/agents/configs/{id}/changes names it: agent_config, skill, knowledge or knowledge_url.' + required: + - resource_type + - name + type: object TagKeySummary: properties: cost_micros_total: @@ -14863,6 +15063,52 @@ paths: "503": $ref: '#/components/responses/Unavailable' summary: What was changed about an agent since its directory was last synced + /v1/agents/configs/{id}/directory: + get: + description: |- + The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ with the pages it is kept filled from in knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call tool at its default, a connector's tools when it grants every one), and a connector that says only its name written as the name alone. + + Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written with its connection's id, whatever label agent.yaml first named it by, and a skill the config no longer names is left out. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + operationId: getAgentDirectory + parameters: + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/AgentDirectory' + description: The agent's directory + headers: + X-Stream-Balance-Micros: + $ref: '#/components/headers/X-Stream-Balance-Micros' + X-Stream-Balance-Warning: + $ref: '#/components/headers/X-Stream-Balance-Warning' + X-Stream-Cost-Estimated: + $ref: '#/components/headers/X-Stream-Cost-Estimated' + X-Stream-Cost-Micros: + $ref: '#/components/headers/X-Stream-Cost-Micros' + "400": + $ref: '#/components/responses/BadRequest' + "401": + $ref: '#/components/responses/Unauthorized' + "402": + $ref: '#/components/responses/PaymentRequired' + "403": + $ref: '#/components/responses/Forbidden' + "404": + $ref: '#/components/responses/NotFound' + "500": + $ref: '#/components/responses/InternalError' + "503": + $ref: '#/components/responses/Unavailable' + summary: An agent config as the files of its directory /v1/agents/connections: get: description: |- @@ -21005,6 +21251,64 @@ paths: "503": $ref: '#/components/responses/Unavailable' summary: Store an agent directory's instructions, skills, knowledge, simulations and settings + /v1/agents/sync/files: + post: + description: |- + POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. + + A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. + + `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + operationId: syncAgentFiles + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/SyncAgentFilesRequest' + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/SyncAgentResult' + description: The config as stored, as it already was, or with dry_run as it would be stored + headers: + X-Stream-Balance-Micros: + $ref: '#/components/headers/X-Stream-Balance-Micros' + X-Stream-Balance-Warning: + $ref: '#/components/headers/X-Stream-Balance-Warning' + X-Stream-Cost-Estimated: + $ref: '#/components/headers/X-Stream-Cost-Estimated' + X-Stream-Cost-Micros: + $ref: '#/components/headers/X-Stream-Cost-Micros' + "400": + $ref: '#/components/responses/BadRequest' + "401": + $ref: '#/components/responses/Unauthorized' + "402": + $ref: '#/components/responses/PaymentRequired' + "403": + $ref: '#/components/responses/Forbidden' + "409": + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + description: Conflict + "413": + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + description: Request Entity Too Large + "500": + $ref: '#/components/responses/InternalError' + "503": + $ref: '#/components/responses/Unavailable' + summary: Store an agent directory sent as its files /v1/agents/users/{user_id}: get: description: |- diff --git a/acceleration/internal/api/admission_test.go b/acceleration/internal/api/admission_test.go index 8b00d9382e..e383bb9976 100644 --- a/acceleration/internal/api/admission_test.go +++ b/acceleration/internal/api/admission_test.go @@ -808,6 +808,26 @@ func (s *AdmissionSuite) TestAKnowledgeIngestWithNoCreditIsAPaymentRequiredAndWr s.Empty(s.documents(namespace)) } +func (s *AdmissionSuite) TestADryRunOfADirectoryWithKnowledgeAndNoCreditIsRefusedAsTheSyncWouldBe() { + name := "agent-" + s.utils.uuid() + s.refused(http.MethodPost, "/v1/agents/runs", s.run("echo/echo-model")) + body := map[string]any{"files": []map[string]string{ + {"path": "agent.yaml", "content": "name: " + name + "\n"}, + {"path": "knowledge/refunds.md", "content": "Refunds take five days.\n"}, + }} + + wet, _ := s.serverClient.call(http.MethodPost, "/v1/agents/sync/files", body) + body["dry_run"] = true + dry, payload := s.serverClient.call(http.MethodPost, "/v1/agents/sync/files", body) + + s.Require().Equal(http.StatusPaymentRequired, dry, string(payload)) + s.Equal(wet, dry) + var answered ErrorResponse + s.Require().NoError(json.Unmarshal(payload, &answered)) + s.Equal(codeInsufficientCredits, answered.Error.Code) + s.Empty(s.documents(name)) +} + func (s *AdmissionSuite) TestAKnowledgeIngestForASuspendedAccountIsForbidden() { s.usage.Credit(s.T(), s.organization(), 10_000_000) s.usage.Suspend(s.T(), s.organization(), "fraud review "+s.utils.uuid()) diff --git a/acceleration/internal/api/apierror.go b/acceleration/internal/api/apierror.go index 9586cc22bd..fbc75ee214 100644 --- a/acceleration/internal/api/apierror.go +++ b/acceleration/internal/api/apierror.go @@ -108,6 +108,7 @@ const ( codeProviderTakesNoKey = "provider_takes_no_key" codeCardedSessionToNative = "carded_session_to_native" codeUnsyncedChanges = "unsynced_changes" + codeInvalidAgentDirectory = "invalid_agent_directory" codePhoneNumberNeedsAddress = "phone_number_needs_address" codePhoneVendorFailed = "phone_vendor_failed" codePhoneNumberSettling = "phone_number_settling" @@ -202,18 +203,20 @@ func (e APIError) DocURL() string { return errorDocs + e.Code } // MarshalJSON answers the failure in the error envelope every failure has. func (e APIError) MarshalJSON() ([]byte, error) { + return marshalFailure(e.detail()) +} + +func (e APIError) detail() ErrorDetail { + return ErrorDetail{Message: e.Message, Type: e.Type, Code: e.Code, DocURL: e.DocURL(), Limit: e.Limit} +} + +func marshalFailure(detail ErrorDetail) ([]byte, error) { encoded := &bytes.Buffer{} encoder := json.NewEncoder(encoded) // A message quotes what was wrong with the request, which is read rather than put in // a page: "expected length >= 1" should not arrive as "\u003e=". encoder.SetEscapeHTML(false) - err := encoder.Encode(ErrorResponse{Error: ErrorDetail{ - Message: e.Message, - Type: e.Type, - Code: e.Code, - DocURL: e.DocURL(), - Limit: e.Limit, - }}) + err := encoder.Encode(ErrorResponse{Error: detail}) return bytes.TrimSuffix(encoded.Bytes(), []byte("\n")), err } @@ -236,11 +239,15 @@ func (*ErrorResponse) TransformSchema(_ huma.Registry, schema *huma.Schema) *hum // ErrorDetail is what went wrong. type ErrorDetail struct { - Message string `json:"message" doc:"What went wrong, for a person to read. Its wording may change; branch on code."` - Type ErrorType `json:"type"` - Code string `json:"code" doc:"What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know."` - DocURL string `json:"doc_url" format:"uri" doc:"Where the code is explained."` - Limit string `json:"limit,omitempty" doc:"Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added."` + Message string `json:"message" doc:"What went wrong, for a person to read. Its wording may change; branch on code."` + Type ErrorType `json:"type"` + Code string `json:"code" doc:"What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know."` + DocURL string `json:"doc_url" format:"uri" doc:"Where the code is explained."` + Limit string `json:"limit,omitempty" doc:"Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added."` + Problems []DirectoryProblem `json:"problems,omitempty" nullable:"false" doc:"What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest."` + ProblemsOmitted int `json:"problems_omitted,omitempty" doc:"How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed."` + Conflicts []SyncConflict `json:"conflicts,omitempty" nullable:"false" doc:"What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only."` + LastChange string `json:"last_change,omitempty" doc:"The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen."` } // newAPIError is a failure of errorType with the code of its type. A failure a client diff --git a/acceleration/internal/api/config_patch.go b/acceleration/internal/api/config_patch.go index f2ffab9d97..8a114d51a7 100644 --- a/acceleration/internal/api/config_patch.go +++ b/acceleration/internal/api/config_patch.go @@ -204,6 +204,7 @@ func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfig } config.Guardrail = override(config.Guardrail, patch.Guardrail) config.ReviewInstructions = reviewOf(config.ReviewInstructions, patch.Review) + config.UISource = keptUISource(config, override(config.UIInstructions, patch.UiInstructions)) config.UIInstructions = override(config.UIInstructions, patch.UiInstructions) config.Skills = override(config.Skills, patch.Skills) if patch.Connectors != nil { diff --git a/acceleration/internal/api/configs.go b/acceleration/internal/api/configs.go index a16dd8e2af..d75c5444fa 100644 --- a/acceleration/internal/api/configs.go +++ b/acceleration/internal/api/configs.go @@ -17,6 +17,7 @@ import ( "strings" "time" + "github.com/GetStream/Vision-Agents/acceleration/internal/agentdir" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/egress" @@ -313,6 +314,7 @@ func (s *Server) updateAgentConfig(ctx context.Context, request *updateAgentConf } config.ReviewInstructions = reviewOf(existing.ReviewInstructions, request.Body.Review) config.UIInstructions = override(existing.UIInstructions, request.Body.UiInstructions) + config.UISource = keptUISource(existing, config.UIInstructions) // Field by field, as the doc says of an update: a block naming only the limit keeps // enabled and the zone. config.Scheduling = schedulingOr(existing.Scheduling, request.Body.Scheduling) @@ -1528,8 +1530,7 @@ func skillComplaint(request SkillRequest) (string, bool) { } size := 0 for name, content := range files { - if name == "" || path.IsAbs(name) || path.Clean(name) != name || name == ".." || - strings.HasPrefix(name, "../") || strings.Contains(name, `\`) { + if !agentdir.ValidPath(name) { return fmt.Sprintf("skill file %q is not a path inside the skill's folder", name), false } size += len(content) diff --git a/acceleration/internal/api/directory.go b/acceleration/internal/api/directory.go new file mode 100644 index 0000000000..7f6bcc38fa --- /dev/null +++ b/acceleration/internal/api/directory.go @@ -0,0 +1,1024 @@ +package api + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" + "reflect" + "slices" + "strconv" + "strings" + "time" + + "github.com/danielgtaylor/huma/v2" + + "github.com/GetStream/Vision-Agents/acceleration/internal/agentdir" + "github.com/GetStream/Vision-Agents/acceleration/internal/pricing" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// maxDirectoryBody is the body of a sync of a directory's files: twice what the files may +// hold, since JSON escapes their line breaks and quotes. +const maxDirectoryBody = 2 * agentdir.MaxBytes + +// DirectoryFile is one file of an agent directory. +type DirectoryFile struct { + Path string `json:"path" minLength:"1" maxLength:"512" example:"skills/refunds/SKILL.md" doc:"Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, skills/.md or skills//SKILL.md with the files beside it, knowledge/, knowledge/urls.yaml, simulations/.yaml, ui/components.json, ui/blueprints.yaml."` + Content string `json:"content" doc:"The file, whole, as text."` +} + +func (*DirectoryFile) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One file of an agent directory, as a sync takes it and an export writes it." + return schema +} + +// DirectoryProblem is one thing wrong with an agent directory, at its place in a file. +type DirectoryProblem struct { + File string `json:"file" example:"agent.yaml" doc:"The file's path in the directory."` + Line int `json:"line,omitempty" example:"12" doc:"The line, counted from 1. Left out when the problem is the file as a whole."` + Column int `json:"column,omitempty" example:"3" doc:"The column, counted from 1. Left out with line."` + Message string `json:"message"` +} + +func (*DirectoryProblem) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One thing wrong with an agent directory, at its place in a file, so an editor can point at it." + return schema +} + +// A refusal names at most maxProblems problems, and its message the first maxProblemsSaid. +const ( + maxProblems = 100 + maxProblemsSaid = 5 +) + +// directoryRefusal is a directory refused for what its files say, with every problem at its +// place. +type directoryRefusal struct { + APIError + problems []DirectoryProblem + // omitted is how many more problems there are than the ones named. + omitted int +} + +func (d directoryRefusal) MarshalJSON() ([]byte, error) { + detail := d.detail() + detail.Problems, detail.ProblemsOmitted = d.problems, d.omitted + return marshalFailure(detail) +} + +// invalidDirectory is the refusal of a directory that does not read. Any other error is +// returned as it is. +func invalidDirectory(err error) error { + var problems agentdir.Problems + if !errors.As(err, &problems) { + return err + } + // Bounded, whatever was sent: the first problems are what somebody fixes first. + said := problems[:min(len(problems), maxProblemsSaid)] + message := said.Error() + if more := len(problems) - len(said); more > 0 { + message += fmt.Sprintf("; and %d more", more) + } + refusal := directoryRefusal{APIError: invalidRequest(message)} + refusal.Code = codeInvalidAgentDirectory + for _, problem := range problems[:min(len(problems), maxProblems)] { + refusal.problems = append(refusal.problems, DirectoryProblem(problem)) + } + refusal.omitted = max(len(problems)-maxProblems, 0) + return refusal +} + +// SyncAgentFilesRequest is an agent directory as its files, with what a program sets beside it. +type SyncAgentFilesRequest struct { + Name string `json:"name,omitempty" doc:"What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the agent."` + Files []DirectoryFile `json:"files" nullable:"false" doc:"The files of the agent's folder, as they are on disk. A client sends what it finds and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no part of the limits or the hash."` + CheckChanges *bool `json:"check_changes,omitempty" doc:"As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over a setting somebody changed since the last one."` + BaseChange *string `json:"base_change,omitempty" doc:"As base_change of POST /v1/agents/sync: the newest change the caller has already seen."` + DryRun *bool `json:"dry_run,omitempty" doc:"Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes for what it would write over, the money for writing its knowledge included. What only the writes can tell is not told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. unchanged is true when the hash matches and a sync would do nothing."` + // What follows is what a program sets in code beside the directory, which wins over the files. + Instructions *string `json:"instructions,omitempty" doc:"The system prompt a program gives in code, in place of instructions.md."` + Guardrail *string `json:"guardrail,omitempty" doc:"The guardrail a program gives in code, in place of guardrail.md."` + Skills *[]SkillRequest `json:"skills,omitempty" doc:"The skills a program writes in code, in place of every skill under skills/. An empty list names none."` + Harness *Harness `json:"harness,omitempty" doc:"In place of agent.yaml's harness."` + Subagent *string `json:"subagent,omitempty" doc:"In place of agent.yaml's subagent."` + Sandbox *Sandbox `json:"sandbox,omitempty" doc:"In place of agent.yaml's sandbox."` + Tags *map[string]string `json:"tags,omitempty" doc:"Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes."` + Llm *string `json:"llm,omitempty" doc:"In place of agent.yaml's llm."` + Stt *string `json:"stt,omitempty" doc:"In place of agent.yaml's stt."` + Tts *string `json:"tts,omitempty" doc:"In place of agent.yaml's tts."` + Sts *string `json:"sts,omitempty" doc:"In place of agent.yaml's sts."` + Voice *string `json:"voice,omitempty" doc:"In place of agent.yaml's voice."` + Greeting *Greeting `json:"greeting,omitempty" doc:"In place of agent.yaml's greeting."` + Video *SessionVideo `json:"video,omitempty" doc:"In place of agent.yaml's video."` +} + +func (*SyncAgentFilesRequest) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "An agent directory as its files, which the router reads, so every client's " + + "directory means the same thing. The " + + "fields from instructions down are what a program sets in code beside the directory: each wins " + + "over what the files say, and is part of the hash.\n\n" + + fmt.Sprintf("A request sends at most %d files, and the directory among them holds at most %d bytes "+ + "a file and %d bytes in all.\n\n", agentdir.MaxFiles, agentdir.MaxFileBytes, agentdir.MaxBytes) + + "The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, " + + "of a run of parts, each written as its length in bytes in decimal, a colon and the part. The " + + "parts are, for every file of the directory in path order by byte, its path and its content; " + + "then, for each field from instructions down that is sent, its name and its value, in this " + + "order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as " + + "sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags. " + + "for each tag in key order; skills with the number of skills in decimal, then for each skill in " + + "name order skills..description, .instructions, .deadline_ms in decimal, .capture_video as " + + "true or false, and .files. for each file in path order; then, for a directory whose " + + "agent.yaml has a ui key, ui and the version of the router's UI compiler, so a router that " + + "compiles ui differently syncs the directory again. A file sent that is no part of the " + + "directory is no part of the hash, so every client's sync of one folder has one hash. While a " + + "connector is left out sync_hash is another hash, so the sync that finds its connection is " + + "not taken for the one that left it out.\n\n" + + "What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the " + + "voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, " + + "chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. " + + "calls is always written whole: a call tool the file does not name goes back to its default. " + + "keyterms and tags are left as stored when the file has none, an empty list or mapping " + + "included, so a file cannot clear them. instructions, guardrail, the skills the config names, " + + "its UI instructions and its knowledge base are the directory's: a file taken out is taken " + + "out of the agent. simulations are left alone without a simulations file, and are exactly " + + "what the files declare with one." + schema.Properties["files"].MaxItems = new(agentdir.MaxFiles) + return schema +} + +// keptUISource is what a config's UI instructions were compiled from, for as long as they are +// those instructions: once somebody writes others, the files no longer say what the agent is +// told, and an export says so instead of writing them back. +func keptUISource(stored store.AgentConfig, instructions string) *store.UISource { + if instructions != stored.UIInstructions { + return nil + } + return stored.UISource +} + +// directorySync is a sync and what no field of its request carries. A sync of a directory's +// files has all of it; one a client sent as fields has the request alone. +type directorySync struct { + body SyncAgentRequest + // directory is what the files said, for a sync of files: where a refusal points. + directory *agentdir.Directory + // ui is what the UI instructions were compiled from, which an export writes back. + ui *store.UISource + warnings []string + dryRun bool +} + +// readDirectory reads the files a sync sent into the request they amount to. The router +// reads them, rather than each client, so every client's directory means the same thing. +func (s *Server) readDirectory(ctx context.Context, customerID string, sent SyncAgentFilesRequest) (directorySync, error) { + files := make([]agentdir.File, 0, len(sent.Files)) + for _, file := range sent.Files { + files = append(files, agentdir.File(file)) + } + // Everything wrong is said at once: what the files say that does not read, and then what + // the settings that did read may not be. + directory, err := agentdir.Parse(files) + var problems agentdir.Problems + if !errors.As(err, &problems) && err != nil { + return directorySync{}, err + } + if directory == nil { + return directorySync{}, invalidDirectory(problems) + } + + read := directorySync{directory: directory, dryRun: value(sent.DryRun), body: SyncAgentRequest{ + Name: cmp.Or(strings.TrimSpace(sent.Name), directory.Settings.Name), + CheckChanges: sent.CheckChanges, BaseChange: sent.BaseChange, + }} + if read.body.Name == "" { + problems = append(problems, agentdir.Problem{File: agentdir.AgentFile, Line: 1, Column: 1, + Message: "the agent has no name: add name to agent.yaml, or send name with the files"}) + } + declareDirectory(&read.body, directory) + if ui := directory.UI; ui != nil { + read.body.UiInstructions = optional(ui.Instructions) + read.ui = &store.UISource{ + Format: ui.Settings.Format, Keep: ui.Settings.Keep, PatchMode: ui.Settings.PatchMode, + VoiceUI: ui.Settings.VoiceUI, Rules: ui.Settings.Rules, + Components: ui.Components, Blueprints: ui.Blueprints, + } + } + written := writtenInCode(&read.body, sent) + unbound, err := s.bindDirectoryConnectors(ctx, customerID, directory, &read) + if err != nil { + return directorySync{}, err + } + problems = append(append(problems, unbound...), s.schemaProblems(directory, read.body, problems)...) + if len(problems) > 0 { + return directorySync{}, invalidDirectory(problems) + } + + beside := written + if directory.UI != nil { + beside = append(beside, "ui", agentdir.UIVersion) + } + // Another hash while a connector is left out, so the sync that finds its connection is not + // taken for this one and written. + for _, connector := range value(read.body.LeftOutConnectors) { + beside = append(beside, "left out", connector.Name, connector.ConnectorId, connector.Connection) + } + read.body.Hash = agentdir.Hash(directory.Files, beside...) + if ignored := directory.Ignored; len(ignored) > 0 { + named := strings.Join(ignored[:min(len(ignored), 3)], ", ") + if len(ignored) > 3 { + named += fmt.Sprintf(" and %d more", len(ignored)-3) + } + read.warnings = append(read.warnings, fmt.Sprintf( + "%d files sent are not part of an agent directory, so they were left out: %s", len(ignored), named)) + } + return read, nil +} + +// writtenInCode puts what a program set in code beside the directory over what its files +// say, and returns each as the hash takes it: its name and then its value, in the order +// SyncAgentFilesRequest documents. +func writtenInCode(body *SyncAgentRequest, sent SyncAgentFilesRequest) []string { + var written []string + said := func(name, text string) { written = append(written, name, text) } + text := func(name string, into **string, sent *string) { + if sent != nil { + *into = sent + said(name, *sent) + } + } + text("instructions", &body.Instructions, sent.Instructions) + text("guardrail", &body.Guardrail, sent.Guardrail) + if sent.Harness != nil { + body.Harness = sent.Harness + said("harness", string(*sent.Harness)) + } + text("subagent", &body.Subagent, sent.Subagent) + if sent.Sandbox != nil { + body.Sandbox = sent.Sandbox + said("sandbox", string(*sent.Sandbox)) + } + text("llm", &body.Llm, sent.Llm) + text("stt", &body.Stt, sent.Stt) + text("tts", &body.Tts, sent.Tts) + text("sts", &body.Sts, sent.Sts) + text("voice", &body.Voice, sent.Voice) + if greeting := sent.Greeting; greeting != nil { + body.Greeting = greeting + said("greeting.text", greeting.Text) + if greeting.Mode != nil { + said("greeting.mode", string(*greeting.Mode)) + } + } + if video := sent.Video; video != nil { + body.Video = video + if video.Source != nil { + said("video.source", *video.Source) + } + if video.MaxFrames != nil { + said("video.max_frames", strconv.Itoa(*video.MaxFrames)) + } + } + if sent.Tags != nil { + tags := maps.Clone(value(body.Tags)) + if tags == nil { + tags = map[string]string{} + } + for _, key := range slices.Sorted(maps.Keys(*sent.Tags)) { + tags[key] = (*sent.Tags)[key] + said("tags."+key, tags[key]) + } + body.Tags = &tags + } + if sent.Skills != nil { + skills := slices.SortedFunc(slices.Values(*sent.Skills), func(a, b SkillRequest) int { return strings.Compare(a.Name, b.Name) }) + body.Skills = nil + if len(skills) > 0 { + body.Skills = sent.Skills + } + said("skills", strconv.Itoa(len(skills))) + for _, skill := range skills { + at := "skills." + skill.Name + "." + said(at+"description", skill.Description) + said(at+"instructions", skill.Instructions) + if skill.DeadlineMs != nil { + said(at+"deadline_ms", strconv.FormatInt(*skill.DeadlineMs, 10)) + } + if skill.CaptureVideo != nil { + said(at+"capture_video", strconv.FormatBool(*skill.CaptureVideo)) + } + for _, file := range slices.Sorted(maps.Keys(value(skill.Files))) { + said(at+"files."+file, (*skill.Files)[file]) + } + } + } + return written +} + +// declareDirectory carries what a directory says onto a sync request. Only what its files +// name is set, so the sync leaves whatever is stored for the rest. +func declareDirectory(body *SyncAgentRequest, directory *agentdir.Directory) { + settings := directory.Settings + body.Instructions = optional(directory.Instructions) + body.Guardrail = optional(directory.Guardrail) + if len(directory.Skills) > 0 { + skills := make([]SkillRequest, 0, len(directory.Skills)) + for _, skill := range directory.Skills { + declared := SkillRequest{ + Name: skill.Name, Description: skill.Description, Instructions: skill.Instructions, + CaptureVideo: &skill.CaptureVideo, + } + if skill.Deadline > 0 { + declared.DeadlineMs = new(skill.Deadline.Milliseconds()) + } + if len(skill.Files) > 0 { + declared.Files = &skill.Files + } + skills = append(skills, declared) + } + body.Skills = &skills + } + if len(directory.Knowledge) > 0 { + documents := make([]KnowledgeDocument, 0, len(directory.Knowledge)) + for _, document := range directory.Knowledge { + documents = append(documents, KnowledgeDocument(document)) + } + body.Knowledge = &documents + } + if len(directory.KnowledgeURLs) > 0 { + pages := make([]KnowledgeUrlDeclaration, 0, len(directory.KnowledgeURLs)) + for _, page := range directory.KnowledgeURLs { + declared := KnowledgeUrlDeclaration{Url: page.URL, Title: optional(page.Title), Description: optional(page.Description)} + if page.RefreshHours > 0 { + declared.RefreshHours = &page.RefreshHours + } + pages = append(pages, declared) + } + body.KnowledgeUrls = &pages + } + if directory.Simulations != nil { + simulations := make([]SimulationDeclaration, 0, len(directory.Simulations)) + for _, simulation := range directory.Simulations { + declared := SimulationDeclaration{ + Name: simulation.Name, Scenario: simulation.Scenario, Assertion: simulation.Assertion, + Mode: optional(simulation.Mode), + Variations: positive(simulation.Variations), + MaxTurns: positive(simulation.MaxTurns), + CallerTarget: optional(simulation.CallerTarget), JudgeTarget: optional(simulation.JudgeTarget), + CallerStt: optional(simulation.CallerSTT), CallerTts: optional(simulation.CallerTTS), + CallerVoice: optional(simulation.CallerVoice), + } + if len(simulation.Tags) > 0 { + declared.Tags = &simulation.Tags + } + simulations = append(simulations, declared) + } + body.Simulations = &simulations + } + + body.Role = named[AgentRole](settings.Role) + body.Mode = named[AgentMode](settings.Mode) + body.Region = optional(settings.Region) + body.Stt = optional(settings.STT) + body.Tts = optional(settings.TTS) + body.Sts = settings.STS + body.Voice = optional(settings.Voice) + body.Llm = optional(settings.LLM) + body.Harness = named[Harness](settings.Harness) + body.Subagent = optional(settings.Subagent) + body.Search = optional(settings.Search) + // Sent even empty, since that is how a file turns drawing off. + body.Image = settings.Image + if settings.Greeting != nil { + body.Greeting = &Greeting{Text: settings.Greeting.Text, Mode: named[GreetingMode](settings.Greeting.Mode)} + } + body.Sandbox = named[Sandbox](settings.Sandbox) + if options := settings.SandboxOptions; options != nil { + body.SandboxOptions = &SandboxOptions{ + Image: &options.Image, Setup: &options.Setup, TimeoutMs: new(int(options.Timeout.Milliseconds())), + Cpu: &options.CPU, MemoryGb: &options.MemoryGB, DiskGb: &options.DiskGB, Network: &options.Network, + AllowedDomains: &options.AllowedDomains, NetworkAllowList: &options.NetworkAllowList, + } + } + if settings.Tools != nil { + groups := make([]ToolGroup, 0, len(*settings.Tools)) + for _, group := range *settings.Tools { + groups = append(groups, ToolGroup{ + Name: group.Name, Tools: group.Tools, + Loading: named[ToolLoading](group.Loading), OutputRetention: optional(group.OutputRetention), + }) + } + body.Tools = &groups + } + if channels := settings.Channels; channels != nil { + line := func(number string) *ChannelLineRequest { + if number == "" { + return nil + } + return &ChannelLineRequest{Number: number} + } + body.Channels = &AgentChannels{ + Whatsapp: line(channels.WhatsApp), Sms: line(channels.SMS), Imessage: line(channels.IMessage), + Identity: named[ChannelIdentity](channels.Identity), + } + } + if settings.ChatChannels != nil { + channels := make([]AgentChatChannel, 0, len(*settings.ChatChannels)) + for _, channel := range *settings.ChatChannels { + channels = append(channels, AgentChatChannel{Type: channel.Type, Answer: named[ChatChannelAnswer](channel.Answer)}) + } + body.ChatChannels = &channels + } + if scheduling := settings.Scheduling; scheduling != nil { + body.Scheduling = &AgentScheduling{ + Enabled: scheduling.Enabled, MaxTasksPerUser: scheduling.MaxTasksPerUser, + DefaultTimezone: optional(scheduling.DefaultTimezone), + } + } + body.Calls = declaredCalls(settings.Calls) + if floor := settings.FloorControl; floor != nil { + body.FloorControl = &FloorControl{Model: floor.Model, MaxWaitMs: floor.MaxWaitMs} + } + if len(settings.Keyterms) > 0 { + body.Keyterms = &settings.Keyterms + } + if len(settings.Tags) > 0 { + body.Tags = &settings.Tags + } + if settings.Agents != nil { + agents := make([]ChildAgent, 0, len(*settings.Agents)) + for _, agent := range *settings.Agents { + declared := ChildAgent{ + Config: agent.Config, Tool: agent.Tool, Description: optional(agent.Description), + TimeoutMs: positive(agent.TimeoutMs), + } + if agent.MaxToolRounds != 0 { + declared.MaxToolRounds = &agent.MaxToolRounds + } + agents = append(agents, declared) + } + body.Agents = &agents + } + if video := settings.Video; video != nil { + body.Video = &SessionVideo{MaxFrames: &video.MaxFrames, Source: optional(video.Source)} + } + if dispatch := settings.Dispatch; dispatch != nil { + body.Dispatch = &AgentDispatch{ + IncomingCall: named[DispatchSetting](dispatch.IncomingCall), Text: named[DispatchSetting](dispatch.Text), + } + } +} + +// declaredCalls always fills the whole block, with the default for what the file leaves +// out, so a sync replaces what the dashboard set. +func declaredCalls(calls *agentdir.Calls) *AgentCalls { + if calls == nil { + calls = &agentdir.Calls{} + } + destinations := make([]TransferDestination, 0, len(calls.Transfer.Destinations)) + for _, destination := range calls.Transfer.Destinations { + destinations = append(destinations, TransferDestination(destination)) + } + return &AgentCalls{ + EndCall: &EndCallSettings{Enabled: new(value(calls.EndCall.Enabled)), When: calls.EndCall.When}, + Press: &PressSettings{Enabled: new(calls.Press.Enabled == nil || *calls.Press.Enabled)}, + Transfer: &TransferSettings{Enabled: new(calls.Transfer.Enabled == nil || *calls.Transfer.Enabled), Destinations: destinations}, + } +} + +// bindDirectoryConnectors turns the connectors agent.yaml names into the bindings a sync +// stores, finding each connection it names among the app's own by id or by label. +// +// An entry whose connection the app does not have is left out and recorded, so the rest of the +// agent still syncs, unless the entry is required: a session needs that one. +func (s *Server) bindDirectoryConnectors( + ctx context.Context, customerID string, directory *agentdir.Directory, read *directorySync, +) (agentdir.Problems, error) { + if directory.Settings.Connectors == nil { + return nil, nil + } + var problems agentdir.Problems + bindings := []AgentConnectorBinding{} + var leftOut []LeftOutConnector + for index, entry := range *directory.Settings.Connectors { + fail := func(format string, args ...any) { + line, column := directory.Locate(fmt.Sprintf("connectors[%d]", index)) + problems = append(problems, agentdir.Problem{ + File: agentdir.AgentFile, Line: line, Column: column, + Message: fmt.Sprintf("connector %q: ", entry.Name) + fmt.Sprintf(format, args...), + }) + } + binding := AgentConnectorBinding{ + Name: entry.Name, + ConnectorId: cmp.Or(entry.Connector, entry.Name), + Connection: AgentConnectorSelection{Type: AgentConnectorSelectionTypeSession}, + Tools: []ConnectorToolGrant{}, + ToolPatterns: &[]string{"*"}, + Required: entry.Required, + Sandbox: entry.Sandbox, + RequireApproval: value(entry.RequireApproval), + Loading: named[ToolLoading](entry.Loading), + OutputRetention: optional(entry.OutputRetention), + } + if entry.Tools != nil { + binding.ToolPatterns = entry.Tools + } + if entry.Connection != nil { + named, err := s.store.AppConnectionsNamed(ctx, customerID, binding.ConnectorId, *entry.Connection) + if err != nil { + return nil, err + } + // An id wins over a label, and a label names a connection only when one has it. + if byID := slices.IndexFunc(named, func(c store.ConnectorConnection) bool { return c.ID == *entry.Connection }); byID >= 0 { + named = named[byID : byID+1] + } + switch { + case len(named) > 1: + fail("%q matches %d app connections: name one by its id", *entry.Connection, len(named)) + continue + case len(named) == 0 && value(entry.Required): + fail("no app connection with id or label %q: add the connection, or drop required", *entry.Connection) + continue + case len(named) == 0: + leftOut = append(leftOut, LeftOutConnector{Name: entry.Name, ConnectorId: binding.ConnectorId, Connection: *entry.Connection}) + read.warnings = append(read.warnings, fmt.Sprintf( + "connector %q was left out: the app has no connection with id or label %q", entry.Name, *entry.Connection)) + continue + } + binding.Connection = AgentConnectorSelection{Type: AgentConnectorSelectionTypeFixed, ConnectionId: &named[0].ID} + } + bindings = append(bindings, binding) + } + read.body.Connectors = &bindings + if len(leftOut) > 0 { + read.body.LeftOutConnectors = &leftOut + } + return problems, nil +} + +// schemaProblems holds the request a directory amounts to against the schema a request sent +// as fields is held to, so both are refused for the same things. Each problem is put where +// agent.yaml says the setting, or at the files a setting was read from, and one about files +// that read already found wrong is left to what read said of them. +func (s *Server) schemaProblems(directory *agentdir.Directory, body SyncAgentRequest, read agentdir.Problems) agentdir.Problems { + encoded, err := json.Marshal(body) + if err != nil { + return agentdir.Problems{{File: agentdir.AgentFile, Message: err.Error()}} + } + var decoded any + if err := json.Unmarshal(encoded, &decoded); err != nil { + return agentdir.Problems{{File: agentdir.AgentFile, Message: err.Error()}} + } + result := &huma.ValidateResult{} + huma.Validate(s.schemas, s.schemas.Schema(reflect.TypeFor[SyncAgentRequest](), true, ""), + huma.NewPathBuffer(nil, 0), huma.ModeWriteToServer, decoded, result) + + elsewhere := map[string]string{ + "skills": agentdir.SkillsDir, "knowledge": agentdir.KnowledgeDir, + "knowledge_urls": agentdir.KnowledgeURLsFile, "simulations": agentdir.SimulationsDir, + "instructions": agentdir.InstructionsFile, "guardrail": agentdir.GuardrailFile, + } + var problems agentdir.Problems + for _, failure := range result.Errors { + var detail *huma.ErrorDetail + if !errors.As(failure, &detail) { + problems = append(problems, agentdir.Problem{File: agentdir.AgentFile, Message: failure.Error()}) + continue + } + problem := agentdir.Problem{File: agentdir.AgentFile, Message: detail.Location + ": " + detail.Message} + setting, _, _ := strings.Cut(strings.NewReplacer("[", ".").Replace(detail.Location), ".") + if file, found := elsewhere[setting]; found { + // What a file there already had wrong with it is what the schema is refusing. + if slices.ContainsFunc(read, func(said agentdir.Problem) bool { return strings.HasPrefix(said.File, file) }) { + continue + } + problem.File = file + } else { + problem.Line, problem.Column = directory.Locate(detail.Location) + } + problems = append(problems, problem) + } + return problems +} + +// named is text as the enum a setting is one of, or nil for none. +func named[T ~string](text string) *T { + if text == "" { + return nil + } + return new(T(text)) +} + +// positive is a count, or nil for none. +func positive(count int) *int { + if count <= 0 { + return nil + } + return &count +} + +// AgentDirectory is an agent as the directory it is synced from. +type AgentDirectory struct { + Name string `json:"name" doc:"What the agent is called, as agent.yaml names it."` + Files []DirectoryFile `json:"files" nullable:"false" doc:"The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they store the agent as it is."` + NotExported []string `json:"not_exported" nullable:"false" doc:"What this agent holds that its directory cannot say and a sync of these files would change, each in a sentence: a connector binding's events, policy or timeout, a connector that grants no tools, a knowledge document that is not a text file, UI instructions no directory's files were compiled into. Empty when a sync of these files leaves the agent as it is."` +} + +func (*AgentDirectory) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "An agent config as the directory it is synced from: agent.yaml, instructions.md, " + + "guardrail.md, its skills, its knowledge, its simulations and its UI files." + return schema +} + +// agentDirectory writes a stored agent as its directory. +func (s *Server) agentDirectory(ctx context.Context, id string) (AgentDirectory, error) { + customerID, ok := CustomerFrom(ctx) + if !ok { + return AgentDirectory{}, errMissingCustomer + } + if s.store == nil { + return AgentDirectory{}, errNoConfigs + } + config, err := s.configs.AgentConfig(ctx, customerID, id) + if err != nil { + return AgentDirectory{}, errUnknownConfig + } + + directory := &agentdir.Directory{Instructions: config.Instructions, Guardrail: config.Guardrail} + exported := AgentDirectory{Name: config.Name, NotExported: []string{}} + note := func(format string, args ...any) { + exported.NotExported = append(exported.NotExported, fmt.Sprintf(format, args...)) + } + directory.Settings = directorySettings(config, note) + switch ui := config.UISource; { + case ui != nil: + directory.UI = &agentdir.UI{ + Settings: agentdir.UISettings{ + Format: ui.Format, Keep: ui.Keep, PatchMode: ui.PatchMode, VoiceUI: ui.VoiceUI, Rules: ui.Rules, + }, + Components: ui.Components, Blueprints: ui.Blueprints, + } + case config.UIInstructions != "": + note("The agent's UI instructions were not compiled from a directory's files, so there is no ui key to write and a sync of these files removes them.") + } + + skills, err := s.store.CustomerSkills(ctx, customerID, config.ID) + if err != nil { + return AgentDirectory{}, err + } + slices.SortFunc(skills, func(a, b store.Skill) int { return strings.Compare(a.Name, b.Name) }) + for _, skill := range skills { + if slices.Contains(config.Skills, skill.Name) { + directory.Skills = append(directory.Skills, agentdir.Skill{ + Name: skill.Name, Description: skill.Description, Instructions: skill.Instructions, + Deadline: time.Duration(skill.DeadlineMs) * time.Millisecond, CaptureVideo: skill.CaptureVideo, + Files: skill.Files, + }) + } + } + + var documents []store.KnowledgeDocument + if namespace := config.KnowledgeNamespace; namespace != "" { + if namespace != config.Name { + note("The agent reads the knowledge base %q. A directory's knowledge is the base named after the agent, so a sync of these files writes it there.", namespace) + } + if documents, err = s.store.CustomerKnowledgeDocumentsWithText(ctx, customerID, namespace); err != nil { + return AgentDirectory{}, err + } + slices.SortFunc(documents, func(a, b store.KnowledgeDocument) int { return strings.Compare(a.Source, b.Source) }) + if s.pages != nil { + pages, err := s.pages.List(ctx, customerID, namespace) + if err != nil { + return AgentDirectory{}, err + } + for _, page := range pages { + directory.KnowledgeURLs = append(directory.KnowledgeURLs, agentdir.KnowledgeURL{ + URL: page.URL, Title: page.DeclaredTitle, Description: page.Description, RefreshHours: page.RefreshHours, + }) + } + } + } + + simulations, err := s.store.CustomerSimulations(ctx, customerID) + if err != nil { + return AgentDirectory{}, err + } + slices.SortFunc(simulations, func(a, b store.Simulation) int { return strings.Compare(a.Name, b.Name) }) + for _, simulation := range simulations { + if simulation.ConfigID != config.ID { + continue + } + declared := agentdir.Simulation{ + Name: simulation.Name, Scenario: simulation.Scenario, Assertion: simulation.Assertion, + CallerTarget: simulation.CallerTarget, JudgeTarget: simulation.JudgeTarget, + CallerSTT: simulation.CallerSTT, CallerTTS: simulation.CallerTTS, CallerVoice: simulation.CallerVoice, + Tags: simulation.Tags, + } + // What a simulation that says nothing is stored with is left out again. + if simulation.Mode != store.SimulationText { + declared.Mode = simulation.Mode + } + if simulation.Variations > 1 { + declared.Variations = simulation.Variations + } + if simulation.MaxTurns != store.DefaultSimulationTurns { + declared.MaxTurns = simulation.MaxTurns + } + directory.Simulations = append(directory.Simulations, declared) + } + + // The knowledge last, held to what a sync takes back once everything else is written: a + // document that is too large for one, or that would take the directory past what one may + // hold, is left out and said to be. + rendered, _ := agentdir.Render(directory) + held := 0 + for _, file := range rendered { + held += len(file.Content) + } + for _, document := range documents { + switch { + case !agentdir.KnowledgeFile(document.Source, document.Text): + note("The knowledge document %q is not a text file a directory holds, so it is left out and a sync of these files removes it.", document.Source) + case len(document.Text) > agentdir.MaxFileBytes, held+len(document.Text) > agentdir.MaxBytes, + len(rendered)+len(directory.Knowledge) >= agentdir.MaxFiles: + note("The knowledge document %q is more than a directory may hold, so it is left out and a sync of these files removes it.", document.Source) + default: + held += len(document.Text) + directory.Knowledge = append(directory.Knowledge, agentdir.Document{Source: document.Source, Text: document.Text}) + } + } + if config.KnowledgeNamespace != "" && len(directory.Knowledge)+len(directory.KnowledgeURLs) == 0 { + note("None of the agent's knowledge base %q is in these files, so a sync of them leaves the agent with no knowledge base.", config.KnowledgeNamespace) + } + for _, kept := range []struct{ file, text string }{ + {agentdir.InstructionsFile, config.Instructions}, {agentdir.GuardrailFile, config.Guardrail}, + } { + if kept.text != strings.TrimSpace(kept.text) { + note("The agent's %s starts or ends with blank space, which a directory's does not keep, so a sync of these files trims it.", kept.file) + } + } + files, unwritten := agentdir.Render(directory) + exported.NotExported = append(exported.NotExported, unwritten...) + for _, file := range files { + exported.Files = append(exported.Files, DirectoryFile(file)) + } + return exported, nil +} + +// directorySettings is a stored config as agent.yaml says it: what a sync fills in on its own is +// left out, and what agent.yaml cannot say and a sync would change is noted. +func directorySettings(config store.AgentConfig, note func(format string, args ...any)) agentdir.Settings { + settings := agentdir.Settings{ + Name: config.Name, Mode: config.Mode, STT: config.STT, TTS: config.TTS, Voice: config.Voice, + LLM: config.LLM, Role: config.Role, Subagent: config.Subagent, Search: config.Search, + Sandbox: config.Sandbox, Keyterms: config.Keyterms, Tags: config.Tags, + } + if config.Region != pricing.DefaultRegion { + settings.Region = config.Region + } + if config.Harness != string(Default) { + settings.Harness = config.Harness + } + if config.STS != "" { + settings.STS = &config.STS + } + if config.Image != "" { + settings.Image = &config.Image + } + if config.Greeting != "" { + settings.Greeting = &agentdir.Greeting{Text: config.Greeting} + if config.GreetingMode != store.GreetingExact { + settings.Greeting.Mode = config.GreetingMode + } + } + if options := config.SandboxOptions; sandboxOptionsOf(options) != nil { + settings.SandboxOptions = &agentdir.SandboxOptions{ + Image: options.Image, Setup: options.Setup, Timeout: time.Duration(options.TimeoutMs) * time.Millisecond, + CPU: options.CPU, MemoryGB: options.MemoryGB, DiskGB: options.DiskGB, Network: options.Network, + AllowedDomains: options.AllowedDomains, NetworkAllowList: options.NetworkAllowList, + } + } + if len(config.Connectors)+len(config.LeftOutConnectors) > 0 { + connectors := []agentdir.Connector{} + for _, binding := range config.Connectors { + if connector, ok := directoryConnector(binding, note); ok { + connectors = append(connectors, connector) + } + } + for _, leftOut := range config.LeftOutConnectors { + connector := agentdir.Connector{Name: leftOut.Name, Connection: &leftOut.Connection} + if leftOut.ConnectorID != leftOut.Name { + connector.Connector = leftOut.ConnectorID + } + connectors = append(connectors, connector) + } + settings.Connectors = &connectors + } + if len(config.ToolGroups) > 0 { + groups := make([]agentdir.ToolGroup, 0, len(config.ToolGroups)) + for _, group := range config.ToolGroups { + groups = append(groups, agentdir.ToolGroup{ + Name: group.Name, Loading: group.Loading, Tools: group.Tools, OutputRetention: string(group.OutputRetention), + }) + } + settings.Tools = &groups + } + if channels := config.Channels; channels.WhatsApp != nil || channels.SMS != nil || channels.IMessage != nil || channels.Identity != "" { + number := func(line *store.ChannelLine) string { + if line == nil { + return "" + } + return line.Number + } + settings.Channels = &agentdir.Channels{ + WhatsApp: number(channels.WhatsApp), SMS: number(channels.SMS), IMessage: number(channels.IMessage), + Identity: channels.Identity, + } + } + if len(config.ChatChannels) > 0 { + channels := make([]agentdir.ChatChannel, 0, len(config.ChatChannels)) + for _, channel := range config.ChatChannels { + channels = append(channels, agentdir.ChatChannel(channel)) + } + settings.ChatChannels = &channels + } + if scheduling := config.Scheduling; scheduling != (store.AgentScheduling{}) { + settings.Scheduling = &agentdir.Scheduling{DefaultTimezone: scheduling.DefaultTimezone} + if scheduling.Enabled { + settings.Scheduling.Enabled = &scheduling.Enabled + } + settings.Scheduling.MaxTasksPerUser = positive(scheduling.MaxTasksPerUser) + } + calls := agentdir.Calls{} + if config.Calls.EndCallOn() { + calls.EndCall.Enabled = new(true) + } + if config.Calls.EndCall != nil { + calls.EndCall.When = config.Calls.EndCall.When + } + if !config.Calls.PressOn() { + calls.Press.Enabled = new(false) + } + if !config.Calls.TransferOn() { + calls.Transfer.Enabled = new(false) + } + if config.Calls.Transfer != nil { + for _, destination := range config.Calls.Transfer.Destinations { + calls.Transfer.Destinations = append(calls.Transfer.Destinations, agentdir.TransferDestination(destination)) + } + } + settings.Calls = &calls + if floor := config.FloorControl; !floor.IsZero() { + settings.FloorControl = &agentdir.FloorControl{Model: &floor.Model, MaxWaitMs: positive(floor.MaxWaitMs)} + } + if len(config.Agents) > 0 { + agents := make([]agentdir.ChildAgent, 0, len(config.Agents)) + for _, agent := range config.Agents { + agents = append(agents, agentdir.ChildAgent(agent)) + } + settings.Agents = &agents + } + if config.VideoSource != "" || config.VideoMaxFrames > 1 { + settings.Video = &agentdir.Video{Source: config.VideoSource, MaxFrames: max(config.VideoMaxFrames, 1)} + } + if config.DispatchIncomingCall || config.DispatchText { + settings.Dispatch = &agentdir.Dispatch{} + if config.DispatchIncomingCall { + settings.Dispatch.IncomingCall = string(Enabled) + } + if config.DispatchText { + settings.Dispatch.Text = string(Enabled) + } + } + return settings +} + +// directoryConnector is a stored binding as agent.yaml names it, or false for one it cannot name. +func directoryConnector(binding store.ConnectorBinding, note func(format string, args ...any)) (agentdir.Connector, bool) { + connector := agentdir.Connector{ + Name: binding.Name, Sandbox: binding.Sandbox, Loading: binding.Loading, + OutputRetention: string(binding.OutputRetention), + } + if binding.ConnectorID != binding.Name { + connector.Connector = binding.ConnectorID + } + switch patterns := value(binding.ToolPatterns); { + case len(patterns) == 1 && patterns[0] == "*": + case len(patterns) > 0: + connector.Tools = &patterns + case len(binding.Tools) > 0: + granted := make([]string, 0, len(binding.Tools)) + for _, tool := range binding.Tools { + granted = append(granted, tool.Name) + } + connector.Tools = &granted + note("The connector %s grants its tools by name and schema digest. agent.yaml names them alone, so a sync of these files grants them whatever their schema.", binding.Name) + default: + // Written with no tools key, a sync would grant every tool instead. + note("The connector %s grants no tools, which agent.yaml cannot say, so it is left out and a sync of these files unbinds it.", binding.Name) + return agentdir.Connector{}, false + } + if binding.Connection.Type == string(AgentConnectorSelectionTypeFixed) { + connector.Connection = &binding.Connection.ConnectionID + } + if binding.Required { + connector.Required = &binding.Required + } + if len(binding.RequireApproval) > 0 { + connector.RequireApproval = &binding.RequireApproval + } + if binding.TimeoutMs > 0 || len(binding.Events) > 0 || binding.Policy != nil { + note("The connector %s has a timeout, events or a policy, which agent.yaml cannot say, so a sync of these files removes them.", binding.Name) + } + return connector, true +} + +type getAgentDirectoryRequest struct { + Id string `path:"id"` +} + +type getAgentDirectoryResponse struct { + Body AgentDirectory +} + +const directoryFiles = "The files are agent.yaml, instructions.md, guardrail.md, each skill as " + + "skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ " + + "with the pages it is kept filled from in knowledge/urls.yaml, its simulations in " + + "simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's " + + "files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync " + + "fills in on its own left out (region us, the default harness, a call tool at its default, a " + + "connector's tools when it grants every one), and a connector that says only its name written as " + + "the name alone.\n\n" + + "Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a " + + "directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, " + + "resume_history, visible_tools and episode_cards. A fixed connector is written with its " + + "connection's id, whatever label agent.yaml first named it by, and a skill the config no longer " + + "names is left out.\n\n" + + "Server-side only: it needs a server-side token, so it cannot be reached from an end user's device." + +type syncAgentFilesRequest struct { + Body SyncAgentFilesRequest +} + +// registerDirectory declares the operations served in directory.go. +func (s *Server) registerDirectory(api huma.API) { + huma.Register(api, huma.Operation{ + OperationID: "getAgentDirectory", + Method: http.MethodGet, + Path: "/v1/agents/configs/{id}/directory", + Summary: "An agent config as the files of its directory", + Description: "The reverse of a sync: the agent as the directory it would be synced from. " + directoryFiles, + Responses: map[string]*huma.Response{ + "200": {Description: "The agent's directory"}, + }, + Errors: []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound}, + }, func(ctx context.Context, request *getAgentDirectoryRequest) (*getAgentDirectoryResponse, error) { + directory, err := s.agentDirectory(ctx, request.Id) + if err != nil { + return nil, err + } + return &getAgentDirectoryResponse{Body: directory}, nil + }) + huma.Register(api, huma.Operation{ + OperationID: "syncAgentFiles", + Method: http.MethodPost, + Path: "/v1/agents/sync/files", + MaxBodyBytes: maxDirectoryBody, + BodyReadTimeout: uploadReadTimeout, + Summary: "Store an agent directory sent as its files", + Description: "POST /v1/agents/sync for a client that sends the directory's files as they are " + + "and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same " + + "thing by one directory. It stores what that sync stores, with the same answer.\n\n" + + "A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 " + + "`invalid_agent_directory`) with every problem at its file, line and column in the error's " + + "`problems`. A connector's connection is found among the app's own by id or by label; one the " + + "app does not have is left out of the agent, stored in `left_out_connectors` and named in a " + + "warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled " + + "into `ui_instructions` here.\n\n" + + "`dry_run` answers with what the sync would store and writes nothing, which is how to show " + + "what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is " + + "the reverse: the stored agent as files.\n\n" + + "Server-side only: it needs a server-side token, so it cannot be reached from an end user's device.", + Responses: map[string]*huma.Response{ + "200": {Description: "The config as stored, as it already was, or with dry_run as it would be stored"}, + }, + Errors: []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, + http.StatusConflict, http.StatusRequestEntityTooLarge}, + }, func(ctx context.Context, request *syncAgentFilesRequest) (*syncAgentResponse, error) { + customerID, ok := CustomerFrom(ctx) + if !ok { + return nil, errMissingCustomer + } + if s.store == nil { + return nil, errNoConfigs + } + read, err := s.readDirectory(ctx, customerID, request.Body) + if err != nil { + return nil, err + } + return s.sync(ctx, read) + }) +} diff --git a/acceleration/internal/api/directory_test.go b/acceleration/internal/api/directory_test.go new file mode 100644 index 0000000000..03aa832c88 --- /dev/null +++ b/acceleration/internal/api/directory_test.go @@ -0,0 +1,1151 @@ +//go:build integration + +package api + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "maps" + "net/http" + "slices" + "strings" + "testing" + + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +type DirectorySuite struct { + RouterSuite +} + +func TestDirectorySuite(t *testing.T) { + runSuite(t, new(DirectorySuite)) +} + +// SetupSuite seeds the built-in connectors as a router start does, so a directory can bind one. +func (s *DirectorySuite) SetupSuite() { + s.connectors = core.Registry{Schemes: map[string]core.Scheme{"oauth2_code": namedScheme("oauth2_code")}} + s.RouterSuite.SetupSuite() + s.Require().NoError(s.store.SeedConnectorDefinitions(context.Background(), providers.FS)) +} + +// SetupTest gives every test an app of its own, because a sync is named by what the agent is +// called. +func (s *DirectorySuite) SetupTest() { + s.useApp(s.data.createApp()) +} + +// sentFiles is a directory as a client sends it, with an agent.yaml naming it support unless the +// test gives one. +func sentFiles(held map[string]string) []map[string]string { + if _, declared := held["agent.yaml"]; !declared { + held["agent.yaml"] = "name: support\n" + } + sent := make([]map[string]string, 0, len(held)) + for _, path := range slices.Sorted(maps.Keys(held)) { + sent = append(sent, map[string]string{"path": path, "content": held[path]}) + } + return sent +} + +// hashOf is the hash the files request documents, worked out here by hand: every part as +// its length in bytes in decimal, a colon and the part. +func hashOf(parts ...string) string { + hasher := sha256.New() + for _, part := range parts { + fmt.Fprintf(hasher, "%d:%s", len(part), part) + } + return hex.EncodeToString(hasher.Sum(nil)) +} + +func (s *DirectorySuite) sync(held map[string]string) SyncAgentResult { + return s.syncWith(held, nil) +} + +// syncWith syncs a directory with the rest of the request beside its files. +func (s *DirectorySuite) syncWith(held map[string]string, beside map[string]any) SyncAgentResult { + body := map[string]any{"files": sentFiles(held)} + maps.Copy(body, beside) + var result SyncAgentResult + status, payload := s.serverClient.call(http.MethodPost, "/v1/agents/sync/files", body) + s.Require().Equal(http.StatusOK, status, string(payload)) + s.Require().NoError(json.Unmarshal(payload, &result)) + return result +} + +// refused syncs a directory that must be refused, and returns the status and what was said. +func (s *DirectorySuite) refused(held map[string]string, beside map[string]any) (int, ErrorDetail) { + body := map[string]any{"files": sentFiles(held)} + maps.Copy(body, beside) + status, payload := s.serverClient.call(http.MethodPost, "/v1/agents/sync/files", body) + var answered ErrorResponse + s.Require().NoError(json.Unmarshal(payload, &answered), string(payload)) + return status, answered.Error +} + +func (s *DirectorySuite) config(id string) AgentConfig { + var config AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+id, nil, &config)) + return config +} + +func (s *DirectorySuite) configsNamed(name string) []AgentConfig { + var listed []AgentConfig + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs?name="+name, nil, &listed)) + return listed +} + +// exported is a config's directory by path. +func (s *DirectorySuite) exported(id string) (map[string]string, AgentDirectory) { + var directory AgentDirectory + s.Require().Equal(http.StatusOK, + s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+id+"/directory", nil, &directory)) + held := map[string]string{} + for _, file := range directory.Files { + held[file.Path] = file.Content + } + return held, directory +} + +// connection is a connection of the app's own to a built-in connector, under a label. +func (s *DirectorySuite) connection(connectorID, label string) string { + ctx := context.Background() + definition, err := s.store.LatestConnectorDefinition(ctx, s.customerID(), connectorID) + s.Require().NoError(err) + connection := &store.ConnectorConnection{ + CustomerID: s.customerID(), ConnectorID: definition.ID, DefinitionRevision: definition.Revision, + OwnerType: store.OwnerApp, AuthScheme: "oauth2_code", Label: label, + } + s.Require().NoError(s.store.CreateConnectorConnection(ctx, s.connectors, connection)) + return connection.ID +} + +// audited is everything on one agent's record. +func (s *DirectorySuite) audited(configID string) []AuditEntry { + var answered AuditPage + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/audit/query", + map[string]any{"filter": map[string]any{"agent_id": configID}}, &answered)) + return answered.Items +} + +func (s *DirectorySuite) dashboard() *testClient { + return s.serverClient.from("dashboard", "volt-7", "Ada Lovelace") +} + +func (s *DirectorySuite) TestSyncingFilesStoresWhatTheDirectorySays() { + held := map[string]string{ + "agent.yaml": "name: support\nmode: text\nllm: llm-flow\ngreeting: {text: Hello., mode: variation}\nkeyterms: [Vision Agents]\ntags: {project: support}\n", + "instructions.md": "Be brief.\n", + "guardrail.md": "---\ntype: llm\n---\nNo medical advice.\n", + "skills/refund.md": "---\ndescription: work out a refund\ndeadline: 45s\n---\nRead the policy.\n", + "knowledge/pricing.md": "Pro costs twenty dollars.\n", + } + + synced := s.sync(held) + + s.False(synced.Unchanged) + stored := s.config(synced.Config.Id) + s.Equal("support", stored.Name) + s.Equal(AgentModeText, stored.Mode) + s.Equal("llm-flow", value(stored.Llm)) + s.Equal("Be brief.", value(stored.Instructions)) + s.Equal("---\ntype: llm\n---\nNo medical advice.", value(stored.Guardrail)) + s.Equal("Hello.", stored.Greeting.Text) + s.Equal(GreetingModeVariation, value(stored.Greeting.Mode)) + s.Equal([]string{"Vision Agents"}, value(stored.Keyterms)) + s.Equal("support", value(stored.Tags)["project"]) + s.Equal([]string{"refund"}, value(stored.Skills)) + s.Equal("support", value(stored.KnowledgeNamespace)) + skills, err := s.store.CustomerSkills(context.Background(), s.customerID(), stored.Id) + s.Require().NoError(err) + s.Require().Len(skills, 1) + s.Equal("Read the policy.", skills[0].Instructions) + s.EqualValues(45000, skills[0].DeadlineMs) +} + +func (s *DirectorySuite) TestTheHashIsTheRoutersOwnOfTheFiles() { + synced := s.sync(map[string]string{"agent.yaml": "name: support\n", "instructions.md": "Be brief.\n"}) + + s.Equal(hashOf("agent.yaml", "name: support\n", "instructions.md", "Be brief.\n"), value(synced.Config.SyncHash)) +} + +func (s *DirectorySuite) TestTheSameFilesAgainWriteNothing() { + held := map[string]string{"instructions.md": "Be brief.\n"} + first := s.sync(held) + recorded := len(s.audited(first.Config.Id)) + + second := s.sync(held) + + s.True(second.Unchanged) + s.Equal(first.Config.UpdatedAt, s.config(first.Config.Id).UpdatedAt) + s.Len(s.audited(first.Config.Id), recorded, "nothing was written, so no sync is recorded") +} + +func (s *DirectorySuite) TestAChangedFileSyncsAgain() { + first := s.sync(map[string]string{"instructions.md": "Be brief.\n"}) + + second := s.sync(map[string]string{"instructions.md": "Be even briefer.\n"}) + + s.False(second.Unchanged) + s.Equal(first.Config.Id, second.Config.Id) + s.Equal("Be even briefer.", value(s.config(first.Config.Id).Instructions)) + s.NotEqual(value(first.Config.SyncHash), value(second.Config.SyncHash)) +} + +func (s *DirectorySuite) TestASettingAgentYAMLLeavesOutIsLeftAlone() { + first := s.sync(map[string]string{"agent.yaml": "name: support\nllm: llm-flow\nvoice: aurora\n"}) + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+first.Config.Id, + map[string]any{"voice": "juniper", "search": "search-fast"}, nil)) + + s.sync(map[string]string{"agent.yaml": "name: support\nllm: llm-fast\n"}) + + stored := s.config(first.Config.Id) + s.Equal("llm-fast", value(stored.Llm)) + s.Equal("juniper", value(stored.Voice), "a voice the file no longer names is the one chosen since") + s.Equal("search-fast", value(stored.Search)) +} + +func (s *DirectorySuite) TestAFilesSyncAskedToCheckIsRefusedOverAChangeItWouldWriteOver() { + first := s.sync(map[string]string{"agent.yaml": "name: support\nllm: llm-flow\n"}) + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+first.Config.Id, + map[string]any{"llm": "llm-fast"}, nil)) + + status, failure := s.refused(map[string]string{"agent.yaml": "name: support\nllm: llm-thinking\n"}, + map[string]any{"check_changes": true}) + + s.Equal(http.StatusConflict, status) + s.Equal(codeUnsyncedChanges, failure.Code) + s.Contains(failure.Message, "llm") + s.Equal("llm-fast", value(s.config(first.Config.Id).Llm)) +} + +func (s *DirectorySuite) TestARefusalOverUnsyncedChangesNamesThemAsDataOnBothSyncs() { + held := map[string]string{ + "agent.yaml": "name: support\nllm: llm-flow\n", + "instructions.md": "Be brief.\n", + "skills/refund.md": "---\ndescription: work out a refund\n---\nRead the policy.\n", + "knowledge/pricing.md": "Pro costs twenty dollars.\n", + } + first := s.sync(held) + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+first.Config.Id, + map[string]any{"llm": "llm-fast", "instructions": "Be thorough.", "voice": "aurora"}, nil)) + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPost, "/v1/agents/knowledge", map[string]any{ + "namespace": "support", "documents": []map[string]string{{"source": "added.md", "text": "Added in the dashboard."}}, + }, nil)) + var changes AgentChanges + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+first.Config.Id+"/changes", nil, &changes)) + want := []SyncConflict{ + {ResourceType: "knowledge", Name: "added.md", Removed: true}, + {ResourceType: "agent_config", Name: "instructions"}, + {ResourceType: "agent_config", Name: "llm"}, + } + + held["agent.yaml"], held["instructions.md"] = "name: support\nllm: llm-thinking\n", "Be terse.\n" + status, files := s.refused(held, map[string]any{"check_changes": true}) + s.Equal(http.StatusConflict, status) + s.ElementsMatch(want, files.Conflicts, "voice is not one: the directory does not say it") + s.Equal(value(changes.LastChange), files.LastChange) + s.Contains(files.Message, "knowledge added.md, which this directory no longer has", "the message still names them") + + status, payload := s.serverClient.call(http.MethodPost, "/v1/agents/sync", map[string]any{ + "name": "support", "hash": "v2", "check_changes": true, "llm": "llm-thinking", "instructions": "Be terse.", + "knowledge": []map[string]string{{"source": "pricing.md", "text": "Pro costs twenty dollars.\n"}}, + }) + var fields ErrorResponse + s.Require().NoError(json.Unmarshal(payload, &fields)) + s.Equal(http.StatusConflict, status) + s.ElementsMatch(want, fields.Error.Conflicts) + s.Equal(value(changes.LastChange), fields.Error.LastChange) + + s.False(s.syncWith(held, map[string]any{"check_changes": true, "base_change": files.LastChange}).Unchanged, + "the last change it named is what lets the sync through") +} + +func (s *DirectorySuite) TestWhatAProgramSetsInCodeWinsOverTheFiles() { + held := map[string]string{ + "agent.yaml": "name: support\nllm: llm-flow\nvoice: aurora\nsubagent: llm-thinking\ntags: {team: support, tier: free}\n", + "instructions.md": "Be brief.\n", + "guardrail.md": "---\ntype: llm\n---\nNo medical advice.\n", + "skills/refund.md": "---\ndescription: work out a refund\n---\nRead the policy.\n", + } + + synced := s.syncWith(held, map[string]any{ + "instructions": "Be thorough.", "guardrail": "---\ntype: llm\n---\nNo legal advice.", + "llm": "llm-fast", "subagent": "llm-flow", "sandbox": "daytona", "harness": "default", + "greeting": map[string]any{"text": "Hello.", "mode": "variation"}, + "tags": map[string]string{"tier": "paid", "customer": "123"}, + "skills": []map[string]any{{"config_id": "", "name": "think", "description": "work it out", "instructions": "Reason."}}, + }) + + stored := s.config(synced.Config.Id) + s.Equal("Be thorough.", value(stored.Instructions)) + s.Equal("---\ntype: llm\n---\nNo legal advice.", value(stored.Guardrail)) + s.Equal("llm-fast", value(stored.Llm)) + s.Equal("aurora", value(stored.Voice), "what the code leaves out is the file's") + s.Equal("llm-flow", value(stored.Subagent)) + s.Equal(Daytona, value(stored.Sandbox)) + s.Equal("Hello.", stored.Greeting.Text) + s.Equal(map[string]string{"team": "support", "tier": "paid", "customer": "123"}, value(stored.Tags)) + s.Equal([]string{"think"}, value(stored.Skills), "skills written in code take the place of the directory's") +} + +func (s *DirectorySuite) TestAnEmptySkillListInCodeNamesNoSkills() { + held := map[string]string{"skills/refund.md": "---\ndescription: work out a refund\n---\nRead the policy.\n"} + + synced := s.syncWith(held, map[string]any{"skills": []any{}}) + + s.Empty(value(synced.Config.Skills)) + s.Equal([]string{"refund"}, value(s.syncWith(held, nil).Config.Skills)) +} + +func (s *DirectorySuite) TestWhatAProgramSetsInCodeIsPartOfTheHash() { + held := map[string]string{"agent.yaml": "name: support\n"} + code := map[string]any{ + "instructions": "Be brief.", "llm": "llm-fast", + "video": map[string]any{"max_frames": 4}, + "tags": map[string]string{"b": "2", "a": "1"}, + "skills": []map[string]any{{"config_id": "", "name": "think", "description": "work it out", "instructions": "Reason.", "deadline_ms": 30000}}, + } + + first := s.syncWith(held, code) + + s.Equal(hashOf("agent.yaml", "name: support\n", + "instructions", "Be brief.", "llm", "llm-fast", "video.max_frames", "4", "tags.a", "1", "tags.b", "2", "skills", "1", + "skills.think.description", "work it out", "skills.think.instructions", "Reason.", "skills.think.deadline_ms", "30000", + ), value(first.Config.SyncHash)) + s.True(s.syncWith(held, code).Unchanged, "the same files and the same code write nothing") + + code["instructions"] = "Be thorough." + changed := s.syncWith(held, code) + s.False(changed.Unchanged, "a setting changed in code syncs again") + s.Equal("Be thorough.", value(changed.Config.Instructions)) + s.False(s.syncWith(held, nil).Unchanged, "and so does taking the code away") +} + +func (s *DirectorySuite) TestASyncOfFilesNeedsFiles() { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sync/files", map[string]any{"name": "support"}) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, "files") + s.Empty(s.configsNamed("support")) +} + +func (s *DirectorySuite) TestTheSyncOfFieldsTakesNoFiles() { + var synced SyncAgentResult + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/sync", map[string]any{ + "name": "support", "hash": "v1", "instructions": "Be brief.", + "files": sentFiles(map[string]string{"agent.yaml": "name: support\nllm: llm-fast\n"}), + }, &synced)) + + s.Equal("v1", value(synced.Config.SyncHash)) + s.Nil(synced.Config.Llm, "a field the operation does not have is not read") +} + +func (s *DirectorySuite) TestTheNameSentWinsOverAgentYAMLsAndOneOfThemIsNeeded() { + named := s.syncWith(map[string]string{"agent.yaml": "name: support\n"}, map[string]any{"name": "billing"}) + s.Equal("billing", named.Config.Name) + + fromDirectory := s.syncWith(map[string]string{"agent.yaml": "llm: llm-fast\n"}, map[string]any{"name": "sales"}) + s.Equal("sales", fromDirectory.Config.Name) + + status, failure := s.refused(map[string]string{"agent.yaml": "llm: llm-fast\n"}, nil) + s.Equal(http.StatusBadRequest, status) + s.Equal(codeInvalidAgentDirectory, failure.Code) + s.Contains(failure.Message, "the agent has no name") +} + +func (s *DirectorySuite) TestADirectoryThatDoesNotReadIsRefusedWithEveryProblemAtItsPlace() { + status, failure := s.refused(map[string]string{ + "agent.yaml": "name: support\nllmm: llm-fast\nplugins:\n - name: github\n", + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n", + }, nil) + + s.Equal(http.StatusBadRequest, status) + s.Equal(ErrorTypeInvalidRequest, failure.Type) + s.Equal(codeInvalidAgentDirectory, failure.Code) + s.Equal([]DirectoryProblem{ + {File: "agent.yaml", Line: 2, Column: 1, Message: `"llmm" is not something agent.yaml says; ` + agentYAMLKeys + ` are`}, + {File: "agent.yaml", Line: 4, Column: 3, Message: "plugins: no longer read: plugins were replaced by connectors, so name the provider under connectors"}, + {File: "simulations/a.yaml", Line: 1, Column: 3, Message: `simulation "lunch" needs an assertion`}, + }, failure.Problems) + s.Contains(failure.Message, "agent.yaml:2:1: ") + s.Empty(s.configsNamed("support")) +} + +const agentYAMLKeys = "name, description, mode, region, stt, tts, sts, voice, llm, harness, role, subagent, search, image, " + + "greeting, sandbox, sandbox_options, connectors, tools, channels, chat_channels, scheduling, calls, floor_control, " + + "agents, keyterms, tags, video, dispatch, ui, app" + +func (s *DirectorySuite) TestAValueTheSchemaRefusesIsRefusedWhereAgentYAMLSaysIt() { + status, failure := s.refused(map[string]string{ + "agent.yaml": "name: support\nmode: sung\ngreeting:\n text: Hi.\n mode: shouted\nchat_channels:\n - type: team\n answer: sometimes\n", + }, nil) + + s.Equal(http.StatusBadRequest, status) + s.Equal(codeInvalidAgentDirectory, failure.Code) + at := map[string][2]int{} + for _, problem := range failure.Problems { + s.Equal("agent.yaml", problem.File) + setting, _, _ := strings.Cut(problem.Message, ": ") + at[setting] = [2]int{problem.Line, problem.Column} + } + s.Equal(map[string][2]int{"mode": {2, 7}, "greeting.mode": {5, 9}, "chat_channels[0].answer": {8, 13}}, at) +} + +func (s *DirectorySuite) TestASimulationTheSchemaRefusesIsRefusedInItsFolder() { + status, failure := s.refused(map[string]string{ + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n variations: 99\n", + }, nil) + + s.Equal(http.StatusBadRequest, status) + s.Require().Len(failure.Problems, 1) + s.Equal("simulations", failure.Problems[0].File) + s.Contains(failure.Problems[0].Message, "simulations[0].variations") +} + +func (s *DirectorySuite) TestAFileOverTheSizeAFileMayHaveIsRefused() { + status, failure := s.refused(map[string]string{"knowledge/big.md": strings.Repeat("a", 1<<20+1)}, nil) + + s.Equal(http.StatusBadRequest, status) + s.Equal(codeInvalidAgentDirectory, failure.Code) + s.Equal("knowledge/big.md", failure.Problems[0].File) + s.Contains(failure.Message, "a file holds at most 1048576") + s.Empty(s.configsNamed("support")) +} + +func (s *DirectorySuite) TestADirectoryOverTheSizeOneMayHaveIsRefused() { + held := map[string]string{} + for _, name := range []string{"a", "b", "c", "d", "e", "f", "g", "h", "i"} { + held["knowledge/"+name+".md"] = strings.Repeat("a", 1<<20) + } + + status, failure := s.refused(held, nil) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure.Message, "one holds at most 8388608") +} + +func (s *DirectorySuite) TestMoreFilesThanARequestMaySendAreRefused() { + held := map[string]string{} + for index := range 1024 { + held[fmt.Sprintf("src/%04d.go", index)] = "x" + } + + status, failure := s.refused(held, nil) + + s.Equal(http.StatusBadRequest, status) + s.Equal(codeValidationFailed, failure.Code) + s.Contains(failure.Message, "files") +} + +func (s *DirectorySuite) TestFilesLeftOutAreWarnedOfOnceWithACount() { + synced := s.sync(map[string]string{"a.txt": "x", "b.txt": "x", "c.txt": "x", "d.txt": "x", "e.txt": "x"}) + + s.Equal([]string{"5 files sent are not part of an agent directory, so they were left out: a.txt, b.txt, c.txt and 2 more"}, synced.Warnings) +} + +func (s *DirectorySuite) TestARefusalNamesAtMostAHundredProblemsAndSaysHowManyMore() { + var declaration strings.Builder + declaration.WriteString("name: support\n") + for index := range 150 { + fmt.Fprintf(&declaration, "unknown_%03d: x\n", index) + } + + status, failure := s.refused(map[string]string{"agent.yaml": declaration.String()}, nil) + + s.Equal(http.StatusBadRequest, status) + s.Require().Len(failure.Problems, 100) + s.Equal(50, failure.ProblemsOmitted) + for _, problem := range failure.Problems { + s.Positive(problem.Line, "every entry is a problem at a place, none a count of the rest: %v", problem) + } + s.Equal(5, strings.Count(failure.Message, "agent.yaml:"), "the message says the first few") + s.Contains(failure.Message, "; and 145 more") + s.Less(len(failure.Message), 4096) +} + +func (s *DirectorySuite) TestARefusalThatNamesEveryProblemOmitsNone() { + _, payload := s.serverClient.call(http.MethodPost, "/v1/agents/sync/files", + map[string]any{"files": sentFiles(map[string]string{"agent.yaml": "name: support\nllmm: x\n"})}) + + s.NotContains(string(payload), "problems_omitted") +} + +func (s *DirectorySuite) TestWhatTheRouterCannotRunIsSaidTogetherWhereAgentYAMLSaysIt() { + status, failure := s.refused(map[string]string{ + "agent.yaml": "name: support\nmode: text\nsubagent: llm-thinking\nfloor_control:\n model: stream/chorus-asr\n", + "skills/pdf/SKILL.md": "---\ndescription: Fill a form\n---\nRun it.\n", + "skills/pdf/fill.py": "print()\n", + }, map[string]any{"dry_run": true}) + + s.Equal(http.StatusBadRequest, status) + s.Equal(codeInvalidAgentDirectory, failure.Code) + at := map[int]string{} + for _, problem := range failure.Problems { + s.Equal("agent.yaml", problem.File) + at[problem.Line] = problem.Message + } + s.Len(failure.Problems, 3, "%v", failure.Problems) + s.Contains(at[3], "subagent", "a text agent names no subagent") + s.Contains(at[4], "chorus", "this router has no chorus-asr server") + s.Contains(at[1], "sandbox", "a skill's script has nowhere to run, said at the top since the file names no sandbox") +} + +func (s *DirectorySuite) TestFilesSentBesideTheDirectoryAreNoPartOfItsHashOrItsLimits() { + held := map[string]string{"agent.yaml": "name: support\n", "instructions.md": "Be brief.\n"} + alone := s.sync(held) + + among := s.sync(map[string]string{ + "agent.yaml": "name: support\n", "instructions.md": "Be brief.\n", + "README.md": "# Support\n", "src/main.go": "package main\n", "build/app.js": strings.Repeat("a", 1<<20+1), + }) + + s.True(among.Unchanged, "a client that sends the whole folder syncs what one that sends the directory alone did") + s.Equal(value(alone.Config.SyncHash), value(among.Config.SyncHash)) +} + +func (s *DirectorySuite) TestAUIFileOutsideTheUIFolderIsReadWhereAgentYAMLNamesIt() { + synced := s.sync(map[string]string{ + "agent.yaml": "name: support\nui:\n blueprints: design/recipes.yaml\n", + "design/recipes.yaml": "- name: booking\n when: booking a table\n order: [CardHeader]\n", + }) + + s.Contains(value(synced.Config.UiInstructions), "**booking**") + s.Empty(synced.Warnings) +} + +func (s *DirectorySuite) TestWhatDoesNotReadAndWhatTheSchemaRefusesAreSaidTogether() { + status, failure := s.refused(map[string]string{"agent.yaml": "name: support\nmode: banana\nllmm: llm-fast\n"}, nil) + + s.Equal(http.StatusBadRequest, status) + s.Require().Len(failure.Problems, 2, "%v", failure.Problems) + s.Equal([]int{3, 1}, []int{failure.Problems[0].Line, failure.Problems[0].Column}) + s.Contains(failure.Problems[0].Message, `"llmm" is not something agent.yaml says`) + s.Equal([]int{2, 7}, []int{failure.Problems[1].Line, failure.Problems[1].Column}) + s.Contains(failure.Problems[1].Message, "mode: ") +} + +func (s *DirectorySuite) TestTwoSkillsOneNameAreRefusedBeforeAnythingIsWritten() { + held := map[string]string{ + "skills/a.md": "---\nname: refund\ndescription: One\n---\nRead the policy.\n", + "skills/b.md": "---\nname: refund\ndescription: Two\n---\nRead the policy.\n", + } + + dry, failure := s.refused(held, map[string]any{"dry_run": true}) + wet, _ := s.refused(held, nil) + + s.Equal(http.StatusBadRequest, dry) + s.Equal(http.StatusBadRequest, wet) + s.Contains(failure.Message, `skill "refund" is also declared in skills/a.md`) + s.Empty(s.configsNamed("support")) +} + +func (s *DirectorySuite) TestTwoSkillsOneNameSentAsFieldsAreRefusedBeforeAnythingIsWritten() { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sync", map[string]any{ + "name": "support", "hash": "v1", + "skills": []map[string]string{ + {"config_id": "", "name": "refund", "description": "one", "instructions": "Read the policy."}, + {"config_id": "", "name": "refund", "description": "two", "instructions": "Read the policy."}, + }, + }) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, `two skills are called "refund"`) + s.Empty(s.configsNamed("support"), "the config is not left stored with half its skills") +} + +func (s *DirectorySuite) TestADryRunRefusesAPageTheSyncWouldRefuse() { + held := map[string]string{"knowledge/urls.yaml": "- https://\n"} + + dry, failure := s.refused(held, map[string]any{"dry_run": true}) + wet, _ := s.refused(held, nil) + + s.Equal(http.StatusBadRequest, dry) + s.Equal(wet, dry) + s.Contains(failure.Message, "names no host") + s.Empty(s.configsNamed("support")) +} + +func (s *DirectorySuite) TestADryRunOfANewAgentAnswersTheModeItWouldBeStoredWith() { + held := map[string]string{"agent.yaml": "name: support\n"} + + preview := s.syncWith(held, map[string]any{"dry_run": true}) + + s.Equal(AgentModeVoice, preview.Config.Mode) + s.Equal(preview.Config.Mode, s.sync(held).Config.Mode) +} + +func (s *DirectorySuite) TestAFileThatIsNoPartOfTheFormatIsLeftOutWithAWarning() { + synced := s.sync(map[string]string{"instruction.md": "Be brief.\n", ".agent_sync": "{}"}) + + s.Equal([]string{"1 files sent are not part of an agent directory, so they were left out: instruction.md"}, synced.Warnings) + s.Empty(value(synced.Config.Instructions)) +} + +func (s *DirectorySuite) TestAConnectorIsBoundToTheConnectionItsLabelOrIdNames() { + labelled := s.connection("slack", "Support workspace") + other := s.connection("slack", "Sales workspace") + + synced := s.sync(map[string]string{"agent.yaml": `name: support +connectors: + - github + - name: inbox + connector: slack + tools: [search] + connection: Support workspace + required: true + - name: sales + connector: slack + connection: ` + other + "\n"}) + + bound := value(synced.Config.Connectors) + s.Require().Len(bound, 3) + s.Equal(AgentConnectorSelectionTypeSession, bound[0].Connection.Type) + s.Equal([]string{"*"}, value(bound[0].ToolPatterns)) + s.Equal("slack", bound[1].ConnectorId) + s.Equal(labelled, value(bound[1].Connection.ConnectionId)) + s.Equal([]string{"search"}, value(bound[1].ToolPatterns)) + s.True(value(bound[1].Required)) + s.Equal(other, value(bound[2].Connection.ConnectionId)) + s.Empty(synced.Warnings) +} + +func (s *DirectorySuite) TestAnIdWinsOverALabelThatSaysTheSame() { + named := s.connection("slack", "placeholder") + s.connection("slack", named) + + synced := s.sync(map[string]string{"agent.yaml": "name: support\nconnectors:\n - {name: slack, connection: " + named + "}\n"}) + + s.Equal(named, value(value(synced.Config.Connectors)[0].Connection.ConnectionId)) +} + +func (s *DirectorySuite) TestAConnectorWhoseConnectionTheAppLacksIsLeftOutUntilItHasOne() { + held := map[string]string{"agent.yaml": "name: support\nllm: llm-flow\nconnectors:\n - github\n - {name: inbox, connector: slack, connection: Support workspace}\n"} + + first := s.sync(held) + + s.Len(value(first.Config.Connectors), 1, "the rest of the agent still syncs") + s.Equal("llm-flow", value(first.Config.Llm)) + s.Equal([]LeftOutConnector{{Name: "inbox", ConnectorId: "slack", Connection: "Support workspace"}}, value(first.Config.LeftOutConnectors)) + s.Equal([]string{`connector "inbox" was left out: the app has no connection with id or label "Support workspace"`}, first.Warnings) + s.True(s.sync(held).Unchanged, "the same files with the connection still missing write nothing") + + connected := s.connection("slack", "Support workspace") + found := s.sync(held) + + s.False(found.Unchanged, "the sync that finds the connection is not taken for the one that left it out") + s.Require().Len(value(found.Config.Connectors), 2) + s.Equal(connected, value(value(found.Config.Connectors)[1].Connection.ConnectionId)) + s.Nil(found.Config.LeftOutConnectors) +} + +func (s *DirectorySuite) TestARequiredConnectorWhoseConnectionTheAppLacksIsRefusedWhereItIsNamed() { + status, failure := s.refused(map[string]string{ + "agent.yaml": "name: support\nconnectors:\n - github\n - name: inbox\n connector: slack\n connection: Support workspace\n required: true\n", + }, nil) + + s.Equal(http.StatusBadRequest, status) + s.Equal([]DirectoryProblem{{File: "agent.yaml", Line: 4, Column: 5, + Message: `connector "inbox": no app connection with id or label "Support workspace": add the connection, or drop required`}}, failure.Problems) + s.Empty(s.configsNamed("support")) +} + +func (s *DirectorySuite) TestALabelTwoConnectionsShareIsRefused() { + s.connection("slack", "workspace") + s.connection("slack", "workspace") + + status, failure := s.refused(map[string]string{ + "agent.yaml": "name: support\nconnectors:\n - {name: slack, connection: workspace}\n", + }, nil) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure.Message, `connector "slack": "workspace" matches 2 app connections`) +} + +func (s *DirectorySuite) TestALabelOfAnotherConnectorsConnectionIsNotFound() { + s.connection("github", "workspace") + + synced := s.sync(map[string]string{"agent.yaml": "name: support\nconnectors:\n - {name: slack, connection: workspace}\n"}) + + s.Empty(value(synced.Config.Connectors)) + s.Len(value(synced.Config.LeftOutConnectors), 1) +} + +func (s *DirectorySuite) TestTheUIKeyIsCompiledByTheRouter() { + synced := s.sync(map[string]string{ + "agent.yaml": "name: support\nui:\n keep: [CardHeader]\n rules: [Be brief.]\n", + "ui/blueprints.yaml": "- name: booking\n when: booking a table\n order: [CardHeader]\n", + }) + + instructions := value(synced.Config.UiInstructions) + s.Contains(instructions, "## Interactive UI Generation") + s.Contains(instructions, "- **booking** (when booking a table): `Card([CardHeader])`") + s.Contains(instructions, "- Be brief.") + s.NotContains(instructions, "BarChart(") + + without := s.sync(map[string]string{"agent.yaml": "name: support\n"}) + s.Nil(without.Config.UiInstructions, "a directory with no ui key teaches none") +} + +func (s *DirectorySuite) TestSimulationFilesAreTheWholeOfTheAgentsSimulationsAndNoFileLeavesThemAlone() { + first := s.sync(map[string]string{ + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n- name: refund\n scenario: Ask.\n assertion: Refunded.\n", + }) + s.Len(s.simulations(first.Config.Id), 2) + + s.sync(map[string]string{"instructions.md": "Be brief.\n"}) + s.Len(s.simulations(first.Config.Id), 2, "a directory with no simulations file leaves them alone") + + s.sync(map[string]string{"simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n"}) + s.Equal([]string{"lunch"}, s.simulations(first.Config.Id)) + + s.sync(map[string]string{"simulations/a.yaml": "[]\n"}) + s.Empty(s.simulations(first.Config.Id), "a file that declares none deletes them") +} + +// simulations are the names of one config's simulations, in order. +func (s *DirectorySuite) simulations(configID string) []string { + all, err := s.store.CustomerSimulations(context.Background(), s.customerID()) + s.Require().NoError(err) + var names []string + for _, simulation := range all { + if simulation.ConfigID == configID { + names = append(names, simulation.Name) + } + } + slices.Sort(names) + return names +} + +func (s *DirectorySuite) TestASyncSaysWhatItDoesToSkillsKnowledgePagesAndSimulations() { + first := map[string]string{ + "skills/refund.md": "---\ndescription: work out a refund\n---\nRead the policy.\n", + "skills/think.md": "---\ndescription: think\n---\nReason.\n", + "knowledge/pricing.md": "Pro costs twenty dollars.\n", + "knowledge/hours.md": "Open nine to five.\n", + "knowledge/urls.yaml": "- https://example.com/pricing\n", + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n- name: refund\n scenario: Ask.\n assertion: Refunded.\n", + } + created := s.sync(first) + s.ElementsMatch([]SyncChange{ + {ResourceType: "skill", Name: "refund", Action: "created"}, {ResourceType: "skill", Name: "think", Action: "created"}, + {ResourceType: "knowledge", Name: "pricing.md", Action: "created"}, {ResourceType: "knowledge", Name: "hours.md", Action: "created"}, + {ResourceType: "knowledge_url", Name: "https://example.com/pricing", Action: "created"}, + {ResourceType: "simulation", Name: "lunch", Action: "created"}, {ResourceType: "simulation", Name: "refund", Action: "created"}, + }, created.Changes) + + second := map[string]string{ + "skills/refund.md": "---\ndescription: work out a refund\n---\nRead the new policy.\n", + "skills/think.md": "---\ndescription: think\n---\nReason.\n", + "knowledge/pricing.md": "Pro costs thirty dollars.\n", + "knowledge/urls.yaml": "- url: https://example.com/pricing\n title: Pricing\n", + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n- name: hours\n scenario: Ask.\n assertion: Told.\n", + } + want := []SyncChange{ + {ResourceType: "skill", Name: "refund", Action: "updated"}, + {ResourceType: "knowledge", Name: "pricing.md", Action: "updated"}, {ResourceType: "knowledge", Name: "hours.md", Action: "deleted"}, + {ResourceType: "knowledge_url", Name: "https://example.com/pricing", Action: "updated"}, + {ResourceType: "simulation", Name: "hours", Action: "created"}, {ResourceType: "simulation", Name: "refund", Action: "deleted"}, + } + + preview := s.syncWith(second, map[string]any{"dry_run": true}) + s.ElementsMatch(want, preview.Changes, "a dry run says what the sync would do, and what it leaves as it is is not listed") + s.Equal([]string{"lunch", "refund"}, s.simulations(created.Config.Id), "and does none of it") + + s.ElementsMatch(want, s.sync(second).Changes) + s.Equal([]string{"hours", "lunch"}, s.simulations(created.Config.Id)) + s.Empty(s.sync(second).Changes) + + none := s.syncWith(map[string]string{"instructions.md": "Be brief.\n"}, map[string]any{"dry_run": true}) + s.ElementsMatch([]SyncChange{ + {ResourceType: "knowledge", Name: "pricing.md", Action: "deleted"}, + }, none.Changes, "with no knowledge folder the agent's own base is emptied, and with no simulations file they are left alone") +} + +func (s *DirectorySuite) TestADryRunAnswersWhatWouldBeStoredAndWritesNothing() { + created := s.syncWith(map[string]string{ + "agent.yaml": "name: support\nllm: llm-flow\n", + "instructions.md": "Be brief.\n", + "skills/refund.md": "---\ndescription: work out a refund\n---\nRead the policy.\n", + "knowledge/pricing.md": "Pro costs twenty dollars.\n", + "simulations/a.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n", + }, map[string]any{"dry_run": true}) + + s.False(created.Unchanged) + s.Empty(created.Config.Id, "a config a dry run would create has no id") + s.Equal("llm-flow", value(created.Config.Llm)) + s.Equal("Be brief.", value(created.Config.Instructions)) + s.Equal([]string{"refund"}, value(created.Config.Skills)) + s.Equal("support", value(created.Config.KnowledgeNamespace)) + s.Empty(s.configsNamed("support"), "nothing was stored") + documents, err := s.store.CustomerKnowledgeDocuments(context.Background(), s.customerID(), "support") + s.Require().NoError(err) + s.Empty(documents) +} + +func (s *DirectorySuite) TestADryRunOverAStoredAgentLeavesItAsItIs() { + first := s.sync(map[string]string{"agent.yaml": "name: support\nllm: llm-flow\n", "instructions.md": "Be brief.\n"}) + before := s.config(first.Config.Id) + recorded := len(s.audited(first.Config.Id)) + + preview := s.syncWith(map[string]string{"agent.yaml": "name: support\nllm: llm-fast\n", "instructions.md": "Be thorough.\n"}, + map[string]any{"dry_run": true}) + + s.Equal(first.Config.Id, preview.Config.Id) + s.Equal("llm-fast", value(preview.Config.Llm)) + s.Equal("Be thorough.", value(preview.Config.Instructions)) + s.Equal(before, s.config(first.Config.Id)) + s.Len(s.audited(first.Config.Id), recorded, "a dry run records no sync") + + same := s.syncWith(map[string]string{"agent.yaml": "name: support\nllm: llm-flow\n", "instructions.md": "Be brief.\n"}, + map[string]any{"dry_run": true}) + s.True(same.Unchanged, "a dry run of the files already synced says a sync would do nothing") +} + +func (s *DirectorySuite) TestADryRunIsRefusedAsTheSyncWouldBe() { + first := s.sync(map[string]string{"agent.yaml": "name: support\nllm: llm-flow\n"}) + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+first.Config.Id, + map[string]any{"llm": "llm-fast"}, nil)) + + conflict, failure := s.refused(map[string]string{"agent.yaml": "name: support\nllm: llm-thinking\n"}, + map[string]any{"dry_run": true, "check_changes": true}) + s.Equal(http.StatusConflict, conflict) + s.Equal(codeUnsyncedChanges, failure.Code) + + invalid, _ := s.refused(map[string]string{"agent.yaml": "name: support\nsandbox: nowhere\n"}, map[string]any{"dry_run": true}) + s.Equal(http.StatusBadRequest, invalid) + + oversized, failure := s.refused(map[string]string{ + "agent.yaml": "name: support\nsandbox: daytona\n", + "skills/big/SKILL.md": "---\ndescription: big\n---\nRun it.\n", + "skills/big/a.txt": strings.Repeat("a", 1<<20), + "skills/big/b.txt": "one byte too many", + }, map[string]any{"dry_run": true}) + s.Equal(http.StatusBadRequest, oversized) + s.Contains(failure.Message, "a skill's files may hold at most") +} + +// frontDesk is a directory written the way an export writes one, setting most of what +// agent.yaml can say. +func (s *DirectorySuite) frontDesk() map[string]string { + connection := s.connection("slack", "Support workspace") + return map[string]string{ + "agent.yaml": `name: front-desk +mode: voice +tts: tts-fast +voice: aurora +llm: llm-flow +subagent: llm-thinking +greeting: + text: Hi, how can I help? + mode: variation +sandbox: daytona +sandbox_options: + setup: + - pip install pandas + timeout: 1m30s + cpu: 2 +connectors: + - github + - name: inbox + connector: slack + tools: + - search + - post_* + connection: ` + connection + ` + required: true + require_approval: + - post_* +tools: + - name: booking + loading: summary + tools: + - lookup_booking + output_retention: 30d +chat_channels: + - type: team + answer: mentioned +scheduling: + enabled: true + max_tasks_per_user: 10 + default_timezone: Europe/Amsterdam +calls: + end_call: + enabled: true + when: The caller says goodbye. + press: + enabled: false + transfer: + destinations: + - name: billing + number: "+15551234567" + when: 'Questions about an invoice: refunds, too.' + warm: true +keyterms: + - Stream + - 10DLC +tags: + project: front-desk +video: + source: screen + max_frames: 4 +dispatch: + incoming_call: enabled +ui: + keep: + - CardHeader + rules: + - Be brief. +`, + "instructions.md": "You answer the phone.\n", + "guardrail.md": "---\ntype: llm\n---\nNo medical advice.\n", + "skills/refunds/SKILL.md": "---\ndescription: Work out a refund\ndeadline: 2m\n---\nRead the policy.\n", + "skills/refunds/reference.md": "# Refund policy\n", + "knowledge/plans/pro.md": "Pro costs twenty dollars.\n", + "simulations/simulations.yaml": "- name: lunch\n scenario: Order a turkey club.\n assertion: One turkey club.\n variations: 3\n", + "ui/blueprints.yaml": "- name: booking\n when: booking a table\n order: [CardHeader]\n", + } +} + +func (s *DirectorySuite) TestAnAgentIsExportedAsTheDirectoryItWasSyncedFrom() { + written := s.frontDesk() + synced := s.sync(written) + + held, directory := s.exported(synced.Config.Id) + + s.Equal("front-desk", directory.Name) + s.Equal(written, held) + s.Empty(directory.NotExported) + var paths []string + for _, file := range directory.Files { + paths = append(paths, file.Path) + } + s.IsIncreasing(paths) +} + +func (s *DirectorySuite) TestAnExportLeavesOutWhatASyncFillsInOnItsOwn() { + var created AgentConfig + s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/configs", + map[string]any{"name": "plain", "mode": "voice"}, &created)) + + held, directory := s.exported(created.Id) + + s.Equal(map[string]string{"agent.yaml": "name: plain\nmode: voice\n"}, held) + s.Empty(directory.NotExported) +} + +func (s *DirectorySuite) TestSyncingAnExportBackChangesNothing() { + synced := s.sync(s.frontDesk()) + before := s.config(synced.Config.Id) + held, _ := s.exported(synced.Config.Id) + + preview := s.syncWith(held, map[string]any{"dry_run": true}) + again := s.sync(held) + + after := s.config(synced.Config.Id) + s.True(preview.Unchanged) + s.True(again.Unchanged, "an export of what was synced is the files that were synced") + s.Equal(before, after) +} + +func (s *DirectorySuite) TestSyncingTheExportOfAnAgentMadeInTheDashboardChangesNothing() { + connection := s.connection("slack", "") + var created AgentConfig + s.Require().Equal(http.StatusCreated, s.dashboard().do(http.MethodPost, "/v1/agents/configs", map[string]any{ + "name": "desk", "mode": "voice", "llm": "llm-flow", "voice": "aurora", "instructions": "Be brief.", + "greeting": map[string]any{"text": "Hello."}, "keyterms": []string{"Stream"}, + "llm_fallbacks": []string{"llm-fast"}, "visible_tools": []string{"search"}, + "connectors": []map[string]any{ + {"name": "inbox", "connector_id": "slack", "connection": map[string]any{"type": "fixed", "connection_id": connection}, + "tools": []any{}, "tool_patterns": []string{"search"}, "required": true}, + }, + "calls": map[string]any{"end_call": map[string]any{"enabled": true, "when": "They say goodbye."}}, + }, &created)) + before := s.config(created.Id) + held, directory := s.exported(created.Id) + s.Empty(directory.NotExported) + + synced := s.sync(held) + + s.False(synced.Unchanged, "the config was never synced, so the files are new to it") + after := s.config(created.Id) + before.UpdatedAt, before.SyncHash = after.UpdatedAt, after.SyncHash + s.Equal(before, after, "what agent.yaml cannot say, such as llm_fallbacks and visible_tools, is left as it was") +} + +func (s *DirectorySuite) TestAnExportSaysWhatItsDirectoryCannot() { + connection := s.connection("slack", "") + var created AgentConfig + s.Require().Equal(http.StatusCreated, s.dashboard().do(http.MethodPost, "/v1/agents/configs", map[string]any{ + "name": "desk", "mode": "voice", "ui_instructions": "Answer with cards.", + "connectors": []map[string]any{ + fixedSlack("inbox", connection), + {"name": "idle", "connector_id": "github", "connection": map[string]any{"type": "session"}, "tools": []any{}}, + }, + }, &created)) + + held, directory := s.exported(created.Id) + + s.Equal("name: desk\nmode: voice\nconnectors:\n - name: inbox\n connector: slack\n tools:\n - search\n connection: "+ + connection+"\n required: true\n", held["agent.yaml"]) + s.Len(directory.NotExported, 4, "%v", directory.NotExported) + said := strings.Join(directory.NotExported, "\n") + s.Contains(said, "The connector inbox grants its tools by name and schema digest") + s.Contains(said, "The connector inbox has a timeout, events or a policy") + s.Contains(said, "The connector idle grants no tools") + s.Contains(said, "UI instructions were not compiled from a directory's files") +} + +func (s *DirectorySuite) TestAConnectorLeftOutIsExportedAsAgentYAMLNamedIt() { + synced := s.sync(map[string]string{"agent.yaml": "name: support\nconnectors:\n - {name: inbox, connector: slack, connection: Support workspace}\n"}) + + held, _ := s.exported(synced.Config.Id) + + s.Equal("name: support\nmode: voice\nconnectors:\n - name: inbox\n connector: slack\n connection: Support workspace\n", held["agent.yaml"]) +} + +func (s *DirectorySuite) TestUIInstructionsWrittenSinceTheSyncAreNotExportedAsTheFilesTheyReplaced() { + held := map[string]string{"agent.yaml": "name: support\nui:\n rules: [Be brief.]\n"} + edits := map[string]func(id string) int{ + "patched": func(id string) int { + return s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+id, map[string]any{"ui_instructions": "Answer with cards."}, nil) + }, + "replaced": func(id string) int { + return s.dashboard().do(http.MethodPut, "/v1/agents/configs/"+id, + map[string]any{"name": "support", "mode": "voice", "ui_instructions": "Answer with cards."}, nil) + }, + } + for how, edit := range edits { + s.useApp(s.data.createApp()) + synced := s.sync(held) + s.Require().Equal(http.StatusOK, edit(synced.Config.Id), how) + + exported, directory := s.exported(synced.Config.Id) + + s.NotContains(exported["agent.yaml"], "ui:", how) + s.Contains(strings.Join(directory.NotExported, "\n"), "UI instructions were not compiled from a directory's files", how) + } +} + +func (s *DirectorySuite) TestAnEditThatLeavesTheUIInstructionsAloneKeepsTheFilesTheyCameFrom() { + synced := s.sync(map[string]string{"agent.yaml": "name: support\nui:\n rules: [Be brief.]\n"}) + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+synced.Config.Id, + map[string]any{"voice": "aurora"}, nil)) + + exported, directory := s.exported(synced.Config.Id) + + s.Contains(exported["agent.yaml"], "ui:\n rules:\n - Be brief.\n") + s.Empty(directory.NotExported) +} + +func (s *DirectorySuite) TestAnExportLeavesOutKnowledgeASyncWouldNotTakeBack() { + synced := s.sync(map[string]string{"knowledge/small.md": "Pro costs twenty dollars.\n"}) + var ingested any + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/knowledge", map[string]any{ + "namespace": "support", "documents": []map[string]string{{"source": "big.md", "text": strings.Repeat("word ", 1<<18)}}, + }, &ingested)) + + held, directory := s.exported(synced.Config.Id) + + s.Contains(held, "knowledge/small.md") + s.NotContains(held, "knowledge/big.md") + s.Contains(strings.Join(directory.NotExported, "\n"), `The knowledge document "big.md" is more than a directory may hold`) + s.Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/sync/files", + map[string]any{"files": sentFiles(held), "dry_run": true}, nil), "what is exported is something a sync takes") +} + +func (s *DirectorySuite) TestASkillIsExportedAsASyncReadsItBack() { + held := map[string]string{ + "agent.yaml": "name: support\nmode: voice\n", + "skills/steps/SKILL.md": "---\ndescription: Say \"hello\"\n---\n- First.\n- Second.\n", + "skills/rule/SKILL.md": "---\ndescription: \"'quoted'\"\n---\n---\n\nAfter a rule.\n", + } + synced := s.sync(held) + + exported, directory := s.exported(synced.Config.Id) + + s.Equal(held["skills/steps/SKILL.md"], exported["skills/steps/SKILL.md"]) + s.Equal(held["skills/rule/SKILL.md"], exported["skills/rule/SKILL.md"]) + s.Empty(directory.NotExported) + s.True(s.sync(exported).Unchanged) +} + +func (s *DirectorySuite) TestAnExportOfSkillFilesAFolderCannotHoldStillSyncsBack() { + synced := s.sync(map[string]string{"agent.yaml": "name: support\nmode: voice\n"}) + for _, skill := range []map[string]any{ + {"name": "Alpha", "files": map[string]string{"SKILL.md": "another", ".hidden.md": "x", "notes.md": "kept"}}, + {"name": "alpha"}, + } { + skill["config_id"], skill["description"], skill["instructions"] = synced.Config.Id, "d", "i" + s.Require().Equal(http.StatusCreated, s.dashboard().do(http.MethodPost, "/v1/agents/skills", skill, nil)) + } + s.Require().Equal(http.StatusOK, s.dashboard().do(http.MethodPatch, "/v1/agents/configs/"+synced.Config.Id, + map[string]any{"skills": []string{"Alpha", "alpha"}}, nil)) + + held, directory := s.exported(synced.Config.Id) + + s.Len(directory.NotExported, 2, "%v", directory.NotExported) + s.Equal("kept", held["skills/Alpha/notes.md"]) + s.Contains(held, "skills/skill-1/SKILL.md", "alpha has a folder Alpha does not share where case folds") + s.Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/sync/files", map[string]any{"files": sentFiles(held)}, nil), + "what is exported is a directory a sync takes") +} + +func (s *DirectorySuite) TestAnExportSaysWhenASyncWouldTrimTheInstructionsOrDropTheKnowledgeBase() { + var created AgentConfig + s.Require().Equal(http.StatusCreated, s.dashboard().do(http.MethodPost, "/v1/agents/configs", map[string]any{ + "name": "desk", "mode": "voice", "instructions": "\nBe brief.\n\n", "knowledge_namespace": "handbook", + }, &created)) + + _, directory := s.exported(created.Id) + + said := strings.Join(directory.NotExported, "\n") + s.Contains(said, "instructions.md starts or ends with blank space") + s.Contains(said, `None of the agent's knowledge base "handbook" is in these files`) +} + +func (s *DirectorySuite) TestAnExportCountsEverythingItWritesAgainstWhatADirectoryMayHold() { + held := map[string]string{"simulations/a.yaml": "- name: lunch\n scenario: " + strings.Repeat("Ask. ", 190_000) + "\n assertion: Answered.\n"} + for _, name := range []string{"a", "b", "c", "d", "e", "f", "g"} { + held["knowledge/"+name+".md"] = strings.Repeat(name+" ", 1<<19)[:1<<20-16] + } + synced := s.sync(held) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/knowledge", map[string]any{ + "namespace": "support", "documents": []map[string]string{{"source": "h.md", "text": strings.Repeat("h ", 1<<18)}}, + }, nil)) + + exported, directory := s.exported(synced.Config.Id) + + total := 0 + for _, content := range exported { + total += len(content) + } + s.LessOrEqual(total, 8<<20) + s.Contains(strings.Join(directory.NotExported, "\n"), `The knowledge document "h.md" is more than a directory may hold`) +} + +func (s *DirectorySuite) TestOnlyTheAppsOwnBackendMayReadOrSendADirectory() { + synced := s.sync(map[string]string{"instructions.md": "Be brief.\n"}) + + s.assertPosture(serverOnly, func(as *testClient) int { + return as.do(http.MethodGet, "/v1/agents/configs/"+synced.Config.Id+"/directory", nil, nil) + }) + s.assertPosture(serverOnly, func(as *testClient) int { + return as.do(http.MethodPost, "/v1/agents/sync/files", map[string]any{ + "files": sentFiles(map[string]string{"agent.yaml": "name: agent-" + s.utils.uuid() + "\n"}), "dry_run": true, + }, nil) + }) +} + +func (s *DirectorySuite) TestAnotherAppsAgentHasNoDirectoryToRead() { + synced := s.sync(map[string]string{"instructions.md": "Be brief.\n"}) + + s.assertHiddenFromOtherApps(func(as *testClient) int { + return as.do(http.MethodGet, "/v1/agents/configs/"+synced.Config.Id+"/directory", nil, nil) + }) +} diff --git a/acceleration/internal/api/knowledge.go b/acceleration/internal/api/knowledge.go index 7450fe3061..5b250d6beb 100644 --- a/acceleration/internal/api/knowledge.go +++ b/acceleration/internal/api/knowledge.go @@ -252,7 +252,31 @@ func (s *Server) knowledgePassages( // that changed nothing in knowledge/ writes nothing and is not refused for money. func (s *Server) fillKnowledge( ctx context.Context, customerID, region, namespace string, documents []KnowledgeDocument, chunkSize *int, -) (_ int, _ int, err error) { +) (int, int, error) { + fill, err := s.planKnowledge(ctx, customerID, region, namespace, documents, chunkSize) + if err != nil { + return 0, 0, err + } + return fill.read, fill.cut, s.writeKnowledge(ctx, customerID, region, namespace, fill) +} + +// knowledgeFill is what filling a knowledge base with some documents would write. +type knowledgeFill struct { + // read is how many documents held anything, and cut how many passages they became. + read, cut int + passages []knowledge.Document + // written are the documents that are not already in the base as they are. + written []store.KnowledgeDocument + before map[string]store.KnowledgeDocument +} + +// planKnowledge works out what filling a base would write, and refuses what the write would +// refuse before it wrote anything: documents with nothing to read, and an owner who may not +// pay for the write. It writes nothing, so a dry run is refused as the sync would be. What it +// cannot tell is whether the provider will take the passages, which only writing them does. +func (s *Server) planKnowledge( + ctx context.Context, customerID, region, namespace string, documents []KnowledgeDocument, chunkSize *int, +) (knowledgeFill, error) { size := ingest.DefaultChunk if chunkSize != nil && *chunkSize > 0 { size = *chunkSize @@ -264,7 +288,7 @@ func (s *Server) fillKnowledge( if s.store != nil { stored, err := s.store.CustomerKnowledgeDocumentsWithText(ctx, customerID, namespace) if err != nil { - return 0, 0, err + return knowledgeFill{}, err } for _, document := range stored { before[document.Source] = document @@ -277,7 +301,7 @@ func (s *Server) fillKnowledge( for _, document := range documents { source := strings.TrimSpace(document.Source) if source == "" { - return 0, 0, invalidRequest("every document needs a source, which is what its passages are keyed by") + return knowledgeFill{}, invalidRequest("every document needs a source, which is what its passages are keyed by") } // A document that is only whitespace is skipped rather than refused: a directory // posted whole often has one in it, and failing the lot over it helps nobody. @@ -303,24 +327,30 @@ func (s *Server) fillKnowledge( } if cut == 0 { - return 0, 0, invalidRequest("there is nothing to read in these documents") + return knowledgeFill{}, invalidRequest("there is nothing to read in these documents") + } + fill := knowledgeFill{read: read, cut: cut, passages: passages, written: written, before: before} + // Refused before any row is written, so a refused ingest leaves nothing listed. + if len(written) > 0 && s.store != nil { + if err := s.knowledgeFor(ctx, customerID, region).Admit(ctx); err != nil { + return knowledgeFill{}, err + } } + return fill, nil +} + +// writeKnowledge writes what planKnowledge worked out. +func (s *Server) writeKnowledge(ctx context.Context, customerID, region, namespace string, fill knowledgeFill) (err error) { + passages, written, before := fill.passages, fill.written, fill.before if len(written) == 0 { - return read, cut, nil + return nil } writer := s.knowledgeFor(ctx, customerID, region) if s.store == nil { - if err := writer.Upsert(ctx, namespace, passages); err != nil { - return 0, 0, err - } - return read, cut, nil - } - // Refused before any row is written, so a refused ingest leaves nothing listed. - if err := writer.Admit(ctx); err != nil { - return 0, 0, err + return writer.Upsert(ctx, namespace, passages) } if err := writer.Keep(ctx, namespace); err != nil { - return 0, 0, err + return err } // Every row is saved before the passages, counting the old version's passages as well as @@ -336,11 +366,11 @@ func (s *Server) fillKnowledge( document.Passages = max(document.Passages, before[document.Source].Passages) document.State = store.KnowledgeDocumentPending if err = s.store.SaveKnowledgeDocument(ctx, &document); err != nil { - return 0, 0, err + return err } } if err = writer.Upsert(ctx, namespace, passages); err != nil { - return 0, 0, err + return err } agentID := s.agentOfKnowledge(ctx, customerID, namespace) @@ -349,11 +379,11 @@ func (s *Server) fillKnowledge( was, had := before[document.Source] stale := ingest.IDs(document.Source, document.Passages, was.Passages) if err = writer.Delete(ctx, namespace, stale); err != nil { - return 0, 0, err + return err } document.State = store.KnowledgeDocumentIndexed if err = s.store.SaveKnowledgeDocument(ctx, document); err != nil { - return 0, 0, err + return err } indexed++ action := store.AuditCreated @@ -368,7 +398,7 @@ func (s *Server) fillKnowledge( Changes: auditDiff(previous, auditedKnowledgeOf(*document)), }) } - return read, cut, nil + return nil } // knowledgeWriteFailed is why a failed document failed, as its row tells the customer. The diff --git a/acceleration/internal/api/openapi.go b/acceleration/internal/api/openapi.go index 7c9fea7216..172d754768 100644 --- a/acceleration/internal/api/openapi.go +++ b/acceleration/internal/api/openapi.go @@ -402,7 +402,9 @@ func (s *Server) newAPI(router chi.Router) huma.API { s.registerOCR(api) documentHandWritten(api) s.registerConfigPatch(api) + s.schemas = api.OpenAPI().Components.Schemas s.registerSync(api) + s.registerDirectory(api) s.registerAudit(api) s.registerConnectors(api) s.registerOAuthClients(api) diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 852dbf6de3..53c99f3c6d 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -381,27 +381,29 @@ type Server struct { knowledge *metered.Knowledge knowledgeLimits ingest.Limits pages *urls.Service - knowledgeFiles *files.Service - voices *voices.Service - library *voices.Catalogue - dispatch *dispatch.Pool - secrets *auth.Sealer - privateModels bool - corsOrigins []string - publicURL string - dashboardURL string - channels *channels.Service - dlc *dlc.Service - gate *dlc.Gate - opsKey string - manageKey string - authenticator auth.Authenticator - authMode auth.Mode - dataRetention time.Duration - exportWritesWait time.Duration - quota *quota.Limiter - policies *policy.Enforcer - connectors core.Registry + // schemas are the API's own, which a directory's settings are held to as a request's are. + schemas huma.Registry + knowledgeFiles *files.Service + voices *voices.Service + library *voices.Catalogue + dispatch *dispatch.Pool + secrets *auth.Sealer + privateModels bool + corsOrigins []string + publicURL string + dashboardURL string + channels *channels.Service + dlc *dlc.Service + gate *dlc.Gate + opsKey string + manageKey string + authenticator auth.Authenticator + authMode auth.Mode + dataRetention time.Duration + exportWritesWait time.Duration + quota *quota.Limiter + policies *policy.Enforcer + connectors core.Registry // connectorSecrets seals consent attempts; credentials stores what a consent got. Both // are nil when connectors are off. connectorSecrets *auth.Sealer diff --git a/acceleration/internal/api/sync.go b/acceleration/internal/api/sync.go index 5aa8afe9c5..e6af8c220b 100644 --- a/acceleration/internal/api/sync.go +++ b/acceleration/internal/api/sync.go @@ -3,17 +3,18 @@ package api import ( "cmp" "context" - "errors" "fmt" + "maps" "net/http" + "slices" "strings" "github.com/danielgtaylor/huma/v2" + "github.com/GetStream/Vision-Agents/acceleration/internal/agentdir" "github.com/GetStream/Vision-Agents/acceleration/internal/knowledge/urls" "github.com/GetStream/Vision-Agents/acceleration/internal/pricing" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" - "github.com/GetStream/Vision-Agents/acceleration/internal/stack" "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/stt" ) @@ -146,9 +147,126 @@ func (*SimulationDeclaration) TransformSchema(_ huma.Registry, schema *huma.Sche // SyncAgentResult is the config a sync left stored. type SyncAgentResult struct { - Unchanged bool `json:"unchanged" doc:"True when the hash matched and nothing was written."` - Config AgentConfig `json:"config"` - Warnings []string `json:"warnings,omitempty" doc:"What was stored but will not work yet, such as a channel line the app has not connected."` + Unchanged bool `json:"unchanged" doc:"True when the hash matched and nothing was written."` + Config AgentConfig `json:"config"` + Warnings []string `json:"warnings,omitempty" doc:"What was stored but will not work yet, such as a channel line the app has not connected."` + Changes []SyncChange `json:"changes,omitempty" nullable:"false" doc:"What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it leaves as it is is not listed, and nothing is for a sync that found the hash unchanged."` +} + +// SyncChange is one thing a sync writes beside the config. +type SyncChange struct { + ResourceType string `json:"resource_type" enum:"skill,knowledge,knowledge_url,simulation" doc:"What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep."` + Name string `json:"name" doc:"Which one: a skill's name, a knowledge document's source, a knowledge url's url, a simulation's name."` + Action string `json:"action" enum:"created,updated,deleted"` +} + +func (*SyncChange) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes." + return schema +} + +// syncChanges works out what a sync would write beside the config, before it writes any of +// it: the same question each write below answers for itself, asked together so a dry run can +// say it. +func (s *Server) syncChanges( + ctx context.Context, customerID string, existing store.AgentConfig, body SyncAgentRequest, fill knowledgeFill, forgets bool, +) ([]SyncChange, error) { + var changes []SyncChange + say := func(kind, name, action string) { + changes = append(changes, SyncChange{ResourceType: kind, Name: name, Action: action}) + } + written := func(held bool) string { + if held { + return store.AuditUpdated + } + return store.AuditCreated + } + + var skills []store.Skill + var simulations []store.Simulation + if existing.ID != "" { + var err error + if skills, err = s.store.CustomerSkills(ctx, customerID, existing.ID); err != nil { + return nil, err + } + all, err := s.store.CustomerSimulations(ctx, customerID) + if err != nil { + return nil, err + } + for _, simulation := range all { + if simulation.ConfigID == existing.ID { + simulations = append(simulations, simulation) + } + } + } + for _, skill := range skillsOf(body.Skills) { + was, held := skillNamedStored(skills, strings.TrimSpace(skill.Name)) + if !held || !sameSkill(was, storedSkill(skill, was.CustomerID)) { + say(store.AuditSkill, strings.TrimSpace(skill.Name), written(held)) + } + } + + for _, document := range fill.written { + _, held := fill.before[document.Source] + say(store.AuditKnowledge, document.Source, written(held)) + } + if forgets { + stored, err := s.store.CustomerKnowledgeDocuments(ctx, customerID, body.Name) + if err != nil { + return nil, err + } + for _, document := range stored { + kept := slices.ContainsFunc(documentsOf(body.Knowledge), func(sent KnowledgeDocument) bool { + return strings.TrimSpace(sent.Source) == document.Source && strings.TrimSpace(sent.Text) != "" + }) + if !kept { + say(store.AuditKnowledge, document.Source, store.AuditDeleted) + } + } + } + if pages := value(body.KnowledgeUrls); len(pages) > 0 { + subscribed, err := s.pages.List(ctx, customerID, body.Name) + if err != nil { + return nil, err + } + for _, page := range pages { + at := slices.IndexFunc(subscribed, func(was store.KnowledgeURL) bool { return was.URL == strings.TrimSpace(page.Url) }) + if at < 0 || subscribed[at].DeclaredTitle != value(page.Title) || subscribed[at].Description != value(page.Description) || + subscribed[at].RefreshHours != value(page.RefreshHours) { + say(store.AuditKnowledgeURL, strings.TrimSpace(page.Url), written(at >= 0)) + } + } + } + + if body.Simulations != nil { + declared := map[string]bool{} + for _, declaration := range *body.Simulations { + name := strings.TrimSpace(declaration.Name) + declared[name] = true + at := slices.IndexFunc(simulations, func(was store.Simulation) bool { return was.Name == name }) + if at < 0 || !sameSimulation(simulations[at], declaration) { + say("simulation", name, written(at >= 0)) + } + } + for _, simulation := range simulations { + if !declared[simulation.Name] { + say("simulation", simulation.Name, store.AuditDeleted) + } + } + } + return changes, nil +} + +// sameSimulation reports whether a declaration says what a stored simulation is, with what +// the store fills in for what a declaration leaves out. +func sameSimulation(was store.Simulation, declared SimulationDeclaration) bool { + return was.Scenario == strings.TrimSpace(declared.Scenario) && was.Assertion == strings.TrimSpace(declared.Assertion) && + was.Mode == cmp.Or(value(declared.Mode), store.SimulationText) && + was.Variations == max(value(declared.Variations), 1) && + was.MaxTurns == cmp.Or(value(declared.MaxTurns), store.DefaultSimulationTurns) && + was.CallerTarget == value(declared.CallerTarget) && was.JudgeTarget == value(declared.JudgeTarget) && + was.CallerSTT == value(declared.CallerStt) && was.CallerTTS == value(declared.CallerTts) && + was.CallerVoice == value(declared.CallerVoice) && maps.Equal(was.Tags, value(declared.Tags)) } type syncAgentRequest struct { @@ -198,12 +316,20 @@ func (s *Server) registerSync(api huma.API) { // The hash is a fingerprint of that directory. A second call with the same hash does // nothing, so a process that syncs on startup is cheap when nothing has changed. func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syncAgentResponse, error) { + return s.sync(ctx, directorySync{body: request.Body}) +} + +// sync stores what a sync says the agent is: the request a client sent, or the one a +// directory's files amount to. +func (s *Server) sync(ctx context.Context, read directorySync) (*syncAgentResponse, error) { customerID, ok := CustomerFrom(ctx) if !ok { return nil, errMissingCustomer } - - body := request.Body + if s.store == nil { + return nil, errNoConfigs + } + body := read.body name := strings.TrimSpace(body.Name) hash := strings.TrimSpace(body.Hash) if name == "" { @@ -213,11 +339,21 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn return nil, invalidRequest("a hash is required, so a second sync can do nothing") } - if s.store == nil { - return nil, errNoConfigs + // A sync of files is told everything its settings may not be at once, each where + // agent.yaml says it. One sent as fields is refused at the first, as it always was. + var problems agentdir.Problems + refuse := func(setting, message string) error { + if read.directory == nil { + return invalidRequest(message) + } + line, column := read.directory.Locate(setting) + problems = append(problems, agentdir.Problem{File: agentdir.AgentFile, Line: line, Column: column, Message: message}) + return nil } - if message, ok := syncComplaint(ctx, body); !ok { - return nil, invalidRequest(message) + for _, complaint := range syncComplaints(ctx, body) { + if err := refuse(complaint.setting, complaint.message); err != nil { + return nil, err + } } // Before the hash is read, so a directory that still names any is refused rather than // found unchanged. @@ -245,7 +381,9 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn if message, ok, err := s.unboundConnectors(ctx, customerID, body.Connectors); err != nil { return nil, err } else if !ok { - return nil, invalidRequest(message) + if err := refuse("connectors", message); err != nil { + return nil, err + } } config := existing var stored *savedSandbox @@ -259,44 +397,68 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn // into a base kept in another region than the agent's. config.Region = cmp.Or(config.Region, pricing.DefaultRegion) if message, ok := textSubagentComplaint(&config, body.Subagent); !ok { - return nil, invalidRequest(message) + if err := refuse("subagent", message); err != nil { + return nil, err + } } warnings, message, ok := s.channelsWarnings(ctx, config) if !ok { - return nil, invalidRequest(message) + if err := refuse("channels", message); err != nil { + return nil, err + } } + warnings = append(read.warnings, warnings...) if message, ok := schedulingComplaint(config); !ok { - return nil, invalidRequest(message) + if err := refuse("scheduling", message); err != nil { + return nil, err + } } if failure, refused := s.floorControlRefusal(body.FloorControl, body.EndOfTurn); refused { - return nil, failure + if read.directory == nil { + return nil, failure + } + _ = refuse("floor_control", failure.Message) } if warning, message, ok := s.floorControlComplaint(ctx, config.FloorControl, existing.FloorControl); !ok { - return nil, invalidRequest(message) + if err := refuse("floor_control", message); err != nil { + return nil, err + } } else if warning != "" && body.FloorControl != nil { warnings = append(warnings, warning) } if message, ok := callsComplaint(config.Calls); !ok { - return nil, invalidRequest(message) + if err := refuse("calls", message); err != nil { + return nil, err + } } if message, ok := teamTagComplaint(config.Tags, existing.Tags); !ok { - return nil, invalidRequest(message) + if err := refuse("tags", message); err != nil { + return nil, err + } } if message, ok := toolsComplaint(config); !ok { - return nil, invalidRequest(message) + if err := refuse("tools", message); err != nil { + return nil, err + } } if message, ok, err := s.sandboxBindingsComplaint(ctx, customerID, config); err != nil { return nil, err } else if !ok { - return nil, invalidRequest(message) + if err := refuse("connectors", message); err != nil { + return nil, err + } } if message, ok, err := s.sensitiveBindingsComplaint(ctx, customerID, config); err != nil { return nil, err } else if !ok { - return nil, invalidRequest(message) + if err := refuse("connectors", message); err != nil { + return nil, err + } } if message, ok := s.liveSTTComplaint(config, existing.STT); !ok { - return nil, invalidRequest(message) + if err := refuse("stt", message); err != nil { + return nil, err + } } var prior *store.AgentConfig if found { @@ -305,14 +467,16 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn if message, ok, err := s.childAgentsComplaint(ctx, customerID, &config, prior); err != nil { return nil, err } else if !ok { - return nil, invalidRequest(message) + if err := refuse("agents", message); err != nil { + return nil, err + } } if failure, refused := s.sandboxLimitsComplaint(ctx, customerID, config, stored); refused { return nil, failure } // Asked of the knowledge base the sync is about to write, the one named after the agent. documents := documentsOf(body.Knowledge) - knows := len(documents) > 0 || (body.KnowledgeUrls != nil && len(*body.KnowledgeUrls) > 0) + knows := len(documents) > 0 || len(value(body.KnowledgeUrls)) > 0 regional := config regional.KnowledgeNamespace = "" if knows { @@ -321,30 +485,64 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn if message, ok, err := s.regionComplaint(ctx, regional, prior); err != nil { return nil, err } else if !ok { - return nil, invalidRequest(message) + if err := refuse("region", message); err != nil { + return nil, err + } } skills := skillsOf(body.Skills) // After the settings, so a sandbox stored before and not repeated still counts. if message, ok := skillSandboxComplaint(skills, config.Sandbox != ""); !ok { - return nil, invalidRequest(message) + if err := refuse("sandbox", message); err != nil { + return nil, err + } } + if len(problems) > 0 { + return nil, invalidDirectory(problems) + } + // Everything a write below would refuse is refused here, before the first of them: a sync + // refused halfway is an agent half written, and a dry run answers as the sync would. named := make([]string, 0, len(skills)) for _, skill := range skills { + // The config owns its skills and may not be stored yet, so there is no id to name. + skill.ConfigId = name + if message, ok := skillComplaint(skill); !ok { + return nil, invalidRequest(message) + } + if slices.Contains(named, strings.TrimSpace(skill.Name)) { + return nil, invalidRequest(fmt.Sprintf("two skills are called %q", strings.TrimSpace(skill.Name))) + } named = append(named, strings.TrimSpace(skill.Name)) } + pages := value(body.KnowledgeUrls) + if len(documents) > 0 && s.knowledge == nil { + return nil, errNoKnowledge + } + if len(pages) > 0 && s.pages == nil { + return nil, errNoKnowledgeURLs + } + for _, document := range documents { + if strings.TrimSpace(document.Source) == "" { + return nil, invalidRequest("every document needs a source, which is what its passages are keyed by") + } + } + for _, page := range pages { + if err := urls.Check(urls.Subscription{URL: page.Url, RefreshHours: value(page.RefreshHours)}); err != nil { + return nil, invalidRequest(err.Error()) + } + } + config.Instructions = value(body.Instructions) + config.Guardrail = value(body.Guardrail) + config.UIInstructions = value(body.UiInstructions) + config.UISource = read.ui + config.Skills = named // Before anything is written, and before the knowledge is filled: a caller that asked // to be told is told instead of having its answer half applied. What the sync would // store is worked out first, because the question is what it would write over rather // than whether anything was edited. if found && value(body.CheckChanges) { - prospective := config - prospective.Instructions = value(body.Instructions) - prospective.Guardrail = value(body.Guardrail) - prospective.UIInstructions = value(body.UiInstructions) - prospective.Skills = named - refusal, conflicting, err := s.syncConflict(ctx, customerID, existing, prospective, body) + refusal, conflicting, err := s.syncConflict(ctx, customerID, existing, config, body) if err != nil { return nil, err } @@ -352,31 +550,46 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn return nil, refusal } } + namespace := "" + if knows { + namespace = name + } + config.KnowledgeNamespace = namespace + config.SyncHash = hash + // The knowledge is worked out, and the money for writing it asked for, before anything is + // written, so a dry run is refused for it as the sync would be. + var fill knowledgeFill + if len(documents) > 0 { + if fill, err = s.planKnowledge(ctx, customerID, config.Region, namespace, documents, nil); err != nil { + return nil, err + } + } + forgets := s.knowledge != nil && (namespace != "" || existing.KnowledgeNamespace == name) + changes, err := s.syncChanges(ctx, customerID, existing, body, fill, forgets) + if err != nil { + return nil, err + } + if read.dryRun { + // What a config that names no mode is stored as (store.normalizeConfig). + config.Mode = cmp.Or(config.Mode, store.AgentModeVoice) + return &syncAgentResponse{Body: SyncAgentResult{Config: agentConfigOf(config), Warnings: warnings, Changes: changes}}, nil + } // The writes are the agent's work, so a base nothing was written to is made in its region // and one kept in another refuses them. - namespace := "" if len(documents) > 0 { - if s.knowledge == nil { - return nil, errNoKnowledge - } - namespace = name - if _, _, err := s.fillKnowledge(ctx, customerID, config.Region, namespace, documents, nil); err != nil { + if err := s.writeKnowledge(ctx, customerID, config.Region, namespace, fill); err != nil { return nil, err } } - if body.KnowledgeUrls != nil && len(*body.KnowledgeUrls) > 0 { - if s.pages == nil { - return nil, errNoKnowledgeURLs - } - namespace = name + if len(pages) > 0 { // A page is read later, by work naming no region, which writes where the base is kept. if s.knowledge != nil { if err := s.knowledgeFor(ctx, customerID, config.Region).Keep(ctx, namespace); err != nil { return nil, err } } - for _, page := range *body.KnowledgeUrls { + for _, page := range pages { wanted := urls.Subscription{Namespace: namespace, URL: page.Url} wanted.Title = value(page.Title) wanted.Description = value(page.Description) @@ -388,19 +601,12 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn } // The directory is the whole of what its knowledge base holds, so a file taken out of // it is taken out of the base too, including the last one. - if s.knowledge != nil && (namespace != "" || existing.KnowledgeNamespace == name) { + if forgets { if err := s.forgetKnowledge(ctx, customerID, name, documents); err != nil { return nil, err } } - config.Instructions = value(body.Instructions) - config.Guardrail = value(body.Guardrail) - config.UIInstructions = value(body.UiInstructions) - config.Skills = named - config.KnowledgeNamespace = namespace - config.SyncHash = hash - if found { if err := s.configs.UpdateAgentConfig(ctx, &config); err != nil { return nil, storeFailure(err, errAgentNameTaken) @@ -420,7 +626,7 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn // agent has no id to hang them off until it has been stored. if len(skills) > 0 { if err := s.upsertSkills(ctx, customerID, config.ID, skills); err != nil { - return nil, invalidRequest(err.Error()) + return nil, storeFailure(err, errSkillNameTaken) } } if body.Simulations != nil { @@ -437,45 +643,51 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn ResourceType: store.AuditAgentConfig, ResourceID: config.ID, ResourceName: config.Name, Action: store.AuditSynced, Changes: synced, }) - return &syncAgentResponse{Body: SyncAgentResult{Unchanged: false, Config: agentConfigOf(config), Warnings: warnings}}, nil + return &syncAgentResponse{Body: SyncAgentResult{Unchanged: false, Config: agentConfigOf(config), Warnings: warnings, Changes: changes}}, nil +} + +// syncSetting is something wrong with one setting of a sync, by the name agent.yaml has for it. +type syncSetting struct { + setting, message string } -// syncComplaint reports what is wrong with the settings a directory declared, if -// anything. It is the same reading configComplaint does, since a directory decides the -// same things a config written by hand does. -func syncComplaint(ctx context.Context, body SyncAgentRequest) (string, bool) { +// syncComplaints reports everything wrong with the settings a directory declared, each +// with the agent.yaml setting it is about. It is the same reading configComplaint does, +// since a directory decides the same things a config written by hand does. +func syncComplaints(ctx context.Context, body SyncAgentRequest) (complaints []syncSetting) { + say := func(setting, message string) { complaints = append(complaints, syncSetting{setting, message}) } if _, ok := modeOf(body.Mode); !ok { - return fmt.Sprintf("an agent is either %s or %s", store.AgentModeVoice, store.AgentModeText), false + say("mode", fmt.Sprintf("an agent is either %s or %s", store.AgentModeVoice, store.AgentModeText)) } if complaint, ok := agentRegionComplaint(body.Region); !ok { - return complaint, false + say("region", complaint) } if complaint, ok := guardrailComplaint(ctx, body.Guardrail); !ok { - return complaint, false + say("guardrail", complaint) } if len(keytermsOf(body.Keyterms)) > stt.MaxKeyterms { - return fmt.Sprintf("a config may name at most %d keyterms", stt.MaxKeyterms), false + say("keyterms", fmt.Sprintf("a config may name at most %d keyterms", stt.MaxKeyterms)) } if _, ok := sandboxOf(body.Sandbox); !ok { - return fmt.Sprintf("there is no sandbox provider called %q", *body.Sandbox), false + say("sandbox", fmt.Sprintf("there is no sandbox provider called %q", *body.Sandbox)) } if _, ok := harnessOf(body.Harness); !ok { - return fmt.Sprintf("there is no harness called %q", *body.Harness), false + say("harness", fmt.Sprintf("there is no harness called %q", *body.Harness)) } if complaint, ok := dispatchComplaint(body.Dispatch); !ok { - return complaint, false + say("dispatch", complaint) } if body.LeftOutConnectors != nil && len(*body.LeftOutConnectors) > 0 && body.Connectors == nil { - return "left_out_connectors goes with connectors: send connectors too, an empty list if none is bound", false + say("connectors", "left_out_connectors goes with connectors: send connectors too, an empty list if none is bound") } if complaint, ok := connectorBindingsComplaint(body.Connectors); !ok { - return complaint, false + say("connectors", complaint) } if complaint, ok := chatChannelsComplaint(body.ChatChannels); !ok { - return complaint, false + say("chat_channels", complaint) } if complaint, ok := sandboxOptionsComplaint(body.SandboxOptions); !ok { - return complaint, false + say("sandbox_options", complaint) } // Simulations are checked here, before anything is written, since a config stored under // the new hash would make the next sync skip the simulations that failed. @@ -483,16 +695,16 @@ func syncComplaint(ctx context.Context, body SyncAgentRequest) (string, bool) { for _, simulation := range simulationsOf(body.Simulations) { name := strings.TrimSpace(simulation.Name) if named[name] { - return fmt.Sprintf("two simulations are called %q", name), false + say("simulations", fmt.Sprintf("two simulations are called %q", name)) } named[name] = true if simulation.Tags != nil { if err := routing.Tags(*simulation.Tags).Validate(); err != nil { - return fmt.Sprintf("simulation %q: %s", name, err), false + say("simulations", fmt.Sprintf("simulation %q: %s", name, err)) } } } - return "", true + return complaints } // replaceSimulations makes the config's simulations exactly the ones declared, finding each @@ -655,12 +867,6 @@ func documentsOf(list *[]KnowledgeDocument) []KnowledgeDocument { func (s *Server) upsertSkills(ctx context.Context, customerID, configID string, skills []SkillRequest) error { names := make([]string, 0, len(skills)) for _, skill := range skills { - // The directory names the skill and the config owns it, so the caller does not - // repeat the config id per skill and it is filled in here. - skill.ConfigId = configID - if message, ok := skillComplaint(skill); !ok { - return stack.Wrap(errors.New(message)) - } names = append(names, strings.TrimSpace(skill.Name)) } @@ -674,6 +880,7 @@ func (s *Server) upsertSkills(ctx context.Context, customerID, configID string, } for _, skill := range skills { + // The config owns the skill, so the caller does not repeat its id per skill. skill.ConfigId = configID row := storedSkill(skill, customerID) if existing, ok := known[row.Name]; ok { diff --git a/acceleration/internal/api/sync_conflict.go b/acceleration/internal/api/sync_conflict.go index 32ad40b9ad..6669905764 100644 --- a/acceleration/internal/api/sync_conflict.go +++ b/acceleration/internal/api/sync_conflict.go @@ -6,6 +6,8 @@ import ( "slices" "strings" + "github.com/danielgtaylor/huma/v2" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -15,13 +17,59 @@ import ( // // The message names what would be lost, because the client's next move is to show the // person exactly that. The code is what a client branches on. -func unsyncedChangesError(lost []string) APIError { - return APIError{ +func unsyncedChangesError(lost []SyncConflict, lastChange string) unsyncedRefusal { + said := make([]string, 0, len(lost)) + for _, conflict := range lost { + said = append(said, conflict.String()) + } + return unsyncedRefusal{conflicts: lost, lastChange: lastChange, APIError: APIError{ Type: ErrorTypeConflict, Code: codeUnsyncedChanges, Message: "this would write over changes made since the last sync: " + - strings.Join(lost, ", ") + + strings.Join(said, ", ") + ". Read GET /v1/agents/configs/{id}/changes, then sync again with base_change to keep them or to write over them", + }} +} + +// unsyncedRefusal is unsyncedChangesError as it is answered: the failure, with what the +// message names as data a client can read without reading the message. +type unsyncedRefusal struct { + APIError + conflicts []SyncConflict + lastChange string +} + +func (u unsyncedRefusal) MarshalJSON() ([]byte, error) { + detail := u.detail() + detail.Conflicts, detail.LastChange = u.conflicts, u.lastChange + return marshalFailure(detail) +} + +// SyncConflict is one thing a sync would write over that somebody changed since the last one. +type SyncConflict struct { + ResourceType AuditResourceType `json:"resource_type" doc:"What was changed, as GET /v1/agents/configs/{id}/changes names it: agent_config, skill, knowledge or knowledge_url."` + Name string `json:"name" doc:"Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url."` + Removed bool `json:"removed,omitempty" doc:"True for a knowledge document the directory no longer has, which the sync would delete."` +} + +func (*SyncConflict) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One thing a sync would write over that somebody changed since the last sync." + return schema +} + +// String is the conflict as the refusal's message names it. +func (c SyncConflict) String() string { + switch c.ResourceType { + case store.AuditSkill: + return "skill " + c.Name + case store.AuditKnowledge: + if c.Removed { + return "knowledge " + c.Name + ", which this directory no longer has" + } + return "knowledge " + c.Name + case store.AuditKnowledgeURL: + return "knowledge url " + c.Name } + return c.Name } // driftedSinceSync reports whether a sync whose hash matches the stored one has anything @@ -64,13 +112,13 @@ func (s *Server) driftedSinceSync( // and is not a conflict. func (s *Server) syncConflict( ctx context.Context, customerID string, existing, prospective store.AgentConfig, body SyncAgentRequest, -) (APIError, bool, error) { +) (unsyncedRefusal, bool, error) { changes, _, err := s.unsyncedChanges(ctx, customerID, existing.ID, value(body.BaseChange)) if err != nil { - return APIError{}, false, err + return unsyncedRefusal{}, false, err } if len(changes) == 0 { - return APIError{}, false, nil + return unsyncedRefusal{}, false, nil } writes := auditFieldsOf(auditDiff(agentConfigOf(existing), agentConfigOf(prospective))) @@ -78,7 +126,7 @@ func (s *Server) syncConflict( var documents []store.KnowledgeDocument if body.Skills != nil { if skills, err = s.store.CustomerSkills(ctx, customerID, existing.ID); err != nil { - return APIError{}, false, err + return unsyncedRefusal{}, false, err } } if body.Knowledge != nil && existing.KnowledgeNamespace != "" { @@ -86,52 +134,50 @@ func (s *Server) syncConflict( // stored, which is a question about the text. documents, err = s.store.CustomerKnowledgeDocumentsWithText(ctx, customerID, existing.KnowledgeNamespace) if err != nil { - return APIError{}, false, err + return unsyncedRefusal{}, false, err } } - var lost []string + var lost []SyncConflict for _, change := range changes { switch change.ResourceType { case store.AuditAgentConfig: for _, field := range auditFieldsOf(change.Changes) { - if slices.Contains(writes, field) && !slices.Contains(lost, field) { - lost = append(lost, field) + if slices.Contains(writes, field) { + lost = appendOnce(lost, SyncConflict{ResourceType: store.AuditAgentConfig, Name: field}) } } case store.AuditSkill: - if named := conflictingSkill(change.ResourceName, body, skills); named != "" { - lost = appendOnce(lost, named) + if conflictingSkill(change.ResourceName, body, skills) { + lost = appendOnce(lost, SyncConflict{ResourceType: store.AuditSkill, Name: change.ResourceName}) } case store.AuditKnowledge: - if named := conflictingDocument(change.ResourceName, body, documents); named != "" { - lost = appendOnce(lost, named) + if conflict, lost2 := conflictingDocument(change.ResourceName, body, documents); lost2 { + lost = appendOnce(lost, conflict) } case store.AuditKnowledgeURL: - if named := conflictingKnowledgeURL(change.ResourceName, body); named != "" { - lost = appendOnce(lost, named) + if conflictingKnowledgeURL(change.ResourceName, body) { + lost = appendOnce(lost, SyncConflict{ResourceType: store.AuditKnowledgeURL, Name: change.ResourceName}) } } } if len(lost) == 0 { - return APIError{}, false, nil + return unsyncedRefusal{}, false, nil } - return unsyncedChangesError(lost), true, nil + // Newest first, as GET /v1/agents/configs/{id}/changes lists them and names its last_change. + return unsyncedChangesError(lost, changes[0].ID), true, nil } -// conflictingSkill is what to call a skill the directory would write differently from how -// it is stored, or the empty string when the sync leaves it as it is. A skill the directory -// does not declare is safe: a sync adds and updates the skills it names and takes none away. -func conflictingSkill(name string, body SyncAgentRequest, stored []store.Skill) string { +// conflictingSkill reports whether the directory would write a skill differently from how it +// is stored. A skill the directory does not declare is safe: a sync adds and updates the +// skills it names and takes none away. +func conflictingSkill(name string, body SyncAgentRequest, stored []store.Skill) bool { declared, found := skillNamed(skillsOf(body.Skills), name) if !found { - return "" + return false } was, held := skillNamedStored(stored, name) - if held && sameSkill(was, storedSkill(declared, was.CustomerID)) { - return "" - } - return "skill " + name + return !held || !sameSkill(was, storedSkill(declared, was.CustomerID)) } // sameSkill reports whether two skills say the same thing, whatever their ids and times. @@ -140,36 +186,30 @@ func sameSkill(a, b store.Skill) bool { a.DeadlineMs == b.DeadlineMs && a.CaptureVideo == b.CaptureVideo && maps.Equal(a.Files, b.Files) } -// conflictingDocument is what to call a knowledge file the directory would write over or -// take away. The directory is the whole of the agent's knowledge base, so a file somebody +// conflictingDocument is a knowledge file the directory would write over or take away, if +// it would. The directory is the whole of the agent's knowledge base, so a file somebody // added in the dashboard and the directory does not have is one this sync would delete. -func conflictingDocument(source string, body SyncAgentRequest, stored []store.KnowledgeDocument) string { +func conflictingDocument(source string, body SyncAgentRequest, stored []store.KnowledgeDocument) (SyncConflict, bool) { + conflict := SyncConflict{ResourceType: store.AuditKnowledge, Name: source} for _, document := range documentsOf(body.Knowledge) { if strings.TrimSpace(document.Source) != source { continue } for _, was := range stored { if was.Source == source && was.Text == document.Text { - return "" + return SyncConflict{}, false } } - return "knowledge " + source + return conflict, true } - return "knowledge " + source + ", which this directory no longer has" + conflict.Removed = true + return conflict, true } -// conflictingKnowledgeURL is what to call a page the directory declares and would write its -// own settings onto. A page the directory does not declare is left alone. -func conflictingKnowledgeURL(url string, body SyncAgentRequest) string { - if body.KnowledgeUrls == nil { - return "" - } - for _, page := range *body.KnowledgeUrls { - if page.Url == url { - return "knowledge url " + url - } - } - return "" +// conflictingKnowledgeURL reports whether the directory declares a page, and so would write +// its own settings onto it. A page the directory does not declare is left alone. +func conflictingKnowledgeURL(url string, body SyncAgentRequest) bool { + return slices.ContainsFunc(value(body.KnowledgeUrls), func(page KnowledgeUrlDeclaration) bool { return page.Url == url }) } func skillNamed(declared []SkillRequest, name string) (SkillRequest, bool) { @@ -190,9 +230,9 @@ func skillNamedStored(stored []store.Skill, name string) (store.Skill, bool) { return store.Skill{}, false } -func appendOnce(list []string, value string) []string { - if slices.Contains(list, value) { +func appendOnce(list []SyncConflict, conflict SyncConflict) []SyncConflict { + if slices.Contains(list, conflict) { return list } - return append(list, value) + return append(list, conflict) } diff --git a/acceleration/internal/knowledge/urls/urls.go b/acceleration/internal/knowledge/urls/urls.go index 92c2556092..4c3a168695 100644 --- a/acceleration/internal/knowledge/urls/urls.go +++ b/acceleration/internal/knowledge/urls/urls.go @@ -215,13 +215,10 @@ func (s *Service) Add(ctx context.Context, customerID string, wanted Subscriptio if namespace == "" { return store.KnowledgeURL{}, stack.Wrap(errors.New("urls: a namespace is required, knowledge is never shared")) } - address, err := clean(wanted.URL) - if err != nil { + if err := Check(wanted); err != nil { return store.KnowledgeURL{}, err } - if wanted.RefreshHours < 0 { - return store.KnowledgeURL{}, stack.Wrap(fmt.Errorf("urls: refresh_hours cannot be negative, got %d", wanted.RefreshHours)) - } + address, _ := clean(wanted.URL) page, subscribed, err := s.store.SubscribedKnowledgeURL(ctx, customerID, namespace, address) if err != nil { @@ -514,6 +511,17 @@ func (s *Service) kept(ctx context.Context, page *store.KnowledgeURL) error { return err } +// Check reports why a subscription would be refused, without subscribing to anything. +func Check(wanted Subscription) error { + if _, err := clean(wanted.URL); err != nil { + return err + } + if wanted.RefreshHours < 0 { + return stack.Wrap(fmt.Errorf("urls: refresh_hours cannot be negative, got %d", wanted.RefreshHours)) + } + return nil +} + // clean reports the url as it will be stored, or why it is not one. // // It is strict about the scheme because the rest of this hands the address to a crawler diff --git a/acceleration/internal/store/agents.go b/acceleration/internal/store/agents.go index 65d8604e10..b17b056878 100644 --- a/acceleration/internal/store/agents.go +++ b/acceleration/internal/store/agents.go @@ -73,7 +73,7 @@ func (s *Store) CreateAgentConfig(ctx context.Context, config *AgentConfig) erro // dropped on every update after, which reads as a setting that will not save. var configColumns = []string{ "name", "role", "mode", "region", "stt", "tts", "sts", "voice", "llm", "llm_fallbacks", "agents", "subagent", - "video_source", "video_max_frames", "search", "image", "instructions", "greeting", "greeting_mode", "guardrail", "review_instructions", "ui_instructions", + "video_source", "video_max_frames", "search", "image", "instructions", "greeting", "greeting_mode", "guardrail", "review_instructions", "ui_instructions", "ui_source", "skills", "connectors", "left_out_connectors", "channels", "chat_channels", "scheduling", "calls", "keyterms", "visible_tools", "knowledge_namespace", "sandbox", "sandbox_options", "harness", "tags", "dispatch_incoming_call", "dispatch_text", "episode_cards", "episode_cards_record", "tool_groups", "resume_history", "floor_control", "sync_hash", "updated_at", } diff --git a/acceleration/internal/store/connections.go b/acceleration/internal/store/connections.go index 79f522185c..7488bf2b70 100644 --- a/acceleration/internal/store/connections.go +++ b/acceleration/internal/store/connections.go @@ -429,6 +429,24 @@ func (s *Store) SetConnectorConnectionTools(ctx context.Context, customerID, id return nil } +// AppConnectionsNamed are the app's own live connections to a connector that have token as +// their id or as their label, which is how agent.yaml names one. +func (s *Store) AppConnectionsNamed(ctx context.Context, customerID, connectorID, token string) ([]ConnectorConnection, error) { + var connections []ConnectorConnection + err := s.db.NewSelect().Model(&connections). + Where("customer_id = ?", customerID). + Where("owner_type = ?", OwnerApp). + Where("connector_id = ?", connectorID). + Where("deleted_at IS NULL"). + Where("(id = ? OR label = ?)", token, token). + Order("created_at DESC", "id DESC"). + Scan(ctx) + if err != nil { + return nil, stack.Wrap(fmt.Errorf("store: connections named %q: %w", token, err)) + } + return connections, nil +} + // ConnectorConnectionsByOwner lists one owner's live connections, or with filter.EveryUser // every user's, newest first, one more than ConnectionLimit(filter.Limit). func (s *Store) ConnectorConnectionsByOwner(ctx context.Context, customerID string, filter ConnectionFilter) ([]ConnectorConnection, error) { diff --git a/acceleration/internal/store/models.go b/acceleration/internal/store/models.go index cd08f69012..4630235f77 100644 --- a/acceleration/internal/store/models.go +++ b/acceleration/internal/store/models.go @@ -596,6 +596,10 @@ type AgentConfig struct { // UIInstructions teach the model to answer with UI, such as agent.yaml's ui: compiled by // the SDK. Apart from Instructions so a session can leave them out (AgentSession.NoUI). UIInstructions string `bun:"ui_instructions,notnull"` + // UISource is what UIInstructions were compiled from when a directory's files were synced: + // agent.yaml's ui key and the two files it named, which an export writes back. Nil for a + // config that has no UI, or whose UI a client compiled itself. + UISource *UISource `bun:"ui_source,type:jsonb"` // Skills names entries in the skill registry rather than carrying their instructions, // so editing a skill changes every config that uses it. Skills []string `bun:"skills,type:jsonb"` @@ -674,6 +678,18 @@ type AgentConfig struct { DeletedAt *time.Time `bun:"deleted_at"` } +// UISource is agent.yaml's ui key and the files it named, as a directory's sync last had them. +type UISource struct { + Format string `json:"format,omitempty"` + Keep []string `json:"keep,omitempty"` + PatchMode bool `json:"patch_mode,omitempty"` + VoiceUI bool `json:"voice_ui,omitempty"` + Rules []string `json:"rules,omitempty"` + // Components and Blueprints are ui/components.json and ui/blueprints.yaml, whole. + Components string `json:"components,omitempty"` + Blueprints string `json:"blueprints,omitempty"` +} + // WritesCards is whether the config's calls, app chats and channel threads write episode // cards and their summaries: on (EpisodeCards) or record (EpisodeCardsRecord). func (c AgentConfig) WritesCards() bool { diff --git a/acceleration/internal/store/simulations.go b/acceleration/internal/store/simulations.go index 6a1d4ad55e..b9b7382b96 100644 --- a/acceleration/internal/store/simulations.go +++ b/acceleration/internal/store/simulations.go @@ -13,10 +13,10 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) -// defaultMaxTurns is how long a conversation a simulation that did not say runs for. A +// DefaultSimulationTurns is how long a conversation a simulation that did not say runs for. A // scenario with three things to ask needs more turns than three, because the agent asks // questions back. -const defaultMaxTurns = 12 +const DefaultSimulationTurns = 12 // maxTurns and maxVariations bound what a customer may ask for, since every turn is a // model call and every variation is a whole conversation. @@ -440,7 +440,7 @@ func normalizeSimulation(simulation *Simulation) { simulation.Variations = 1 } if simulation.MaxTurns <= 0 { - simulation.MaxTurns = defaultMaxTurns + simulation.MaxTurns = DefaultSimulationTurns } if simulation.Tags == nil { simulation.Tags = map[string]string{} diff --git a/acceleration/migrations/20270105090000_agent_config_ui_source.sql b/acceleration/migrations/20270105090000_agent_config_ui_source.sql new file mode 100644 index 0000000000..138012e629 --- /dev/null +++ b/acceleration/migrations/20270105090000_agent_config_ui_source.sql @@ -0,0 +1,25 @@ +-- +goose NO TRANSACTION +-- +goose Up + +-- agent_configs.ui_source is agent.yaml's ui key and the two files it named, as the directory +-- last synced from its files had them (store.AgentConfig.UISource): what ui_instructions was +-- compiled from, kept so the directory can be written back. Null, as on every config synced +-- before it, is a config with no UI or one whose UI a client compiled itself. The default +-- rewrites no row; the lock waits at most 5 s behind a running query, past which the migration +-- fails and the router's next start tries again. +-- +goose StatementBegin +DO $$ +BEGIN + SET LOCAL lock_timeout = '5s'; + ALTER TABLE agent_configs ADD COLUMN IF NOT EXISTS ui_source JSONB; +END $$; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + SET LOCAL lock_timeout = '5s'; + ALTER TABLE agent_configs DROP COLUMN IF EXISTS ui_source; +END $$; +-- +goose StatementEnd From d262040179ef3fd3d21cc2f185d0b49f78c237ca Mon Sep 17 00:00:00 2001 From: thesyncim Date: Fri, 20 Nov 2026 17:39:58 +0100 Subject: [PATCH 3/6] feat(sdk-go): sync an agent directory as its files, which the router reads Sync reads the files the format names when it syncs, and no other file of the folder, and sends them to POST /v1/agents/sync/files with what the code set beside the directory, which still wins: the instructions, the guardrail, the harness's subagent, sandbox and skills, and the cost tracking labels. The router decides what agent.yaml means and which connections it names. Load still parses the directory for the program holding it. A link out of the directory is refused, what is not a regular file of text is left behind, and a directory over what a sync sends is refused by name. .agent_sync keeps a hash of what was sent and the sync_hash the router stored it under, in the format the JavaScript SDK writes, and a sync is skipped only while the stored config still has that hash and left no connector out. --- .claude/skills/sdk-go/SKILL.md | 28 +- sdks/go/README.md | 15 +- sdks/go/acceleration/generated.go | 4665 +++++++++++++++++------------ sdks/go/agents/agent.go | 6 +- sdks/go/agents/agent_test.go | 1650 +--------- sdks/go/agents/config.go | 586 +--- sdks/go/agents/folder.go | 137 +- sdks/go/agents/folder_test.go | 128 + 8 files changed, 3322 insertions(+), 3893 deletions(-) diff --git a/.claude/skills/sdk-go/SKILL.md b/.claude/skills/sdk-go/SKILL.md index 3e35d54048..b5056e4119 100644 --- a/.claude/skills/sdk-go/SKILL.md +++ b/.claude/skills/sdk-go/SKILL.md @@ -58,8 +58,32 @@ Known gaps, generated only (docs on getstream.io call some of them raw today): s their runs, voices, knowledge documents and URLs beyond ingest and add, scheduled tasks, campaigns, channels, connectors, a connection's credentials and tools, SIP trunks, 10DLC and opt-outs, phone transfer, digits and release, account, credits, spend limits, usage events, teams, prices, -stats, policies, provider keys, runs, OCR and classify. Folder sync does not read -`resume_history:` from agent.yaml yet, so one that names it is refused. +stats, policies, provider keys, runs, OCR and classify. + +## Folder sync + +`Agent.Sync` sends an agent directory's files to `POST /v1/agents/sync/files`, and the router +(`acceleration/internal/agentdir`) reads, validates and stores them: it is what decides what +agent.yaml means, finds the connections and compiles `ui:`. + +- `agents.Load` still parses the directory, as it did, to fill `Folder.Settings`, `Skills`, + `Knowledge` and the rest for the program holding it, and refuses a file it cannot read. It + decides nothing about what is stored. Removing that parser is AI-3441; until then a key added + to agent.yaml is added to the router first, and here only so `Load` does not refuse it. +- `Folder.files` reads what is sent, at sync time: the files the format names and no others + (`agent.yaml`, `instructions.md`, `guardrail.md`, `skills/`, `knowledge/`, `ui/`, the YAML + files of `simulations/`, and the two files `ui:` may name elsewhere), so a directory kept + beside a program's source sends none of it. It skips what the router skips, anything that is + not a regular file of text, and refuses a link out of the directory and a directory over + `maxSyncBytes`. +- What `Options` sets beside a `Dir` goes in the same request and wins over the files: + instructions, guardrail, the harness's name, subagent, sandbox and skills written in code, + and the cost tracking labels as tags. +- `.agent_sync` holds `hash`, the `sentHash` of the request, and `sync_hash`, what the router + stored it under: one format and one fingerprint with the JavaScript SDK. A sync is skipped + only while both still hold: the request is the same, and the stored config has that + `sync_hash` and left no connector out. +- The router does not read `resume_history:` from agent.yaml yet, so one that names it is refused. ## Errors, retries and idempotency diff --git a/sdks/go/README.md b/sdks/go/README.md index 729b63b7a2..43e8d2b768 100644 --- a/sdks/go/README.md +++ b/sdks/go/README.md @@ -608,14 +608,15 @@ agent, _ := agents.New(agents.Options{Dir: "agents/jean", LLM: llm}) agent.Sync(ctx) ``` -`Sync` sends the whole directory in one request: the skills, the files and pages for a -knowledge base named after the agent, the simulations, and what `agent.yaml` declares. A key -`agent.yaml` or a simulation file does not know is refused. The simulations in `simulations/` +`Sync` sends the directory's files in one request, as they are and no other file of the folder, and the router reads them: the +skills, the files and pages for a knowledge base named after the agent, the simulations, the UI +files and what `agent.yaml` declares. The router decides what a file means and refuses what it +cannot read, with the file, line and column of every problem. `agents.New` reads the directory +too, for your program (`agent.Folder()`), and refuses a key it does not know. The simulations in `simulations/` are the whole of the agent's: one taken out is deleted on the next sync, and a directory -without `simulations/` leaves the stored ones alone. The request carries a hash of the -directory, the same one the Python SDK takes for a directory without simulations, and -`.agent_sync` records it, so running `Sync` again on an unchanged -directory only reads the config back. What is written in code wins over what the directory +without `simulations/` leaves the stored ones alone. `.agent_sync` records what was sent and the +hash the router stored it under, so running `Sync` again on an unchanged directory, whose +stored config nobody has changed since, only reads the config back. What is written in code wins over what the directory says, so a directory is a starting point rather than an override. `region: eu` (or `us`) in `agent.yaml` is where the agent's work is done: every model it runs, diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 8416d02a59..9f44f7a533 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -282,22 +282,22 @@ func (e AgentRole) Valid() bool { // Defines values for AuditAction. const ( - Created AuditAction = "created" - Deleted AuditAction = "deleted" - Synced AuditAction = "synced" - Updated AuditAction = "updated" + AuditActionCreated AuditAction = "created" + AuditActionDeleted AuditAction = "deleted" + AuditActionSynced AuditAction = "synced" + AuditActionUpdated AuditAction = "updated" ) // Valid indicates whether the value is a known member of the AuditAction enum. func (e AuditAction) Valid() bool { switch e { - case Created: + case AuditActionCreated: return true - case Deleted: + case AuditActionDeleted: return true - case Synced: + case AuditActionSynced: return true - case Updated: + case AuditActionUpdated: return true default: return false @@ -3031,6 +3031,51 @@ func (e StsOptionsTurnDetection) Valid() bool { } } +// Defines values for SyncChangeAction. +const ( + SyncChangeActionCreated SyncChangeAction = "created" + SyncChangeActionDeleted SyncChangeAction = "deleted" + SyncChangeActionUpdated SyncChangeAction = "updated" +) + +// Valid indicates whether the value is a known member of the SyncChangeAction enum. +func (e SyncChangeAction) Valid() bool { + switch e { + case SyncChangeActionCreated: + return true + case SyncChangeActionDeleted: + return true + case SyncChangeActionUpdated: + return true + default: + return false + } +} + +// Defines values for SyncChangeResourceType. +const ( + SyncChangeResourceTypeKnowledge SyncChangeResourceType = "knowledge" + SyncChangeResourceTypeKnowledgeUrl SyncChangeResourceType = "knowledge_url" + SyncChangeResourceTypeSimulation SyncChangeResourceType = "simulation" + SyncChangeResourceTypeSkill SyncChangeResourceType = "skill" +) + +// Valid indicates whether the value is a known member of the SyncChangeResourceType enum. +func (e SyncChangeResourceType) Valid() bool { + switch e { + case SyncChangeResourceTypeKnowledge: + return true + case SyncChangeResourceTypeKnowledgeUrl: + return true + case SyncChangeResourceTypeSimulation: + return true + case SyncChangeResourceTypeSkill: + return true + default: + return false + } +} + // Defines values for TextContentPartType. const ( TextContentPartTypeText TextContentPartType = "text" @@ -4143,6 +4188,18 @@ type AgentConnectorSelection struct { // AgentConnectorSelectionType fixed is the app's own connection named by connection_id, the same for every session. session is the connection the session's verified end user picks when the session is created, which has to be their own. When they pick none, it is their connection to the connector if exactly one of theirs is connected. For a session the router opens itself, the end user is nobody for an MCP event, which it opens as the app, or for a WhatsApp or SMS message the sender (phone:+E164) or the user the number is linked to. Such a session also uses that user's only connected connection when none is named. type AgentConnectorSelectionType string +// AgentDirectory An agent config as the directory it is synced from: agent.yaml, instructions.md, guardrail.md, its skills, its knowledge, its simulations and its UI files. +type AgentDirectory struct { + // Files The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they store the agent as it is. + Files []DirectoryFile `json:"files"` + + // Name What the agent is called, as agent.yaml names it. + Name string `json:"name"` + + // NotExported What this agent holds that its directory cannot say and a sync of these files would change, each in a sentence: a connector binding's events, policy or timeout, a connector that grants no tools, a knowledge document that is not a text file, UI instructions no directory's files were compiled into. Empty when a sync of these files leaves the agent as it is. + NotExported []string `json:"not_exported"` +} + // AgentDispatch What the agent leaves to the customer's own server, which waits on /v1/dispatch. Omitted settings are disabled. type AgentDispatch struct { // IncomingCall Whether this kind of work is left to the customer's own dispatch worker. @@ -6630,6 +6687,36 @@ type DetectionResult struct { // DetectionStatus Whether the image was looked at. A failed detection says why in error_code and error. type DetectionStatus string +// DirectoryFile One file of an agent directory, as a sync takes it and an export writes it. +type DirectoryFile struct { + // Content The file, whole, as text. + Content string `json:"content"` + + // Path Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, skills/.md or skills//SKILL.md with the files beside it, knowledge/, knowledge/urls.yaml, simulations/.yaml, ui/components.json, ui/blueprints.yaml. + // + // Example: skills/refunds/SKILL.md + Path string `json:"path"` +} + +// DirectoryProblem One thing wrong with an agent directory, at its place in a file, so an editor can point at it. +type DirectoryProblem struct { + // Column The column, counted from 1. Left out with line. + // + // Example: 3 + Column *int64 `json:"column,omitempty"` + + // File The file's path in the directory. + // + // Example: agent.yaml + File string `json:"file"` + + // Line The line, counted from 1. Left out when the problem is the file as a whole. + // + // Example: 12 + Line *int64 `json:"line,omitempty"` + Message string `json:"message"` +} + // DispatchSetting Whether this kind of work is left to the customer's own dispatch worker. type DispatchSetting string @@ -6701,18 +6788,30 @@ type EqualsOrIn1 struct { // ErrorDetail defines model for ErrorDetail. type ErrorDetail struct { - // Code What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. + // Code What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. Code string `json:"code"` + // Conflicts What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. + Conflicts *[]SyncConflict `json:"conflicts,omitempty"` + // DocUrl Where the code is explained. DocUrl string `json:"doc_url"` + // LastChange The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen. + LastChange *string `json:"last_change,omitempty"` + // Limit Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. Limit *string `json:"limit,omitempty"` // Message What went wrong, for a person to read. Its wording may change; branch on code. Message string `json:"message"` + // Problems What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. + Problems *[]DirectoryProblem `json:"problems,omitempty"` + + // ProblemsOmitted How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed. + ProblemsOmitted *int64 `json:"problems_omitted,omitempty"` + // Type The kind of failure, which decides the status it is answered with: invalid_request 400, authentication 401, payment_required 402, permission 403, not_found 404, method_not_allowed 405, not_acceptable 406, conflict 409, gone 410, payload_too_large 413, unsupported_media_type 415, rate_limited 429, internal 500, unavailable 503, timeout 504. Type ErrorType `json:"type"` } @@ -10286,6 +10385,70 @@ type SuspendTelephonyRequest struct { SuspendedBy string `json:"suspended_by"` } +// SyncAgentFilesRequest An agent directory as its files, which the router reads, so every client's directory means the same thing. The fields from instructions down are what a program sets in code beside the directory: each wins over what the files say, and is part of the hash. +// +// A request sends at most 1024 files, and the directory among them holds at most 1048576 bytes a file and 8388608 bytes in all. +// +// The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the part. The parts are, for every file of the directory in path order by byte, its path and its content; then, for each field from instructions down that is sent, its name and its value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags. for each tag in key order; skills with the number of skills in decimal, then for each skill in name order skills..description, .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files. for each file in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of the router's UI compiler, so a router that compiles ui differently syncs the directory again. A file sent that is no part of the directory is no part of the hash, so every client's sync of one folder has one hash. While a connector is left out sync_hash is another hash, so the sync that finds its connection is not taken for the one that left it out. +// +// What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. calls is always written whole: a call tool the file does not name goes back to its default. keyterms and tags are left as stored when the file has none, an empty list or mapping included, so a file cannot clear them. instructions, guardrail, the skills the config names, its UI instructions and its knowledge base are the directory's: a file taken out is taken out of the agent. simulations are left alone without a simulations file, and are exactly what the files declare with one. +type SyncAgentFilesRequest struct { + // BaseChange As base_change of POST /v1/agents/sync: the newest change the caller has already seen. + BaseChange *string `json:"base_change,omitempty"` + + // CheckChanges As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over a setting somebody changed since the last one. + CheckChanges *bool `json:"check_changes,omitempty"` + + // DryRun Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes for what it would write over, the money for writing its knowledge included. What only the writes can tell is not told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. unchanged is true when the hash matches and a sync would do nothing. + DryRun *bool `json:"dry_run,omitempty"` + + // Files The files of the agent's folder, as they are on disk. A client sends what it finds and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no part of the limits or the hash. + Files []DirectoryFile `json:"files"` + + // Greeting What the agent says as it joins, before anyone speaks. + Greeting *Greeting `json:"greeting,omitempty"` + + // Guardrail The guardrail a program gives in code, in place of guardrail.md. + Guardrail *string `json:"guardrail,omitempty"` + + // Harness Which harness the agent's sessions run: what hands work to the subagent, loads skills, compacts the conversation and starts the sandbox. Set on the agent, never on a session. Omit it for the default, the only one there is. + Harness *Harness `json:"harness,omitempty"` + + // Instructions The system prompt a program gives in code, in place of instructions.md. + Instructions *string `json:"instructions,omitempty"` + + // Llm In place of agent.yaml's llm. + Llm *string `json:"llm,omitempty"` + + // Name What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the agent. + Name *string `json:"name,omitempty"` + + // Sandbox Where the agent may run code it writes. A text agent runs it itself; a voice agent hands it to the subagent, since running code takes seconds a call has none of. Omit it and the agent works everything out in its head. + Sandbox *Sandbox `json:"sandbox,omitempty"` + + // Skills The skills a program writes in code, in place of every skill under skills/. An empty list names none. + Skills *[]SkillRequest `json:"skills,omitempty"` + + // Sts In place of agent.yaml's sts. + Sts *string `json:"sts,omitempty"` + + // Stt In place of agent.yaml's stt. + Stt *string `json:"stt,omitempty"` + + // Subagent In place of agent.yaml's subagent. + Subagent *string `json:"subagent,omitempty"` + + // Tags Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes. + Tags *map[string]string `json:"tags,omitempty"` + + // Tts In place of agent.yaml's tts. + Tts *string `json:"tts,omitempty"` + Video *SessionVideo `json:"video,omitempty"` + + // Voice In place of agent.yaml's voice. + Voice *string `json:"voice,omitempty"` +} + // SyncAgentRequest An agent directory as it is on disk. Everything after the simulations is what the directory's declaration decides rather than what it holds, and a setting left out leaves whatever is stored, so a model chosen in the dashboard survives a sync that says nothing about it. type SyncAgentRequest struct { // Agents agent.yaml's agents: the app's other text agents this one may hand work to, each as a tool, by name. Sent, they replace the stored list whole, an empty list removing it; left out, the stored list stays. An agent named must already exist, so a directory is synced after the agents it names. @@ -10416,7 +10579,9 @@ type SyncAgentRequest_Plugins_Item struct { // SyncAgentResult defines model for SyncAgentResult. type SyncAgentResult struct { - Config AgentConfig `json:"config"` + // Changes What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it leaves as it is is not listed, and nothing is for a sync that found the hash unchanged. + Changes *[]SyncChange `json:"changes,omitempty"` + Config AgentConfig `json:"config"` // Unchanged True when the hash matched and nothing was written. Unchanged bool `json:"unchanged"` @@ -10425,6 +10590,35 @@ type SyncAgentResult struct { Warnings *[]string `json:"warnings,omitempty"` } +// SyncChange One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes. +type SyncChange struct { + Action SyncChangeAction `json:"action"` + + // Name Which one: a skill's name, a knowledge document's source, a knowledge url's url, a simulation's name. + Name string `json:"name"` + + // ResourceType What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. + ResourceType SyncChangeResourceType `json:"resource_type"` +} + +// SyncChangeAction defines model for SyncChange.Action. +type SyncChangeAction string + +// SyncChangeResourceType What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. +type SyncChangeResourceType string + +// SyncConflict One thing a sync would write over that somebody changed since the last sync. +type SyncConflict struct { + // Name Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url. + Name string `json:"name"` + + // Removed True for a knowledge document the directory no longer has, which the sync would delete. + Removed *bool `json:"removed,omitempty"` + + // ResourceType What the change was made to. All of them are configuration: what an agent does while it runs is traffic, and is read from the sessions and the logs instead. price_list is the deployment's own, changed through the management API, and is never listed for an app. end_user is one of the app's end users whose id was forgotten in the usage records, named by the id that replaced it. limit is one of the organization's spend limits, named by its id, a reset of one, named reset:, or a grant, named grant:; a change staff made through the management API is kept under the organization's id. provider_key is a key the app keeps for its own account at a vendor, named /; its changes show the key's last four characters at most, never the key. + ResourceType AuditResourceType `json:"resource_type"` +} + // TagKeySummary defines model for TagKeySummary. type TagKeySummary struct { CostMicrosTotal int64 `json:"cost_micros_total"` @@ -12398,6 +12592,9 @@ type UpdateSkillJSONRequestBody = SkillRequest // SyncAgentJSONRequestBody defines body for SyncAgent for application/json ContentType. type SyncAgentJSONRequestBody = SyncAgentRequest +// SyncAgentFilesJSONRequestBody defines body for SyncAgentFiles for application/json ContentType. +type SyncAgentFilesJSONRequestBody = SyncAgentFilesRequest + // UpdateUserJSONRequestBody defines body for UpdateUser for application/json ContentType. type UpdateUserJSONRequestBody = AgentUserRequest @@ -13637,6 +13834,17 @@ type ClientInterface interface { // Corresponds with GET /v1/agents/configs/{id}/changes (the `GetAgentChanges` operationId). GetAgentChanges(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetAgentDirectory An agent config as the files of its directory + // + // The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ with the pages it is kept filled from in knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call tool at its default, a connector's tools when it grants every one), and a connector that says only its name written as the name alone. + // + // Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written with its connection's id, whatever label agent.yaml first named it by, and a skill the config no longer names is left out. + // + // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + // + // Corresponds with GET /v1/agents/configs/{id}/directory (the `GetAgentDirectory` operationId). + GetAgentDirectory(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListConnections List connections // // Connections, newest first: the app's own, those of the user the backend acts for, or every user's when it acts for none. @@ -15154,6 +15362,36 @@ type ClientInterface interface { // Corresponds with POST /v1/agents/sync (the `SyncAgent` operationId). SyncAgent(ctx context.Context, body SyncAgentJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // SyncAgentFilesWithBody Store an agent directory sent as its files + // + // POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. + // + // A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. + // + // `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. + // + // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). + SyncAgentFilesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SyncAgentFiles Store an agent directory sent as its files + // + // POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. + // + // A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. + // + // `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. + // + // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). + SyncAgentFiles(ctx context.Context, body SyncAgentFilesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetUser Get a user's phone link // // The number linked to a user of the app, and how much of what it said before the link the user reads. A user with no number linked has a null phone. @@ -17514,6 +17752,27 @@ func (c *Client) GetAgentChanges(ctx context.Context, id string, reqEditors ...R return c.Client.Do(req) } +// GetAgentDirectory An agent config as the files of its directory +// +// The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ with the pages it is kept filled from in knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call tool at its default, a connector's tools when it grants every one), and a connector that says only its name written as the name alone. +// +// Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written with its connection's id, whatever label agent.yaml first named it by, and a skill the config no longer names is left out. +// +// Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. +// +// Corresponds with GET /v1/agents/configs/{id}/directory (the `GetAgentDirectory` operationId). +func (c *Client) GetAgentDirectory(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetAgentDirectoryRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // ListConnections List connections // // Connections, newest first: the app's own, those of the user the backend acts for, or every user's when it acts for none. @@ -20561,6 +20820,56 @@ func (c *Client) SyncAgent(ctx context.Context, body SyncAgentJSONRequestBody, r return c.Client.Do(req) } +// SyncAgentFilesWithBody Store an agent directory sent as its files +// +// POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. +// +// A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. +// +// `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. +// +// Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). +func (c *Client) SyncAgentFilesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSyncAgentFilesRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// SyncAgentFiles Store an agent directory sent as its files +// +// POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. +// +// A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. +// +// `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. +// +// Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). +func (c *Client) SyncAgentFiles(ctx context.Context, body SyncAgentFilesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSyncAgentFilesRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // GetUser Get a user's phone link // // The number linked to a user of the app, and how much of what it said before the link the user reads. A user with no number linked has a null phone. @@ -25233,6 +25542,40 @@ func NewGetAgentChangesRequest(server string, id string) (*http.Request, error) return req, nil } +// NewGetAgentDirectoryRequest constructs an http.Request for the GetAgentDirectory method +func NewGetAgentDirectoryRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/agents/configs/%s/directory", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewListConnectionsRequest constructs an http.Request for the ListConnections method func NewListConnectionsRequest(server string, params *ListConnectionsParams) (*http.Request, error) { var err error @@ -30842,6 +31185,46 @@ func NewSyncAgentRequestWithBody(server string, contentType string, body io.Read return req, nil } +// NewSyncAgentFilesRequest calls the generic SyncAgentFiles builder with application/json body +func NewSyncAgentFilesRequest(server string, body SyncAgentFilesJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewSyncAgentFilesRequestWithBody(server, "application/json", bodyReader) +} + +// NewSyncAgentFilesRequestWithBody constructs an http.Request for the SyncAgentFiles method, with any body, and a specified content type +func NewSyncAgentFilesRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/agents/sync/files") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + // NewGetUserRequest constructs an http.Request for the GetUser method func NewGetUserRequest(server string, userId string) (*http.Request, error) { var err error @@ -36705,6 +37088,19 @@ type ClientWithResponsesInterface interface { // Corresponds with GET /v1/agents/configs/{id}/changes (the `GetAgentChanges` operationId). GetAgentChangesWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetAgentChangesResponse, error) + // GetAgentDirectoryWithResponse An agent config as the files of its directory + // + // The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ with the pages it is kept filled from in knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call tool at its default, a connector's tools when it grants every one), and a connector that says only its name written as the name alone. + // + // Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written with its connection's id, whatever label agent.yaml first named it by, and a skill the config no longer names is left out. + // + // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with GET /v1/agents/configs/{id}/directory (the `GetAgentDirectory` operationId). + GetAgentDirectoryWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetAgentDirectoryResponse, error) + // ListConnectionsWithResponse List connections // // Connections, newest first: the app's own, those of the user the backend acts for, or every user's when it acts for none. @@ -38372,6 +38768,36 @@ type ClientWithResponsesInterface interface { // Corresponds with POST /v1/agents/sync (the `SyncAgent` operationId). SyncAgentWithResponse(ctx context.Context, body SyncAgentJSONRequestBody, reqEditors ...RequestEditorFn) (*SyncAgentResponse, error) + // SyncAgentFilesWithBodyWithResponse Store an agent directory sent as its files + // + // POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. + // + // A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. + // + // `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. + // + // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + // + // Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). + SyncAgentFilesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SyncAgentFilesResponse, error) + + // SyncAgentFilesWithResponse Store an agent directory sent as its files + // + // POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. + // + // A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. + // + // `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. + // + // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + // + // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). + SyncAgentFilesWithResponse(ctx context.Context, body SyncAgentFilesJSONRequestBody, reqEditors ...RequestEditorFn) (*SyncAgentFilesResponse, error) + // GetUserWithResponse Get a user's phone link // // The number linked to a user of the app, and how much of what it said before the link the user reads. A user with no number linked has a null phone. @@ -44146,6 +44572,114 @@ func (r GetAgentChangesResponse) ContentType() string { return "" } +// GetAgentDirectoryResponse200Headers the declared response headers of an HTTP 200 response for GetAgentDirectory +type GetAgentDirectoryResponse200Headers struct { + XStreamBalanceMicros *int64 + XStreamBalanceWarning *string + XStreamCostEstimated *string + XStreamCostMicros *int64 +} + +// GetAgentDirectoryResponse402Headers the declared response headers of an HTTP 402 response for GetAgentDirectory +type GetAgentDirectoryResponse402Headers struct { + XStreamBalanceMicros *int64 + XStreamBalanceWarning *string +} + +type GetAgentDirectoryResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *AgentDirectory + // JSON400 the response for an HTTP 400 `application/json` response + JSON400 *BadRequest + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Unauthorized + // JSON402 the response for an HTTP 402 `application/json` response + JSON402 *PaymentRequired + // JSON403 the response for an HTTP 403 `application/json` response + JSON403 *Forbidden + // JSON404 the response for an HTTP 404 `application/json` response + JSON404 *NotFound + // JSON500 the response for an HTTP 500 `application/json` response + JSON500 *InternalError + // JSON503 the response for an HTTP 503 `application/json` response + JSON503 *Unavailable + // Headers200 the parsed response headers for an HTTP 200 response + Headers200 *GetAgentDirectoryResponse200Headers + // Headers402 the parsed response headers for an HTTP 402 response + Headers402 *GetAgentDirectoryResponse402Headers +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON200() *AgentDirectory { + return r.JSON200 +} + +// GetJSON400 returns the response for an HTTP 400 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON400() *BadRequest { + return r.JSON400 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON401() *Unauthorized { + return r.JSON401 +} + +// GetJSON402 returns the response for an HTTP 402 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON402() *PaymentRequired { + return r.JSON402 +} + +// GetJSON403 returns the response for an HTTP 403 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON403() *Forbidden { + return r.JSON403 +} + +// GetJSON404 returns the response for an HTTP 404 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON404() *NotFound { + return r.JSON404 +} + +// GetJSON500 returns the response for an HTTP 500 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON500() *InternalError { + return r.JSON500 +} + +// GetJSON503 returns the response for an HTTP 503 `application/json` response +func (r GetAgentDirectoryResponse) GetJSON503() *Unavailable { + return r.JSON503 +} + +// GetBody returns the raw response body bytes +func (r GetAgentDirectoryResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r GetAgentDirectoryResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetAgentDirectoryResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetAgentDirectoryResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + // ListConnectionsResponse200Headers the declared response headers of an HTTP 200 response for ListConnections type ListConnectionsResponse200Headers struct { XStreamBalanceMicros *int64 @@ -56395,6 +56929,121 @@ func (r SyncAgentResponse) ContentType() string { return "" } +// SyncAgentFilesResponse200Headers the declared response headers of an HTTP 200 response for SyncAgentFiles +type SyncAgentFilesResponse200Headers struct { + XStreamBalanceMicros *int64 + XStreamBalanceWarning *string + XStreamCostEstimated *string + XStreamCostMicros *int64 +} + +// SyncAgentFilesResponse402Headers the declared response headers of an HTTP 402 response for SyncAgentFiles +type SyncAgentFilesResponse402Headers struct { + XStreamBalanceMicros *int64 + XStreamBalanceWarning *string +} + +type SyncAgentFilesResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *SyncAgentResult + // JSON400 the response for an HTTP 400 `application/json` response + JSON400 *BadRequest + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Unauthorized + // JSON402 the response for an HTTP 402 `application/json` response + JSON402 *PaymentRequired + // JSON403 the response for an HTTP 403 `application/json` response + JSON403 *Forbidden + // JSON409 the response for an HTTP 409 `application/json` response + JSON409 *ErrorResponse + // JSON413 the response for an HTTP 413 `application/json` response + JSON413 *ErrorResponse + // JSON500 the response for an HTTP 500 `application/json` response + JSON500 *InternalError + // JSON503 the response for an HTTP 503 `application/json` response + JSON503 *Unavailable + // Headers200 the parsed response headers for an HTTP 200 response + Headers200 *SyncAgentFilesResponse200Headers + // Headers402 the parsed response headers for an HTTP 402 response + Headers402 *SyncAgentFilesResponse402Headers +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r SyncAgentFilesResponse) GetJSON200() *SyncAgentResult { + return r.JSON200 +} + +// GetJSON400 returns the response for an HTTP 400 `application/json` response +func (r SyncAgentFilesResponse) GetJSON400() *BadRequest { + return r.JSON400 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r SyncAgentFilesResponse) GetJSON401() *Unauthorized { + return r.JSON401 +} + +// GetJSON402 returns the response for an HTTP 402 `application/json` response +func (r SyncAgentFilesResponse) GetJSON402() *PaymentRequired { + return r.JSON402 +} + +// GetJSON403 returns the response for an HTTP 403 `application/json` response +func (r SyncAgentFilesResponse) GetJSON403() *Forbidden { + return r.JSON403 +} + +// GetJSON409 returns the response for an HTTP 409 `application/json` response +func (r SyncAgentFilesResponse) GetJSON409() *ErrorResponse { + return r.JSON409 +} + +// GetJSON413 returns the response for an HTTP 413 `application/json` response +func (r SyncAgentFilesResponse) GetJSON413() *ErrorResponse { + return r.JSON413 +} + +// GetJSON500 returns the response for an HTTP 500 `application/json` response +func (r SyncAgentFilesResponse) GetJSON500() *InternalError { + return r.JSON500 +} + +// GetJSON503 returns the response for an HTTP 503 `application/json` response +func (r SyncAgentFilesResponse) GetJSON503() *Unavailable { + return r.JSON503 +} + +// GetBody returns the raw response body bytes +func (r SyncAgentFilesResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r SyncAgentFilesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SyncAgentFilesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SyncAgentFilesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + // GetUserResponse200Headers the declared response headers of an HTTP 200 response for GetUser type GetUserResponse200Headers struct { XStreamBalanceMicros *int64 @@ -68050,6 +68699,25 @@ func (c *ClientWithResponses) GetAgentChangesWithResponse(ctx context.Context, i return ParseGetAgentChangesResponse(rsp) } +// GetAgentDirectoryWithResponse An agent config as the files of its directory +// +// The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ with the pages it is kept filled from in knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call tool at its default, a connector's tools when it grants every one), and a connector that says only its name written as the name alone. +// +// Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written with its connection's id, whatever label agent.yaml first named it by, and a skill the config no longer names is left out. +// +// Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with GET /v1/agents/configs/{id}/directory (the `GetAgentDirectory` operationId). +func (c *ClientWithResponses) GetAgentDirectoryWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetAgentDirectoryResponse, error) { + rsp, err := c.GetAgentDirectory(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetAgentDirectoryResponse(rsp) +} + // ListConnectionsWithResponse List connections // // Connections, newest first: the app's own, those of the user the backend acts for, or every user's when it acts for none. @@ -70635,6 +71303,48 @@ func (c *ClientWithResponses) SyncAgentWithResponse(ctx context.Context, body Sy return ParseSyncAgentResponse(rsp) } +// SyncAgentFilesWithBodyWithResponse Store an agent directory sent as its files +// +// POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. +// +// A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. +// +// `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. +// +// Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. +// +// Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). +func (c *ClientWithResponses) SyncAgentFilesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SyncAgentFilesResponse, error) { + rsp, err := c.SyncAgentFilesWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSyncAgentFilesResponse(rsp) +} + +// SyncAgentFilesWithResponse Store an agent directory sent as its files +// +// POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. +// +// A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. +// +// `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. +// +// Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. +// +// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/agents/sync/files (the `SyncAgentFiles` operationId). +func (c *ClientWithResponses) SyncAgentFilesWithResponse(ctx context.Context, body SyncAgentFilesJSONRequestBody, reqEditors ...RequestEditorFn) (*SyncAgentFilesResponse, error) { + rsp, err := c.SyncAgentFiles(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSyncAgentFilesResponse(rsp) +} + // GetUserWithResponse Get a user's phone link // // The number linked to a user of the app, and how much of what it said before the link the user reads. A user with no number linked has a null phone. @@ -77947,22 +78657,22 @@ func ParseGetAgentChangesResponse(rsp *http.Response) (*GetAgentChangesResponse, return response, nil } -// ParseListConnectionsResponse parses an HTTP response from a ListConnectionsWithResponse call -func ParseListConnectionsResponse(rsp *http.Response) (*ListConnectionsResponse, error) { +// ParseGetAgentDirectoryResponse parses an HTTP response from a GetAgentDirectoryWithResponse call +func ParseGetAgentDirectoryResponse(rsp *http.Response) (*GetAgentDirectoryResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListConnectionsResponse{ + response := &GetAgentDirectoryResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ConnectionPage + var dest AgentDirectory if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -77996,6 +78706,13 @@ func ParseListConnectionsResponse(rsp *http.Response) (*ListConnectionsResponse, } response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -78014,7 +78731,7 @@ func ParseListConnectionsResponse(rsp *http.Response) (*ListConnectionsResponse, switch { case rsp.StatusCode == 200: - var headers ListConnectionsResponse200Headers + var headers GetAgentDirectoryResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -78045,7 +78762,7 @@ func ParseListConnectionsResponse(rsp *http.Response) (*ListConnectionsResponse, } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListConnectionsResponse402Headers + var headers GetAgentDirectoryResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -78066,26 +78783,26 @@ func ParseListConnectionsResponse(rsp *http.Response) (*ListConnectionsResponse, return response, nil } -// ParseCreateConnectionResponse parses an HTTP response from a CreateConnectionWithResponse call -func ParseCreateConnectionResponse(rsp *http.Response) (*CreateConnectionResponse, error) { +// ParseListConnectionsResponse parses an HTTP response from a ListConnectionsWithResponse call +func ParseListConnectionsResponse(rsp *http.Response) (*ListConnectionsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateConnectionResponse{ + response := &ListConnectionsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest Connection + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ConnectionPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -78132,8 +78849,8 @@ func ParseCreateConnectionResponse(rsp *http.Response) (*CreateConnectionRespons } switch { - case rsp.StatusCode == 201: - var headers CreateConnectionResponse201Headers + case rsp.StatusCode == 200: + var headers ListConnectionsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -78162,9 +78879,9 @@ func ParseCreateConnectionResponse(rsp *http.Response) (*CreateConnectionRespons } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateConnectionResponse402Headers + var headers ListConnectionsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -78185,22 +78902,141 @@ func ParseCreateConnectionResponse(rsp *http.Response) (*CreateConnectionRespons return response, nil } -// ParseDeleteConnectionResponse parses an HTTP response from a DeleteConnectionWithResponse call -func ParseDeleteConnectionResponse(rsp *http.Response) (*DeleteConnectionResponse, error) { +// ParseCreateConnectionResponse parses an HTTP response from a CreateConnectionWithResponse call +func ParseCreateConnectionResponse(rsp *http.Response) (*CreateConnectionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteConnectionResponse{ + response := &CreateConnectionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Connection + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 201: + var headers CreateConnectionResponse201Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers201 = &headers + case rsp.StatusCode == 402: + var headers CreateConnectionResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseDeleteConnectionResponse parses an HTTP response from a DeleteConnectionWithResponse call +func ParseDeleteConnectionResponse(rsp *http.Response) (*DeleteConnectionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteConnectionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -80763,8 +81599,382 @@ func ParseGetConnectorResponse(rsp *http.Response) (*GetConnectorResponse, error } switch { - case rsp.StatusCode == 200: - var headers GetConnectorResponse200Headers + case rsp.StatusCode == 200: + var headers GetConnectorResponse200Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers200 = &headers + case rsp.StatusCode == 402: + var headers GetConnectorResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseListConnectorEventDestinationsResponse parses an HTTP response from a ListConnectorEventDestinationsWithResponse call +func ParseListConnectorEventDestinationsResponse(rsp *http.Response) (*ListConnectorEventDestinationsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListConnectorEventDestinationsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ConnectorEventDestinationPage + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 200: + var headers ListConnectorEventDestinationsResponse200Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers200 = &headers + case rsp.StatusCode == 402: + var headers ListConnectorEventDestinationsResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseCreateConnectorEventDestinationResponse parses an HTTP response from a CreateConnectorEventDestinationWithResponse call +func ParseCreateConnectorEventDestinationResponse(rsp *http.Response) (*CreateConnectorEventDestinationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateConnectorEventDestinationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest ConnectorEventDestinationSecret + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 201: + var headers CreateConnectorEventDestinationResponse201Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers201 = &headers + case rsp.StatusCode == 402: + var headers CreateConnectorEventDestinationResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseDeleteConnectorEventDestinationResponse parses an HTTP response from a DeleteConnectorEventDestinationWithResponse call +func ParseDeleteConnectorEventDestinationResponse(rsp *http.Response) (*DeleteConnectorEventDestinationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteConnectorEventDestinationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 204: + var headers DeleteConnectorEventDestinationResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -80793,9 +82003,9 @@ func ParseGetConnectorResponse(rsp *http.Response) (*GetConnectorResponse, error } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers GetConnectorResponse402Headers + var headers DeleteConnectorEventDestinationResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -80816,22 +82026,22 @@ func ParseGetConnectorResponse(rsp *http.Response) (*GetConnectorResponse, error return response, nil } -// ParseListConnectorEventDestinationsResponse parses an HTTP response from a ListConnectorEventDestinationsWithResponse call -func ParseListConnectorEventDestinationsResponse(rsp *http.Response) (*ListConnectorEventDestinationsResponse, error) { +// ParseRotateConnectorEventDestinationSecretResponse parses an HTTP response from a RotateConnectorEventDestinationSecretWithResponse call +func ParseRotateConnectorEventDestinationSecretResponse(rsp *http.Response) (*RotateConnectorEventDestinationSecretResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListConnectorEventDestinationsResponse{ + response := &RotateConnectorEventDestinationSecretResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ConnectorEventDestinationPage + var dest ConnectorEventDestinationSecret if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -80865,6 +82075,13 @@ func ParseListConnectorEventDestinationsResponse(rsp *http.Response) (*ListConne } response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -80883,7 +82100,7 @@ func ParseListConnectorEventDestinationsResponse(rsp *http.Response) (*ListConne switch { case rsp.StatusCode == 200: - var headers ListConnectorEventDestinationsResponse200Headers + var headers RotateConnectorEventDestinationSecretResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -80914,7 +82131,7 @@ func ParseListConnectorEventDestinationsResponse(rsp *http.Response) (*ListConne } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListConnectorEventDestinationsResponse402Headers + var headers RotateConnectorEventDestinationSecretResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -80935,26 +82152,22 @@ func ParseListConnectorEventDestinationsResponse(rsp *http.Response) (*ListConne return response, nil } -// ParseCreateConnectorEventDestinationResponse parses an HTTP response from a CreateConnectorEventDestinationWithResponse call -func ParseCreateConnectorEventDestinationResponse(rsp *http.Response) (*CreateConnectorEventDestinationResponse, error) { +// ParseDeleteConnectorOAuthClientResponse parses an HTTP response from a DeleteConnectorOAuthClientWithResponse call +func ParseDeleteConnectorOAuthClientResponse(rsp *http.Response) (*DeleteConnectorOAuthClientResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateConnectorEventDestinationResponse{ + response := &DeleteConnectorOAuthClientResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest ConnectorEventDestinationSecret - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON201 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -80991,13 +82204,6 @@ func ParseCreateConnectorEventDestinationResponse(rsp *http.Response) (*CreateCo } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81015,8 +82221,8 @@ func ParseCreateConnectorEventDestinationResponse(rsp *http.Response) (*CreateCo } switch { - case rsp.StatusCode == 201: - var headers CreateConnectorEventDestinationResponse201Headers + case rsp.StatusCode == 204: + var headers DeleteConnectorOAuthClientResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81045,9 +82251,9 @@ func ParseCreateConnectorEventDestinationResponse(rsp *http.Response) (*CreateCo } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers CreateConnectorEventDestinationResponse402Headers + var headers DeleteConnectorOAuthClientResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81068,22 +82274,26 @@ func ParseCreateConnectorEventDestinationResponse(rsp *http.Response) (*CreateCo return response, nil } -// ParseDeleteConnectorEventDestinationResponse parses an HTTP response from a DeleteConnectorEventDestinationWithResponse call -func ParseDeleteConnectorEventDestinationResponse(rsp *http.Response) (*DeleteConnectorEventDestinationResponse, error) { +// ParseGetConnectorOAuthClientResponse parses an HTTP response from a GetConnectorOAuthClientWithResponse call +func ParseGetConnectorOAuthClientResponse(rsp *http.Response) (*GetConnectorOAuthClientResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteConnectorEventDestinationResponse{ + response := &GetConnectorOAuthClientResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest StoredConnectorOAuthClient + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -81137,8 +82347,8 @@ func ParseDeleteConnectorEventDestinationResponse(rsp *http.Response) (*DeleteCo } switch { - case rsp.StatusCode == 204: - var headers DeleteConnectorEventDestinationResponse204Headers + case rsp.StatusCode == 200: + var headers GetConnectorOAuthClientResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81167,9 +82377,9 @@ func ParseDeleteConnectorEventDestinationResponse(rsp *http.Response) (*DeleteCo } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteConnectorEventDestinationResponse402Headers + var headers GetConnectorOAuthClientResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81190,27 +82400,34 @@ func ParseDeleteConnectorEventDestinationResponse(rsp *http.Response) (*DeleteCo return response, nil } -// ParseRotateConnectorEventDestinationSecretResponse parses an HTTP response from a RotateConnectorEventDestinationSecretWithResponse call -func ParseRotateConnectorEventDestinationSecretResponse(rsp *http.Response) (*RotateConnectorEventDestinationSecretResponse, error) { +// ParseSetConnectorOAuthClientResponse parses an HTTP response from a SetConnectorOAuthClientWithResponse call +func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAuthClientResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RotateConnectorEventDestinationSecretResponse{ + response := &SetConnectorOAuthClientResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ConnectorEventDestinationSecret + var dest ConnectorOAuthClient if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest ConnectorOAuthClient + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81246,6 +82463,13 @@ func ParseRotateConnectorEventDestinationSecretResponse(rsp *http.Response) (*Ro } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81264,7 +82488,174 @@ func ParseRotateConnectorEventDestinationSecretResponse(rsp *http.Response) (*Ro switch { case rsp.StatusCode == 200: - var headers RotateConnectorEventDestinationSecretResponse200Headers + var headers SetConnectorOAuthClientResponse200Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers200 = &headers + case rsp.StatusCode == 201: + var headers SetConnectorOAuthClientResponse201Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers201 = &headers + case rsp.StatusCode == 402: + var headers SetConnectorOAuthClientResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseDeleteConnectorProviderAppResponse parses an HTTP response from a DeleteConnectorProviderAppWithResponse call +func ParseDeleteConnectorProviderAppResponse(rsp *http.Response) (*DeleteConnectorProviderAppResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteConnectorProviderAppResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 204: + var headers DeleteConnectorProviderAppResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81293,9 +82684,9 @@ func ParseRotateConnectorEventDestinationSecretResponse(rsp *http.Response) (*Ro } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers RotateConnectorEventDestinationSecretResponse402Headers + var headers DeleteConnectorProviderAppResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81316,22 +82707,33 @@ func ParseRotateConnectorEventDestinationSecretResponse(rsp *http.Response) (*Ro return response, nil } -// ParseDeleteConnectorOAuthClientResponse parses an HTTP response from a DeleteConnectorOAuthClientWithResponse call -func ParseDeleteConnectorOAuthClientResponse(rsp *http.Response) (*DeleteConnectorOAuthClientResponse, error) { +// ParseSetConnectorProviderAppResponse parses an HTTP response from a SetConnectorProviderAppWithResponse call +func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProviderAppResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteConnectorOAuthClientResponse{ + response := &SetConnectorProviderAppResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ConnectorProviderApp + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest ConnectorProviderApp + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -81368,6 +82770,20 @@ func ParseDeleteConnectorOAuthClientResponse(rsp *http.Response) (*DeleteConnect } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81385,8 +82801,8 @@ func ParseDeleteConnectorOAuthClientResponse(rsp *http.Response) (*DeleteConnect } switch { - case rsp.StatusCode == 204: - var headers DeleteConnectorOAuthClientResponse204Headers + case rsp.StatusCode == 200: + var headers SetConnectorProviderAppResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81415,9 +82831,40 @@ func ParseDeleteConnectorOAuthClientResponse(rsp *http.Response) (*DeleteConnect } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers + case rsp.StatusCode == 201: + var headers SetConnectorProviderAppResponse201Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers DeleteConnectorOAuthClientResponse402Headers + var headers SetConnectorProviderAppResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81438,22 +82885,22 @@ func ParseDeleteConnectorOAuthClientResponse(rsp *http.Response) (*DeleteConnect return response, nil } -// ParseGetConnectorOAuthClientResponse parses an HTTP response from a GetConnectorOAuthClientWithResponse call -func ParseGetConnectorOAuthClientResponse(rsp *http.Response) (*GetConnectorOAuthClientResponse, error) { +// ParseGetConversationCommandResponse parses an HTTP response from a GetConversationCommandWithResponse call +func ParseGetConversationCommandResponse(rsp *http.Response) (*GetConversationCommandResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetConnectorOAuthClientResponse{ + response := &GetConversationCommandResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest StoredConnectorOAuthClient + var dest CommandReceipt if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -81480,13 +82927,6 @@ func ParseGetConnectorOAuthClientResponse(rsp *http.Response) (*GetConnectorOAut } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81512,7 +82952,7 @@ func ParseGetConnectorOAuthClientResponse(rsp *http.Response) (*GetConnectorOAut switch { case rsp.StatusCode == 200: - var headers GetConnectorOAuthClientResponse200Headers + var headers GetConversationCommandResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81543,7 +82983,7 @@ func ParseGetConnectorOAuthClientResponse(rsp *http.Response) (*GetConnectorOAut } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetConnectorOAuthClientResponse402Headers + var headers GetConversationCommandResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81564,34 +83004,27 @@ func ParseGetConnectorOAuthClientResponse(rsp *http.Response) (*GetConnectorOAut return response, nil } -// ParseSetConnectorOAuthClientResponse parses an HTTP response from a SetConnectorOAuthClientWithResponse call -func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAuthClientResponse, error) { +// ParseGetConversationMessagesResponse parses an HTTP response from a GetConversationMessagesWithResponse call +func ParseGetConversationMessagesResponse(rsp *http.Response) (*GetConversationMessagesResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &SetConnectorOAuthClientResponse{ + response := &GetConversationMessagesResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ConnectorOAuthClient + var dest map[string]interface{} if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest ConnectorOAuthClient - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON201 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81620,20 +83053,6 @@ func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAut } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81652,7 +83071,7 @@ func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAut switch { case rsp.StatusCode == 200: - var headers SetConnectorOAuthClientResponse200Headers + var headers GetConversationMessagesResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81682,8 +83101,99 @@ func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAut headers.XStreamCostMicros = &value } response.Headers200 = &headers - case rsp.StatusCode == 201: - var headers SetConnectorOAuthClientResponse201Headers + case rsp.StatusCode == 402: + var headers GetConversationMessagesResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseAnswerConversationToolApprovalResponse parses an HTTP response from a AnswerConversationToolApprovalWithResponse call +func ParseAnswerConversationToolApprovalResponse(rsp *http.Response) (*AnswerConversationToolApprovalResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AnswerConversationToolApprovalResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 204: + var headers AnswerConversationToolApprovalResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81712,9 +83222,9 @@ func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAut } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers SetConnectorOAuthClientResponse402Headers + var headers AnswerConversationToolApprovalResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81735,22 +83245,26 @@ func ParseSetConnectorOAuthClientResponse(rsp *http.Response) (*SetConnectorOAut return response, nil } -// ParseDeleteConnectorProviderAppResponse parses an HTTP response from a DeleteConnectorProviderAppWithResponse call -func ParseDeleteConnectorProviderAppResponse(rsp *http.Response) (*DeleteConnectorProviderAppResponse, error) { +// ParseCreateGuestUserResponse parses an HTTP response from a CreateGuestUserWithResponse call +func ParseCreateGuestUserResponse(rsp *http.Response) (*CreateGuestUserResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteConnectorProviderAppResponse{ + response := &CreateGuestUserResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest GuestUser + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -81774,32 +83288,11 @@ func ParseDeleteConnectorProviderAppResponse(rsp *http.Response) (*DeleteConnect response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON429 = &dest + response.JSON403 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -81818,8 +83311,8 @@ func ParseDeleteConnectorProviderAppResponse(rsp *http.Response) (*DeleteConnect } switch { - case rsp.StatusCode == 204: - var headers DeleteConnectorProviderAppResponse204Headers + case rsp.StatusCode == 201: + var headers CreateGuestUserResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81848,9 +83341,9 @@ func ParseDeleteConnectorProviderAppResponse(rsp *http.Response) (*DeleteConnect } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers DeleteConnectorProviderAppResponse402Headers + var headers CreateGuestUserResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81871,34 +83364,27 @@ func ParseDeleteConnectorProviderAppResponse(rsp *http.Response) (*DeleteConnect return response, nil } -// ParseSetConnectorProviderAppResponse parses an HTTP response from a SetConnectorProviderAppWithResponse call -func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProviderAppResponse, error) { +// ParseClaimGuestUserResponse parses an HTTP response from a ClaimGuestUserWithResponse call +func ParseClaimGuestUserResponse(rsp *http.Response) (*ClaimGuestUserResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &SetConnectorProviderAppResponse{ + response := &ClaimGuestUserResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ConnectorProviderApp + var dest ClaimGuestResult if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest ConnectorProviderApp - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON201 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81941,13 +83427,6 @@ func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProv } response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON429 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -81966,7 +83445,7 @@ func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProv switch { case rsp.StatusCode == 200: - var headers SetConnectorProviderAppResponse200Headers + var headers ClaimGuestUserResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -81996,8 +83475,106 @@ func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProv headers.XStreamCostMicros = &value } response.Headers200 = &headers - case rsp.StatusCode == 201: - var headers SetConnectorProviderAppResponse201Headers + case rsp.StatusCode == 402: + var headers ClaimGuestUserResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseDeleteKnowledgeResponse parses an HTTP response from a DeleteKnowledgeWithResponse call +func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteKnowledgeResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 204: + var headers DeleteKnowledgeResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82026,9 +83603,9 @@ func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProv } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers SetConnectorProviderAppResponse402Headers + var headers DeleteKnowledgeResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82049,22 +83626,22 @@ func ParseSetConnectorProviderAppResponse(rsp *http.Response) (*SetConnectorProv return response, nil } -// ParseGetConversationCommandResponse parses an HTTP response from a GetConversationCommandWithResponse call -func ParseGetConversationCommandResponse(rsp *http.Response) (*GetConversationCommandResponse, error) { +// ParseIngestKnowledgeResponse parses an HTTP response from a IngestKnowledgeWithResponse call +func ParseIngestKnowledgeResponse(rsp *http.Response) (*IngestKnowledgeResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetConversationCommandResponse{ + response := &IngestKnowledgeResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CommandReceipt + var dest IngestedKnowledge if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -82091,12 +83668,12 @@ func ParseGetConversationCommandResponse(rsp *http.Response) (*GetConversationCo } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON404 = &dest + response.JSON403 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -82116,7 +83693,7 @@ func ParseGetConversationCommandResponse(rsp *http.Response) (*GetConversationCo switch { case rsp.StatusCode == 200: - var headers GetConversationCommandResponse200Headers + var headers IngestKnowledgeResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82147,7 +83724,7 @@ func ParseGetConversationCommandResponse(rsp *http.Response) (*GetConversationCo } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetConversationCommandResponse402Headers + var headers IngestKnowledgeResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82168,22 +83745,22 @@ func ParseGetConversationCommandResponse(rsp *http.Response) (*GetConversationCo return response, nil } -// ParseGetConversationMessagesResponse parses an HTTP response from a GetConversationMessagesWithResponse call -func ParseGetConversationMessagesResponse(rsp *http.Response) (*GetConversationMessagesResponse, error) { +// ParseListKnowledgeDocumentsResponse parses an HTTP response from a ListKnowledgeDocumentsWithResponse call +func ParseListKnowledgeDocumentsResponse(rsp *http.Response) (*ListKnowledgeDocumentsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetConversationMessagesResponse{ + response := &ListKnowledgeDocumentsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest map[string]interface{} + var dest []IndexedKnowledgeDocument if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -82235,7 +83812,7 @@ func ParseGetConversationMessagesResponse(rsp *http.Response) (*GetConversationM switch { case rsp.StatusCode == 200: - var headers GetConversationMessagesResponse200Headers + var headers ListKnowledgeDocumentsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82266,7 +83843,7 @@ func ParseGetConversationMessagesResponse(rsp *http.Response) (*GetConversationM } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetConversationMessagesResponse402Headers + var headers ListKnowledgeDocumentsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82287,15 +83864,15 @@ func ParseGetConversationMessagesResponse(rsp *http.Response) (*GetConversationM return response, nil } -// ParseAnswerConversationToolApprovalResponse parses an HTTP response from a AnswerConversationToolApprovalWithResponse call -func ParseAnswerConversationToolApprovalResponse(rsp *http.Response) (*AnswerConversationToolApprovalResponse, error) { +// ParseDeleteKnowledgeDocumentResponse parses an HTTP response from a DeleteKnowledgeDocumentWithResponse call +func ParseDeleteKnowledgeDocumentResponse(rsp *http.Response) (*DeleteKnowledgeDocumentResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &AnswerConversationToolApprovalResponse{ + response := &DeleteKnowledgeDocumentResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -82357,7 +83934,7 @@ func ParseAnswerConversationToolApprovalResponse(rsp *http.Response) (*AnswerCon switch { case rsp.StatusCode == 204: - var headers AnswerConversationToolApprovalResponse204Headers + var headers DeleteKnowledgeDocumentResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82388,7 +83965,7 @@ func ParseAnswerConversationToolApprovalResponse(rsp *http.Response) (*AnswerCon } response.Headers204 = &headers case rsp.StatusCode == 402: - var headers AnswerConversationToolApprovalResponse402Headers + var headers DeleteKnowledgeDocumentResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82409,26 +83986,26 @@ func ParseAnswerConversationToolApprovalResponse(rsp *http.Response) (*AnswerCon return response, nil } -// ParseCreateGuestUserResponse parses an HTTP response from a CreateGuestUserWithResponse call -func ParseCreateGuestUserResponse(rsp *http.Response) (*CreateGuestUserResponse, error) { +// ParseGetKnowledgeDocumentResponse parses an HTTP response from a GetKnowledgeDocumentWithResponse call +func ParseGetKnowledgeDocumentResponse(rsp *http.Response) (*GetKnowledgeDocumentResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateGuestUserResponse{ + response := &GetKnowledgeDocumentResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest GuestUser + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest IndexedKnowledgeDocument if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -82452,12 +84029,19 @@ func ParseCreateGuestUserResponse(rsp *http.Response) (*CreateGuestUserResponse, response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest ErrorResponse + var dest Forbidden if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -82475,8 +84059,8 @@ func ParseCreateGuestUserResponse(rsp *http.Response) (*CreateGuestUserResponse, } switch { - case rsp.StatusCode == 201: - var headers CreateGuestUserResponse201Headers + case rsp.StatusCode == 200: + var headers GetKnowledgeDocumentResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82505,9 +84089,9 @@ func ParseCreateGuestUserResponse(rsp *http.Response) (*CreateGuestUserResponse, } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateGuestUserResponse402Headers + var headers GetKnowledgeDocumentResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82528,22 +84112,22 @@ func ParseCreateGuestUserResponse(rsp *http.Response) (*CreateGuestUserResponse, return response, nil } -// ParseClaimGuestUserResponse parses an HTTP response from a ClaimGuestUserWithResponse call -func ParseClaimGuestUserResponse(rsp *http.Response) (*ClaimGuestUserResponse, error) { +// ParseListKnowledgeDocumentPassagesResponse parses an HTTP response from a ListKnowledgeDocumentPassagesWithResponse call +func ParseListKnowledgeDocumentPassagesResponse(rsp *http.Response) (*ListKnowledgeDocumentPassagesResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ClaimGuestUserResponse{ + response := &ListKnowledgeDocumentPassagesResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ClaimGuestResult + var dest []KnowledgePassage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -82584,13 +84168,6 @@ func ParseClaimGuestUserResponse(rsp *http.Response) (*ClaimGuestUserResponse, e } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -82609,7 +84186,7 @@ func ParseClaimGuestUserResponse(rsp *http.Response) (*ClaimGuestUserResponse, e switch { case rsp.StatusCode == 200: - var headers ClaimGuestUserResponse200Headers + var headers ListKnowledgeDocumentPassagesResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82640,7 +84217,7 @@ func ParseClaimGuestUserResponse(rsp *http.Response) (*ClaimGuestUserResponse, e } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ClaimGuestUserResponse402Headers + var headers ListKnowledgeDocumentPassagesResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82661,22 +84238,26 @@ func ParseClaimGuestUserResponse(rsp *http.Response) (*ClaimGuestUserResponse, e return response, nil } -// ParseDeleteKnowledgeResponse parses an HTTP response from a DeleteKnowledgeWithResponse call -func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, error) { +// ParseUploadKnowledgeFileResponse parses an HTTP response from a UploadKnowledgeFileWithResponse call +func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteKnowledgeResponse{ + response := &UploadKnowledgeFileResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: + var dest IndexedKnowledgeDocument + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON202 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -82706,19 +84287,12 @@ func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 413: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON409 = &dest + response.JSON413 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -82728,7 +84302,7 @@ func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -82737,8 +84311,8 @@ func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, } switch { - case rsp.StatusCode == 204: - var headers DeleteKnowledgeResponse204Headers + case rsp.StatusCode == 202: + var headers UploadKnowledgeFileResponse202Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82767,9 +84341,9 @@ func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers202 = &headers case rsp.StatusCode == 402: - var headers DeleteKnowledgeResponse402Headers + var headers UploadKnowledgeFileResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82790,22 +84364,22 @@ func ParseDeleteKnowledgeResponse(rsp *http.Response) (*DeleteKnowledgeResponse, return response, nil } -// ParseIngestKnowledgeResponse parses an HTTP response from a IngestKnowledgeWithResponse call -func ParseIngestKnowledgeResponse(rsp *http.Response) (*IngestKnowledgeResponse, error) { +// ParseListKnowledgeUrlsResponse parses an HTTP response from a ListKnowledgeUrlsWithResponse call +func ParseListKnowledgeUrlsResponse(rsp *http.Response) (*ListKnowledgeUrlsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &IngestKnowledgeResponse{ + response := &ListKnowledgeUrlsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest IngestedKnowledge + var dest []KnowledgeUrl if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -82857,7 +84431,7 @@ func ParseIngestKnowledgeResponse(rsp *http.Response) (*IngestKnowledgeResponse, switch { case rsp.StatusCode == 200: - var headers IngestKnowledgeResponse200Headers + var headers ListKnowledgeUrlsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82888,7 +84462,7 @@ func ParseIngestKnowledgeResponse(rsp *http.Response) (*IngestKnowledgeResponse, } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers IngestKnowledgeResponse402Headers + var headers ListKnowledgeUrlsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -82909,26 +84483,26 @@ func ParseIngestKnowledgeResponse(rsp *http.Response) (*IngestKnowledgeResponse, return response, nil } -// ParseListKnowledgeDocumentsResponse parses an HTTP response from a ListKnowledgeDocumentsWithResponse call -func ParseListKnowledgeDocumentsResponse(rsp *http.Response) (*ListKnowledgeDocumentsResponse, error) { +// ParseAddKnowledgeUrlResponse parses an HTTP response from a AddKnowledgeUrlWithResponse call +func ParseAddKnowledgeUrlResponse(rsp *http.Response) (*AddKnowledgeUrlResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListKnowledgeDocumentsResponse{ + response := &AddKnowledgeUrlResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []IndexedKnowledgeDocument + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest KnowledgeUrl if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -82975,8 +84549,8 @@ func ParseListKnowledgeDocumentsResponse(rsp *http.Response) (*ListKnowledgeDocu } switch { - case rsp.StatusCode == 200: - var headers ListKnowledgeDocumentsResponse200Headers + case rsp.StatusCode == 201: + var headers AddKnowledgeUrlResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83005,9 +84579,9 @@ func ParseListKnowledgeDocumentsResponse(rsp *http.Response) (*ListKnowledgeDocu } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers ListKnowledgeDocumentsResponse402Headers + var headers AddKnowledgeUrlResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83028,15 +84602,15 @@ func ParseListKnowledgeDocumentsResponse(rsp *http.Response) (*ListKnowledgeDocu return response, nil } -// ParseDeleteKnowledgeDocumentResponse parses an HTTP response from a DeleteKnowledgeDocumentWithResponse call -func ParseDeleteKnowledgeDocumentResponse(rsp *http.Response) (*DeleteKnowledgeDocumentResponse, error) { +// ParseDeleteKnowledgeUrlResponse parses an HTTP response from a DeleteKnowledgeUrlWithResponse call +func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteKnowledgeDocumentResponse{ + response := &DeleteKnowledgeUrlResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -83098,7 +84672,7 @@ func ParseDeleteKnowledgeDocumentResponse(rsp *http.Response) (*DeleteKnowledgeD switch { case rsp.StatusCode == 204: - var headers DeleteKnowledgeDocumentResponse204Headers + var headers DeleteKnowledgeUrlResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83129,7 +84703,7 @@ func ParseDeleteKnowledgeDocumentResponse(rsp *http.Response) (*DeleteKnowledgeD } response.Headers204 = &headers case rsp.StatusCode == 402: - var headers DeleteKnowledgeDocumentResponse402Headers + var headers DeleteKnowledgeUrlResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83150,22 +84724,22 @@ func ParseDeleteKnowledgeDocumentResponse(rsp *http.Response) (*DeleteKnowledgeD return response, nil } -// ParseGetKnowledgeDocumentResponse parses an HTTP response from a GetKnowledgeDocumentWithResponse call -func ParseGetKnowledgeDocumentResponse(rsp *http.Response) (*GetKnowledgeDocumentResponse, error) { +// ParseGetKnowledgeUrlResponse parses an HTTP response from a GetKnowledgeUrlWithResponse call +func ParseGetKnowledgeUrlResponse(rsp *http.Response) (*GetKnowledgeUrlResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetKnowledgeDocumentResponse{ + response := &GetKnowledgeUrlResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest IndexedKnowledgeDocument + var dest KnowledgeUrl if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83224,7 +84798,7 @@ func ParseGetKnowledgeDocumentResponse(rsp *http.Response) (*GetKnowledgeDocumen switch { case rsp.StatusCode == 200: - var headers GetKnowledgeDocumentResponse200Headers + var headers GetKnowledgeUrlResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83255,7 +84829,7 @@ func ParseGetKnowledgeDocumentResponse(rsp *http.Response) (*GetKnowledgeDocumen } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetKnowledgeDocumentResponse402Headers + var headers GetKnowledgeUrlResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83276,22 +84850,22 @@ func ParseGetKnowledgeDocumentResponse(rsp *http.Response) (*GetKnowledgeDocumen return response, nil } -// ParseListKnowledgeDocumentPassagesResponse parses an HTTP response from a ListKnowledgeDocumentPassagesWithResponse call -func ParseListKnowledgeDocumentPassagesResponse(rsp *http.Response) (*ListKnowledgeDocumentPassagesResponse, error) { +// ParseIndexKnowledgeUrlResponse parses an HTTP response from a IndexKnowledgeUrlWithResponse call +func ParseIndexKnowledgeUrlResponse(rsp *http.Response) (*IndexKnowledgeUrlResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListKnowledgeDocumentPassagesResponse{ + response := &IndexKnowledgeUrlResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []KnowledgePassage + var dest KnowledgeUrl if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83350,7 +84924,7 @@ func ParseListKnowledgeDocumentPassagesResponse(rsp *http.Response) (*ListKnowle switch { case rsp.StatusCode == 200: - var headers ListKnowledgeDocumentPassagesResponse200Headers + var headers IndexKnowledgeUrlResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83381,7 +84955,7 @@ func ParseListKnowledgeDocumentPassagesResponse(rsp *http.Response) (*ListKnowle } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListKnowledgeDocumentPassagesResponse402Headers + var headers IndexKnowledgeUrlResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83402,26 +84976,26 @@ func ParseListKnowledgeDocumentPassagesResponse(rsp *http.Response) (*ListKnowle return response, nil } -// ParseUploadKnowledgeFileResponse parses an HTTP response from a UploadKnowledgeFileWithResponse call -func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileResponse, error) { +// ParseListKnowledgeUrlPassagesResponse parses an HTTP response from a ListKnowledgeUrlPassagesWithResponse call +func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUrlPassagesResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UploadKnowledgeFileResponse{ + response := &ListKnowledgeUrlPassagesResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: - var dest IndexedKnowledgeDocument + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []KnowledgePassage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON202 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -83451,12 +85025,12 @@ func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileR } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 413: - var dest ErrorResponse + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON413 = &dest + response.JSON404 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -83466,7 +85040,7 @@ func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileR response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83475,8 +85049,8 @@ func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileR } switch { - case rsp.StatusCode == 202: - var headers UploadKnowledgeFileResponse202Headers + case rsp.StatusCode == 200: + var headers ListKnowledgeUrlPassagesResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83505,9 +85079,9 @@ func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileR } headers.XStreamCostMicros = &value } - response.Headers202 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers UploadKnowledgeFileResponse402Headers + var headers ListKnowledgeUrlPassagesResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83528,22 +85102,22 @@ func ParseUploadKnowledgeFileResponse(rsp *http.Response) (*UploadKnowledgeFileR return response, nil } -// ParseListKnowledgeUrlsResponse parses an HTTP response from a ListKnowledgeUrlsWithResponse call -func ParseListKnowledgeUrlsResponse(rsp *http.Response) (*ListKnowledgeUrlsResponse, error) { +// ParseListAgentLogsResponse parses an HTTP response from a ListAgentLogsWithResponse call +func ParseListAgentLogsResponse(rsp *http.Response) (*ListAgentLogsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListKnowledgeUrlsResponse{ + response := &ListAgentLogsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []KnowledgeUrl + var dest AgentLogPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83585,7 +85159,7 @@ func ParseListKnowledgeUrlsResponse(rsp *http.Response) (*ListKnowledgeUrlsRespo response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83595,7 +85169,7 @@ func ParseListKnowledgeUrlsResponse(rsp *http.Response) (*ListKnowledgeUrlsRespo switch { case rsp.StatusCode == 200: - var headers ListKnowledgeUrlsResponse200Headers + var headers ListAgentLogsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83626,126 +85200,7 @@ func ParseListKnowledgeUrlsResponse(rsp *http.Response) (*ListKnowledgeUrlsRespo } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListKnowledgeUrlsResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseAddKnowledgeUrlResponse parses an HTTP response from a AddKnowledgeUrlWithResponse call -func ParseAddKnowledgeUrlResponse(rsp *http.Response) (*AddKnowledgeUrlResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &AddKnowledgeUrlResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest KnowledgeUrl - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON201 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON402 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 201: - var headers AddKnowledgeUrlResponse201Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers201 = &headers - case rsp.StatusCode == 402: - var headers AddKnowledgeUrlResponse402Headers + var headers ListAgentLogsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83766,23 +85221,20 @@ func ParseAddKnowledgeUrlResponse(rsp *http.Response) (*AddKnowledgeUrlResponse, return response, nil } -// ParseDeleteKnowledgeUrlResponse parses an HTTP response from a DeleteKnowledgeUrlWithResponse call -func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlResponse, error) { +// ParseStreamAgentLogsResponse parses an HTTP response from a StreamAgentLogsWithResponse call +func ParseStreamAgentLogsResponse(rsp *http.Response) (*StreamAgentLogsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteKnowledgeUrlResponse{ + response := &StreamAgentLogsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -83811,13 +85263,6 @@ func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlRes } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -83826,7 +85271,7 @@ func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlRes response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83835,8 +85280,8 @@ func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlRes } switch { - case rsp.StatusCode == 204: - var headers DeleteKnowledgeUrlResponse204Headers + case rsp.StatusCode == 200: + var headers StreamAgentLogsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83865,9 +85310,9 @@ func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlRes } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteKnowledgeUrlResponse402Headers + var headers StreamAgentLogsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83888,34 +85333,27 @@ func ParseDeleteKnowledgeUrlResponse(rsp *http.Response) (*DeleteKnowledgeUrlRes return response, nil } -// ParseGetKnowledgeUrlResponse parses an HTTP response from a GetKnowledgeUrlWithResponse call -func ParseGetKnowledgeUrlResponse(rsp *http.Response) (*GetKnowledgeUrlResponse, error) { +// ParseGetAgentLogResponse parses an HTTP response from a GetAgentLogWithResponse call +func ParseGetAgentLogResponse(rsp *http.Response) (*GetAgentLogResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetKnowledgeUrlResponse{ + response := &GetAgentLogResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest KnowledgeUrl + var dest AgentLog if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest Unauthorized if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -83952,7 +85390,7 @@ func ParseGetKnowledgeUrlResponse(rsp *http.Response) (*GetKnowledgeUrlResponse, response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -83962,7 +85400,7 @@ func ParseGetKnowledgeUrlResponse(rsp *http.Response) (*GetKnowledgeUrlResponse, switch { case rsp.StatusCode == 200: - var headers GetKnowledgeUrlResponse200Headers + var headers GetAgentLogResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -83993,7 +85431,7 @@ func ParseGetKnowledgeUrlResponse(rsp *http.Response) (*GetKnowledgeUrlResponse, } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetKnowledgeUrlResponse402Headers + var headers GetAgentLogResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84014,22 +85452,22 @@ func ParseGetKnowledgeUrlResponse(rsp *http.Response) (*GetKnowledgeUrlResponse, return response, nil } -// ParseIndexKnowledgeUrlResponse parses an HTTP response from a IndexKnowledgeUrlWithResponse call -func ParseIndexKnowledgeUrlResponse(rsp *http.Response) (*IndexKnowledgeUrlResponse, error) { +// ParseListCustomModelsResponse parses an HTTP response from a ListCustomModelsWithResponse call +func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &IndexKnowledgeUrlResponse{ + response := &ListCustomModelsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest KnowledgeUrl + var dest CustomModelPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -84063,13 +85501,6 @@ func ParseIndexKnowledgeUrlResponse(rsp *http.Response) (*IndexKnowledgeUrlRespo } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84088,7 +85519,7 @@ func ParseIndexKnowledgeUrlResponse(rsp *http.Response) (*IndexKnowledgeUrlRespo switch { case rsp.StatusCode == 200: - var headers IndexKnowledgeUrlResponse200Headers + var headers ListCustomModelsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84119,7 +85550,7 @@ func ParseIndexKnowledgeUrlResponse(rsp *http.Response) (*IndexKnowledgeUrlRespo } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers IndexKnowledgeUrlResponse402Headers + var headers ListCustomModelsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84140,26 +85571,26 @@ func ParseIndexKnowledgeUrlResponse(rsp *http.Response) (*IndexKnowledgeUrlRespo return response, nil } -// ParseListKnowledgeUrlPassagesResponse parses an HTTP response from a ListKnowledgeUrlPassagesWithResponse call -func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUrlPassagesResponse, error) { +// ParseCreateCustomModelResponse parses an HTTP response from a CreateCustomModelWithResponse call +func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListKnowledgeUrlPassagesResponse{ + response := &CreateCustomModelResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []KnowledgePassage + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest CustomModel if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -84189,12 +85620,12 @@ func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUr } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON404 = &dest + response.JSON409 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -84203,6 +85634,13 @@ func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUr } response.JSON500 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON501 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84213,8 +85651,8 @@ func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUr } switch { - case rsp.StatusCode == 200: - var headers ListKnowledgeUrlPassagesResponse200Headers + case rsp.StatusCode == 201: + var headers CreateCustomModelResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84243,9 +85681,9 @@ func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUr } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers ListKnowledgeUrlPassagesResponse402Headers + var headers CreateCustomModelResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84266,26 +85704,22 @@ func ParseListKnowledgeUrlPassagesResponse(rsp *http.Response) (*ListKnowledgeUr return response, nil } -// ParseListAgentLogsResponse parses an HTTP response from a ListAgentLogsWithResponse call -func ParseListAgentLogsResponse(rsp *http.Response) (*ListAgentLogsResponse, error) { +// ParseDeleteCustomModelResponse parses an HTTP response from a DeleteCustomModelWithResponse call +func ParseDeleteCustomModelResponse(rsp *http.Response) (*DeleteCustomModelResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListAgentLogsResponse{ + response := &DeleteCustomModelResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest AgentLogPage - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -84315,117 +85749,12 @@ func ParseListAgentLogsResponse(rsp *http.Response) (*ListAgentLogsResponse, err } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 200: - var headers ListAgentLogsResponse200Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers200 = &headers - case rsp.StatusCode == 402: - var headers ListAgentLogsResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseStreamAgentLogsResponse parses an HTTP response from a StreamAgentLogsWithResponse call -func ParseStreamAgentLogsResponse(rsp *http.Response) (*StreamAgentLogsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &StreamAgentLogsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON402 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON403 = &dest + response.JSON404 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -84435,7 +85764,7 @@ func ParseStreamAgentLogsResponse(rsp *http.Response) (*StreamAgentLogsResponse, response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -84444,8 +85773,8 @@ func ParseStreamAgentLogsResponse(rsp *http.Response) (*StreamAgentLogsResponse, } switch { - case rsp.StatusCode == 200: - var headers StreamAgentLogsResponse200Headers + case rsp.StatusCode == 204: + var headers DeleteCustomModelResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84474,9 +85803,9 @@ func ParseStreamAgentLogsResponse(rsp *http.Response) (*StreamAgentLogsResponse, } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers StreamAgentLogsResponse402Headers + var headers DeleteCustomModelResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84497,27 +85826,34 @@ func ParseStreamAgentLogsResponse(rsp *http.Response) (*StreamAgentLogsResponse, return response, nil } -// ParseGetAgentLogResponse parses an HTTP response from a GetAgentLogWithResponse call -func ParseGetAgentLogResponse(rsp *http.Response) (*GetAgentLogResponse, error) { +// ParseGetCustomModelResponse parses an HTTP response from a GetCustomModelWithResponse call +func ParseGetCustomModelResponse(rsp *http.Response) (*GetCustomModelResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetAgentLogResponse{ + response := &GetCustomModelResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest AgentLog + var dest CustomModel if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest Unauthorized if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84554,7 +85890,7 @@ func ParseGetAgentLogResponse(rsp *http.Response) (*GetAgentLogResponse, error) response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -84564,7 +85900,7 @@ func ParseGetAgentLogResponse(rsp *http.Response) (*GetAgentLogResponse, error) switch { case rsp.StatusCode == 200: - var headers GetAgentLogResponse200Headers + var headers GetCustomModelResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84595,7 +85931,7 @@ func ParseGetAgentLogResponse(rsp *http.Response) (*GetAgentLogResponse, error) } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetAgentLogResponse402Headers + var headers GetCustomModelResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84616,22 +85952,22 @@ func ParseGetAgentLogResponse(rsp *http.Response) (*GetAgentLogResponse, error) return response, nil } -// ParseListCustomModelsResponse parses an HTTP response from a ListCustomModelsWithResponse call -func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsResponse, error) { +// ParseUpdateCustomModelResponse parses an HTTP response from a UpdateCustomModelWithResponse call +func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListCustomModelsResponse{ + response := &UpdateCustomModelResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CustomModelPage + var dest CustomModel if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -84665,6 +86001,20 @@ func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsRespons } response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84672,6 +86022,13 @@ func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsRespons } response.JSON500 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON501 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84683,7 +86040,7 @@ func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsRespons switch { case rsp.StatusCode == 200: - var headers ListCustomModelsResponse200Headers + var headers UpdateCustomModelResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84714,7 +86071,7 @@ func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListCustomModelsResponse402Headers + var headers UpdateCustomModelResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84735,26 +86092,26 @@ func ParseListCustomModelsResponse(rsp *http.Response) (*ListCustomModelsRespons return response, nil } -// ParseCreateCustomModelResponse parses an HTTP response from a CreateCustomModelWithResponse call -func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelResponse, error) { +// ParseListProviderKeysResponse parses an HTTP response from a ListProviderKeysWithResponse call +func ParseListProviderKeysResponse(rsp *http.Response) (*ListProviderKeysResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateCustomModelResponse{ + response := &ListProviderKeysResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest CustomModel + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ProviderKeyPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -84784,13 +86141,6 @@ func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelRespo } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84798,13 +86148,6 @@ func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelRespo } response.JSON500 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON501 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84815,8 +86158,8 @@ func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelRespo } switch { - case rsp.StatusCode == 201: - var headers CreateCustomModelResponse201Headers + case rsp.StatusCode == 200: + var headers ListProviderKeysResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84845,9 +86188,9 @@ func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelRespo } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateCustomModelResponse402Headers + var headers ListProviderKeysResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84868,22 +86211,26 @@ func ParseCreateCustomModelResponse(rsp *http.Response) (*CreateCustomModelRespo return response, nil } -// ParseDeleteCustomModelResponse parses an HTTP response from a DeleteCustomModelWithResponse call -func ParseDeleteCustomModelResponse(rsp *http.Response) (*DeleteCustomModelResponse, error) { +// ParsePutProviderKeyResponse parses an HTTP response from a PutProviderKeyWithResponse call +func ParsePutProviderKeyResponse(rsp *http.Response) (*PutProviderKeyResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteCustomModelResponse{ + response := &PutProviderKeyResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ProviderKey + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -84913,13 +86260,6 @@ func ParseDeleteCustomModelResponse(rsp *http.Response) (*DeleteCustomModelRespo } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -84937,8 +86277,8 @@ func ParseDeleteCustomModelResponse(rsp *http.Response) (*DeleteCustomModelRespo } switch { - case rsp.StatusCode == 204: - var headers DeleteCustomModelResponse204Headers + case rsp.StatusCode == 200: + var headers PutProviderKeyResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84967,9 +86307,9 @@ func ParseDeleteCustomModelResponse(rsp *http.Response) (*DeleteCustomModelRespo } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteCustomModelResponse402Headers + var headers PutProviderKeyResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -84990,26 +86330,22 @@ func ParseDeleteCustomModelResponse(rsp *http.Response) (*DeleteCustomModelRespo return response, nil } -// ParseGetCustomModelResponse parses an HTTP response from a GetCustomModelWithResponse call -func ParseGetCustomModelResponse(rsp *http.Response) (*GetCustomModelResponse, error) { +// ParseDeleteProviderKeyResponse parses an HTTP response from a DeleteProviderKeyWithResponse call +func ParseDeleteProviderKeyResponse(rsp *http.Response) (*DeleteProviderKeyResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetCustomModelResponse{ + response := &DeleteProviderKeyResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CustomModel - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -85063,8 +86399,8 @@ func ParseGetCustomModelResponse(rsp *http.Response) (*GetCustomModelResponse, e } switch { - case rsp.StatusCode == 200: - var headers GetCustomModelResponse200Headers + case rsp.StatusCode == 204: + var headers DeleteProviderKeyResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85093,9 +86429,9 @@ func ParseGetCustomModelResponse(rsp *http.Response) (*GetCustomModelResponse, e } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers GetCustomModelResponse402Headers + var headers DeleteProviderKeyResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85116,22 +86452,22 @@ func ParseGetCustomModelResponse(rsp *http.Response) (*GetCustomModelResponse, e return response, nil } -// ParseUpdateCustomModelResponse parses an HTTP response from a UpdateCustomModelWithResponse call -func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelResponse, error) { +// ParseCreateRunResponse parses an HTTP response from a CreateRunWithResponse call +func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateCustomModelResponse{ + response := &CreateRunResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CustomModel + var dest Run if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -85159,7 +86495,7 @@ func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelRespo response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -85172,12 +86508,12 @@ func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelRespo } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON409 = &dest + response.JSON429 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -85186,25 +86522,25 @@ func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelRespo } response.JSON500 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON501 = &dest + response.JSON503 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 504: + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON503 = &dest + response.JSON504 = &dest } switch { case rsp.StatusCode == 200: - var headers UpdateCustomModelResponse200Headers + var headers CreateRunResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85235,7 +86571,7 @@ func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelRespo } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers UpdateCustomModelResponse402Headers + var headers CreateRunResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85256,22 +86592,22 @@ func ParseUpdateCustomModelResponse(rsp *http.Response) (*UpdateCustomModelRespo return response, nil } -// ParseListProviderKeysResponse parses an HTTP response from a ListProviderKeysWithResponse call -func ParseListProviderKeysResponse(rsp *http.Response) (*ListProviderKeysResponse, error) { +// ParseListScheduledTasksResponse parses an HTTP response from a ListScheduledTasksWithResponse call +func ParseListScheduledTasksResponse(rsp *http.Response) (*ListScheduledTasksResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListProviderKeysResponse{ + response := &ListScheduledTasksResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ProviderKeyPage + var dest ScheduledTaskPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -85312,6 +86648,13 @@ func ParseListProviderKeysResponse(rsp *http.Response) (*ListProviderKeysRespons } response.JSON500 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON501 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -85323,7 +86666,7 @@ func ParseListProviderKeysResponse(rsp *http.Response) (*ListProviderKeysRespons switch { case rsp.StatusCode == 200: - var headers ListProviderKeysResponse200Headers + var headers ListScheduledTasksResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85354,7 +86697,7 @@ func ParseListProviderKeysResponse(rsp *http.Response) (*ListProviderKeysRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListProviderKeysResponse402Headers + var headers ListScheduledTasksResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85375,26 +86718,26 @@ func ParseListProviderKeysResponse(rsp *http.Response) (*ListProviderKeysRespons return response, nil } -// ParsePutProviderKeyResponse parses an HTTP response from a PutProviderKeyWithResponse call -func ParsePutProviderKeyResponse(rsp *http.Response) (*PutProviderKeyResponse, error) { +// ParseCreateScheduledTaskResponse parses an HTTP response from a CreateScheduledTaskWithResponse call +func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &PutProviderKeyResponse{ + response := &CreateScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ProviderKey + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest ScheduledTask if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -85424,134 +86767,33 @@ func ParsePutProviderKeyResponse(rsp *http.Response) (*PutProviderKeyResponse, e } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 200: - var headers PutProviderKeyResponse200Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers200 = &headers - case rsp.StatusCode == 402: - var headers PutProviderKeyResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseDeleteProviderKeyResponse parses an HTTP response from a DeleteProviderKeyWithResponse call -func ParseDeleteProviderKeyResponse(rsp *http.Response) (*DeleteProviderKeyResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &DeleteProviderKeyResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.StatusCode == 204: - break // No content-type - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON402 = &dest + response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON403 = &dest + response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON404 = &dest + response.JSON500 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON500 = &dest + response.JSON501 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable @@ -85563,8 +86805,8 @@ func ParseDeleteProviderKeyResponse(rsp *http.Response) (*DeleteProviderKeyRespo } switch { - case rsp.StatusCode == 204: - var headers DeleteProviderKeyResponse204Headers + case rsp.StatusCode == 201: + var headers CreateScheduledTaskResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85593,9 +86835,9 @@ func ParseDeleteProviderKeyResponse(rsp *http.Response) (*DeleteProviderKeyRespo } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers DeleteProviderKeyResponse402Headers + var headers CreateScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85616,26 +86858,22 @@ func ParseDeleteProviderKeyResponse(rsp *http.Response) (*DeleteProviderKeyRespo return response, nil } -// ParseCreateRunResponse parses an HTTP response from a CreateRunWithResponse call -func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { +// ParseDeleteScheduledTaskResponse parses an HTTP response from a DeleteScheduledTaskWithResponse call +func ParseDeleteScheduledTaskResponse(rsp *http.Response) (*DeleteScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateRunResponse{ + response := &DeleteScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Run - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -85659,7 +86897,7 @@ func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { response.JSON402 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest ErrorResponse + var dest Forbidden if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -85672,13 +86910,6 @@ func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON429 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -85687,24 +86918,17 @@ func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON503 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 504: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON504 = &dest - } switch { - case rsp.StatusCode == 200: - var headers CreateRunResponse200Headers + case rsp.StatusCode == 204: + var headers DeleteScheduledTaskResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85733,9 +86957,9 @@ func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers CreateRunResponse402Headers + var headers DeleteScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85756,22 +86980,22 @@ func ParseCreateRunResponse(rsp *http.Response) (*CreateRunResponse, error) { return response, nil } -// ParseListScheduledTasksResponse parses an HTTP response from a ListScheduledTasksWithResponse call -func ParseListScheduledTasksResponse(rsp *http.Response) (*ListScheduledTasksResponse, error) { +// ParseGetScheduledTaskResponse parses an HTTP response from a GetScheduledTaskWithResponse call +func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListScheduledTasksResponse{ + response := &GetScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ScheduledTaskPage + var dest ScheduledTask if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -85805,19 +87029,19 @@ func ParseListScheduledTasksResponse(rsp *http.Response) (*ListScheduledTasksRes } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON500 = &dest + response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: - var dest ErrorResponse + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON501 = &dest + response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable @@ -85830,7 +87054,7 @@ func ParseListScheduledTasksResponse(rsp *http.Response) (*ListScheduledTasksRes switch { case rsp.StatusCode == 200: - var headers ListScheduledTasksResponse200Headers + var headers GetScheduledTaskResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85861,7 +87085,7 @@ func ParseListScheduledTasksResponse(rsp *http.Response) (*ListScheduledTasksRes } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListScheduledTasksResponse402Headers + var headers GetScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85882,26 +87106,26 @@ func ParseListScheduledTasksResponse(rsp *http.Response) (*ListScheduledTasksRes return response, nil } -// ParseCreateScheduledTaskResponse parses an HTTP response from a CreateScheduledTaskWithResponse call -func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskResponse, error) { +// ParseUpdateScheduledTaskResponse parses an HTTP response from a UpdateScheduledTaskWithResponse call +func ParseUpdateScheduledTaskResponse(rsp *http.Response) (*UpdateScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateScheduledTaskResponse{ + response := &UpdateScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest ScheduledTask if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -85938,13 +87162,6 @@ func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskR } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -85952,13 +87169,6 @@ func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskR } response.JSON500 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON501 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -85969,8 +87179,8 @@ func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskR } switch { - case rsp.StatusCode == 201: - var headers CreateScheduledTaskResponse201Headers + case rsp.StatusCode == 200: + var headers UpdateScheduledTaskResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -85999,9 +87209,9 @@ func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskR } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateScheduledTaskResponse402Headers + var headers UpdateScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86022,22 +87232,26 @@ func ParseCreateScheduledTaskResponse(rsp *http.Response) (*CreateScheduledTaskR return response, nil } -// ParseDeleteScheduledTaskResponse parses an HTTP response from a DeleteScheduledTaskWithResponse call -func ParseDeleteScheduledTaskResponse(rsp *http.Response) (*DeleteScheduledTaskResponse, error) { +// ParsePauseScheduledTaskResponse parses an HTTP response from a PauseScheduledTaskWithResponse call +func ParsePauseScheduledTaskResponse(rsp *http.Response) (*PauseScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteScheduledTaskResponse{ + response := &PauseScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ScheduledTask + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -86091,8 +87305,8 @@ func ParseDeleteScheduledTaskResponse(rsp *http.Response) (*DeleteScheduledTaskR } switch { - case rsp.StatusCode == 204: - var headers DeleteScheduledTaskResponse204Headers + case rsp.StatusCode == 200: + var headers PauseScheduledTaskResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86121,9 +87335,9 @@ func ParseDeleteScheduledTaskResponse(rsp *http.Response) (*DeleteScheduledTaskR } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteScheduledTaskResponse402Headers + var headers PauseScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86144,15 +87358,15 @@ func ParseDeleteScheduledTaskResponse(rsp *http.Response) (*DeleteScheduledTaskR return response, nil } -// ParseGetScheduledTaskResponse parses an HTTP response from a GetScheduledTaskWithResponse call -func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskResponse, error) { +// ParseResumeScheduledTaskResponse parses an HTTP response from a ResumeScheduledTaskWithResponse call +func ParseResumeScheduledTaskResponse(rsp *http.Response) (*ResumeScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetScheduledTaskResponse{ + response := &ResumeScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -86166,7 +87380,7 @@ func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskRespons response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -86200,6 +87414,13 @@ func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskRespons } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -86218,7 +87439,7 @@ func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskRespons switch { case rsp.StatusCode == 200: - var headers GetScheduledTaskResponse200Headers + var headers ResumeScheduledTaskResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86249,7 +87470,7 @@ func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetScheduledTaskResponse402Headers + var headers ResumeScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86270,26 +87491,26 @@ func ParseGetScheduledTaskResponse(rsp *http.Response) (*GetScheduledTaskRespons return response, nil } -// ParseUpdateScheduledTaskResponse parses an HTTP response from a UpdateScheduledTaskWithResponse call -func ParseUpdateScheduledTaskResponse(rsp *http.Response) (*UpdateScheduledTaskResponse, error) { +// ParseRunScheduledTaskResponse parses an HTTP response from a RunScheduledTaskWithResponse call +func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateScheduledTaskResponse{ + response := &RunScheduledTaskResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ScheduledTask + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: + var dest ScheduledTaskRun if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON202 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -86333,6 +87554,13 @@ func ParseUpdateScheduledTaskResponse(rsp *http.Response) (*UpdateScheduledTaskR } response.JSON500 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON501 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -86343,8 +87571,8 @@ func ParseUpdateScheduledTaskResponse(rsp *http.Response) (*UpdateScheduledTaskR } switch { - case rsp.StatusCode == 200: - var headers UpdateScheduledTaskResponse200Headers + case rsp.StatusCode == 202: + var headers RunScheduledTaskResponse202Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86373,9 +87601,9 @@ func ParseUpdateScheduledTaskResponse(rsp *http.Response) (*UpdateScheduledTaskR } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers202 = &headers case rsp.StatusCode == 402: - var headers UpdateScheduledTaskResponse402Headers + var headers RunScheduledTaskResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86396,22 +87624,22 @@ func ParseUpdateScheduledTaskResponse(rsp *http.Response) (*UpdateScheduledTaskR return response, nil } -// ParsePauseScheduledTaskResponse parses an HTTP response from a PauseScheduledTaskWithResponse call -func ParsePauseScheduledTaskResponse(rsp *http.Response) (*PauseScheduledTaskResponse, error) { +// ParseListScheduledTaskRunsResponse parses an HTTP response from a ListScheduledTaskRunsWithResponse call +func ParseListScheduledTaskRunsResponse(rsp *http.Response) (*ListScheduledTaskRunsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &PauseScheduledTaskResponse{ + response := &ListScheduledTaskRunsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ScheduledTask + var dest ScheduledTaskRunPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -86470,7 +87698,7 @@ func ParsePauseScheduledTaskResponse(rsp *http.Response) (*PauseScheduledTaskRes switch { case rsp.StatusCode == 200: - var headers PauseScheduledTaskResponse200Headers + var headers ListScheduledTaskRunsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86501,7 +87729,7 @@ func ParsePauseScheduledTaskResponse(rsp *http.Response) (*PauseScheduledTaskRes } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers PauseScheduledTaskResponse402Headers + var headers ListScheduledTaskRunsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86522,29 +87750,29 @@ func ParsePauseScheduledTaskResponse(rsp *http.Response) (*PauseScheduledTaskRes return response, nil } -// ParseResumeScheduledTaskResponse parses an HTTP response from a ResumeScheduledTaskWithResponse call -func ParseResumeScheduledTaskResponse(rsp *http.Response) (*ResumeScheduledTaskResponse, error) { +// ParseCreateSessionResponse parses an HTTP response from a CreateSessionWithResponse call +func ParseCreateSessionResponse(rsp *http.Response) (*CreateSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ResumeScheduledTaskResponse{ + response := &CreateSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ScheduledTask + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Session if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest ErrorResponse + var dest BadRequest if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -86602,8 +87830,8 @@ func ParseResumeScheduledTaskResponse(rsp *http.Response) (*ResumeScheduledTaskR } switch { - case rsp.StatusCode == 200: - var headers ResumeScheduledTaskResponse200Headers + case rsp.StatusCode == 201: + var headers CreateSessionResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86632,9 +87860,9 @@ func ParseResumeScheduledTaskResponse(rsp *http.Response) (*ResumeScheduledTaskR } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers ResumeScheduledTaskResponse402Headers + var headers CreateSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86655,26 +87883,26 @@ func ParseResumeScheduledTaskResponse(rsp *http.Response) (*ResumeScheduledTaskR return response, nil } -// ParseRunScheduledTaskResponse parses an HTTP response from a RunScheduledTaskWithResponse call -func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskResponse, error) { +// ParseQuerySessionsResponse parses an HTTP response from a QuerySessionsWithResponse call +func ParseQuerySessionsResponse(rsp *http.Response) (*QuerySessionsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RunScheduledTaskResponse{ + response := &QuerySessionsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: - var dest ScheduledTaskRun + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SessionPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON202 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -86697,20 +87925,6 @@ func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskRespons } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -86718,13 +87932,6 @@ func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskRespons } response.JSON500 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 501: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON501 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -86735,8 +87942,8 @@ func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskRespons } switch { - case rsp.StatusCode == 202: - var headers RunScheduledTaskResponse202Headers + case rsp.StatusCode == 200: + var headers QuerySessionsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86765,9 +87972,9 @@ func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskRespons } headers.XStreamCostMicros = &value } - response.Headers202 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers RunScheduledTaskResponse402Headers + var headers QuerySessionsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86788,26 +87995,22 @@ func ParseRunScheduledTaskResponse(rsp *http.Response) (*RunScheduledTaskRespons return response, nil } -// ParseListScheduledTaskRunsResponse parses an HTTP response from a ListScheduledTaskRunsWithResponse call -func ParseListScheduledTaskRunsResponse(rsp *http.Response) (*ListScheduledTaskRunsResponse, error) { +// ParseDeleteSessionResponse parses an HTTP response from a DeleteSessionWithResponse call +func ParseDeleteSessionResponse(rsp *http.Response) (*DeleteSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListScheduledTaskRunsResponse{ + response := &DeleteSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ScheduledTaskRunPage - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -86830,13 +88033,6 @@ func ParseListScheduledTaskRunsResponse(rsp *http.Response) (*ListScheduledTaskR } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -86861,8 +88057,8 @@ func ParseListScheduledTaskRunsResponse(rsp *http.Response) (*ListScheduledTaskR } switch { - case rsp.StatusCode == 200: - var headers ListScheduledTaskRunsResponse200Headers + case rsp.StatusCode == 204: + var headers DeleteSessionResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86891,9 +88087,9 @@ func ParseListScheduledTaskRunsResponse(rsp *http.Response) (*ListScheduledTaskR } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers ListScheduledTaskRunsResponse402Headers + var headers DeleteSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -86914,26 +88110,26 @@ func ParseListScheduledTaskRunsResponse(rsp *http.Response) (*ListScheduledTaskR return response, nil } -// ParseCreateSessionResponse parses an HTTP response from a CreateSessionWithResponse call -func ParseCreateSessionResponse(rsp *http.Response) (*CreateSessionResponse, error) { +// ParseGetSessionResponse parses an HTTP response from a GetSessionWithResponse call +func ParseGetSessionResponse(rsp *http.Response) (*GetSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateSessionResponse{ + response := &GetSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest Session if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -86970,13 +88166,6 @@ func ParseCreateSessionResponse(rsp *http.Response) (*CreateSessionResponse, err } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -86994,8 +88183,8 @@ func ParseCreateSessionResponse(rsp *http.Response) (*CreateSessionResponse, err } switch { - case rsp.StatusCode == 201: - var headers CreateSessionResponse201Headers + case rsp.StatusCode == 200: + var headers GetSessionResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87024,9 +88213,9 @@ func ParseCreateSessionResponse(rsp *http.Response) (*CreateSessionResponse, err } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateSessionResponse402Headers + var headers GetSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87047,22 +88236,22 @@ func ParseCreateSessionResponse(rsp *http.Response) (*CreateSessionResponse, err return response, nil } -// ParseQuerySessionsResponse parses an HTTP response from a QuerySessionsWithResponse call -func ParseQuerySessionsResponse(rsp *http.Response) (*QuerySessionsResponse, error) { +// ParseUpdateSessionResponse parses an HTTP response from a UpdateSessionWithResponse call +func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &QuerySessionsResponse{ + response := &UpdateSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest SessionPage + var dest Session if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -87089,113 +88278,12 @@ func ParseQuerySessionsResponse(rsp *http.Response) (*QuerySessionsResponse, err } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 200: - var headers QuerySessionsResponse200Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers200 = &headers - case rsp.StatusCode == 402: - var headers QuerySessionsResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseDeleteSessionResponse parses an HTTP response from a DeleteSessionWithResponse call -func ParseDeleteSessionResponse(rsp *http.Response) (*DeleteSessionResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &DeleteSessionResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.StatusCode == 204: - break // No content-type - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON402 = &dest + response.JSON403 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound @@ -87221,8 +88309,8 @@ func ParseDeleteSessionResponse(rsp *http.Response) (*DeleteSessionResponse, err } switch { - case rsp.StatusCode == 204: - var headers DeleteSessionResponse204Headers + case rsp.StatusCode == 200: + var headers UpdateSessionResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87251,9 +88339,9 @@ func ParseDeleteSessionResponse(rsp *http.Response) (*DeleteSessionResponse, err } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteSessionResponse402Headers + var headers UpdateSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87274,22 +88362,22 @@ func ParseDeleteSessionResponse(rsp *http.Response) (*DeleteSessionResponse, err return response, nil } -// ParseGetSessionResponse parses an HTTP response from a GetSessionWithResponse call -func ParseGetSessionResponse(rsp *http.Response) (*GetSessionResponse, error) { +// ParseGetSessionCommandResponse parses an HTTP response from a GetSessionCommandWithResponse call +func ParseGetSessionCommandResponse(rsp *http.Response) (*GetSessionCommandResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetSessionResponse{ + response := &GetSessionCommandResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Session + var dest CommandReceipt if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -87316,13 +88404,6 @@ func ParseGetSessionResponse(rsp *http.Response) (*GetSessionResponse, error) { } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -87348,7 +88429,7 @@ func ParseGetSessionResponse(rsp *http.Response) (*GetSessionResponse, error) { switch { case rsp.StatusCode == 200: - var headers GetSessionResponse200Headers + var headers GetSessionCommandResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87379,7 +88460,7 @@ func ParseGetSessionResponse(rsp *http.Response) (*GetSessionResponse, error) { } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetSessionResponse402Headers + var headers GetSessionCommandResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87400,22 +88481,22 @@ func ParseGetSessionResponse(rsp *http.Response) (*GetSessionResponse, error) { return response, nil } -// ParseUpdateSessionResponse parses an HTTP response from a UpdateSessionWithResponse call -func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, error) { +// ParseInterruptSessionCommandResponse parses an HTTP response from a InterruptSessionCommandWithResponse call +func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSessionCommandResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateSessionResponse{ + response := &InterruptSessionCommandResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Session + var dest CommandReceipt if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -87442,13 +88523,6 @@ func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, err } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -87464,7 +88538,7 @@ func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, err response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -87474,7 +88548,7 @@ func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, err switch { case rsp.StatusCode == 200: - var headers UpdateSessionResponse200Headers + var headers InterruptSessionCommandResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87505,7 +88579,7 @@ func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, err } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers UpdateSessionResponse402Headers + var headers InterruptSessionCommandResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87526,26 +88600,26 @@ func ParseUpdateSessionResponse(rsp *http.Response) (*UpdateSessionResponse, err return response, nil } -// ParseGetSessionCommandResponse parses an HTTP response from a GetSessionCommandWithResponse call -func ParseGetSessionCommandResponse(rsp *http.Response) (*GetSessionCommandResponse, error) { +// ParseForkSessionResponse parses an HTTP response from a ForkSessionWithResponse call +func ParseForkSessionResponse(rsp *http.Response) (*ForkSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetSessionCommandResponse{ + response := &ForkSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CommandReceipt + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Session if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -87568,6 +88642,13 @@ func ParseGetSessionCommandResponse(rsp *http.Response) (*GetSessionCommandRespo } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -87592,8 +88673,8 @@ func ParseGetSessionCommandResponse(rsp *http.Response) (*GetSessionCommandRespo } switch { - case rsp.StatusCode == 200: - var headers GetSessionCommandResponse200Headers + case rsp.StatusCode == 201: + var headers ForkSessionResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87622,9 +88703,9 @@ func ParseGetSessionCommandResponse(rsp *http.Response) (*GetSessionCommandRespo } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers GetSessionCommandResponse402Headers + var headers ForkSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87645,26 +88726,22 @@ func ParseGetSessionCommandResponse(rsp *http.Response) (*GetSessionCommandRespo return response, nil } -// ParseInterruptSessionCommandResponse parses an HTTP response from a InterruptSessionCommandWithResponse call -func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSessionCommandResponse, error) { +// ParseInterruptSessionResponse parses an HTTP response from a InterruptSessionWithResponse call +func ParseInterruptSessionResponse(rsp *http.Response) (*InterruptSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &InterruptSessionCommandResponse{ + response := &InterruptSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CommandReceipt - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -87687,6 +88764,13 @@ func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSession } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -87702,7 +88786,7 @@ func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSession response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -87711,8 +88795,8 @@ func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSession } switch { - case rsp.StatusCode == 200: - var headers InterruptSessionCommandResponse200Headers + case rsp.StatusCode == 204: + var headers InterruptSessionResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87741,9 +88825,9 @@ func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSession } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers InterruptSessionCommandResponse402Headers + var headers InterruptSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87764,26 +88848,22 @@ func ParseInterruptSessionCommandResponse(rsp *http.Response) (*InterruptSession return response, nil } -// ParseForkSessionResponse parses an HTTP response from a ForkSessionWithResponse call -func ParseForkSessionResponse(rsp *http.Response) (*ForkSessionResponse, error) { +// ParseDeleteSessionMemoriesResponse parses an HTTP response from a DeleteSessionMemoriesWithResponse call +func ParseDeleteSessionMemoriesResponse(rsp *http.Response) (*DeleteSessionMemoriesResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ForkSessionResponse{ + response := &DeleteSessionMemoriesResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest Session - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON201 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -87837,8 +88917,8 @@ func ParseForkSessionResponse(rsp *http.Response) (*ForkSessionResponse, error) } switch { - case rsp.StatusCode == 201: - var headers ForkSessionResponse201Headers + case rsp.StatusCode == 204: + var headers DeleteSessionMemoriesResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87867,9 +88947,9 @@ func ParseForkSessionResponse(rsp *http.Response) (*ForkSessionResponse, error) } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers ForkSessionResponse402Headers + var headers DeleteSessionMemoriesResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87890,20 +88970,27 @@ func ParseForkSessionResponse(rsp *http.Response) (*ForkSessionResponse, error) return response, nil } -// ParseInterruptSessionResponse parses an HTTP response from a InterruptSessionWithResponse call -func ParseInterruptSessionResponse(rsp *http.Response) (*InterruptSessionResponse, error) { +// ParseRespondSessionResponse parses an HTTP response from a RespondSessionWithResponse call +func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &InterruptSessionResponse{ + response := &RespondSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CommandReceipt + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + case rsp.StatusCode == 204: break // No content-type @@ -87942,6 +89029,13 @@ func ParseInterruptSessionResponse(rsp *http.Response) (*InterruptSessionRespons } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -87959,8 +89053,39 @@ func ParseInterruptSessionResponse(rsp *http.Response) (*InterruptSessionRespons } switch { + case rsp.StatusCode == 200: + var headers RespondSessionResponse200Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers200 = &headers case rsp.StatusCode == 204: - var headers InterruptSessionResponse204Headers + var headers RespondSessionResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -87991,7 +89116,7 @@ func ParseInterruptSessionResponse(rsp *http.Response) (*InterruptSessionRespons } response.Headers204 = &headers case rsp.StatusCode == 402: - var headers InterruptSessionResponse402Headers + var headers RespondSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88012,22 +89137,26 @@ func ParseInterruptSessionResponse(rsp *http.Response) (*InterruptSessionRespons return response, nil } -// ParseDeleteSessionMemoriesResponse parses an HTTP response from a DeleteSessionMemoriesWithResponse call -func ParseDeleteSessionMemoriesResponse(rsp *http.Response) (*DeleteSessionMemoriesResponse, error) { +// ParseListResponsesResponse parses an HTTP response from a ListResponsesWithResponse call +func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteSessionMemoriesResponse{ + response := &ListResponsesResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest AgentResponsePage + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -88081,8 +89210,8 @@ func ParseDeleteSessionMemoriesResponse(rsp *http.Response) (*DeleteSessionMemor } switch { - case rsp.StatusCode == 204: - var headers DeleteSessionMemoriesResponse204Headers + case rsp.StatusCode == 200: + var headers ListResponsesResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88111,9 +89240,9 @@ func ParseDeleteSessionMemoriesResponse(rsp *http.Response) (*DeleteSessionMemor } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteSessionMemoriesResponse402Headers + var headers ListResponsesResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88134,29 +89263,26 @@ func ParseDeleteSessionMemoriesResponse(rsp *http.Response) (*DeleteSessionMemor return response, nil } -// ParseRespondSessionResponse parses an HTTP response from a RespondSessionWithResponse call -func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, error) { +// ParseCreateResponseResponse parses an HTTP response from a CreateResponseWithResponse call +func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RespondSessionResponse{ + response := &CreateResponseResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CommandReceipt + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: + var dest AgentResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest - - case rsp.StatusCode == 204: - break // No content-type + response.JSON202 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -88208,7 +89334,7 @@ func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, e response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88217,8 +89343,8 @@ func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, e } switch { - case rsp.StatusCode == 200: - var headers RespondSessionResponse200Headers + case rsp.StatusCode == 202: + var headers CreateResponseResponse202Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88247,9 +89373,104 @@ func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, e } headers.XStreamCostMicros = &value } - response.Headers200 = &headers - case rsp.StatusCode == 204: - var headers RespondSessionResponse204Headers + response.Headers202 = &headers + case rsp.StatusCode == 402: + var headers CreateResponseResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseListResponseItemsResponse parses an HTTP response from a ListResponseItemsWithResponse call +func ParseListResponseItemsResponse(rsp *http.Response) (*ListResponseItemsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListResponseItemsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest AgentResponseItemPage + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 200: + var headers ListResponseItemsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88278,9 +89499,9 @@ func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, e } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers RespondSessionResponse402Headers + var headers ListResponseItemsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88301,22 +89522,22 @@ func ParseRespondSessionResponse(rsp *http.Response) (*RespondSessionResponse, e return response, nil } -// ParseListResponsesResponse parses an HTTP response from a ListResponsesWithResponse call -func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, error) { +// ParseActivateResponseResponse parses an HTTP response from a ActivateResponseWithResponse call +func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListResponsesResponse{ + response := &ActivateResponseResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest AgentResponsePage + var dest ActivatedBranch if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88357,6 +89578,20 @@ func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, err } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 410: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON410 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -88365,7 +89600,7 @@ func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, err response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88375,7 +89610,7 @@ func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, err switch { case rsp.StatusCode == 200: - var headers ListResponsesResponse200Headers + var headers ActivateResponseResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88406,7 +89641,7 @@ func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, err } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListResponsesResponse402Headers + var headers ActivateResponseResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88427,26 +89662,26 @@ func ParseListResponsesResponse(rsp *http.Response) (*ListResponsesResponse, err return response, nil } -// ParseCreateResponseResponse parses an HTTP response from a CreateResponseWithResponse call -func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, error) { +// ParseGetResponseBranchResponse parses an HTTP response from a GetResponseBranchWithResponse call +func ParseGetResponseBranchResponse(rsp *http.Response) (*GetResponseBranchResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateResponseResponse{ + response := &GetResponseBranchResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: - var dest AgentResponse + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BranchMessagePage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON202 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -88483,12 +89718,12 @@ func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, e } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 410: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON409 = &dest + response.JSON410 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -88498,7 +89733,7 @@ func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, e response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88507,8 +89742,8 @@ func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, e } switch { - case rsp.StatusCode == 202: - var headers CreateResponseResponse202Headers + case rsp.StatusCode == 200: + var headers GetResponseBranchResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88537,9 +89772,9 @@ func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, e } headers.XStreamCostMicros = &value } - response.Headers202 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateResponseResponse402Headers + var headers GetResponseBranchResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88560,22 +89795,22 @@ func ParseCreateResponseResponse(rsp *http.Response) (*CreateResponseResponse, e return response, nil } -// ParseListResponseItemsResponse parses an HTTP response from a ListResponseItemsWithResponse call -func ParseListResponseItemsResponse(rsp *http.Response) (*ListResponseItemsResponse, error) { +// ParseListResponseSiblingsResponse parses an HTTP response from a ListResponseSiblingsWithResponse call +func ParseListResponseSiblingsResponse(rsp *http.Response) (*ListResponseSiblingsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListResponseItemsResponse{ + response := &ListResponseSiblingsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest AgentResponseItemPage + var dest ResponseSiblingPage if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88634,7 +89869,7 @@ func ParseListResponseItemsResponse(rsp *http.Response) (*ListResponseItemsRespo switch { case rsp.StatusCode == 200: - var headers ListResponseItemsResponse200Headers + var headers ListResponseSiblingsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88665,7 +89900,7 @@ func ParseListResponseItemsResponse(rsp *http.Response) (*ListResponseItemsRespo } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListResponseItemsResponse402Headers + var headers ListResponseSiblingsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88686,22 +89921,22 @@ func ParseListResponseItemsResponse(rsp *http.Response) (*ListResponseItemsRespo return response, nil } -// ParseActivateResponseResponse parses an HTTP response from a ActivateResponseWithResponse call -func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseResponse, error) { +// ParseResumeSessionResponse parses an HTTP response from a ResumeSessionWithResponse call +func ParseResumeSessionResponse(rsp *http.Response) (*ResumeSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ActivateResponseResponse{ + response := &ResumeSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ActivatedBranch + var dest Session if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88742,20 +89977,6 @@ func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseRespons } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 410: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON410 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -88764,7 +89985,7 @@ func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseRespons response.JSON500 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest ErrorResponse + var dest Unavailable if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -88774,7 +89995,7 @@ func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseRespons switch { case rsp.StatusCode == 200: - var headers ActivateResponseResponse200Headers + var headers ResumeSessionResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88805,7 +90026,7 @@ func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ActivateResponseResponse402Headers + var headers ResumeSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88826,26 +90047,22 @@ func ParseActivateResponseResponse(rsp *http.Response) (*ActivateResponseRespons return response, nil } -// ParseGetResponseBranchResponse parses an HTTP response from a GetResponseBranchWithResponse call -func ParseGetResponseBranchResponse(rsp *http.Response) (*GetResponseBranchResponse, error) { +// ParseRewindSessionResponse parses an HTTP response from a RewindSessionWithResponse call +func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetResponseBranchResponse{ + response := &RewindSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest BranchMessagePage - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -88882,12 +90099,12 @@ func ParseGetResponseBranchResponse(rsp *http.Response) (*GetResponseBranchRespo } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 410: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON410 = &dest + response.JSON409 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -88906,8 +90123,8 @@ func ParseGetResponseBranchResponse(rsp *http.Response) (*GetResponseBranchRespo } switch { - case rsp.StatusCode == 200: - var headers GetResponseBranchResponse200Headers + case rsp.StatusCode == 204: + var headers RewindSessionResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88936,9 +90153,9 @@ func ParseGetResponseBranchResponse(rsp *http.Response) (*GetResponseBranchRespo } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers GetResponseBranchResponse402Headers + var headers RewindSessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -88959,26 +90176,22 @@ func ParseGetResponseBranchResponse(rsp *http.Response) (*GetResponseBranchRespo return response, nil } -// ParseListResponseSiblingsResponse parses an HTTP response from a ListResponseSiblingsWithResponse call -func ParseListResponseSiblingsResponse(rsp *http.Response) (*ListResponseSiblingsResponse, error) { +// ParseSaySessionResponse parses an HTTP response from a SaySessionWithResponse call +func ParseSaySessionResponse(rsp *http.Response) (*SaySessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListResponseSiblingsResponse{ + response := &SaySessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ResponseSiblingPage - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -89032,8 +90245,8 @@ func ParseListResponseSiblingsResponse(rsp *http.Response) (*ListResponseSibling } switch { - case rsp.StatusCode == 200: - var headers ListResponseSiblingsResponse200Headers + case rsp.StatusCode == 204: + var headers SaySessionResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89062,9 +90275,9 @@ func ParseListResponseSiblingsResponse(rsp *http.Response) (*ListResponseSibling } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers ListResponseSiblingsResponse402Headers + var headers SaySessionResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89085,15 +90298,15 @@ func ParseListResponseSiblingsResponse(rsp *http.Response) (*ListResponseSibling return response, nil } -// ParseResumeSessionResponse parses an HTTP response from a ResumeSessionWithResponse call -func ParseResumeSessionResponse(rsp *http.Response) (*ResumeSessionResponse, error) { +// ParseSetSessionSettingsResponse parses an HTTP response from a SetSessionSettingsWithResponse call +func ParseSetSessionSettingsResponse(rsp *http.Response) (*SetSessionSettingsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ResumeSessionResponse{ + response := &SetSessionSettingsResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -89159,7 +90372,7 @@ func ParseResumeSessionResponse(rsp *http.Response) (*ResumeSessionResponse, err switch { case rsp.StatusCode == 200: - var headers ResumeSessionResponse200Headers + var headers SetSessionSettingsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89190,7 +90403,7 @@ func ParseResumeSessionResponse(rsp *http.Response) (*ResumeSessionResponse, err } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ResumeSessionResponse402Headers + var headers SetSessionSettingsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89211,15 +90424,15 @@ func ParseResumeSessionResponse(rsp *http.Response) (*ResumeSessionResponse, err return response, nil } -// ParseRewindSessionResponse parses an HTTP response from a RewindSessionWithResponse call -func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, error) { +// ParseStopSessionResponse parses an HTTP response from a StopSessionWithResponse call +func ParseStopSessionResponse(rsp *http.Response) (*StopSessionResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RewindSessionResponse{ + response := &StopSessionResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -89249,6 +90462,125 @@ func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, err } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFound + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Unavailable + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + switch { + case rsp.StatusCode == 204: + var headers StopSessionResponse204Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamCostEstimated = &value + } + if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamCostMicros = &value + } + response.Headers204 = &headers + case rsp.StatusCode == 402: + var headers StopSessionResponse402Headers + if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { + var value int64 + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { + return nil, err + } + headers.XStreamBalanceMicros = &value + } + if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { + var value string + if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { + return nil, err + } + headers.XStreamBalanceWarning = &value + } + response.Headers402 = &headers + } + + return response, nil +} + +// ParseGetSessionTokensResponse parses an HTTP response from a GetSessionTokensWithResponse call +func ParseGetSessionTokensResponse(rsp *http.Response) (*GetSessionTokensResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetSessionTokensResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CallTokens + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Unauthorized + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest PaymentRequired + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: var dest Forbidden if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -89263,13 +90595,6 @@ func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, err } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -89287,8 +90612,8 @@ func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, err } switch { - case rsp.StatusCode == 204: - var headers RewindSessionResponse204Headers + case rsp.StatusCode == 200: + var headers GetSessionTokensResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89317,9 +90642,9 @@ func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, err } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers RewindSessionResponse402Headers + var headers GetSessionTokensResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89340,22 +90665,26 @@ func ParseRewindSessionResponse(rsp *http.Response) (*RewindSessionResponse, err return response, nil } -// ParseSaySessionResponse parses an HTTP response from a SaySessionWithResponse call -func ParseSaySessionResponse(rsp *http.Response) (*SaySessionResponse, error) { +// ParseListSessionToolsResponse parses an HTTP response from a ListSessionToolsWithResponse call +func ParseListSessionToolsResponse(rsp *http.Response) (*ListSessionToolsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &SaySessionResponse{ + response := &ListSessionToolsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest OfferedTools + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -89378,13 +90707,6 @@ func ParseSaySessionResponse(rsp *http.Response) (*SaySessionResponse, error) { } response.JSON402 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -89409,8 +90731,8 @@ func ParseSaySessionResponse(rsp *http.Response) (*SaySessionResponse, error) { } switch { - case rsp.StatusCode == 204: - var headers SaySessionResponse204Headers + case rsp.StatusCode == 200: + var headers ListSessionToolsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89439,9 +90761,9 @@ func ParseSaySessionResponse(rsp *http.Response) (*SaySessionResponse, error) { } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers SaySessionResponse402Headers + var headers ListSessionToolsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89462,26 +90784,22 @@ func ParseSaySessionResponse(rsp *http.Response) (*SaySessionResponse, error) { return response, nil } -// ParseSetSessionSettingsResponse parses an HTTP response from a SetSessionSettingsWithResponse call -func ParseSetSessionSettingsResponse(rsp *http.Response) (*SetSessionSettingsResponse, error) { +// ParseAddSessionToolsResponse parses an HTTP response from a AddSessionToolsWithResponse call +func ParseAddSessionToolsResponse(rsp *http.Response) (*AddSessionToolsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &SetSessionSettingsResponse{ + response := &AddSessionToolsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Session - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -89518,120 +90836,12 @@ func ParseSetSessionSettingsResponse(rsp *http.Response) (*SetSessionSettingsRes } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 200: - var headers SetSessionSettingsResponse200Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers200 = &headers - case rsp.StatusCode == 402: - var headers SetSessionSettingsResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseStopSessionResponse parses an HTTP response from a StopSessionWithResponse call -func ParseStopSessionResponse(rsp *http.Response) (*StopSessionResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &StopSessionResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case rsp.StatusCode == 204: - break // No content-type - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON402 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON404 = &dest + response.JSON409 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -89651,7 +90861,7 @@ func ParseStopSessionResponse(rsp *http.Response) (*StopSessionResponse, error) switch { case rsp.StatusCode == 204: - var headers StopSessionResponse204Headers + var headers AddSessionToolsResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89682,7 +90892,7 @@ func ParseStopSessionResponse(rsp *http.Response) (*StopSessionResponse, error) } response.Headers204 = &headers case rsp.StatusCode == 402: - var headers StopSessionResponse402Headers + var headers AddSessionToolsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89703,26 +90913,22 @@ func ParseStopSessionResponse(rsp *http.Response) (*StopSessionResponse, error) return response, nil } -// ParseGetSessionTokensResponse parses an HTTP response from a GetSessionTokensWithResponse call -func ParseGetSessionTokensResponse(rsp *http.Response) (*GetSessionTokensResponse, error) { +// ParseRemoveSessionToolResponse parses an HTTP response from a RemoveSessionToolWithResponse call +func ParseRemoveSessionToolResponse(rsp *http.Response) (*RemoveSessionToolResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetSessionTokensResponse{ + response := &RemoveSessionToolResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest CallTokens - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -89776,8 +90982,8 @@ func ParseGetSessionTokensResponse(rsp *http.Response) (*GetSessionTokensRespons } switch { - case rsp.StatusCode == 200: - var headers GetSessionTokensResponse200Headers + case rsp.StatusCode == 204: + var headers RemoveSessionToolResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89806,9 +91012,9 @@ func ParseGetSessionTokensResponse(rsp *http.Response) (*GetSessionTokensRespons } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers GetSessionTokensResponse402Headers + var headers RemoveSessionToolResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89829,22 +91035,22 @@ func ParseGetSessionTokensResponse(rsp *http.Response) (*GetSessionTokensRespons return response, nil } -// ParseListSessionToolsResponse parses an HTTP response from a ListSessionToolsWithResponse call -func ParseListSessionToolsResponse(rsp *http.Response) (*ListSessionToolsResponse, error) { +// ParseStopSessionVoiceResponse parses an HTTP response from a StopSessionVoiceWithResponse call +func ParseStopSessionVoiceResponse(rsp *http.Response) (*StopSessionVoiceResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListSessionToolsResponse{ + response := &StopSessionVoiceResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest OfferedTools + var dest Session if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -89896,7 +91102,7 @@ func ParseListSessionToolsResponse(rsp *http.Response) (*ListSessionToolsRespons switch { case rsp.StatusCode == 200: - var headers ListSessionToolsResponse200Headers + var headers StopSessionVoiceResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89927,7 +91133,7 @@ func ParseListSessionToolsResponse(rsp *http.Response) (*ListSessionToolsRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListSessionToolsResponse402Headers + var headers StopSessionVoiceResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -89948,22 +91154,26 @@ func ParseListSessionToolsResponse(rsp *http.Response) (*ListSessionToolsRespons return response, nil } -// ParseAddSessionToolsResponse parses an HTTP response from a AddSessionToolsWithResponse call -func ParseAddSessionToolsResponse(rsp *http.Response) (*AddSessionToolsResponse, error) { +// ParseStartSessionVoiceResponse parses an HTTP response from a StartSessionVoiceWithResponse call +func ParseStartSessionVoiceResponse(rsp *http.Response) (*StartSessionVoiceResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &AddSessionToolsResponse{ + response := &StartSessionVoiceResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Session + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -90024,8 +91234,8 @@ func ParseAddSessionToolsResponse(rsp *http.Response) (*AddSessionToolsResponse, } switch { - case rsp.StatusCode == 204: - var headers AddSessionToolsResponse204Headers + case rsp.StatusCode == 200: + var headers StartSessionVoiceResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90054,9 +91264,9 @@ func ParseAddSessionToolsResponse(rsp *http.Response) (*AddSessionToolsResponse, } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers AddSessionToolsResponse402Headers + var headers StartSessionVoiceResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90077,22 +91287,26 @@ func ParseAddSessionToolsResponse(rsp *http.Response) (*AddSessionToolsResponse, return response, nil } -// ParseRemoveSessionToolResponse parses an HTTP response from a RemoveSessionToolWithResponse call -func ParseRemoveSessionToolResponse(rsp *http.Response) (*RemoveSessionToolResponse, error) { +// ParseListSimulationRunsResponse parses an HTTP response from a ListSimulationRunsWithResponse call +func ParseListSimulationRunsResponse(rsp *http.Response) (*ListSimulationRunsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RemoveSessionToolResponse{ + response := &ListSimulationRunsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []SimulationRun + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -90122,13 +91336,6 @@ func ParseRemoveSessionToolResponse(rsp *http.Response) (*RemoveSessionToolRespo } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -90146,8 +91353,8 @@ func ParseRemoveSessionToolResponse(rsp *http.Response) (*RemoveSessionToolRespo } switch { - case rsp.StatusCode == 204: - var headers RemoveSessionToolResponse204Headers + case rsp.StatusCode == 200: + var headers ListSimulationRunsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90176,9 +91383,9 @@ func ParseRemoveSessionToolResponse(rsp *http.Response) (*RemoveSessionToolRespo } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers RemoveSessionToolResponse402Headers + var headers ListSimulationRunsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90199,22 +91406,22 @@ func ParseRemoveSessionToolResponse(rsp *http.Response) (*RemoveSessionToolRespo return response, nil } -// ParseStopSessionVoiceResponse parses an HTTP response from a StopSessionVoiceWithResponse call -func ParseStopSessionVoiceResponse(rsp *http.Response) (*StopSessionVoiceResponse, error) { +// ParseGetSimulationRunResponse parses an HTTP response from a GetSimulationRunWithResponse call +func ParseGetSimulationRunResponse(rsp *http.Response) (*GetSimulationRunResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &StopSessionVoiceResponse{ + response := &GetSimulationRunResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Session + var dest SimulationRun if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -90241,6 +91448,13 @@ func ParseStopSessionVoiceResponse(rsp *http.Response) (*StopSessionVoiceRespons } response.JSON402 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Forbidden + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest NotFound if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -90266,7 +91480,7 @@ func ParseStopSessionVoiceResponse(rsp *http.Response) (*StopSessionVoiceRespons switch { case rsp.StatusCode == 200: - var headers StopSessionVoiceResponse200Headers + var headers GetSimulationRunResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90297,7 +91511,7 @@ func ParseStopSessionVoiceResponse(rsp *http.Response) (*StopSessionVoiceRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers StopSessionVoiceResponse402Headers + var headers GetSimulationRunResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90318,22 +91532,22 @@ func ParseStopSessionVoiceResponse(rsp *http.Response) (*StopSessionVoiceRespons return response, nil } -// ParseStartSessionVoiceResponse parses an HTTP response from a StartSessionVoiceWithResponse call -func ParseStartSessionVoiceResponse(rsp *http.Response) (*StartSessionVoiceResponse, error) { +// ParseCancelSimulationRunResponse parses an HTTP response from a CancelSimulationRunWithResponse call +func ParseCancelSimulationRunResponse(rsp *http.Response) (*CancelSimulationRunResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &StartSessionVoiceResponse{ + response := &CancelSimulationRunResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Session + var dest SimulationRun if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -90374,13 +91588,6 @@ func ParseStartSessionVoiceResponse(rsp *http.Response) (*StartSessionVoiceRespo } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -90399,7 +91606,7 @@ func ParseStartSessionVoiceResponse(rsp *http.Response) (*StartSessionVoiceRespo switch { case rsp.StatusCode == 200: - var headers StartSessionVoiceResponse200Headers + var headers CancelSimulationRunResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90430,7 +91637,7 @@ func ParseStartSessionVoiceResponse(rsp *http.Response) (*StartSessionVoiceRespo } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers StartSessionVoiceResponse402Headers + var headers CancelSimulationRunResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90451,22 +91658,22 @@ func ParseStartSessionVoiceResponse(rsp *http.Response) (*StartSessionVoiceRespo return response, nil } -// ParseListSimulationRunsResponse parses an HTTP response from a ListSimulationRunsWithResponse call -func ParseListSimulationRunsResponse(rsp *http.Response) (*ListSimulationRunsResponse, error) { +// ParseListSimulationsResponse parses an HTTP response from a ListSimulationsWithResponse call +func ParseListSimulationsResponse(rsp *http.Response) (*ListSimulationsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListSimulationRunsResponse{ + response := &ListSimulationsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []SimulationRun + var dest []Simulation if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -90518,7 +91725,7 @@ func ParseListSimulationRunsResponse(rsp *http.Response) (*ListSimulationRunsRes switch { case rsp.StatusCode == 200: - var headers ListSimulationRunsResponse200Headers + var headers ListSimulationsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90549,7 +91756,7 @@ func ParseListSimulationRunsResponse(rsp *http.Response) (*ListSimulationRunsRes } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers ListSimulationRunsResponse402Headers + var headers ListSimulationsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90570,26 +91777,26 @@ func ParseListSimulationRunsResponse(rsp *http.Response) (*ListSimulationRunsRes return response, nil } -// ParseGetSimulationRunResponse parses an HTTP response from a GetSimulationRunWithResponse call -func ParseGetSimulationRunResponse(rsp *http.Response) (*GetSimulationRunResponse, error) { +// ParseCreateSimulationResponse parses an HTTP response from a CreateSimulationWithResponse call +func ParseCreateSimulationResponse(rsp *http.Response) (*CreateSimulationResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetSimulationRunResponse{ + response := &CreateSimulationResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest SimulationRun + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Simulation if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -90643,8 +91850,8 @@ func ParseGetSimulationRunResponse(rsp *http.Response) (*GetSimulationRunRespons } switch { - case rsp.StatusCode == 200: - var headers GetSimulationRunResponse200Headers + case rsp.StatusCode == 201: + var headers CreateSimulationResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90673,9 +91880,9 @@ func ParseGetSimulationRunResponse(rsp *http.Response) (*GetSimulationRunRespons } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers GetSimulationRunResponse402Headers + var headers CreateSimulationResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90696,26 +91903,22 @@ func ParseGetSimulationRunResponse(rsp *http.Response) (*GetSimulationRunRespons return response, nil } -// ParseCancelSimulationRunResponse parses an HTTP response from a CancelSimulationRunWithResponse call -func ParseCancelSimulationRunResponse(rsp *http.Response) (*CancelSimulationRunResponse, error) { +// ParseDeleteSimulationResponse parses an HTTP response from a DeleteSimulationWithResponse call +func ParseDeleteSimulationResponse(rsp *http.Response) (*DeleteSimulationResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CancelSimulationRunResponse{ + response := &DeleteSimulationResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest SimulationRun - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -90769,8 +91972,8 @@ func ParseCancelSimulationRunResponse(rsp *http.Response) (*CancelSimulationRunR } switch { - case rsp.StatusCode == 200: - var headers CancelSimulationRunResponse200Headers + case rsp.StatusCode == 204: + var headers DeleteSimulationResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90799,9 +92002,9 @@ func ParseCancelSimulationRunResponse(rsp *http.Response) (*CancelSimulationRunR } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers CancelSimulationRunResponse402Headers + var headers DeleteSimulationResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -90822,145 +92025,26 @@ func ParseCancelSimulationRunResponse(rsp *http.Response) (*CancelSimulationRunR return response, nil } -// ParseListSimulationsResponse parses an HTTP response from a ListSimulationsWithResponse call -func ParseListSimulationsResponse(rsp *http.Response) (*ListSimulationsResponse, error) { +// ParseGetSimulationResponse parses an HTTP response from a GetSimulationWithResponse call +func ParseGetSimulationResponse(rsp *http.Response) (*GetSimulationResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListSimulationsResponse{ + response := &GetSimulationResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []Simulation - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON402 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON403 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 200: - var headers ListSimulationsResponse200Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers200 = &headers - case rsp.StatusCode == 402: - var headers ListSimulationsResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseCreateSimulationResponse parses an HTTP response from a CreateSimulationWithResponse call -func ParseCreateSimulationResponse(rsp *http.Response) (*CreateSimulationResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &CreateSimulationResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: var dest Simulation if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON201 = &dest + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -91014,8 +92098,8 @@ func ParseCreateSimulationResponse(rsp *http.Response) (*CreateSimulationRespons } switch { - case rsp.StatusCode == 201: - var headers CreateSimulationResponse201Headers + case rsp.StatusCode == 200: + var headers GetSimulationResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91044,9 +92128,9 @@ func ParseCreateSimulationResponse(rsp *http.Response) (*CreateSimulationRespons } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers CreateSimulationResponse402Headers + var headers GetSimulationResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91067,22 +92151,26 @@ func ParseCreateSimulationResponse(rsp *http.Response) (*CreateSimulationRespons return response, nil } -// ParseDeleteSimulationResponse parses an HTTP response from a DeleteSimulationWithResponse call -func ParseDeleteSimulationResponse(rsp *http.Response) (*DeleteSimulationResponse, error) { +// ParseUpdateSimulationResponse parses an HTTP response from a UpdateSimulationWithResponse call +func ParseUpdateSimulationResponse(rsp *http.Response) (*UpdateSimulationResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteSimulationResponse{ + response := &UpdateSimulationResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Simulation + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -91136,8 +92224,8 @@ func ParseDeleteSimulationResponse(rsp *http.Response) (*DeleteSimulationRespons } switch { - case rsp.StatusCode == 204: - var headers DeleteSimulationResponse204Headers + case rsp.StatusCode == 200: + var headers UpdateSimulationResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91166,9 +92254,9 @@ func ParseDeleteSimulationResponse(rsp *http.Response) (*DeleteSimulationRespons } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteSimulationResponse402Headers + var headers UpdateSimulationResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91189,26 +92277,26 @@ func ParseDeleteSimulationResponse(rsp *http.Response) (*DeleteSimulationRespons return response, nil } -// ParseGetSimulationResponse parses an HTTP response from a GetSimulationWithResponse call -func ParseGetSimulationResponse(rsp *http.Response) (*GetSimulationResponse, error) { +// ParseRunSimulationResponse parses an HTTP response from a RunSimulationWithResponse call +func ParseRunSimulationResponse(rsp *http.Response) (*RunSimulationResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetSimulationResponse{ + response := &RunSimulationResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Simulation + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: + var dest SimulationRun if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON200 = &dest + response.JSON202 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -91262,8 +92350,8 @@ func ParseGetSimulationResponse(rsp *http.Response) (*GetSimulationResponse, err } switch { - case rsp.StatusCode == 200: - var headers GetSimulationResponse200Headers + case rsp.StatusCode == 202: + var headers RunSimulationResponse202Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91292,9 +92380,9 @@ func ParseGetSimulationResponse(rsp *http.Response) (*GetSimulationResponse, err } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers202 = &headers case rsp.StatusCode == 402: - var headers GetSimulationResponse402Headers + var headers RunSimulationResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91315,22 +92403,22 @@ func ParseGetSimulationResponse(rsp *http.Response) (*GetSimulationResponse, err return response, nil } -// ParseUpdateSimulationResponse parses an HTTP response from a UpdateSimulationWithResponse call -func ParseUpdateSimulationResponse(rsp *http.Response) (*UpdateSimulationResponse, error) { +// ParseListSkillsResponse parses an HTTP response from a ListSkillsWithResponse call +func ParseListSkillsResponse(rsp *http.Response) (*ListSkillsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateSimulationResponse{ + response := &ListSkillsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Simulation + var dest []Skill if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -91364,13 +92452,6 @@ func ParseUpdateSimulationResponse(rsp *http.Response) (*UpdateSimulationRespons } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -91389,7 +92470,7 @@ func ParseUpdateSimulationResponse(rsp *http.Response) (*UpdateSimulationRespons switch { case rsp.StatusCode == 200: - var headers UpdateSimulationResponse200Headers + var headers ListSkillsResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91420,7 +92501,7 @@ func ParseUpdateSimulationResponse(rsp *http.Response) (*UpdateSimulationRespons } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers UpdateSimulationResponse402Headers + var headers ListSkillsResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91441,26 +92522,26 @@ func ParseUpdateSimulationResponse(rsp *http.Response) (*UpdateSimulationRespons return response, nil } -// ParseRunSimulationResponse parses an HTTP response from a RunSimulationWithResponse call -func ParseRunSimulationResponse(rsp *http.Response) (*RunSimulationResponse, error) { +// ParseCreateSkillResponse parses an HTTP response from a CreateSkillWithResponse call +func ParseCreateSkillResponse(rsp *http.Response) (*CreateSkillResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RunSimulationResponse{ + response := &CreateSkillResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 202: - var dest SimulationRun + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Skill if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON202 = &dest + response.JSON201 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -91497,124 +92578,12 @@ func ParseRunSimulationResponse(rsp *http.Response) (*RunSimulationResponse, err } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: - var dest InternalError - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON500 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: - var dest Unavailable - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON503 = &dest - - } - - switch { - case rsp.StatusCode == 202: - var headers RunSimulationResponse202Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Estimated"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Estimated", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamCostEstimated = &value - } - if values := rsp.Header.Values("X-Stream-Cost-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Cost-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamCostMicros = &value - } - response.Headers202 = &headers - case rsp.StatusCode == 402: - var headers RunSimulationResponse402Headers - if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { - var value int64 - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { - return nil, err - } - headers.XStreamBalanceMicros = &value - } - if values := rsp.Header.Values("X-Stream-Balance-Warning"); len(values) > 0 { - var value string - if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Warning", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "string", Format: ""}); err != nil { - return nil, err - } - headers.XStreamBalanceWarning = &value - } - response.Headers402 = &headers - } - - return response, nil -} - -// ParseListSkillsResponse parses an HTTP response from a ListSkillsWithResponse call -func ParseListSkillsResponse(rsp *http.Response) (*ListSkillsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ListSkillsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []Skill - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest BadRequest - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: - var dest Unauthorized - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON401 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: - var dest PaymentRequired - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON402 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: - var dest Forbidden + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON403 = &dest + response.JSON409 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError @@ -91633,8 +92602,8 @@ func ParseListSkillsResponse(rsp *http.Response) (*ListSkillsResponse, error) { } switch { - case rsp.StatusCode == 200: - var headers ListSkillsResponse200Headers + case rsp.StatusCode == 201: + var headers CreateSkillResponse201Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91663,9 +92632,9 @@ func ParseListSkillsResponse(rsp *http.Response) (*ListSkillsResponse, error) { } headers.XStreamCostMicros = &value } - response.Headers200 = &headers + response.Headers201 = &headers case rsp.StatusCode == 402: - var headers ListSkillsResponse402Headers + var headers CreateSkillResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91686,26 +92655,22 @@ func ParseListSkillsResponse(rsp *http.Response) (*ListSkillsResponse, error) { return response, nil } -// ParseCreateSkillResponse parses an HTTP response from a CreateSkillWithResponse call -func ParseCreateSkillResponse(rsp *http.Response) (*CreateSkillResponse, error) { +// ParseDeleteSkillResponse parses an HTTP response from a DeleteSkillWithResponse call +func ParseDeleteSkillResponse(rsp *http.Response) (*DeleteSkillResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateSkillResponse{ + response := &DeleteSkillResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: - var dest Skill - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON201 = &dest + case rsp.StatusCode == 204: + break // No content-type case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -91742,13 +92707,6 @@ func ParseCreateSkillResponse(rsp *http.Response) (*CreateSkillResponse, error) } response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: - var dest ErrorResponse - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON409 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -91766,8 +92724,8 @@ func ParseCreateSkillResponse(rsp *http.Response) (*CreateSkillResponse, error) } switch { - case rsp.StatusCode == 201: - var headers CreateSkillResponse201Headers + case rsp.StatusCode == 204: + var headers DeleteSkillResponse204Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91796,9 +92754,9 @@ func ParseCreateSkillResponse(rsp *http.Response) (*CreateSkillResponse, error) } headers.XStreamCostMicros = &value } - response.Headers201 = &headers + response.Headers204 = &headers case rsp.StatusCode == 402: - var headers CreateSkillResponse402Headers + var headers DeleteSkillResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91819,22 +92777,26 @@ func ParseCreateSkillResponse(rsp *http.Response) (*CreateSkillResponse, error) return response, nil } -// ParseDeleteSkillResponse parses an HTTP response from a DeleteSkillWithResponse call -func ParseDeleteSkillResponse(rsp *http.Response) (*DeleteSkillResponse, error) { +// ParseGetSkillResponse parses an HTTP response from a GetSkillWithResponse call +func ParseGetSkillResponse(rsp *http.Response) (*GetSkillResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteSkillResponse{ + response := &GetSkillResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case rsp.StatusCode == 204: - break // No content-type + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Skill + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest BadRequest @@ -91888,8 +92850,8 @@ func ParseDeleteSkillResponse(rsp *http.Response) (*DeleteSkillResponse, error) } switch { - case rsp.StatusCode == 204: - var headers DeleteSkillResponse204Headers + case rsp.StatusCode == 200: + var headers GetSkillResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91918,9 +92880,9 @@ func ParseDeleteSkillResponse(rsp *http.Response) (*DeleteSkillResponse, error) } headers.XStreamCostMicros = &value } - response.Headers204 = &headers + response.Headers200 = &headers case rsp.StatusCode == 402: - var headers DeleteSkillResponse402Headers + var headers GetSkillResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -91941,15 +92903,15 @@ func ParseDeleteSkillResponse(rsp *http.Response) (*DeleteSkillResponse, error) return response, nil } -// ParseGetSkillResponse parses an HTTP response from a GetSkillWithResponse call -func ParseGetSkillResponse(rsp *http.Response) (*GetSkillResponse, error) { +// ParseUpdateSkillResponse parses an HTTP response from a UpdateSkillWithResponse call +func ParseUpdateSkillResponse(rsp *http.Response) (*UpdateSkillResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetSkillResponse{ + response := &UpdateSkillResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -91997,6 +92959,13 @@ func ParseGetSkillResponse(rsp *http.Response) (*GetSkillResponse, error) { } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -92015,7 +92984,7 @@ func ParseGetSkillResponse(rsp *http.Response) (*GetSkillResponse, error) { switch { case rsp.StatusCode == 200: - var headers GetSkillResponse200Headers + var headers UpdateSkillResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -92046,7 +93015,7 @@ func ParseGetSkillResponse(rsp *http.Response) (*GetSkillResponse, error) { } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers GetSkillResponse402Headers + var headers UpdateSkillResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -92067,22 +93036,22 @@ func ParseGetSkillResponse(rsp *http.Response) (*GetSkillResponse, error) { return response, nil } -// ParseUpdateSkillResponse parses an HTTP response from a UpdateSkillWithResponse call -func ParseUpdateSkillResponse(rsp *http.Response) (*UpdateSkillResponse, error) { +// ParseSyncAgentResponse parses an HTTP response from a SyncAgentWithResponse call +func ParseSyncAgentResponse(rsp *http.Response) (*SyncAgentResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateSkillResponse{ + response := &SyncAgentResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Skill + var dest SyncAgentResult if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -92116,13 +93085,6 @@ func ParseUpdateSkillResponse(rsp *http.Response) (*UpdateSkillResponse, error) } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest NotFound - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: var dest ErrorResponse if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -92148,7 +93110,7 @@ func ParseUpdateSkillResponse(rsp *http.Response) (*UpdateSkillResponse, error) switch { case rsp.StatusCode == 200: - var headers UpdateSkillResponse200Headers + var headers SyncAgentResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -92179,7 +93141,7 @@ func ParseUpdateSkillResponse(rsp *http.Response) (*UpdateSkillResponse, error) } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers UpdateSkillResponse402Headers + var headers SyncAgentResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -92200,15 +93162,15 @@ func ParseUpdateSkillResponse(rsp *http.Response) (*UpdateSkillResponse, error) return response, nil } -// ParseSyncAgentResponse parses an HTTP response from a SyncAgentWithResponse call -func ParseSyncAgentResponse(rsp *http.Response) (*SyncAgentResponse, error) { +// ParseSyncAgentFilesResponse parses an HTTP response from a SyncAgentFilesWithResponse call +func ParseSyncAgentFilesResponse(rsp *http.Response) (*SyncAgentFilesResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &SyncAgentResponse{ + response := &SyncAgentFilesResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -92256,6 +93218,13 @@ func ParseSyncAgentResponse(rsp *http.Response) (*SyncAgentResponse, error) { } response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 413: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON413 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -92274,7 +93243,7 @@ func ParseSyncAgentResponse(rsp *http.Response) (*SyncAgentResponse, error) { switch { case rsp.StatusCode == 200: - var headers SyncAgentResponse200Headers + var headers SyncAgentFilesResponse200Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { @@ -92305,7 +93274,7 @@ func ParseSyncAgentResponse(rsp *http.Response) (*SyncAgentResponse, error) { } response.Headers200 = &headers case rsp.StatusCode == 402: - var headers SyncAgentResponse402Headers + var headers SyncAgentFilesResponse402Headers if values := rsp.Header.Values("X-Stream-Balance-Micros"); len(values) > 0 { var value int64 if err := runtime.BindStyledParameterWithOptions("simple", "X-Stream-Balance-Micros", values[0], &value, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false, Type: "integer", Format: "int64"}); err != nil { diff --git a/sdks/go/agents/agent.go b/sdks/go/agents/agent.go index 066cd5660d..e0a3c38997 100644 --- a/sdks/go/agents/agent.go +++ b/sdks/go/agents/agent.go @@ -81,7 +81,10 @@ type Agent struct { options Options folder *Folder - logger *slog.Logger + // skillsInCode is whether the harness's skills were written in code rather than folded + // in from the directory, which sends them itself. + skillsInCode bool + logger *slog.Logger } // New validates an agent's configuration and reads its directory, if it has one. @@ -92,6 +95,7 @@ func New(options Options) (*Agent, error) { } agent := &Agent{options: options, logger: logger} + agent.skillsInCode = options.Harness != nil && len(options.Harness.Skills) > 0 agent.Sessions = &Sessions{agent: agent} dir := options.Dir if dir == "" && options.Name != "" { diff --git a/sdks/go/agents/agent_test.go b/sdks/go/agents/agent_test.go index 26af722e5e..4cb58616f4 100644 --- a/sdks/go/agents/agent_test.go +++ b/sdks/go/agents/agent_test.go @@ -1,18 +1,17 @@ package agents import ( - "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" "io" - "log/slog" "maps" "net/http" "net/http/httptest" "path/filepath" - "reflect" "slices" "strings" "sync" @@ -32,18 +31,16 @@ type backend struct { mu sync.Mutex configs []acceleration.AgentConfig skills []acceleration.Skill - syncs []acceleration.SyncAgentRequest + syncs []acceleration.SyncAgentFilesRequest syncRaw [][]byte updates []string // refuseSkills, when set, is the reason POST /v1/agents/skills answers 400. refuseSkills string // refuseSkillEdits, when set, is the reason PUT /v1/agents/skills/{id} answers 400. refuseSkillEdits string - // ignoresUI stores a sync without its ui_instructions, as a router older than them does. - ignoresUI bool - // connections answers GET /v1/agents/connections. Nil answers an empty page. - connections func(*http.Request) acceleration.ConnectionPage - connectionQueries []string + // leavesOut, when set, is a connector every sync leaves out, as the router does for one + // whose connection the app does not have. + leavesOut *acceleration.LeftOutConnector } func newBackend(t *testing.T) *backend { @@ -172,51 +169,33 @@ func newBackend(t *testing.T) *backend { reply(w, http.StatusNotFound, acceleration.ErrorResponse{Error: acceleration.ErrorDetail{Message: "no such skill"}}) }) - mux.HandleFunc("GET /v1/agents/connections", func(w http.ResponseWriter, r *http.Request) { - router.mu.Lock() - router.connectionQueries = append(router.connectionQueries, r.URL.RawQuery) - answer := router.connections - router.mu.Unlock() - if answer == nil { - reply(w, http.StatusOK, acceleration.ConnectionPage{}) - return - } - reply(w, http.StatusOK, answer(r)) - }) - - mux.HandleFunc("POST /v1/agents/sync", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("POST /v1/agents/sync/files", func(w http.ResponseWriter, r *http.Request) { raw, err := io.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } - var request acceleration.SyncAgentRequest + var request acceleration.SyncAgentFilesRequest _ = json.Unmarshal(raw, &request) router.mu.Lock() defer router.mu.Unlock() router.syncRaw = append(router.syncRaw, raw) router.syncs = append(router.syncs, request) - stored := acceleration.AgentConfig{ - Id: "config-" + request.Name, Name: request.Name, Instructions: request.Instructions, - Subagent: request.Subagent, Llm: request.Llm, Tags: request.Tags, - CreatedAt: time.Now(), UpdatedAt: time.Now(), - } - if !router.ignoresUI { - stored.UiInstructions = request.UiInstructions - } - if request.Knowledge != nil || request.KnowledgeUrls != nil { - stored.KnowledgeNamespace = &request.Name - } - if request.Skills != nil { - named := []string{} - for _, skill := range *request.Skills { - named = append(named, skill.Name) - } - stored.Skills = &named - } - router.configs = append(router.configs[:0:0], stored) - reply(w, http.StatusOK, acceleration.SyncAgentResult{Config: stored}) + // Whatever the router makes of the request: the same one hashes the same. + hashed := sha256.Sum256(raw) + hash := hex.EncodeToString(hashed[:]) + result := acceleration.SyncAgentResult{} + name := deref(request.Name) + result.Config = acceleration.AgentConfig{ + Id: "config-" + name, Name: name, SyncHash: &hash, CreatedAt: time.Now(), UpdatedAt: time.Now(), + } + if router.leavesOut != nil { + result.Config.LeftOutConnectors = &[]acceleration.LeftOutConnector{*router.leavesOut} + result.Warnings = &[]string{"connector " + router.leavesOut.Name + " was left out"} + } + router.configs = append(router.configs[:0:0], result.Config) + reply(w, http.StatusOK, result) }) router.Server = httptest.NewServer(mux) @@ -275,12 +254,6 @@ func scripts(paths []string) []string { return run } -func (b *backend) answerConnections(answer func(*http.Request) acceleration.ConnectionPage) { - b.mu.Lock() - b.connections = answer - b.mu.Unlock() -} - func reply(w http.ResponseWriter, status int, body any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) @@ -784,861 +757,233 @@ func TestASyncTheRouterRefusesCarriesWhatItSaid(t *testing.T) { } } -func TestSyncPushesADirectorysSkillsAndKnowledge(t *testing.T) { +func TestAnUnchangedDirectoryIsNotSyncedAgain(t *testing.T) { root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "llm: openai/gpt-5.6\ntags:\n team: support\n") + write(t, root, "agent.yaml", "name: jean\n") write(t, root, "instructions.md", "You are Jean.\n") - write(t, root, "skills/think.md", "---\ndescription: Work it out\n---\nReason it through.\n") - write(t, root, "knowledge/pricing.md", "# Pricing\n\nA call costs a penny.\n") - write(t, root, "knowledge/urls.yaml", "- url: https://example.com/plans\n title: Plans\n refresh_hours: 24\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - stored, err := agent.Sync(t.Context()) - if err != nil { - t.Fatal(err) - } - router.mu.Lock() - defer router.mu.Unlock() - - if len(router.syncs) != 1 { - t.Fatalf("the directory was synced in %d requests", len(router.syncs)) - } - synced := router.syncs[0] - if synced.Hash != agent.Folder().Hash() { - t.Errorf("the directory was sent as %q, but hashes to %q", synced.Hash, agent.Folder().Hash()) - } - if synced.Skills == nil || (*synced.Skills)[0].Name != "think" { - t.Errorf("the skills sent are %+v", synced.Skills) - } - if synced.Knowledge == nil || (*synced.Knowledge)[0].Source != "pricing.md" { - t.Errorf("the knowledge sent is %+v", synced.Knowledge) - } - if synced.KnowledgeUrls == nil || (*synced.KnowledgeUrls)[0].Url != "https://example.com/plans" || - *(*synced.KnowledgeUrls)[0].Title != "Plans" || (*synced.KnowledgeUrls)[0].Description != nil || - *(*synced.KnowledgeUrls)[0].RefreshHours != 24 { - t.Errorf("the pages sent are %+v", synced.KnowledgeUrls) - } - if synced.Llm == nil || *synced.Llm != "openai/gpt-5.6" || (*synced.Tags)["team"] != "support" { - t.Errorf("what agent.yaml declares did not go with it: %+v", synced) - } - if synced.Stt != nil || synced.Mode != nil { - t.Errorf("settings the declaration never named were sent: %+v", synced) - } - if stored.KnowledgeNamespace == nil || *stored.KnowledgeNamespace != "jean" { - t.Errorf("the config does not point at the knowledge: %+v", stored) - } - if ReadStamp(root) != synced.Hash { - t.Errorf("%s records %q", AgentStamp, ReadStamp(root)) + for range 2 { + stored, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()) + if err != nil { + t.Fatal(err) + } + if stored == nil || stored.Name != "jean" { + t.Fatalf("the sync answered %+v", stored) + } } -} - -func TestSyncSendsHowTheSandboxIsBuilt(t *testing.T) { - root := filepath.Join(t.TempDir(), "artist") - write(t, root, "agent.yaml", `sandbox: daytona -sandbox_options: - setup: [pip install bpy==5.2.2] - timeout: 5m - memory_gb: 4 -`) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { + write(t, root, "instructions.md", "You are Jean, and brief.\n") + if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { t.Fatal(err) } router.mu.Lock() defer router.mu.Unlock() - options := router.syncs[0].SandboxOptions - if options == nil || (*options.Setup)[0] != "pip install bpy==5.2.2" || *options.TimeoutMs != 300000 || *options.MemoryGb != 4 { - t.Errorf("how the sandbox is built went as %+v", options) + if len(router.syncs) != 2 { + t.Errorf("three syncs, one of them of an edited directory, sent %d requests", len(router.syncs)) } } -func TestSyncSendsWhatTheSandboxMayReach(t *testing.T) { - root := filepath.Join(t.TempDir(), "researcher") - write(t, root, "agent.yaml", `sandbox: daytona -sandbox_options: - network: true - allowed_domains: [api.example.com] - network_allow_list: [10.0.0.0/8] -`) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) +func TestSyncSendsADirectorysFilesAsTheyAre(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + held := map[string]string{ + "agent.yaml": "llm: openai/gpt-5.6\ntags:\n team: support\n", + "instructions.md": "You are Jean.\n", + "guardrail.md": "---\ntype: llm\n---\nNo medical advice.\n", + "skills/think.md": "---\ndescription: Work it out\n---\nReason it through.\n", + "skills/pdf/SKILL.md": "---\ndescription: Fill a form\n---\nRun the script.\n", + "skills/pdf/fill.py": "print('filled')\n", + "knowledge/pricing.md": "# Pricing\n\nA call costs a penny.\n", + "knowledge/urls.yaml": "- url: https://example.com/plans\n title: Plans\n", + "simulations/lunch.yaml": "- name: lunch\n scenario: Order.\n assertion: Ordered.\n", + "ui/components.json": "[]\n", } - - router.mu.Lock() - defer router.mu.Unlock() - options := router.syncs[0].SandboxOptions - if options == nil || !*options.Network || (*options.AllowedDomains)[0] != "api.example.com" || - (*options.NetworkAllowList)[0] != "10.0.0.0/8" { - t.Errorf("what the sandbox may reach went as %+v", options) + for path, content := range held { + write(t, root, path, content) } -} -func TestSyncSendsTheChannelsTheAgentAnswersOn(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", `channels: - whatsapp: - number: "+15556325550" - sms: - number: "+12187021098" - identity: link -`) router := newBackend(t) agent := agentOn(t, router, Options{Dir: root}) - if _, err := agent.Sync(t.Context()); err != nil { + stored, err := agent.Sync(t.Context()) + if err != nil { t.Fatal(err) } router.mu.Lock() defer router.mu.Unlock() - named := router.syncs[0].Channels - if named == nil || named.Whatsapp == nil || named.Whatsapp.Number != "+15556325550" || - named.Sms == nil || named.Sms.Number != "+12187021098" || named.Imessage != nil || - named.Identity == nil || *named.Identity != acceleration.ChannelIdentityLink { - t.Errorf("the channels went as %+v", named) + if len(router.syncs) != 1 { + t.Fatalf("the directory was synced in %d requests", len(router.syncs)) } -} - -// chat_channels go as the file lists them: nil when it names none, which leaves the stored -// list, and an empty list when it lists none, which removes it. -func TestSyncSendsTheChatChannelsTheAgentAnswersIn(t *testing.T) { - for _, c := range []struct { - declared string - want *[]acceleration.AgentChatChannel - }{ - {"chat_channels:\n - type: callouts\n - type: shifts\n", &[]acceleration.AgentChatChannel{{Type: "callouts"}, {Type: "shifts"}}}, - {"chat_channels:\n - type: callouts\n answer: mentioned\n - type: shifts\n answer: always\n", - &[]acceleration.AgentChatChannel{{Type: "callouts", Answer: pointer(acceleration.Mentioned)}, {Type: "shifts", Answer: pointer(acceleration.Always)}}}, - {"chat_channels: []\n", &[]acceleration.AgentChatChannel{}}, - {"chat_channels: ~\n", nil}, - {"llm: llm-fast\n", nil}, - } { - root := filepath.Join(t.TempDir(), "rota") - write(t, root, "agent.yaml", c.declared) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - sent := router.syncs[0].ChatChannels - router.mu.Unlock() - if !reflect.DeepEqual(sent, c.want) { - t.Errorf("%q: chat_channels went as %+v, not %+v", c.declared, sent, c.want) - } + synced := router.syncs[0] + if deref(synced.Name) != "jean" { + t.Errorf("the directory was synced as %q, not after its folder", deref(synced.Name)) } -} - -// A chat channel entry with a key nobody knows is refused, as any declaration key is. -func TestAChatChannelKeyNobodyKnowsIsRefused(t *testing.T) { - root := filepath.Join(t.TempDir(), "rota") - write(t, root, "agent.yaml", "chat_channels:\n - type: callouts\n mention: true\n") - - if _, err := Load(root); err == nil || !strings.Contains(err.Error(), "mention") { - t.Errorf("loaded with an unknown chat channel key: %v", err) + sent := map[string]string{} + for _, file := range synced.Files { + sent[file.Path] = file.Content } -} - -func TestSyncSendsTheSchedulingTheAgentDeclared(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", `scheduling: - enabled: true - max_tasks_per_user: 10 - default_timezone: America/New_York -`) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) + if !maps.Equal(sent, held) { + t.Errorf("the files sent are %+v", sent) } - - router.mu.Lock() - defer router.mu.Unlock() - declared := router.syncs[0].Scheduling - if declared == nil || declared.Enabled == nil || !*declared.Enabled || - declared.MaxTasksPerUser == nil || *declared.MaxTasksPerUser != 10 || - declared.DefaultTimezone == nil || *declared.DefaultTimezone != "America/New_York" { - t.Errorf("the scheduling went as %+v", declared) + var body map[string]json.RawMessage + if err := json.Unmarshal(router.syncRaw[0], &body); err != nil { + t.Fatal(err) } -} - -// agent.yaml's floor_control goes as written, a model the router does not know and an empty -// mapping included, and a file that names none, or null, sends none, so the stored choice stays. -func TestSyncSendsTheFloorControlTheAgentDeclared(t *testing.T) { - for _, c := range []struct { - declared string - want *acceleration.FloorControl - }{ - {"floor_control:\n model: stream/chorus-asr\n max_wait_ms: 800\n", - &acceleration.FloorControl{Model: pointer("stream/chorus-asr"), MaxWaitMs: pointer(int64(800))}}, - {"floor_control:\n model: stream/chorus-asr\n", &acceleration.FloorControl{Model: pointer("stream/chorus-asr")}}, - {"floor_control: {model: other}\n", &acceleration.FloorControl{Model: pointer("other")}}, - {"floor_control: {}\n", &acceleration.FloorControl{}}, - {"floor_control:\n", nil}, - {"floor_control: ~\n", nil}, - {"llm: openai/gpt-5.6\n", nil}, - } { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", c.declared) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - got := router.syncs[0].FloorControl - router.mu.Unlock() - if !reflect.DeepEqual(got, c.want) { - t.Errorf("%q: floor_control went as %s, not %s", c.declared, describe(got), describe(c.want)) - } + if len(body) != 2 { + t.Errorf("the request says more than the name and the files, which is the router's to read: %s", router.syncRaw[0]) } -} - -// agent.yaml's agents go as written, and an empty list goes as one so it removes the stored -// list, while a file that names none, or null, sends none, so the stored list stays. -func TestSyncSendsTheAgentsTheAgentDeclared(t *testing.T) { - for _, c := range []struct { - declared string - want *[]acceleration.ChildAgent - }{ - {"mode: text\nagents:\n - config: security-lens\n tool: security\n description: Reviews for security bugs.\n timeout_ms: 90000\n max_tool_rounds: -1\n - {config: ranker, tool: rank}\n", - &[]acceleration.ChildAgent{ - {Config: "security-lens", Tool: "security", Description: pointer("Reviews for security bugs."), TimeoutMs: pointer(int64(90000)), MaxToolRounds: pointer(int64(-1))}, - {Config: "ranker", Tool: "rank"}, - }}, - {"agents: []\n", &[]acceleration.ChildAgent{}}, - {"agents:\n", nil}, - {"llm: openai/gpt-5.6\n", nil}, - } { - root := filepath.Join(t.TempDir(), "lead") - write(t, root, "agent.yaml", c.declared) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - got := router.syncs[0].Agents - router.mu.Unlock() - if !reflect.DeepEqual(got, c.want) { - sent, _ := json.Marshal(got) - wanted, _ := json.Marshal(c.want) - t.Errorf("%q: agents went as %s, not %s", c.declared, sent, wanted) - } + if stamp := readStamp(root); stamp.SyncHash != deref(stored.SyncHash) || stamp.Hash == "" { + t.Errorf("%s records %+v, and the router answered %q", AgentStamp, stamp, deref(stored.SyncHash)) } } -// agent.yaml's image goes as written, and a file that names none sends none, so the stored one -// stays and an agent that never asked for drawing is not offered it. -func TestSyncSendsTheImageTargetTheAgentDeclared(t *testing.T) { - for _, c := range []struct { - declared string - want *string - }{ - {"mode: text\nimage: image-fast\n", pointer("image-fast")}, - {"mode: text\nimage: \"\"\n", pointer("")}, - {"mode: text\nimage:\n", nil}, - {"mode: text\nllm: openai/gpt-5.6\n", nil}, - } { - root := filepath.Join(t.TempDir(), "illustrator") - write(t, root, "agent.yaml", c.declared) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) +func TestAStampedDirectoryIsSyncedAgainOnceTheStoredConfigIsNoLongerWhatWasSynced(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\n") + router := newBackend(t) - if _, err := agent.Sync(t.Context()); err != nil { + for range 2 { + if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { t.Fatal(err) } - - router.mu.Lock() - got := router.syncs[0].Image - router.mu.Unlock() - if !reflect.DeepEqual(got, c.want) { - t.Errorf("%q: image went as %v, not %v", c.declared, got, c.want) - } } -} - -func describe(floorControl *acceleration.FloorControl) string { - raw, _ := json.Marshal(floorControl) - return string(raw) -} - -func TestAFolderDeclaresCalls(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", `calls: - end_call: - enabled: true - when: The caller said goodbye, or their question is answered and they need nothing else. - press: - enabled: false - transfer: - enabled: true - destinations: - - name: Sales - number: "+15550001111" - when: The caller wants to buy, upgrade or ask about pricing. - warm: true - - name: Billing - number: "+15550002222" - when: A charge they don't recognise. -`) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { + // Somebody imports another directory in the dashboard, or edits the config, which clears it. + router.mu.Lock() + edited := "imported" + router.configs[0].SyncHash = &edited + router.mu.Unlock() + if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { t.Fatal(err) } router.mu.Lock() defer router.mu.Unlock() - calls := router.syncs[0].Calls - if calls == nil || calls.EndCall == nil || calls.Press == nil || calls.Transfer == nil { - t.Fatalf("the calls went as %+v", calls) - } - if !*calls.EndCall.Enabled || *calls.EndCall.When != "The caller said goodbye, or their question is answered and they need nothing else." { - t.Errorf("end_call went as %+v", calls.EndCall) - } - if *calls.Press.Enabled { - t.Errorf("press went as %+v", calls.Press) - } - if !*calls.Transfer.Enabled || calls.Transfer.Destinations == nil || len(*calls.Transfer.Destinations) != 2 { - t.Fatalf("transfer went as %+v", calls.Transfer) - } - sales, billing := (*calls.Transfer.Destinations)[0], (*calls.Transfer.Destinations)[1] - if sales.Name != "Sales" || sales.Number != "+15550001111" || *sales.When != "The caller wants to buy, upgrade or ask about pricing." || - sales.Warm == nil || !*sales.Warm { - t.Errorf("Sales went as %+v", sales) - } - if billing.Name != "Billing" || billing.Number != "+15550002222" || *billing.When != "A charge they don't recognise." || - (billing.Warm != nil && *billing.Warm) { - t.Errorf("Billing went as %+v", billing) + if len(router.syncs) != 2 { + t.Errorf("the directory was sent %d times: once, not again while the config was as synced, and again once it was not", len(router.syncs)) } } -// A sync replaces what the dashboard changed, so a file with no calls sends the defaults. -func TestAFolderWithoutCallsSendsTheDefaults(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "llm: llm-fast\n") +func TestWhatTheCodeSetsBesideADirectoryGoesWithItsFilesAndWinsOverThem(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\n") + write(t, root, "instructions.md", "You are Jean.\n") router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - if _, err := agent.Sync(t.Context()); err != nil { + if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { t.Fatal(err) } + written := Options{ + Dir: root, Instructions: "You are somebody else.", Guardrail: "Refuse medical advice.", + CostTracking: map[string]string{"team": "support", "customer": "123"}, + Harness: &Harness{ + Subagents: map[string]string{"default": "openai/gpt-5.6-sol"}, Sandbox: Daytona(), + Skills: []Skill{ + {Name: "think", Description: "Work it out", Instructions: "Reason.", Deadline: 30 * time.Second}, + {Name: "fill", Description: "Fill a form", Instructions: "Run it.", Files: map[string]string{"fill.py": "print()\n"}}, + }, + }, + } + for range 2 { + if _, err := agentOn(t, router, written).Sync(t.Context()); err != nil { + t.Fatal(err) + } + } router.mu.Lock() defer router.mu.Unlock() - calls := router.syncs[0].Calls - if calls == nil || calls.EndCall == nil || calls.Press == nil || calls.Transfer == nil { - t.Fatalf("the calls went as %+v", calls) + if len(router.syncs) != 2 { + t.Fatalf("what the code set was synced %d times, not once after the directory's own", len(router.syncs)-1) } - if *calls.EndCall.Enabled || !*calls.Press.Enabled || !*calls.Transfer.Enabled { - t.Errorf("defaults went as end_call %v, press %v, transfer %v", *calls.EndCall.Enabled, *calls.Press.Enabled, *calls.Transfer.Enabled) + plain, synced := router.syncs[0], router.syncs[1] + if plain.Instructions != nil || plain.Guardrail != nil || plain.Tags != nil || plain.Skills != nil || plain.Subagent != nil { + t.Errorf("a directory with nothing set in code was sent with %+v", plain) } - if calls.Transfer.Destinations != nil && len(*calls.Transfer.Destinations) != 0 { - t.Errorf("destinations went as %+v", *calls.Transfer.Destinations) + if deref(synced.Instructions) != "You are somebody else." || deref(synced.Guardrail) != "Refuse medical advice." { + t.Errorf("the instructions and guardrail written in code went as %v and %v", synced.Instructions, synced.Guardrail) } -} - -// A tool block without enabled takes that tool's default. -func TestACallsToolWithoutEnabledTakesItsDefault(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", `calls: - end_call: - when: They are done. - transfer: - destinations: - - name: Sales - number: "+15550001111" -`) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) + if deref(synced.Subagent) != "openai/gpt-5.6-sol" || deref(synced.Sandbox) != "daytona" || synced.Harness != nil { + t.Errorf("the harness went as %v, %v and %v", synced.Harness, synced.Subagent, synced.Sandbox) } - - router.mu.Lock() - defer router.mu.Unlock() - calls := router.syncs[0].Calls - if *calls.EndCall.Enabled || *calls.EndCall.When != "They are done." || !*calls.Press.Enabled || - !*calls.Transfer.Enabled || len(*calls.Transfer.Destinations) != 1 { - t.Errorf("the calls went as %+v", calls) + if !maps.Equal(deref(synced.Tags), written.CostTracking) { + t.Errorf("the cost labels went as %v", synced.Tags) } -} - -// A file saying nothing about scheduling leaves the stored setting alone. -func TestSyncSendsNoSchedulingWhenTheFileNamesNone(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "llm: llm-fast\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) + if skills := deref(synced.Skills); len(skills) != 2 || skills[1].Name != "fill" || deref(skills[1].Files)["fill.py"] != "print()\n" || + skills[0].Name != "think" || deref(skills[0].DeadlineMs) != 30000 { + t.Errorf("the skills written in code went as %+v", synced.Skills) } - - router.mu.Lock() - defer router.mu.Unlock() - if router.syncs[0].Scheduling != nil { - t.Errorf("the scheduling went as %+v", router.syncs[0].Scheduling) + if len(synced.Files) != 2 || synced.Files[1].Content != "You are Jean.\n" { + t.Errorf("the directory's own files went as %+v", synced.Files) } } -// A file saying nothing about channels leaves the agent reachable in Stream Chat alone. -func TestSyncSendsNoChannelsWhenTheFileNamesNone(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "llm: llm-fast\n") +func TestADirectoryThatLeftAConnectorOutIsSentAgainUntilItsConnectionIsFound(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\nconnectors:\n - {name: linear, connection: company}\n") router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) + router.leavesOut = &acceleration.LeftOutConnector{Name: "linear", ConnectorId: "linear", Connection: "company"} - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) + for range 2 { + if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { + t.Fatal(err) + } } - router.mu.Lock() - defer router.mu.Unlock() - if router.syncs[0].Channels != nil { - t.Errorf("the channels went as %+v", router.syncs[0].Channels) - } -} - -func TestSyncSendsTheToolGroups(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "tools:\n"+ - " - name: booking\n tools: [lookup_booking]\n"+ - " - name: refunds\n loading: deferred\n output_retention: 30d\n tools: [refund_booking, void_ticket]\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) + router.leavesOut = nil + router.mu.Unlock() + for range 2 { + if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { + t.Fatal(err) + } } router.mu.Lock() defer router.mu.Unlock() - sent := router.syncs[0].Tools - if sent == nil || len(*sent) != 2 { - t.Fatalf("tools went as %+v", sent) - } - booking, refunds := (*sent)[0], (*sent)[1] - if booking.Name != "booking" || booking.Loading != nil || booking.OutputRetention != nil { - t.Errorf("a group that says nothing more went as %+v", booking) - } - if refunds.Loading == nil || *refunds.Loading != acceleration.ToolLoadingDeferred || - refunds.OutputRetention == nil || *refunds.OutputRetention != "30d" || - !slices.Equal(refunds.Tools, []string{"refund_booking", "void_ticket"}) { - t.Errorf("refunds went as %+v", refunds) + if len(router.syncs) != 3 { + t.Errorf("the directory was sent %d times: twice while a connector was left out, once to bind it, and not again", len(router.syncs)) } } -func TestSyncSendsHowAConnectorsToolsAreOffered(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "connectors:\n - name: linear\n loading: summary\n output_retention: none\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) +func TestAMemoryFilterSaysWhoTheMemoriesAreAboutAndWhatNarrowsThem(t *testing.T) { + memory := memoryOf(map[string]string{"user_id": "123", "tenant": "acme"}) - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) + if memory.UserId == nil || *memory.UserId != "123" { + t.Fatalf("the memories are about %+v", memory.UserId) } - - router.mu.Lock() - defer router.mu.Unlock() - bindings := router.syncs[0].Connectors - if bindings == nil || len(*bindings) != 1 { - t.Fatalf("connectors went as %+v", bindings) + if memory.Filter == nil || (*memory.Filter)["tenant"] != "acme" { + t.Errorf("the filter is %+v", memory.Filter) } - binding := (*bindings)[0] - if binding.Loading == nil || *binding.Loading != acceleration.ToolLoadingSummary || - binding.OutputRetention == nil || *binding.OutputRetention != "none" { - t.Errorf("linear went as %+v", binding) + if _, leaked := (*memory.Filter)["user_id"]; leaked { + t.Error("who the memories are about is not also a label") } -} - -func TestAnAgentWhoseFolderNamesPluginsIsNotMade(t *testing.T) { - root := filepath.Join(t.TempDir(), "triage") - write(t, root, "agent.yaml", "plugins: [sentry]\n") - - if _, err := New(Options{Dir: root}); err == nil || !strings.Contains(err.Error(), "plugins is no longer read") { - t.Errorf("an agent naming plugins was made: %v", err) + if memoryOf(nil) != nil { + t.Error("without a filter nothing is recalled and nothing is sent") } } -// emptyPluginsYAML names plugins and plugin_events with nothing in them. Its sync body was -// probed on 259da758b, while the SDK still read both keys. -// The body now also carries calls, which a sync always sends; an older router ignores it -// (Huma's AllowAdditionalPropertiesByDefault). -const emptyPluginsYAML = "name: concierge\nplugins: []\nplugin_events: []\nconnectors:\n - linear\n" - -func TestSyncOfEmptyPluginKeysSendsTheBodyItSentBefore(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", emptyPluginsYAML) +func TestTheDefaultHarnessLeavesTheBuiltInSkillsAlone(t *testing.T) { router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { + stored, err := agentOn(t, router, Options{Name: "jean", Harness: DefaultHarness()}).Sync(t.Context()) + if err != nil { t.Fatal(err) } - router.mu.Lock() - defer router.mu.Unlock() - const probed = `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"connectors":[{"connection":{"type":"session"},"connector_id":"linear","name":"linear","tool_patterns":["*"],"tools":[]}],"hash":"5d7a06efa5f0e215c95f81ffe13b0585","name":"concierge"}` - if len(router.syncRaw) != 1 || string(router.syncRaw[0]) != probed { - t.Errorf("body = %s", router.syncRaw) + if stored.Skills != nil { + t.Errorf("the built-in set was replaced by %+v", *stored.Skills) } } -// An empty or null mcp_servers sent no MCP servers. Its sync bodies were probed on -// 1af941985, while the SDK still read the key. -func TestSyncOfAnEmptyMCPServerListSendsTheBodyItSentBefore(t *testing.T) { - for declared, probed := range map[string]string{ - "name: concierge\nmcp_servers: []\nconnectors:\n - linear\n": `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"connectors":[{"connection":{"type":"session"},"connector_id":"linear","name":"linear","tool_patterns":["*"],"tools":[]}],"hash":"39719d1b342a09b5e9d4a6fb77832132","name":"concierge"}`, - "name: concierge\nmcp_servers:\nconnectors:\n - linear\n": `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"connectors":[{"connection":{"type":"session"},"connector_id":"linear","name":"linear","tool_patterns":["*"],"tools":[]}],"hash":"51634dd05c567ccc87600dbd3bd2ac5b","name":"concierge"}`, - } { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", declared) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatalf("%q: %v", declared, err) - } - - router.mu.Lock() - if len(router.syncRaw) != 1 || string(router.syncRaw[0]) != probed { - t.Errorf("%q: body = %s", declared, router.syncRaw) - } - router.mu.Unlock() +func TestAHarnessThatDoesNotExistIsRefused(t *testing.T) { + if _, err := New(Options{Name: "jean", Harness: &Harness{Name: "fancy"}}); err == nil { + t.Fatal("the backend has only the default harness, so another name means nothing") } } -func TestSyncSaysNothingOfTheSandboxWhenTheDeclarationDoesNot(t *testing.T) { - root := filepath.Join(t.TempDir(), "analyst") - write(t, root, "agent.yaml", "sandbox: daytona\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } +func TestSeveralSubagentsWithNoDefaultIsRefused(t *testing.T) { + harness := &Harness{Subagents: map[string]string{"fast": "a", "slow": "b"}} - router.mu.Lock() - defer router.mu.Unlock() - if router.syncs[0].SandboxOptions != nil { - t.Errorf("options nobody declared were sent: %+v", router.syncs[0].SandboxOptions) - } -} - -func TestAnUnchangedDirectoryIsNotSyncedAgain(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\n") - write(t, root, "instructions.md", "You are Jean.\n") - router := newBackend(t) - - for range 2 { - stored, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()) - if err != nil { - t.Fatal(err) - } - if stored == nil || stored.Name != "jean" { - t.Fatalf("the sync answered %+v", stored) - } - } - write(t, root, "instructions.md", "You are Jean, and brief.\n") - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 2 { - t.Errorf("three syncs, one of them of an edited directory, sent %d requests", len(router.syncs)) - } -} - -func TestSyncSendsTheUIApartFromTheInstructions(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nui:\n keep: [CardHeader]\n") - write(t, root, "instructions.md", "You are Juno.\n") - router := newBackend(t) - - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 1 { - t.Fatalf("the sync sent %d requests", len(router.syncs)) - } - sent := router.syncs[0] - if got := deref(sent.Instructions); got != "You are Juno." { - t.Errorf("the instructions went as %q", got) - } - if ui := deref(sent.UiInstructions); !strings.HasPrefix(ui, "## Interactive UI Generation") || !strings.Contains(ui, "CardHeader(") { - t.Errorf("the UI went as %q", ui) - } -} - -func TestAChangedUIBlueprintIsSyncedAgain(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nui:\n keep: [CardHeader]\n") - write(t, root, "ui/blueprints.yaml", "- name: booking\n when: booking a table\n order: [CardHeader]\n") - router := newBackend(t) - - for range 2 { - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - } - write(t, root, "ui/blueprints.yaml", "- name: booking\n when: booking a table for tonight\n order: [CardHeader]\n") - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 2 { - t.Fatalf("three syncs, one of them after the blueprint changed, sent %d requests", len(router.syncs)) - } - if ui := deref(router.syncs[1].UiInstructions); !strings.Contains(ui, "booking a table for tonight") { - t.Errorf("the second sync sent the UI %q", ui) - } -} - -// A router older than ui_instructions takes the sync and drops them, so the stamp that sync -// left must not keep the UI from the router once it stores them. -func TestAStampCoveringUITheStoredConfigLacksIsSyncedAgain(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nui:\n keep: [CardHeader]\n") - router := newBackend(t) - router.ignoresUI = true - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - router.ignoresUI = false - router.mu.Unlock() - stored, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()) - if err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 2 { - t.Fatalf("the unchanged directory was sent %d times, not again once the router kept no UI", len(router.syncs)) - } - if ui := deref(stored.UiInstructions); !strings.Contains(ui, "CardHeader(") { - t.Errorf("the config came back with the UI %q", ui) - } -} - -func TestWhatTheCodeSetsIsPartOfWhatIsSynced(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\n") - write(t, root, "instructions.md", "You are Jean.\n") - router := newBackend(t) - - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - written := Options{Dir: root, Instructions: "You are somebody else."} - if _, err := agentOn(t, router, written).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 2 || *router.syncs[1].Instructions != "You are somebody else." { - t.Errorf("instructions written in code were not synced: %+v", router.syncs) - } -} - -func TestADirectorysSkillsAreWhatTheAgentJoinsWith(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\n") - write(t, root, "skills/think.md", "---\ndescription: Work it out\n---\nReason it through.\n") - - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - skills := router.syncs[0].Skills - if skills == nil || len(*skills) != 1 || (*skills)[0].Name != "think" { - t.Errorf("the config would be stored with %+v", skills) - } -} - -func TestADirectoryDoesNotWriteThroughToAHarnessSharedWithAnotherAgent(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\n") - write(t, root, "skills/think.md", "---\ndescription: Work it out\n---\nReason it through.\n") - - router := newBackend(t) - shared := DefaultHarness() - agentOn(t, router, Options{Dir: root, Harness: shared}) - - if len(shared.Skills) != 0 { - t.Errorf("the caller's harness now holds %+v", shared.Skills) - } -} - -func TestAMemoryFilterSaysWhoTheMemoriesAreAboutAndWhatNarrowsThem(t *testing.T) { - memory := memoryOf(map[string]string{"user_id": "123", "tenant": "acme"}) - - if memory.UserId == nil || *memory.UserId != "123" { - t.Fatalf("the memories are about %+v", memory.UserId) - } - if memory.Filter == nil || (*memory.Filter)["tenant"] != "acme" { - t.Errorf("the filter is %+v", memory.Filter) - } - if _, leaked := (*memory.Filter)["user_id"]; leaked { - t.Error("who the memories are about is not also a label") - } - if memoryOf(nil) != nil { - t.Error("without a filter nothing is recalled and nothing is sent") - } -} - -func TestAgentYAMLNamesTheHarnessAndSandboxTheConfigIsStoredWith(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\nharness: default\nsandbox: daytona\n") - - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root, Harness: &Harness{ - Subagents: map[string]string{"default": "openai/gpt-5.6-sol"}, - }}) - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - synced := router.syncs[0] - if synced.Harness == nil || *synced.Harness != acceleration.Default { - t.Errorf("the harness was stored as %v", synced.Harness) - } - if synced.Sandbox == nil || *synced.Sandbox != "daytona" { - t.Errorf("the sandbox was stored as %v", synced.Sandbox) - } - if synced.Subagent == nil || *synced.Subagent != "openai/gpt-5.6-sol" { - t.Errorf("the subagent was stored as %v", synced.Subagent) - } -} - -func TestAgentYAMLNamesTheRoleTheConfigIsStoredWith(t *testing.T) { - root := filepath.Join(t.TempDir(), "nora") - write(t, root, "agent.yaml", "name: nora\nrole: agent_moderator\n") - - router := newBackend(t) - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if role := router.syncs[0].Role; role == nil || *role != acceleration.AgentModerator { - t.Errorf("the role was stored as %v", role) - } -} - -func TestAgentYAMLNamesTheRegionTheAgentsWorkIsDoneIn(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\nregion: eu\n") - - router := newBackend(t) - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if region := router.syncs[0].Region; region == nil || *region != "eu" { - t.Errorf("the region was sent as %v", region) - } -} - -// A declaration that says nothing about the region sends none, which leaves the stored one, and -// a new agent is in us. -func TestAgentYAMLWithoutARegionSendsNone(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\n") - - router := newBackend(t) - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if region := router.syncs[0].Region; region != nil { - t.Errorf("a declaration without a region sent %v", *region) - } -} - -// A declaration that says nothing about the role sends none, which leaves the stored one. -func TestAgentYAMLWithoutARoleSendsNone(t *testing.T) { - root := filepath.Join(t.TempDir(), "jean") - write(t, root, "agent.yaml", "name: jean\n") - - router := newBackend(t) - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if role := router.syncs[0].Role; role != nil { - t.Errorf("a declaration without a role sent %v", *role) - } -} - -func TestTheDefaultHarnessLeavesTheBuiltInSkillsAlone(t *testing.T) { - router := newBackend(t) - stored, err := agentOn(t, router, Options{Name: "jean", Harness: DefaultHarness()}).Sync(t.Context()) - if err != nil { - t.Fatal(err) - } - - if stored.Skills != nil { - t.Errorf("the built-in set was replaced by %+v", *stored.Skills) - } -} - -func TestAHarnessThatDoesNotExistIsRefused(t *testing.T) { - if _, err := New(Options{Name: "jean", Harness: &Harness{Name: "fancy"}}); err == nil { - t.Fatal("the backend has only the default harness, so another name means nothing") - } -} - -func TestSeveralSubagentsWithNoDefaultIsRefused(t *testing.T) { - harness := &Harness{Subagents: map[string]string{"fast": "a", "slow": "b"}} - - if err := harness.Validate(); err == nil { - t.Fatal("which one runs skills would be decided by map iteration order") + if err := harness.Validate(); err == nil { + t.Fatal("which one runs skills would be decided by map iteration order") } } @@ -1649,681 +994,4 @@ func TestSeveralSubagentsWithNoDefaultIsRefused(t *testing.T) { // (Huma's AllowAdditionalPropertiesByDefault). const controlYAML = "name: concierge\nllm: openai/gpt-5.6\n" -func TestSyncWithoutConnectorsSendsTheBodyItSentBefore(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", controlYAML) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - const probed = `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"hash":"aa0b594ad264ea72935f1c74441f8155","llm":"openai/gpt-5.6","name":"concierge"}` - if len(router.syncRaw) != 1 || string(router.syncRaw[0]) != probed { - t.Errorf("body = %s", router.syncRaw) - } - if len(router.connectionQueries) != 0 { - t.Errorf("connections were listed: %v", router.connectionQueries) - } -} - -func TestSyncSendsAConnectorNamedAloneAsASessionBinding(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - linear\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 { - t.Fatalf("connectors went as %+v", sent) - } - linear := (*sent)[0] - if linear.Name != "linear" || linear.ConnectorId != "linear" || - linear.Connection.Type != acceleration.AgentConnectorSelectionTypeSession || linear.Connection.ConnectionId != nil || - linear.ToolPatterns == nil || strings.Join(*linear.ToolPatterns, ",") != "*" || len(linear.Tools) != 0 || linear.Required != nil { - t.Errorf("linear went as %+v", linear) - } - if strings.Contains(string(router.syncRaw[0]), `"tools":null`) { - t.Errorf("body = %s", router.syncRaw[0]) - } - if len(router.connectionQueries) != 0 { - t.Errorf("a session binding listed connections: %v", router.connectionQueries) - } -} - -func TestSyncSendsConnectorToolsAsPatterns(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: github\n tools: [list_*, get_issue]\n required: true\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 { - t.Fatalf("connectors went as %+v", sent) - } - github := (*sent)[0] - if github.Name != "github" || github.ConnectorId != "github" || - github.Connection.Type != acceleration.AgentConnectorSelectionTypeSession || - github.ToolPatterns == nil || strings.Join(*github.ToolPatterns, ",") != "list_*,get_issue" || - github.Required == nil || !*github.Required || len(github.Tools) != 0 { - t.Errorf("github went as %+v", github) - } -} - -func TestSyncSendsEveryToolWhenToolsAreNull(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: github\n tools: null\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].ToolPatterns == nil || strings.Join(*(*sent)[0].ToolPatterns, ",") != "*" { - t.Errorf("null tools went as %+v", sent) - } -} - -func TestSyncSendsRequiredFalse(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: github\n required: false\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Required == nil || *(*sent)[0].Required || - (*sent)[0].ToolPatterns == nil || strings.Join(*(*sent)[0].ToolPatterns, ",") != "*" { - t.Errorf("required went as %+v", sent) - } - if !strings.Contains(string(router.syncRaw[0]), `"required":false`) { - t.Errorf("body = %s", router.syncRaw[0]) - } -} - -func TestSyncSendsSandboxOnEachBindingThatSetsIt(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: github\n sandbox: true\n"+ - " - name: code\n connector: github\n connection: company\n sandbox: true\n - linear\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("conn-1", "company")) - }) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 3 { - t.Fatalf("connectors went as %+v", sent) - } - github, code, linear := (*sent)[0], (*sent)[1], (*sent)[2] - if github.Sandbox == nil || !*github.Sandbox || github.Connection.Type != acceleration.AgentConnectorSelectionTypeSession { - t.Errorf("github went as %+v", github) - } - if code.Sandbox == nil || !*code.Sandbox || code.Connection.ConnectionId == nil || *code.Connection.ConnectionId != "conn-1" { - t.Errorf("code went as %+v", code) - } - if linear.Sandbox != nil { - t.Errorf("linear went with sandbox %v", *linear.Sandbox) - } - if strings.Count(string(router.syncRaw[0]), `"sandbox":true`) != 2 { - t.Errorf("body = %s", router.syncRaw[0]) - } -} - -func TestSyncSendsRequireApprovalOnEachBindingThatSetsIt(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: github\n require_approval: [create_*, merge_pull_request]\n"+ - " - linear\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 2 { - t.Fatalf("connectors went as %+v", sent) - } - github, linear := (*sent)[0], (*sent)[1] - if github.RequireApproval == nil || strings.Join(*github.RequireApproval, ",") != "create_*,merge_pull_request" { - t.Errorf("github went as %+v", github) - } - if linear.RequireApproval != nil { - t.Errorf("linear went with require_approval %v", *linear.RequireApproval) - } - if strings.Count(string(router.syncRaw[0]), `"require_approval"`) != 1 { - t.Errorf("body = %s", router.syncRaw[0]) - } -} - -// sandboxlessYAML is a connector entry with no sandbox key. Its sync body was probed on -// e5d6d8057, before agent.yaml read sandbox on a connector. -// The body now also carries calls, which a sync always sends; an older router ignores it -// (Huma's AllowAdditionalPropertiesByDefault). -const sandboxlessYAML = "name: concierge\nconnectors:\n - name: github\n required: true\n" - -func TestSyncOfAConnectorWithoutSandboxSendsTheBodyItSentBefore(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", sandboxlessYAML) - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - const probed = `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"connectors":[{"connection":{"type":"session"},"connector_id":"github","name":"github","required":true,"tool_patterns":["*"],"tools":[]}],"hash":"aeda4c2bbe3be818d7c79f48ee9ab0b8","name":"concierge"}` - if len(router.syncRaw) != 1 || string(router.syncRaw[0]) != probed { - t.Errorf("body = %s", router.syncRaw) - } -} - -func TestSyncSendsNoSandboxKeyForSandboxFalse(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: github\n sandbox: false\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncRaw) != 1 || strings.Contains(string(router.syncRaw[0]), `"sandbox"`) { - t.Errorf("body = %s", router.syncRaw) - } -} - -func TestSyncOfAnEmptyConnectorListClearsThem(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors: []\n") - router := newBackend(t) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if router.syncs[0].Connectors == nil || len(*router.syncs[0].Connectors) != 0 { - t.Errorf("connectors went as %+v", router.syncs[0].Connectors) - } - if !strings.Contains(string(router.syncRaw[0]), `"connectors":[]`) { - t.Errorf("body = %s", router.syncRaw[0]) - } -} - -func TestSyncResolvesAConnectionIdBeforeItsLabel(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connector: linear\n connection: acct\n") - router := newBackend(t) - router.answerConnections(func(r *http.Request) acceleration.ConnectionPage { - query := r.URL.Query() - if query.Get("owner_type") != "app" || query.Get("connector_id") != "linear" { - t.Errorf("listed %s", r.URL.RawQuery) - } - if query.Get("cursor") == "" { - return connectionPage("2", listedConnection("wrong", "acct")) - } - return connectionPage("", listedConnection("acct", "other")) - }) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.connectionQueries) != 2 { - t.Fatalf("queries = %v", router.connectionQueries) - } - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 { - t.Fatalf("connectors went as %+v", sent) - } - got := (*sent)[0] - if got.Name != "issues" || got.ConnectorId != "linear" || - got.Connection.Type != acceleration.AgentConnectorSelectionTypeFixed || - got.Connection.ConnectionId == nil || *got.Connection.ConnectionId != "acct" { - t.Errorf("issues went as %+v", got) - } -} - -func TestSyncResolvesTheOneConnectionWithThatLabel(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connector: linear\n connection: work\n") - router := newBackend(t) - router.answerConnections(func(r *http.Request) acceleration.ConnectionPage { - if r.URL.Query().Get("connector_id") != "linear" { - t.Errorf("listed connector %s", r.URL.Query().Get("connector_id")) - } - if r.URL.Query().Get("cursor") == "" { - return connectionPage("2", listedConnection("other", "nope")) - } - return connectionPage("", listedConnection("the-one", "work")) - }) - agent := agentOn(t, router, Options{Dir: root}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Connection.ConnectionId == nil || *(*sent)[0].Connection.ConnectionId != "the-one" { - t.Errorf("issues went as %+v, queries %v", sent, router.connectionQueries) - } - if len(router.connectionQueries) != 2 { - t.Errorf("queries = %v", router.connectionQueries) - } -} - -// resolvingYAML names a session binding and a connection the app has. Its sync body was -// probed on a5721c90, before a missing connection was left out. -// The body now also carries calls, which a sync always sends; an older router ignores it -// (Huma's AllowAdditionalPropertiesByDefault). -const resolvingYAML = "name: concierge\nconnectors:\n - linear\n - name: code\n connector: github\n connection: company\n" - -func TestSyncOfConnectionsThatAllResolveSendsTheBodyItSentBefore(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", resolvingYAML) - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("conn-1", "company")) - }) - var logged bytes.Buffer - agent := agentOn(t, router, Options{Dir: root, Logger: slog.New(slog.NewTextHandler(&logged, nil))}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - const probed = `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"connectors":[{"connection":{"type":"session"},"connector_id":"linear","name":"linear","tool_patterns":["*"],"tools":[]},{"connection":{"connection_id":"conn-1","type":"fixed"},"connector_id":"github","name":"code","tool_patterns":["*"],"tools":[]}],"hash":"84cee98b6c473b082438ee7b52cea7c6","name":"concierge"}` - if len(router.syncRaw) != 1 || string(router.syncRaw[0]) != probed { - t.Errorf("body = %s", router.syncRaw) - } - if stamp := ReadStamp(root); stamp != router.syncs[0].Hash { - t.Errorf("stamped %q after sending %q", stamp, router.syncs[0].Hash) - } - if strings.Contains(logged.String(), "left out") { - t.Errorf("warned of a connection the app has: %q", logged.String()) - } -} - -func TestSyncLeavesOutAConnectorWhoseConnectionIsMissing(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - linear\n - name: issues\n connection: missing\n required: false\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - var logged bytes.Buffer - agent := agentOn(t, router, Options{Dir: root, Logger: slog.New(slog.NewTextHandler(&logged, nil))}) - - stored, err := agent.Sync(t.Context()) - if err != nil { - t.Fatal(err) - } - - if stored == nil || stored.Name != "concierge" { - t.Errorf("the sync answered %+v", stored) - } - if !strings.Contains(logged.String(), `level=WARN msg="agent.yaml connector left out: the app has no such connection" agent=concierge connector=issues connection=missing`) { - t.Errorf("no warning in %q", logged.String()) - } - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 1 { - t.Fatalf("%d syncs were sent", len(router.syncs)) - } - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Name != "linear" { - t.Errorf("connectors went as %+v", sent) - } -} - -// The router is told what was left out, so it can show it. The hash is not the one 7f4c3e16 -// sent for this directory (87c8a2808cd085a316aa2942c6b827a8), before the list was sent: the -// router stored that one without the list, and would answer unchanged to it. -func TestSyncSendsTheConnectorsItLeftOut(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - linear\n - name: issues\n connection: company\n - name: code\n connector: github\n connection: team\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - const want = `{"calls":{"end_call":{"enabled":false},"press":{"enabled":true},"transfer":{"destinations":[],"enabled":true}},"connectors":[{"connection":{"type":"session"},"connector_id":"linear","name":"linear","tool_patterns":["*"],"tools":[]}],"hash":"370694e1e9f5b6495455c9b89fce3218",` + - `"left_out_connectors":[{"connection":"company","connector_id":"issues","name":"issues"},{"connection":"team","connector_id":"github","name":"code"}],"name":"concierge"}` - if len(router.syncRaw) != 1 || string(router.syncRaw[0]) != want { - t.Errorf("body = %s", router.syncRaw) - } -} - -// An entry over the router's caps is warned about but not sent in the list, so the router -// does not refuse the whole sync over it. The hash still covers it. -func TestSyncLeavesAnOverLongLeftOutEntryOutOfTheList(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - label := strings.Repeat("c", 121) - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - linear\n - name: issues\n connection: "+label+ - "\n - name: "+strings.Repeat("a", 64)+"\n connection: team\n - name: tracker\n connector: "+strings.Repeat("b", 65)+"\n connection: team\n - name: code\n connector: github\n connection: team\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - var logged bytes.Buffer - agent := agentOn(t, router, Options{Dir: root, Logger: slog.New(slog.NewTextHandler(&logged, nil))}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - if !strings.Contains(logged.String(), "connector=issues connection="+label) { - t.Errorf("no warning for the long label in %q", logged.String()) - } - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].LeftOutConnectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Name != "code" { - t.Errorf("left_out_connectors went as %+v", sent) - } -} - -// The caps are the router's: an entry exactly at them is sent. The label is multibyte, over -// the cap in bytes and at it in runes, which is what the router counts. -func TestSyncSendsALeftOutEntryExactlyAtTheCaps(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - alias, connector, label := strings.Repeat("a", 63), strings.Repeat("b", 64), strings.Repeat("é", 120) - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - linear\n - name: "+alias+"\n connector: "+connector+"\n connection: "+label+"\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - want := []acceleration.LeftOutConnector{{Name: alias, ConnectorId: connector, Connection: label}} - if got := router.syncs[0].LeftOutConnectors; got == nil || !reflect.DeepEqual(*got, want) { - t.Errorf("left_out_connectors went as %+v", got) - } -} - -// The same holds for a multibyte alias and connector id, whose bytes are over the caps and -// whose runes are at them. -func TestSyncCountsRunesNotBytesInTheNameAndConnectorOfALeftOutEntry(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - alias, connector := strings.Repeat("é", 63), strings.Repeat("é", 64) - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - linear\n - name: "+alias+"\n connector: "+connector+"\n connection: team\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if got := router.syncs[0].LeftOutConnectors; got == nil || len(*got) != 1 { - t.Errorf("left_out_connectors went as %+v", got) - } -} - -// The router takes at most 64 entries. More are left out of the list, so the sync is not -// refused where it synced before, and each is still warned about. -func TestSyncSendsAtMost64LeftOutEntries(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - yaml := "name: concierge\nconnectors:\n" - for i := range 65 { - yaml += fmt.Sprintf(" - name: c%d\n connector: github\n connection: team\n", i) - } - write(t, root, "agent.yaml", yaml) - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - var logged bytes.Buffer - agent := agentOn(t, router, Options{Dir: root, Logger: slog.New(slog.NewTextHandler(&logged, nil))}) - - if _, err := agent.Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - sent := router.syncs[0].LeftOutConnectors - if sent == nil || len(*sent) != 64 || (*sent)[63].Name != "c63" { - t.Errorf("left_out_connectors went as %+v", sent) - } - if !strings.Contains(logged.String(), "connector=c64 ") { - t.Errorf("no warning for the 65th in %q", logged.String()) - } -} - -// Two entries left out: each is warned about, and the hash covers both, so finding one of the -// connections later still changes it. -func TestSyncOfTwoMissingConnectionsWarnsOfBothAndAddsOneOnceItExists(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connection: company\n - name: chat\n connection: team\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - var logged bytes.Buffer - if _, err := agentOn(t, router, Options{Dir: root, Logger: slog.New(slog.NewTextHandler(&logged, nil))}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - for _, want := range []string{"connector=issues connection=company", "connector=chat connection=team"} { - if !strings.Contains(logged.String(), want) { - t.Errorf("no warning with %q in %q", want, logged.String()) - } - } - - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("conn-1", "company")) - }) - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 2 { - t.Fatalf("%d syncs were sent", len(router.syncs)) - } - if router.syncs[0].Hash == router.syncs[1].Hash { - t.Errorf("both syncs sent hash %q, so the router keeps the first", router.syncs[0].Hash) - } - sent := router.syncs[1].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Name != "issues" { - t.Errorf("connectors went as %+v", sent) - } -} - -func TestSyncRefusesARequiredConnectorWhoseConnectionIsMissing(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connection: missing\n required: true\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - agent := agentOn(t, router, Options{Dir: root}) - - _, err := agent.Sync(t.Context()) - if err == nil || !strings.Contains(err.Error(), `connector "issues"`) || !strings.Contains(err.Error(), `"missing"`) || - !strings.Contains(err.Error(), "add the connection, or drop required") { - t.Fatalf("sync error = %v", err) - } - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncRaw) != 0 { - t.Errorf("a sync was sent: %s", router.syncRaw[0]) - } -} - -func TestSyncFailsWhenConnectionsCannotBeListed(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connection: work\n") - closed := httptest.NewServer(http.NotFoundHandler()) - closed.Close() - agent, err := New(Options{Dir: root, LLM: stream.Accelerated(stream.Config{ - Backend: stream.Backend{URL: closed.URL, CustomerID: "acme"}, - })}) - if err != nil { - t.Fatal(err) - } - - if _, err := agent.Sync(t.Context()); err == nil || !strings.Contains(err.Error(), "listing connections") { - t.Fatalf("sync error = %v", err) - } -} - -// The router does nothing for a hash it already stored (acceleration/internal/api/sync.go:180), -// so the sync that finds the connection has to send another one. -func TestASyncThatLeftAConnectorOutAddsItOnceTheConnectionExists(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connection: company\n") - router := newBackend(t) - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("other", "work")) - }) - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - - router.answerConnections(func(*http.Request) acceleration.ConnectionPage { - return connectionPage("", listedConnection("conn-1", "company")) - }) - for range 2 { - if _, err := agentOn(t, router, Options{Dir: root}).Sync(t.Context()); err != nil { - t.Fatal(err) - } - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.syncs) != 2 { - t.Fatalf("three syncs, the last of an unchanged directory, sent %d requests", len(router.syncs)) - } - if router.syncs[0].Hash == router.syncs[1].Hash { - t.Errorf("both syncs sent hash %q, so the router keeps the first", router.syncs[0].Hash) - } - sent := router.syncs[1].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Connection.ConnectionId == nil || *(*sent)[0].Connection.ConnectionId != "conn-1" { - t.Errorf("connectors went as %+v", sent) - } -} - -func TestSyncStopsWhenAConnectionPageRepeatsItsCursor(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connector: linear\n connection: work\n") - router := newBackend(t) - router.answerConnections(func(r *http.Request) acceleration.ConnectionPage { - if r.URL.Query().Get("cursor") == "" { - return connectionPage("again", listedConnection("other", "nope")) - } - return connectionPage("again", listedConnection("the-one", "work")) - }) - agent := agentOn(t, router, Options{Dir: root}) - - ctx, cancel := context.WithTimeout(t.Context(), time.Second) - defer cancel() - if _, err := agent.Sync(ctx); err != nil { - t.Fatal(err) - } - - router.mu.Lock() - defer router.mu.Unlock() - if len(router.connectionQueries) != 2 { - t.Fatalf("queries = %v", router.connectionQueries) - } - sent := router.syncs[0].Connectors - if sent == nil || len(*sent) != 1 || (*sent)[0].Connection.ConnectionId == nil || *(*sent)[0].Connection.ConnectionId != "the-one" { - t.Errorf("issues went as %+v", sent) - } -} - -func TestSyncRefusesALabelSharedByTwoConnections(t *testing.T) { - root := filepath.Join(t.TempDir(), "concierge") - write(t, root, "agent.yaml", "name: concierge\nconnectors:\n - name: issues\n connection: work\n") - router := newBackend(t) - router.answerConnections(func(r *http.Request) acceleration.ConnectionPage { - if r.URL.Query().Get("cursor") == "" { - return connectionPage("2", listedConnection("a", "work")) - } - return connectionPage("", listedConnection("b", "work")) - }) - agent := agentOn(t, router, Options{Dir: root}) - - _, err := agent.Sync(t.Context()) - if err == nil || !strings.Contains(err.Error(), `connector "issues"`) || !strings.Contains(err.Error(), "matches 2") { - t.Fatalf("sync error = %v", err) - } -} - -func listedConnection(id, label string) acceleration.Connection { - return acceleration.Connection{Id: &id, Label: &label} -} - -func connectionPage(next string, items ...acceleration.Connection) acceleration.ConnectionPage { - copied := append([]acceleration.Connection(nil), items...) - page := acceleration.ConnectionPage{Items: &copied} - if next != "" { - page.NextCursor = &next - } - return page -} - func pointer[T any](value T) *T { return &value } diff --git a/sdks/go/agents/config.go b/sdks/go/agents/config.go index b4a276e41b..bea2572767 100644 --- a/sdks/go/agents/config.go +++ b/sdks/go/agents/config.go @@ -1,12 +1,13 @@ package agents import ( + "bytes" "context" - "errors" + "crypto/sha256" + "encoding/hex" + "encoding/json" "fmt" - "maps" "net/http" - "unicode/utf8" "github.com/GetStream/Vision-Agents/sdks/go/acceleration" "github.com/GetStream/Vision-Agents/sdks/go/stream" @@ -21,9 +22,9 @@ import ( // has a sandbox its skills are written before the config, so a config the router refuses // leaves those skill edits applied; a corrected retry converges. // -// An agent read from a directory is synced whole, with what its agent.yaml declares, and -// .agent_sync records the fingerprint of what was stored. A directory unchanged since then -// is only read back, not written again. +// An agent read from a directory is synced as its files, which the router reads, and +// .agent_sync records the fingerprint the router took of them. A directory unchanged since +// then is only read back, not sent again. func (a *Agent) Sync(ctx context.Context) (*acceleration.AgentConfig, error) { client, err := a.Client() if err != nil { @@ -33,7 +34,10 @@ func (a *Agent) Sync(ctx context.Context) (*acceleration.AgentConfig, error) { return a.syncFolder(ctx, client) } - skills := a.syncedSkills() + var skills []Skill + if a.options.Harness != nil { + skills = a.options.Harness.Skills + } wanted := acceleration.AgentConfigRequest{Name: a.options.Name} setString(&wanted.Instructions, a.options.Instructions) setString(&wanted.Guardrail, a.options.Guardrail) @@ -79,129 +83,52 @@ func (a *Agent) Sync(ctx context.Context) (*acceleration.AgentConfig, error) { return config, nil } -// syncFolder stores the agent's directory in one request. What the code set wins over what -// the directory says, and is part of the fingerprint, so changing either syncs again. +// syncFolder stores the agent's directory in one request: its files as they are, which the +// router reads, and what the code set beside them, which wins over them. func (a *Agent) syncFolder(ctx context.Context, client *acceleration.ClientWithResponses) (*acceleration.AgentConfig, error) { folder := a.folder - skills := a.syncedSkills() - hash := withUI(fingerprint(folder.Declaration, a.options.Instructions, a.options.Guardrail, - skills, folder.Knowledge, folder.KnowledgeURLs, folder.Simulations), folder.UIInstructions) - harness, subagent, sandbox := a.options.Harness.stored() - if harness != nil || subagent != nil || sandbox != nil || len(a.options.CostTracking) > 0 { - hash = fingerprint(hash, fmt.Sprint(deref(harness), deref(subagent), deref(sandbox)), - fmt.Sprint(a.options.CostTracking), nil, nil, nil, nil) + files, err := folder.files() + if err != nil { + return nil, err } - - if ReadStamp(folder.Path) == hash { - stored, err := storedConfig(ctx, client, a.options.Name) - if err != nil { - return nil, err - } - // A router older than ui_instructions takes the sync and drops them, which the stamp - // cannot tell, so a config missing the UI the stamp covers is synced again. - if stored != nil && (folder.UIInstructions == "" || deref(stored.UiInstructions) != "") { - return stored, nil - } + body := acceleration.SyncAgentFilesRequest{Name: &a.options.Name, Files: files} + if a.options.Instructions != folder.Instructions { + body.Instructions = &a.options.Instructions } - - body := acceleration.SyncAgentRequest{Name: a.options.Name, Hash: hash} - setString(&body.Instructions, a.options.Instructions) - setString(&body.Guardrail, a.options.Guardrail) - setString(&body.UiInstructions, folder.UIInstructions) - if len(skills) > 0 { - requests := make([]acceleration.SkillRequest, 0, len(skills)) - for _, skill := range skills { - requests = append(requests, skillRequestOf(skill)) - } - body.Skills = &requests + if a.options.Guardrail != folder.Guardrail { + body.Guardrail = &a.options.Guardrail } - if len(folder.Knowledge) > 0 { - documents := make([]acceleration.KnowledgeDocument, 0, len(folder.Knowledge)) - for _, document := range folder.Knowledge { - documents = append(documents, acceleration.KnowledgeDocument{Source: document.Source, Text: document.Text}) - } - body.Knowledge = &documents - } - if len(folder.KnowledgeURLs) > 0 { - pages := make([]acceleration.KnowledgeUrlDeclaration, 0, len(folder.KnowledgeURLs)) - for _, page := range folder.KnowledgeURLs { - declared := acceleration.KnowledgeUrlDeclaration{Url: page.URL} - setString(&declared.Title, page.Title) - setString(&declared.Description, page.Description) - if page.RefreshHours > 0 { - hours := int64(page.RefreshHours) - declared.RefreshHours = &hours - } - pages = append(pages, declared) - } - body.KnowledgeUrls = &pages + body.Harness, body.Subagent, body.Sandbox = a.options.Harness.stored() + if len(a.options.CostTracking) > 0 { + body.Tags = &a.options.CostTracking } - if folder.Simulations != nil { - declared := make([]acceleration.SimulationDeclaration, 0, len(folder.Simulations)) - for _, simulation := range folder.Simulations { - declared = append(declared, simulationDeclarationOf(simulation)) + if a.skillsInCode { + requests := make([]acceleration.SkillRequest, 0, len(a.options.Harness.Skills)) + for _, skill := range a.options.Harness.Skills { + requests = append(requests, skillRequestOf(skill)) } - body.Simulations = &declared + body.Skills = &requests } - declareSettings(&body, folder.Settings) - bindings, missing, err := connectorBindings(ctx, client, folder.Settings) + + // Nothing is sent when the directory and what the code set are what was last sent, and the + // config still is what the router then stored: one somebody has edited or synced since, or + // one on another router, is synced again, and so is one that left a connector out, so the + // sync that finds its connection is made. + hash, err := sentHash(body) if err != nil { - return nil, err - } - body.Connectors = bindings - for _, connection := range missing { - a.logger.Warn("agent.yaml connector left out: the app has no such connection", - "agent", a.options.Name, "connector", connection.name, "connection", connection.token) - } - if len(missing) > 0 { - // Sent so the router stores them and the dashboard can say what the agent is missing. - // An entry over the router's caps is left out of the list (the warning above still - // names it), and so is one past the router's 64, so a sync never fails over the list. - leftOut := make([]acceleration.LeftOutConnector, 0, len(missing)) - for _, connection := range missing { - if len(leftOut) == maxLeftOutEntries { - break - } - if utf8.RuneCountInString(connection.name) > maxLeftOutName || - utf8.RuneCountInString(connection.connectorID) > maxLeftOutConnectorID || - utf8.RuneCountInString(connection.token) > maxLeftOutConnection { - continue - } - leftOut = append(leftOut, acceleration.LeftOutConnector{ - Name: connection.name, ConnectorId: connection.connectorID, Connection: connection.token, - }) - } - if len(leftOut) > 0 { - body.LeftOutConnectors = &leftOut - } - // Another hash for a sync that left a connector out, sent and stamped: the router does - // nothing for a hash it already stored, and the sync that finds the connection must not - // be taken for this one. The marker keeps it from being the hash a sync that left the - // same connectors out sent before the list was sent, which the router has stored - // without the list. - body.Hash = fingerprint(hash, "missing connections", "left_out_connectors "+fmt.Sprint(missing), nil, nil, nil, nil) - } - if harness != nil { - body.Harness = harness - } - if subagent != nil { - body.Subagent = subagent - } - if sandbox != nil { - body.Sandbox = sandbox + return nil, fmt.Errorf("agents: syncing %s: %w", a.options.Name, err) } - if len(a.options.CostTracking) > 0 { - tags := map[string]string{} - if body.Tags != nil { - tags = *body.Tags + if stamp := readStamp(folder.Path); stamp.Hash == hash { + stored, err := storedConfig(ctx, client, a.options.Name) + if err != nil { + return nil, err } - for key, value := range a.options.CostTracking { - tags[key] = value + if stored != nil && deref(stored.SyncHash) == stamp.SyncHash && len(deref(stored.LeftOutConnectors)) == 0 { + return stored, nil } - body.Tags = &tags } - synced, err := client.SyncAgentWithResponse(ctx, body) + synced, err := client.SyncAgentFilesWithResponse(ctx, body) if err != nil { return nil, fmt.Errorf("agents: syncing %s: %w", a.options.Name, err) } @@ -212,373 +139,34 @@ func (a *Agent) syncFolder(ctx context.Context, client *acceleration.ClientWithR for _, warning := range deref(result.Warnings) { a.logger.Warn("synced with a warning", "agent", a.options.Name, "warning", warning) } - if err := WriteStamp(folder.Path, body.Hash); err != nil { + if err := writeStamp(folder.Path, syncStamp{Hash: hash, SyncHash: deref(result.Config.SyncHash)}); err != nil { return nil, err } return &result.Config, nil } -// declareSettings carries what agent.yaml declared onto the sync request. Only what the file -// names is sent, so the router leaves whatever is already stored for the rest. -func declareSettings(body *acceleration.SyncAgentRequest, settings Settings) { - if settings.Role != "" { - role := acceleration.AgentRole(settings.Role) - body.Role = &role - } - if settings.Mode != "" { - mode := acceleration.AgentMode(settings.Mode) - body.Mode = &mode - } - setString(&body.Region, settings.Region) - setString(&body.Stt, settings.STT) - setString(&body.Tts, settings.TTS) - body.Sts = settings.STS - setString(&body.Voice, settings.Voice) - setString(&body.Llm, settings.LLM) - if settings.Harness != "" { - harness := acceleration.Harness(settings.Harness) - body.Harness = &harness - } - if settings.Dispatch != nil { - body.Dispatch = &acceleration.AgentDispatch{} - if settings.Dispatch.IncomingCall != "" { - setting := acceleration.DispatchSetting(settings.Dispatch.IncomingCall) - body.Dispatch.IncomingCall = &setting - } - if settings.Dispatch.Text != "" { - setting := acceleration.DispatchSetting(settings.Dispatch.Text) - body.Dispatch.Text = &setting - } - } - setString(&body.Subagent, settings.Subagent) - setString(&body.Search, settings.Search) - // Sent even empty, since that is how a file turns drawing off. - body.Image = settings.Image - if settings.Greeting != nil { - body.Greeting = &acceleration.Greeting{Text: settings.Greeting.Text} - if settings.Greeting.Mode != "" { - mode := acceleration.GreetingMode(settings.Greeting.Mode) - body.Greeting.Mode = &mode - } - } - if settings.Sandbox != "" { - sandbox := acceleration.Sandbox(settings.Sandbox) - body.Sandbox = &sandbox - } - if options := settings.SandboxOptions; options != nil { - timeout := options.timeout.Milliseconds() - cpu, memory, disk := int64(options.CPU), int64(options.MemoryGB), int64(options.DiskGB) - body.SandboxOptions = &acceleration.SandboxOptions{ - Image: &options.Image, Setup: &options.Setup, TimeoutMs: &timeout, - Cpu: &cpu, MemoryGb: &memory, DiskGb: &disk, Network: &options.Network, - AllowedDomains: &options.AllowedDomains, NetworkAllowList: &options.NetworkAllowList, - } - } - if settings.Tools != nil { - groups := make([]acceleration.ToolGroup, 0, len(*settings.Tools)) - for _, group := range *settings.Tools { - sent := acceleration.ToolGroup{Name: group.Name, Tools: group.Tools} - if group.Loading != "" { - loading := acceleration.ToolLoading(group.Loading) - sent.Loading = &loading - } - if group.OutputRetention != "" { - sent.OutputRetention = &group.OutputRetention - } - groups = append(groups, sent) - } - body.Tools = &groups - } - if settings.Channels != nil { - declared := acceleration.AgentChannels{ - Whatsapp: channelLine(settings.Channels.WhatsApp), - Sms: channelLine(settings.Channels.SMS), - Imessage: channelLine(settings.Channels.IMessage), - } - if settings.Channels.Identity != "" { - identity := acceleration.ChannelIdentity(settings.Channels.Identity) - declared.Identity = &identity - } - body.Channels = &declared - } - if settings.ChatChannels != nil { - named := make([]acceleration.AgentChatChannel, 0, len(*settings.ChatChannels)) - for _, channel := range *settings.ChatChannels { - declared := acceleration.AgentChatChannel{Type: channel.Type} - if channel.Answer != "" { - answer := acceleration.ChatChannelAnswer(channel.Answer) - declared.Answer = &answer - } - named = append(named, declared) - } - body.ChatChannels = &named - } - if settings.Scheduling != nil { - declared := acceleration.AgentScheduling{ - Enabled: settings.Scheduling.Enabled, - DefaultTimezone: &settings.Scheduling.DefaultTimezone, - } - if settings.Scheduling.MaxTasksPerUser != nil { - maximum := int64(*settings.Scheduling.MaxTasksPerUser) - declared.MaxTasksPerUser = &maximum - } - if settings.Scheduling.DefaultTimezone == "" { - declared.DefaultTimezone = nil - } - body.Scheduling = &declared - } - body.Calls = declareCalls(settings.Calls) - body.FloorControl = declareFloorControl(settings.FloorControl) - if len(settings.Keyterms) > 0 { - body.Keyterms = &settings.Keyterms - } - if len(settings.Tags) > 0 { - tags := maps.Clone(settings.Tags) - body.Tags = &tags - } - if settings.Agents != nil { - agents := make([]acceleration.ChildAgent, 0, len(*settings.Agents)) - for _, child := range *settings.Agents { - declared := acceleration.ChildAgent{Config: child.Config, Tool: child.Tool} - setString(&declared.Description, child.Description) - if child.TimeoutMs > 0 { - timeout := int64(child.TimeoutMs) - declared.TimeoutMs = &timeout - } - if child.MaxToolRounds != 0 { - rounds := int64(child.MaxToolRounds) - declared.MaxToolRounds = &rounds - } - agents = append(agents, declared) - } - body.Agents = &agents - } - if settings.Video != nil { - body.Video = &acceleration.SessionVideo{MaxFrames: &settings.Video.MaxFrames} - setString(&body.Video.Source, settings.Video.Source) - } -} - -// declareCalls always fills the whole block, so a sync resets what a file leaves out. -func declareCalls(calls *CallSettings) *acceleration.AgentCalls { - if calls == nil { - calls = &CallSettings{} - } - endCall := calls.EndCall - if endCall == nil { - endCall = &EndCallSettings{} - } - press := calls.Press - if press == nil { - press = &CallToolSettings{} - } - transfer := calls.Transfer - if transfer == nil { - transfer = &TransferSettings{} - } - destinations := make([]acceleration.TransferDestination, 0, len(transfer.Destinations)) - for _, destination := range transfer.Destinations { - declared := acceleration.TransferDestination{Name: destination.Name, Number: destination.Number, Warm: &destination.Warm} - if destination.When != "" { - declared.When = &destination.When - } - destinations = append(destinations, declared) - } - declared := &acceleration.AgentCalls{ - EndCall: &acceleration.EndCallSettings{Enabled: enabledOr(endCall.Enabled, false)}, - Press: &acceleration.PressSettings{Enabled: enabledOr(press.Enabled, true)}, - Transfer: &acceleration.TransferSettings{Enabled: enabledOr(transfer.Enabled, true), Destinations: &destinations}, - } - if endCall.When != "" { - declared.EndCall.When = &endCall.When - } - return declared -} - -// declareFloorControl is what the file says of floor_control for the wire, as written, or nil -// when it says nothing, which leaves the stored choice. An empty mapping is sent as an empty -// object, no choice again, which the router's default rules; {model: flow-controller} keeps -// the flow controller whatever that default. -func declareFloorControl(settings *FloorControlSettings) *acceleration.FloorControl { - if settings == nil { - return nil - } - declared := &acceleration.FloorControl{Model: settings.Model} - if settings.MaxWaitMs != nil { - wait := int64(*settings.MaxWaitMs) - declared.MaxWaitMs = &wait - } - return declared -} - -func enabledOr(enabled *bool, fallback bool) *bool { - if enabled == nil { - return &fallback - } - return enabled -} - -// connectorBindings are the connectors agent.yaml names, in the shape the sync takes. -// Nil when the key was left out, so the stored bindings stay; empty when the file -// lists none, which removes them. -// -// An entry whose connection the app does not have is left out and returned, so the rest of -// the agent still syncs, unless the entry is required: a session needs that one. -func connectorBindings(ctx context.Context, client *acceleration.ClientWithResponses, settings Settings) (*[]acceleration.AgentConnectorBinding, []missingConnection, error) { - if settings.Connectors == nil { - return nil, nil, nil - } - bindings := make([]acceleration.AgentConnectorBinding, 0, len(settings.Connectors)) - var missing []missingConnection - for _, entry := range settings.Connectors { - binding, err := connectorBinding(ctx, client, entry) - var absent missingConnection - if errors.As(err, &absent) { - if deref(entry.Required) { - return nil, nil, fmt.Errorf("%w: add the connection, or drop required", err) - } - missing = append(missing, absent) - continue - } - if err != nil { - return nil, nil, err - } - bindings = append(bindings, binding) - } - return &bindings, missing, nil -} - -// The longest alias, connector id and connection label the router takes in a -// left_out_connectors entry (LeftOutConnector in acceleration/internal/api/sync.go). -const ( - maxLeftOutName = 63 - maxLeftOutConnectorID = 64 - maxLeftOutConnection = 120 - maxLeftOutEntries = 64 -) - -// missingConnection is a connection an agent.yaml entry names that the app does not have. -// -// The sync's hash prints a list of them, which formats each through Error, so a field that -// Error leaves out does not change the hash. The hash also carries a "left_out_connectors" -// marker, so it is not the one a sync sent before the list was sent. -type missingConnection struct { - name, token string - connectorID string -} - -func (m missingConnection) Error() string { - return fmt.Sprintf("agents: connector %q: no app connection with id or label %q", m.name, m.token) -} - -func connectorBinding(ctx context.Context, client *acceleration.ClientWithResponses, entry ConnectorSettings) (acceleration.AgentConnectorBinding, error) { - connectorID := entry.Connector - if connectorID == "" { - connectorID = entry.Name - } - patterns := []string{"*"} - if entry.Tools != nil { - patterns = append([]string(nil), (*entry.Tools)...) - } - binding := acceleration.AgentConnectorBinding{ - Name: entry.Name, - ConnectorId: connectorID, - Tools: []acceleration.ConnectorToolGrant{}, - ToolPatterns: &patterns, - Required: entry.Required, - Connection: acceleration.AgentConnectorSelection{Type: acceleration.AgentConnectorSelectionTypeSession}, - } - binding.RequireApproval = entry.RequireApproval - if entry.Loading != "" { - loading := acceleration.ToolLoading(entry.Loading) - binding.Loading = &loading - } - if entry.OutputRetention != "" { - binding.OutputRetention = &entry.OutputRetention - } - if entry.Sandbox { - binding.Sandbox = &entry.Sandbox - } - if entry.Connection == nil { - return binding, nil - } - id, err := fixedConnection(ctx, client, entry.Name, connectorID, *entry.Connection) - if err != nil { - return acceleration.AgentConnectorBinding{}, err - } - binding.Connection = acceleration.AgentConnectorSelection{ - Type: acceleration.AgentConnectorSelectionTypeFixed, - ConnectionId: &id, - } - return binding, nil -} - -// fixedConnection is the app connection entry names, by id or by the one label that -// matches. An id wins over a label. Every page is read first: a label on an early page -// must not hide the id on a later one, and a label is only unique once the list ends. -func fixedConnection(ctx context.Context, client *acceleration.ClientWithResponses, name, connectorID, token string) (string, error) { - connections, err := appConnections(ctx, client, connectorID) +// sentHash is the fingerprint .agent_sync keeps of a sync's request: the SHA-256, in hex, of +// the request as JSON with every object's keys in order and nothing between its tokens. It +// is the one the JavaScript SDK takes (sentHash in sdks/js/src/agent.ts), so a directory +// either of them synced is not sent again by the other. +func sentHash(body acceleration.SyncAgentFilesRequest) (string, error) { + encoded, err := json.Marshal(body) if err != nil { - return "", fmt.Errorf("agents: connector %q: %w", name, err) - } - for _, connection := range connections { - if connection.Id != nil && *connection.Id == token { - return *connection.Id, nil - } - } - var labels []string - for _, connection := range connections { - if connection.Label != nil && *connection.Label == token && connection.Id != nil { - labels = append(labels, *connection.Id) - } + return "", err } - switch len(labels) { - case 1: - return labels[0], nil - case 0: - return "", missingConnection{name: name, token: token, connectorID: connectorID} - default: - return "", fmt.Errorf("agents: connector %q: %q matches %d app connections", name, token, len(labels)) + var ordered any + if err := json.Unmarshal(encoded, &ordered); err != nil { + return "", err } -} - -func appConnections(ctx context.Context, client *acceleration.ClientWithResponses, connectorID string) ([]acceleration.Connection, error) { - // Named although omitted is app, so a router from before owner_type was optional answers too. - app := acceleration.ConnectionOwnerTypeApp - var cursor *string - asked := map[string]bool{} - var connections []acceleration.Connection - for { - key := "" - if cursor != nil { - key = *cursor - } - if asked[key] { - break - } - asked[key] = true - - listed, err := client.ListConnectionsWithResponse(ctx, &acceleration.ListConnectionsParams{ - OwnerType: &app, - ConnectorId: &connectorID, - Cursor: cursor, - }) - if err != nil { - return nil, fmt.Errorf("listing connections: %w", err) - } - page, err := answer(listed.JSON200, listed.HTTPResponse, listed.Body) - if err != nil { - return nil, err - } - if page.Items != nil { - connections = append(connections, (*page.Items)...) - } - if page.NextCursor == nil || *page.NextCursor == "" { - break - } - cursor = page.NextCursor + var canonical bytes.Buffer + encoder := json.NewEncoder(&canonical) + // JavaScript writes <, > and & as they are. + encoder.SetEscapeHTML(false) + if err := encoder.Encode(ordered); err != nil { + return "", err } - return connections, nil + hashed := sha256.Sum256(bytes.TrimSuffix(canonical.Bytes(), []byte("\n"))) + return hex.EncodeToString(hashed[:]), nil } // storedConfig is the config stored under a name, or nil when there is none. @@ -602,18 +190,6 @@ func storedConfig(ctx context.Context, client *acceleration.ClientWithResponses, return nil, nil } -// syncedSkills are the skills the stored config should name. The harness is the whole of -// them: a directory's skills are folded into it when the agent is built. -func (a *Agent) syncedSkills() []Skill { - if a.options.Harness != nil && len(a.options.Harness.Skills) > 0 { - return a.options.Harness.Skills - } - if a.folder != nil { - return a.folder.Skills - } - return nil -} - // DefineAgent stores an agent configuration on the router backend points at, editing // whichever is already under that name. func DefineAgent( @@ -731,36 +307,6 @@ func skillRequestOf(skill Skill) acceleration.SkillRequest { return body } -func simulationDeclarationOf(simulation Simulation) acceleration.SimulationDeclaration { - declared := acceleration.SimulationDeclaration{ - Name: simulation.Name, - Scenario: simulation.Scenario, - Assertion: simulation.Assertion, - } - if simulation.Mode != "" { - mode := acceleration.SimulationDeclarationMode(simulation.Mode) - declared.Mode = &mode - } - if simulation.Variations > 0 { - variations := int64(simulation.Variations) - declared.Variations = &variations - } - if simulation.MaxTurns > 0 { - turns := int64(simulation.MaxTurns) - declared.MaxTurns = &turns - } - setString(&declared.CallerTarget, simulation.CallerTarget) - setString(&declared.JudgeTarget, simulation.JudgeTarget) - setString(&declared.CallerStt, simulation.CallerSTT) - setString(&declared.CallerTts, simulation.CallerTTS) - setString(&declared.CallerVoice, simulation.CallerVoice) - if len(simulation.Tags) > 0 { - tags := maps.Clone(simulation.Tags) - declared.Tags = &tags - } - return declared -} - // IngestKnowledge fills a knowledge base with documents an agent can look things up in. // // The documents are cut into passages by the backend, so a directory pushed from here and @@ -853,11 +399,3 @@ func setString(field **string, value string) { *field = &value } } - -// channelLine is one declared channel for the wire, or nothing when it names no number. -func channelLine(line *ChannelSettings) *acceleration.ChannelLineRequest { - if line == nil || line.Number == "" { - return nil - } - return &acceleration.ChannelLineRequest{Number: line.Number} -} diff --git a/sdks/go/agents/folder.go b/sdks/go/agents/folder.go index d3d02f8aec..aa1f073971 100644 --- a/sdks/go/agents/folder.go +++ b/sdks/go/agents/folder.go @@ -20,6 +20,8 @@ import ( "unicode/utf8" "gopkg.in/yaml.v3" + + "github.com/GetStream/Vision-Agents/sdks/go/acceleration" ) // AgentFile is what makes a directory an agent: it names it and says what it runs on. @@ -701,6 +703,94 @@ func Load(path string) (*Folder, error) { return folder, nil } +// maxSyncBytes is how much a sync of a directory may send: what the router takes (MaxBytes in +// acceleration/internal/agentdir), checked here so a directory over it is told so by name +// rather than by a refused request. +const maxSyncBytes = 8 << 20 + +// files reads the directory's files as a sync sends them to the router, which reads them: by +// slash path, in path order. They are the files the format names and no others, so a +// directory kept beside a program's source sends none of it: agent.yaml, instructions.md, +// guardrail.md, what is under skills/, knowledge/ and ui/, the .yaml and .yml files of +// simulations/, and the two files agent.yaml's ui may name elsewhere. +// +// Hidden files, __pycache__ and node_modules are left behind, as the router skips them, and +// so is anything that is not a regular file of text. A link is read only to a file inside +// the directory: one that leads out of it is refused, so a link left pointing at a +// credentials file is never synced, and one to a folder is not followed. +func (f *Folder) files() ([]acceleration.DirectoryFile, error) { + root, err := filepath.EvalSymlinks(f.Path) + if err != nil { + return nil, fmt.Errorf("agents: reading %s: %w", f.Path, err) + } + var files []acceleration.DirectoryFile + held := 0 + read := func(file string) error { + target, err := filepath.EvalSymlinks(file) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("agents: reading %s: %w", file, err) + } + if inside, err := filepath.Rel(root, target); err != nil || inside == ".." || strings.HasPrefix(inside, ".."+string(filepath.Separator)) { + return fmt.Errorf("agents: %s links outside the agent directory", file) + } + info, err := os.Stat(target) + if err != nil || !info.Mode().IsRegular() { + return err + } + content, err := os.ReadFile(target) + if err != nil || !utf8.Valid(content) { + return err + } + relative, err := filepath.Rel(f.Path, file) + if err != nil { + return err + } + if held += len(content); held > maxSyncBytes { + return fmt.Errorf("agents: %s holds more than the %d bytes a sync sends: take files out of it, knowledge first", f.Path, maxSyncBytes) + } + files = append(files, acceleration.DirectoryFile{Path: filepath.ToSlash(relative), Content: string(content)}) + return nil + } + + named := []string{AgentFile, InstructionsFile, GuardrailFile} + if ui := f.Settings.UI; ui != nil { + named = append(named, ui.Components, ui.Blueprints) + } + for _, name := range named { + if name != "" { + if err := read(filepath.Join(f.Path, filepath.FromSlash(name))); err != nil { + return nil, err + } + } + } + for _, dir := range []string{SkillsDir, KnowledgeDir, SimulationsDir, "ui"} { + top := filepath.Join(f.Path, dir) + err := filepath.WalkDir(top, func(file string, entry fs.DirEntry, err error) error { + switch { + case errors.Is(err, fs.ErrNotExist) && file == top: + return filepath.SkipAll + case err != nil: + return err + case file != top && skipped(entry.Name()) && entry.IsDir(): + return filepath.SkipDir + case entry.IsDir() || skipped(entry.Name()): + return nil + case dir == SimulationsDir && !slices.Contains([]string{".yaml", ".yml"}, strings.ToLower(filepath.Ext(file))): + return nil + } + return read(file) + }) + if err != nil { + return nil, err + } + } + slices.SortFunc(files, func(a, b acceleration.DirectoryFile) int { return strings.Compare(a.Path, b.Path) }) + return slices.CompactFunc(files, func(a, b acceleration.DirectoryFile) bool { return a.Path == b.Path }), nil +} + // fill puts what the directory says into whatever the options left empty. What is written // in code wins, so a directory is a starting point rather than an override. func (f *Folder) fill(options *Options) { @@ -816,32 +906,27 @@ func fingerprint( return hex.EncodeToString(hasher.Sum(nil)) } -// syncStamp is what .agent_sync holds. +// syncStamp is what .agent_sync holds: the fingerprint of what was sent, the sync_hash the +// router stored it under, and when. type syncStamp struct { Hash string `json:"hash"` + SyncHash string `json:"sync_hash,omitempty"` SyncedAt string `json:"synced_at"` } -// ReadStamp is the fingerprint a directory was last synced under, or empty when it never -// was or the stamp cannot be read. -func ReadStamp(path string) string { - raw, err := os.ReadFile(filepath.Join(path, AgentStamp)) - if err != nil { - return "" - } +// readStamp is what a directory was last synced as, or the zero stamp when it never was or +// the stamp cannot be read. +func readStamp(path string) syncStamp { var recorded syncStamp - if json.Unmarshal(raw, &recorded) != nil { - return "" + if raw, err := os.ReadFile(filepath.Join(path, AgentStamp)); err == nil { + _ = json.Unmarshal(raw, &recorded) } - return recorded.Hash + return recorded } -// WriteStamp records what was synced and when, so a second sync can do nothing. -func WriteStamp(path, hash string) error { - recorded, err := json.Marshal(syncStamp{ - Hash: hash, - SyncedAt: time.Now().UTC().Truncate(time.Second).Format("2006-01-02T15:04:05+00:00"), - }) +func writeStamp(path string, stamp syncStamp) error { + stamp.SyncedAt = time.Now().UTC().Truncate(time.Second).Format("2006-01-02T15:04:05+00:00") + recorded, err := json.Marshal(stamp) if err != nil { return err } @@ -851,6 +936,17 @@ func WriteStamp(path, hash string) error { return nil } +// ReadStamp is the fingerprint a directory was last synced under, or empty when it never +// was or the stamp cannot be read. +func ReadStamp(path string) string { + return readStamp(path).Hash +} + +// WriteStamp records what was synced and when, so a second sync can do nothing. +func WriteStamp(path, hash string) error { + return writeStamp(path, syncStamp{Hash: hash}) +} + // AgentSettings is one of agent.yaml's agents: another of the app's text agents, offered to // this one's model as a tool that hands it work and answers with what it said. type AgentSettings struct { @@ -1019,10 +1115,11 @@ func loadSkillFiles(dir string) (map[string]string, error) { return files, nil } -// skipped says whether a file or folder in a skill folder is left behind: hidden ones such -// as .DS_Store, and the __pycache__ that running a skill's Python scripts locally leaves. +// skipped says whether a file or folder is left behind wherever it is: hidden ones such as +// .DS_Store, the __pycache__ that running a skill's Python scripts locally leaves, and +// node_modules. It is what the router skips (hidden in acceleration/internal/agentdir). func skipped(name string) bool { - return strings.HasPrefix(name, ".") || name == "__pycache__" + return strings.HasPrefix(name, ".") || name == "__pycache__" || name == "node_modules" } // parseSkill reads a skill file: frontmatter between --- lines, then the instructions. diff --git a/sdks/go/agents/folder_test.go b/sdks/go/agents/folder_test.go index ded5276161..89d7481667 100644 --- a/sdks/go/agents/folder_test.go +++ b/sdks/go/agents/folder_test.go @@ -1,12 +1,17 @@ package agents import ( + "fmt" "os" "path/filepath" "reflect" + "slices" "strings" + "syscall" "testing" "time" + + "github.com/GetStream/Vision-Agents/sdks/go/acceleration" ) // write puts a file in a directory under the test's own temporary one. @@ -1057,3 +1062,126 @@ func TestASkillsFilesChangeTheHashOnlyWhenThereAreSome(t *testing.T) { t.Error("a file added to a skill left the hash as it was") } } + +// sent are the paths of the files a sync of a directory would send. +func sent(t *testing.T, root string) []string { + t.Helper() + folder, err := Load(root) + if err != nil { + t.Fatal(err) + } + files, err := folder.files() + if err != nil { + t.Fatal(err) + } + paths := make([]string, 0, len(files)) + for _, file := range files { + paths = append(paths, file.Path) + } + return paths +} + +func TestASyncSendsTheFilesTheFormatNamesAndNothingElseOfTheFolder(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\nui:\n blueprints: design/recipes.yaml\n") + write(t, root, "instructions.md", "You are Jean.\n") + write(t, root, "design/recipes.yaml", "- name: booking\n when: booking a table\n order: [CardHeader]\n") + write(t, root, "design/other.yaml", "not named by agent.yaml\n") + write(t, root, "ui/components.json", "[]\n") + write(t, root, "skills/pdf/SKILL.md", "---\ndescription: Fill a form\n---\nRun it.\n") + write(t, root, "skills/pdf/fill.py", "print()\n") + write(t, root, "knowledge/pricing.md", "Pro.\n") + write(t, root, "knowledge/data.csv", "a,b\n") + write(t, root, "simulations/lunch.yaml", "- name: lunch\n scenario: Ask.\n assertion: Answered.\n") + write(t, root, "simulations/notes.md", "not a simulations file\n") + // What a project keeps beside its agent, none of which is the agent. + write(t, root, "main.go", "package main\n") + write(t, root, ".env", "SECRET=1\n") + write(t, root, "go.sum", "example.com/x v1.0.0 h1:abc\n") + write(t, root, "internal/keys/prod.pem", "-----BEGIN PRIVATE KEY-----\n") + write(t, root, "skills/pdf/.DS_Store", "\x00") + write(t, root, "skills/pdf/__pycache__/fill.cpython-312.pyc", "\x00\xff") + write(t, root, "knowledge/node_modules/left-pad/index.js", "module.exports = 1\n") + write(t, root, "knowledge/diagram.png", "\x89PNG\xff\xfe") + + want := []string{ + "agent.yaml", "design/recipes.yaml", "instructions.md", "knowledge/data.csv", "knowledge/pricing.md", + "simulations/lunch.yaml", "skills/pdf/SKILL.md", "skills/pdf/fill.py", "ui/components.json", + } + if got := sent(t, root); !slices.Equal(got, want) { + t.Errorf("the sync would send %v", got) + } +} + +func TestASyncRefusesALinkOutOfTheDirectoryAndReadsOneWithinIt(t *testing.T) { + outside := t.TempDir() + write(t, outside, "secret.md", "the keys\n") + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\n") + write(t, root, "knowledge/pricing.md", "Pro.\n") + if err := os.Symlink(filepath.Join(root, "knowledge", "pricing.md"), filepath.Join(root, "knowledge", "plans.md")); err != nil { + t.Skip("this file system has no symbolic links: ", err) + } + if err := os.Symlink(root, filepath.Join(root, "knowledge", "loop")); err != nil { + t.Fatal(err) + } + if got := sent(t, root); !slices.Equal(got, []string{"agent.yaml", "knowledge/plans.md", "knowledge/pricing.md"}) { + t.Errorf("the sync would send %v, a link back up the tree followed or a link within it left out", got) + } + + if err := os.Symlink(filepath.Join(outside, "secret.md"), filepath.Join(root, "knowledge", "leak.md")); err != nil { + t.Fatal(err) + } + folder, err := Load(root) + if err != nil { + t.Skip("Load itself refused the link: ", err) + } + if _, err := folder.files(); err == nil || !strings.Contains(err.Error(), "leak.md links outside the agent directory") { + t.Errorf("a link out of the directory was read with %v", err) + } +} + +func TestASyncSkipsWhatIsNotARegularFileRatherThanWaitOnIt(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\n") + write(t, root, "ui/components.json", "[]\n") + if err := syscall.Mkfifo(filepath.Join(root, "ui", "pipe"), 0o644); err != nil { + t.Skip("this system makes no named pipes: ", err) + } + + if got := sent(t, root); !slices.Equal(got, []string{"agent.yaml", "ui/components.json"}) { + t.Errorf("the sync would send %v", got) + } +} + +func TestADirectoryOverWhatASyncSendsIsRefusedHereByName(t *testing.T) { + root := filepath.Join(t.TempDir(), "jean") + write(t, root, "agent.yaml", "name: jean\n") + for index := range 9 { + write(t, root, fmt.Sprintf("knowledge/%d.md", index), strings.Repeat("a", 1<<20)) + } + folder, err := Load(root) + if err != nil { + t.Fatal(err) + } + + if _, err := folder.files(); err == nil || !strings.Contains(err.Error(), "holds more than the 8388608 bytes a sync sends") { + t.Errorf("a directory over the limit was read with %v", err) + } +} + +func TestTheFingerprintOfARequestIsTheOneTheJavaScriptSDKTakes(t *testing.T) { + name := "jean" + hash, err := sentHash(acceleration.SyncAgentFilesRequest{ + Name: &name, Tags: &map[string]string{"b": "<2>", "a": "1"}, + Files: []acceleration.DirectoryFile{{Path: "agent.yaml", Content: "name: jean\n"}}, + }) + if err != nil { + t.Fatal(err) + } + // sha256 of {"files":[{"content":"name: jean\n","path":"agent.yaml"}],"name":"jean","tags":{"a":"1","b":"<2>"}}, + // which sdks/js/tests/agent.test.ts holds the JavaScript SDK to as well. + if hash != "8e57238c214f215939fb6a466b9791aae8abbfd7df14e752f9d0d767aaed3ad9" { + t.Errorf("the request fingerprints as %s", hash) + } +} From c2e62a5cbf2ed4d362971894ab62288c0b988007 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Fri, 20 Nov 2026 17:39:58 +0100 Subject: [PATCH 4/6] feat(sdk-js): sync an agent directory as its files, which the router reads sync reads the files the format names when it syncs, and no other file of the folder, and sends a folder from loadFolder to POST /v1/agents/sync/files with what the code set beside it, which still wins: instructions, guardrail, harness, skills, the pipeline's models and the cost labels. The router reads the files, finds the connections and compiles ui:. loadFolder still parses the directory for the program holding it. A directory over what a sync sends is refused by name. .agent_sync keeps a hash of what was sent and the sync_hash the router stored it under, in the format the Go SDK writes, and a sync is skipped only while the stored config still has that hash and left no connector out. A folder built by hand without files, and an agent written in code, sync as before. --- .claude/skills/sdk-js/SKILL.md | 27 +- sdks/js/README.md | 8 +- sdks/js/src/agent.ts | 77 +++++ sdks/js/src/folder.ts | 97 +++++- sdks/js/src/generated/api.ts | 262 ++++++++++++++++- sdks/js/tests/agent.test.ts | 523 ++++++++++++++------------------- 6 files changed, 674 insertions(+), 320 deletions(-) diff --git a/.claude/skills/sdk-js/SKILL.md b/.claude/skills/sdk-js/SKILL.md index 126e5cd20a..71d813a134 100644 --- a/.claude/skills/sdk-js/SKILL.md +++ b/.claude/skills/sdk-js/SKILL.md @@ -238,11 +238,28 @@ would have to be found and undone by whoever fixes it. socket of its own for the next caller. - Instructions are the stored config's, written by `sync`: a session takes none. - What is written in code wins over what a `folder` says. A directory is a starting point. -- `sync` uses **`POST /v1/agents/sync`**, one request carrying the whole directory, not the - configs/skills/knowledge sequence, with the directory's knowledge urls as `knowledge_urls` in - the same body. It sends a SHA-256 `fingerprint` of everything in the body, and a folder - from `loadFolder` records it in `.agent_sync`, so syncing on startup sends nothing when - nothing changed. The stamp's file access is handed in as `Folder.stamp` by `./node`, which +- `sync` of a folder from `loadFolder` uses **`POST /v1/agents/sync/files`**: one request + carrying what `Folder.files()` reads at sync time and what the code set beside them + (instructions, guardrail, harness, skills, `pipeline` models and the cost labels), which + wins over the files. The files are the ones the format names and no others (`agent.yaml`, + `instructions.md`, `guardrail.md`, `skills/`, `knowledge/`, `ui/`, the YAML files of + `simulations/`, and the two files `ui:` may name elsewhere), so a directory kept beside a + program's source sends none of it; `directoryFiles` skips what the router skips and anything + that is not a regular file of text, and refuses a link out of the directory and a directory + over `MAX_SYNC_BYTES`. The router (`acceleration/internal/agentdir`) reads the files, finds + the connections and compiles `ui:`, so never add a key, a default or a mapping for agent.yaml + to the sync path. +- `.agent_sync` holds `hash`, the `sentHash` of the request, and `sync_hash`, what the router + stored it under: one format and one fingerprint with the Go SDK. A sync is skipped only while + both still hold: the request is the same, and the stored config has that `sync_hash` and left + no connector out. +- `loadFolder` still parses the directory with the hand parsers in `folder.ts` and the UI + compilers, to fill `Folder.settings`, `skills` and the rest for the program holding it, and + refuses a file it cannot read. It decides nothing about what is stored. Removing those + parsers is AI-3441; until then a key added to agent.yaml is added to the router first, and + here only so `loadFolder` does not refuse it. +- An agent written in code, or a `Folder` built by hand with no `files`, uses + **`POST /v1/agents/sync`** with the fields it holds and a SHA-256 `fingerprint` of them. The stamp's file access is handed in as `Folder.stamp` by `./node`, which keeps `Agent.sync` free of `node:fs` in the browser entry. - `resolveConfig` turns a config *name* into an id once and caches it. A name matching nothing stored is passed through, because it is then either an id or a mistake the router can report diff --git a/sdks/js/README.md b/sdks/js/README.md index 43bf4dbe33..a3b596e613 100644 --- a/sdks/js/README.md +++ b/sdks/js/README.md @@ -592,9 +592,11 @@ await agent.sync(); ``` `sync` stores it as a config a session can then be created from by name, in one request -carrying the files, the pages and what `agent.yaml` declares. A key `agent.yaml` does not -know is refused. The request carries a fingerprint of everything in it and `.agent_sync` -records it, so syncing on every startup only reads the config back when nothing has changed. +carrying the directory's files as they are, with whatever the code set beside them. The router +reads the files, so what `agent.yaml` means is the same for every SDK, the CLI and the +dashboard: it finds the connections the file names and compiles its `ui`. The router answers +with its hash of the request and `.agent_sync` records it, so syncing on every startup only +reads the config back when nothing has changed. A setting left out leaves whatever is stored — a model chosen in the dashboard survives a sync that says nothing about it. The harness (`harness`, subagent, sandbox and skills) is stored on the config this way too, never on a session: a session runs its config's. diff --git a/sdks/js/src/agent.ts b/sdks/js/src/agent.ts index e5ca215311..141bc4f240 100644 --- a/sdks/js/src/agent.ts +++ b/sdks/js/src/agent.ts @@ -209,6 +209,14 @@ export interface SyncStamp { export interface Folder { path: string; name: string; + /** + * Reads the directory's files for a sync: the ones the format names, each by its slash path, + * in path order. `loadFolder` gives it. A folder that has it is synced as its files, which + * the router reads: what agent.yaml means, and what it refuses, is then the router's to + * decide, the same for every client. A folder built by hand without it is synced as the + * fields below. + */ + files?: () => Promise; /** What agent.yaml declares. */ settings?: Declaration; instructions: string; @@ -550,6 +558,9 @@ export class Agent { * Server side only: how an agent is configured is not a browser's to rewrite. */ async sync(): Promise { + if (this.folder?.files) { + return this.syncFiles(this.folder, await this.folder.files()); + } const pipeline = this.options.pipeline ?? {}; const declared = this.folder?.settings ?? {}; const skills = this.harness?.skills ?? this.folder?.skills ?? []; @@ -639,6 +650,56 @@ export class Agent { return result; } + /** + * Stores a directory as its files, with what the code set beside it, which wins over them. + * The router reads the files, finds the connections agent.yaml names and compiles its `ui`. + */ + private async syncFiles(folder: Folder, files: Schemas["DirectoryFile"][]): Promise { + const { instructions, guardrail, pipeline = {}, costTracking: tags, harness } = this.options; + const thinking = harness?.subagents?.["default"]; + const greeting = greetingOf(pipeline).greeting; + const body: Schemas["SyncAgentFilesRequest"] = { + name: this.name, + files, + ...(instructions ? { instructions } : {}), + ...(guardrail ? { guardrail } : {}), + ...(harness?.name ? { harness: harness.name } : {}), + ...(thinking ? { subagent: thinking } : {}), + ...(harness?.vm ? { sandbox: harness.vm.provider } : {}), + ...(pipeline.llm ? { llm: pipeline.llm } : {}), + ...(pipeline.stt ? { stt: pipeline.stt } : {}), + ...(pipeline.tts ? { tts: pipeline.tts } : {}), + ...(pipeline.sts ? { sts: pipeline.sts } : {}), + ...(pipeline.voice ? { voice: pipeline.voice } : {}), + ...(greeting ? { greeting } : {}), + ...(pipeline.video ? { video: pipeline.video } : {}), + ...(tags && Object.keys(tags).length > 0 ? { tags } : {}), + // An empty list is sent too: skills written in code take the place of the directory's. + ...(harness?.skills ? { skills: harness.skills.map((skill) => ({ ...skillRequest(skill), config_id: "" })) } : {}), + }; + + // Nothing is sent when the directory and what the code set are what was last sent, and the + // config still is what the router then stored: one deleted, edited or synced since, or one + // on another router, is synced again, and so is one that left a connector out, so the sync + // that finds its connection is made. The stamp holds both: the fingerprint of what was + // sent and, after a colon, the sync_hash the router stored it under. + const sent = await sentHash(body); + const stamped = await folder.stamp?.read(); + if (stamped?.startsWith(`${sent}:`)) { + const [stored] = await this.client.get("/v1/agents/configs", { query: { name: this.name } }); + if ( + stored?.name === this.name && + stamped === `${sent}:${stored.sync_hash ?? ""}` && + !stored.left_out_connectors?.length + ) { + return { unchanged: true, config: stored }; + } + } + const result = await this.client.post("/v1/agents/sync/files", { body }); + await folder.stamp?.write(`${sent}:${result.config.sync_hash ?? ""}`); + return result; + } + /** The connectors agent.yaml names, in the shape the sync takes. */ private async bindings( declared: ConnectorDeclaration[], @@ -858,6 +919,22 @@ async function fingerprint(body: unknown): Promise { return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); } +/** + * The fingerprint `.agent_sync` keeps of a sync's request: the SHA-256, in hex, of the request + * as JSON with every object's keys in order and nothing between its tokens. It is the one the + * Go SDK takes (`sentHash` in sdks/go/agents/config.go), so a directory either of them synced + * is not sent again by the other. + */ +async function sentHash(body: Schemas["SyncAgentFilesRequest"]): Promise { + const canonical = JSON.stringify(body, (_, value: unknown) => + value && typeof value === "object" && !Array.isArray(value) + ? Object.fromEntries(Object.entries(value).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0))) + : value, + ); + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical)); + return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); +} + /** Refuses a harness that would mean something different on every run. */ function validate(harness: Harness | undefined): void { if (!harness) { diff --git a/sdks/js/src/folder.ts b/sdks/js/src/folder.ts index 910e5bae4a..8fbca1af15 100644 --- a/sdks/js/src/folder.ts +++ b/sdks/js/src/folder.ts @@ -1,4 +1,4 @@ -import { readFile, readdir, realpath, stat, writeFile } from "node:fs/promises"; +import { lstat, readFile, readdir, realpath, stat, writeFile } from "node:fs/promises"; import { basename, extname, isAbsolute, join, posix, relative, sep } from "node:path"; import type { ConnectorDeclaration, Declaration, Folder, Skill, SyncStamp } from "./agent.js"; @@ -95,6 +95,7 @@ export async function loadFolder(path: string): Promise { return { path, name: settings.name || basename(path.replace(/[/\\]+$/, "")), + files: () => directoryFiles(path, settings.ui), settings, stamp: stampAt(join(path, AGENT_STAMP)), instructions, @@ -110,6 +111,82 @@ export async function loadFolder(path: string): Promise { }; } +/** + * How much a sync of a directory may send: what the router takes (`MaxBytes` in + * acceleration/internal/agentdir), checked here so a directory over it is told so by name + * rather than by a refused request. + */ +const MAX_SYNC_BYTES = 8 << 20; + +/** + * Reads the directory's files as a sync sends them to the router, which reads them: by slash + * path, in path order. They are the files the format names and no others, so a directory kept + * beside a program's source sends none of it: agent.yaml, instructions.md, guardrail.md, what + * is under skills/, knowledge/ and ui/, the .yaml and .yml files of simulations/, and the two + * files agent.yaml's `ui` may name elsewhere. + * + * Hidden files, `__pycache__` and `node_modules` are left behind, as the router skips them, + * and so is anything that is not a regular file of text. A link is read only to a file inside + * the directory: one that leads out of it is refused, and one to a folder is not followed. + */ +async function directoryFiles(path: string, ui: UIDeclaration | undefined): Promise<{ path: string; content: string }[]> { + const files = new Map(); + const root = await realpath(path); + const text = new TextDecoder("utf-8", { fatal: true }); + const encoder = new TextEncoder(); + let held = 0; + const read = async (file: string): Promise => { + const info = await lstat(file).catch(missing); + if (!info || !(await syncedFile(root, file, info)) || !(await stat(file)).isFile()) { + return; + } + let content: string; + try { + content = text.decode(await readFile(file)); + } catch (cause) { + if (cause instanceof TypeError) { + return; + } + throw cause; + } + held += encoder.encode(content).length; + if (held > MAX_SYNC_BYTES) { + throw new ConfigurationError( + `${path} holds more than the ${MAX_SYNC_BYTES} bytes a sync sends: take files out of it, knowledge first`, + ); + } + files.set(relative(path, file).split(sep).join(posix.sep), content); + }; + const walk = async (top: string, directory: string): Promise => { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const file = join(directory, entry.name); + if (skipped(entry.name)) { + continue; + } + if (entry.isDirectory()) { + await walk(top, file); + } else if (top !== SIMULATIONS_DIR || [".yaml", ".yml"].includes(extname(entry.name).toLowerCase())) { + await read(file); + } + } + }; + + for (const name of [AGENT_FILE, INSTRUCTIONS_FILE, GUARDRAIL_FILE, ui?.components, ui?.blueprints]) { + if (name) { + await read(join(path, name)); + } + } + for (const top of [SKILLS_DIR, KNOWLEDGE_DIR, SIMULATIONS_DIR, "ui"]) { + if ((await stat(join(path, top)).catch(missing))?.isDirectory()) { + await insideAgent(root, join(path, top)); + await walk(top, join(path, top)); + } + } + return [...files] + .map(([name, content]) => ({ path: name, content })) + .sort((one, other) => (one.path < other.path ? -1 : one.path > other.path ? 1 : 0)); +} + /** * Reads every .yaml and .yml file in simulations/, by file name, each a list of simulations. * @@ -1735,7 +1812,11 @@ export function parseBlueprints(content: string, where = DEFAULT_UI_BLUEPRINTS): }); } -/** `.agent_sync`: the fingerprint a directory was last synced under, and when. */ +/** + * `.agent_sync`: what a directory was last synced as, and when. The file holds `hash`, the + * fingerprint of what was sent, and `sync_hash`, the hash the router stored it under, as the + * Go SDK writes it; a sync hands them over as one stamp, joined by a colon. + */ function stampAt(path: string): SyncStamp { return { async read() { @@ -1746,12 +1827,16 @@ function stampAt(path: string): SyncStamp { } catch { return ""; } - const hash = recorded && typeof recorded === "object" ? (recorded as { hash?: unknown }).hash : ""; - return typeof hash === "string" ? hash : ""; + const { hash, sync_hash: synced } = (recorded && typeof recorded === "object" ? recorded : {}) as Record; + if (typeof hash !== "string") { + return ""; + } + return typeof synced === "string" && synced ? `${hash}:${synced}` : hash; }, - async write(hash) { + async write(stamp) { + const [hash, synced] = stamp.split(":"); const syncedAt = new Date().toISOString().replace(/\.\d+Z$/, "+00:00"); - await writeFile(path, `${JSON.stringify({ hash, synced_at: syncedAt })}\n`); + await writeFile(path, `${JSON.stringify({ hash, ...(synced ? { sync_hash: synced } : {}), synced_at: syncedAt })}\n`); }, }; } diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index aeb83f9cc4..b7d267dcea 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -822,6 +822,30 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/v1/agents/configs/{id}/directory": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** + * An agent config as the files of its directory + * @description The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the agent's knowledge base as knowledge/ with the pages it is kept filled from in knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call tool at its default, a connector's tools when it grants every one), and a connector that says only its name written as the name alone. + * + * Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written with its connection's id, whatever label agent.yaml first named it by, and a skill the config no longer names is left out. + * + * Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + */ + readonly get: operations["getAgentDirectory"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/v1/agents/connections": { readonly parameters: { readonly query?: never; @@ -2806,6 +2830,32 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/v1/agents/sync/files": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly get?: never; + readonly put?: never; + /** + * Store an agent directory sent as its files + * @description POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It stores what that sync stores, with the same answer. + * + * A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 `invalid_agent_directory`) with every problem at its file, line and column in the error's `problems`. A connector's connection is found among the app's own by id or by label; one the app does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, unless the connector is required, which is refused. agent.yaml's `ui` is compiled into `ui_instructions` here. + * + * `dry_run` answers with what the sync would store and writes nothing, which is how to show what an upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the stored agent as files. + * + * Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + */ + readonly post: operations["syncAgentFiles"]; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/v1/agents/users/{user_id}": { readonly parameters: { readonly query?: never; @@ -5138,6 +5188,15 @@ export type components = { * @enum {string} */ readonly AgentConnectorSelectionType: "fixed" | "session"; + /** @description An agent config as the directory it is synced from: agent.yaml, instructions.md, guardrail.md, its skills, its knowledge, its simulations and its UI files. */ + readonly AgentDirectory: { + /** @description The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they store the agent as it is. */ + readonly files: readonly components["schemas"]["DirectoryFile"][]; + /** @description What the agent is called, as agent.yaml names it. */ + readonly name: string; + /** @description What this agent holds that its directory cannot say and a sync of these files would change, each in a sentence: a connector binding's events, policy or timeout, a connector that grants no tools, a knowledge document that is not a text file, UI instructions no directory's files were compiled into. Empty when a sync of these files leaves the agent as it is. */ + readonly not_exported: readonly string[]; + }; /** @description What the agent leaves to the customer's own server, which waits on /v1/dispatch. Omitted settings are disabled. */ readonly AgentDispatch: { /** @description A call to one of the customer's numbers is handed to a dispatch worker. Every inbound call already is, since a number is not tied to an agent config. */ @@ -7369,6 +7428,37 @@ export type components = { * @enum {string} */ readonly DetectionStatus: "completed" | "failed"; + /** @description One file of an agent directory, as a sync takes it and an export writes it. */ + readonly DirectoryFile: { + /** @description The file, whole, as text. */ + readonly content: string; + /** + * @description Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, skills/.md or skills//SKILL.md with the files beside it, knowledge/, knowledge/urls.yaml, simulations/.yaml, ui/components.json, ui/blueprints.yaml. + * @example skills/refunds/SKILL.md + */ + readonly path: string; + }; + /** @description One thing wrong with an agent directory, at its place in a file, so an editor can point at it. */ + readonly DirectoryProblem: { + /** + * Format: int64 + * @description The column, counted from 1. Left out with line. + * @example 3 + */ + readonly column?: number; + /** + * @description The file's path in the directory. + * @example agent.yaml + */ + readonly file: string; + /** + * Format: int64 + * @description The line, counted from 1. Left out when the problem is the file as a whole. + * @example 12 + */ + readonly line?: number; + readonly message: string; + }; /** * @description Whether this kind of work is left to the customer's own dispatch worker. * @enum {string} @@ -7422,17 +7512,28 @@ export type components = { readonly $in?: readonly string[]; }; readonly ErrorDetail: { - /** @description What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. */ + /** @description What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. */ readonly code: string; + /** @description What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. */ + readonly conflicts?: readonly components["schemas"]["SyncConflict"][]; /** * Format: uri * @description Where the code is explained. */ readonly doc_url: string; + /** @description The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen. */ + readonly last_change?: string; /** @description Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. */ readonly limit?: string; /** @description What went wrong, for a person to read. Its wording may change; branch on code. */ readonly message: string; + /** @description What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. */ + readonly problems?: readonly components["schemas"]["DirectoryProblem"][]; + /** + * Format: int64 + * @description How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed. + */ + readonly problems_omitted?: number; readonly type: components["schemas"]["ErrorType"]; }; /** @description The body of every failure. A failure that is not the caller's own is a 500 of type internal saying only "something went wrong": quote the response's X-Request-Id to find out more. */ @@ -10650,6 +10751,57 @@ export type components = { /** @description Who is suspending it. */ readonly suspended_by: string; }; + /** + * @description An agent directory as its files, which the router reads, so every client's directory means the same thing. The fields from instructions down are what a program sets in code beside the directory: each wins over what the files say, and is part of the hash. + * + * A request sends at most 1024 files, and the directory among them holds at most 1048576 bytes a file and 8388608 bytes in all. + * + * The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the part. The parts are, for every file of the directory in path order by byte, its path and its content; then, for each field from instructions down that is sent, its name and its value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags. for each tag in key order; skills with the number of skills in decimal, then for each skill in name order skills..description, .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files. for each file in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of the router's UI compiler, so a router that compiles ui differently syncs the directory again. A file sent that is no part of the directory is no part of the hash, so every client's sync of one folder has one hash. While a connector is left out sync_hash is another hash, so the sync that finds its connection is not taken for the one that left it out. + * + * What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. calls is always written whole: a call tool the file does not name goes back to its default. keyterms and tags are left as stored when the file has none, an empty list or mapping included, so a file cannot clear them. instructions, guardrail, the skills the config names, its UI instructions and its knowledge base are the directory's: a file taken out is taken out of the agent. simulations are left alone without a simulations file, and are exactly what the files declare with one. + */ + readonly SyncAgentFilesRequest: { + /** @description As base_change of POST /v1/agents/sync: the newest change the caller has already seen. */ + readonly base_change?: string; + /** @description As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over a setting somebody changed since the last one. */ + readonly check_changes?: boolean; + /** @description Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes for what it would write over, the money for writing its knowledge included. What only the writes can tell is not told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. unchanged is true when the hash matches and a sync would do nothing. */ + readonly dry_run?: boolean; + /** @description The files of the agent's folder, as they are on disk. A client sends what it finds and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no part of the limits or the hash. */ + readonly files: readonly components["schemas"]["DirectoryFile"][]; + /** @description In place of agent.yaml's greeting. */ + readonly greeting?: components["schemas"]["Greeting"]; + /** @description The guardrail a program gives in code, in place of guardrail.md. */ + readonly guardrail?: string; + /** @description In place of agent.yaml's harness. */ + readonly harness?: components["schemas"]["Harness"]; + /** @description The system prompt a program gives in code, in place of instructions.md. */ + readonly instructions?: string; + /** @description In place of agent.yaml's llm. */ + readonly llm?: string; + /** @description What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the agent. */ + readonly name?: string; + /** @description In place of agent.yaml's sandbox. */ + readonly sandbox?: components["schemas"]["Sandbox"]; + /** @description The skills a program writes in code, in place of every skill under skills/. An empty list names none. */ + readonly skills?: readonly components["schemas"]["SkillRequest"][]; + /** @description In place of agent.yaml's sts. */ + readonly sts?: string; + /** @description In place of agent.yaml's stt. */ + readonly stt?: string; + /** @description In place of agent.yaml's subagent. */ + readonly subagent?: string; + /** @description Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes. */ + readonly tags?: { + readonly [key: string]: string; + }; + /** @description In place of agent.yaml's tts. */ + readonly tts?: string; + /** @description In place of agent.yaml's video. */ + readonly video?: components["schemas"]["SessionVideo"]; + /** @description In place of agent.yaml's voice. */ + readonly voice?: string; + }; /** @description An agent directory as it is on disk. Everything after the simulations is what the directory's declaration decides rather than what it holds, and a setting left out leaves whatever is stored, so a model chosen in the dashboard survives a sync that says nothing about it. */ readonly SyncAgentRequest: { /** @description agent.yaml's agents: the app's other text agents this one may hand work to, each as a tool, by name. Sent, they replace the stored list whole, an empty list removing it; left out, the stored list stays. An agent named must already exist, so a directory is synced after the agents it names. */ @@ -10741,12 +10893,35 @@ export type components = { readonly voice?: string; }; readonly SyncAgentResult: { + /** @description What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it leaves as it is is not listed, and nothing is for a sync that found the hash unchanged. */ + readonly changes?: readonly components["schemas"]["SyncChange"][]; readonly config: components["schemas"]["AgentConfig"]; /** @description True when the hash matched and nothing was written. */ readonly unchanged: boolean; /** @description What was stored but will not work yet, such as a channel line the app has not connected. */ readonly warnings?: readonly string[] | null; }; + /** @description One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes. */ + readonly SyncChange: { + /** @enum {string} */ + readonly action: "created" | "updated" | "deleted"; + /** @description Which one: a skill's name, a knowledge document's source, a knowledge url's url, a simulation's name. */ + readonly name: string; + /** + * @description What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. + * @enum {string} + */ + readonly resource_type: "skill" | "knowledge" | "knowledge_url" | "simulation"; + }; + /** @description One thing a sync would write over that somebody changed since the last sync. */ + readonly SyncConflict: { + /** @description Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url. */ + readonly name: string; + /** @description True for a knowledge document the directory no longer has, which the sync would delete. */ + readonly removed?: boolean; + /** @description What was changed, as GET /v1/agents/configs/{id}/changes names it: agent_config, skill, knowledge or knowledge_url. */ + readonly resource_type: components["schemas"]["AuditResourceType"]; + }; readonly TagKeySummary: { /** Format: int64 */ readonly cost_micros_total: number; @@ -13717,6 +13892,39 @@ export interface operations { readonly 503: components["responses"]["Unavailable"]; }; }; + readonly getAgentDirectory: { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path: { + readonly id: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description The agent's directory */ + readonly 200: { + headers: { + readonly "X-Stream-Balance-Micros": components["headers"]["X-Stream-Balance-Micros"]; + readonly "X-Stream-Balance-Warning": components["headers"]["X-Stream-Balance-Warning"]; + readonly "X-Stream-Cost-Estimated": components["headers"]["X-Stream-Cost-Estimated"]; + readonly "X-Stream-Cost-Micros": components["headers"]["X-Stream-Cost-Micros"]; + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["AgentDirectory"]; + }; + }; + readonly 400: components["responses"]["BadRequest"]; + readonly 401: components["responses"]["Unauthorized"]; + readonly 402: components["responses"]["PaymentRequired"]; + readonly 403: components["responses"]["Forbidden"]; + readonly 404: components["responses"]["NotFound"]; + readonly 500: components["responses"]["InternalError"]; + readonly 503: components["responses"]["Unavailable"]; + }; + }; readonly listConnections: { readonly parameters: { readonly query?: { @@ -18521,6 +18729,58 @@ export interface operations { readonly 503: components["responses"]["Unavailable"]; }; }; + readonly syncAgentFiles: { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody: { + readonly content: { + readonly "application/json": components["schemas"]["SyncAgentFilesRequest"]; + }; + }; + readonly responses: { + /** @description The config as stored, as it already was, or with dry_run as it would be stored */ + readonly 200: { + headers: { + readonly "X-Stream-Balance-Micros": components["headers"]["X-Stream-Balance-Micros"]; + readonly "X-Stream-Balance-Warning": components["headers"]["X-Stream-Balance-Warning"]; + readonly "X-Stream-Cost-Estimated": components["headers"]["X-Stream-Cost-Estimated"]; + readonly "X-Stream-Cost-Micros": components["headers"]["X-Stream-Cost-Micros"]; + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["SyncAgentResult"]; + }; + }; + readonly 400: components["responses"]["BadRequest"]; + readonly 401: components["responses"]["Unauthorized"]; + readonly 402: components["responses"]["PaymentRequired"]; + readonly 403: components["responses"]["Forbidden"]; + /** @description Conflict */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Request Entity Too Large */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + readonly 500: components["responses"]["InternalError"]; + readonly 503: components["responses"]["Unavailable"]; + }; + }; readonly getUser: { readonly parameters: { readonly query?: never; diff --git a/sdks/js/tests/agent.test.ts b/sdks/js/tests/agent.test.ts index a0ce3080f7..931086a800 100644 --- a/sdks/js/tests/agent.test.ts +++ b/sdks/js/tests/agent.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -22,11 +23,6 @@ import { loadFolder } from "../src/node.js"; import { inPage } from "./device.js"; import { TestRouter } from "./router.js"; -// The sync body of a connector entry with neither sandbox nor require_approval, probed on -// 8e132bd37, before agent.yaml read either. -const PROBED_CONNECTOR_BODY = - '{"name":"jean","instructions":"Be brief.","connectors":[{"name":"github","connector_id":"github","tools":[],"tool_patterns":["*"],"required":true,"connection":{"type":"session"}}],"hash":"38df39c4d53c61a144cbb643b522795d61737c5239450b70fd44955053aedf10"}'; - const session = { id: "sess_1", call_id: "demo", @@ -570,39 +566,6 @@ describe("Agent", () => { assert.notEqual(hashes[1], hashes[2]); }); - it("sends a skill folder's files, and fingerprints a skill moved into a folder the same until it brings one", async () => { - router.serve("POST", "/v1/agents/sync", { - body: { - unchanged: false, - config: { id: "cfg_1", name: "jean", created_at: "2026-01-01T00:00:00Z" }, - }, - }); - // Nothing stored, so a stamp that still matches syncs again and the request is seen. - router.serve("GET", "/v1/agents/configs", { body: [] }); - const root = join(await mkdtemp(join(tmpdir(), "vision-agents-")), "jean"); - const skill = "---\ndescription: Fill PDF forms\ndeadline: 2m\n---\nFill the form.\n"; - await mkdir(join(root, "skills"), { recursive: true }); - await writeFile(join(root, "agent.yaml"), "name: jean\n"); - await writeFile(join(root, "skills", "pdf.md"), skill); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - - await rm(join(root, "skills", "pdf.md")); - await mkdir(join(root, "skills", "pdf", "scripts"), { recursive: true }); - await writeFile(join(root, "skills", "pdf", "SKILL.md"), skill); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - - await writeFile(join(root, "skills", "pdf", "scripts", "fill.py"), "print('filled')\n"); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - - const [asFile, asFolder, withFile] = router - .requestsTo("POST", "/v1/agents/sync") - .map((one) => one.body as Schemas["SyncAgentRequest"]); - assert.equal(asFolder?.skills?.[0] && "files" in asFolder.skills[0], false); - assert.deepEqual(withFile?.skills?.[0]?.files, { "scripts/fill.py": "print('filled')\n" }); - assert.equal(asFile?.hash, asFolder?.hash, "moving a skill into a folder would sync it again"); - assert.notEqual(asFolder?.hash, withFile?.hash, "a file added to a skill would not sync"); - }); - describe("connectors", () => { const stored = { id: "cfg_1", name: "jean", created_at: "2026-01-01T00:00:00Z" }; const folder = (connectors: ConnectorDeclaration[] | undefined): Folder => ({ @@ -653,72 +616,6 @@ describe("Agent", () => { return router.requestsTo("POST", "/v1/agents/sync").at(-1)?.body as Record; } - it("sends agent.yaml's image as written, an empty one that turns drawing off included", async () => { - const drawing = await syncedFrom("name: jean\nmode: text\nimage: image-fast\n"); - const off = await syncedFrom('name: jean\nmode: text\nimage: ""\n'); - const unsaid = await syncedFrom("name: jean\nmode: text\n"); - const bare = await syncedFrom("name: jean\nmode: text\nimage:\n"); - - assert.equal(drawing["image"], "image-fast"); - assert.equal(off["image"], "", "an empty image is how a file turns drawing off"); - assert.equal("image" in unsaid, false, "a file that names none leaves the stored one"); - assert.equal("image" in bare, false, "a bare image: says nothing, as in Go and Python"); - }); - - it("sends sandbox and require_approval from agent.yaml on each binding that sets them", async () => { - router.serve("GET", "/v1/agents/connections", { body: { items: [connection("conn-1", "company")], has_more: false } }); - - const body = await syncedFrom( - [ - "name: jean", - "connectors:", - " - name: github", - " sandbox: true", - " - name: code", - " connector: github", - " connection: company", - " sandbox: true", - " - name: issues", - " connector: linear", - " require_approval: [create_*, update_issue]", - " - name: mail", - " sandbox: false", - " require_approval: []", - " - linear", - "", - ].join("\n"), - ); - - const session = { type: "session" }; - assert.deepEqual(body["connectors"], [ - { name: "github", connector_id: "github", tools: [], tool_patterns: ["*"], sandbox: true, connection: session }, - { - name: "code", - connector_id: "github", - tools: [], - tool_patterns: ["*"], - sandbox: true, - connection: { type: "fixed", connection_id: "conn-1" }, - }, - { - name: "issues", - connector_id: "linear", - tools: [], - tool_patterns: ["*"], - require_approval: ["create_*", "update_issue"], - connection: session, - }, - { name: "mail", connector_id: "mail", tools: [], tool_patterns: ["*"], require_approval: [], connection: session }, - { name: "linear", connector_id: "linear", tools: [], tool_patterns: ["*"], connection: session }, - ]); - }); - - it("sends the body it sent before for a connector that sets neither", async () => { - const body = await syncedFrom("name: jean\nconnectors:\n - name: github\n required: true\n"); - - assert.equal(JSON.stringify(body), PROBED_CONNECTOR_BODY); - }); - it("sends no connectors when agent.yaml has none, and an empty list when it lists none", async () => { const without = await synced(undefined); const emptied = await synced([]); @@ -796,250 +693,266 @@ describe("Agent", () => { return router.requestsTo("POST", "/v1/agents/sync").at(-1)?.body as Record; } - it("sends them the way the Go SDK does", async () => { - const body = await synced( - [ - "name: jean", - "channels:", - " whatsapp:", - ' number: "+15551234567" # the main line', - " sms:", - " number: +15557654321", - " imessage:", - " identity: link # by link", - "", - ].join("\n"), + it("refuses plugins and mcp_servers that name something, and sends nothing", async () => { + await assert.rejects(() => synced("name: jean\nplugins:\n - weather\n"), /plugins is no longer read/); + await assert.rejects( + () => synced("name: jean\nmcp_servers:\n - name: a\n url: https://a.example.com\n"), + /mcp_servers is no longer read/, ); - - assert.deepEqual(body["channels"], { - whatsapp: { number: "+15551234567" }, - sms: { number: "+15557654321" }, - identity: "link", - }); + assert.equal(router.requestsTo("POST", "/v1/agents/sync").length, 0); }); + }); - it("sends empty channels for an empty mapping", async () => { - const body = await synced("name: jean\nchannels: {}\n"); + describe("of a directory's files", () => { + /** Writes an agent directory under a temporary one, and hands back its path. */ + async function agentDir(files: Record): Promise { + const root = join(await mkdtemp(join(tmpdir(), "vision-agents-")), "jean"); + for (const [name, content] of Object.entries(files)) { + await mkdir(join(root, name, ".."), { recursive: true }); + await writeFile(join(root, name), content); + } + return root; + } - assert.deepEqual(body["channels"], {}); - }); + /** Answers a sync as the router does: the config, under a hash of what was sent. */ + function serveSync(leftOut: Schemas["LeftOutConnector"][] = []): { sync_hash: string } { + const stored = { + id: "cfg_1", name: "jean", created_at: "2026-01-01T00:00:00Z", sync_hash: "", + ...(leftOut.length > 0 ? { left_out_connectors: leftOut } : {}), + }; + router.serve("POST", "/v1/agents/sync/files", (request) => { + stored.sync_hash = createHash("sha256").update(JSON.stringify(request.body)).digest("hex"); + return { body: { unchanged: false, config: stored } }; + }); + router.serve("GET", "/v1/agents/configs", { body: [stored] }); + return stored; + } - it("fingerprints a change to channels", async () => { - const one = await synced("name: jean\nchannels:\n sms:\n number: +15550000001\n"); - const other = await synced("name: jean\nchannels:\n sms:\n number: +15550000002\n"); + function synced(): Schemas["SyncAgentFilesRequest"][] { + return router + .requestsTo("POST", "/v1/agents/sync/files") + .map((one) => one.body as Schemas["SyncAgentFilesRequest"]); + } - assert.notEqual(one["hash"], other["hash"]); + it("sends a loaded directory's files as they are, and leaves reading them to the router", async () => { + const held = { + "agent.yaml": "llm: llm-smart\ntags:\n team: support\nconnectors:\n - {name: linear, connection: company}\nui: {}\n", + "instructions.md": "Be brief.\n", + "guardrail.md": "Refuse medical advice.\n", + "skills/think.md": "---\ndescription: Think\n---\nWork it out.\n", + "skills/pdf/SKILL.md": "---\ndescription: Fill a form\n---\nRun the script.\n", + "skills/pdf/scripts/fill.py": "print('filled')\n", + "knowledge/pricing.md": "The plans cost money.\n", + "knowledge/urls.yaml": "- https://example.com\n", + "simulations/order.yaml": "- name: order\n scenario: Order a wrap.\n assertion: One wrap.\n", + "ui/blueprints.yaml": "- name: booking\n when: booking a table\n order: [CardHeader]\n", + }; + const root = await agentDir(held); + serveSync(); + + const result = await new Agent({ folder: await loadFolder(root), client: api }).sync(); + + assert.equal(result.config.id, "cfg_1"); + assert.equal(router.received.length, 1, "the whole directory goes in one request, and no connection is looked up here"); + const [body] = synced(); + assert.deepEqual(Object.keys(body ?? {}).sort(), ["files", "name"], "what the files say is the router's to read"); + assert.equal(body?.name, "jean"); + assert.deepEqual(Object.fromEntries((body?.files ?? []).map((file) => [file.path, file.content])), held); + assert.deepEqual((body?.files ?? []).map((file) => file.path), Object.keys(held).sort(), "in path order"); }); - it("sends floor_control as written, and none when agent.yaml names none, so the stored choice stays", async () => { - for (const [declared, chosen] of [ - [ - "floor_control:\n model: stream/chorus-asr\n max_wait_ms: 800\n", - { model: "stream/chorus-asr", max_wait_ms: 800 }, - ], - ["floor_control: {model: stream/chorus-asr}\n", { model: "stream/chorus-asr" }], - // Sent rather than dropped: the router refuses what it does not know, naming why. - ["floor_control: {model: other, max_wait_ms: 0}\n", { model: "other", max_wait_ms: 0 }], - // An empty one is no choice again, which the router's default rules. - ["floor_control: {}\n", {}], - ["llm: llm-fast\n", undefined], - ["floor_control:\n", undefined], - ["floor_control: null\n", undefined], - ] as const) { - const body = await synced(`name: jean\n${declared}`); - - assert.deepEqual(body["floor_control"], chosen, declared); - assert.equal("floor_control" in body, chosen !== undefined, declared); - } + it("only reads back a directory nothing has touched since .agent_sync was written", async () => { + serveSync(); + const root = await agentDir({ "agent.yaml": "name: jean\n", "instructions.md": "Be brief.\n" }); - const one = await synced("name: jean\nfloor_control:\n model: stream/chorus-asr\n max_wait_ms: 900\n"); - const other = await synced("name: jean\nfloor_control:\n model: stream/chorus-asr\n max_wait_ms: 1200\n"); - assert.notEqual(one["hash"], other["hash"], "a changed max_wait_ms would not sync"); + await new Agent({ folder: await loadFolder(root), client: api }).sync(); + const again = await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await writeFile(join(root, "instructions.md"), "Be warm.\n"); + const edited = await new Agent({ folder: await loadFolder(root), client: api }).sync(); + + assert.equal(again.unchanged, true); + assert.equal(again.config.id, "cfg_1"); + assert.equal(synced().length, 2); + assert.equal(router.requestsTo("GET", "/v1/agents/configs")[0]?.query.get("name"), "jean"); + const recorded = JSON.parse(await readFile(join(root, ".agent_sync"), "utf8")) as { + hash: string; + synced_at: string; + }; + assert.match(recorded.hash, /^[0-9a-f]{64}$/); + assert.equal( + (recorded as { sync_hash?: string }).sync_hash, + edited.config.sync_hash, + "the stamp keeps the hash the router stored it under, as the Go SDK writes it", + ); + assert.match(recorded.synced_at, /^\d{4}-\d\d-\d\dT/); }); - it("sends how the sandbox is built and what it may reach", async () => { - const body = await synced( - [ - "name: jean", - "sandbox: daytona", - "sandbox_options:", - " setup:", - " - pip install bpy==5.2.2", - " timeout: 5m", - " memory_gb: 4", - " network: true", - " allowed_domains: [api.example.com]", - " network_allow_list: [10.0.0.0/8]", - "", - ].join("\n"), - ); + it("sends a directory again while a connector of it is left out, so the sync that finds its connection is made", async () => { + serveSync([{ name: "linear", connector_id: "linear", connection: "company" }]); + const root = await agentDir({ "agent.yaml": "name: jean\nconnectors:\n - {name: linear, connection: company}\n" }); - assert.deepEqual(body["sandbox_options"], { - setup: ["pip install bpy==5.2.2"], - timeout_ms: 300_000, - memory_gb: 4, - network: true, - allowed_domains: ["api.example.com"], - network_allow_list: ["10.0.0.0/8"], - }); - }); + await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder: await loadFolder(root), client: api }).sync(); - it("sends the same body as before for an agent.yaml with no plugins or mcp_servers, or empty ones", async () => { - for (const extra of ["", "plugins: []\n", "plugins:\n", "mcp_servers: []\n", "mcp_servers:\n", "plugins: []\nmcp_servers: ~\n"]) { - const body = await synced(`name: jean\nllm: llm-fast\n${extra}`); - - assert.deepEqual(body, { - name: "jean", - instructions: "Be brief.", - llm: "llm-fast", - // Probed on the base, 39edf6a16, for each of these files. - hash: "bee9653c8f8302df07255b6d11a843a43b12ef5fee7e9be5b6201c4a3d92ba98", - }); - } + assert.equal(synced().length, 2); }); - it("refuses plugins and mcp_servers that name something, and sends nothing", async () => { - await assert.rejects(() => synced("name: jean\nplugins:\n - weather\n"), /plugins is no longer read/); - await assert.rejects( - () => synced("name: jean\nmcp_servers:\n - name: a\n url: https://a.example.com\n"), - /mcp_servers is no longer read/, - ); - assert.equal(router.requestsTo("POST", "/v1/agents/sync").length, 0); - }); - }); + it("sends a stamped directory again once the stored config is no longer what was synced", async () => { + const stored = serveSync(); + const root = await agentDir({ "agent.yaml": "name: jean\n" }); - it("only reads back a directory nothing has touched since .agent_sync was written", async () => { - const stored = { id: "cfg_1", name: "jean", created_at: "2026-01-01T00:00:00Z", sync_hash: "" }; - router.serve("POST", "/v1/agents/sync", (request) => { - stored.sync_hash = (request.body as Schemas["SyncAgentRequest"]).hash; - return { body: { unchanged: false, config: stored } }; - }); - router.serve("GET", "/v1/agents/configs", { body: [stored] }); - const root = join(await mkdtemp(join(tmpdir(), "vision-agents-")), "jean"); - await mkdir(root); - await writeFile(join(root, "agent.yaml"), "name: jean\n"); - await writeFile(join(root, "instructions.md"), "Be brief.\n"); - - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - const again = await new Agent({ folder: await loadFolder(root), client: api }).sync(); - await writeFile(join(root, "instructions.md"), "Be warm.\n"); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - - assert.equal(again.unchanged, true); - assert.equal(again.config.id, "cfg_1"); - assert.equal(router.requestsTo("POST", "/v1/agents/sync").length, 2); - assert.equal(router.requestsTo("GET", "/v1/agents/configs")[0]?.query.get("name"), "jean"); - const recorded = JSON.parse(await readFile(join(root, ".agent_sync"), "utf8")) as { - hash: string; - synced_at: string; - }; - const last = router.requestsTo("POST", "/v1/agents/sync").at(-1); - assert.equal(recorded.hash, (last?.body as Schemas["SyncAgentRequest"]).hash); - assert.match(recorded.synced_at, /^\d{4}-\d\d-\d\dT/); - }); + await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder: await loadFolder(root), client: api }).sync(); + // Somebody imports another directory in the dashboard, or edits the config, which clears it. + stored.sync_hash = "imported"; + await new Agent({ folder: await loadFolder(root), client: api }).sync(); - describe("ui_instructions", () => { - let stored: Record; - /** Off, the fake is a router older than ui_instructions: it takes a sync and drops them. */ - let knowsUI: boolean; + assert.equal(synced().length, 2, "once, not again while the config was as synced, and again once it was not"); + }); - beforeEach(() => { - knowsUI = true; - stored = { id: "cfg_1", name: "jean", created_at: "2026-01-01T00:00:00Z", sync_hash: "" }; - router.serve("POST", "/v1/agents/sync", (request) => { - const { ui_instructions: ui, hash, instructions } = request.body as Schemas["SyncAgentRequest"]; - const { ui_instructions: _before, ...kept } = stored; - stored = { ...kept, sync_hash: hash, instructions, ...(knowsUI && ui ? { ui_instructions: ui } : {}) }; - return { body: { unchanged: false, config: stored } }; + it("sends the files the format names and nothing else of the folder", async () => { + serveSync(); + const root = await agentDir({ + "agent.yaml": "name: jean\nui:\n blueprints: design/recipes.yaml\n", + "design/recipes.yaml": "- name: booking\n when: booking\n order: [CardHeader]\n", + "design/other.yaml": "not named by agent.yaml\n", + "ui/components.json": "[]\n", + "knowledge/pricing.md": "Pro.\n", + "knowledge/data.csv": "a,b\n", + "simulations/lunch.yaml": "- name: lunch\n scenario: Ask.\n assertion: Answered.\n", + "simulations/notes.md": "not a simulations file\n", + // What a project keeps beside its agent, none of which is the agent. + "index.ts": "export {};\n", + "package-lock.json": "{}\n", + ".env": "SECRET=1\n", + "keys/prod.pem": "-----BEGIN PRIVATE KEY-----\n", + "knowledge/node_modules/left-pad/index.js": "module.exports = 1;\n", }); - router.serve("GET", "/v1/agents/configs", () => ({ body: [stored] })); - }); + await writeFile(join(root, "knowledge", "logo.png"), new Uint8Array([0x89, 0x50, 0xff, 0xfe])); - async function folder(yaml: string): Promise { - const root = join(await mkdtemp(join(tmpdir(), "vision-agents-")), "jean"); - await mkdir(root); - await writeFile(join(root, "agent.yaml"), yaml); - await writeFile(join(root, "instructions.md"), "Be brief.\n"); - return root; - } + await new Agent({ folder: await loadFolder(root), client: api }).sync(); - function syncs(): Schemas["SyncAgentRequest"][] { - return router.requestsTo("POST", "/v1/agents/sync").map((one) => one.body as Schemas["SyncAgentRequest"]); - } + assert.deepEqual(synced()[0]?.files.map((file) => file.path), [ + "agent.yaml", + "design/recipes.yaml", + "knowledge/data.csv", + "knowledge/pricing.md", + "simulations/lunch.yaml", + "ui/components.json", + ]); + }); - it("sends agent.yaml's ui apart from the instructions, so a session opened with ui false is not told it", async () => { - const root = await folder("name: jean\nui: {}\n"); + it("reads the files when it syncs, so an edit after the folder was loaded is what is sent", async () => { + serveSync(); + const root = await agentDir({ "agent.yaml": "name: jean\n", "instructions.md": "Be brief.\n" }); + const folder = await loadFolder(root); + await writeFile(join(root, "knowledge.md"), "beside the directory\n"); + await mkdir(join(root, "knowledge")); + await writeFile(join(root, "knowledge", "pricing.md"), "Pro.\n"); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder, client: api }).sync(); - const [body] = syncs(); - assert.equal(body?.instructions, "Be brief."); - assert.match(body?.ui_instructions ?? "", /^## Interactive UI Generation\n/); + assert.deepEqual(synced()[0]?.files.map((file) => file.path), ["agent.yaml", "instructions.md", "knowledge/pricing.md"]); }); - it("sends the folder's ui beside instructions the code gives in place of instructions.md", async () => { - const root = await folder("name: jean\nui: {}\n"); - - await new Agent({ folder: await loadFolder(root), instructions: "Be warm.", client: api }).sync(); + it("refuses a directory over what a sync sends, by name, before it sends anything", async () => { + serveSync(); + const files: Record = { "agent.yaml": "name: jean\n" }; + for (let index = 0; index < 9; index++) { + files[`knowledge/${index}.md`] = "a".repeat(1 << 20); + } + const folder = await loadFolder(await agentDir(files)); - const [body] = syncs(); - assert.equal(body?.instructions, "Be warm."); - assert.match(body?.ui_instructions ?? "", /^## Interactive UI Generation\n/); + await assert.rejects( + () => new Agent({ folder, client: api }).sync(), + (cause: unknown) => cause instanceof ConfigurationError && /holds more than the 8388608 bytes a sync sends/.test(cause.message), + ); + assert.equal(synced().length, 0); }); - it("sends none without a ui:, so such a directory keeps the fingerprint it was stamped with", async () => { - const root = await folder("name: jean\n"); + it("stamps a request with the fingerprint the Go SDK takes of it", async () => { + serveSync(); + let stamp = ""; + const folder: Folder = { + path: "/agents/jean", name: "jean", instructions: "", guardrail: "", skills: [], knowledge: [], knowledgeURLs: [], + files: async () => [{ path: "agent.yaml", content: "name: jean\n" }], + stamp: { read: async () => stamp, write: async (value) => { stamp = value; } }, + }; - await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder, client: api, costTracking: { b: "<2>", a: "1" } }).sync(); - const [body] = syncs(); - assert.equal(body && "ui_instructions" in body, false); - // What the SDK sent for this directory before the UI was synced apart from the - // instructions, so a .agent_sync written then still matches. - assert.equal(body?.hash, "b25c07032945a5bbcb9ae171a85d69d9fc4350ea0e24cbc9422df8d16ec5b5d7"); + // sha256 of {"files":[{"content":"name: jean\n","path":"agent.yaml"}],"name":"jean","tags":{"a":"1","b":"<2>"}}, + // which sdks/go/agents/folder_test.go holds the Go SDK to as well. + assert.equal(stamp.split(":")[0], "8e57238c214f215939fb6a466b9791aae8abbfd7df14e752f9d0d767aaed3ad9"); }); - it("keeps the ui in the instructions on a router older than ui_instructions, and asks again next time", async () => { - knowsUI = false; - const root = await folder("name: jean\nui: {}\n"); + it("sends what the code set beside the directory, which wins over its files", async () => { + const root = await agentDir({ "agent.yaml": "name: jean\nllm: llm-smart\n", "instructions.md": "Be brief.\n" }); + const written = { + instructions: "Be warm.", + guardrail: "Refuse medical advice.", + pipeline: { llm: "llm-fast", tts: "sonic_36", greeting: "Hello", greetingMode: "variation" as const, video: { max_frames: 4 } }, + costTracking: { team: "support", customer: "123" }, + harness: { + name: "default" as const, + subagents: { default: "llm-slow" }, + vm: daytona(), + skills: [ + { name: "think", description: "Think", instructions: "Work it out.", deadlineMs: 30_000 }, + { name: "fill", description: "Fill a form", instructions: "Run it.", files: { "fill.py": "print()\n" } }, + ], + }, + }; + serveSync(); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder: await loadFolder(root), client: api, ...written }).sync(); + const again = await new Agent({ folder: await loadFolder(root), client: api, ...written }).sync(); - const [first, fallback] = syncs(); - assert.match(String(stored["instructions"]), /^Be brief\.\n\n## Interactive UI Generation\n/); - assert.equal(fallback && "ui_instructions" in fallback, false); - assert.notEqual(fallback?.hash, first?.hash); - // Never stamped while the router drops the UI, so every sync asks it again. - assert.equal(syncs().length, 4); - await assert.rejects(() => readFile(join(root, ".agent_sync"), "utf8")); + assert.equal(again.unchanged, true); + assert.equal(synced().length, 1); + const [body] = synced(); + assert.equal(body?.instructions, "Be warm."); + assert.equal(body?.guardrail, "Refuse medical advice."); + assert.equal(body?.llm, "llm-fast", "what the code set wins over agent.yaml"); + assert.equal(body?.tts, "sonic_36"); + assert.deepEqual(body?.greeting, { text: "Hello", mode: "variation" }); + assert.deepEqual(body?.video, { max_frames: 4 }); + assert.deepEqual(body?.tags, { team: "support", customer: "123" }); + assert.equal(body?.harness, "default"); + assert.equal(body?.subagent, "llm-slow"); + assert.equal(body?.sandbox, "daytona"); + assert.deepEqual(body?.skills?.map((skill) => skill.name), ["think", "fill"]); + assert.deepEqual( + body?.files.map((file) => file.content), + ["name: jean\nllm: llm-smart\n", "Be brief.\n"], + "the files go as they are", + ); }); - it("moves the ui apart once the router knows ui_instructions", async () => { - knowsUI = false; - const root = await folder("name: jean\nui: {}\n"); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - knowsUI = true; + it("sends an explicitly empty skill list, so the directory's skills are not the agent's", async () => { + serveSync(); + const root = await agentDir({ "agent.yaml": "name: jean\n", "skills/think.md": "---\ndescription: Think\n---\nWork it out.\n" }); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - const settled = await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder: await loadFolder(root), client: api, harness: { skills: [] } }).sync(); - assert.equal(stored["instructions"], "Be brief."); - assert.match(String(stored["ui_instructions"]), /^## Interactive UI Generation\n/); - assert.equal(settled.unchanged, true); - assert.equal(syncs().length, 3); + assert.deepEqual(synced()[0]?.skills, []); }); - it("syncs again a stamped config that lost its ui", async () => { - const root = await folder("name: jean\nui: {}\n"); - await new Agent({ folder: await loadFolder(root), client: api }).sync(); - const { ui_instructions: _lost, ...withoutUI } = stored; - stored = withoutUI; + it("syncs a folder built by hand, with no files, as the fields it holds", async () => { + router.serve("POST", "/v1/agents/sync", { + body: { unchanged: false, config: { id: "cfg_1", name: "jean", created_at: "2026-01-01T00:00:00Z" } }, + }); + const folder: Folder = { + path: "/agents/jean", name: "jean", instructions: "Be brief.", guardrail: "", + settings: { llm: "llm-smart" }, skills: [], knowledge: [], knowledgeURLs: [], + }; - const again = await new Agent({ folder: await loadFolder(root), client: api }).sync(); + await new Agent({ folder, client: api }).sync(); - assert.equal(again.unchanged, false); - assert.match(String(stored["ui_instructions"]), /^## Interactive UI Generation\n/); + const body = router.requestsTo("POST", "/v1/agents/sync")[0]?.body as Schemas["SyncAgentRequest"]; + assert.equal(body.llm, "llm-smart"); + assert.match(body.hash, /^[0-9a-f]{64}$/); + assert.equal(synced().length, 0); }); }); }); From 65556f6c11764783d5d4e74070b5027585cf9db5 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Fri, 20 Nov 2026 17:39:58 +0100 Subject: [PATCH 5/6] docs: the router reads the agent directory The sdk skill's note says what the other SDKs and the getstream CLI should do to send a directory's files; the generative-ui and connectors skills say where ui: is compiled and connections are found for a sync of files. Removing the SDKs' own parsers is AI-3441. --- .claude/skills/connectors/SKILL.md | 13 ++++++---- .claude/skills/generative-ui/SKILL.md | 37 ++++++++++++++++----------- .claude/skills/sdk/SKILL.md | 1 + CHANGELOG.md | 10 ++++++++ 4 files changed, 41 insertions(+), 20 deletions(-) diff --git a/.claude/skills/connectors/SKILL.md b/.claude/skills/connectors/SKILL.md index a62b54a9cc..304cf90e5f 100644 --- a/.claude/skills/connectors/SKILL.md +++ b/.claude/skills/connectors/SKILL.md @@ -195,11 +195,14 @@ For a session your backend creates, pass the end user's connection in `connector_bindings: [{"name": "linear", "connection_id": "…"}]`. Leave it out and the router uses the user's only connected connection to that connector, if there is exactly one. -`agent.yaml`: the sync API accepts `connectors`, and the Go SDK folder reader reads the block -(`sdks/go/agents/config.go`, `connectorBindings`). An entry whose `connection:` the app does not have -is left out with a warning, and the rest of the agent syncs; `required: true` makes it an error. `sandbox: true` lets code in the session's sandbox call the connector's API with the binding's connection. -The left-out entries go to the router as `left_out_connectors` and are served on the agent config. -Other SDKs: unverified, check `git grep connectors sdks/js/src plugins/stream` before relying on it. +`agent.yaml`: a sync that sends the directory's files (Go and JavaScript do) has its `connectors` +block read by the router (`acceleration/internal/api/directory.go`, `bindDirectoryConnectors`), +which finds a `connection:` among the app's own by id or by label. An entry whose connection the +app does not have is left out with a warning, stored as `left_out_connectors` and served on the +agent config, and the rest of the agent syncs; `required: true` makes it an error. `sandbox: true` +lets code in the session's sandbox call the connector's API with the binding's connection. +An SDK that still reads the folder itself sends `connectors` and `left_out_connectors` as fields: +check `git grep connectors plugins/stream` before relying on one. ### Sandbox access diff --git a/.claude/skills/generative-ui/SKILL.md b/.claude/skills/generative-ui/SKILL.md index f3c40d935f..5d423c38b4 100644 --- a/.claude/skills/generative-ui/SKILL.md +++ b/.claude/skills/generative-ui/SKILL.md @@ -24,9 +24,13 @@ model tokens ## The agent.yaml `ui:` key -`ui:` tells the model what it may draw. The SDK that loads the folder compiles it into a -`## Interactive UI Generation` section and syncs it as the config's `ui_instructions`, apart from -`instructions.md`, so the router sees only text. The output is deterministic, so the prompt +`ui:` tells the model what it may draw. It is compiled into a `## Interactive UI Generation` +section stored as the config's `ui_instructions`, apart from `instructions.md`. For a sync of the +directory's files (`POST /v1/agents/sync/files`, which Go and JavaScript send) the router compiles +it (`acceleration/internal/agentdir/ui.go`) and keeps the key and the two files beside it +(`agent_configs.ui_source`), which `GET /v1/agents/configs/{id}/directory` writes back until +somebody writes other `ui_instructions`. An SDK that still syncs the fields it read compiles it +and sends the text. The output is deterministic, so the prompt prefix stays cacheable across turns. The prompt is mixed mode: the model answers in prose and adds a card only when it helps. @@ -68,17 +72,19 @@ ui: Paths are relative to the agent directory and may not leave it (symlinks included); each file is capped at 512 KiB. -Loaded by: Go (`sdks/go/agents/ui.go`, from `Load`, into `Folder.UIInstructions`) and JavaScript (`sdks/js/src/ui-catalog.ts`, -from `loadFolder` in `folder.ts`). Python, .NET, Ruby, Rust and PHP don't read `ui:` yet (see the -note at the end of the `sdk` skill), and the `getstream` CLI refuses it as an unknown key -(`cli/internal/agentrc/agentrc.go`, `KnownFields`), so `getstream agents sync` fails on it. The two compilers must produce the same bytes for the same -folder: `sdks/testdata/ui/concierge/` is compiled by a Go test and a JavaScript test, both held to -`sdks/testdata/ui/concierge.instructions.txt`, which Go writes: what the model is told, the -instructions and the UI joined by a blank line, as the router joins them. An SDK that adds `ui:` checks itself -against the same pair. `a2ui` is compiled by Go (`sdks/go/agents/ui_a2ui.go`) and JavaScript -(`sdks/js/src/ui-a2ui.ts`), both held to `sdks/testdata/ui/concierge-a2ui/` and -`concierge-a2ui.instructions.txt`. JavaScript parses this YAML by hand; it still differs from yaml.v3 on -escapes inside quoted strings (`'it''s'`), empty list items, and `ui:` written as a flow mapping. +Compiled by: the router (`acceleration/internal/agentdir/ui.go` and `ui_a2ui.go`) for a sync of +files, which is what Go and JavaScript send. Both SDKs still compile it too, for the program +holding the folder (`Folder.UIInstructions` from `sdks/go/agents/ui.go`, `Folder.uiInstructions` +from `sdks/js/src/ui-catalog.ts`), until their parsers go (AI-3441). Python, .NET, Ruby, Rust and +PHP don't read `ui:` yet (see the note at the end of the `sdk` skill), and the `getstream` CLI +refuses it as an unknown key (`cli/internal/agentrc/agentrc.go`, `KnownFields`), so `getstream +agents sync` fails on it. Every compiler must produce the same bytes for the same folder: +`sdks/testdata/ui/concierge/` and `concierge-a2ui/` are compiled by the router's test, a Go SDK +test and a JavaScript test, all held to `concierge.instructions.txt` and +`concierge-a2ui.instructions.txt`: what the model is told, the instructions and the UI joined by +a blank line, as the router joins them. JavaScript parses this YAML by hand; it still differs from +yaml.v3 on escapes inside quoted strings (`'it''s'`), empty list items, and `ui:` written as a flow +mapping. ## How the model writes UI @@ -90,7 +96,8 @@ own components, then `updateComponents`, `root` first. The prompt is the one str renderer writes for itself (`A2UIInstructions`): its protocol and guidelines, then the catalog as JSON Schema, the basic catalog's components and functions that `keep` names beside the app's own, each app component as the renderer has it (`PortableComponent`: its parameters as properties, its -events joining its description). `sdks/go/agents/a2ui/` holds the basic catalog and the protocol as +events joining its description). `sdks/go/agents/a2ui/` and its copy `acceleration/internal/agentdir/a2ui/`, which a router test +holds to it, hold the basic catalog and the protocol as the renderer has them, which `a2ui/generate.sh` writes again from a stream-chat-swift checkout; a Go test holds the catalog to the one in `swift_assistant/a2ui/instructions.md`, which the renderer wrote, so regenerate both together. JavaScript carries the same three files as a module, diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 3ac4a7df6b..359d6fc239 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -943,3 +943,4 @@ Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Con Ruby connections and the user parameter (AI-3380, AI-3387): `Client#connections` has `create(connector, label:, user_id:)`, `authorize(id, return_url:, user_id:)`, `get(id, user_id:)`, `list(connector:, user_id:)` (every page, `owner_type` app or user) and `delete(id, user_id:)`; a `user_id` is the owner on create and `X-Stream-User-Id` on every call, none is the app's connection with no header. `Client#get`, `post`, `put`, `patch`, `delete` and `socket` take an optional `user_id:` last (nil keeps whoever the backend acts for, empty drops it), and `Backend#acting_for` keeps working with a `@deprecated` tag pointing at it; `Dispatch#answer` acts through `Backend#acting` (`@api private`). Other SDKs follow the same rule (AI-3378..AI-3383). A screened turn carries its guardrail check: `TimelineEntry.guardrail` and the `guardrail` field of the session socket's `turn` frame, a `GuardrailCheck` (`kind`, `model`, `probability`, `threshold`, `allowed`, `latency_ms`, `held_ms`, `mode`, `failed`), absent when no check ran; a written aside (`Agent.Ask`) is no turn, so its check is not recorded. A `type: decision_model` guardrail.md takes a `question:` key, and a guardrail webhook's body has `conversation`, the lines said before the turn. Go has the regenerated client and `agents.GuardrailAsk.Conversation`. The generated clients are regenerated for Go, JavaScript types and Python `plugins/stream`. Other SDKs need to update: Ruby, PHP, .NET and Rust should regenerate for `GuardrailCheck`, and add `conversation` to their guardrail webhook body where they have one; Swift, Kotlin and Dart read `guardrail` off the `turn` frame once they show one (Swift's client was not regenerated here: its generator needs the chat repo's `tools/openapi`). Acting for a user (AI-3396): Go deprecated `Backend.ActingFor`: name the user on the call where it takes one (`UserID` of `client.Connections()` options, `XStreamUserId` of a generated call's params such as `CreateScheduledTaskParams`, or an `X-Stream-User-Id` set on one request with an `acceleration.RequestEditorFn`); `client.Agent(...)` calls take no per-call user yet, so `ActingFor` stays how they act for one. `ActingFor` keeps working and sends what it always did. Other SDKs need to update: JavaScript (#2110), Python (#2103), Ruby (#2102) and PHP (#2101) deprecate their own helper in their open PRs, each with an optional per-call user; .NET (#2099) and Rust (#2100) add the per-call user and have no public helper to deprecate. Until those merge, none of them is deprecated. +A directory is synced as its files, and the router reads them (AI-3441 is the follow-up): `POST /v1/agents/sync/files` takes `SyncAgentFilesRequest`, `files` (`[{path, content}]`) with `name`, `check_changes`, `base_change`, `dry_run` and what a program sets in code beside the directory, which wins over the files: `instructions`, `guardrail`, `skills`, `harness`, `subagent`, `sandbox`, `tags` (merged over agent.yaml's), `llm`, `stt`, `tts`, `sts`, `voice`, `greeting` and `video`. A client sends the files the format names (agent.yaml, `instructions.md`, `guardrail.md`, what is under `skills/`, `knowledge/` and `ui/`, the YAML files of `simulations/`, and the two files `ui:` may name elsewhere) and never the rest of the folder, which may be a project's source; it reads them at sync time, skips anything that is not a regular file of text, refuses a link out of the folder, and refuses a folder over the router's `MaxBytes` itself, by name. The router still decides which of the files sent are the directory: it skips a file or folder whose name starts with a dot, `__pycache__` and `node_modules` (`hidden` in `acceleration/internal/agentdir`), and leaves out, with one warning, whatever is no part of the format; the limits (`MaxFileBytes`, `MaxBytes` there, and `MaxFiles` for the request) and the hash are of the files it used. The router parses agent.yaml, `instructions.md`, `guardrail.md`, `skills/`, `knowledge/`, `knowledge/urls.yaml`, `simulations/*.yaml` and the UI files agent.yaml names, compiles `ui:` into `ui_instructions`, finds each connector's connection among the app's own by id or label and leaves out, with a warning and `left_out_connectors`, one the app does not have, and takes the hash itself, as the request's description spells out, answered as the config's `sync_hash`. A directory that does not read is a 400 `invalid_agent_directory` whose `error.problems` lists every problem with `file`, `line`, `column` and `message`. `dry_run` answers the config as it would be stored, refuses what the sync would refuse and writes nothing. It answers `SyncAgentResult`, as `POST /v1/agents/sync` does, which still takes the fields a client read from the directory; the result's `changes` lists each skill, knowledge document, knowledge url and simulation the sync creates, updates or deletes, and an `unsynced_changes` refusal carries `conflicts` and `last_change`. `GET /v1/agents/configs/{id}/directory` answers the stored agent as `{name, files, not_exported}`. Both new operations are server-side only. Go and JavaScript are done: `Sync` reads the files when it syncs (`Folder.files` in both) and sends them with what the code set. `.agent_sync` keeps `hash`, the SHA-256 of the request as JSON with sorted keys, and `sync_hash`, what the router answered, in one format both SDKs read; a sync is skipped only while the request is the same and the stored config still has that `sync_hash` and left no connector out. Both SDKs still parse the directory for the program holding it, and refuse locally what they always refused; the router is what validates and stores. Other SDKs need to update: Python (`plugins/stream`), .NET, Ruby, Rust and PHP should send the folder's files to `/v1/agents/sync/files` the same way and stop mapping agent.yaml and looking up connections for a sync. The `getstream` CLI (GetStream/cli) uses none of the SDKs: it has its own parser in `internal/agentrc` and should switch too. Until each does, `POST /v1/agents/sync` works as before. Removing the parsers from the SDKs, Go and JavaScript included, is AI-3441. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bac998668..12f7a8ac5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Features +### The router reads an agent directory from its files, and writes it back + +`POST /v1/agents/sync/files` takes an agent directory as its raw `files` (`[{path, content}]`), and the router parses, validates and stores them (`acceleration/internal/agentdir`), so a CLI, an SDK and the dashboard mean the same thing by one directory. The router decides which of the files sent are the directory; what is no part of the format is left out with a warning, and is no part of the limits or the hash. A key agent.yaml does not have, a retired one (`plugins`, `plugin_events`, `mcp_servers`) or a value of the wrong type is a 400 `invalid_agent_directory` whose `error.problems` names the file, line and column of every problem at once. The router compiles agent.yaml's `ui:` into `ui_instructions`, finds a connector's `connection` among the app's own by id or label (one the app lacks is left out with a warning, a required one refused), and takes the hash of the request itself, answered as the config's `sync_hash`. What a program sets in code beside the directory goes in the same request and wins over the files: `instructions`, `guardrail`, `skills`, `harness`, `subagent`, `sandbox`, `tags`, `llm`, `stt`, `tts`, `sts`, `voice`, `greeting` and `video`. `dry_run: true` answers what the sync would store, refuses what the sync would refuse, and writes nothing. The answer's `changes` lists each skill, knowledge document, knowledge url and simulation a sync creates, updates or deletes, on a dry run too. + +`POST /v1/agents/sync` takes the same request as before. It now checks the skills, the knowledge sources and the page urls, and asks for the money its knowledge costs, before it writes anything, and refuses two skills of one name up front (400) where it used to store the config and then fail. A 409 `unsynced_changes` from either sync carries what it would write over as `conflicts` (`resource_type`, `name`, `removed`), with the `last_change` to send back as `base_change`. + +`GET /v1/agents/configs/{id}/directory` answers a stored agent as its directory, `{name, files, not_exported}`: canonical agent.yaml (a fixed key order, what a sync fills in on its own left out), `instructions.md`, `guardrail.md`, each skill as `skills//SKILL.md` with its files, its knowledge base and `knowledge/urls.yaml`, `simulations/simulations.yaml` and the UI files. Sent back to `/v1/agents/sync/files` it stores the agent as it is, apart from what `not_exported` lists. Both operations are server-side only. A migration adds `agent_configs.ui_source`. An agent.yaml `greeting` may be its text alone. + +The Go and JavaScript SDKs sync a directory this way: `Sync` sends the files the format names (never the rest of the folder), read when it syncs, with whatever the code set beside the directory. They need a router that has `POST /v1/agents/sync/files`, so the router is deployed before an SDK with this change is. Nothing an application calls changed: both SDKs still read the directory for your program and refuse what they refused, and the router is what validates and stores it. `.agent_sync` now also keeps the hash the router stored the directory under, in one format for both SDKs, so a directory is synced again when its stored config was changed since, in the dashboard say. Removing the SDKs' own parsers is a follow-up (AI-3441). + ### The Rust SDK connects a user's own accounts `Client::connections()` creates, authorizes, reads, lists and deletes connections: `create(&NewConnection { connector, label, user_id })`, `authorize(id, &AuthorizeOptions { return_url, user_id })` (the consent's launch URL, handoff token and expiry), `get(id, user_id)`, `list(&ConnectionFilter { connector, user_id })` (every page) and `delete(id, user_id)`. A user given goes out as both the owner and `X-Stream-User-Id`; `None` is the app's own connection and leaves the client's own `ClientOptions::user_id` as it is. From b4bf11497b0a82831599c2dd82a71ba93b3f74a6 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Fri, 20 Nov 2026 17:39:58 +0100 Subject: [PATCH 6/6] chore(sdks): regenerate clients for the agent directory endpoints POST /v1/agents/sync/files and GET /v1/agents/configs/{id}/directory, the changes a sync answers with, and the problems, conflicts and last_change an error carries, as each SDK's generator writes them. Generated files only. --- .../api/default/get_agent_directory.py | 259 ++++++++++++ .../api/default/sync_agent_files.py | 397 ++++++++++++++++++ .../stream/_generated/models/__init__.py | 18 + .../_generated/models/agent_directory.py | 98 +++++ .../_generated/models/directory_file.py | 73 ++++ .../_generated/models/directory_problem.py | 91 ++++ .../stream/_generated/models/error_detail.py | 124 ++++-- .../models/sync_agent_files_request.py | 341 +++++++++++++++ .../models/sync_agent_files_request_tags.py | 48 +++ .../_generated/models/sync_agent_result.py | 25 ++ .../stream/_generated/models/sync_change.py | 84 ++++ .../_generated/models/sync_change_action.py | 30 ++ .../models/sync_change_resource_type.py | 31 ++ .../stream/_generated/models/sync_conflict.py | 91 ++++ .../Generated/Models.cs | 349 ++++++++++++++- .../core/generated/AuditResourceType.kt | 121 ++++++ .../core/generated/DirectoryProblem.kt | 67 +++ .../android/core/generated/ErrorDetail.kt | 28 +- .../android/core/generated/SyncConflict.kt | 63 +++ sdks/php/src/Generated/AgentDirectory.php | 54 +++ sdks/php/src/Generated/DirectoryFile.php | 47 +++ sdks/php/src/Generated/DirectoryProblem.php | 59 +++ sdks/php/src/Generated/ErrorDetail.php | 26 ++ .../src/Generated/SyncAgentFilesRequest.php | 180 ++++++++ sdks/php/src/Generated/SyncAgentResult.php | 7 + sdks/php/src/Generated/SyncChange.php | 51 +++ sdks/php/src/Generated/SyncConflict.php | 53 +++ .../getstream/vision_agents/generated/spec.rb | 40 +- sdks/rust/src/operations.rs | 29 ++ sdks/rust/src/types.rs | 241 ++++++++++- 30 files changed, 3093 insertions(+), 32 deletions(-) create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_agent_directory.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/api/default/sync_agent_files.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/agent_directory.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/directory_file.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/directory_problem.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request_tags.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_action.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_resource_type.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/sync_conflict.py create mode 100644 sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/AuditResourceType.kt create mode 100644 sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/DirectoryProblem.kt create mode 100644 sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/SyncConflict.kt create mode 100644 sdks/php/src/Generated/AgentDirectory.php create mode 100644 sdks/php/src/Generated/DirectoryFile.php create mode 100644 sdks/php/src/Generated/DirectoryProblem.php create mode 100644 sdks/php/src/Generated/SyncAgentFilesRequest.php create mode 100644 sdks/php/src/Generated/SyncChange.php create mode 100644 sdks/php/src/Generated/SyncConflict.php diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_agent_directory.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_agent_directory.py new file mode 100644 index 0000000000..e76cd73f1e --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_agent_directory.py @@ -0,0 +1,259 @@ +from http import HTTPStatus +from typing import Any +from urllib.parse import quote + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.agent_directory import AgentDirectory +from ...models.error_response import ErrorResponse +from ...types import Response + + +def _get_kwargs( + id: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/v1/agents/configs/{id}/directory".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> AgentDirectory | ErrorResponse | None: + if response.status_code == 200: + response_200 = AgentDirectory.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = ErrorResponse.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = ErrorResponse.from_dict(response.json()) + + return response_401 + + if response.status_code == 402: + response_402 = ErrorResponse.from_dict(response.json()) + + return response_402 + + if response.status_code == 403: + response_403 = ErrorResponse.from_dict(response.json()) + + return response_403 + + if response.status_code == 404: + response_404 = ErrorResponse.from_dict(response.json()) + + return response_404 + + if response.status_code == 500: + response_500 = ErrorResponse.from_dict(response.json()) + + return response_500 + + if response.status_code == 503: + response_503 = ErrorResponse.from_dict(response.json()) + + return response_503 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[AgentDirectory | ErrorResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: str, + *, + client: AuthenticatedClient | Client, +) -> Response[AgentDirectory | ErrorResponse]: + """An agent config as the files of its directory + + The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, + instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the + agent's knowledge base as knowledge/ with the pages it is kept filled from in + knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and + ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys + in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call + tool at its default, a connector's tools when it grants every one), and a connector that says only + its name written as the name alone. + + Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what + `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: + llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written + with its connection's id, whatever label agent.yaml first named it by, and a skill the config no + longer names is left out. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AgentDirectory | ErrorResponse] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: str, + *, + client: AuthenticatedClient | Client, +) -> AgentDirectory | ErrorResponse | None: + """An agent config as the files of its directory + + The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, + instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the + agent's knowledge base as knowledge/ with the pages it is kept filled from in + knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and + ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys + in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call + tool at its default, a connector's tools when it grants every one), and a connector that says only + its name written as the name alone. + + Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what + `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: + llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written + with its connection's id, whatever label agent.yaml first named it by, and a skill the config no + longer names is left out. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AgentDirectory | ErrorResponse + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: str, + *, + client: AuthenticatedClient | Client, +) -> Response[AgentDirectory | ErrorResponse]: + """An agent config as the files of its directory + + The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, + instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the + agent's knowledge base as knowledge/ with the pages it is kept filled from in + knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and + ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys + in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call + tool at its default, a connector's tools when it grants every one), and a connector that says only + its name written as the name alone. + + Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what + `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: + llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written + with its connection's id, whatever label agent.yaml first named it by, and a skill the config no + longer names is left out. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AgentDirectory | ErrorResponse] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: str, + *, + client: AuthenticatedClient | Client, +) -> AgentDirectory | ErrorResponse | None: + """An agent config as the files of its directory + + The reverse of a sync: the agent as the directory it would be synced from. The files are agent.yaml, + instructions.md, guardrail.md, each skill as skills//SKILL.md with the files beside it, the + agent's knowledge base as knowledge/ with the pages it is kept filled from in + knowledge/urls.yaml, its simulations in simulations/simulations.yaml, and ui/components.json and + ui/blueprints.yaml when a directory's files gave the agent its UI. agent.yaml is canonical: its keys + in a fixed order, what a sync fills in on its own left out (region us, the default harness, a call + tool at its default, a connector's tools when it grants every one), and a connector that says only + its name written as the name alone. + + Sent to POST /v1/agents/sync/files, the files store the agent as it is, apart from what + `not_exported` lists. What a directory never says is not in the files and a sync leaves it alone: + llm_fallbacks, review, resume_history, visible_tools and episode_cards. A fixed connector is written + with its connection's id, whatever label agent.yaml first named it by, and a skill the config no + longer names is left out. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AgentDirectory | ErrorResponse + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/sync_agent_files.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/sync_agent_files.py new file mode 100644 index 0000000000..e48f724290 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/sync_agent_files.py @@ -0,0 +1,397 @@ +from http import HTTPStatus +from typing import Any + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.error_response import ErrorResponse +from ...models.sync_agent_files_request import SyncAgentFilesRequest +from ...models.sync_agent_result import SyncAgentResult +from ...types import Response + + +def _get_kwargs( + *, + body: SyncAgentFilesRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/v1/agents/sync/files", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> ErrorResponse | SyncAgentResult | None: + if response.status_code == 200: + response_200 = SyncAgentResult.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = ErrorResponse.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = ErrorResponse.from_dict(response.json()) + + return response_401 + + if response.status_code == 402: + response_402 = ErrorResponse.from_dict(response.json()) + + return response_402 + + if response.status_code == 403: + response_403 = ErrorResponse.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = ErrorResponse.from_dict(response.json()) + + return response_409 + + if response.status_code == 413: + response_413 = ErrorResponse.from_dict(response.json()) + + return response_413 + + if response.status_code == 500: + response_500 = ErrorResponse.from_dict(response.json()) + + return response_500 + + if response.status_code == 503: + response_503 = ErrorResponse.from_dict(response.json()) + + return response_503 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[ErrorResponse | SyncAgentResult]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + body: SyncAgentFilesRequest, +) -> Response[ErrorResponse | SyncAgentResult]: + """Store an agent directory sent as its files + + POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading + them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It + stores what that sync stores, with the same answer. + + A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 + `invalid_agent_directory`) with every problem at its file, line and column in the error's + `problems`. A connector's connection is found among the app's own by id or by label; one the app + does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, + unless the connector is required, which is refused. agent.yaml's `ui` is compiled into + `ui_instructions` here. + + `dry_run` answers with what the sync would store and writes nothing, which is how to show what an + upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the + stored agent as files. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + body (SyncAgentFilesRequest): An agent directory as its files, which the router reads, so + every client's directory means the same thing. The fields from instructions down are what + a program sets in code beside the directory: each wins over what the files say, and is + part of the hash. + + A request sends at most 1024 files, and the directory among them holds at most 1048576 + bytes a file and 8388608 bytes in all. + + The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, + in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the + part. The parts are, for every file of the directory in path order by byte, its path and + its content; then, for each field from instructions down that is sent, its name and its + value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, + sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames + in decimal; tags. for each tag in key order; skills with the number of skills in + decimal, then for each skill in name order skills..description, .instructions, + .deadline_ms in decimal, .capture_video as true or false, and .files. for each file + in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of + the router's UI compiler, so a router that compiles ui differently syncs the directory + again. A file sent that is no part of the directory is no part of the hash, so every + client's sync of one folder has one hash. While a connector is left out sync_hash is + another hash, so the sync that finds its connection is not taken for the one that left it + out. + + What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the + voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, + chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. + calls is always written whole: a call tool the file does not name goes back to its + default. keyterms and tags are left as stored when the file has none, an empty list or + mapping included, so a file cannot clear them. instructions, guardrail, the skills the + config names, its UI instructions and its knowledge base are the directory's: a file taken + out is taken out of the agent. simulations are left alone without a simulations file, and + are exactly what the files declare with one. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ErrorResponse | SyncAgentResult] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + body: SyncAgentFilesRequest, +) -> ErrorResponse | SyncAgentResult | None: + """Store an agent directory sent as its files + + POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading + them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It + stores what that sync stores, with the same answer. + + A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 + `invalid_agent_directory`) with every problem at its file, line and column in the error's + `problems`. A connector's connection is found among the app's own by id or by label; one the app + does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, + unless the connector is required, which is refused. agent.yaml's `ui` is compiled into + `ui_instructions` here. + + `dry_run` answers with what the sync would store and writes nothing, which is how to show what an + upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the + stored agent as files. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + body (SyncAgentFilesRequest): An agent directory as its files, which the router reads, so + every client's directory means the same thing. The fields from instructions down are what + a program sets in code beside the directory: each wins over what the files say, and is + part of the hash. + + A request sends at most 1024 files, and the directory among them holds at most 1048576 + bytes a file and 8388608 bytes in all. + + The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, + in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the + part. The parts are, for every file of the directory in path order by byte, its path and + its content; then, for each field from instructions down that is sent, its name and its + value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, + sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames + in decimal; tags. for each tag in key order; skills with the number of skills in + decimal, then for each skill in name order skills..description, .instructions, + .deadline_ms in decimal, .capture_video as true or false, and .files. for each file + in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of + the router's UI compiler, so a router that compiles ui differently syncs the directory + again. A file sent that is no part of the directory is no part of the hash, so every + client's sync of one folder has one hash. While a connector is left out sync_hash is + another hash, so the sync that finds its connection is not taken for the one that left it + out. + + What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the + voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, + chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. + calls is always written whole: a call tool the file does not name goes back to its + default. keyterms and tags are left as stored when the file has none, an empty list or + mapping included, so a file cannot clear them. instructions, guardrail, the skills the + config names, its UI instructions and its knowledge base are the directory's: a file taken + out is taken out of the agent. simulations are left alone without a simulations file, and + are exactly what the files declare with one. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ErrorResponse | SyncAgentResult + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: SyncAgentFilesRequest, +) -> Response[ErrorResponse | SyncAgentResult]: + """Store an agent directory sent as its files + + POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading + them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It + stores what that sync stores, with the same answer. + + A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 + `invalid_agent_directory`) with every problem at its file, line and column in the error's + `problems`. A connector's connection is found among the app's own by id or by label; one the app + does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, + unless the connector is required, which is refused. agent.yaml's `ui` is compiled into + `ui_instructions` here. + + `dry_run` answers with what the sync would store and writes nothing, which is how to show what an + upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the + stored agent as files. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + body (SyncAgentFilesRequest): An agent directory as its files, which the router reads, so + every client's directory means the same thing. The fields from instructions down are what + a program sets in code beside the directory: each wins over what the files say, and is + part of the hash. + + A request sends at most 1024 files, and the directory among them holds at most 1048576 + bytes a file and 8388608 bytes in all. + + The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, + in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the + part. The parts are, for every file of the directory in path order by byte, its path and + its content; then, for each field from instructions down that is sent, its name and its + value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, + sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames + in decimal; tags. for each tag in key order; skills with the number of skills in + decimal, then for each skill in name order skills..description, .instructions, + .deadline_ms in decimal, .capture_video as true or false, and .files. for each file + in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of + the router's UI compiler, so a router that compiles ui differently syncs the directory + again. A file sent that is no part of the directory is no part of the hash, so every + client's sync of one folder has one hash. While a connector is left out sync_hash is + another hash, so the sync that finds its connection is not taken for the one that left it + out. + + What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the + voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, + chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. + calls is always written whole: a call tool the file does not name goes back to its + default. keyterms and tags are left as stored when the file has none, an empty list or + mapping included, so a file cannot clear them. instructions, guardrail, the skills the + config names, its UI instructions and its knowledge base are the directory's: a file taken + out is taken out of the agent. simulations are left alone without a simulations file, and + are exactly what the files declare with one. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ErrorResponse | SyncAgentResult] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + body: SyncAgentFilesRequest, +) -> ErrorResponse | SyncAgentResult | None: + """Store an agent directory sent as its files + + POST /v1/agents/sync for a client that sends the directory's files as they are and leaves reading + them to the router, so a CLI, an SDK and the dashboard all mean the same thing by one directory. It + stores what that sync stores, with the same answer. + + A key agent.yaml does not have, a retired one or a value of the wrong type is refused (400 + `invalid_agent_directory`) with every problem at its file, line and column in the error's + `problems`. A connector's connection is found among the app's own by id or by label; one the app + does not have is left out of the agent, stored in `left_out_connectors` and named in a warning, + unless the connector is required, which is refused. agent.yaml's `ui` is compiled into + `ui_instructions` here. + + `dry_run` answers with what the sync would store and writes nothing, which is how to show what an + upload would change before applying it. `GET /v1/agents/configs/{id}/directory` is the reverse: the + stored agent as files. + + Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. + + Args: + body (SyncAgentFilesRequest): An agent directory as its files, which the router reads, so + every client's directory means the same thing. The fields from instructions down are what + a program sets in code beside the directory: each wins over what the files say, and is + part of the hash. + + A request sends at most 1024 files, and the directory among them holds at most 1048576 + bytes a file and 8388608 bytes in all. + + The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, + in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the + part. The parts are, for every file of the directory in path order by byte, its path and + its content; then, for each field from instructions down that is sent, its name and its + value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, + sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames + in decimal; tags. for each tag in key order; skills with the number of skills in + decimal, then for each skill in name order skills..description, .instructions, + .deadline_ms in decimal, .capture_video as true or false, and .files. for each file + in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of + the router's UI compiler, so a router that compiles ui differently syncs the directory + again. A file sent that is no part of the directory is no part of the hash, so every + client's sync of one folder has one hash. While a connector is left out sync_hash is + another hash, so the sync that finds its connection is not taken for the one that left it + out. + + What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the + voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, + chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. + calls is always written whole: a call tool the file does not name goes back to its + default. keyterms and tags are left as stored when the file has none, an empty list or + mapping included, so a file cannot clear them. instructions, guardrail, the skills the + config names, its UI instructions and its knowledge base are the directory's: a file taken + out is taken out of the agent. simulations are left alone without a simulations file, and + are exactly what the files declare with one. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ErrorResponse | SyncAgentResult + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py index a16b70d159..f4fe40e987 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py @@ -38,6 +38,7 @@ from .agent_connector_binding import AgentConnectorBinding from .agent_connector_selection import AgentConnectorSelection from .agent_connector_selection_type import AgentConnectorSelectionType +from .agent_directory import AgentDirectory from .agent_dispatch import AgentDispatch from .agent_log import AgentLog from .agent_log_details import AgentLogDetails @@ -257,6 +258,8 @@ from .detection_request_tags import DetectionRequestTags from .detection_result import DetectionResult from .detection_status import DetectionStatus +from .directory_file import DirectoryFile +from .directory_problem import DirectoryProblem from .dispatch_setting import DispatchSetting from .duplicate_campaign_request import DuplicateCampaignRequest from .duplicate_campaign_request_contacts import DuplicateCampaignRequestContacts @@ -578,12 +581,18 @@ from .stt_options_overwrites import SttOptionsOverwrites from .subject_usage import SubjectUsage from .suspend_telephony_request import SuspendTelephonyRequest +from .sync_agent_files_request import SyncAgentFilesRequest +from .sync_agent_files_request_tags import SyncAgentFilesRequestTags from .sync_agent_request import SyncAgentRequest from .sync_agent_request_mcp_servers_item import SyncAgentRequestMcpServersItem from .sync_agent_request_plugin_events_item import SyncAgentRequestPluginEventsItem from .sync_agent_request_plugins_item_type_1 import SyncAgentRequestPluginsItemType1 from .sync_agent_request_tags import SyncAgentRequestTags from .sync_agent_result import SyncAgentResult +from .sync_change import SyncChange +from .sync_change_action import SyncChangeAction +from .sync_change_resource_type import SyncChangeResourceType +from .sync_conflict import SyncConflict from .tag_key_summary import TagKeySummary from .tag_stats_bucket import TagStatsBucket from .tag_value_summary import TagValueSummary @@ -705,6 +714,7 @@ "AgentConnectorBinding", "AgentConnectorSelection", "AgentConnectorSelectionType", + "AgentDirectory", "AgentDispatch", "AgentLog", "AgentLogDetails", @@ -920,6 +930,8 @@ "DetectionRequestTags", "DetectionResult", "DetectionStatus", + "DirectoryFile", + "DirectoryProblem", "DispatchSetting", "DuplicateCampaignRequest", "DuplicateCampaignRequestContacts", @@ -1239,12 +1251,18 @@ "SttOptionsOverwrites", "SubjectUsage", "SuspendTelephonyRequest", + "SyncAgentFilesRequest", + "SyncAgentFilesRequestTags", "SyncAgentRequest", "SyncAgentRequestMcpServersItem", "SyncAgentRequestPluginEventsItem", "SyncAgentRequestPluginsItemType1", "SyncAgentRequestTags", "SyncAgentResult", + "SyncChange", + "SyncChangeAction", + "SyncChangeResourceType", + "SyncConflict", "TagKeySummary", "TagStatsBucket", "TagValueSummary", diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_directory.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_directory.py new file mode 100644 index 0000000000..c4c16d4a75 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_directory.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +if TYPE_CHECKING: + from ..models.directory_file import DirectoryFile + + +T = TypeVar("T", bound="AgentDirectory") + + +@_attrs_define +class AgentDirectory: + """An agent config as the directory it is synced from: agent.yaml, instructions.md, guardrail.md, its skills, its + knowledge, its simulations and its UI files. + + Attributes: + files (list[DirectoryFile]): The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they + store the agent as it is. + name (str): What the agent is called, as agent.yaml names it. + not_exported (list[str]): What this agent holds that its directory cannot say and a sync of these files would + change, each in a sentence: a connector binding's events, policy or timeout, a connector that grants no tools, a + knowledge document that is not a text file, UI instructions no directory's files were compiled into. Empty when + a sync of these files leaves the agent as it is. + """ + + files: list[DirectoryFile] + name: str + not_exported: list[str] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + files = [] + for files_item_data in self.files: + files_item = files_item_data.to_dict() + files.append(files_item) + + name = self.name + + not_exported = self.not_exported + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "files": files, + "name": name, + "not_exported": not_exported, + } + ) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.directory_file import DirectoryFile + + d = dict(src_dict) + files = [] + _files = d.pop("files") + for files_item_data in _files: + files_item = DirectoryFile.from_dict(files_item_data) + + files.append(files_item) + + name = d.pop("name") + + not_exported = cast(list[str], d.pop("not_exported")) + + agent_directory = cls( + files=files, + name=name, + not_exported=not_exported, + ) + + agent_directory.additional_properties = d + return agent_directory + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/directory_file.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/directory_file.py new file mode 100644 index 0000000000..ccfe1f936d --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/directory_file.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +T = TypeVar("T", bound="DirectoryFile") + + +@_attrs_define +class DirectoryFile: + """One file of an agent directory, as a sync takes it and an export writes it. + + Attributes: + content (str): The file, whole, as text. + path (str): Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, + skills/.md or skills//SKILL.md with the files beside it, knowledge/, knowledge/urls.yaml, + simulations/.yaml, ui/components.json, ui/blueprints.yaml. Example: skills/refunds/SKILL.md. + """ + + content: str + path: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + content = self.content + + path = self.path + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "content": content, + "path": path, + } + ) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + content = d.pop("content") + + path = d.pop("path") + + directory_file = cls( + content=content, + path=path, + ) + + directory_file.additional_properties = d + return directory_file + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/directory_problem.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/directory_problem.py new file mode 100644 index 0000000000..f071570c8d --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/directory_problem.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="DirectoryProblem") + + +@_attrs_define +class DirectoryProblem: + """One thing wrong with an agent directory, at its place in a file, so an editor can point at it. + + Attributes: + file (str): The file's path in the directory. Example: agent.yaml. + message (str): + column (int | Unset): The column, counted from 1. Left out with line. Example: 3. + line (int | Unset): The line, counted from 1. Left out when the problem is the file as a whole. Example: 12. + """ + + file: str + message: str + column: int | Unset = UNSET + line: int | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + file = self.file + + message = self.message + + column = self.column + + line = self.line + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "file": file, + "message": message, + } + ) + if column is not UNSET: + field_dict["column"] = column + if line is not UNSET: + field_dict["line"] = line + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + file = d.pop("file") + + message = d.pop("message") + + column = d.pop("column", UNSET) + + line = d.pop("line", UNSET) + + directory_problem = cls( + file=file, + message=message, + column=column, + line=line, + ) + + directory_problem.additional_properties = d + return directory_problem + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/error_detail.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/error_detail.py index 130d10c210..8d3b0ab9bc 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/error_detail.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/error_detail.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Mapping -from typing import Any, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar from attrs import define as _attrs_define from attrs import field as _attrs_field @@ -10,6 +10,11 @@ from ..models.error_type import ErrorType from ..types import UNSET, Unset +if TYPE_CHECKING: + from ..models.directory_problem import DirectoryProblem + from ..models.sync_conflict import SyncConflict + + T = TypeVar("T", bound="ErrorDetail") @@ -22,30 +27,31 @@ class ErrorDetail: payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, - unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent - config, router config or voice, or another skill of the same agent config, already has the name, so another name - will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and - one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: - the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, - failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the - call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client - for the connector, and the message names each way the connector lets the app give it one), invalid_config (a - 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent - config was declared or given a function that none of the config's tool groups names, and the message names it), - insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until - credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's - spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, - the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, - on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, - so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the - request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), - spend_check_unavailable (a 503: the router could not share what the organization is spending with the other - routers for a while, so work that costs money is refused until it can; a model that costs nothing is still - served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which - spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same - interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at - that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset - or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), + unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the + files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another + agent config, router config or voice, or another skill of the same agent config, already has the name, so + another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection + as fixed, and one agent answers a channel connection's messages, so the message names that config), + call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names + how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the + agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent + found no OAuth client for the connector, and the message names each way the connector lets the app give it one), + invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a + session under an agent config was declared or given a function that none of the config's tool groups names, and + the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money + is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the + organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names + the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend + limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and + when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one + end user the request is for is spent, which stops that user and no one else, and Retry-After says when its + window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with + the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is + still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, + which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the + same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit + at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to + reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country @@ -97,6 +103,15 @@ class ErrorDetail: limit (str | Unset): Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. + problems (list[DirectoryProblem] | Unset): What is wrong with an agent directory, each problem at its file, line + and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the + rest. + conflicts (list[SyncConflict] | Unset): What a sync would write over that somebody changed since the last sync, + as the message names them, present with unsynced_changes only. + last_change (str | Unset): The newest change the sync was refused for, present with unsynced_changes only: send + it as base_change on a sync to say these have been seen. + problems_omitted (int | Unset): How many more problems an agent directory has than problems names, present only + when there are more than it lists: they are named once these are fixed. """ code: str @@ -104,6 +119,10 @@ class ErrorDetail: message: str type_: ErrorType limit: str | Unset = UNSET + problems: list[DirectoryProblem] | Unset = UNSET + conflicts: list[SyncConflict] | Unset = UNSET + last_change: str | Unset = UNSET + problems_omitted: int | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -117,6 +136,24 @@ def to_dict(self) -> dict[str, Any]: limit = self.limit + problems: list[dict[str, Any]] | Unset = UNSET + if not isinstance(self.problems, Unset): + problems = [] + for problems_item_data in self.problems: + problems_item = problems_item_data.to_dict() + problems.append(problems_item) + + conflicts: list[dict[str, Any]] | Unset = UNSET + if not isinstance(self.conflicts, Unset): + conflicts = [] + for conflicts_item_data in self.conflicts: + conflicts_item = conflicts_item_data.to_dict() + conflicts.append(conflicts_item) + + last_change = self.last_change + + problems_omitted = self.problems_omitted + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -129,11 +166,22 @@ def to_dict(self) -> dict[str, Any]: ) if limit is not UNSET: field_dict["limit"] = limit + if problems is not UNSET: + field_dict["problems"] = problems + if conflicts is not UNSET: + field_dict["conflicts"] = conflicts + if last_change is not UNSET: + field_dict["last_change"] = last_change + if problems_omitted is not UNSET: + field_dict["problems_omitted"] = problems_omitted return field_dict @classmethod def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.directory_problem import DirectoryProblem + from ..models.sync_conflict import SyncConflict + d = dict(src_dict) code = d.pop("code") @@ -145,12 +193,38 @@ def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: limit = d.pop("limit", UNSET) + _problems = d.pop("problems", UNSET) + problems: list[DirectoryProblem] | Unset = UNSET + if _problems is not UNSET: + problems = [] + for problems_item_data in _problems: + problems_item = DirectoryProblem.from_dict(problems_item_data) + + problems.append(problems_item) + + _conflicts = d.pop("conflicts", UNSET) + conflicts: list[SyncConflict] | Unset = UNSET + if _conflicts is not UNSET: + conflicts = [] + for conflicts_item_data in _conflicts: + conflicts_item = SyncConflict.from_dict(conflicts_item_data) + + conflicts.append(conflicts_item) + + last_change = d.pop("last_change", UNSET) + + problems_omitted = d.pop("problems_omitted", UNSET) + error_detail = cls( code=code, doc_url=doc_url, message=message, type_=type_, limit=limit, + problems=problems, + conflicts=conflicts, + last_change=last_change, + problems_omitted=problems_omitted, ) error_detail.additional_properties = d diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request.py new file mode 100644 index 0000000000..fae55a9d8e --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +from ..models.harness import Harness +from ..models.sandbox import Sandbox +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.directory_file import DirectoryFile + from ..models.greeting import Greeting + from ..models.session_video import SessionVideo + from ..models.skill_request import SkillRequest + from ..models.sync_agent_files_request_tags import SyncAgentFilesRequestTags + + +T = TypeVar("T", bound="SyncAgentFilesRequest") + + +@_attrs_define +class SyncAgentFilesRequest: + """An agent directory as its files, which the router reads, so every client's directory means the same thing. The + fields from instructions down are what a program sets in code beside the directory: each wins over what the files + say, and is part of the hash. + + A request sends at most 1024 files, and the directory among them holds at most 1048576 bytes a file and 8388608 + bytes in all. + + The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, of a run of parts, + each written as its length in bytes in decimal, a colon and the part. The parts are, for every file of the directory + in path order by byte, its path and its content; then, for each field from instructions down that is sent, its name + and its value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as + sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags. for each tag in key + order; skills with the number of skills in decimal, then for each skill in name order skills..description, + .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files. for each file in path + order; then, for a directory whose agent.yaml has a ui key, ui and the version of the router's UI compiler, so a + router that compiles ui differently syncs the directory again. A file sent that is no part of the directory is no + part of the hash, so every client's sync of one folder has one hash. While a connector is left out sync_hash is + another hash, so the sync that finds its connection is not taken for the one that left it out. + + What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the voice, the mode, the + region, a greeting, the sandbox, connectors, tools, channels, chat_channels, scheduling, floor_control, agents, + video and dispatch are left as stored. calls is always written whole: a call tool the file does not name goes back + to its default. keyterms and tags are left as stored when the file has none, an empty list or mapping included, so a + file cannot clear them. instructions, guardrail, the skills the config names, its UI instructions and its knowledge + base are the directory's: a file taken out is taken out of the agent. simulations are left alone without a + simulations file, and are exactly what the files declare with one. + + Attributes: + files (list[DirectoryFile]): The files of the agent's folder, as they are on disk. A client sends what it finds + and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, + knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, + and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no + part of the limits or the hash. + base_change (str | Unset): As base_change of POST /v1/agents/sync: the newest change the caller has already + seen. + check_changes (bool | Unset): As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, + when it would write over a setting somebody changed since the last one. + dry_run (bool | Unset): Work out what the sync would store and write nothing. The answer is the config as it + would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request + is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes + for what it would write over, the money for writing its knowledge included. What only the writes can tell is not + told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. + unchanged is true when the hash matches and a sync would do nothing. + greeting (Greeting | Unset): What the agent says as it joins, before anyone speaks. + guardrail (str | Unset): The guardrail a program gives in code, in place of guardrail.md. + harness (Harness | Unset): Which harness the agent's sessions run: what hands work to the subagent, loads + skills, compacts the conversation and starts the sandbox. Set on the agent, never on a session. Omit it for the + default, the only one there is. + instructions (str | Unset): The system prompt a program gives in code, in place of instructions.md. + llm (str | Unset): In place of agent.yaml's llm. + name (str | Unset): What the config is called. It wins over agent.yaml's name, and may be left out when + agent.yaml names the agent. + sandbox (Sandbox | Unset): Where the agent may run code it writes. A text agent runs it itself; a voice agent + hands it to the subagent, since running code takes seconds a call has none of. Omit it and the agent works + everything out in its head. + skills (list[SkillRequest] | Unset): The skills a program writes in code, in place of every skill under skills/. + An empty list names none. + sts (str | Unset): In place of agent.yaml's sts. + stt (str | Unset): In place of agent.yaml's stt. + subagent (str | Unset): In place of agent.yaml's subagent. + tags (SyncAgentFilesRequestTags | Unset): Labels added to agent.yaml's tags, winning where both name a key: what + an SDK's cost tracking writes. + tts (str | Unset): In place of agent.yaml's tts. + video (SessionVideo | Unset): + voice (str | Unset): In place of agent.yaml's voice. + """ + + files: list[DirectoryFile] + base_change: str | Unset = UNSET + check_changes: bool | Unset = UNSET + dry_run: bool | Unset = UNSET + greeting: Greeting | Unset = UNSET + guardrail: str | Unset = UNSET + harness: Harness | Unset = UNSET + instructions: str | Unset = UNSET + llm: str | Unset = UNSET + name: str | Unset = UNSET + sandbox: Sandbox | Unset = UNSET + skills: list[SkillRequest] | Unset = UNSET + sts: str | Unset = UNSET + stt: str | Unset = UNSET + subagent: str | Unset = UNSET + tags: SyncAgentFilesRequestTags | Unset = UNSET + tts: str | Unset = UNSET + video: SessionVideo | Unset = UNSET + voice: str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + files = [] + for files_item_data in self.files: + files_item = files_item_data.to_dict() + files.append(files_item) + + base_change = self.base_change + + check_changes = self.check_changes + + dry_run = self.dry_run + + greeting: dict[str, Any] | Unset = UNSET + if not isinstance(self.greeting, Unset): + greeting = self.greeting.to_dict() + + guardrail = self.guardrail + + harness: str | Unset = UNSET + if not isinstance(self.harness, Unset): + harness = self.harness.value + + instructions = self.instructions + + llm = self.llm + + name = self.name + + sandbox: str | Unset = UNSET + if not isinstance(self.sandbox, Unset): + sandbox = self.sandbox.value + + skills: list[dict[str, Any]] | Unset = UNSET + if not isinstance(self.skills, Unset): + skills = [] + for skills_item_data in self.skills: + skills_item = skills_item_data.to_dict() + skills.append(skills_item) + + sts = self.sts + + stt = self.stt + + subagent = self.subagent + + tags: dict[str, Any] | Unset = UNSET + if not isinstance(self.tags, Unset): + tags = self.tags.to_dict() + + tts = self.tts + + video: dict[str, Any] | Unset = UNSET + if not isinstance(self.video, Unset): + video = self.video.to_dict() + + voice = self.voice + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "files": files, + } + ) + if base_change is not UNSET: + field_dict["base_change"] = base_change + if check_changes is not UNSET: + field_dict["check_changes"] = check_changes + if dry_run is not UNSET: + field_dict["dry_run"] = dry_run + if greeting is not UNSET: + field_dict["greeting"] = greeting + if guardrail is not UNSET: + field_dict["guardrail"] = guardrail + if harness is not UNSET: + field_dict["harness"] = harness + if instructions is not UNSET: + field_dict["instructions"] = instructions + if llm is not UNSET: + field_dict["llm"] = llm + if name is not UNSET: + field_dict["name"] = name + if sandbox is not UNSET: + field_dict["sandbox"] = sandbox + if skills is not UNSET: + field_dict["skills"] = skills + if sts is not UNSET: + field_dict["sts"] = sts + if stt is not UNSET: + field_dict["stt"] = stt + if subagent is not UNSET: + field_dict["subagent"] = subagent + if tags is not UNSET: + field_dict["tags"] = tags + if tts is not UNSET: + field_dict["tts"] = tts + if video is not UNSET: + field_dict["video"] = video + if voice is not UNSET: + field_dict["voice"] = voice + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.directory_file import DirectoryFile + from ..models.greeting import Greeting + from ..models.session_video import SessionVideo + from ..models.skill_request import SkillRequest + from ..models.sync_agent_files_request_tags import SyncAgentFilesRequestTags + + d = dict(src_dict) + files = [] + _files = d.pop("files") + for files_item_data in _files: + files_item = DirectoryFile.from_dict(files_item_data) + + files.append(files_item) + + base_change = d.pop("base_change", UNSET) + + check_changes = d.pop("check_changes", UNSET) + + dry_run = d.pop("dry_run", UNSET) + + _greeting = d.pop("greeting", UNSET) + greeting: Greeting | Unset + if isinstance(_greeting, Unset): + greeting = UNSET + else: + greeting = Greeting.from_dict(_greeting) + + guardrail = d.pop("guardrail", UNSET) + + _harness = d.pop("harness", UNSET) + harness: Harness | Unset + if isinstance(_harness, Unset): + harness = UNSET + else: + harness = Harness._decode(_harness) + + instructions = d.pop("instructions", UNSET) + + llm = d.pop("llm", UNSET) + + name = d.pop("name", UNSET) + + _sandbox = d.pop("sandbox", UNSET) + sandbox: Sandbox | Unset + if isinstance(_sandbox, Unset): + sandbox = UNSET + else: + sandbox = Sandbox._decode(_sandbox) + + _skills = d.pop("skills", UNSET) + skills: list[SkillRequest] | Unset = UNSET + if _skills is not UNSET: + skills = [] + for skills_item_data in _skills: + skills_item = SkillRequest.from_dict(skills_item_data) + + skills.append(skills_item) + + sts = d.pop("sts", UNSET) + + stt = d.pop("stt", UNSET) + + subagent = d.pop("subagent", UNSET) + + _tags = d.pop("tags", UNSET) + tags: SyncAgentFilesRequestTags | Unset + if isinstance(_tags, Unset): + tags = UNSET + else: + tags = SyncAgentFilesRequestTags.from_dict(_tags) + + tts = d.pop("tts", UNSET) + + _video = d.pop("video", UNSET) + video: SessionVideo | Unset + if isinstance(_video, Unset): + video = UNSET + else: + video = SessionVideo.from_dict(_video) + + voice = d.pop("voice", UNSET) + + sync_agent_files_request = cls( + files=files, + base_change=base_change, + check_changes=check_changes, + dry_run=dry_run, + greeting=greeting, + guardrail=guardrail, + harness=harness, + instructions=instructions, + llm=llm, + name=name, + sandbox=sandbox, + skills=skills, + sts=sts, + stt=stt, + subagent=subagent, + tags=tags, + tts=tts, + video=video, + voice=voice, + ) + + sync_agent_files_request.additional_properties = d + return sync_agent_files_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request_tags.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request_tags.py new file mode 100644 index 0000000000..5e6fe56a6d --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_files_request_tags.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +T = TypeVar("T", bound="SyncAgentFilesRequestTags") + + +@_attrs_define +class SyncAgentFilesRequestTags: + """Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes.""" + + additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + sync_agent_files_request_tags = cls() + + sync_agent_files_request_tags.additional_properties = d + return sync_agent_files_request_tags + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> str: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: str) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_result.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_result.py index a80e600178..cf8c2147af 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_result.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_agent_result.py @@ -11,6 +11,7 @@ if TYPE_CHECKING: from ..models.agent_config import AgentConfig + from ..models.sync_change import SyncChange T = TypeVar("T", bound="SyncAgentResult") @@ -24,11 +25,15 @@ class SyncAgentResult: unchanged (bool): True when the hash matched and nothing was written. warnings (list[str] | None | Unset): What was stored but will not work yet, such as a channel line the app has not connected. + changes (list[SyncChange] | Unset): What the sync did, or with dry_run would do, to what the agent holds beside + its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it + leaves as it is is not listed, and nothing is for a sync that found the hash unchanged. """ config: AgentConfig unchanged: bool warnings: list[str] | None | Unset = UNSET + changes: list[SyncChange] | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -45,6 +50,13 @@ def to_dict(self) -> dict[str, Any]: else: warnings = self.warnings + changes: list[dict[str, Any]] | Unset = UNSET + if not isinstance(self.changes, Unset): + changes = [] + for changes_item_data in self.changes: + changes_item = changes_item_data.to_dict() + changes.append(changes_item) + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -55,12 +67,15 @@ def to_dict(self) -> dict[str, Any]: ) if warnings is not UNSET: field_dict["warnings"] = warnings + if changes is not UNSET: + field_dict["changes"] = changes return field_dict @classmethod def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: from ..models.agent_config import AgentConfig + from ..models.sync_change import SyncChange d = dict(src_dict) config = AgentConfig.from_dict(d.pop("config")) @@ -84,10 +99,20 @@ def _parse_warnings(data: object) -> list[str] | None | Unset: warnings = _parse_warnings(d.pop("warnings", UNSET)) + _changes = d.pop("changes", UNSET) + changes: list[SyncChange] | Unset = UNSET + if _changes is not UNSET: + changes = [] + for changes_item_data in _changes: + changes_item = SyncChange.from_dict(changes_item_data) + + changes.append(changes_item) + sync_agent_result = cls( config=config, unchanged=unchanged, warnings=warnings, + changes=changes, ) sync_agent_result.additional_properties = d diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change.py new file mode 100644 index 0000000000..51649cd4d6 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +from ..models.sync_change_action import SyncChangeAction +from ..models.sync_change_resource_type import SyncChangeResourceType + +T = TypeVar("T", bound="SyncChange") + + +@_attrs_define +class SyncChange: + """One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes. + + Attributes: + action (SyncChangeAction): + name (str): Which one: a skill's name, a knowledge document's source, a knowledge url's url, a simulation's + name. + resource_type (SyncChangeResourceType): What it is, named as GET /v1/agents/configs/{id}/changes names a skill, + a knowledge document and a knowledge url, and simulation, which that record does not keep. + """ + + action: SyncChangeAction + name: str + resource_type: SyncChangeResourceType + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + action = self.action.value + + name = self.name + + resource_type = self.resource_type.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "action": action, + "name": name, + "resource_type": resource_type, + } + ) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + action = SyncChangeAction._decode(d.pop("action")) + + name = d.pop("name") + + resource_type = SyncChangeResourceType._decode(d.pop("resource_type")) + + sync_change = cls( + action=action, + name=name, + resource_type=resource_type, + ) + + sync_change.additional_properties = d + return sync_change + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_action.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_action.py new file mode 100644 index 0000000000..4091fbb825 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_action.py @@ -0,0 +1,30 @@ +from enum import StrEnum + + +class SyncChangeAction(StrEnum): + CREATED = "created" + DELETED = "deleted" + UPDATED = "updated" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "SyncChangeAction": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_resource_type.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_resource_type.py new file mode 100644 index 0000000000..634e82fec5 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_change_resource_type.py @@ -0,0 +1,31 @@ +from enum import StrEnum + + +class SyncChangeResourceType(StrEnum): + KNOWLEDGE = "knowledge" + KNOWLEDGE_URL = "knowledge_url" + SIMULATION = "simulation" + SKILL = "skill" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "SyncChangeResourceType": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_conflict.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_conflict.py new file mode 100644 index 0000000000..63bb7da676 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/sync_conflict.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +from ..models.audit_resource_type import AuditResourceType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="SyncConflict") + + +@_attrs_define +class SyncConflict: + """One thing a sync would write over that somebody changed since the last sync. + + Attributes: + name (str): Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge + document's source; a knowledge url's url. + resource_type (AuditResourceType): What the change was made to. All of them are configuration: what an agent + does while it runs is traffic, and is read from the sessions and the logs instead. price_list is the + deployment's own, changed through the management API, and is never listed for an app. end_user is one of the + app's end users whose id was forgotten in the usage records, named by the id that replaced it. limit is one of + the organization's spend limits, named by its id, a reset of one, named reset:, or a grant, named + grant:; a change staff made through the management API is kept under the organization's id. provider_key is + a key the app keeps for its own account at a vendor, named /; its changes show the key's last + four characters at most, never the key. + removed (bool | Unset): True for a knowledge document the directory no longer has, which the sync would delete. + """ + + name: str + resource_type: AuditResourceType + removed: bool | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + resource_type = self.resource_type.value + + removed = self.removed + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "resource_type": resource_type, + } + ) + if removed is not UNSET: + field_dict["removed"] = removed + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + name = d.pop("name") + + resource_type = AuditResourceType._decode(d.pop("resource_type")) + + removed = d.pop("removed", UNSET) + + sync_conflict = cls( + name=name, + resource_type=resource_type, + removed=removed, + ) + + sync_conflict.additional_properties = d + return sync_conflict + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index c22832e5b6..75c1082564 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -1472,6 +1472,42 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// An agent config as the directory it is synced from: agent.yaml, instructions.md, guardrail.md, its skills, its knowledge, its simulations and its UI files. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class AgentDirectory + { + + /// + /// The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they store the agent as it is. + /// + [System.Text.Json.Serialization.JsonPropertyName("files")] + public System.Collections.Generic.List Files { get; set; } = new System.Collections.Generic.List(); + + /// + /// What the agent is called, as agent.yaml names it. + /// + [System.Text.Json.Serialization.JsonPropertyName("name")] + public string Name { get; set; } = default!; + + /// + /// What this agent holds that its directory cannot say and a sync of these files would change, each in a sentence: a connector binding's events, policy or timeout, a connector that grants no tools, a knowledge document that is not a text file, UI instructions no directory's files were compiled into. Empty when a sync of these files leaves the agent as it is. + /// + [System.Text.Json.Serialization.JsonPropertyName("not_exported")] + public System.Collections.Generic.List NotExported { get; set; } = new System.Collections.Generic.List(); + + private System.Collections.Generic.IDictionary? _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + /// /// What the agent leaves to the customer's own server, which waits on /v1/dispatch. Omitted settings are disabled. /// @@ -7386,6 +7422,75 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// One file of an agent directory, as a sync takes it and an export writes it. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class DirectoryFile + { + + /// + /// The file, whole, as text. + /// + [System.Text.Json.Serialization.JsonPropertyName("content")] + public string Content { get; set; } = default!; + + /// + /// Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, skills/<name>.md or skills/<name>/SKILL.md with the files beside it, knowledge/<file>, knowledge/urls.yaml, simulations/<file>.yaml, ui/components.json, ui/blueprints.yaml. + /// + [System.Text.Json.Serialization.JsonPropertyName("path")] + public string Path { get; set; } = default!; + + private System.Collections.Generic.IDictionary? _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// One thing wrong with an agent directory, at its place in a file, so an editor can point at it. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class DirectoryProblem + { + + /// + /// The column, counted from 1. Left out with line. + /// + [System.Text.Json.Serialization.JsonPropertyName("column")] + public long? Column { get; set; } = default!; + + /// + /// The file's path in the directory. + /// + [System.Text.Json.Serialization.JsonPropertyName("file")] + public string File { get; set; } = default!; + + /// + /// The line, counted from 1. Left out when the problem is the file as a whole. + /// + [System.Text.Json.Serialization.JsonPropertyName("line")] + public long? Line { get; set; } = default!; + + [System.Text.Json.Serialization.JsonPropertyName("message")] + public string Message { get; set; } = default!; + + private System.Collections.Generic.IDictionary? _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class DuplicateCampaignRequest { @@ -7507,17 +7612,29 @@ public partial class ErrorDetail { /// - /// What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and <resource>_not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. + /// What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and <resource>_not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. /// [System.Text.Json.Serialization.JsonPropertyName("code")] public string Code { get; set; } = default!; + /// + /// What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. + /// + [System.Text.Json.Serialization.JsonPropertyName("conflicts")] + public System.Collections.Generic.List? Conflicts { get; set; } = default!; + /// /// Where the code is explained. /// [System.Text.Json.Serialization.JsonPropertyName("doc_url")] public System.Uri DocUrl { get; set; } = default!; + /// + /// The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen. + /// + [System.Text.Json.Serialization.JsonPropertyName("last_change")] + public string? LastChange { get; set; } = default!; + /// /// Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. /// @@ -7530,6 +7647,18 @@ public partial class ErrorDetail [System.Text.Json.Serialization.JsonPropertyName("message")] public string Message { get; set; } = default!; + /// + /// What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. + /// + [System.Text.Json.Serialization.JsonPropertyName("problems")] + public System.Collections.Generic.List? Problems { get; set; } = default!; + + /// + /// How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed. + /// + [System.Text.Json.Serialization.JsonPropertyName("problems_omitted")] + public long? ProblemsOmitted { get; set; } = default!; + [System.Text.Json.Serialization.JsonPropertyName("type")] public string Type { get; set; } = default!; @@ -15566,6 +15695,144 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// An agent directory as its files, which the router reads, so every client's directory means the same thing. The fields from instructions down are what a program sets in code beside the directory: each wins over what the files say, and is part of the hash. + ///
+ ///
A request sends at most 1024 files, and the directory among them holds at most 1048576 bytes a file and 8388608 bytes in all. + ///
+ ///
The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the part. The parts are, for every file of the directory in path order by byte, its path and its content; then, for each field from instructions down that is sent, its name and its value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags.<key> for each tag in key order; skills with the number of skills in decimal, then for each skill in name order skills.<name>.description, .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files.<path> for each file in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of the router's UI compiler, so a router that compiles ui differently syncs the directory again. A file sent that is no part of the directory is no part of the hash, so every client's sync of one folder has one hash. While a connector is left out sync_hash is another hash, so the sync that finds its connection is not taken for the one that left it out. + ///
+ ///
What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. calls is always written whole: a call tool the file does not name goes back to its default. keyterms and tags are left as stored when the file has none, an empty list or mapping included, so a file cannot clear them. instructions, guardrail, the skills the config names, its UI instructions and its knowledge base are the directory's: a file taken out is taken out of the agent. simulations are left alone without a simulations file, and are exactly what the files declare with one. + ///
+ [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class SyncAgentFilesRequest + { + + /// + /// As base_change of POST /v1/agents/sync: the newest change the caller has already seen. + /// + [System.Text.Json.Serialization.JsonPropertyName("base_change")] + public string? BaseChange { get; set; } = default!; + + /// + /// As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over a setting somebody changed since the last one. + /// + [System.Text.Json.Serialization.JsonPropertyName("check_changes")] + public bool? CheckChanges { get; set; } = default!; + + /// + /// Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes for what it would write over, the money for writing its knowledge included. What only the writes can tell is not told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. unchanged is true when the hash matches and a sync would do nothing. + /// + [System.Text.Json.Serialization.JsonPropertyName("dry_run")] + public bool? DryRun { get; set; } = default!; + + /// + /// The files of the agent's folder, as they are on disk. A client sends what it finds and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no part of the limits or the hash. + /// + [System.Text.Json.Serialization.JsonPropertyName("files")] + public System.Collections.Generic.List Files { get; set; } = new System.Collections.Generic.List(); + + /// + /// In place of agent.yaml's greeting. + /// + [System.Text.Json.Serialization.JsonPropertyName("greeting")] + public Greeting? Greeting { get; set; } = default!; + + /// + /// The guardrail a program gives in code, in place of guardrail.md. + /// + [System.Text.Json.Serialization.JsonPropertyName("guardrail")] + public string? Guardrail { get; set; } = default!; + + /// + /// In place of agent.yaml's harness. + /// + [System.Text.Json.Serialization.JsonPropertyName("harness")] + public string? Harness { get; set; } = default!; + + /// + /// The system prompt a program gives in code, in place of instructions.md. + /// + [System.Text.Json.Serialization.JsonPropertyName("instructions")] + public string? Instructions { get; set; } = default!; + + /// + /// In place of agent.yaml's llm. + /// + [System.Text.Json.Serialization.JsonPropertyName("llm")] + public string? Llm { get; set; } = default!; + + /// + /// What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the agent. + /// + [System.Text.Json.Serialization.JsonPropertyName("name")] + public string? Name { get; set; } = default!; + + /// + /// In place of agent.yaml's sandbox. + /// + [System.Text.Json.Serialization.JsonPropertyName("sandbox")] + public string? Sandbox { get; set; } = default!; + + /// + /// The skills a program writes in code, in place of every skill under skills/. An empty list names none. + /// + [System.Text.Json.Serialization.JsonPropertyName("skills")] + public System.Collections.Generic.List? Skills { get; set; } = default!; + + /// + /// In place of agent.yaml's sts. + /// + [System.Text.Json.Serialization.JsonPropertyName("sts")] + public string? Sts { get; set; } = default!; + + /// + /// In place of agent.yaml's stt. + /// + [System.Text.Json.Serialization.JsonPropertyName("stt")] + public string? Stt { get; set; } = default!; + + /// + /// In place of agent.yaml's subagent. + /// + [System.Text.Json.Serialization.JsonPropertyName("subagent")] + public string? Subagent { get; set; } = default!; + + /// + /// Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes. + /// + [System.Text.Json.Serialization.JsonPropertyName("tags")] + public System.Collections.Generic.Dictionary? Tags { get; set; } = default!; + + /// + /// In place of agent.yaml's tts. + /// + [System.Text.Json.Serialization.JsonPropertyName("tts")] + public string? Tts { get; set; } = default!; + + /// + /// In place of agent.yaml's video. + /// + [System.Text.Json.Serialization.JsonPropertyName("video")] + public SessionVideo? Video { get; set; } = default!; + + /// + /// In place of agent.yaml's voice. + /// + [System.Text.Json.Serialization.JsonPropertyName("voice")] + public string? Voice { get; set; } = default!; + + private System.Collections.Generic.IDictionary? _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + /// /// An agent directory as it is on disk. Everything after the simulations is what the directory's declaration decides rather than what it holds, and a setting left out leaves whatever is stored, so a model chosen in the dashboard survives a sync that says nothing about it. /// @@ -15798,6 +16065,12 @@ public System.Collections.Generic.IDictionary AdditionalProperti public partial class SyncAgentResult { + /// + /// What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it leaves as it is is not listed, and nothing is for a sync that found the hash unchanged. + /// + [System.Text.Json.Serialization.JsonPropertyName("changes")] + public System.Collections.Generic.List? Changes { get; set; } = default!; + [System.Text.Json.Serialization.JsonPropertyName("config")] public AgentConfig Config { get; set; } = new AgentConfig(); @@ -15824,6 +16097,80 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class SyncChange + { + + /// + /// One of `created`, `updated`, `deleted`. + /// + [System.Text.Json.Serialization.JsonPropertyName("action")] + public string Action { get; set; } = default!; + + /// + /// Which one: a skill's name, a knowledge document's source, a knowledge url's url, a simulation's name. + /// + [System.Text.Json.Serialization.JsonPropertyName("name")] + public string Name { get; set; } = default!; + + /// + /// What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. + ///
+ ///
One of `skill`, `knowledge`, `knowledge_url`, `simulation`. + ///
+ [System.Text.Json.Serialization.JsonPropertyName("resource_type")] + public string ResourceType { get; set; } = default!; + + private System.Collections.Generic.IDictionary? _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// One thing a sync would write over that somebody changed since the last sync. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class SyncConflict + { + + /// + /// Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url. + /// + [System.Text.Json.Serialization.JsonPropertyName("name")] + public string Name { get; set; } = default!; + + /// + /// True for a knowledge document the directory no longer has, which the sync would delete. + /// + [System.Text.Json.Serialization.JsonPropertyName("removed")] + public bool? Removed { get; set; } = default!; + + /// + /// What was changed, as GET /v1/agents/configs/{id}/changes names it: agent_config, skill, knowledge or knowledge_url. + /// + [System.Text.Json.Serialization.JsonPropertyName("resource_type")] + public string ResourceType { get; set; } = default!; + + private System.Collections.Generic.IDictionary? _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class TagKeySummary { diff --git a/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/AuditResourceType.kt b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/AuditResourceType.kt new file mode 100644 index 0000000000..0d737e67df --- /dev/null +++ b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/AuditResourceType.kt @@ -0,0 +1,121 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package io.getstream.agents.android.core.generated + + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + + +/** + * What the change was made to. All of them are configuration: what an agent does while it runs is traffic, and is read from the sessions and the logs instead. price_list is the deployment's own, changed through the management API, and is never listed for an app. end_user is one of the app's end users whose id was forgotten in the usage records, named by the id that replaced it. limit is one of the organization's spend limits, named by its id, a reset of one, named reset:, or a grant, named grant:; a change staff made through the management API is kept under the organization's id. provider_key is a key the app keeps for its own account at a vendor, named /; its changes show the key's last four characters at most, never the key. + * + * Values: agent_config,skill,knowledge,knowledge_url,router_config,plugin,policy,price_list,end_user,limit,provider_key,unknown_default_open_api + */ +@Serializable(with = AuditResourceTypeSerializer::class) +internal enum class AuditResourceType(val value: kotlin.String) { + + @SerialName(value = "agent_config") + agent_config("agent_config"), + + @SerialName(value = "skill") + skill("skill"), + + @SerialName(value = "knowledge") + knowledge("knowledge"), + + @SerialName(value = "knowledge_url") + knowledge_url("knowledge_url"), + + @SerialName(value = "router_config") + router_config("router_config"), + + @SerialName(value = "plugin") + plugin("plugin"), + + @SerialName(value = "policy") + policy("policy"), + + @SerialName(value = "price_list") + price_list("price_list"), + + @SerialName(value = "end_user") + end_user("end_user"), + + @SerialName(value = "limit") + limit("limit"), + + @SerialName(value = "provider_key") + provider_key("provider_key"), + + @SerialName(value = "unknown_default_open_api") + unknown_default_open_api("unknown_default_open_api"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is AuditResourceType) "$data" else null + + /** + * Returns a valid [AuditResourceType] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): AuditResourceType? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + +internal object AuditResourceTypeSerializer : KSerializer { + override val descriptor = kotlin.String.serializer().descriptor + + override fun deserialize(decoder: Decoder): AuditResourceType { + val value = decoder.decodeSerializableValue(kotlin.String.serializer()) + return AuditResourceType.entries.firstOrNull { it.value == value } + ?: AuditResourceType.unknown_default_open_api + } + + override fun serialize(encoder: Encoder, value: AuditResourceType) { + encoder.encodeSerializableValue(kotlin.String.serializer(), value.value) + } +} + + diff --git a/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/DirectoryProblem.kt b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/DirectoryProblem.kt new file mode 100644 index 0000000000..b405311e0c --- /dev/null +++ b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/DirectoryProblem.kt @@ -0,0 +1,67 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package io.getstream.agents.android.core.generated + + +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +/** + * One thing wrong with an agent directory, at its place in a file, so an editor can point at it. + * + * @param file The file's path in the directory. + * @param message + * @param column The column, counted from 1. Left out with line. + * @param line The line, counted from 1. Left out when the problem is the file as a whole. + */ +@Serializable + +internal data class DirectoryProblem ( + + /* The file's path in the directory. */ + @SerialName(value = "file") + val file: kotlin.String, + + @SerialName(value = "message") + val message: kotlin.String, + + /* The column, counted from 1. Left out with line. */ + @SerialName(value = "column") + val column: kotlin.Long? = null, + + /* The line, counted from 1. Left out when the problem is the file as a whole. */ + @SerialName(value = "line") + val line: kotlin.Long? = null + +) { + + +} + diff --git a/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/ErrorDetail.kt b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/ErrorDetail.kt index 5f6db752af..df0d9ee770 100644 --- a/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/ErrorDetail.kt +++ b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/ErrorDetail.kt @@ -23,7 +23,9 @@ package io.getstream.agents.android.core.generated +import io.getstream.agents.android.core.generated.DirectoryProblem import io.getstream.agents.android.core.generated.ErrorType +import io.getstream.agents.android.core.generated.SyncConflict import kotlinx.serialization.Serializable import kotlinx.serialization.SerialName @@ -37,17 +39,21 @@ import kotlinx.serialization.encoding.Encoder /** * * - * @param code What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. + * @param code What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. * @param docUrl Where the code is explained. * @param message What went wrong, for a person to read. Its wording may change; branch on code. * @param type + * @param conflicts What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. + * @param lastChange The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen. * @param limit Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. + * @param problems What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. + * @param problemsOmitted How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed. */ @Serializable internal data class ErrorDetail ( - /* What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. */ + /* What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. */ @SerialName(value = "code") val code: kotlin.String, @@ -62,9 +68,25 @@ internal data class ErrorDetail ( @Contextual @SerialName(value = "type") val type: ErrorType, + /* What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. */ + @SerialName(value = "conflicts") + val conflicts: kotlin.collections.List? = null, + + /* The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen. */ + @SerialName(value = "last_change") + val lastChange: kotlin.String? = null, + /* Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. */ @SerialName(value = "limit") - val limit: kotlin.String? = null + val limit: kotlin.String? = null, + + /* What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. */ + @SerialName(value = "problems") + val problems: kotlin.collections.List? = null, + + /* How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed. */ + @SerialName(value = "problems_omitted") + val problemsOmitted: kotlin.Long? = null ) { diff --git a/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/SyncConflict.kt b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/SyncConflict.kt new file mode 100644 index 0000000000..3f2b0350fe --- /dev/null +++ b/sdks/kotlin/core/src/main/kotlin/io/getstream/agents/android/core/generated/SyncConflict.kt @@ -0,0 +1,63 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package io.getstream.agents.android.core.generated + +import io.getstream.agents.android.core.generated.AuditResourceType + +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +/** + * One thing a sync would write over that somebody changed since the last sync. + * + * @param name Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url. + * @param resourceType + * @param removed True for a knowledge document the directory no longer has, which the sync would delete. + */ +@Serializable + +internal data class SyncConflict ( + + /* Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url. */ + @SerialName(value = "name") + val name: kotlin.String, + + @Contextual @SerialName(value = "resource_type") + val resourceType: AuditResourceType, + + /* True for a knowledge document the directory no longer has, which the sync would delete. */ + @SerialName(value = "removed") + val removed: kotlin.Boolean? = null + +) { + + +} + diff --git a/sdks/php/src/Generated/AgentDirectory.php b/sdks/php/src/Generated/AgentDirectory.php new file mode 100644 index 0000000000..800fe463b1 --- /dev/null +++ b/sdks/php/src/Generated/AgentDirectory.php @@ -0,0 +1,54 @@ + */ + public array $files, + // What the agent is called, as agent.yaml names it. + public string $name, + // What this agent holds that its directory cannot say and a sync of these files would change, each in a sente... + /** @var list */ + public array $notExported, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + files: array_map(DirectoryFile::fromArray(...), Json::objects($data, 'files')), + name: Json::string($data, 'name'), + notExported: Json::strings($data, 'not_exported'), + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['files'] = array_map(static fn (DirectoryFile $each): array => $each->toArray(), $this->files); + $out['name'] = $this->name; + $out['not_exported'] = $this->notExported; + return $out; + } +} diff --git a/sdks/php/src/Generated/DirectoryFile.php b/sdks/php/src/Generated/DirectoryFile.php new file mode 100644 index 0000000000..f54722a30c --- /dev/null +++ b/sdks/php/src/Generated/DirectoryFile.php @@ -0,0 +1,47 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + content: Json::string($data, 'content'), + path: Json::string($data, 'path'), + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['content'] = $this->content; + $out['path'] = $this->path; + return $out; + } +} diff --git a/sdks/php/src/Generated/DirectoryProblem.php b/sdks/php/src/Generated/DirectoryProblem.php new file mode 100644 index 0000000000..529c3918c0 --- /dev/null +++ b/sdks/php/src/Generated/DirectoryProblem.php @@ -0,0 +1,59 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + file: Json::string($data, 'file'), + message: Json::string($data, 'message'), + column: array_key_exists('column', $data) && $data['column'] !== null ? Json::int($data, 'column') : null, + line: array_key_exists('line', $data) && $data['line'] !== null ? Json::int($data, 'line') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['file'] = $this->file; + $out['message'] = $this->message; + if ($this->column !== null) { + $out['column'] = $this->column; + } + if ($this->line !== null) { + $out['line'] = $this->line; + } + return $out; + } +} diff --git a/sdks/php/src/Generated/ErrorDetail.php b/sdks/php/src/Generated/ErrorDetail.php index 5720046994..604d2090cc 100644 --- a/sdks/php/src/Generated/ErrorDetail.php +++ b/sdks/php/src/Generated/ErrorDetail.php @@ -20,6 +20,16 @@ public function __construct( public ErrorType|string $type, // Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or... public ?string $limit = null, + // What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agen... + /** @var list|null */ + public ?array $problems = null, + // What a sync would write over that somebody changed since the last sync, as the message names them, present... + /** @var list|null */ + public ?array $conflicts = null, + // The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a... + public ?string $lastChange = null, + // How many more problems an agent directory has than problems names, present only when there are more than it... + public ?int $problemsOmitted = null, ) { } @@ -34,6 +44,10 @@ public static function fromArray(array $data): self message: Json::string($data, 'message'), type: Json::enum($data, 'type', ErrorType::class), limit: array_key_exists('limit', $data) && $data['limit'] !== null ? Json::string($data, 'limit') : null, + problems: array_key_exists('problems', $data) && $data['problems'] !== null ? array_map(DirectoryProblem::fromArray(...), Json::objects($data, 'problems')) : null, + conflicts: array_key_exists('conflicts', $data) && $data['conflicts'] !== null ? array_map(SyncConflict::fromArray(...), Json::objects($data, 'conflicts')) : null, + lastChange: array_key_exists('last_change', $data) && $data['last_change'] !== null ? Json::string($data, 'last_change') : null, + problemsOmitted: array_key_exists('problems_omitted', $data) && $data['problems_omitted'] !== null ? Json::int($data, 'problems_omitted') : null, ); } @@ -52,6 +66,18 @@ public function toArray(): array if ($this->limit !== null) { $out['limit'] = $this->limit; } + if ($this->problems !== null) { + $out['problems'] = array_map(static fn (DirectoryProblem $each): array => $each->toArray(), $this->problems); + } + if ($this->conflicts !== null) { + $out['conflicts'] = array_map(static fn (SyncConflict $each): array => $each->toArray(), $this->conflicts); + } + if ($this->lastChange !== null) { + $out['last_change'] = $this->lastChange; + } + if ($this->problemsOmitted !== null) { + $out['problems_omitted'] = $this->problemsOmitted; + } return $out; } } diff --git a/sdks/php/src/Generated/SyncAgentFilesRequest.php b/sdks/php/src/Generated/SyncAgentFilesRequest.php new file mode 100644 index 0000000000..6de089c061 --- /dev/null +++ b/sdks/php/src/Generated/SyncAgentFilesRequest.php @@ -0,0 +1,180 @@ + for each tag in key order; skills with the number of + * skills in decimal, then for each skill in name order skills..description, + * .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files. + * for each file in path order; then, for a directory whose agent.yaml has a ui key, ui and the + * version of the router's UI compiler, so a router that compiles ui differently syncs the + * directory again. A file sent that is no part of the directory is no part of the hash, so + * every client's sync of one folder has one hash. While a connector is left out sync_hash is + * another hash, so the sync that finds its connection is not taken for the one that left it + * out. What a sync does with a setting agent.yaml leaves out depends on the setting. A model, + * the voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, + * chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. + * calls is always written whole: a call tool the file does not name goes back to its default. + * keyterms and tags are left as stored when the file has none, an empty list or mapping + * included, so a file cannot clear them. instructions, guardrail, the skills the config names, + * its UI instructions and its knowledge base are the directory's: a file taken out is taken + * out of the agent. simulations are left alone without a simulations file, and are exactly + * what the files declare with one. + */ +final readonly class SyncAgentFilesRequest +{ + public function __construct( + // The files of the agent's folder, as they are on disk. A client sends what it finds and the router decides w... + /** @var list */ + public array $files, + // As base_change of POST /v1/agents/sync: the newest change the caller has already seen. + public ?string $baseChange = null, + // As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over... + public ?bool $checkChanges = null, + // Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a... + public ?bool $dryRun = null, + // In place of agent.yaml's greeting. + public ?Greeting $greeting = null, + // The guardrail a program gives in code, in place of guardrail.md. + public ?string $guardrail = null, + // In place of agent.yaml's harness. + public Harness|string|null $harness = null, + // The system prompt a program gives in code, in place of instructions.md. + public ?string $instructions = null, + // In place of agent.yaml's llm. + public ?string $llm = null, + // What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the ag... + public ?string $name = null, + // In place of agent.yaml's sandbox. + public Sandbox|string|null $sandbox = null, + // The skills a program writes in code, in place of every skill under skills/. An empty list names none. + /** @var list|null */ + public ?array $skills = null, + // In place of agent.yaml's sts. + public ?string $sts = null, + // In place of agent.yaml's stt. + public ?string $stt = null, + // In place of agent.yaml's subagent. + public ?string $subagent = null, + // Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes. + /** @var array|null */ + public ?array $tags = null, + // In place of agent.yaml's tts. + public ?string $tts = null, + // In place of agent.yaml's video. + public ?SessionVideo $video = null, + // In place of agent.yaml's voice. + public ?string $voice = null, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + files: array_map(DirectoryFile::fromArray(...), Json::objects($data, 'files')), + baseChange: array_key_exists('base_change', $data) && $data['base_change'] !== null ? Json::string($data, 'base_change') : null, + checkChanges: array_key_exists('check_changes', $data) && $data['check_changes'] !== null ? Json::bool($data, 'check_changes') : null, + dryRun: array_key_exists('dry_run', $data) && $data['dry_run'] !== null ? Json::bool($data, 'dry_run') : null, + greeting: array_key_exists('greeting', $data) && $data['greeting'] !== null ? Greeting::fromArray(Json::object($data, 'greeting')) : null, + guardrail: array_key_exists('guardrail', $data) && $data['guardrail'] !== null ? Json::string($data, 'guardrail') : null, + harness: array_key_exists('harness', $data) && $data['harness'] !== null ? Json::enum($data, 'harness', Harness::class) : null, + instructions: array_key_exists('instructions', $data) && $data['instructions'] !== null ? Json::string($data, 'instructions') : null, + llm: array_key_exists('llm', $data) && $data['llm'] !== null ? Json::string($data, 'llm') : null, + name: array_key_exists('name', $data) && $data['name'] !== null ? Json::string($data, 'name') : null, + sandbox: array_key_exists('sandbox', $data) && $data['sandbox'] !== null ? Json::enum($data, 'sandbox', Sandbox::class) : null, + skills: array_key_exists('skills', $data) && $data['skills'] !== null ? array_map(SkillRequest::fromArray(...), Json::objects($data, 'skills')) : null, + sts: array_key_exists('sts', $data) && $data['sts'] !== null ? Json::string($data, 'sts') : null, + stt: array_key_exists('stt', $data) && $data['stt'] !== null ? Json::string($data, 'stt') : null, + subagent: array_key_exists('subagent', $data) && $data['subagent'] !== null ? Json::string($data, 'subagent') : null, + tags: array_key_exists('tags', $data) && $data['tags'] !== null ? Json::stringMap($data, 'tags') : null, + tts: array_key_exists('tts', $data) && $data['tts'] !== null ? Json::string($data, 'tts') : null, + video: array_key_exists('video', $data) && $data['video'] !== null ? SessionVideo::fromArray(Json::object($data, 'video')) : null, + voice: array_key_exists('voice', $data) && $data['voice'] !== null ? Json::string($data, 'voice') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['files'] = array_map(static fn (DirectoryFile $each): array => $each->toArray(), $this->files); + if ($this->baseChange !== null) { + $out['base_change'] = $this->baseChange; + } + if ($this->checkChanges !== null) { + $out['check_changes'] = $this->checkChanges; + } + if ($this->dryRun !== null) { + $out['dry_run'] = $this->dryRun; + } + if ($this->greeting !== null) { + $out['greeting'] = $this->greeting->toArray(); + } + if ($this->guardrail !== null) { + $out['guardrail'] = $this->guardrail; + } + if ($this->harness !== null) { + $out['harness'] = Json::enumValue($this->harness); + } + if ($this->instructions !== null) { + $out['instructions'] = $this->instructions; + } + if ($this->llm !== null) { + $out['llm'] = $this->llm; + } + if ($this->name !== null) { + $out['name'] = $this->name; + } + if ($this->sandbox !== null) { + $out['sandbox'] = Json::enumValue($this->sandbox); + } + if ($this->skills !== null) { + $out['skills'] = array_map(static fn (SkillRequest $each): array => $each->toArray(), $this->skills); + } + if ($this->sts !== null) { + $out['sts'] = $this->sts; + } + if ($this->stt !== null) { + $out['stt'] = $this->stt; + } + if ($this->subagent !== null) { + $out['subagent'] = $this->subagent; + } + if ($this->tags !== null) { + $out['tags'] = $this->tags; + } + if ($this->tts !== null) { + $out['tts'] = $this->tts; + } + if ($this->video !== null) { + $out['video'] = $this->video->toArray(); + } + if ($this->voice !== null) { + $out['voice'] = $this->voice; + } + return $out; + } +} diff --git a/sdks/php/src/Generated/SyncAgentResult.php b/sdks/php/src/Generated/SyncAgentResult.php index b1ba003e69..475e074736 100644 --- a/sdks/php/src/Generated/SyncAgentResult.php +++ b/sdks/php/src/Generated/SyncAgentResult.php @@ -17,6 +17,9 @@ public function __construct( // What was stored but will not work yet, such as a channel line the app has not connected. /** @var list|null */ public ?array $warnings = null, + // What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowled... + /** @var list|null */ + public ?array $changes = null, ) { } @@ -29,6 +32,7 @@ public static function fromArray(array $data): self config: AgentConfig::fromArray(Json::object($data, 'config')), unchanged: Json::bool($data, 'unchanged'), warnings: array_key_exists('warnings', $data) && $data['warnings'] !== null ? Json::strings($data, 'warnings') : null, + changes: array_key_exists('changes', $data) && $data['changes'] !== null ? array_map(SyncChange::fromArray(...), Json::objects($data, 'changes')) : null, ); } @@ -45,6 +49,9 @@ public function toArray(): array if ($this->warnings !== null) { $out['warnings'] = $this->warnings; } + if ($this->changes !== null) { + $out['changes'] = array_map(static fn (SyncChange $each): array => $each->toArray(), $this->changes); + } return $out; } } diff --git a/sdks/php/src/Generated/SyncChange.php b/sdks/php/src/Generated/SyncChange.php new file mode 100644 index 0000000000..65b0d27bff --- /dev/null +++ b/sdks/php/src/Generated/SyncChange.php @@ -0,0 +1,51 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + action: Json::string($data, 'action'), + name: Json::string($data, 'name'), + resourceType: Json::string($data, 'resource_type'), + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['action'] = $this->action; + $out['name'] = $this->name; + $out['resource_type'] = $this->resourceType; + return $out; + } +} diff --git a/sdks/php/src/Generated/SyncConflict.php b/sdks/php/src/Generated/SyncConflict.php new file mode 100644 index 0000000000..a64a842cba --- /dev/null +++ b/sdks/php/src/Generated/SyncConflict.php @@ -0,0 +1,53 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + name: Json::string($data, 'name'), + resourceType: Json::enum($data, 'resource_type', AuditResourceType::class), + removed: array_key_exists('removed', $data) && $data['removed'] !== null ? Json::bool($data, 'removed') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['name'] = $this->name; + $out['resource_type'] = Json::enumValue($this->resourceType); + if ($this->removed !== null) { + $out['removed'] = $this->removed; + } + return $out; + } +} diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index d3de9f917d..340e68d157 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -500,6 +500,12 @@ module Generated body: nil, body_required: false, socket: false, client_accessible: false }.freeze, + "getAgentDirectory" => { + method: :get, path: "/v1/agents/configs/{id}/directory", + path_params: %w[id].freeze, query: [].freeze, + body: nil, body_required: false, + socket: false, client_accessible: false + }.freeze, "getAgentLog" => { method: :get, path: "/v1/agents/logs/{id}", path_params: %w[id].freeze, query: [].freeze, @@ -1664,6 +1670,12 @@ module Generated body: "SyncAgentRequest", body_required: true, socket: false, client_accessible: false }.freeze, + "syncAgentFiles" => { + method: :post, path: "/v1/agents/sync/files", + path_params: [].freeze, query: [].freeze, + body: "SyncAgentFilesRequest", body_required: true, + socket: false, client_accessible: false + }.freeze, "transcribeRecording" => { method: :post, path: "/v1/stt/recordings", path_params: [].freeze, query: [].freeze, @@ -1905,6 +1917,10 @@ module Generated properties: %w[connection_id type].freeze, required: %w[type].freeze, open: false }.freeze, + "AgentDirectory" => { + properties: %w[files name not_exported].freeze, + required: %w[name files not_exported].freeze, open: false + }.freeze, "AgentDispatch" => { properties: %w[incoming_call text].freeze, required: [].freeze, open: false @@ -2449,6 +2465,14 @@ module Generated properties: %w[cost_micros detections error error_code id model provider status].freeze, required: %w[cost_micros detections id status].freeze, open: false }.freeze, + "DirectoryFile" => { + properties: %w[content path].freeze, + required: %w[path content].freeze, open: false + }.freeze, + "DirectoryProblem" => { + properties: %w[column file line message].freeze, + required: %w[file message].freeze, open: false + }.freeze, "DuplicateCampaignRequest" => { properties: %w[contacts].freeze, required: %w[contacts].freeze, open: false @@ -2462,7 +2486,7 @@ module Generated required: [].freeze, open: false }.freeze, "ErrorDetail" => { - properties: %w[code doc_url limit message type].freeze, + properties: %w[code conflicts doc_url last_change limit message problems problems_omitted type].freeze, required: %w[message type code doc_url].freeze, open: false }.freeze, "ErrorResponse" => { @@ -3173,14 +3197,26 @@ module Generated properties: %w[reason suspended_by].freeze, required: %w[reason suspended_by].freeze, open: false }.freeze, + "SyncAgentFilesRequest" => { + properties: %w[base_change check_changes dry_run files greeting guardrail harness instructions llm name sandbox skills sts stt subagent tags tts video voice].freeze, + required: %w[files].freeze, open: false + }.freeze, "SyncAgentRequest" => { properties: %w[agents base_change calls channels chat_channels check_changes connectors dispatch floor_control greeting guardrail harness hash image instructions keyterms knowledge knowledge_urls left_out_connectors llm mcp_servers mode name plugin_events plugins region resume_history role sandbox sandbox_options scheduling search simulations skills sts stt subagent tags tools tts ui_instructions video voice].freeze, required: %w[name hash].freeze, open: false }.freeze, "SyncAgentResult" => { - properties: %w[config unchanged warnings].freeze, + properties: %w[changes config unchanged warnings].freeze, required: %w[unchanged config].freeze, open: false }.freeze, + "SyncChange" => { + properties: %w[action name resource_type].freeze, + required: %w[resource_type name action].freeze, open: false + }.freeze, + "SyncConflict" => { + properties: %w[name removed resource_type].freeze, + required: %w[resource_type name].freeze, open: false + }.freeze, "TagKeySummary" => { properties: %w[cost_micros_total coverage key request_count top_values value_count].freeze, required: %w[cost_micros_total coverage key request_count top_values value_count].freeze, open: false diff --git a/sdks/rust/src/operations.rs b/sdks/rust/src/operations.rs index 94b7da0ab6..5b3f0c92aa 100644 --- a/sdks/rust/src/operations.rs +++ b/sdks/rust/src/operations.rs @@ -605,6 +605,19 @@ impl Client { ) .await } + /// An agent config as the files of its directory + /// + /// `GET /v1/agents/configs/{id}/directory` (`getAgentDirectory`). + pub async fn get_agent_directory(&self, id: &str) -> Result { + self.send( + Method::GET, + &format!("/v1/agents/configs/{id}/directory", id = segment(id)), + None::<&()>, + None::<&()>, + "getAgentDirectory", + ) + .await + } /// List connections /// /// `GET /v1/agents/connections` (`listConnections`). @@ -2393,6 +2406,22 @@ impl Client { ) .await } + /// Store an agent directory sent as its files + /// + /// `POST /v1/agents/sync/files` (`syncAgentFiles`). + pub async fn sync_agent_files( + &self, + body: &types::SyncAgentFilesRequest, + ) -> Result { + self.send( + Method::POST, + "/v1/agents/sync/files", + None::<&()>, + Some(body), + "syncAgentFiles", + ) + .await + } /// Get a user's phone link /// /// `GET /v1/agents/users/{user_id}` (`getUser`). diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index 65e0d31578..92aed28106 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -954,6 +954,16 @@ impl ::std::convert::TryFrom<::std::string::String> for AgentConnectorSelectionT value.parse() } } +///An agent config as the directory it is synced from: agent.yaml, instructions.md, guardrail.md, its skills, its knowledge, its simulations and its UI files. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] +pub struct AgentDirectory { + ///The directory's files, in path order. Sent back to POST /v1/agents/sync/files, they store the agent as it is. + pub files: ::std::vec::Vec, + ///What the agent is called, as agent.yaml names it. + pub name: ::std::string::String, + ///What this agent holds that its directory cannot say and a sync of these files would change, each in a sentence: a connector binding's events, policy or timeout, a connector that grants no tools, a knowledge document that is not a text file, UI instructions no directory's files were compiled into. Empty when a sync of these files leaves the agent as it is. + pub not_exported: ::std::vec::Vec<::std::string::String>, +} ///What the agent leaves to the customer's own server, which waits on /v1/dispatch. Omitted settings are disabled. #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, Default, PartialEq)] pub struct AgentDispatch { @@ -5642,6 +5652,27 @@ impl ::std::convert::TryFrom<::std::string::String> for DetectionStatus { value.parse() } } +///One file of an agent directory, as a sync takes it and an export writes it. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] +pub struct DirectoryFile { + ///The file, whole, as text. + pub content: ::std::string::String, + ///Where the file is in the directory, with forward slashes: agent.yaml, instructions.md, guardrail.md, skills/.md or skills//SKILL.md with the files beside it, knowledge/, knowledge/urls.yaml, simulations/.yaml, ui/components.json, ui/blueprints.yaml. + pub path: ::std::string::String, +} +///One thing wrong with an agent directory, at its place in a file, so an editor can point at it. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] +pub struct DirectoryProblem { + ///The column, counted from 1. Left out with line. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub column: ::std::option::Option, + ///The file's path in the directory. + pub file: ::std::string::String, + ///The line, counted from 1. Left out when the problem is the file as a whole. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub line: ::std::option::Option, + pub message: ::std::string::String, +} ///Whether this kind of work is left to the customer's own dispatch worker. #[derive( ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, @@ -5885,15 +5916,27 @@ pub enum EqualsOrIn { ///`ErrorDetail` #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] pub struct ErrorDetail { - ///What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. + ///What went wrong, for a program to branch on. Every type has a code of its own name (invalid_request, unauthenticated, forbidden, payment_required, not_found, method_not_allowed, not_acceptable, conflict, gone, payload_too_large, unsupported_media_type, rate_limited, internal_error, unavailable, timeout) that a failure has when nothing names it better. The others are validation_failed, missing_customer, missing_organization, server_side_only, not_configured (this deployment does not offer the feature), modality_not_routed, unsynced_changes (a sync asked to check would write over somebody's edits), invalid_agent_directory (a 400: the files of an agent directory do not read, and problems says where in which file), name_taken (a 409: another agent config, router config or voice, or another skill of the same agent config, already has the name, so another name will do), channel_connection_taken (a 409: another live agent config binds the channel connection as fixed, and one agent answers a channel connection's messages, so the message names that config), call_unanswered (a 409: the call placed for a phone session ended with nobody answering, and the message names how: busy, no_answer, failed or canceled. Opening the session is refused, or, when the status came while the agent was joining the call, the session is ended at once and kept as ended), no_oauth_client (a 400: a consent found no OAuth client for the connector, and the message names each way the connector lets the app give it one), invalid_config (a 400: an agent config a run names does not start a session), tool_not_configured (a 400: a session under an agent config was declared or given a function that none of the config's tool groups names, and the message names it), insufficient_credits (a 402: the organization's credit is spent, so work that costs money is refused until credit is added; a model that costs nothing is still served), system_limit_reached (a 402: the organization's spend hard limit for the day or the month is reached, whatever its credit, and the message names the interval, the amount and when it resets), spend_limit_reached (a 402: one of the organization's own spend limits is spent, on the organization, an app, a key, a usage category or a team, and the message says which and when it resets, so retrying before then is refused again), user_limit_reached (a 429: a spend limit on the one end user the request is for is spent, which stops that user and no one else, and Retry-After says when its window ends), spend_check_unavailable (a 503: the router could not share what the organization is spending with the other routers for a while, so work that costs money is refused until it can; a model that costs nothing is still served, and Retry-After says to try again in a few seconds), budget_moved (a 400: a policy sent a budget, which spend limits replaced), limit_above_parent (a 400: a spend limit is above a limit of its parent in the same interval, and the message names the parent's limit), limit_exists (a 409: the subject already has a limit at that level and interval, and the message names its id), no_limit (a 404: the subject has no spend limit to reset or grant past), use_team (a 400: a category starting team: was sent, where the team field names a team), invalid_expiry (a 400: a grant's expires_at is not in the future, or is more than 366 days away), too_many_grants (a 409: the organization has 20 live grants, as many as it may), tier_limit_reached (the organization's tier limits refuse the work, and limit says which: a 403 for a call or a transfer, to a country the tier does not reach, past its minutes or recipients of the day, or past its calls at once; a 400 for an agent config whose sandbox is bigger or more open than the organization's sandbox limits allow. The message names the tier and the limit), account_suspended (a 403: the organization is suspended, and every request is refused, one for a model that costs nothing included, until it is restored; the message says to contact support), concurrency_limited (a 429: the app has as many runs in flight as it may, and Retry-After says when to try again), model_failed (a 503: the model failed or gave no answer), prompt_injection (a 400: the prompt injection screen refused the input of a run or a tool result it read, which retrying an unchanged input does not fix), image_unavailable (a 400: an image a run was handed could not be fetched or is not a JPEG, PNG, WebP or GIF, which retrying the same image does not fix), document_too_large (a 413: a file sent with a response has more pages or text than one may, alone or with the files the conversation already holds, and the message names the limit), document_unreadable (a 400: a file sent with a response could not be read, such as one with a password, one that is damaged or one with no text in it, which retrying the same file does not fix), invalid_usage_categories (a 400: the usage categories the request names, in the token's usage_categories and team claims or in X-Stream-Usage-Categories, are more than 10, one is not 1 to 64 characters of A-Z, a-z, 0-9, _ . : -, more than one names a team, or the team is over 59 characters), memory_unavailable (a 503: the memory store could not delete what was asked, so nothing that waits on it was deleted either, and the same request later can succeed), billing_not_enabled (a 404: this deployment bills nobody, or the caller's app is in no organization it bills, so there is no account to read), provider_takes_no_key (a 400: a key was put for a provider whose work is never routed on a customer's own key here, and the message names the ones that are), campaign_locked (a 409: the campaign's state does not allow the change, such as a launched campaign's sequence, or resuming one that is running), campaign_not_ready (a 400: a launch found the campaign missing what it needs to ring anybody, and the message says what), consent_required (a 400: a launch did not say the people on the campaign agreed to be called), branch_limit_reached (a 409: the conversation has as many edit and regenerate points as Stream Chat keeps for it, 100, so a regenerate or an edit is refused and the conversation is continued in a new chat; asking and reading are unaffected), branch_too_long (a 409: the branch an activation would bring back is more than 100 messages to send again, so it is continued in a new chat), branch_unavailable (a 410: the copies of a hidden branch were deleted, as a memory truncate deletes them, so it can be neither read nor brought back), switch_unfinished (a 409: a regenerate, an edit or an activation of the session failed after Stream Chat may have rewound, and finishing it still fails because Stream Chat does not answer, so the session's questions, regenerates, edits and activations are refused meanwhile; try again: each one tries to finish it first, so it clears once Stream Chat answers), and _not_found for agent_config, call, campaign, channel_account, command, connection, grant, knowledge_document, knowledge_url, limit, provider_key, router_config, scheduled_task, session, simulation, simulation_run, skill and voice. A scheduled task also has invalid_schedule (a schedule that does not read: at and in both or neither, a date, time or duration that does not parse, or until without repeat), schedule_in_past, schedule_too_far (a one-shot, or an in, more than a year ahead), invalid_timezone, timezone_unknown (no zone was given and neither the user nor the config has one), invalid_repeat, interval_too_short (a run moved to less than 15 minutes from now and earlier than the run it replaces) and too_many_tasks (a 409: the user is at their active-task limit). More may be added, so a client should expect one it does not know. pub code: ::std::string::String, + ///What a sync would write over that somebody changed since the last sync, as the message names them, present with unsynced_changes only. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub conflicts: ::std::option::Option<::std::vec::Vec>, ///Where the code is explained. pub doc_url: ::std::string::String, + ///The newest change the sync was refused for, present with unsynced_changes only: send it as base_change on a sync to say these have been seen. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub last_change: ::std::option::Option<::std::string::String>, ///Which limit refused the work, present with tier_limit_reached only: country, per_day, recipients_per_day or concurrent for a call or a transfer, sandbox_network, sandbox_cpu, sandbox_memory_gb or sandbox_disk_gb for an agent config's sandbox. More may be added. #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub limit: ::std::option::Option<::std::string::String>, ///What went wrong, for a person to read. Its wording may change; branch on code. pub message: ::std::string::String, + ///What is wrong with an agent directory, each problem at its file, line and column, present with invalid_agent_directory only. At most 100 are named, and problems_omitted counts the rest. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub problems: ::std::option::Option<::std::vec::Vec>, + ///How many more problems an agent directory has than problems names, present only when there are more than it lists: they are named once these are fixed. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub problems_omitted: ::std::option::Option, #[serde(rename = "type")] pub type_: ErrorType, } @@ -13205,6 +13248,75 @@ pub struct SuspendTelephonyRequest { ///Who is suspending it. pub suspended_by: ::std::string::String, } +/**An agent directory as its files, which the router reads, so every client's directory means the same thing. The fields from instructions down are what a program sets in code beside the directory: each wins over what the files say, and is part of the hash. + +A request sends at most 1024 files, and the directory among them holds at most 1048576 bytes a file and 8388608 bytes in all. + +The hash of a sync is the router's own, answered as the config's sync_hash: the SHA-256, in hex, of a run of parts, each written as its length in bytes in decimal, a colon and the part. The parts are, for every file of the directory in path order by byte, its path and its content; then, for each field from instructions down that is sent, its name and its value, in this order: instructions, guardrail, harness, subagent, sandbox, llm, stt, tts, sts and voice as sent; greeting.text and greeting.mode; video.source and video.max_frames in decimal; tags. for each tag in key order; skills with the number of skills in decimal, then for each skill in name order skills..description, .instructions, .deadline_ms in decimal, .capture_video as true or false, and .files. for each file in path order; then, for a directory whose agent.yaml has a ui key, ui and the version of the router's UI compiler, so a router that compiles ui differently syncs the directory again. A file sent that is no part of the directory is no part of the hash, so every client's sync of one folder has one hash. While a connector is left out sync_hash is another hash, so the sync that finds its connection is not taken for the one that left it out. + +What a sync does with a setting agent.yaml leaves out depends on the setting. A model, the voice, the mode, the region, a greeting, the sandbox, connectors, tools, channels, chat_channels, scheduling, floor_control, agents, video and dispatch are left as stored. calls is always written whole: a call tool the file does not name goes back to its default. keyterms and tags are left as stored when the file has none, an empty list or mapping included, so a file cannot clear them. instructions, guardrail, the skills the config names, its UI instructions and its knowledge base are the directory's: a file taken out is taken out of the agent. simulations are left alone without a simulations file, and are exactly what the files declare with one.*/ +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] +pub struct SyncAgentFilesRequest { + ///As base_change of POST /v1/agents/sync: the newest change the caller has already seen. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub base_change: ::std::option::Option<::std::string::String>, + ///As check_changes of POST /v1/agents/sync: refuse the sync, with unsynced_changes, when it would write over a setting somebody changed since the last one. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub check_changes: ::std::option::Option, + ///Work out what the sync would store and write nothing. The answer is the config as it would be stored, one a dry run would create having no id, with the warnings a sync would give, and the request is refused as the sync would be: for what the files say, for what the router cannot run, and with check_changes for what it would write over, the money for writing its knowledge included. What only the writes can tell is not told: whether the knowledge provider takes the passages, and whether a page of knowledge/urls.yaml can be read. unchanged is true when the hash matches and a sync would do nothing. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub dry_run: ::std::option::Option, + ///The files of the agent's folder, as they are on disk. A client sends what it finds and the router decides what is the directory: agent.yaml, instructions.md, guardrail.md, what is under skills/, knowledge/ and simulations/, and the UI files agent.yaml names. A file or folder whose name starts with a dot, and anything under __pycache__ or node_modules, is skipped. Any other file is left out with a warning, and is no part of the limits or the hash. + pub files: ::std::vec::Vec, + ///In place of agent.yaml's greeting. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub greeting: ::std::option::Option, + ///The guardrail a program gives in code, in place of guardrail.md. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub guardrail: ::std::option::Option<::std::string::String>, + ///In place of agent.yaml's harness. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub harness: ::std::option::Option, + ///The system prompt a program gives in code, in place of instructions.md. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub instructions: ::std::option::Option<::std::string::String>, + ///In place of agent.yaml's llm. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub llm: ::std::option::Option<::std::string::String>, + ///What the config is called. It wins over agent.yaml's name, and may be left out when agent.yaml names the agent. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub name: ::std::option::Option<::std::string::String>, + ///In place of agent.yaml's sandbox. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub sandbox: ::std::option::Option, + ///The skills a program writes in code, in place of every skill under skills/. An empty list names none. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub skills: ::std::option::Option<::std::vec::Vec>, + ///In place of agent.yaml's sts. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub sts: ::std::option::Option<::std::string::String>, + ///In place of agent.yaml's stt. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub stt: ::std::option::Option<::std::string::String>, + ///In place of agent.yaml's subagent. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub subagent: ::std::option::Option<::std::string::String>, + ///Labels added to agent.yaml's tags, winning where both name a key: what an SDK's cost tracking writes. + #[serde( + default, + skip_serializing_if = ":: std :: collections :: BTreeMap::is_empty" + )] + pub tags: ::std::collections::BTreeMap<::std::string::String, ::std::string::String>, + ///In place of agent.yaml's tts. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub tts: ::std::option::Option<::std::string::String>, + ///In place of agent.yaml's video. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub video: ::std::option::Option, + ///In place of agent.yaml's voice. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub voice: ::std::option::Option<::std::string::String>, +} ///An agent directory as it is on disk. Everything after the simulations is what the directory's declaration decides rather than what it holds, and a setting left out leaves whatever is stored, so a model chosen in the dashboard survives a sync that says nothing about it. #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] pub struct SyncAgentRequest { @@ -13343,6 +13455,9 @@ impl ::std::convert::From<::serde_json::Map<::std::string::String, ::serde_json: ///`SyncAgentResult` #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] pub struct SyncAgentResult { + ///What the sync did, or with dry_run would do, to what the agent holds beside its config: each skill, knowledge document, knowledge url and simulation it created, updated or deleted. One it leaves as it is is not listed, and nothing is for a sync that found the hash unchanged. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub changes: ::std::option::Option<::std::vec::Vec>, pub config: AgentConfig, ///True when the hash matched and nothing was written. pub unchanged: bool, @@ -13350,6 +13465,130 @@ pub struct SyncAgentResult { #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub warnings: ::std::option::Option<::std::vec::Vec<::std::string::String>>, } +///One skill, knowledge document, knowledge url or simulation a sync creates, updates or deletes. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +pub struct SyncChange { + pub action: SyncChangeAction, + ///Which one: a skill's name, a knowledge document's source, a knowledge url's url, a simulation's name. + pub name: ::std::string::String, + ///What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. + pub resource_type: SyncChangeResourceType, +} +///`SyncChangeAction` +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum SyncChangeAction { + #[serde(rename = "created")] + Created, + #[serde(rename = "updated")] + Updated, + #[serde(rename = "deleted")] + Deleted, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for SyncChangeAction { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Created => f.write_str("created"), + Self::Updated => f.write_str("updated"), + Self::Deleted => f.write_str("deleted"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for SyncChangeAction { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "created" => Ok(Self::Created), + "updated" => Ok(Self::Updated), + "deleted" => Ok(Self::Deleted), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for SyncChangeAction { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for SyncChangeAction { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} +///What it is, named as GET /v1/agents/configs/{id}/changes names a skill, a knowledge document and a knowledge url, and simulation, which that record does not keep. +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum SyncChangeResourceType { + #[serde(rename = "skill")] + Skill, + #[serde(rename = "knowledge")] + Knowledge, + #[serde(rename = "knowledge_url")] + KnowledgeUrl, + #[serde(rename = "simulation")] + Simulation, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for SyncChangeResourceType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Skill => f.write_str("skill"), + Self::Knowledge => f.write_str("knowledge"), + Self::KnowledgeUrl => f.write_str("knowledge_url"), + Self::Simulation => f.write_str("simulation"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for SyncChangeResourceType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "skill" => Ok(Self::Skill), + "knowledge" => Ok(Self::Knowledge), + "knowledge_url" => Ok(Self::KnowledgeUrl), + "simulation" => Ok(Self::Simulation), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for SyncChangeResourceType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for SyncChangeResourceType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} +///One thing a sync would write over that somebody changed since the last sync. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +pub struct SyncConflict { + ///Which one: the field of an agent_config, such as llm or instructions; a skill's name; a knowledge document's source; a knowledge url's url. + pub name: ::std::string::String, + ///True for a knowledge document the directory no longer has, which the sync would delete. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub removed: ::std::option::Option, + ///What was changed, as GET /v1/agents/configs/{id}/changes names it: agent_config, skill, knowledge or knowledge_url. + pub resource_type: AuditResourceType, +} ///`TagKeySummary` #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] pub struct TagKeySummary {