action

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OPTIONS_PREFIX            = "options-"
	OPTIONS_PREFIX_UNDERSCORE = "options_"
)
View Source
const (
	SourceUI  = ""
	SourceAPI = "api"
	SourceCLI = "cli"
	SourceMCP = "mcp"
)

Audit operation prefixes, one per surface. The audit operation is <source>_execute|suggest|validate, the form UI uses the bare names

View Source
const API_PATH = "/api"

API_PATH is the path under the app path which is reserved for the actions REST API. Action apps cannot define an action at this path

View Source
const (

	// AuditOpRunFinish is the audit operation of the completion event of an
	// async run
	AuditOpRunFinish = "run_finish"
)
View Source
const MCPConfirmKey = "confirm"

MCPConfirmKey is the input request id of the confirmation

View Source
const MCPDeclinedStatus = "declined by the user, no changes were made"

MCPDeclinedStatus is the status of a declined confirmation

Variables

View Source
var ErrFileTooLarge = errors.New("file is larger than the size limit")

ErrFileTooLarge is the FileFetcher error for a file over the size limit. The file has not been consumed: a single access file can still be fetched

View Source
var ErrRunNotFound = errors.New("run not found")

ErrRunNotFound is returned by run lookups for an unknown id

Functions

func AuditOp added in v0.20.0

func AuditOp(source string, op Op) string

AuditOp returns the audit operation name for an op on a surface

func BuildAPIRouter added in v0.19.4

func BuildAPIRouter(appName, appPath string, actions []*Action) *chi.Mux

BuildAPIRouter creates the router for the actions REST API. Each action gets exec/suggest/validate endpoints under the per operation prefixes, in addition to the app level action list and OpenAPI spec endpoints

func BuildMCPHandler added in v0.20.0

func BuildMCPHandler(appName string, listTTL time.Duration, actions []*Action) (http.Handler, error)

BuildMCPHandler creates the Streamable HTTP handler serving the actions as MCP tools. listTTL is the freshness hint of the tool list

func DecodeResult added in v0.20.0

func DecodeResult(run *types.ActionRun, limit int) (valuesMap []map[string]any, valuesStr []string, err error)

DecodeResult decodes a stored result document into the values the result renderers take, limited to the first limit rows when limit is positive

func Defs added in v0.20.0

func Defs(actions []*Action) []types.ActionDef

Defs returns the definitions of the actions as persisted in the app metadata

func MCPConfirmAnswer added in v0.20.0

func MCPConfirmAnswer(req *mcp.CallToolRequest) (answered, accepted bool)

MCPConfirmAnswer reports whether the call carries the answer to the confirmation (the retry) and whether the user accepted

func MCPConfirmRequest added in v0.20.0

func MCPConfirmRequest(message string) *mcp.CallToolResult

MCPConfirmRequest is the input_required result asking the user to confirm

func MCPConfirmSupported added in v0.20.0

func MCPConfirmSupported(req *mcp.CallToolRequest) bool

MCPConfirmSupported reports whether the calling client can complete a confirmation round trip in stateless mode: protocol 2026-07-28 or later (the input_required retry is client-driven; older clients would need the server-side live elicitation bridge, which stateless mode cannot serve) and a declared form elicitation capability, the mode the confirmation uses. An elicitation capability naming no mode means form (the shape of clients before modes existed); a client naming url only cannot answer a form and runs at once, as a client without elicitation does. In stateless mode the SDK fills the initialize params from the _meta of each request

func MCPDeclinedResult added in v0.20.0

func MCPDeclinedResult() *mcp.CallToolResult

MCPDeclinedResult is the result of a declined confirmation: not an error, nothing ran

func MCPListTTLOf added in v0.20.0

func MCPListTTLOf(config types.ActionConfig) (time.Duration, error)

MCPListTTLOf returns the freshness hint of the tool list from the app config (action.mcp_list_ttl), the default when unset

func OpenAPISpec added in v0.20.0

func OpenAPISpec(ctx context.Context, appName, appPath string, actions []*Action) (map[string]any, error)

OpenAPISpec generates the OpenAPI 3.0 spec for the app actions. Only the actions the caller (the identity in ctx) is authorized for are included, the param definitions and defaults of restricted actions are not disclosed

func RunDeferredCleanup

func RunDeferredCleanup(thread *starlark.Thread) error

func ToolNames added in v0.20.0

func ToolNames(actions []*Action) map[*Action]string

