sdk

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 3 Imported by: 0

README

Luminarys Go SDK

Go SDK for building Luminarys WASM skills.

Installation

go mod init my-company/my-skill
# Add to go.mod:
# require github.com/LuminarysAI/sdk-go v0.1.0

Quick Start

package main

import sdk "github.com/LuminarysAI/sdk-go"

// @skill:id      com.my-company.my-skill
// @skill:name    "My Skill"
// @skill:version 1.0.0
// @skill:desc    "My first skill."

// @skill:method greet "Greet by name."
// @skill:param  name required "User name"
// @skill:result "Greeting text"
func Greet(ctx *sdk.Context, name string) (string, error) {
    return "Hello, " + name + "!", nil
}

Build:

lmsk genkey                            # once: create developer signing key
lmsk generate -lang go .              # generate main.go
GOOS=wasip1 GOARCH=wasm go build -buildmode=c-shared -o my-skill.wasm .
lmsk sign my-skill.wasm               # → com.my-company.my-skill.skill

Alternatively, you can use TinyGo for smaller binaries:

tinygo build -target=wasip1 -o my-skill.wasm .
lmsk sign my-skill.wasm

Documentation

luminarys.ai

Tools

Download lmsk from releases.

License

MIT

Documentation

Overview

Package sdk provides the Go SDK for writing WASM skills. Skills compile with: GOOS=wasip1 GOARCH=wasm go build -o dist/skill.wasm ./

Index

Constants

View Source
const (
	SDKVersionMajor = 0
	SDKVersionMinor = 2
	SDKVersionPatch = 0
	SDKVersion      = (SDKVersionMajor << 16) | (SDKVersionMinor << 8) | SDKVersionPatch
)

SDK version packed as uint32.

View Source
const (
	PermOwnerRead  uint32 = 0400
	PermOwnerWrite uint32 = 0200
	PermOwnerExec  uint32 = 0100
	PermGroupRead  uint32 = 0040
	PermGroupWrite uint32 = 0020
	PermGroupExec  uint32 = 0010
	PermOtherRead  uint32 = 0004
	PermOtherWrite uint32 = 0002
	PermOtherExec  uint32 = 0001

	PermReadOnly   uint32 = 0444 // r--r--r--
	PermDefault    uint32 = 0644 // rw-r--r--
	PermDefaultDir uint32 = 0755 // rwxr-xr-x
	PermPrivate    uint32 = 0600 // rw-------
	PermPrivateDir uint32 = 0700 // rwx------
)

Permission bit constants.

View Source
const (
	LogLevelDebug = "debug"
	LogLevelInfo  = "info"
	LogLevelWarn  = "warn"
	LogLevelError = "error"
)
View Source
const (
	WsMessageText   = "text"
	WsMessageBinary = "binary"
	WsMessageClose  = "close"
)
View Source
const Version = 1

Version is the protocol version. Must be incremented on breaking changes.

Variables

This section is empty.

Functions

func FileTransferRecv

func FileTransferRecv(sourceNode, remotePath, localPath string) error

FileTransferRecv requests a file from a remote cluster node (pull mode).

func FileTransferSend

func FileTransferSend(targetNode, localPath, remotePath string) error

FileTransferSend sends a local file to a remote cluster node.

func FsChmod

func FsChmod(path string, mode uint32, recursive bool) error

FsChmod changes file permissions. Requires fs.enabled.

mode is the permission bits (e.g. 0o755 = 493). Use PermXxx constants.

func FsCopy

func FsCopy(source, dest string) error

FsCopy copies a file. Both paths must be within allowed directories. Requires fs.enabled.

func FsCreate

func FsCreate(path string, content []byte) error

FsCreate creates a new file. Fails if the file already exists. Requires fs.enabled.

func FsDelete

func FsDelete(path string) error

FsDelete deletes a file or directory. Requires fs.enabled.

func FsMkdir

func FsMkdir(path string) error

FsMkdir creates a directory (with parents, like mkdir -p). Requires fs.enabled.

Supports brace expansion: "logs/{2024,2025}" creates two directories.

func FsRead

func FsRead(path string) ([]byte, error)

FsRead reads a file and returns its contents as bytes. Requires fs.enabled.

func FsWrite

func FsWrite(path string, content []byte) error

FsWrite writes content to a file, replacing it entirely. Requires fs.enabled.

func GetEnv

func GetEnv(key string) string

GetEnv reads a named value declared in the skill's manifest under env.

func Log

func Log(level, message string, fields map[string]any)

Log writes a structured log message.

func LogDebug

func LogDebug(message string, fields map[string]any)

LogDebug is a shorthand for Log("debug", ...).

func LogError

func LogError(message string, fields map[string]any)

LogError is a shorthand for Log("error", ...).

func LogInfo

func LogInfo(message string, fields map[string]any)

