neui

package module
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

Neui: an AI agent built into your Go web app

Go Reference

Neui is an AI agent and a web framework built as one stack. The framework, Doors (Apache-2.0), lets Go teams build modern interactive apps with no separate frontend and no API layer. Neui adds the agent: it runs inside the user's session, sees the parts of the page you let it see, operates the UI like a user, and brings its own work environment for the jobs a chat alone cannot do.

Every feature you build for users is instantly usable by the agent, with a work environment powerful enough to automate the work your users do by hand.

Contents

What you get

The agent operates your UI

Developers mark which parts of the page the agent may see and use, right in the existing markup. The agent then clicks, types and reads like a user, and the app's own logic runs. There is no per-action code to write and no state to mirror.

Capability-based tools with reactive permissions

A tool is one Go function that runs on the server, with no endpoint or permission code to write. Developers decide what the agent can see and do right where they build the UI, so its access is scoped to each user and updates with the screen.

An agent work environment

The agent gets its own file workspace, scripts that run bulk UI work in one step, spreadsheets, web search, MCP connectors, background tasks, and automatic handling of long conversations. One script can call every tool and work across the whole UI in a single step.

Agentic apps

When a user needs functionality your UI doesn't have, the agent builds it on the spot, anything from a single screen to a specialized app. It runs in the page with the user's permissions, and the agent stays in the loop to make the decisions.

Your users get the chat experience they already know from chat apps, with nothing to build or purchase.

Cheaper to run

The conversation is prompt-cache friendly, so input costs 6 to 14 times less than in copilots that rebuild the prompt for every screen. Built-in scripts do bulk work without extra model turns or context bloat.

The browser can't steer the agent

The conversation, instructions and tools live on the server, and the browser sends only the user's new message. A tampered browser can't add tools, rewrite history or change what the agent is told.

Runtime

Every open page runs on the server, integrated with the agent harness. You mark in the page template what the agent may see and use.

Works the real UI. The agent reads, fills and clicks the elements you mark, as the user would, and your handlers run as usual. There's no state to mirror and no action to re-implement.

~>neui.Use{
    Desc: "Customer's email",
    // RW: the agent reads the value in the user's browser or writes its own.
    Rights: neui.RW,
} <input type="email" name="email">

Tools in the template. Register agent tools right in the page template, based on the UI context and the user's permissions.

~(if user.IsAdmin() {
    ~neui.Tool[Refund, Receipt]{
        Name: "refund",
        Desc: "Refund the order",
        Handler: orders.Refund,
    }
})

Persistent tools. Go functions registered for the whole app or for one session are available in every chat. The built-in work environment works the same way.

crm := neui.NewModule("crm", "Customer records of the signed-in user")
crm.Tool("find", "Find a customer by name or email", customers.Find)

Page context. Attach data to a part of the page to tell the agent what it shows, such as the records in a view or hints on how to use it.

~neui.Data{
    Text: "Open orders of this customer",
    Object: orders,
}

App events. Your app can tell the agent when something happens, such as a payment arriving. An idle agent reacts right away, and a busy one picks it up on its next turn.

neui.Instance(ctx).Emit(ctx, "payment_received", map[string]string{"invoice": id}, nil)

Stays in sync without token waste. The framework tracks tools, data and elements as the page changes, and the agent reads them only when it needs to.

Agentic Apps

An agentic app is a program the agent writes and runs for the user in an island, a region of the page. You declare the island in the page template and give it the components and Go functions its apps may use.

~neui.Island{
	Name:     "workbench",
	Desc:     "Apps for the user's invoice work",
	Template: func(slot gox.Comp) gox.Elem { return <section>~(slot)</section> },
	Library: func(l neui.Library) error {
		l.Tool("overdue", "Overdue invoices, one page at a time", invoices.Overdue)
		l.Tool("remind", "Send a payment reminder", invoices.Remind)
		return nekit.IslandRegisterAll(l)
	},
}
  • The agent writes a program. It builds an app for the user's request from your component library and the tools you declare, and runs it right away.
  • The model is called only for decisions. The app handles user actions itself and calls the agent only when a decision is needed. The UI stays responsive, no tokens are spent on routine steps, and the agent is still in the loop.
  • Data stays out of the context. The agent works with data through the app's script, without loading it into its context. Data costs no tokens, and text inside it can't steer the agent.
  • App changes on the fly. The user can ask for an extra column, another step or a different check, and the agent updates the running app without losing their work.
  • Runs with the user's permissions. The app is sandboxed and can do only what the signed-in user can, through the components and functions you declared, with no endpoints to build.

Widgets included. neui.dev/nekit includes a general-purpose widget set built to cover any business flow, from data entry to review and reporting. It takes your theme from CSS variables, and your own components work alongside it.

  • Layout. Columns, rows and grids that compose widgets into typical layouts.
  • Form. Declarative forms for any purpose: every field type, groups, repeatable lists and multi-step flows, with live validation.
  • Table. A full-featured data table with paging, sorting, search, row selection and row actions.
  • Markdown cards. A universal output block for text, tables, images and file downloads, plain or as a card, info, success, warning or danger.

Compared with declarative generative UI. In A2UI and similar formats the model describes the screen, and every user action is another model turn. That suits a one-off screen such as a confirmation. An agentic app is cheaper and faster as soon as the user does more than a few things.

Chat

