Skip to content

Latest commit

 

History

History
577 lines (508 loc) · 31.9 KB

README.md

File metadata and controls

577 lines (508 loc) · 31.9 KB

Lithe plugin backend SDK for Go

The Go module github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go, package lithe, is the official way to write a plugin backend in Go: the one long-lived process a plugin declares under backend in plugin.json, which Lithe starts on demand (a page's first call, a command, workspace open; see Backend lifecycle and workspace contexts). The backend is a packaged executable, so a plugin ships one archive per platform. It speaks the LSP base protocol on stdio and implements, from the plugin contract, which lives in this repository next to the SDK and changes with it:

  • litheFunctions: plugin functions with progress, cancellation, and registration at runtime, and the view functions that draw a plugin's tool windows and settings regions.
  • Host services: the plugin's own credentials, kept by the host in the platform's secret store, workspace contexts, files, documents, editors, preview, the browser, window messages, commands, native terminals, and subscriptions, and calls to the functions other plugins export, relayed by Core, with the Caller a function called that way sees.
  • litheKeymapImport: independently negotiated shortcut import providers reading only explicitly selected source snapshots.
  • litheLogging: typed diagnostics, required at initialization; see Logging.

It covers the same protocols as the Rust SDK, and the same Core end-to-end scenario checks both. The SDK owns the wire format, negotiation, cancellation, and error mapping; your code supplies only handlers. It uses only the Go standard library, runs every call on a goroutine of its own, and needs Go 1.27.4 or newer.

This SDK has no build provider or VCS provider API; write build providers with the Node.js or Java SDK, and VCS providers with the Node.js SDK.

What the Lithe desktop serves

The Lithe desktop declares backend and pluginFunctions (both version 0), so the function and host-service protocols below run there. It does not declare keymapImportProviders: a plugin whose manifest requires it is not offered for installation there, although the Core end-to-end tests still drive the protocol. Which host services a session may call is reported at run time; see Host services.

A minimal backend

"pluginAPIVersion": 0,
"requires": { "backend": 0, "ui": 0 },
"permissions": ["backend.launch", "credentials.store", "ui.contribute", "ui.web"],
"backend": { "launch": { "kind": "packaged", "path": "bin/backend" }, "arguments": ["--state", "${stateDir}"] }
package main

import (
	"encoding/json"
	"os"

	"github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe"
)

func main() {
	backend := lithe.NewBackend("example-backend").Version("1.0.0")
	err := backend.Function("connection.test", func(params json.RawMessage, call *lithe.Context) (any, error) {
		call.ProgressPercent("Connecting", 10)
		var input struct {
			Connection string `json:"connection"`
		}
		if json.Unmarshal(params, &input) != nil || input.Connection == "" {
			return nil, lithe.NewPluginError("example.invalidParams", `"connection" must be a string.`)
		}
		_, present, err := call.Credentials().Get("connection:" + input.Connection)
		if err != nil {
			return nil, err
		}
		if err := call.CheckCancelled(); err != nil {
			return nil, err
		}
		return map[string]any{"hasPassword": present}, nil
	})
	if err != nil {
		panic(err)
	}
	os.Exit(backend.Listen())
}

The page calls it through the host bridge, without an instance:

const { value } = await lithe.request('functions.invoke', { function: 'connection.test', params: { connection: 'main' } });

examples/sample-backend is a complete plugin: the manifest, a web page, notes kept in ${stateDir} with progress, a function registered at runtime, a secret in the credential store, cancellation, a watch on the page's workspace, a native terminal, a command answered with a message in its window, and a handler for workspace changes. From the root of this repository, node shared/plugins/scripts/sdk-e2e.mjs builds it and drives it through a real Core session with the scenario in sdk/e2e/plugin_sdk/backend.rs.

Build one executable per platform, without cgo so it needs nothing installed:

CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath -o package/bin/backend .
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath -o package/bin/backend.exe .

Plugin views

A tool window or settings region whose manifest entry has view: { function } is drawn by that backend function (Plugin views). Declare it with backend.View(id, handler). The handler gets a *lithe.ViewEvent: Kind, Instance, Surface, Language, the Effective and Draft setting values, and the fields of that event (Node, Canvas, Value, Setting, Item, Viewport, Width). Params that are not a view event fail the call with sdk.view.invalidEvent before the handler runs; an optional field that is null counts as absent. The handler answers a lithe.ViewResult:

  • lithe.View(nodes...): a whole view. The first answer after ViewOpen must be one.
  • lithe.Patches(patches...): edits to the view the host is drawing, built with PatchSet, PatchReplace, PatchRemove, and PatchInsert (placed with .Under, .At, .InTree, or .InCanvas).
  • lithe.Unchanged(): nothing changed. The SDK answers {}.

Nodes are any JSON-serializable values shaped as plugin-ui.schema.json describes. Core checks every answer, and the host draws nothing that Core refused. Return view text in event.Language. A host that reports the view's width sends it as event.Width on every event; a canvas that follows the window lays itself out at that width, lists resize in its on, and answers ViewResize with the scene laid out again (Canvas).

must(backend.View("explorer.draw", func(event *lithe.ViewEvent, _ *lithe.Context) (lithe.ViewResult, error) {
	switch {
	case event.Kind == lithe.ViewOpen:
		return lithe.View(map[string]any{"type": "row", "children": []any{
			map[string]any{"type": "label", "text": "Modules"},
			map[string]any{"type": "button", "id": "refresh", "text": "Refresh"},
		}}), nil
	case event.Kind == lithe.ViewClick && event.Node == "refresh":
		return lithe.Patches(lithe.PatchSet("refresh", map[string]any{"enabled": false})), nil
	}
	return lithe.Unchanged(), nil
}))

Shortcut import providers

Declare backend.KeymapImportProvider(id, handler) before listening. The host negotiates IDs independently of plugin functions; a handler receives a KeymapImportRequest and a call-scoped *Context. Use request.ListInputs(call.Host()) and request.ReadChunk(call.Host(), fileID, offset, maximumBytes) to read declared files in bounded chunks. KeymapSourceFile.Path is a relative label; the file ID is the authority. Return { "bindings": [...] } in the normalized contract format. The host cancels the call on import cancellation and revokes the snapshot when it ends. Do not convert conditional or multi-stroke rules into global bindings.

Getting the SDK

The SDK is a Go module in a subdirectory of this repository, so its versions are tags named shared/plugins/sdk/go/v<version>; the Go module proxy and checksum database serve it, and go.sum pins its exact contents:

go get github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go@v0.1.0

Until the first tag, name a commit of main instead of v0.1.0; Go records it as a pseudo-version. Fetch the module at build time, never at runtime; go mod vendor keeps a copy in your repository when your build must not reach the network.

Logging

The SDK requires experimental.litheLogging at initialization and refuses a host that does not offer it. See plugin logging for the typed diagnostics API, host-owned catalog, exact levels, operation correlation and ${logDir}. Use Diagnostics().Degraded and .Recovered for handled fallback or recovery facts. Function terminal facts are automatic; do not log a failure before returning it to the SDK. Suppress successful high-frequency reads with SuppressSuccessDiagnostics. There is no free-text log API, no stderr fallback and no plugin-owned file writer.

API

API Purpose
lithe.NewBackend(name).Version(version) Creates the backend; name and version are reported as serverInfo.
backend.Function(id, handler) Declares a function offered in initialize.
backend.View(id, handler) Declares a view function; see Plugin views.
backend.OnInitialize(hook) Runs before the initialize answer with an *Initialize: the host's Params(), FunctionsVersion() (0, true when the host offered litheFunctions), RootPath() (the plugin's ${stateDir}), and Function(id, handler) to add functions that depend on state found at startup. An error refuses initialize.
backend.OnShutdown(hook) Runs on shutdown, after running calls were cancelled.
backend.Handle() A *BackendHandle for other goroutines.
backend.Listen() Serves stdio until exit or the end of input and returns the exit code: 0 after shutdown and exit, 1 otherwise.
backend.Serve(input, output) The same on other streams, for tests.
handle.RegisterFunction(id, handler), handle.UnregisterFunction(id) Adds or withdraws a function after initialize and waits until the host accepted it. Withdrawing revokes and cancels running calls; a handler must not withdraw its own function.
handle.FunctionIDs(), handle.FunctionsVersion() What the backend serves, and 0, true when the host offered litheFunctions.
backend.OnCommand(id, handler) Runs func(commandID string, context *WorkspaceContext) error when the user runs one of the plugin's commands.
backend.OnContextsChanged(handler), backend.OnHostNotification(method, handler) Handle lithe/host/workspace/didChangeContexts and any other lithe/host/* notification a later host adds.
handle.Host(), call.Host() The host services. handle.Host() is bound to no call.
handle.Credentials(), call.Credentials() Shorthand for Host().Credentials().
lithe.NewPluginError(code, message) A failure meant for your own UI.

A handler is func(params json.RawMessage, call *lithe.Context) (any, error); params is {} when the host sent none. Its context offers:

Member Meaning
Cancellation() A *Cancellation, fired when Lithe cancels the call, its deadline passes, the function is withdrawn, or the session ends: IsCancelled(), Check(), Done(), Context() (a context.Context to pass to database drivers and HTTP clients), WaitTimeout(duration) (use it instead of time.Sleep), and OnCancel(callback).
CheckCancelled() lithe.ErrCancelled once cancelled.
Progress(message), ProgressPercent(message, percentage) The message is cut to 1024 bytes and the percentage clamped to 0–100; reports after the call ended are dropped.
Host() Host services bound to the call: a request still waiting for the host when the call is cancelled ends at once. Credentials() is Host().Credentials().
WorkspaceContext() The *WorkspaceContext of the window whose page made the call; nil when no window made it.
Caller() The *Caller (PluginID()) of the plugin whose backend called this function through Core's relay; nil when the host started the call and when the host's caller is not exactly { pluginID } with a non-empty string.
Backend(), FunctionID(), Diagnostics() The handle, the function's ID, and typed diagnostics correlated with this call.

Host services

A backend may ask the host for services; each is granted by a manifest permission and refused otherwise. They are available when the host offers litheFunctions in initialize; without it, host requests fail locally with plugin.host.unavailable and send nothing. Every method blocks its goroutine until the host answers and returns an error that is a *lithe.SdkError; wrong arguments fail locally and send nothing.

must(backend.Function("query.run", func(params json.RawMessage, call *lithe.Context) (any, error) {
	// Permission credentials.store: the platform's secret store, per plugin.
	password, present, err := call.Host().Credentials().Get("connection.prod:password")
	if err != nil {
		return nil, err
	}
	if !present {
		return nil, lithe.NewPluginError("query.noPassword", "Sign in first.")
	}
	// The window the page runs in.
	var folders json.RawMessage
	if workspace := call.WorkspaceContext(); workspace != nil {
		if ok, err := call.Host().Supports("lithe/host/workspace/getFolders"); err == nil && ok {
			if folders, err = call.Host().Workspace().GetFolders(*workspace); err != nil {
				return nil, err
			}
		}
	}
	return runQuery(params, password, folders)
}))

host := backend.Handle().Host()
must(backend.OnCommand("db.refresh", func(_ string, workspace *lithe.WorkspaceContext) error {
	if workspace == nil {
		return nil
	}
	_, err := host.Window().ShowInformation(*workspace, map[string]any{"text": "Refreshed."})
	return err
}))
Host member Purpose
Credentials().Get(key), .Set(key, secret), .Delete(key) Secrets in the platform's store; see Credentials.
Capabilities(), Supports(method) What this session may call, from lithe/host/getCapabilities (asked once).
Workspace().ListContexts(), .GetContext(context), .GetFolders(context) Workspace contexts; only GetContext returns, and creates, the context's stateDirectory.
Workspace().GetHostPaths(context, rootIDs...), .ProcessRoots(context) Root paths on the remote host of a remote context; see Remote workspaces.
Workspace().ReadDirectory, .Stat, .ReadFile, .FindFiles, .FindText, .Watch Files of a local context, addressed as { rootID, path } from GetFolders.
Documents().List, .GetSnapshot; Editor().GetActive, .GetSelections, .ApplyEdits, .ReplaceSelections, .InsertText, .Open, .Reveal, .RegisterActions Live documents and editors. Edits name the expectedVersion they were computed against.
Documents().Save, .SaveAs, .Close; Workspace().Create, .Rename, .Copy, .Trash Saves, closes, and file changes, with the documents.save and workspace.files.write permissions. Nothing is overwritten, discarded, or deleted permanently; see saving documents and changing files.
Preview().OpenHTML, Browser().OpenExternal, Window().ShowInformation, .ShowWarning, .ShowError Preview, browser, and messages.
Terminal().Create, .Show, .Close, .Reopen, .Dispose, .OnExit Native terminals; see Native terminal API.
Functions().Providers(functionID), .Invoke(context, call) The plugins that export a function, and a call to one of them; see Calling other plugins.
Request(method, params), Subscribe(method, params) Any lithe/host/* method, including ones a later host adds.
Subscriptions().Dispose(id) Ends a subscription; Subscription.Dispose() does the same.
WithCancellation(cancellation) The same services, cancelled together with cancellation.
Negotiated() true when the host offered litheFunctions in this session; false before initialize.

A host registers only the services it implements, and Capabilities() lists exactly those; call Supports(method) before depending on one of them. What the Lithe desktop does not register yet is listed under Capability versions.

Methods taking a workspace context take a WorkspaceContext: one from call.WorkspaceContext(), lithe.NewWorkspaceContext(id, generation), or lithe.ParseWorkspaceContext on a whole context from ListContexts. Their params are the contract's, without context, and they return the contract's result as json.RawMessage. The full params and results are in the contract.

What the SDK does for you, and what it leaves to you:

  • Refusals keep the host's code. Get the *lithe.SdkError with errors.As and branch on Code(), such as plugin.host.contextExpired; RPCCode() is the JSON-RPC number and Details() the host's object, if any. A code this SDK does not know is kept as sent. On versionConflict reread and recompute; on contextExpired resolve the original target again, never the focused window; retry busy and rateLimited (after the retryAfterMilliseconds detail) with a bound; permissionDenied and readOnly need the user, and so does diskChanged; on alreadyExists pick another target. An unknown param is plugin.host.unsupportedOption naming it in the option detail, so you can retry without it. lithe.HostErrorCodes lists the codes and numbers the contract defines.
  • Cancellation has no rollback. Cancelling the token given to WithCancellation, or ending the call whose call.Host() sent a request, fails it at once with sdk.call.cancelled; the SDK also sends $/cancelRequest so the host stops. An edit or an external open may already have taken effect, and the SDK never sends a request again.
  • At most 16 host requests are unanswered. Further ones wait in the SDK for a free slot instead of being refused.
  • Subscriptions route by ID. Workspace().Watch, Editor().RegisterActions, Terminal().OnExit, and Subscribe return a *Subscription; Recv() and RecvTimeout(duration) give each Event in order, with Sequence(), Event(), and Gap(), which is true when events were missed, so rescan. Events the host sends before its answer are kept. No event is delivered after Dispose() or the end of the session, not even one still queued: Recv() returns false and RecvTimeout returns lithe.ErrSubscriptionDisposed (lithe.ErrRecvTimeout when nothing arrived in time).
  • Commands are events. OnCommand runs on a goroutine of its own when the user runs one of the plugin's commands, with the window's *WorkspaceContext when the host sent one. The host waits for no result, and a failure is only logged. A stopped backend is started for it only when the manifest declares onCommand:<commandID>. Host notifications without a handler are ignored.

Credentials

A key is 1–128 ASCII letters, digits, ., _, :, or - (lithe.IsCredentialKey); a secret is at most 16 KiB. Credentials are private to your plugin ID, survive disabling and updating the plugin, and are deleted when it is uninstalled. They are never written to ${stateDir} or the package. Get returns "", false, nil when nothing is stored.

Failure (SdkError.Code()) Meaning
plugin.host.unavailable The host did not offer litheFunctions, so it has no host services. Nothing was sent.
plugin.host.permissionDenied The plugin lacks the credentials.store permission.
plugin.host.invalidParams, sdk.credentials.invalidKey, sdk.credentials.invalidSecret A malformed key or secret.
plugin.host.failed The host's secret store failed, for example a locked secret store; the message says why and never contains the secret.
sdk.call.cancelled The call was cancelled while waiting; returning it answers as cancelled.
sdk.session.notReady, sdk.session.closed The session has not finished initialize, or it ended while waiting.

Remote workspaces

A backend runs on the machine that runs Lithe also when the workspace is on a remote host. Such a context has authority.kind remote and authority.platform { os, arch }, and its folders carry no path. GetHostPaths gives their paths on the host. It needs the workspace.metadata permission, and only a host that serves it lists it, so check Supports("lithe/host/workspace/getHostPaths") first.

full, err := host.Workspace().GetContext(*workspace)
if err != nil {
	return nil, err
}
roots, err := host.Workspace().ProcessRoots(full)
if err != nil {
	return nil, err
}
for _, root := range roots {
	// A local root has Path; a remote one has HostPath.
	cwd := root.Path
	if cwd == "" {
		cwd = root.HostPath.String()
	}
	// ...
}
  • lithe.HostPath is its own type, so it is not passed to os, filepath or exec by mistake: the machine that runs the backend has no file there. Give String() only to what runs on the host, such as process arguments or a debug configuration; it marshals to JSON as that string.
  • ProcessRoots takes a full context. For a local one it reads the folders without asking the host; otherwise it calls GetHostPaths.
  • GetHostPaths without root IDs asks for every root; with them it takes 1–256 distinct root IDs, and others fail locally with sdk.host.invalidParams. An answer without absolute paths is sdk.host.invalidResult.
  • plugin.host.remoteDisconnected means the connection was lost while the request ran, so whether it took effect is unknown; plugin.host.platformUnavailable means the plugin has nothing for the host's platform. The remote workspaces guide says which services serve a remote context.

Calling other plugins

A backend may call a function another plugin exports; Core relays the call and the provider's backend never learns more than the call it serves. The manifest declares both sides: the caller lists { id, version } under pluginFunctions.calls, and the provider lists { id, version, context: "workspace" } under pluginFunctions.exports and registers the function with backend.Function(id, handler). See cross-plugin calls for the manifest, the order of Core's checks, and the call chain.

must(backend.Function("project.options", func(_ json.RawMessage, call *lithe.Context) (any, error) {
	workspace := call.WorkspaceContext()
	if workspace == nil {
		return nil, lithe.NewPluginError("example.noWorkspace", "Open a folder first.")
	}
	host := call.Host()
	if ok, err := host.Supports("lithe/host/functions/invoke"); err != nil || !ok {
		return map[string]any{"options": []any{}}, err
	}
	answer, err := host.Functions().Providers("project.describe")
	if err != nil {
		return nil, err
	}
	var providers struct {
		Providers []struct {
			PluginID string `json:"pluginID"`
		} `json:"providers"`
	}
	if json.Unmarshal(answer, &providers) != nil || len(providers.Providers) == 0 {
		return map[string]any{"options": []any{}}, nil
	}
	described, err := host.Functions().Invoke(*workspace, map[string]any{
		"pluginID":            providers.Providers[0].PluginID,
		"functionID":          "project.describe",
		"params":              map[string]any{"project": "app"},
		"timeoutMilliseconds": 5000,
	})
	if err != nil {
		return nil, err
	}
	return map[string]any{"options": described}, nil
}))

must(backend.Function("project.describe", func(params json.RawMessage, call *lithe.Context) (any, error) {
	// Core wrote the caller from the calling session; it cannot be forged.
	askedBy := ""
	if caller := call.Caller(); caller != nil {
		askedBy = caller.PluginID()
	}
	return map[string]any{"params": params, "askedBy": askedBy}, nil
}))
  • Check before calling. Supports("lithe/host/functions/invoke") and Supports("lithe/host/functions/providers") tell whether this session may call. Host services alone are not enough: a plugin that declares no calls gets plugin.host.permissionDenied. When the host did not offer litheFunctions, Providers, Invoke, and Host().Request with either method fail locally with plugin.host.unavailable and send nothing.
  • Providers(functionID) answers { "providers": [{ "pluginID", "version" }] }: the enabled plugins other than this one that export the function, sorted by plugin ID. This plugin must have declared the function, or the host answers plugin.function.notDeclared. A provider's backend need not be running.
  • Invoke(context, call) answers { "value": ... }, where value is the provider's result and may be null. context is a WorkspaceContext this backend learned from the workspace service or call.WorkspaceContext(); the relay accepts local workspaces only. call is an object (a map or a struct) with pluginID and functionID, and optionally params (an object, {} by default), timeoutMilliseconds (a positive integer; the host defaults it to 60000 and caps it at 600000, and the SDK does not clamp it), and parentOperationID. Any other key, such as context or caller, is not sent; the host would refuse it as plugin.host.unsupportedOption. A call that is not an object, lacks pluginID or functionID, or has a field of the wrong type fails locally with sdk.functions.invalidCall, and a functionID that is not a function ID does the same for Providers.
  • Limits are the host's. A chain has at most 4 calls and does not return to a plugin already on it (plugin.function.callCycle); a caller has at most 8 relayed calls running; params and a result are at most 256 KiB. A provider that is asked to apply values must not call the plugin that asked inside that call.
  • parentOperationID is filled in for you inside a handler. A call made with call.Host().Functions().Invoke(...) while a function runs names that call's operationID, so Core makes it a child: cancelling or ending the handler's call cancels the relayed call. An explicit parentOperationID in call overrides it (1 to 128 bytes). A handle.Host() serves no call and a generic Request is sent as written, so neither fills it in. An ID that names a call this backend is no longer serving fails with plugin.host.cancelled.
  • A relayed call occupies a request slot. It counts among the 16 unanswered host requests until the provider answers, which can take up to 600 seconds; further requests wait in the SDK. Keep relayed calls bounded with timeoutMilliseconds.
  • call.Caller() names the calling plugin. It is non-nil only for a call Core relayed, and nil for a call the host started. The SDK accepts only a caller that is exactly { "pluginID": "<non-empty string>" }; any other shape is read as no caller. It names who called, not what they may do: authorize with the plugin's own rules.
Failure (SdkError.Code()) Meaning
sdk.functions.invalidCall The call or the function ID was malformed. Nothing was sent.
plugin.host.unavailable The host did not offer litheFunctions. Nothing was sent.
plugin.host.permissionDenied The plugin declares no pluginFunctions.calls.
plugin.function.notDeclared, .providerDisabled, .notExported, .versionMismatch The call is not declared, the provider is missing or disabled, does not export the function now, or exports another version.
plugin.function.callCycle, .depthExceeded, .tooManyCalls, .payloadTooLarge The chain, the caller's running calls, or a payload exceeded a limit.
plugin.function.providerUnavailable, .invalidResult The provider's backend stopped or did not start in time, or answered with no result or one over 1 MiB.
plugin.function.failed The provider's function returned an error. The pluginErrorCode entry of Details() is the provider's own PluginError code, and Message() is its message.
plugin.host.contextExpired, plugin.host.timeout, plugin.host.cancelled The context was closed or replaced, the deadline passed, or the call (or its parent) was cancelled. A remote workspace's context is relayed like a local one.
sdk.host.invalidResult The host answered with something other than an object.

Results and errors

Handler outcome What Lithe sees
value, nil (including nil) result.value
nil, *PluginError (or an error wrapping one) plugin.function.failed with your message and pluginErrorCode. The code is for your plugin's own UI; Lithe never branches on it.
Any other error, or a panic plugin.function.failed with a generic message, so paths, secrets, and stack traces never reach the UI. Automatic SDK diagnostics record only a fixed failure category. A panic ends only its call.
lithe.ErrCancelled (or an error wrapping it, such as sdk.call.cancelled), or any outcome after cancellation requestCancelled (or Lithe's timeout or revocation outcome)

A result must serialize to at most 1 MiB of JSON; a json.RawMessage is sent as it is. A function ID is dot-separated lowerCamelCase segments (snapshot.refresh, lithe.IsFunctionID), at most 128 bytes, and a session holds at most 256 functions. A PluginError code matches [A-Za-z][A-Za-z0-9._-]*, at most 64 bytes (lithe.IsPluginErrorCode); NewPluginError panics on any other code.

Rules that keep Lithe in charge

  1. stdout belongs to the protocol. On Unix, Listen() moves the protocol to a duplicate of the stdout descriptor and points stdout at stderr, so a stray fmt.Println in your code or a dependency lands in the host's log. Elsewhere, never print to stdout.
  2. The package is read-only. Keep caches and databases under ${stateDir}, which Lithe also passes as the root and working directory. Diagnostics use the SDK and host; native log files require an explicitly supplied ${logDir}. Writing to the package breaks code signing and update deltas.
  3. Secrets go to the credentials service. Never write a password or token to ${stateDir}, to a log line, or to a PluginError message.
  4. Work ends with its call. Check the cancellation in long loops, use WaitTimeout between retries, and pass Cancellation().Context() to blocking driver calls. Lithe has already ended the call when it cancels; the SDK answers requestCancelled whatever the handler returns.
  5. No calls back into Lithe's dispatch. The SDK never sends lithe/function/invoke or lithe/build/*; Lithe would refuse them as plugin.function.recursiveCall. Host.Request sends only lithe/host/* and refuses anything else as sdk.host.method. To call another plugin, use Host().Functions(), which sends lithe/host/functions/invoke and lets Core relay it.

Native terminal API

The SDK includes wrappers for plugin-owned native terminal create/show/close, reopen with bounded display history, disposal and exit subscriptions. They are host methods discovered through Capabilities(); they require a host that offers them and the terminal.create permission. See the native terminal guide.

Testing

Run these from this directory:

go test -race ./...
go vet ./...
gofmt -l .

and, from the root of this repository, node shared/plugins/scripts/sdk-e2e.mjs. CI runs the first three on the Go release that go.mod names.

The unit tests drive a session through in-process pipes with a scripted host; lithe/host_services_test.go checks the host services against the contract's fixture. The end-to-end check builds the sample, installs it as a package, and runs it through a real Core session of this checkout. It needs Go, Rust, Node.js 20.3 or newer, Java (LITHE_PLUGIN_SDK_JAVA_RUNTIME or java on PATH) and Maven; LITHE_PLUGIN_SDK_GO_SAMPLE names an already built sample-backend.

Workflow host methods (quick pick, input, previews, diff, view refresh, output, progress, status, clipboard, reveal and HTTP) are documented in the plugin workflow guide. Discover each method before calling it; wrappers do not grant permissions.