LogInfo is a shorthand for Log("info", ...).

func LogWarn

func LogWarn(message string, fields map[string]any)

LogWarn is a shorthand for Log("warn", ...).

func MarshalErrorResponse

func MarshalErrorResponse(msg string) []byte

MarshalErrorResponse encodes an error-only InvokeResponse.

func MarshalState

func MarshalState(schemaVersion int, state interface{}) ([]byte, error)

MarshalState encodes skill state into a versioned envelope.

func Register

func Register(h Handler, methods ...MethodInfo)

Register sets the skill's dispatch handler and appends method descriptors. Safe to call multiple times from different init() functions — each call appends its methods and, if h is non-nil, sets the handler.

The generated skill_gen.go calls this once with _skillDispatch and the generated method list. You do not need to call it again unless you need to replace the top-level handler.

func RegisterMethods

func RegisterMethods(methods ...MethodInfo)

RegisterMethods appends method descriptors and, if a method carries a Handle(...) handler, registers it for dispatch — without touching the generated _skillDispatch or _skillHandlers.

This is the primary extension point for hand-written methods:

func init() {
    sdk.RegisterMethods(
        sdk.Method("debug_dump", "Dump internal state.").
            SetInternal().
            Handle(func(req sdk.InvokeRequest) sdk.InvokeResponse {
                // ...
            }),
    )
}

func RegisterRequirements

func RegisterRequirements(reqs ...RequirementInfo)

RegisterRequirements appends requirement descriptors for the skill. Called by generated init() code.

func SetSkillIdentity

func SetSkillIdentity(id, name, version, description string)

SetSkillIdentity sets the skill's identity metadata. Called by generated init() code from @skill:id, @skill:name, etc.

func ShrinkResultBuf added in v0.2.0

func ShrinkResultBuf(ptr uint32)

ShrinkResultBuf releases the persistent result buffer. Called by the generated skill_free when the host signals it has read the result.

func TcpClose

func TcpClose(connID string) error

TcpClose closes the connection. Idempotent.

func TcpConnect

func TcpConnect(opts TcpConnectOptions) (string, error)

TcpConnect dials a TCP connection (plain or TLS). Requires tcp.enabled.

func TcpSetCallback

func TcpSetCallback(connID, callback string) error

TcpSetCallback updates the read callback for an existing connection.

func TcpWrite

func TcpWrite(connID string, data []byte) error

TcpWrite sends data over an existing connection.

func UnmarshalState

func UnmarshalState(raw []byte, dst interface{}) (schemaVersion int, err error)

UnmarshalState decodes the versioned envelope and populates dst. Returns the schema version so callers can run migrations if needed.

func WriteResult

func WriteResult(b []byte) uint64

WriteResult stores b in a GC-safe buffer and returns (ptr<<32 | len).

func WsClose

func WsClose(connID string, code int, reason string) error

WsClose sends a Close frame and removes the connection.

func WsConnect

func WsConnect(url string, headers []Header, timeoutMs int64, callback string, insecure bool) (string, error)

WsConnect dials a WebSocket connection. Requires http.enabled and http.allow_websocket.

func WsSend

func WsSend(connID string, data []byte, messageType string) error

WsSend sends a message over an existing WebSocket connection.

Types

type ABIError

type ABIError struct {
	Msg string
}

ABIError wraps an error string returned from an SDK call.

func (*ABIError) Error

func (e *ABIError) Error() string

type AllowedDir

type AllowedDir struct {
	// Path is the absolute directory path.
	Path string `msgpack:"path"`
	// Mode is "ro" (read-only) or "rw" (read-write).
	Mode string `msgpack:"mode"`
}

AllowedDir describes one directory the skill can access.

func FsAllowedDirs

func FsAllowedDirs() ([]AllowedDir, error)

FsAllowedDirs returns the directories this skill can access. Requires fs.enabled.

type ArchiveListEntry

type ArchiveListEntry struct {
	Name  string `msgpack:"name"`
	Size  int64  `msgpack:"size"`
	IsDir bool   `msgpack:"is_dir"`
}

ArchiveListEntry is one entry in an archive listing.

func ArchiveList

func ArchiveList(archivePath, format, exclude string) ([]ArchiveListEntry, error)

ArchiveList lists the contents of a tar.gz or zip archive.

type ArchivePackResult

type ArchivePackResult struct {
	FilesCount int    `msgpack:"files_count"`
	Format     string `msgpack:"format"`
	Error      string `msgpack:"error,omitempty"`
}

ArchivePackResult is the response from ArchivePack.

func ArchivePack

func ArchivePack(source, output, format, exclude string) (ArchivePackResult, error)

ArchivePack creates a tar.gz or zip archive from a directory.

type ArchiveUnpackResult added in v0.2.0

type ArchiveUnpackResult struct {
	FilesCount int    `msgpack:"files_count"`
	Error      string `msgpack:"error,omitempty"`
}

