Plugin SDK development
Plugin SDK development — GalCraft Studio product manual.
This guide covers SDK and plugins at 0.1.0, engine 0.1.1, manifest schemas 1/2 and Web/Windows targets. The maintainer distributes SDK 0.1.0 through npm and GitHub Releases under MPL-2.0.
Use @galcraft/plugins/contracts for contributions/services, @galcraft/plugins/react for shared React and @galcraft/plugins/pixi (Pixi / PIXI) for shared Pixi. Host composition owns registries, storage and IPC. Install the contracts and plugins SDK packages outside the repository; source-path imports are not the public SDK.
Start with author-tool: its report tool reads the selected statements, making the build, installation, activation and execution path easy to verify. This exercise uses npm SDK packages; prepare Node.js to begin. The independent plugin development CLI requires Node.js 22.12.0 or later; use the latest Node.js 24 LTS patch and its included npm. The contracts and optional DSL parser also expose browser entries; those browser consumers need no Node.js runtime. Authors using existing plugins can go directly to installation.
1. Prepare the SDK
Plugin authors install @galcraft/contracts@0.1.0 and @galcraft/plugins@0.1.0 from npm. Plugins that parse GalCraft statements also install @galcraft/dsl@0.1.0. The 0.1.0 release provides the same tarballs. Read the SDK license notice for MPL-2.0 terms and matching source.
Source maintainers can prepare the fixed environment from Source development, then run node tools/plugin-development/distribute-sdk.mjs out/sdk at the repository root to obtain the three tarballs and sdk-distribution.json.
2. Create and build your first plugin
Open PowerShell in a working directory outside the repository. Install the exact SDK versions to obtain the scaffold command, then install the independent plugin’s dependencies inside example:
mkdir my-plugin
cd my-plugin
npm init -y
npm install @galcraft/contracts@0.1.0 @galcraft/plugins@0.1.0
npx --no-install galcraft-plugin create example org.example.plugin author-tool
cd example
npm install @galcraft/contracts@0.1.0 @galcraft/plugins@0.1.0
npm run typecheck
npm run build
npm run check
npm run packContinue after each command succeeds. The scaffold destination example must be empty; choose a new directory if it already contains files.
| File or command | Purpose and expected result |
|---|---|
plugin.config.json | Plugin identity, contribution declarations and source entries consumed by build |
src/definition.ts | DOM-free definitions, document fields and messages |
src/editor.ts | Studio selection report and field editor |
npm run typecheck | Check TypeScript against SDK types before building |
npm run build | Emit package/manifest.json and environment-specific ESM |
npm run check | Validate the generated manifest, contribution implementations and dependency graph |
npm run pack | After successful checking, emit an ordinary .galplugin installer in dist/ |
After editing source or configuration, rebuild, check and pack again. The generated package/ is the loadable output and is regenerated by the next build.
Other scaffolds are game-system, resource-stage, service-provider and complete. After this first tool, choose a game-state, resource/stage, production-service or complete example for the capability you need.
3. Install and execute the selection report
- Open an exercise project. In Studio → Plugins, install the generated
dist/*.galplugin. - Check package ID
org.example.pluginand version0.1.0, then install. Select it, choose Enable in project, review the impact, confirm and save all. - In Authoring, select one statement card. Open Selection report from the plugin tools list or command palette. Tools that require a statement selection explain their applicability.
- Run the tool. Its report should show
Selected statements: 1. Select several statements, reopen the tool and check the new count.
A tool captures the selection when opened. Reopen it to inspect a new range. This report reads selection and produces no project edit.
During development, the development-directory action can inspect/load example/package/. Rebuild before reloading that directory. For ordinary installation, select the newly generated .galplugin instead.
Change code that actually runs
In generated src/editor.ts, find the report tool's run in the tools array. Replace that method with the following. Keep the existing declaration, imports and fieldEditors:
run: async (_input, context, signal) => {
if (signal.aborted) return ok({ kind: 'none' as const });
const count = context.scope?.statementIds.length ?? 0;
return ok({
kind: 'report' as const,
message: `My plugin received ${count} selected statement(s).`,
issues: [],
});
},The scaffold's common.ts supplies ok. context.scope is the authoring range for this invocation, and report asks the host to present the message. Rerun typecheck, build, check and pack; reload the development directory or reinstall the same-version package, then close/reopen the tool. With one selected statement, expect “My plugin received 1 selected statement(s).”.
| Problem | Next action |
|---|---|
SDK .tgz is missing | Check the actual directory and filenames in $sdkDirectory |
| Scaffold command is unavailable | Confirm the local plugins SDK installed successfully in the current directory; --no-install uses the local command |
| Check reports a declaration/implementation mismatch | Correct the entry named in plugin.config.json, rebuild and check again |
| Tool is unavailable | Open a project, enable the exact version and select statements as instructed |
| Old report still appears | Rebuild, reload the development directory or reinstall the new package, then reopen the tool |
Plugin names and interface languages
Manifest name and description contain the author's source text. Add localizations inside manifest in plugin.config.json for other languages. Merge this field excerpt into the existing manifest:
{
"name": "My plugin",
"description": "Report the number of selected statements.",
"localizations": {
"zh-CN": {
"name": "我的插件",
"description": "显示当前选中的语句数量。"
}
}
}Studio updates displayed plugin text when its interface language changes. Missing translations show the source text. The public pluginDisplayMetadata(manifest,locale) helper checks the exact locale, its language and then the source text. Package IDs, versions and project dependencies retain their identity.
The Studio plugin explorer shows the current work activation state beside each exact version. Local installation and activation in a work are separate. Confirming an enable/disable change keeps the affected plugin selected and displays its updated state.
Entries, versions and dependencies
Schema 1 retains its package behavior. Schema 2 requires entry.definition and applicable editor/services/runtime entries. sdkMajor: 0 and engineRange define compatibility; current plugin packages use version 0.1.0 with engine range ^0.1.0. Projects lock exact dependencies.
The current bundled engine uses 0.1.1; plugin and SDK exact versions remain at 0.1.0. Ordinary installation refreshes a plugin, Studio startup refreshes the bundled engine, existing sessions finish their leases and new loads use new files. Installation retains project locks, state and task inputs. Source backups use versions/0.1.0; install the current package/ or a newly packed archive. Manifest schema, contract/type/state versions describe their own data and do not all change together.
| Entry | Export / environment | Responsibility |
|---|---|---|
| definition | createDefinition(): PluginDefinition or definition; no DOM | Schemas, fields, initial data, reference rewrite, conversion, configuration mapping, messages |
| editor | createPlugin(): GalCraftPlugin; Studio | Tools and field editors; named workbenches also export createStudioPlugin() |
| services | createPlugin(): GalCraftPlugin; Node | Generation, processing and publish checks |
| runtime | createPlugin(): GalCraftPlugin; playtest/Player | Commands, conditions, systems, pages, components, resources, stage and platform |
dependencies applies to all environments. environmentDependencies declares definition/editor/services/runtime dependencies by id/range, optionally restricted by targets. Publishing reads definition/runtime closure. Build bundles ordinary JS dependencies while preserving shared React. Checks require relative imports in files; Node service entries may use node:. Definition callbacks are synchronous/pure; hosts retain handles until delayed consumers finish.
include adds licenses/static assets. nativeSources: [{target,arch,source}] builds native entries. Windows x64/arm64 examples export createPlatformProvider(context); native dependencies use package-relative paths and join the manifest closure. Resource inspect receives available source files and returns the entry and actual dependencies. A single-file kind returns [rootFile]; grouped resources follow declared references. Hosts copy the returned set only.
Contributions and consumers
| Contribution | Interface | Consumer |
|---|---|---|
| document | schema/fields/initial/collectReferences/rewriteReferences, optional validation/conversion/state/config mapping | M02 editing/copy/delete; M03 compilation; backup/publishing |
| tool | locations/scope/applicable/run | M01 selection-dependent actions and results |
| fieldEditor | contributionKey/fieldKey/mount | Same-plugin public fields; host-mediated commit |
| command / condition | spec/execute/resume, fields/evaluate | M03 shared catalogue and M05 execution/recovery |
| system | Progress/persistent schemas, defaults, conversion, merging/checkpoint | M05/M07 state under plugin ID, one authoritative definition |
| page / component | Render, schema, fields, samples, public parts and state binding | M08 configuration/preview; M07 Player/actions |
| resource / stage | Node inspection; runtime update/set/capture/pause/dispose | M04 file/capability resolution; M06 provider-key dispatch; M11 same resource closure |
| generationProvider | Purpose, config, input/output schema, capabilities, create | M10 exact contribution/version/config freeze and candidates |
| resourceProcessor | Input/output kinds, cancellation, fields, process | M04 controlled reads, validation and provenance |
| platform | Named actions, targets, required/fallback policy, invoke | M05/M07; architecture-specific Windows entry |
| publishCheck | check({snapshot,lock,target,settings},signal?) | M11 diagnostics for the frozen publish input |
PluginDefinition.messages maps locale codes to namespaced text keys. Fields support labelKey/descriptionKey and titles titleKey; hosts fall back through current locale, Chinese and key text. Generic forms use validatePluginData(schema,data) with optional document validation. JSON schemas support inline properties, types, enum/const, ranges, lengths, array items and required fields. External $ref produces diagnostics.
Authoring context and adoption
StudioPluginContext.scope exposes page, scene, document, instruction, selected text/assets, insertion point and versions with disposable subscriptions. Navigation opens public pages or source locations. Documents expose query/transactions; semantic/assets/production/playerUi services retain their module ownership. Check optional services and show prerequisites when unavailable.
Tools obtain author services from PluginContext.studio and retain their starting scope/baseline version. PluginToolResult can report, propose edits, create tasks/candidates or return none; legacy EditInput|null is supported. The host reviews proposals before M02 applies them with a receipt. Saving confirms disk persistence. Cancellation/conflicts retain results and original content.
Document configMapping: {purpose,mode,required} produces per-plugin runtime configuration. Each document entry preserves contribution key, identity, version, purpose and data; the array supports multiple instances. Required configuration and fixed-instance declarations enter compilation diagnostics. Legacy flat config prefers plugins/<pluginId>/documents/config.json, then plugins/<pluginId>/config.json. Official and installed packages use the same public definitions.
Field kind asset selects the active version; variant fixes a version. Generic forms, compilation, publishing, backup and runtime retain that choice. Component FieldSpecs collect/rewrite nested and array references; ordinary text is not identity-rewritten. Documents provide their own reference collection/rewrite. Missing fixed versions return located diagnostics.
Lifecycle, tasks and restoration
Activate registers contributions; deactivate releases UI/listeners/resources. Node plugins register disposers through context.onDispose. Async work consumes cancellation signals. Each load copies the full file graph away from replaceable package locations, binding relative imports to that load. Failed preparation retains the last valid contributions. Refresh/reload retains active leases until consumers finish.
Each page/component render gets its own signal/onDispose. Release listeners, timers and temporary handles within that scope. PLUGIN_DISPOSE reports failures while hosts continue releasing remaining resources.
Providers separately declare query, output refetch, per-task cancellation and reconnection. M10 restores with the original exact service package/configuration. Unconfirmed remote state remains unknown for the author to review before a new request. Local stop and remote cancellation are distinct. Read credentials at the Node service boundary with context.credentials.read(id); keep them out of definitions/packages.
Input schemas validate complete PluginGenerationInput. Output schemas validate {artifacts,usage} events; M10 accumulates streaming text deltas into text artifacts. Page wait.restorable describes restoration, and wait.cancel determines continuing or retaining the wait on close. Hosts own execution tokens. Progress, long-term data and config have separate conversions; failure retains original state/package.
Validation
Build/check validate manifests, schema/fields, declared implementations, one authoritative state definition and environment dependency graphs. Pack emits the ordinary package after checks pass. Activation registers contributions; real consumers invoke services.
In Studio, exercise the selection, review, undo, save/reopen and cancel operations your plugin provides. For a generation service, run its task and candidate flow. For runtime contributions, run the corresponding pages, components, resources or platform functions on the declared release targets.
Asset editors and previews
Associate editorKey/previewKey/thumbnailKey in the type definition, declare assetEditor/assetPreview/assetThumbnail and return implementations from the same plugin's editor entry. Studio loads the exact project lock. Dedicated regions share host general properties/saving instead of replacing the whole Inspector.
AssetEditorContext.target.kind distinguishes asset, instruction and instance; resource supplies the actual asset/variant. Asset commits go through M04/M02; the host injects the appropriate instruction/instance commit. Stop submitting when read-only or aborted. Type filter fields reference declared string/number/boolean fields and match active-version values.
AssetPreviewContext includes asset/candidate identity, exact variant, read-only root and file list. Read declared files through resource.read(path) and type data through variant.typeData.value. Return a disposer, optionally asynchronously; register already acquired resources before awaiting. Check cancellation and release canvases/media/listeners/loops on close/reload. custom-asset is an ordinary external-package example.
Typed production operations
No-DOM definitions declare namespaced operation IDs, independent business version, fields/schema, typed input/output ports, MIME and adoption purposes, linked to the same plugin's provider. Type/operation definitions use contractVersion 1; existing document/index/snapshot/task/candidate/draft/recipe envelopes retain schemaVersion 1. New records validate typeData/operationSnapshot as needed. Reading old records preserves them without automatic rewriting or POST.
Generic production forms implement each port's type, MIME, required and multiple rules. References retain port; changes preserve other ports. Optional fieldEditor can provide dedicated input controls. ProductionFieldEditorContext.commit submits parameters/references through M10 draft-revision checking/saving and invalidates old send plans, without editing project content.
External runtimes
Manifest 2 declares namespaced capability keys in externalRuntimeDependencies. Optional runtimeDependencies.resolve(key) returns host-verified {url,expected}; load returns those fields plus the module. Undeclared/unprepared keys diagnose failure. Check module interfaces and expected version before creating instances. Static plugin graphs stay closed; runtime manifests own external files/licenses.
Studio services also return release(). Register leases with onDispose before awaiting more resources; release results that arrive after closing. Optional stage assets.readText/readBytes(resource,path) and Node PluginResourceSource.readText/readBytes read declared grouped files. Missing ports produce recoverable prerequisites; do not guess disk locations or substitute versions.
Live2D's ordinary exact package supplies definition, Node services, runtime and editor; Core stays external. Declared builtin-kind/provider aliases read existing model identities without rewriting envelopes or locks on open. Optional studio.assets.inspect(assetId) checks active-version capabilities through M04/M02 while pinned references retain their version. See Live2D usage.
Public target builders and native platforms
A target package declares a targetBuilder contribution and a real entry.services. Service activation supplies the matching targetBuilders entry. The public TargetBuilderContribution includes describe for target, architecture, environment, tools, options schema and entry; detect/prepare for external toolchains; validate for frozen options; and build for native project/artifact generation inside M11's staging directory. Return relative entry, handoff and artifacts, and use the supplied cancellation/progress context. M11 owns saved snapshots, exact dependencies, common Web runtime files, plans and atomic output commit.
Official Android/iOS and external packages use the same installation and exact selection port. Author builders are declared in the target-builder catalog. Player runtime plugins belong to the work’s exact dependency Lock; runtime plugins and assets each declare support for the selected target. SDKs and full tool caches remain in the author's selected location. See the official target package READMEs and source for complete implementations.
Windows native entries export createPlatformProvider(context). projectPlatform comes from saved project platform settings; runtime contains the actual release directory and executable host. The provider owns initialization, calls, events and disposal. Native files follow the actual Player architecture. Steam0.1.0 uses steamworks.js0.4.0 Windows x64 files; account results require separate execution evidence.
Soundbanks and workflow contributions
Operations can declare presets: [{id, name, description, defaults}]. Use stable valid IDs and declared fields; defaults can contain structured JSON such as an editable score. M10 exposes presets from enabled exact plugins through the existing scheme library, including read-only use, copying to personal/project scope and export. Copies retain the operation snapshot and complete starting content. Authors select personal connections, reference media and adoption targets in the workstation. Saving or using a preset prepares a draft; execution follows the explicit send review.
Production operations integrate through public definition fields, references, providers and adoption declarations. An operation can contribute a data-only workflow template for the author to inspect and select in a connection. The host reads the actual contribution. Speech inputs live in production drafts; character presets commit through the M02 character transaction.
The composition package declares the soundbanks capability to access the local catalog. Service contexts expose read-only listing/resolution; Studio editors explicitly install or import through the owning host interface. Ordinary exact plugin packages contain their required environment outputs. Player release closure uses adopted audio and public runtime contracts.