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 ¶
- func Disable(ctx context.Context)
- func Enable(ctx context.Context, opts ...Option) error
- func Instance(ctx context.Context) api.Instance
- func IslandDir(ctx context.Context) string
- func IslandFS(ctx context.Context) api.FS
- func IslandID(ctx context.Context) string
- func IslandReport(ctx context.Context, err error)
- func IslandScope(ctx context.Context) doors.Scopes
- func IslandStore(ctx context.Context) doors.Store
- func ToolConfig(ctx context.Context) api.ThreadConfig
- func ToolFS(ctx context.Context) api.FS
- func ToolFilesConfig(ctx context.Context) api.FilesConfig
- func ToolFromAgent(ctx context.Context) bool
- func ToolFromJS(ctx context.Context) bool
- func ToolModel(ctx context.Context) api.Model
- func ToolThreadContext(ctx context.Context) context.Context
- func ToolThreadID(ctx context.Context) api.ThreadID
- func WithFilesConfig(c api.FilesConfig) doors.With
- func WithIslandConfig(c api.IslandConfig) doors.With
- func WithJSConfig(c JSConfig) doors.With
- func WithModules(m ...ModuleFactory) doors.With
- func WithProvider(p api.Provider) doors.With
- func WithSystemPrompt(prompt ...string) doors.With
- func WithThreadConfig(c api.ThreadConfig) doors.With
- func WithUploadStorage(s api.UploadStorage) doors.With
- type Answer
- type AnyModule
- type AnyTool
- type Ask
- type Data
- type Island
- type IslandCall
- type JSConfig
- type Library
- func (l Library) Add(t Tooler) error
- func (l Library) Control[I any, U any, O any](name string, desc string, ...) error
- func (l Library) Head(e ...gox.Elem)
- func (l Library) Layout[I any](name string, desc string, f func(i I, children []gox.Comp) gox.Comp) error
- func (l Library) Tool[I any, O any](name string, desc string, f func(ctx context.Context, input I) (O, error)) error
- func (l Library) View[I any, U any](name string, desc string, ...) error
- type MCPConfig
- type Module
- func (m Module) Add(t Tooler) (ToolID, error)
- func (m Module) Ask[I any, O any](name string, desc string, f func(input I, answer Answer[O]) api.ChatAsk) (ToolID, error)
- func (m Module) Desc() string
- func (m Module) Get(name string) (AnyTool, bool)
- func (m Module) List() []AnyTool
- func (m Module) Name() string
- func (m Module) Remove(id ToolID)
- func (m Module) Tool[I any, O any](name string, desc string, f func(ctx context.Context, input I) (O, error)) (ToolID, error)
- type ModuleFactory
- type Option
- func OptionFilesConfig(c api.FilesConfig) Option
- func OptionForce() Option
- func OptionMessageStorage(s api.MessageStorage) Option
- func OptionModules(m ...ModuleFactory) Option
- func OptionProvider(p api.Provider) Option
- func OptionSystemPrompt(prompt ...string) Option
- func OptionUploadStorage(s api.UploadStorage) Option
- type Rights
- type SearchBackend
- type SearchQuery
- type SearchResult
- type Space
- type Task
- type Tool
- type ToolID
- type Tooler
- type Use
- type WebConfig
- type XLSConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Disable ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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.
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.
type IslandCall ¶
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 ¶
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 as a tool to its app child space, 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 ¶
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 ¶
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 ¶
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) Get ¶
Get returns the tool with that name, sanitized as NewModule does, and whether there is one.
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 ¶
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 ¶
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 ¶
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 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.
type 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.
type 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.
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
|
|
|
business-systems/backoffice
command
|
|
|
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. |
|
testkit/conform/fetchspec
command
|
|
|
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 api.Provider for OpenAI's Responses API.
|
Package gpt is the api.Provider for OpenAI's Responses API. |
|
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. |