ToolNames returns a unique tool name for each action: the name an action is selected by in the CLI, the MCP tool name and the name in the OpenAPI operation ids (run_<name>, validate_<name>, ...). The name is derived from the action path (/orders/cancel is orders_cancel), the action at the root path takes the slug of its action name instead (Cancel Order is cancel_order), no caller should have to type "root". Colliding names get a numeric suffix, chosen so it does not clash with the name of any other action either

func ToolNamesOfDefs added in v0.20.0

func ToolNamesOfDefs(defs []types.ActionDef) []string

ToolNamesOfDefs is ToolNames for the action definitions persisted in the app metadata: the same names, in the order of the definitions

func WriteRunOutput added in v0.20.0

func WriteRunOutput(w http.ResponseWriter, run *types.ActionRun, since int64)

WriteRunOutput writes the output window of a run as plain text with the continuation headers

Types

type Action

type Action struct {
	*types.Logger

	AppTemplate *template.Template
	StyleType   types.StyleType
	LightTheme  string
	DarkTheme   string

	Links []ActionLink // links to other actions
	// contains filtered or unexported fields
}

Action represents a single action that is exposed by the App. Actions provide a way to trigger app operations, with an auto-generated form UI and an API interface

func FindAction added in v0.20.0

func FindAction(actions []*Action, selector string) (*Action, error)

FindAction resolves an action selector: a tool name (cancel_order) or an action path (/cancel). An empty selector selects the only action of a single action app

func NewAction

func NewAction(logger *types.Logger, sourceFS *appfs.SourceFs, isDev bool, name, description, appName, apath string, run, suggest starlark.Callable,
	params []apptype.AppParam, paramValuesStr map[string]string, paramDict starlark.StringDict,
	appPath string, styleType types.StyleType, containerProxyUrl string, hidden []string, showValidate bool,
	auditInsert func(*types.AuditEvent) error, containerManager any, jsLibs []types.JSLibrary, appPathDomain types.AppPathDomain,
	serverConfig *types.ServerConfig, actionConfig types.ActionConfig, permit []string, rbacApi rbac.RBACAPI,
	async bool, timeout string) (*Action, error)

NewAction creates a new action

func (*Action) APIResult added in v0.20.0

func (a *Action) APIResult(o *Outcome, isValidate bool) (map[string]any, int)

APIResult builds the JSON response document and the http status for a run or validate outcome. Param validation errors are reported with a 422 status

func (*Action) Authorized added in v0.20.0

func (a *Action) Authorized(ctx context.Context) (bool, error)

Authorized reports whether the caller has access to the action, as per the action's permit list

func (*Action) BuildRouter

func (a *Action) BuildRouter() (*chi.Mux, error)

func (*Action) CancelRun added in v0.20.0

func (a *Action) CancelRun(ctx context.Context, runId string) (*types.ActionRun, *InvokeError)

CancelRun cancels an active run of this action executing on this node

func (*Action) Description added in v0.20.0

func (a *Action) Description() string

Description returns the action description

func (a *Action) GetLink() ActionLink

func (*Action) HasParam added in v0.20.0

func (a *Action) HasParam(name string) bool

HasParam reports whether the action has a visible param with the name

func (*Action) HasRequiredFileParam added in v0.20.0

func (a *Action) HasRequiredFileParam() bool

HasRequiredFileParam reports whether the action has a required file upload param, such an action cannot be called with a JSON args document

func (*Action) HasSuggest added in v0.20.0

func (a *Action) HasSuggest() bool

HasSuggest reports whether the action has a suggest handler

func (*Action) Hints added in v0.20.0

func (a *Action) Hints() *types.ActionHints

Hints returns the side-effect hints declared with ace.action, nil when the action declares none

func (*Action) InputJSONSchema added in v0.20.0

func (a *Action) InputJSONSchema(skipFiles bool) (map[string]any, error)

InputJSONSchema returns the JSON schema of the args object for the action: the request body schema in the OpenAPI spec and the MCP tool input schema. File upload params cannot be carried in a JSON document, they are left out when skipFiles is set (MCP)

func (*Action) Invoke added in v0.20.0

func (a *Action) Invoke(ctx context.Context, inv Invocation) (*Outcome, *InvokeError)

Invoke authorizes the caller against the permit list and calls the action

func (*Action) IsAsync added in v0.20.0

func (a *Action) IsAsync() bool

IsAsync reports whether the action runs in the background (is_async=True)

func (*Action) IsDestructive added in v0.20.0

func (a *Action) IsDestructive() bool

IsDestructive reports whether the action declares destructive=True: the MCP tools ask capable clients to confirm before running it, the form shows a badge

func (*Action) ListRuns added in v0.20.0

