Integrate a Feature with AI Worker
Use the base AI contracts for short handler-based requests. For long interactive or background work, depend on the worker's session/job contracts directly. Routing a synchronous provider through the worker does not turn it into a durable job.
Interactive Sessions
Inject Hyva\AiWorker\Api\SessionIssuerInterface and call:
$session = $sessionIssuer->issue(
task: 'page_generation',
provider: $provider,
model: $model,
constraints: $limits,
providerConfig: $options,
userId: (string) $adminUserId,
requestPayload: $serverBuiltRequest,
type: 'your_feature',
jobMeta: ['entity_type' => $entityType, 'entity_id' => $entityId]
);
The variables in this example must come from your authenticated, authorised feature controller. Build prompts and context on the server, validate the chosen entity/model, and enforce feature permissions before issuing a session. Requested limits can lower configured ceilings, not raise them.
The response includes session_id, stream_url, image_url, fallback_stream_url, fallback_image_url, browser_token, expires_at and job/item identifiers. The immutable request is stored in Magento and consumed once by the worker. Do not send prompts, provider credentials or mutable provider request bodies in the browser's worker POST.
The package supplies window.hyvaAiWorker in its admin client template. runJob({createUrl, formKey, payload, claimUrl, signal, handlers}) coordinates session creation, streaming, durable-result recovery and claiming. Lower-level integrations can use createSession, streamSSE, generateImage, pollJobStatus, resumeJob and claimJob. Pass session.fallback_stream_url as the fifth argument to streamSSE, or session.fallback_image_url as the fourth argument to generateImage. Backup URLs are empty when PHP is disabled or already selected. Generate admin URLs server-side; do not hard-code an /admin path.
Runtime Selection and Backup
WorkerConnection prefers a healthy configured external worker, caching its health for
30 seconds, and selects enabled PHP when the external worker is unavailable. Browser and
server clients can also try PHP after a connection/start failure. They reuse the same signed
token and stored-request credential, so Magento's atomic consumption permits only one
provider call. Do not mint a new session as part of runtime fallback.
Provider failures and established streams are not restarted on PHP. If PHP finds the request already consumed, durable jobs wait for the existing result. Image requests do not have the text job recovery flow: an ambiguous failure can still require a user-visible error. The scheduler keeps the selected URL with the transport decision, so a Cloudflare runtime cannot accidentally receive a detached dispatch intended for PHP/Node.
Stream Contract
| Event | Meaning |
|---|---|
meta |
Session, provider, model and worker version. |
delta |
Incremental text. |
component |
Completed top-level node in supported JSON page-array generation. |
warning |
Incomplete/truncated/invalid-output notice before termination. |
done |
Result, usage, optional finish reason and tool calls. |
error |
Terminal error with message and code. |
The worker emits one meta and one terminal done or error for an established stream. Failures before streaming are ordinary JSON errors with an HTTP status. Ignore unknown additive fields/events. A done event is a transport result, not permission to save unchecked content: inspect warnings, completeness and your feature schema.
Tool calls are returned as data. The worker does not authorise or execute Magento actions requested by a model. Your feature must validate tool names, arguments and permissions before executing any operation.
Durable Bulk Jobs
Implement Hyva\AiWorker\Api\ChunkHandlerInterface:
| Method | Responsibility |
|---|---|
resolveProvider(array $job): array |
Return provider, model and provider configuration. |
buildRequestPayload(array $job, array $items): array |
Rebuild the entire request from durable job/item state. |
applyResult(array $job, array $items, array $response): void |
Validate and record each item's outcome through JobManager. |
Register it in the handlers argument of Hyva\AiWorker\Model\Queue\ChunkHandlerPool, keyed by job type. Submit through Hyva\AiWorker\Api\BulkJobSubmitterInterface::submit($type, $task, $items, $meta, $payload, $expiresAt). Submission refuses unregistered job types and empty work.
The scheduler must be able to reconstruct every request without the original PHP process. Do not rely on session state or a browser-held prompt. Result handling must tolerate callback redelivery and preserve per-item validation. Use whole-chunk JobManager operations where appropriate.
The transport is detected from worker health: self-hosted dispatch (Node or bundled PHP-FPM) or Cloudflare completion with a connection holder. PHP-FPM stays occupied for a dispatched PHP generation; it does not gain Node's process isolation. Features use the same handler contract in either case. See Operations for required processes.
Provider and Feature Extensions
| Extension | Registration |
|---|---|
| Credentials | Prefer the base ProviderApiKeyResolverInterface and Hyva\Ai\Model\ApiKeyResolverPool.resolvers. Existing worker-specific resolver registrations remain compatible. |
| Text models | Provider-owned ProviderResolver.providerModels, including worker_adapter metadata for a supported worker protocol. Legacy worker OptionsSchema.modelOptions registrations remain supported. |
| PHP streaming adapters | Provider package implements Hyva\Ai\Api\StreamDialectInterface, registered in Hyva\Ai\Model\Provider\StreamDialectPool.dialects. |
| PHP image adapters | Provider package implements Hyva\Ai\Api\ImageDialectInterface, registered in Hyva\Ai\Model\Provider\ImageDialectPool.dialects. |
| Image choices | Provider-owned Hyva\Ai\Model\ImageModelRegistry.models; a matching runtime image adapter is still required. |
| Signed provider options | Hyva\AiWorker\Model\TokenIssuer.providerConfigKeys allowlist. |
| Job labels | EntityLabelProviderInterface through Model\Job\EntityLabelResolver. |
| Job completion/failure | Observe hyva_ai_worker_job_status_change with job_id and status. |
| Session decoration | Preference/plugin on SessionIssuerInterface. |
PHP provider adapters belong to their provider package, under Model/Worker/. Base AI owns
the contracts and registries, so a provider can be installed without AI Worker. The PHP worker
owns orchestration and transport; it reads installed registrations instead of naming providers.
OpenAI uses base AI's shared Chat Completions wire helpers.
A new external provider dialect also needs an adapter in worker.js: Node/Cloudflare cannot
load Magento PHP classes. Shared fixtures check the PHP and JavaScript implementations against
the same request/result contract. Registering a model or API key alone does not add an adapter. Keep the runtime a single dependency-free file, bump its version and Magento's required version together, and deploy both sides. Consult Hyva_AiWorkerCms for context building, validation, review and draft saving.