ArchiveUnpackResult is the response from ArchiveUnpack.

func ArchiveUnpack

func ArchiveUnpack(archive, dest, format, exclude string, strip int) (ArchiveUnpackResult, error)

ArchiveUnpack extracts a tar.gz or zip archive to a directory.

type BatchInvokePayload

type BatchInvokePayload struct {
	Items       []BatchItem `msgpack:"items"`
	Callback    string      `msgpack:"callback"`
	Concurrency int         `msgpack:"concurrency"` // 0 = unlimited
}

BatchInvokePayload is the payload map for a CmdBatchInvoke Command. Use BatchInvokeCommand() to construct it correctly.

type BatchItem

type BatchItem struct {
	// Index is the caller-assigned position; preserved in BatchResult.Items.
	Index   int    `msgpack:"index"`
	SkillID string `msgpack:"skill_id"`
	Method  string `msgpack:"method"`
	// Payload is the msgpack-encoded arguments for the method.
	Payload []byte `msgpack:"payload"`
}

BatchItem is one call inside a batch_invoke command.

type BatchItemResult

type BatchItemResult struct {
	Index   int    `msgpack:"index"`
	Payload []byte `msgpack:"payload,omitempty"`
	// Error is the skill-level error string, or "" on success.
	Error string `msgpack:"error,omitempty"`
}

BatchItemResult holds the outcome of one BatchItem after execution.

type BatchResult

type BatchResult struct {
	// BatchID is a unique ID for this batch execution (generated by the host).
	BatchID string            `msgpack:"batch_id"`
	Items   []BatchItemResult `msgpack:"items"`
}

BatchResult is delivered to the callback method declared in batch_invoke.

func UnmarshalBatchResult

func UnmarshalBatchResult(payload []byte) (*BatchResult, error)

UnmarshalBatchResult decodes a batch callback payload into a BatchResult.

type ClusterNodeInfo

type ClusterNodeInfo struct {
	NodeID string   `msgpack:"node_id"`
	Role   string   `msgpack:"role"`
	Skills []string `msgpack:"skills"`
}

ClusterNodeInfo describes a cluster node.

type ClusterNodeListResult

type ClusterNodeListResult struct {
	CurrentNode string            `msgpack:"current_node"`
	Nodes       []ClusterNodeInfo `msgpack:"nodes"`
	Error       string            `msgpack:"error,omitempty"`
}

ClusterNodeListResult is the response from ClusterNodeList.

func ClusterNodeList

func ClusterNodeList() (ClusterNodeListResult, error)

ClusterNodeList returns the list of known cluster nodes.

type Command

type Command struct {
	Type    CommandType            `msgpack:"type"`
	Payload map[string]interface{} `msgpack:"payload,omitempty"`
}

Command is an instruction returned by the skill to the platform.

func BatchInvokeCommand

func BatchInvokeCommand(items []BatchItem, callback string, concurrency int) Command

BatchInvokeCommand builds a batch_invoke Command ready to include in InvokeResponse.Commands.

return sdk.InvokeResponse{
    Commands: []sdk.Command{
        sdk.BatchInvokeCommand([]sdk.BatchItem{
            {Index: 0, SkillID: "fs-skill", Method: "read", Payload: p0},
            {Index: 1, SkillID: "fs-skill", Method: "read", Payload: p1},
        }, "on_batch_result", 0),
    },
}

func NewCallModule

func NewCallModule(skillID, method string, payload interface{}, callback, callCtx string) Command

NewCallModule creates a command that invokes another skill.

func NewEmitEvent

func NewEmitEvent(topic string, payload interface{}) Command

NewEmitEvent creates a command that publishes an event to the MessageBus.

func NewLoadKV

func NewLoadKV(key, callback string) Command

NewLoadKV creates a command to load a value from the Shared KV (L3).

func NewSchedule

func NewSchedule(method string, delayMs int64, payload interface{}) Command

NewSchedule creates a command to schedule a delayed method invocation.

func NewStoreKV

func NewStoreKV(key string, value interface{}) Command

NewStoreKV creates a command to store a value in the Shared KV (L3).

type CommandType

type CommandType string

CommandType enumerates the command types the platform understands.

const (
	CmdCallModule  CommandType = "call_module"
	CmdBatchInvoke CommandType = "batch_invoke"
	CmdSchedule    CommandType = "schedule"
	CmdEmitEvent   CommandType = "emit_event"
	CmdSubscribe   CommandType = "subscribe"
	CmdStoreKV     CommandType = "store_kv"
	CmdLoadKV      CommandType = "load_kv"
	CmdSpawn       CommandType = "spawn"
	CmdTerminate   CommandType = "terminate"
)

type ConnEvent