func (a *Action) ListRuns(ctx context.Context, status string, before types.ActionRunCursor, limit int) ([]types.ActionRun, error)

ListRuns lists this action's runs, newest first; before continues a listing (keyset paging)

func (*Action) LoadRun added in v0.20.0

func (a *Action) LoadRun(ctx context.Context, runId string, payload bool) (*types.ActionRun, error)

LoadRun returns a run of this action (a run of another action or app is not found here), with the payload when asked

func (*Action) MCPConfirmMessage added in v0.20.0

func (a *Action) MCPConfirmMessage(args map[string]jsontext.Value, previewStatus string) string

MCPConfirmMessage builds the confirmation prompt of an action: the action, its app and description, the args as name=value lines (password params hidden) and the status the validate pass reported

func (*Action) MCPResult added in v0.20.0

func (a *Action) MCPResult(ctx context.Context, o *Outcome, op Op, progress func(chunk string)) *mcp.CallToolResult

MCPResult builds the tool result for an outcome: the structured content for programs and a text block written for a model. A stream result is consumed to completion, progress (optional) receives the output as it arrives and is called with an empty chunk at the end to flush

func (*Action) MaxWait added in v0.20.0

func (a *Action) MaxWait(wait time.Duration) time.Duration

MaxWait caps a wait requested by a run read API

func (*Action) Name added in v0.20.0

func (a *Action) Name() string

Name returns the action name

func (*Action) Path added in v0.20.0

func (a *Action) Path() string

Path returns the action path within the app

func (*Action) Permit added in v0.20.0

func (a *Action) Permit() []string

Permit returns the custom permissions of which the caller needs one, empty when the action is not restricted

func (*Action) ResolveResultURL added in v0.20.0

func (a *Action) ResolveResultURL(rawURL string) (local string, external bool, err error)

ResolveResultURL resolves the url of a result row the way a browser showing the action page does: a relative url is relative to the action page. local is the server path (with the query) when the url is within the app; a url with a host, or one which resolves outside the app path, is external

func (*Action) ResultDocument added in v0.20.0

func (a *Action) ResultDocument(ctx context.Context, o *Outcome, op Op, progress func(chunk string)) (map[string]any, string, bool)

ResultDocument returns the result of an outcome as a document (status, report, values, param_errors; output and exit_status for a stream), its rendering as text for a model, and whether the result is an error the caller can act on (param errors, a failed command)

func (*Action) RunAPIResult added in v0.20.0

func (a *Action) RunAPIResult(run *types.ActionRun) map[string]any

RunAPIResult is the run document of the REST and management APIs: the run without the payload columns, plus the decoded result of a finished values run in the ActionResult shape

func (*Action) RunDocument added in v0.20.0

func (a *Action) RunDocument(run *types.ActionRun, checkWith string) (map[string]any, string, bool)

RunDocument returns a run as a document: run_id, run_status and the run fields, plus the result document of a finished run. checkWith names the tool a client polls the run with, for the text of a running run

func (*Action) RunMCPResult added in v0.20.0

func (a *Action) RunMCPResult(ctx context.Context, run *types.ActionRun, checkWith string) *mcp.CallToolResult

RunMCPResult builds the tool result for a run: the run document and a text block; a finished values run renders as the action's result would, a stream run as its output tail

func (*Action) RunPagePath added in v0.20.0

func (a *Action) RunPagePath(runId string) string

RunPagePath returns the path of a run's page in the action UI

func (*Action) RunStarted added in v0.20.0

func (a *Action) RunStarted(run *types.ActionRun) types.ActionRunStarted

RunStarted is the API response for a started run

func (*Action) RunStore added in v0.20.0

func (a *Action) RunStore() RunStore

RunStore returns the store async runs are recorded in, nil when the action has no run host

func (*Action) Schema added in v0.20.0

func (a *Action) Schema() (*ActionSchema, error)

Schema returns the param definitions for an action. Hidden params and the options params are not included. The caller is expected to have checked Authorized, the definitions and defaults of restricted actions are not to be disclosed

func (*Action) SetConfigSource added in v0.20.0

func (a *Action) SetConfigSource(source func() *types.ServerConfig)

SetConfigSource sets the accessor of the effective server config, for the settings which change dynamically (the MCP confirmation switch)

func (*Action) SetFileFetcher added in v0.20.0

func (a *Action) SetFileFetcher(fetcher FileFetcher)

SetFileFetcher sets the fetcher used to inline result files (MCP)

func (*Action) SetHints added in v0.20.0

