Skip to main content

Invocation and host APIs

Tools, actions, data sources, services and message handlers export guest.invoke(request-json) -> result<string,string> from the contribution world. Glixo constructs the invocation envelope, checks the signed contribution and validates input, then calls your component. You validate the fields your handler uses and return JSON matching that contribution's output schema.

Invocation envelope

For an approved Text Stats call, the JSON has this shape:

{
  "kind": "tools",
  "contributionId": "text-stats",
  "configuration": {},
  "input": {"text": "Glixo makes tools."},
  "context": {
    "sessionId": "host-issued-session",
    "resourceHandles": {},
    "endpoints": []
  }
}

The example session value is illustrative; never create handles or session IDs yourself. A workspace-enabled call may receive context.resourceHandles.workspace; an approved network connection may supply endpoints with {name,handle,baseUrl}. Secret slots can appear in resourceHandles as opaque references. The exact available resources depend on the contribution, account and approved grants.

Field How to use it
kind Check the contribution group, such as tools, actions, dataSources, backgroundServices or messageMiddleware.
contributionId Match the stable ID declared in your manifest; reject another feature's input.
configuration Host-selected non-secret settings. Validate types, ranges and defaults.
input Feature-specific input described by your signed schema; validate every field you read.
context.sessionId Identifies the invocation context; it is not a credential.
context.resourceHandles Names mapped to opaque host resources; use only supplied values.
context.endpoints Named, approved endpoints with an authority handle and base URL.

Text Stats returns the direct result string {"wordCount":3,"characterCount":18}. Do not wrap it in request or response unless your declared output schema explicitly calls for that property. SDK GuestReply<T> is a convenience shape; it does not require a response wrapper in every contribution. See the public entry point and envelope types.

Connect imports to adapters

The contribution broker's WIT source defines state, logging and workspace calls. This TypeScript adapter implements the SDK interfaces using those imports:

import { stateGet, stateSet, stateList, stateDelete, log,
  workspaceSearch, workspaceRead } from 'glixo:contribution/broker@1.0.0';
import type { ScopedState, WorkspaceReader, ExtensionLogger }
  from '@glixo/extension-sdk';

export const state: ScopedState = {
  get: stateGet, set: stateSet, list: stateList, delete: stateDelete,
};
export const workspace: WorkspaceReader = {
  search: workspaceSearch, read: workspaceRead,
};
export const logger: ExtensionLogger = { log };

These imports resolve when Jco componentizes the project. They need the contribution world, not the provider world. They throw on WIT errors; let the exported wrapper convert errors. Other languages implement their corresponding SDK traits/interfaces with generated imports.

Scoped state

WIT operation SDK TypeScript signature Meaning
state-get get(key:string): string | undefined Read a string; absent key is undefined. Failure is a WIT error.
state-set set(key:string,value:string): void Write a string under the approved prefix. Serialize your own JSON.
state-list list(prefix:string): readonly string[] List keys in an approved prefix. Validate/filter keys before returning to callers.
state-delete delete(key:string): boolean Delete a key; return whether it existed.

Declare storage.extension in permissions.requested and put every key prefix in its scope:

{
  "id": "storage.extension",
  "scope": {"prefixes": ["accessible-theme/preferences/"]},
  "reason": "Save this extension's appearance preferences."
}

This is one permission entry inside a complete manifest. The user must approve it before the call succeeds. State is scoped by the host; a string prefix alone does not authorize access to another package or account.

Here is a handler helper using that exact prefix:

import type { ScopedState } from '@glixo/extension-sdk/state';

const key = 'accessible-theme/preferences/current';
export function saveAccent(state: ScopedState, accent: unknown): {completed: true} {
  if (typeof accent !== 'string' || !/^#[0-9a-f]{6}$/i.test(accent)) {
    throw new Error('accent_invalid');
  }
  state.set(key, JSON.stringify({accent, largeControls: false}));
  return {completed: true};
}

Call it from an actions handler after checking the action ID and envelope. It is a helper, not a complete extension. The panel action demonstrates the complete dispatch. Storage has no SDK transaction or compare-and-swap method; don't promise atomic multi-call updates. Bound values before writing, and keep credentials in host-managed secret slots. Workspace Storage demonstrates all four operations and a 4 KiB sample value limit.

Workspace access

search(handle,query,limit) returns a JSON string containing an inventory. Parse and validate it:

{"items":[{"path":"notes/meeting.md","bytes":241}],"truncated":false}

read(handle,path,maxBytes) returns file content as a string. Use workspace-relative forward-slash paths from the validated inventory. Keep the requested byte limit small; reading is bounded by host policy and this argument. Do not accept an arbitrary local disk path or reuse a handle in another invocation.

Declare fs.workspace.search and/or fs.workspace.read with the supported project-local scope from your generated manifest. Obtain the current workspace handle from the host envelope. The Workspace Health handler searches with a limit of 100 and reports sampled totals when results are truncated. The Document Index handler searches relative paths and reads only small files, up to 4096 bytes, for short excerpts. Its manifest shows both permission entries.

Validate inventory paths, byte counts, duplicates and truncation. File name search is not semantic content search. A missing handle means your invocation lacks the resource; return a clear error rather than guessing a directory.

Logging, services and messages

log(level,message) sends a message to host diagnostics. Use the level strings your host supports; examples use info. Keep messages bounded and exclude credentials, private input and upstream bodies. Contribution logging returns a WIT result; the provider host's log has no result return. These are different imports despite similar names.

Background services receive bounded initialize, wake, health and stop operations, and return checkpoints/events for Glixo to manage. They do not start an infinite polling loop or schedule their own process. See Mail Watch service operations and handler source. Message middleware reads or returns the declared message shapes using separately approved observe/transform grants; see message processing.

Failure behavior and tests

Handle invalid JSON, wrong IDs, missing handles and host denial as expected errors. Keep codes stable and public. Do not treat denied state access as an empty store, or an HTTP failure as an empty model list. Every invocation must finish within its declared timeout. Use durable host state or returned checkpoints for data you need after restart; a guest global or stream handle is not durable storage.

Test valid input, invalid types, missing handles, denied adapters, empty state, repeated operations and bounded output. Then install and activate, remove a permission, and confirm protected operations stop. Mock tests and manifest validation cannot prove the installed account's resource access.