type ConnEvent struct {
	ConnID    string    `msgpack:"conn_id"`
	Data      []byte    `msgpack:"data,omitempty"`
	ErrorKind ErrorKind `msgpack:"error_kind,omitempty"`
	ErrorMsg  string    `msgpack:"error_msg,omitempty"`
}

ConnEvent is the payload delivered to the skill's read callback.

func UnmarshalConnEvent

func UnmarshalConnEvent(payload []byte) (ConnEvent, error)

UnmarshalConnEvent deserialises a ConnEvent from raw bytes.

type Context

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

Context is passed to every skill handler. Provides read access to invocation metadata and write access to response annotations.

func NewContext

func NewContext(req *InvokeRequest, res *InvokeResponse) *Context

NewContext creates a Context bound to the given request and response.

func (*Context) AppendLLMContext

func (c *Context) AppendLLMContext(text string)

AppendLLMContext appends text to any existing LLMContext, separated by "\n".

func (*Context) CallerID

func (c *Context) CallerID() string

CallerID returns the skill ID of the caller when invoked via call_module.

func (*Context) LLMSessionID

func (c *Context) LLMSessionID() string

LLMSessionID returns the LLM session ID.

func (*Context) Method

func (c *Context) Method() string

Method returns the method name being invoked.

func (*Context) RequestID

func (c *Context) RequestID() string

RequestID returns the unique ID of this invocation.

func (*Context) SessionID

func (c *Context) SessionID() string

SessionID returns the user session ID.

func (*Context) SetLLMContext

func (c *Context) SetLLMContext(text string)

SetLLMContext sets additional text appended to the tool result for the LLM.

func (*Context) SkillID

func (c *Context) SkillID() string

SkillID returns the ID of the skill being invoked.

func (*Context) TraceID

func (c *Context) TraceID() string

TraceID returns the distributed trace ID.

type Cookie struct {
	Name     string `msgpack:"name"`
	Value    string `msgpack:"value"`
	Domain   string `msgpack:"domain,omitempty"`
	Path     string `msgpack:"path,omitempty"`
	Expires  int64  `msgpack:"expires,omitempty"` // Unix timestamp; 0 = session
	Secure   bool   `msgpack:"secure,omitempty"`
	HTTPOnly bool   `msgpack:"httponly,omitempty"`
}

Cookie represents an HTTP cookie.

type DirEntry

type DirEntry struct {
	// Name is the file or directory name.
	Name string `msgpack:"name"`
	// Size in bytes (0 for directories).
	Size int64 `msgpack:"size"`
	// IsDir is true for directories.
	IsDir bool `msgpack:"is_dir"`
	// ModTime is the Unix timestamp in seconds. Only populated when long=true.
	ModTime int64 `msgpack:"mod_time,omitempty"`
	// Mode is the permission bits (e.g. 493 = 0o755). Only populated when long=true.
	Mode uint32 `msgpack:"mode,omitempty"`
	// ModeStr is human-readable permissions, e.g. "drwxr-xr-x". Only populated when long=true.
	ModeStr string `msgpack:"mode_str,omitempty"`
}

DirEntry represents one entry returned by FsLs.

func FsLs

func FsLs(path string, long bool) ([]DirEntry, error)

FsLs lists directory contents. Requires fs.enabled.

When long is true, ModTime, Mode, and ModeStr are populated for each entry.

type DiskUsageResult

type DiskUsageResult struct {
	TotalBytes int64   `msgpack:"total_bytes"`
	FreeBytes  int64   `msgpack:"free_bytes"`
	UsedBytes  int64   `msgpack:"used_bytes"`
	UsedPct    float64 `msgpack:"used_pct"`
	Error      string  `msgpack:"error,omitempty"`
}

DiskUsageResult holds disk space information.

func DiskUsage

func DiskUsage(path string) (DiskUsageResult, error)

DiskUsage returns disk space information for the given path. Requires fs.enabled.

type ErrorKind

type ErrorKind string

ErrorKind classifies a TCP connection error.

const (
	ErrorKindNone    ErrorKind = ""
	ErrorKindEOF     ErrorKind = "eof"
	ErrorKindReset   ErrorKind = "reset"
	ErrorKindTimeout ErrorKind = "timeout"
	ErrorKindTLS     ErrorKind = "tls"
	ErrorKindIO      ErrorKind = "io"
)

type FSChmodRequest

type FSChmodRequest struct {
	Path      string `msgpack:"path"`
	Mode      uint32 `msgpack:"mode"`
	Recursive bool   `msgpack:"recursive"`
}

type FSLsRequest

type FSLsRequest struct {
	Path string `msgpack:"path"`
	Long bool   `msgpack:"long"`
}

type FSLsResponse

type FSLsResponse struct {
	Entries []DirEntry `msgpack:"entries"`
	Error   string     `msgpack:"error,omitempty"`
}

type FSMkdirRequest

type FSMkdirRequest struct {
	Path string `msgpack:"path"`
}