func (a *Action) SetHints(hints *types.ActionHints)

SetHints sets the side-effect hints declared with ace.action

func (*Action) SetRunHost added in v0.20.0

func (a *Action) SetRunHost(host *RunHost)

SetRunHost sets the run services; async actions cannot start runs without them

func (*Action) SuggestResult added in v0.20.0

func (a *Action) SuggestResult(retVal starlark.Value) (map[string]any, *InvokeError)

SuggestResult builds the JSON response document for a suggest handler response. The response params are filtered the same way as the form UI suggest handling

func (*Action) Timeout added in v0.20.0

func (a *Action) Timeout() time.Duration

Timeout returns the async run timeout

func (*Action) WaitRun added in v0.20.0

func (a *Action) WaitRun(ctx context.Context, runId string, wait time.Duration, payload bool) (*types.ActionRun, error)

WaitRun returns the run, waiting up to wait (capped by the app config) for it to end

func (*Action) WriteStreamText added in v0.20.0

func (a *Action) WriteStreamText(w http.ResponseWriter, r *http.Request, outcome *Outcome)

writeStreamText streams a result as chunked plain text: the API mode response (curl -N friendly) and the fallback for non-HTMX form posts. The result status text travels in the OpenRun-Action-Status header and the exit status in the OpenRun-Exit-Status trailer; a missing trailer means the stream was cut (a read failure or a client disconnect). No synthetic lines are mixed into the output

type ActionLink struct {
	Name       string
	Path       string
	Permits    []string
	Authorized bool
	Active     bool // whether this link is the currently shown action
}

type ActionSchema added in v0.20.0

type ActionSchema struct {
	Name        string              `json:"name"`
	Description string              `json:"description"`
	Params      []types.ActionParam `json:"params"`
	Suggest     bool                `json:"suggest"`
}

ActionSchema has the param definitions for an action

type Args

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

Args is a starlark.Value that represents the arguments being passed to the Action handler. It contains value for the params.

func NewArgs added in v0.19.4

func NewArgs(members starlark.StringDict) *Args

NewArgs builds an Args value from the given members

func (*Args) Attr

func (a *Args) Attr(name string) (starlark.Value, error)

func (*Args) AttrNames

func (a *Args) AttrNames() []string

func (*Args) Freeze

func (a *Args) Freeze()

func (*Args) Hash

func (a *Args) Hash() (uint32, error)

func (*Args) String

func (a *Args) String() string

func (*Args) Truth

func (a *Args) Truth() starlark.Bool

func (*Args) Type

func (a *Args) Type() string

type FetchedFile added in v0.20.0

type FetchedFile struct {
	Data     []byte
	MimeType string
}

FetchedFile is a file fetched from an app local url

type FileFetcher added in v0.20.0

type FileFetcher func(ctx context.Context, localURL string, limit int64) (*FetchedFile, error)

FileFetcher fetches an app local url (as returned by ResolveResultURL) through the app's router, as the identity in ctx. limit caps the file size

type Invocation added in v0.20.0

type Invocation struct {
	Op      Op
	AuditOp string // audit operation name, see AuditOp

	// JSONArgs are the arg values keyed by param name. Params not present
	// retain the app level param values. Used when IsForm is false
	JSONArgs map[string]jsontext.Value

	// IsForm selects form semantics: Form holds the submitted fields, a
	// boolean param missing from the form is false (unchecked checkbox) and a
	// missing file is the empty string
	IsForm bool
	Form   url.Values

	// Files are the uploads for file upload params, keyed by param name
	Files map[string]UploadedFile
}

Invocation is one call of an action

type InvokeError added in v0.20.0

type InvokeError struct {
	Code int
	Msg  string
}

InvokeError is a failed invocation, Code has the HTTP status semantics (400 bad args, 403 not permitted, 500 handler failure, 501 no suggest)

func (*InvokeError) Error added in v0.20.0

func (e *InvokeError) Error() string

type MCPTool added in v0.20.0

type MCPTool struct {
	Tool    *mcp.Tool
	Action  *Action
	Suggest bool // the tool runs the suggest handler
	// contains filtered or unexported fields
}

MCPTool is an action exposed as an MCP tool

func MCPTools added in v0.20.0

func MCPTools(actions []*Action) ([]*MCPTool, error)

MCPTools returns the MCP tools for the actions: a tool per action, named by ToolNames, plus a <tool>_suggest tool for the actions with a suggest handler. An action with a required file upload param cannot be called with a JSON args document and gets no tool

type Op added in v0.20.0

type Op int

Op is the operation to run on an action