Neui ships a complete chat experience out of the box. Use it as is, configure its theme and features, or fork it to build something of your own.

  • Controls users already know. Stop a run, edit and resend a message, queue the next one while the agent works, or duplicate a thread to try another path.
  • Persistence out of the box. History, the thread list and search are built in. Use the included storages or plug in your own.
  • Runs on the server. The conversation, the running answer and the agent's tools live on the server, and the browser only displays them. Nothing sensitive reaches the client, and a reload or a second tab picks up where the user left off.
  • Files both ways. Users attach files to a message, and the agent returns finished files as downloads in its answer.
  • Long conversations keep working. Older turns are summarized in the background when the context fills up, without interrupting the user.
  • Task management and more. Background jobs show in the chat and can be cancelled, the agent can ask questions with ready answers, and your app can notify the agent when something happens.

Work environment

Besides the chat and the page, the agent has a workspace on the server for real work.

  • Filesystem. Each chat gets its own sandboxed filesystem, where the agent reads uploads, unpacks archives and builds new files for the user to download.
  • Scripts for bulk work. The agent writes one script that calls its tools and works across the page, so updating 300 invoices takes a single model call.
  • Spreadsheets. The agent reads large .xlsx files and turns raw exports into finished reports with totals, charts and highlighting.
  • Web and connectors. The agent reads web pages, searches through a service you connect, and uses the tools of your MCP servers.
  • Background tasks. Long operations run in the background, and the agent picks up each result when it arrives, so the user keeps chatting.
  • Contained and configurable. Resources are capped, and you choose which tools each app or user gets.

Compared with CopilotKit and Vercel AI SDK

The usual alternatives are CopilotKit (plus paid Intelligence), Vercel AI SDK with Sandbox, assistant-ui, OpenAI ChatKit, LangGraph with Agent Server, browser agents and WebMCP. For a Go team each of them means bolting on a React island, CopilotKit and a Node runtime: a second stack.

Each row was checked against neui's code and the competitors' current docs and source. Competitor cells describe the default open-source path.

Capability Neui CopilotKit Vercel AI SDK
Agent operates the UI Yes. Developers mark, right in the UI template, which elements the agent may see and use; no per-action code is needed. Partial. One hand-written frontend tool per action No. Fully hand-wired: each UI action needs a tool on the server and a handler in the browser
Agent work environment Built in. Its own files and scripts; one script can call every tool and work across the whole UI in a single step No. One tool call per action; sandbox only through a third-party service; files need own wiring Partial. Code can call your tools, with Claude only; paid cloud sandbox; files need own wiring
Agentic apps Agent-written app. Built from your components, it runs on the server, handles clicks and data itself, and calls the model only when a step needs judgment Model per click, or a free-form page. The model fills your components and each click starts a new agent run. Or it writes its own web page, reaching your data through functions the developer registers Model picks a tool, you pre-wire the screen. The model calls one of your tools and your component shows the result. Clicks run code you wrote in advance; the next agent step is another model request
Agent permissions Built into the screen. Developers decide what the agent can see and do where they build the UI; no permission code to write Manual. Developers write checks for each agent action; tools sent by the browser are trusted Manual. Developers write checks for each tool
Provider isolation Yes. Keys, prompt and tools are server-only Weak. Keys stay on the server, but the browser sends history, tools, context and state on every run, and the server uses them as sent Partial. Tools declared on the server; chat history sent from the browser
Prompt-cache stability Yes. Fixed tools and system prompt; page state arrives in tool results No. The system prompt is rebuilt from app state every run Yes. Server owns tools and prompt; history is only appended
Traffic per message Tiny. Only the new message; history stays on the server, minimal delays Grows with the conversation. Full history on every run and every tool call Grows with the conversation by default. Full history on every request and tool call; trimming needs your own server-side store
Advanced chat features Built in. Thread list, full-text search, rewind, clone Partial. Thread list needs the paid tier; other features require own wiring and backend support No. No thread list; thread features are yours to build
Auto-compaction Yes. Rolling, in the background, seamless for the user, or manual, and recovers when the history outgrows the model's window, for example after a switch to a smaller model No Partial. Manual recipe in the docs
Supported platforms One. Web apps built with Go and Doors Many. React-first web frontends Many. Most JavaScript frameworks

Getting started

go get neui.dev

Neui is a Go module (neui.dev) that plugs into a Doors app: you configure the agent once with options on the Doors app, turn it on per session once the user is known, and render nekit.Chat on the pages where the user should talk to the agent.

Claude, GPT and DeepSeek providers are included, as are SQLite thread storage and disk or S3 upload storage.

Start with the quick start and the back office example, and see the package documentation in doc.go, api/doc.go and nekit/doc.go, and the Doors documentation for building the app itself.

Documentation

Overview

Package neui is an agent harness for Doors apps: it runs a chat agent inside the user's session that can see and operate the page.

Configure the app with optional app options for doors.NewApp, such as WithProvider, WithModules and WithThreadConfig, and turn the agent on per session with Enable(ctx, opts...), typically from an auth hook or handler once the user is known; its Option values add to or take precedence over the app options. A session needs a provider from WithProvider or OptionProvider. Render a chat UI, such as nekit.Chat, where the user should talk to the agent.

The agent acts through tools. A Module built with NewModule, or a built-in one such as ModuleJS or ModuleWeb, serves tools to the threads of the sessions it is registered for. On the page, Space, Tool, Data and Use expose regions, actions, context and elements of what the user sees, and Island gives the agent a region where it runs its own UI.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Disable

func Disable(ctx context.Context)