type FSReadLinesRequest

type FSReadLinesRequest struct {
	// Path is the file path. Required.
	Path string `msgpack:"path"`
	// Offset is the 0-based start line.
	Offset int `msgpack:"offset"`
	// Limit is the max lines to return (0 = all).
	Limit int `msgpack:"limit"`
}

FSReadLinesRequest configures FsReadLines.

type FSRequest

type FSRequest struct {
	Path    string `msgpack:"path"`
	Content []byte `msgpack:"content,omitempty"`
}

type FSResponse

type FSResponse struct {
	Content []byte `msgpack:"content,omitempty"`
	Error   string `msgpack:"error,omitempty"`
}

type GlobEntry

type GlobEntry struct {
	Path  string `msgpack:"path"`
	IsDir bool   `msgpack:"is_dir"`
}

GlobEntry is one result from FsGlob.

func FsGlob

func FsGlob(opts GlobOptions) ([]GlobEntry, error)

FsGlob finds files matching glob patterns. Requires fs.enabled.

type GlobOptions

type GlobOptions struct {
	// Patterns is a list of glob patterns (union). Supports *, **, ?, [abc], {a,b}.
	Patterns []string `msgpack:"patterns"`
	// Path is the base directory. Empty = all allowed directories.
	Path        string   `msgpack:"path"`
	MatchHidden bool     `msgpack:"match_hidden"`
	IgnoreDirs  []string `msgpack:"ignore_dirs"`
	MaxDepth    int      `msgpack:"max_depth"`
	OnlyFiles   bool     `msgpack:"only_files"`
	OnlyDirs    bool     `msgpack:"only_dirs"`
}

GlobOptions configures FsGlob.

type GrepFileMatch

type GrepFileMatch struct {
	Path    string          `msgpack:"path"`
	Matches []GrepLineMatch `msgpack:"matches"`
}

GrepFileMatch holds all matches in one file.

func FsGrep

func FsGrep(opts GrepOptions) ([]GrepFileMatch, error)

FsGrep searches file contents by regex pattern. Requires fs.enabled.

type GrepLineMatch

type GrepLineMatch struct {
	LineNum int         `msgpack:"line_num"`
	Line    string      `msgpack:"line,omitempty"`
	Ranges  []GrepRange `msgpack:"ranges,omitempty"`
}

GrepLineMatch is one matching line.

type GrepOptions

type GrepOptions struct {
	// Pattern is a regex (or literal when Fixed=true).
	Pattern string `msgpack:"pattern"`
	// Path to search. Empty = all allowed directories.
	Path            string   `msgpack:"path"`
	Fixed           bool     `msgpack:"fixed"`
	CaseInsensitive bool     `msgpack:"case_insensitive"`
	MaxDepth        int      `msgpack:"max_depth"`
	MaxCount        int      `msgpack:"max_count"`
	Workers         int      `msgpack:"workers"`
	TypeFilter      string   `msgpack:"type_filter"`
	Include         []string `msgpack:"include"`
	Exclude         []string `msgpack:"exclude"`
	IgnoreDirs      []string `msgpack:"ignore_dirs"`
	WithLines       bool     `msgpack:"with_lines"`
	FilenameOnly    bool     `msgpack:"filename_only"`
}

GrepOptions configures FsGrep.

type GrepRange

type GrepRange struct {
	Start int `msgpack:"start"`
	End   int `msgpack:"end"`
}

GrepRange is a [Start, End) byte offset within a line.

type Handler

type Handler func(req InvokeRequest) InvokeResponse

Handler is the function signature every skill must implement.

type Header struct {
	Name  string `msgpack:"name"`
	Value string `msgpack:"value"`
}

Header is an ordered HTTP header name/value pair.

func HeadersFromJSON added in v0.2.0

func HeadersFromJSON(jsonStr string) []Header

HeadersFromJSON parses a JSON object string into an ordered Header slice. Preserves key insertion order from the source string.

type HistoryMessage

type HistoryMessage struct {
	Role    string `msgpack:"role"`
	Content string `msgpack:"content"`
}

HistoryMessage is one entry from the dialogue history.

func HistoryGet

func HistoryGet(filter string) ([]HistoryMessage, error)

HistoryGet fetches dialogue history matching the given filter.

type HttpRequestOptions

type HttpRequestOptions struct {
	Method          string // defaults to "GET"
	URL             string
	Headers         []Header // applied in listed order
	Cookies         []Cookie
	Body            []byte
	TimeoutMs       int64
	MaxBytes        int // 0 = manifest limit (1 MiB default)
	FollowRedirects bool
	UseJar          bool // enable the persistent per-skill cookie jar
}

HttpRequestOptions configures a fully customised HTTP request.

type HttpResponse