const (
	OpRun      Op = iota // run the handler
	OpValidate           // run the handler with dry_run=True
	OpSuggest            // run the suggest handler
)

type Outcome added in v0.20.0

type Outcome struct {
	Status      string
	Report      string // report type as returned by the handler, can be AUTO
	ValuesStr   []string
	ValuesMap   []map[string]any
	ParamErrors map[string]any
	Suggest     starlark.Value   // the suggest handler response, for OpSuggest
	QueryParams url.Values       // non password form values, for the UI push url
	Run         *types.ActionRun // the started run of an async action; the other fields are unset
	// contains filtered or unexported fields
}

Outcome is the result of an invocation. Close must be called once the outcome has been rendered: it releases the stream, the uploaded files and writes the audit events

func (*Outcome) Close added in v0.20.0

func (o *Outcome) Close()

Close releases the resources of the invocation and records the audit events

func (*Outcome) ConsumeStream added in v0.20.0

func (o *Outcome) ConsumeStream(ctx context.Context, emit func(chunk string) error) (int, error)

ConsumeStream drains the result stream, passing each output chunk (with its trailing newline restored) to emit, and records the stream outcome for the audit event. It returns the command's exit status when the stream ended through a process exit (0 for a clean end without an exit error), or an error for a caller disconnect, an emit failure or a stream failure that is not an exit status

func (*Outcome) IsStream added in v0.20.0

func (o *Outcome) IsStream() bool

IsStream reports whether the handler returned a stream result

type OutputWindow added in v0.20.0

type OutputWindow struct {
	Output  string // the bytes, starting at Since
	Since   int64  // the offset the bytes start at
	Total   int64  // the bytes produced so far, the offset to continue from
	Omitted int64  // bytes not available between the head and the tail
	Restart bool   // the reader's offset was no longer available, the output restarts from the head
}

OutputWindow is the readable output of a run from an offset

func ReadOutput added in v0.20.0

func ReadOutput(run *types.ActionRun, since int64) OutputWindow

ReadOutput returns the output of a run from offset since: the head covers [0, len(head)), the tail covers [total-len(tail), total). An offset in the tail returns the tail from there; an offset in the head (or zero) returns the head, an omitted marker when bytes are missing, then the tail; an offset in the gap restarts from the head. An offset inside a multi byte rune is moved forward to the rune's end, so the window is valid text; Since reports the offset used

type ParamDef

type ParamDef struct {
	Name               string
	Description        string
	Value              any
	InputType          string
	Options            []string
	Strict             bool // dropdown value must be one of the options (default; COMBO display type loosens)
	DisplayType        string
	DisplayTypeOptions string
}

type ResultFile added in v0.20.0

type ResultFile struct {
	Name string
	URL  string
}

ResultFile is a file row of a DOWNLOAD or IMAGE result

func ResultFiles added in v0.20.0

func ResultFiles(valuesMap []map[string]any) []ResultFile

ResultFiles returns the files of a DOWNLOAD or IMAGE outcome: the rows which have a url

type RunHost added in v0.20.0

type RunHost struct {
	Store          RunStore
	Registry       *system.RunRegistry
	NodeId         string
	AppId          types.AppId
	AppPath        string // the app path domain
	Version        int
	Acquire        func() (release func(), err error)
	RecordActivity func()
}

RunHost is what an action needs from its app and the server to execute async runs: the store, the node's run registry, the identity of the app instance, and the app pin (Acquire keeps the app open for the run's lifetime: a reload or delete which closes the app defers the close until the run releases it)

type RunStore added in v0.20.0

type RunStore interface {
	CreateActionRun(ctx context.Context, run *types.ActionRun) error
	GetActionRun(ctx context.Context, id string, payload bool) (*types.ActionRun, error)
	ListActionRuns(ctx context.Context, appIds []types.AppId, actionPaths []string, status string, before types.ActionRunCursor, limit int) ([]types.ActionRun, error)
	UpdateActionRunLease(ctx context.Context, id string, leaseUntil time.Time) error
	UpdateActionRunOutput(ctx context.Context, id string, head *string, tail string, outputBytes, omittedBytes int64) error
	FinishActionRun(ctx context.Context, run *types.ActionRun) error
	PruneActionRuns(ctx context.Context, appId types.AppId, keep int) (int, error)
}

RunStore persists async runs; the metadata database implements it

type UploadedFile added in v0.20.0

type UploadedFile struct {
	Filename string
	Open     func() (io.ReadCloser, error)
}

UploadedFile is a file submitted for a file upload param

Jump to

Keyboard shortcuts

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