Disable turns neui off for the doors session ctx belongs to: every tab's chat closes its thread and shows the disabled state. It does nothing when the session is not enabled; a later Enable turns it on again.

func Enable

func Enable(ctx context.Context, opts ...Option) error

Enable turns neui on for the doors session ctx belongs to, typically from an auth hook or handler once the user is known; ctx must be a doors context of that session. Every tab of the session, open now or later, links its chat to it. Once enabled, later calls do nothing unless OptionForce is passed.

The session's provider is the one OptionProvider sets, else the app's WithProvider; when there is neither, Enable returns api.ErrNoProvider and leaves the session as it was.

Without a message or file storage set, threads are kept in memory and files in a per-session temporary directory, both lost when the session ends.

Enable creates a per-session temporary directory for the agent's workspace and returns an error when it cannot; a later call tries again.

func Instance

func Instance(ctx context.Context) api.Instance

Instance returns the neui view of the doors instance (browser tab) ctx belongs to: its chat state, the session's open chats, and thread switching. A host uses it to build its own chat list or thread controls. ctx must come from a doors render or handler; it works before Enable, reporting api.InstanceDisabled.

func IslandDir

func IslandDir(ctx context.Context) string

IslandDir returns the workspace dir of the island app ctx renders or handles events for, where widgets keep their files. It is emptied when the app starts and kept after it ends. It is "" outside an island.

func IslandFS

func IslandFS(ctx context.Context) api.FS

IslandFS returns the workspace filesystem of the thread running the island app, so a widget can read or write the files the agent works with. It is nil outside an island.

func IslandID

func IslandID(ctx context.Context) string

IslandID returns the id of the island ctx renders or handles events for. The element holding the island's content carries it as data-neui-island, so [data-neui-island="<id>"] selects inside one island when a page has several. It stays the same across the island's app runs. It is "" outside an island.

func IslandReport

func IslandReport(ctx context.Context, err error)