type HttpResponse struct {
	Status    int      `msgpack:"status"`
	Headers   []Header `msgpack:"headers,omitempty"`
	Cookies   []Cookie `msgpack:"cookies,omitempty"`
	Body      []byte   `msgpack:"body,omitempty"`
	Truncated bool     `msgpack:"truncated,omitempty"`
}

HttpResponse is the response returned by all HTTP calls.

func HttpGet

func HttpGet(url string, timeoutMs int64, maxBytes int) (HttpResponse, error)

HttpGet performs a GET request. Requires http.enabled.

timeoutMs=0 uses 30 s default. maxBytes=0 uses the manifest limit (or 1 MiB default).

func HttpPost

func HttpPost(url string, body []byte, contentType string, timeoutMs int64, maxBytes int) (HttpResponse, error)

HttpPost performs a POST request. Requires http.enabled.

contentType defaults to "application/octet-stream" if empty.

func HttpRequest

func HttpRequest(opts HttpRequestOptions) (HttpResponse, error)

HttpRequest performs a fully customised HTTP request with ordered headers, persistent cookie jar, and full control over method, redirects and body. Requires http.enabled.

type InvokeRequest

type InvokeRequest struct {
	Version      int    `msgpack:"version"`
	RequestID    string `msgpack:"request_id"`
	TraceID      string `msgpack:"trace_id"`
	SessionID    string `msgpack:"session_id"`
	LLMSessionID string `msgpack:"llm_session_id"`
	Method       string `msgpack:"method"`
	SkillID      string `msgpack:"skill_id"`
	CallerID     string `msgpack:"caller_id,omitempty"` // skill ID if called by another skill
	State        []byte `msgpack:"state"`
	Payload      []byte `msgpack:"payload"`
	DeadlineNs   int64  `msgpack:"deadline_ns"`
}

InvokeRequest represents an incoming skill invocation.

type InvokeResponse

type InvokeResponse struct {
	Version  int       `msgpack:"version"`
	State    []byte    `msgpack:"state"`
	Payload  []byte    `msgpack:"payload"`
	Error    string    `msgpack:"error,omitempty"`
	Commands []Command `msgpack:"commands,omitempty"`
	// LLMContext is optional extra text sent to the LLM alongside the tool result.
	// Set via ctx.SetLLMContext("...") in the handler.
	// The host appends it to the MCP response as additional context.
	LLMContext string `msgpack:"llm_context,omitempty"`
}

InvokeResponse is returned by the skill's handle() function.

func CallHandler

func CallHandler(req InvokeRequest) InvokeResponse

CallHandler dispatches an InvokeRequest to the registered handler. Extra handlers registered via RegisterMethods(...).Handle(...) take priority over the generated _skillDispatch.

type MethodInfo

type MethodInfo struct {
	Name        string      `msgpack:"name"`
	Description string      `msgpack:"description"`
	Params      []ParamInfo `msgpack:"params,omitempty"`
	// MCPHidden marks the method as hidden from MCP tools/list.
	// Hidden methods remain callable by other skills via call_module.
	// Set via @skill:internal annotation (codegen) or .SetInternal() builder.
	MCPHidden bool `msgpack:"mcp_hidden,omitempty"`
	// PrivateCallback marks the method as a private callback.
	// Private callbacks are ONLY callable by the skill itself (host enforces this).
	// Use for TCP/HTTP/WS read callbacks — they should never be invoked by
	// other skills. Set via @skill:callback annotation or .Callback() builder.
	PrivateCallback bool `msgpack:"private_callback,omitempty"`
	// contains filtered or unexported fields
}

MethodInfo describes a single exported method including its parameter schema.

func Method

func Method(name, description string) MethodInfo

Method starts building a MethodInfo with a fluent builder.

func (MethodInfo) Callback

func (m MethodInfo) Callback() MethodInfo

Callback marks the method as a private callback. Private callbacks are hidden from MCP AND are only callable by the skill that owns them — other skills cannot invoke them via call_module.

Use for all TCP/HTTP/WebSocket read callbacks:

sdk.Method("on_data", "Receives TCP data").Callback()

func (MethodInfo) Handle

func (m MethodInfo) Handle(fn Handler) MethodInfo

Handle attaches an inline handler function to this method descriptor. When the method is registered via RegisterMethods, the SDK dispatches incoming calls to this function — no changes to the generated files needed.

sdk.RegisterMethods(
    sdk.Method("debug_dump", "Dump internal state.").
        SetInternal().
        Handle(func(req sdk.InvokeRequest) sdk.InvokeResponse {
            payload, _ := msgpack.Marshal(map[string]int{"conns": len(activeConns)})
            return sdk.InvokeResponse{Payload: payload}
        }),
)

func (MethodInfo) Param

func (m MethodInfo) Param(name string, p ParamInfo) MethodInfo

Param adds a parameter descriptor to the method.

func (MethodInfo) SetInternal

func (m MethodInfo) SetInternal() MethodInfo

SetInternal marks the method as hidden from MCP tools/list. The method remains callable by other skills via call_module.

type ParamInfo

type ParamInfo struct {
	Name        string      `msgpack:"name"`
	Description string      `msgpack:"description,omitempty"`
	TypeVal     string      `msgpack:"type"`
	IsRequired  bool        `msgpack:"required,omitempty"`
	EnumVals    []string    `msgpack:"enum,omitempty"`
	Items       *ParamInfo  `msgpack:"items,omitempty"`
	DefaultVal  interface{} `msgpack:"default,omitempty"`
	ExampleVal  interface{} `msgpack:"example,omitempty"`
}

ParamInfo describes one parameter of a method.

func TypeArray

func TypeArray(items ParamInfo) ParamInfo

TypeArray creates an array parameter with the given item type:

sdk.TypeArray(sdk.TypeString())  →  array of strings

func TypeBool

func TypeBool() ParamInfo

func TypeInt

func TypeInt() ParamInfo

func TypeNumber

func TypeNumber() ParamInfo

func TypeObject

func TypeObject() ParamInfo

func TypeString

func TypeString() ParamInfo

func (ParamInfo) Default

func (p ParamInfo) Default(v interface{}) ParamInfo

Default sets the default value shown in documentation.

func (ParamInfo) Desc

func (p ParamInfo) Desc(d string) ParamInfo

Desc sets the human-readable description.

func (ParamInfo) Enum

func (p ParamInfo) Enum(values ...string) ParamInfo

Enum restricts accepted values to the given set.

func (ParamInfo) Example

func (p ParamInfo) Example(v interface{}) ParamInfo

Example sets an illustrative example value.

func (ParamInfo) Required

func (p ParamInfo) Required() ParamInfo

Required marks the parameter as required.

type PromptRequest

type PromptRequest struct {
	Prompt      string  `msgpack:"prompt"`
	Temperature float64 `msgpack:"temperature"`
	MaxTokens   int     `msgpack:"max_tokens"`
}

PromptRequest is sent to the host's prompt_complete ABI function.

type PromptResponse

type PromptResponse struct {
	Content string `msgpack:"content"`
	Error   string `msgpack:"error,omitempty"`
}

PromptResponse is returned from the host's prompt_complete ABI function.

func PromptComplete

func PromptComplete(req PromptRequest) (PromptResponse, error)

PromptComplete sends a prompt to the LLM.

type RequirementInfo

type RequirementInfo struct {
	Kind    string `msgpack:"kind"`              // "fs", "http", "tcp", "ws", "shell", "llm", "env", "invoke"
	Pattern string `msgpack:"pattern,omitempty"` // glob, URL, command, env name, skill ID
	Mode    string `msgpack:"mode,omitempty"`    // "ro" or "rw" (fs only)
}

RequirementInfo declares one permission the skill expects from its manifest. Populated by codegen from @skill:require annotations.

type ShellExecRequest

type ShellExecRequest struct {
	// Command is the shell command to execute (required).
	Command string `msgpack:"command"`
	// Workdir is the working directory. Defaults to sandbox root.
	Workdir string `msgpack:"workdir"`
	// TimeoutMs is the command timeout in milliseconds. 0 = 30s default.
	TimeoutMs int `msgpack:"timeout_ms"`
	// Tail returns only the last N lines of output. 0 = all lines.
	Tail int `msgpack:"tail"`
	// Grep filters output lines by regex pattern.
	Grep string `msgpack:"grep"`
	// AsDaemon starts the process in background and returns immediately with PID.
	AsDaemon bool `msgpack:"as_daemon"`
	// LogFile is the output file for daemon mode.
	LogFile string `msgpack:"log_file,omitempty"`
}

ShellExecRequest is the request for ShellExec. Requires shell.enabled.

type ShellExecResult

type ShellExecResult struct {
	Output   string `msgpack:"output"`
	ExitCode int    `msgpack:"exit_code"`
	Pid      int    `msgpack:"pid,omitempty"`
	LogFile  string `msgpack:"log_file,omitempty"`
	Error    string `msgpack:"error,omitempty"`
}

ShellExecResult is the response from ShellExec.

func ShellExec

func ShellExec(req ShellExecRequest) (ShellExecResult, error)

ShellExec executes a shell command and returns combined output and exit code. Requires shell.enabled.

type SkillDescriptor

type SkillDescriptor struct {
	Version      int               `msgpack:"version"`
	SkillID      string            `msgpack:"skill_id,omitempty"`
	SkillName    string            `msgpack:"skill_name,omitempty"`
	SkillVersion string            `msgpack:"skill_version,omitempty"`
	Description  string            `msgpack:"description,omitempty"`
	Methods      []MethodInfo      `msgpack:"methods"`
	Requirements []RequirementInfo `msgpack:"requirements,omitempty"`
	// SDKVersionCode is the SDK version packed as uint32.
	SDKVersionCode uint32 `msgpack:"sdk_version,omitempty"`
}

SkillDescriptor describes the skill's identity, methods, and requirements.

func GetDescriptor

func GetDescriptor() SkillDescriptor

GetDescriptor returns the SkillDescriptor for the registered skill.

type StateEnvelope

type StateEnvelope struct {
	SchemaVersion int    `msgpack:"schema_version"`
	Data          []byte `msgpack:"data"`
}

StateEnvelope wraps any skill state with a schema version.

type SysInfoResult

type SysInfoResult struct {
	OS       string `msgpack:"os"`
	Arch     string `msgpack:"arch"`
	Hostname string `msgpack:"hostname"`
	NumCPU   int    `msgpack:"num_cpu"`
}

SysInfoResult holds host OS and hardware information.

func SysInfo

func SysInfo() (SysInfoResult, error)

SysInfo returns information about the host OS and hardware.

type TcpConnectOptions added in v0.2.0

type TcpConnectOptions struct {
	// Host:port to connect to (required).
	Addr string `msgpack:"addr"`
	// Callback method name called with ConnEvent on reads. "" = drain silently.
	Callback string `msgpack:"callback"`
	// TLS enables TLS encryption.
	TLS bool `msgpack:"tls"`
	// Insecure skips TLS certificate verification (dev only).
	Insecure bool `msgpack:"insecure"`
	// ServerName overrides the TLS SNI hostname.
	ServerName string `msgpack:"server_name,omitempty"`
	// TimeoutMs is the dial timeout in milliseconds. 0 = 30s default.
	TimeoutMs int64 `msgpack:"timeout_ms"`
}

TcpConnectOptions configures a persistent TCP connection. Requires tcp.enabled.

type TcpRequestOptions

type TcpRequestOptions struct {
	// Host:port to connect to (required).
	Addr string `msgpack:"addr"`
	// Data is the payload to send (required).
	Data []byte `msgpack:"data"`
	// TLS enables TLS for the connection.
	TLS bool `msgpack:"tls"`
	// Insecure skips TLS certificate verification (dev only).
	Insecure bool `msgpack:"insecure"`
	// TimeoutMs is the total timeout for connect+send+read. 0 = 30s.
	TimeoutMs int `msgpack:"timeout_ms"`
	// MaxBytes limits the response size. 0 = 1MB.
	MaxBytes int `msgpack:"max_bytes"`
}

TcpRequestOptions configures a synchronous TCP request. Requires tcp.enabled.

type TcpRequestResult

type TcpRequestResult struct {
	Data  []byte `msgpack:"data"`
	Error string `msgpack:"error,omitempty"`
}

TcpRequestResult holds the response from TcpRequest.

func TcpRequest

func TcpRequest(opts TcpRequestOptions) (TcpRequestResult, error)

TcpRequest performs a synchronous TCP request: connect, send, read, close. Requires tcp.enabled.

type TextFileContent

type TextFileContent struct {
	Lines       []string `msgpack:"lines"`
	TotalLines  int      `msgpack:"total_lines"`
	Offset      int      `msgpack:"offset"`
	IsTruncated bool     `msgpack:"is_truncated"`
}

TextFileContent is the result of FsReadLines.

func FsReadLines

func FsReadLines(req FSReadLinesRequest) (TextFileContent, error)

FsReadLines reads a range of lines from a text file. Requires fs.enabled.

Offset is 0-based. Limit 0 means all remaining lines.

type TimeNowResult

type TimeNowResult struct {
	Unix      int64  `msgpack:"unix"`
	UnixNano  int64  `msgpack:"unix_nano"`
	RFC3339   string `msgpack:"rfc3339"`
	Timezone  string `msgpack:"timezone"`
	UTCOffset int    `msgpack:"utc_offset"`
}

TimeNowResult holds the current host time.

func TimeNow

func TimeNow() (TimeNowResult, error)

TimeNow returns the current host time.

type WsEvent

type WsEvent struct {
	ConnID      string    `msgpack:"conn_id"`
	Data        []byte    `msgpack:"data,omitempty"`
	MessageType string    `msgpack:"message_type,omitempty"` // "text"|"binary"|"close"
	CloseCode   int       `msgpack:"close_code,omitempty"`
	CloseText   string    `msgpack:"close_text,omitempty"`
	ErrorKind   ErrorKind `msgpack:"error_kind,omitempty"`
	ErrorMsg    string    `msgpack:"error_msg,omitempty"`
}

WsEvent is the payload delivered to the skill's WebSocket callback.

func UnmarshalWsEvent

func UnmarshalWsEvent(payload []byte) (WsEvent, error)

UnmarshalWsEvent deserialises a WsEvent from raw bytes.

Jump to

Keyboard shortcuts

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