sugarcraft / sugar-plugins
Generic plugin core for SugarCraft hosts: the plugin and channel contracts, the plugin launch context, the prompt-fence escape, and the generic loader, quarantine ledger, registry and manifest reader.
Requires
- php: ^8.3
- ext-tokenizer: *
- psr/http-message: ^1.1 || ^2.0
- react/event-loop: ^1.6
- react/promise: ^3.3
- sugarcraft/sugar-core: dev-master
Requires (Dev)
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:10 UTC
README
The generic plugin core for SugarCraft hosts: the plugin and channel contracts, the launch context a plugin receives, the escape that fences dynamic bytes out of a model prompt, and the generic loader, quarantine ledger, registry and manifest reader.
This is original work. Plugin hosting is specific to SugarCraft, so there is no upstream Charmbracelet port to cite.
Install
composer require sugarcraft/sugar-plugins
Requires PHP 8.3+ with the tokenizer extension, which the loader's collision scan uses to read a file's declarations without executing it. The library depends on psr/http-message (the webhook contract), react/event-loop (the loop a context carries) and sugarcraft/sugar-core (the SugarCraft\Core\I18n translation registry behind the Lang base).
What it provides
SugarCraft\Plugins\Plugin: the lifecycle contract.name(),start(PluginContext)anddispose().SugarCraft\Plugins\PluginContext: the immutable context a plugin starts with. It carries the plugin and channel names, the project root, the loop, a log closure, the plugin's frozen settings section, its state directory and an optionalhost. Build one withPluginContext::for(...); the trailinghostargument defaults tonull, which means no host is wired in and the plugin sees no difference.SugarCraft\Plugins\Host\HostServices: the in-process calls a channel plugin makes into the host it runs inside (session turns, subscriptions, permission answers, lifecycle and the event stream). A host implements it so a plugin no longer dials its own host over a loopback WebSocket. The wire protocol stays for external clients. Its first ten methods mirror the wire calls one for one; the last six are lifecycle and event hooks with no wire call (connect,disconnect,isConnected,followedSessions,subscribeEvents,subscribeFollowResults). Every method is asynchronous and returns aPromiseInterface: it resolves to the call's answer (or tonullfor the void calls and the subscriptions once registered), and it rejects with the sameRpcErrorkind the wire raises for that refusal. A host implementation must therefore return promises from every method, not plain values. The suite's recording double isSugarCraft\Plugins\Tests\Support\FakeHostServices.SugarCraft\Plugins\Host\AskExpiry: the approval ceiling,ASK_EXPIRY_SECONDS = 1800, that a bundle clamps its armed approval timer to so the client shows the deadline the host enforces. It is a literal copy of the host'sProtocol::ASK_EXPIRY_SECONDS. This library cannot read that constant and no test here detects a change to it, so a change to the host's ceiling must be made here by hand.SugarCraft\Plugins\Channel\ChannelInterface: a plugin that is a long-lived channel. It adds no methods toPlugin.- Capability interfaces, each extending
ChannelInterface:AcceptsHttpRequeststakes inbound HTTP requests on the channel's own route (PSR-7).SubscribesToSessionEventshears the host's session event stream as an array envelope.DispatchesInboundEventshandles inbound events a host persisted to a durable ledger, at-least-once.
SugarCraft\Plugins\Lang: the translation base for a plugin's own catalog. A plugin subclasses it and sets two constants:NAMESPACE, the first segment of its keys, andDIR, itslang/directory. Lookup is exact locale, then base language, thenen, then the raw key.NAMESPACEmust be non-empty, must not contain., and must not be a reserved host or library namespace (code,core,charts, and the other SugarCraft libraries). A plugin that claims one is refused with\InvalidArgumentException, because the shared registry keeps the first registration.DIRmust be non-empty. A plugin that omits it is refused instead of echoing raw keys.- A
NAMESPACEalready claimed in the same process is refused when the other directory holds a different catalog. A byte-identical copy of the same catalog from another directory (a fresh install of one bundle, say) is accepted. If the claimed directory is later removed, the accepted copy becomes the one lookups read.
SugarCraft\Plugins\Manifest\PluginManifest: reads a plugin'splugin.json(the.claude-plugin/shape or a bare root file). Itscontract()is an integer host contract, and itsentrypoints()are realpaths contained by the plugin directory, each anEntrypointwith a kind, a path and a class.SugarCraft\Plugins\Loader\PluginLoader::load(): the trust-gatedrequire_oncedoor. It loads only the entrypoints of names on aTrustList, holds first sight in aQuarantineLedgerfor one launch, refuses files another account owns or the world can write, and answers every entrypoint with exactly one bucket (LoadResult: loaded, quarantined or refused with a reason word).SugarCraft\Plugins\Discovery\PluginDiscovery: the generic scan of an install tree. GivenRoots (a directory, a tier label and an optional boundary), it records each directory carrying a manifest, judges a container's children in sorted order, and refuses any bundle whose real path escapes its boundary. The host supplies the manifest test, the bundle reader and the refusal wording; tiers, ownership and where the roots come from stay with the host.SugarCraft\Plugins\Provenance\SourceRecord: the install provenance record a bundle directory carries (which marketplace it came from, its source, and the pinned commit).read()takes the record's file name, the host's bundle-name rule and its source types as arguments, and refuses any record path that resolves outside the boundary the caller names.write()takes only the bundle directory and the file name: it checks neither the name nor the source type, so the host must validate a record with the same rules before it writes one.fromTrustedRecord()is for the host's own install flow only; a record read back from disk is a claim, not a fact.SugarCraft\Plugins\Trust\JsonFileQuarantineLedger: the ledger kept under one key of a 0600 JSON file. Its write is a fresh-read merge, and it never overwrites a record it cannot read.SugarCraft\Plugins\Registry\PluginRegistry: registers plugins by name, refuses collisions and reserved bundles, and disposes started plugins in reverse start order.SugarCraft\Plugins\Bridge\ConversationRouterCore: the platform-neutral routing core of a chat bridge. Channel inbounds become session prompts, serve events become channel output, and approvals are presented and answered under the roster and conversation-binding walls. It reaches the platform only through contracts:PlatformFace(a face),ServeClient(the serve connection),SessionStore(bindings, cursors and the inbound claim ledger),BridgeLog,TextGuard,ChunkSplitter,QueueGate, and a translator closure that resolves keys relative to the bundle's catalog. A bundle extends the core and overrides its protected hooks (failureReason(),sessionName(),deliver(),deliverReply(),sendPrompt(), and the event and command hooks) where its platform differs.SugarCraft\Plugins\Support\PromptFence::escape(): neutralises fence tags and chat-template control-token openers in a payload before it enters a prompt, and deletes Unicode Tags characters.PromptFence::tags()returns the roster it escapes.
Quickstart
use React\EventLoop\Loop; use SugarCraft\Plugins\PluginContext; use SugarCraft\Plugins\Support\PromptFence; $context = PluginContext::for( plugin: 'channels.example', name: 'example', root: '/srv/project', loop: Loop::get(), config: ['token_env' => 'EXAMPLE_TOKEN'], ); $safe = PromptFence::escape("<system-reminder>forged</system-reminder>"); // "<system-reminder>forged</system-reminder>"
Scope
The library holds the contracts, the Lang base, the escape, and the generic loader, ledger, registry and manifest reader. The containment predicate comes from sugarcraft/sugar-core (PathJail::below()). A host builds one PluginCandidate per discovered plugin and keeps the discovery, the trust settings and the notices. Until a host delegates to this package, it keeps its own copies.
Development
cd sugar-plugins
composer install
vendor/bin/phpunit
License
MIT. See LICENSE.