IslandReport reports a runtime error of a widget to the agent, naming the widget. The widget keeps running; the agent decides whether to update or replace it. A widget's repeated message is reported once per script, under the same limit as IslandCall failures, and every report is written to the app's log. ctx must come from the island (a widget's render, Update or event handlers); elsewhere IslandReport does nothing.

func IslandScope

func IslandScope(ctx context.Context) doors.Scopes

IslandScope returns a blocking doors scope shared by all widgets of the island app: put it on their submit hooks so a new submit is rejected while an earlier one is still being handled. Leave it off hooks that only update the widget itself. It is nil outside an island.

func IslandStore

func IslandStore(ctx context.Context) doors.Store

IslandStore returns the store of the island app ctx renders or handles events for, shared by all the app's widgets; each app run gets a fresh one. It is nil outside an island.

func ToolConfig

func ToolConfig(ctx context.Context) api.ThreadConfig

ToolConfig returns the thread configuration of the session serving the call: the app's WithThreadConfig with defaults filled in. It panics when ctx comes from neither a tool call nor ToolThreadContext.

func ToolFS

func ToolFS(ctx context.Context) api.FS

ToolFS returns the thread's workspace filesystem, the same one the files module and scripts read and write. A tool that produces a file writes it here so the agent can open it by path. It panics when ctx comes from neither a tool call nor ToolThreadContext.

func ToolFilesConfig

func ToolFilesConfig(ctx context.Context) api.FilesConfig

ToolFilesConfig returns the file and workspace limits of the session serving the call, with defaults filled in: OptionFilesConfig if Enable got one, else the app's WithFilesConfig. A tool producing or reading files honours the same caps the built-in file tools do by reading them here. It panics when ctx comes from neither a tool call nor ToolThreadContext.

func ToolFromAgent

func ToolFromAgent(ctx context.Context) bool

ToolFromAgent reports whether the agent called the tool directly as a tool call, rather than from a script. It is false outside a tool call.

func ToolFromJS

func ToolFromJS(ctx context.Context) bool

ToolFromJS reports whether the tool was called from a script rather than by the agent directly; a tool can refuse script calls or behave differently. It is false outside a tool call.

func ToolModel

func ToolModel(ctx context.Context) api.Model

ToolModel returns the model of the session's provider, the one the thread streams with: its name and its context, image and request limits, where a zero limit means unknown. It panics when ctx comes from neither a tool call nor ToolThreadContext.

func ToolThreadContext

func ToolThreadContext(ctx context.Context) context.Context

ToolThreadContext returns a context that outlives the tool call: for a module tool it ends when the thread closes, for a page tool when the thread is no longer linked to the page that rendered it. ToolFS, ToolThreadID, ToolConfig, ToolModel, ToolFilesConfig and ToolTask work on it; ToolFromJS and ToolFromAgent report false on it. Run background work registered with ToolTask on it. It panics when ctx comes from neither a tool call nor ToolThreadContext.

func ToolThreadID

func ToolThreadID(ctx context.Context) api.ThreadID

ToolThreadID returns the ID of the thread the tool call belongs to, e.g. to key host-side state per conversation. It panics when ctx comes from neither a tool call nor ToolThreadContext.

func WithFilesConfig

func WithFilesConfig(c api.FilesConfig) doors.With

WithFilesConfig sets the workspace filesystem and files module limits of every session the app serves, as an app option for doors.NewApp; without it every limit takes its default. OptionFilesConfig takes precedence for one session.

func WithIslandConfig

func WithIslandConfig(c api.IslandConfig) doors.With

WithIslandConfig sets the limits of the scripts that draw into islands, as an app option for doors.NewApp.

func WithJSConfig

func WithJSConfig(c JSConfig) doors.With

WithJSConfig tunes the js runtime of ModuleJS, as an app option for doors.NewApp: the app then schedules scripts against its own memory and worker limits. Without it, the app runs on defaults and shares one set of limits with every other app in the process that does not set it. The runtime and its scheduling goroutine live for the rest of the process, even after the app is dropped, so build each app once per process.

func WithModules

func WithModules(m ...ModuleFactory) doors.With

WithModules registers modules for every session the app serves, as an app option for doors.NewApp. OptionModules adds more to one session.

func WithProvider

func WithProvider(p api.Provider) doors.With

WithProvider sets the app-wide provider, as an app option for doors.NewApp. It is optional: a session enabled with OptionProvider runs on that provider instead, and Enable returns api.ErrNoProvider when neither is set.

func WithSystemPrompt

func WithSystemPrompt(prompt ...string) doors.With

WithSystemPrompt adds text to the system prompt of every session the app serves, as an app option for doors.NewApp. Its parts are joined by blank lines after neui's own runtime note and before the modules' guidance. OptionSystemPrompt adds more after it for one session.

func WithThreadConfig

func WithThreadConfig(c api.ThreadConfig) doors.With

WithThreadConfig sets the configuration every session the app serves runs on, as an app option for doors.NewApp.

func WithUploadStorage

func WithUploadStorage(s api.UploadStorage) doors.With

WithUploadStorage sets where every session's uploaded files are stored, as an app option for doors.NewApp, replacing the per-session temporary directory. OptionUploadStorage overrides it for one session.

Types

type Answer

type Answer[O any] = common.Answer[O]

Answer is how an Ask's form returns the user's answer to the waiting tool call: Submit with the answer or Fail with an error.

type AnyModule

type AnyModule = common.Module

AnyModule is what a ModuleFactory returns: a named set of tools. Module implements it; a host implements it directly only to serve tools it builds itself. The runtime calls its methods from several goroutines and reads Desc and List again for every request, so a change shows up at the next one.

type AnyTool

type AnyTool = common.Tool

AnyTool is one tool as the runtime sees it, the result of a Tool or Ask definition.

type Ask

type Ask[I any, O any] struct {
	// Name is the tool's name. Names are reduced to ASCII letters, digits
	// and _ (runs of other characters become one _); names that reduce to
	// the same value replace each other, and a name must keep at least one
	// letter or digit.
	Name string
	// Desc tells the agent what the question is for; a note that the call
	// waits for the user and fails when they dismiss it is appended.
	Desc string
	// Handler builds the question from the decoded input: the api.ChatAsk
	// form shown in the chat, whose handlers call answer.Submit or
	// answer.Fail. The runtime sets ChatAsk.Cancel itself, so a dismissal
	// fails the call with api.ErrCanceledByUser.
	Handler func(input I, answer Answer[O]) api.ChatAsk
}

Ask defines a tool that shows the user a question in the chat and returns their answer. Add it to a Module; a Library refuses it with ErrAskInIsland.

type Data

type Data struct {
	// Text is a note in plain words, on its own or saying what Object is.
	Text string
	// Object is a structured payload, sent to the agent as JSON.
	Object any
}

Data attaches information for the agent to the space it is rendered in, such as the records a view shows or hints on how to use it. It need not match what the screen displays. The agent sees it as it was at render: render it again to change what the agent sees.

func (Data) Main

func (d Data) Main() gox.Elem

Main adds the data to the space it is rendered in, for as long as that render lives. It renders nothing; the render fails when Object cannot be encoded to JSON.

type Island

type Island struct {
	// Name identifies the island among the spaces next to it; the agent sees
	// it with Desc. Names are reduced to ASCII letters, digits and _ (runs of
	// other characters become one _); names that reduce to the same value
	// replace each other. Give it at least one letter or digit: a name
	// without one is replaced and a warning is logged. An empty name fails
	// the render.
	Name string
	// Desc tells the agent what the island is for.
	Desc string
	// Placeholder shows while no app runs, including after the user stops
	// one.
	Placeholder gox.Elem
	// Template wraps a running app: slot is where the app's UI goes.
	Template func(slot gox.Comp) gox.Elem
	// Success replaces the app when it ends without error; nil shows
	// Placeholder. Calling close shows Placeholder.
	Success func(close func(ctx context.Context)) gox.Elem
	// Failure replaces the app when it ends with err; nil shows Placeholder.
	// Calling close shows Placeholder.
	Failure func(close func(ctx context.Context), err error) gox.Elem
	// Library fills l with what scripts may use; it runs on every render.
	// Package nekit has built-in layouts and widgets to add.
	Library func(l Library) error
}

Island is a region of the page where the agent runs an app: a script that draws a UI from the views, controls and layouts its Library offers and reacts to what the user does there. It appears to the agent as a space marked as an island. Template and Library are required.

func (Island) Main

func (i Island) Main() gox.Elem

Main renders the island and adds its space. When Library returns an error, the error is logged and Placeholder renders with no island space. A running app ends when the island unmounts.

type IslandCall

type IslandCall[I, O any] = island.Call[I, O]

IslandCall is a widget param or patch field that takes a function from the island script: the source of a single-argument JavaScript function, such as `(row) => app.price(row.sku) * row.qty`. Its syntax is checked when the params are decoded, so a broken source throws at the script's line. In the widget's schema it reads as a string holding a function from the schema of I to the schema of O.

The widget runs it with Call(ctx, i), which decodes the result into an O. Calls of one app run one at a time on a JS runtime separate from the island script, limited by IslandConfig.FnMemory, with each call limited by IslandConfig.FnTime and IslandConfig.MaxCallDepth. Its globals are frozen, so no call leaves state for the next, and a call sees only its argument, the app functions, console and the standard built-ins. ctx must come from the island (a widget's render, Update or event handlers); elsewhere Call returns an error. A failure caused by the function, including a result that does not decode into O, is written to the app's log and reported to the agent once per source in each script; past a limit on reports per script, it is only logged.

type JSConfig

type JSConfig struct {
	// TotalMemory is the sum in bytes of the memory budgets of all scripts
	// executing at once across the app. Default 512 MiB; a value below
	// WorkerMemory is raised to it.
	TotalMemory int
	// WorkerMemory is the largest memory budget in bytes one script may
	// take. Default 128 MiB; a value below DefaultMemory is raised to it.
	WorkerMemory int
	// DefaultMemory is the memory budget in bytes of a script that asks for
	// less or none. Default 16 MiB, at least 4 MiB.
	DefaultMemory int
	// MaxWorkers is how many scripts may execute at once across the app.
	// Default 16.
	MaxWorkers int
	// JobTimeout caps how long one script may execute, its tool calls
	// included: tool calls in flight are cancelled at the limit. A script may
	// ask for less. Default 30s.
	JobTimeout time.Duration
	// AsyncAfter is how long a run keeps the tool call waiting before it
	// detaches and delivers its result later as a background task. Default
	// 10s.
	AsyncAfter time.Duration
	// MaxQueue is how many scripts may wait to start across the app; one
	// submitted past it is rejected. Default 100.
	MaxQueue int
	// MaxCallDepth is how many nested JS calls a script may make before an
	// error is thrown. Default 1000.
	MaxCallDepth int
}

JSConfig tunes the js runtime; a zero or negative field takes its default. The limits are shared by every session of an app that sets WithJSConfig, and by every app in the process that does not: a script waits to start until a worker and enough of TotalMemory are free.

type Library

type Library struct {
	// contains filtered or unexported fields
}

Library is what an island's scripts may use: app functions, views, controls, layouts and head elements. Island.Library fills it. Names of views, controls and layouts must be JavaScript identifiers, unique among them, and not slot, draw, notify, end or root; scripts reach them as ui.<name>.

func (Library) Add

func (l Library) Add(t Tooler) error

Add adds the tool t defines as an app function, which scripts call as app.<name>, with the name sanitized as NewModule does. The island also adds it to its space as a tool, so the agent and scripts outside the island call it with the page tools. It fails when that name is empty, starts with a digit or is used by another app function, when the input or output type has no JSON schema, and with api.ErrAskInIsland for an Ask.

func (Library) Control

func (l Library) Control[I any, U any, O any](name string, desc string, f func(ctx context.Context, i I, submit func(ctx context.Context, o O) bool) (api.Widget[U], error)) error

Control adds a widget like View that also hands the script a value O the user produced, such as a form submission. submit delivers o to the script waiting in ui.draw() and reports whether it was taken; it returns false when no script is waiting or the app has ended, so the widget can keep the user's input. Call it from an event handler, with that handler's ctx.

func (Library) Head

func (l Library) Head(e ...gox.Elem)

Head adds elements, such as stylesheets, rendered ahead of every app the island runs.

func (Library) Layout

func (l Library) Layout[I any](name string, desc string, f func(i I, children []gox.Comp) gox.Comp) error

Layout adds a container scripts use to arrange other items; f builds it from the params decoded into I and the rendered children, in order.

func (Library) Tool

func (l Library) Tool[I any, O any](name string, desc string, f func(ctx context.Context, input I) (O, error)) error

Tool is shorthand for Add(Tool[I, O]{name, desc, f}).

func (Library) View

func (l Library) View[I any, U any](name string, desc string, f func(ctx context.Context, i I) (api.Widget[U], error)) error

View adds a widget scripts create with params decoded into I and later patch with values decoded into U; f builds it from the params, with the island ctx of the script call that creates it. Use it for UI that shows rather than collects, such as text, tables or charts.

type MCPConfig

type MCPConfig struct {
	// Name is the module name the server's tools register under, sanitized as
	// NewModule does.
	Name string
	// URL is the server's streamable HTTP endpoint.
	URL string
	// Headers go on every request to the server, e.g. Authorization.
	Headers map[string]string
	// Enable filters the server's tools by name; nil enables them all.
	Enable func(toolName string) bool
	// IdleTimeout closes the connection after this long without a tool call,
	// or after at most a minute when no call has been made yet. Default 10m.
	IdleTimeout time.Duration
	// Ping is the keepalive interval; a missed ping reconnects. Default 30s.
	Ping time.Duration
}

MCPConfig describes one MCP server. Name and URL must be set; any other zero field takes its default.

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module is a tool module a host assembles with Add and Remove; they, the Tool and Ask shorthands, and the AnyModule reads the runtime makes, are safe to call from any goroutine. Module is a handle: copies share one tool set, so one Module can back every thread and a change reaches all of them. Make one with NewModule; the zero Module is not usable.

func NewModule

func NewModule(name string, desc string) Module

NewModule returns an empty module to fill with Add, Tool and Ask. Its tools reach the agent as name__tool, and desc is added to the system prompt as the module's guidance; leave it empty to add nothing. Names are reduced to ASCII letters, digits and _ (runs of other characters become one _); names that reduce to the same value replace each other, and a name with no letter or digit becomes empty. Leading and trailing runs are dropped. Register it with a factory that returns the same value for every thread:

m := neui.NewModule("crm", "Customer records of the signed-in user.")
neui.WithModules(func(context.Context) neui.AnyModule { return m })

func (Module) Add

func (m Module) Add(t Tooler) (ToolID, error)

Add adds the tool t defines and returns its ID; a tool with the same name is replaced. It fails when the input or output type has no JSON schema.

func (Module) Ask

func (m Module) Ask[I any, O any](name string, desc string, f func(input I, answer Answer[O]) api.ChatAsk) (ToolID, error)

Ask is shorthand for Add(Ask[I, O]{name, desc, f}).

func (Module) Desc

func (m Module) Desc() string

Desc is the module's guidance for the system prompt.

func (Module) Get

func (m Module) Get(name string) (AnyTool, bool)

Get returns the tool with that name, sanitized as NewModule does, and whether there is one.

func (Module) List

func (m Module) List() []AnyTool

List returns the module's tools in name order.

func (Module) Name

func (m Module) Name() string

Name is the module's sanitized name, the prefix of its tools' names.

func (Module) Remove

func (m Module) Remove(id ToolID)

Remove removes the tool Add returned id for. It does nothing when that tool is gone or was replaced by a later Add of the same name.

func (Module) Tool

func (m Module) Tool[I any, O any](name string, desc string, f func(ctx context.Context, input I) (O, error)) (ToolID, error)

Tool is shorthand for Add(Tool[I, O]{name, desc, f}).

type ModuleFactory

type ModuleFactory = common.ModuleFactory

ModuleFactory returns the module a thread uses: a fresh one or a shared one. The runtime calls it each time a thread opens, with a context that lasts while the thread stays open and carries no tool call. When two modules of a thread share a name, the later one is skipped and an error is logged; the built-in chat, time and files modules come first. Register factories with WithModules or OptionModules.

var ModuleJS ModuleFactory = js.Module

ModuleJS is the js module: js__run lets the agent run a JavaScript file from the workspace or inline code, with the thread's tools callable as synchronous functions (a tool can refuse script calls, as js's own tools do), and js__stop cancels a run that outlived its call. Scripts run on QuickJS (plain ES2023: no Node, browser APIs or promises), limited by JSConfig.

func ModuleMCP

func ModuleMCP(c MCPConfig) ModuleFactory

ModuleMCP is a module backed by a remote MCP server over streamable HTTP. Its tools register under MCPConfig.Name, sanitized as NewModule does, as name__tool, and follow the server's list-changed notifications. Each thread gets its own connection, opened when the thread opens and retried with backoff while it fails; a call made while it is failing fails at once. The connection, live or still retrying, closes after IdleTimeout without a call, or after at most a minute when no call has been made yet, which also stops the retries; the next call reconnects and waits for it.

func ModuleWeb

func ModuleWeb(c WebConfig) ModuleFactory

ModuleWeb is the web module: web__fetch for one URL over HTTP and, when WebConfig.Search is set, web__search against that backend. No search backend ships with the module, so the zero WebConfig takes every default and registers fetch alone.

func ModuleXLS

func ModuleXLS(c XLSConfig) ModuleFactory

ModuleXLS is the xls module: Excel workbooks read and written through the workspace. The zero XLSConfig takes every default.

type Option

type Option = common.Option

Option configures one session in Enable. Options apply in order on top of the app-wide With* values.

func OptionFilesConfig

func OptionFilesConfig(c api.FilesConfig) Option

OptionFilesConfig sets the session's workspace filesystem and files module limits, taking precedence over the app's WithFilesConfig if there is one. It is not merged with the app's config: a zero field takes the built-in default.

func OptionForce

func OptionForce() Option

OptionForce makes Enable rebuild the configuration of a session that is already enabled, instead of doing nothing. The new configuration starts from the app-wide values again, so options passed to an earlier Enable do not carry over. Every open tab then relinks its chat to it.

func OptionMessageStorage

func OptionMessageStorage(s api.MessageStorage) Option

OptionMessageStorage sets where the session's threads, rounds and records are stored, replacing the in-memory default that is lost with the session.

func OptionModules

func OptionModules(m ...ModuleFactory) Option

OptionModules registers modules for one session, after the built-in and the app's own; a module whose name is already taken is skipped.

func OptionProvider

func OptionProvider(p api.Provider) Option

OptionProvider sets the session's provider, taking precedence over the app's WithProvider if there is one. A nil p leaves the session without a provider, and Enable returns api.ErrNoProvider.

func OptionSystemPrompt

func OptionSystemPrompt(prompt ...string) Option

OptionSystemPrompt appends to the app's system prompt for one session.

func OptionUploadStorage

func OptionUploadStorage(s api.UploadStorage) Option

OptionUploadStorage sets where the session's uploaded files are stored, both the user's (api.UserUploadsDir) and the agent's (api.AgentUploadsDir), overriding the app's WithUploadStorage and the default temporary directory.

type Rights

type Rights int

Rights sets what the agent may do with a Use.

const (
	// RW allows reading, writing, clicking and focusing; it is the zero value.
	RW Rights = iota
	// R allows reading and focusing only.
	R
	// W allows writing, clicking and focusing, but not reading the value.
	W
)

type SearchBackend

type SearchBackend interface {
	// Search runs q and returns up to q.Num results, best first.
	Search(ctx context.Context, q SearchQuery) ([]SearchResult, error)
}

SearchBackend is what web__search queries; supply one as WebConfig.Search. It returns results in rank order, best first, and no error when the query simply matched nothing.

type SearchQuery

type SearchQuery struct {
	// Text is what to search for, as words rather than a URL.
	Text string
	// Num is how many results the caller wants, best first.
	Num int
	// Domains restricts results to these hostnames; empty means no
	// restriction. A backend that cannot filter on it ignores it.
	Domains []string
	// Since keeps only pages published after it; zero means no window. A
	// backend that cannot filter on it ignores it.
	Since time.Time
}

SearchQuery is one search request handed to a SearchBackend.

type SearchResult

type SearchResult struct {
	// Title is the backend's title for the page.
	Title string
	// URL is the page address, what the model fetches to read it.
	URL string
	// Snippet is the backend's own one- or two-sentence extract; empty when
	// it returns Content instead.
	Snippet string
	// Content is passages from the page when the backend returns them; the
	// module caps each result's Content at WebConfig.SearchChars.
	Content string
	// Published is the publication date the backend reports, as text; empty
	// when it reports none.
	Published string
}

SearchResult is one search hit; a backend fills the fields it has and leaves the rest empty.

type Space

type Space struct {
	// Name identifies the space among its siblings; the agent sees it with
	// Desc. Names are reduced to ASCII letters, digits and _ (runs of other
	// characters become one _); a sibling rendered later with the same
	// reduced name replaces the earlier one. Give it at least one letter or
	// digit: a name without one is replaced and a warning is logged. An empty
	// name fails the render.
	Name string
	// Desc tells the agent what the region is and what it is for.
	Desc string
}

Space marks a region of the page for the agent: the tools, inputs, data, islands and spaces rendered inside it belong to it. Wrap the region's markup with it:

~>neui.Space{Name: "cart", Desc: "the user's shopping cart"} <section>...</section>

Content rendered outside any Space belongs to the page root. A space lives as long as its render: when that part of the page re-renders or unmounts, the space and everything in it go away.

func (Space) Proxy

func (s Space) Proxy(cur gox.Cursor, el gox.Elem) error

Proxy renders el inside the space. It fails when the enclosing render has already ended.

type Task

type Task = common.Task

Task is a background task registered with ToolTask. Ok or Err delivers its final result and ends it. Notify delivers an interim record while the task keeps running; it is dropped once the task has finished.

func ToolTask

func ToolTask(ctx context.Context, comment string, attrs map[string]any, cancel context.CancelCauseFunc) (Task, error)

ToolTask registers a background task for the calling tool; the tool usually returns at once and the task delivers its result later through the returned Task. comment is a short description shown to the user while the task runs and stored with its result; attrs become the task's meta, nil meaning none. cancel is what a chat UI calls through api.Task.Cancel to stop the task (nekit.Chat passes api.ErrCanceledByUser), and the cause it receives is what the task should report with Err; the runtime calls it with ErrCanceledByUser when the round that started the task is rewound, and the work must also stop when ToolThreadContext ends; cancel must not be nil. Run the work on ToolThreadContext, not the call's ctx, which ends with the call. Call it before the tool returns: it fails with context.Canceled when the thread is closed, with an error when cancel is nil or the round of tool calls it belongs to has ended, and with an error when the tool was called from a script (ToolFromJS), since scripts cannot start background tasks. It panics when ctx comes from neither a tool call nor ToolThreadContext.

type Tool

type Tool[I any, O any] struct {
	// Name is the tool's name. Names are reduced to ASCII letters, digits
	// and _ (runs of other characters become one _); names that reduce to
	// the same value replace each other, and a name must keep at least one
	// letter or digit.
	Name string
	// Desc tells the agent what the tool does and when to call it; the
	// output schema is appended to it.
	Desc string
	// Handler runs the call with the input decoded from JSON into I; the
	// input and output schemas the agent sees come from I and O. On a direct
	// agent call to a module tool, a string or fmt.Stringer result reaches
	// the agent as text, an api content value as itself and anything else as
	// JSON; a script gets the result as JSON, and so does the agent from a
	// page tool, together with what the call changed on the page. An error
	// fails the call with its message as text; when it is or wraps an
	// api.Container or api.MultiContainer, that content goes with it, as JSON
	// to a script or from a page tool. ctx works with the Tool* functions;
	// for a tool rendered on a page it is also a doors context of that
	// render, so the handler can update the page, and it runs once the page
	// has settled.
	Handler func(ctx context.Context, i I) (O, error)
}

Tool defines a tool. Add it to a Module or a Library, or render it to add it to the page space it is rendered in.

func (Tool[I, O]) Main

func (a Tool[I, O]) Main() gox.Elem

Main adds the tool to the space it is rendered in, for as long as that render lives, replacing a tool of the same name there. It renders nothing; the render fails when I or O has no JSON schema.

type ToolID

type ToolID = tools.ToolID

ToolID identifies a tool within its own module, for Remove. An ID is only meaningful to the module that issued it.

type Tooler

type Tooler interface {
	// contains filtered or unexported methods
}

Tooler is a tool definition: a Tool or an Ask. The same value can be added to a Module and, for a Tool, to an island Library or rendered on a page.

type Use

type Use struct {
	// Desc tells the agent what the element does or holds.
	Desc string
	// Rights limits what the agent may do with it. Default RW.
	Rights Rights
}

Use exposes one interactive element to the agent in the enclosing space, so it can read, fill or click it as the user would. Wrap exactly one element:

~>neui.Use{Desc: "delete this contact"} <button>Delete</button>

Supported tags are button, a, input, textarea and select; an input of type submit, button, reset or image counts as a button, and a radio stands for its whole same-name group. The input goes away with its render.

Give the inputs of a space distinct descriptions. Inputs with the same type, name and static value (a button's or checkbox's value, a link's href) are told apart only by Desc; when two cannot be told apart, the agent's call on them fails and the error is logged.

When the agent clicks or writes the element, the page briefly marks it with an overlay of class neui-act plus neui-act-click or neui-act-write; style those classes to restyle the cue.

func (Use) Proxy

func (u Use) Proxy(cur gox.Cursor, el gox.Elem) error

Proxy renders el and registers its element. When el does not start with a supported element, or the element is already wrapped by another Use, it logs the error and renders el unregistered.

type WebConfig

type WebConfig struct {
	// HTTPClient is the client every fetch uses. The default client refuses,
	// at connect time and on every redirect hop, any address IANA marks not
	// globally reachable (loopback, private, link-local including cloud
	// metadata, CGNAT, documentation, benchmarking, multicast, reserved,
	// IPv6 outside 2000::/3, 6to4, Teredo) and any address of the host's own
	// network interfaces, judges NAT64 64:ff9b::/96 by the IPv4 address
	// inside it, refuses the ports the WHATWG Fetch standard bars, ignores
	// HTTP_PROXY/HTTPS_PROXY because a proxy hides the real destination, caps
	// redirects at 10, allows only http/https per hop and strips
	// credentials. Passing a client replaces all of it; behind a
	// mandatory proxy, pass a client that uses it and let that proxy enforce
	// destination policy. Leave Timeout at zero: the module bounds each fetch
	// with a context deadline.
	HTTPClient *http.Client
	// Search is the search backend behind web__search. Nil registers no
	// search tool.
	Search SearchBackend
	// UserAgent is the honest identification of this module: what a fetch
	// retries with after a bot wall answers the browser User-Agent with a
	// challenge. Default "neui/0.1 (+https://neui.dev)".
	UserAgent string
	// MaxBytes caps one response body, aborted mid-stream. Default 5<<20.
	MaxBytes int64
	// Timeout bounds a fetch the agent sets no timeout for, and every search.
	// Default 30s; a value above MaxTimeout is lowered to it.
	Timeout time.Duration
	// MaxTimeout caps the timeout the agent sets for a fetch, and Timeout.
	// Default 120s.
	MaxTimeout time.Duration
	// CacheTTL is how long a converted page stays pageable without a second
	// request. Default 15m.
	CacheTTL time.Duration
	// CacheBytes caps the converted text held per thread. Default 8<<20; a
	// value below twice MaxBytes is raised to it, so with the default MaxBytes
	// the cap is 10<<20.
	CacheBytes int64
	// SearchChars caps the page content of each search result on its own,
	// in characters; a result cut there ends with "… (content truncated)".
	// Default 2000.
	SearchChars int
}

WebConfig tunes the web module; a zero field takes its default.

type XLSConfig

type XLSConfig struct {
	// MaxFileSize is the largest workbook file on disk, in bytes, the module
	// opens; a larger one is refused. Default 50 MiB.
	MaxFileSize int64
	// MaxUnzipSize caps the uncompressed contents of a workbook in bytes; a
	// workbook that expands past it, or holds a part over 1 MiB compressed
	// more than 100x, is refused. Default 1 GiB.
	MaxUnzipSize int64
	// MaxReadRows caps the rows returned, or matches collected, by one call;
	// it also caps the rows profile reads to guess column types. Default 200.
	MaxReadRows uint
}

XLSConfig tunes the xls module; a zero field takes its default.

Directories

Path Synopsis
Package api holds the contracts shared by hosts, providers and storages.
Package api holds the contracts shared by hosts, providers and storages.
examples
internal
devkit
Package devkit runs an island app from a script, with no agent in the loop, for development: Go tests drive it with a headless browser, and a program under cmd/ serves it to try widgets by hand.
Package devkit runs an island app from a script, with no agent in the loop, for development: Go tests drive it with a headless browser, and a program under cmd/ serves it to try widgets by hand.
precheck
Package precheck finds what would surely fail in a part of an island script before it runs.
Package precheck finds what would surely fail in a part of an island script before it runs.
Package nekit is the ready-made chat widget for neui.
Package nekit is the ready-made chat widget for neui.
internal/chat/css
Package css holds the nechat stylesheet and its theme overrides.
Package css holds the nechat stylesheet and its theme overrides.
internal/chat/params
Package params carries nekit chat settings through the widget's components.
Package params carries nekit chat settings through the widget's components.
provider
claude
Package claude is the api.Provider for Anthropic's Messages API.
Package claude is the api.Provider for Anthropic's Messages API.
deepseek
Package deepseek is the api.Provider for DeepSeek's Chat Completions API.
Package deepseek is the api.Provider for DeepSeek's Chat Completions API.
gpt
Package gpt is the OpenAI provider for neui.
Package gpt is the OpenAI provider for neui.
lib
Package lib holds the parts of a Provider that do not depend on which API answered: reading a server sent event stream, keeping a deadline on one, and handing a caller events while the wire keeps moving.
Package lib holds the parts of a Provider that do not depend on which API answered: reading a server sent event stream, keeping a deadline on one, and handing a caller events while the wire keeps moving.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL