WU / DOCSUNIVERSAL MICROFRONTENDS
EN

AI, context, and workflow reference

Providers, conversations, actions, orchestration, permissions, and AI subsystem cleanup.

Preparing an AI instance

Obtain const ai = await wu.aiReady() before configuring the subsystem. Only WuAI is a public export of wu-framework/ai; context, conversation, and permissions expose specific methods, not unrestricted access to their internal classes.

For conversation examples, first configure a demo provider with custom transport or a server proxy. Handle action responses with success:false even if the promise resolves. Result names in signatures describe data structures and do not promise additional TypeScript exports.

AI policy and core grants serve different purposes. Deterministic workflows execute host primitives directly; they are not an API for granting execution to third-party code. See the AI and MCP recipe for guided integration.

wu.aiReady

Loads the optional subsystem and returns an instance ready to configure.

wu.aiReady(): Promise<WuAI>

  • Parameters: Importing wu-framework/ai is unnecessary when using the core facade.
  • Returns: Promise of the WuAI instance.
  • Errors: Rejects if the optional module cannot be imported.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
const ai = await wu.aiReady();
ai.init({ permissions: { executeActions: false } });

For immediate reads, await aiReady: the lazy facade may return initial values before loading finishes.

Reference: src/index.js.

WuAI

Creates the AI coordinator with explicit dependencies.

new WuAI({ eventBus, store, core?, token? })

  • Parameters: eventBus and store shared with the host; core allows querying apps.
  • Returns: Instance not yet initialized.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
import { WuAI } from 'wu-framework/ai';
const ai = new WuAI({ eventBus: wu.eventBus, store: wu.store, core: wu });
ai.init();

Reference: src/ai/wu-ai.js.

ai.init

Initializes providers, conversations, actions, context, and execution protection.

ai.init(config?): WuAI

  • Parameters: permissions, context, conversation, triggers, agent, orchestrate, rateLimit, circuitBreaker, loopProtection, allowedDomains, and browser. Register the provider separately with ai.provider(name, config).
  • Returns: The same instance; subsequent calls reconfigure supported options.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
const ai = await wu.aiReady();
ai.init({ permissions: { executeActions: true, network: false }, allowedDomains: [] });

Declared authorization does not isolate JavaScript captured by a custom handler: host code remains trusted.

Reference: src/ai/wu-ai.js.

ai.provider

Registers a built-in provider or custom transport functions.

ai.provider(name, config): WuAI

  • Parameters: name; adapter, endpoint, model, active; or custom send/stream. Use a server proxy for credentials.
  • Returns: The same instance.
  • Errors: Throws if the adapter is unrecognized and send/stream are absent. A direct API key is removed by default when production is detected.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
ai.provider('demo', {
  send: async () => ({ content: 'Respuesta determinista', usage: {} }),
});
const result = await ai.send('Hola', { provider: 'demo' });

Custom transport is privileged host code, not a way to prove network isolation.

Reference: src/ai/wu-ai.js.

ai.send

Sends a message and processes tools requested by the provider.

ai.send(message, options?): Promise<ConversationResponse>

  • Parameters: message string; namespace, provider, systemPrompt, templateVars, temperature, maxTokens, responseFormat, and signal.
  • Returns: Response with content, namespace, and available results/usage. Denied preflight resolves content:“[blocked] …”; cancellation resolves content:“[aborted]”.
  • Errors: Provider errors normally reject; preflight blocking and AbortError are represented as resolved responses with a content marker.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: ai.abort(namespace) interrupts that conversation; clear removes history, deleteNamespace removes and aborts.
const response = await ai.send('Resume el estado', { namespace: 'help', provider: 'demo' });
console.log(response.content);

Reference: src/ai/wu-ai.js.

ai.stream

Delivers text and tool events incrementally.

ai.stream(message, options?): AsyncGenerator<StreamChunk>

  • Parameters: Same conversation options as send; the provider must support streaming.
  • Returns: Async iterator with chunks typed by type.
  • Errors: Provider errors and abort are emitted as type:“error” chunks. Building systemPrompt happens before the try and may reject iteration.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
for await (const chunk of ai.stream('Explica el estado', { namespace: 'help' })) {
  if (chunk.type === 'text') console.log(chunk.content);
}

Do not assume every chunk contains text: there are tool results, completion, and errors.

Reference: src/ai/wu-ai.js.

ai.json

Requests JSON output and separates received text from the parsed result.

ai.json(message, options?): Promise<JsonResponse>

  • Parameters: Optional schema/schemaName, plus send options.
  • Returns: {data, raw, error, usage, namespace}.
  • Errors: Invalid JSON is reported in error with data:null; provider failures may reject.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
const result = await ai.json('Devuelve {"ready":true}', { provider: 'demo' });
if (result.error) console.error(result.error);
else console.log(result.data);

Provider schema support does not replace business validation of the result.

Reference: src/ai/wu-ai.js.

ai.abort

Cancels active requests for one or all conversations.

ai.abort(namespace?): void

  • Parameters: Optional namespace; omitting it aborts all.
  • Returns: void.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Aborting does not delete previous messages; use conversation.clear to empty history too.
ai.abort('help');

Reference: src/ai/wu-ai.js.

ai.action

Registers an executable operation with description, parameters, and handler.

ai.action(name, config): WuAI

  • Parameters: description, parameters, handler; optional confirm, permissions, permissionsWhen, and dangerous.
  • Returns: The same instance.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: executeActions authorizes execution; permissions/permissionsWhen may require additional AI flags.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
ai.action('math.double', {
  description: 'Duplica un número',
  parameters: { type: 'object', properties: { value: { type: 'number' } }, required: ['value'] },
  handler: ({ value }) => value * 2,
});

Reference: src/ai/wu-ai.js.

ai.execute

Executes a registered action through subsystem policy and controls.

ai.execute(actionName, params?): Promise<ActionResult>

  • Parameters: Exact name and argument object.
  • Returns: {success, result?, reason?}; success:false is also a resolved response.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: Requires executeActions and action-specific permissions; may require confirmation.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
const result = await ai.execute('math.double', { value: 21 });
if (!result.success) throw new Error(result.reason);
console.log(result.result);

Reference: src/ai/wu-ai.js.

ai.trigger

Connects an event pattern to an assistant request.

ai.trigger(name, config): WuAI

  • Parameters: pattern, prompt; optional condition, debounce, priority, and onResult.
  • Returns: The same instance.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: ai.destroy() removes trigger-created subscriptions.
ai.trigger('cart-help', {
  pattern: 'cart:help',
  prompt: 'Explica cómo revisar este carrito',
  debounce: 500,
  onResult: (response) => console.log(response.content),
});

Use condition and debounce to limit activations; do not publish sensitive data in events intended for context.

Reference: src/ai/wu-ai.js.

ai.fireTrigger

Explicitly requests execution of a registered trigger.

ai.fireTrigger(name, data?): Promise<unknown>

  • Parameters: Name and data received by its prompt/condition configuration.
  • Returns: Asynchronous execution result, or no result when skipped.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
await ai.fireTrigger('cart-help', { itemCount: 2 });

Reference: src/ai/wu-ai.js.

ai.agent

Runs a step loop that can inspect context and call actions.

ai.agent(goal, options?): AsyncGenerator<AgentStep>

  • Parameters: goal string; agent options such as maxSteps, namespace, provider, and signal.
  • Returns: Step iterator, not a single text response.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: Actions remain subject to executeActions and their flags. Limiting maxSteps grants no permissions.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
for await (const step of ai.agent('Explica las acciones disponibles', { maxSteps: 3 })) {
  console.log(step);
}

Reference: src/ai/wu-ai.js.

ai.capability

Registers an action under an application’s functional identity for orchestration.

ai.capability(appName, actionName, config): WuAI

  • Parameters: appName, actionName, and action configuration with description, parameters, and handler.
  • Returns: The same instance.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
ai.capability('calculator', 'double', {
  description: 'Duplica un número',
  parameters: { value: { type: 'number', required: true } },
  handler: ({ value }) => value * 2,
});

Here capability means an action published to the orchestrator. It does not create a core events.emit/rpc.call/store.write grant.

Reference: src/ai/wu-ai.js.

ai.intent

Resolves an intent using capabilities registered by applications.

ai.intent(description, options?): Promise<IntentResult>

  • Parameters: Description and orchestration/provider options.
  • Returns: Result with content, tool_results, usage, resolved, and appsInvolved.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
const result = await ai.intent('Duplica 7 usando calculator');
console.log(result.resolved, result.appsInvolved);

Reference: src/ai/wu-ai.js.

ai.removeApp

Removes AI capabilities associated with an application.

ai.removeApp(appName): WuAI

  • Parameters: Name used when registering capability.
  • Returns: The same instance.
  • Errors: Propagates configuration or execution errors; catch rejections and inspect action results.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Does not unmount the core application or delete its global state.
ai.removeApp('calculator');

Reference: src/ai/wu-ai.js.

ai.workflow

Registers a deterministic action sequence or agent-interpreted steps.

ai.workflow(name, config): WuAI

  • Parameters: Nonempty steps; deterministic mode supports click, type, navigate, wait, emit, and setState. AI mode accepts descriptions. Optional parameters, maxSteps, provider, and temperature.
  • Returns: The same instance.
  • Errors: Missing name or empty/invalid steps throw during registration.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
ai.workflow('mark-ready', {
  mode: 'deterministic',
  steps: [{ action: 'setState', path: 'workflow.ready', value: true }],
});

Deterministic steps are host primitives and do not call actions registered with ai.action. They execute directly, without ai.execute or its permission checks.

Reference: src/ai/wu-ai.js.

ai.runWorkflow

Runs a workflow and emits step progress.

ai.runWorkflow(name, params?, options?): AsyncGenerator<WorkflowStep>

  • Parameters: Registered name, parameters required by workflow.parameters, and execution options.
  • Returns: Async result iterator.
  • Errors: Unknown workflow or missing required parameter rejects during iteration.
  • Permissions: AI mode controls tool calls; deterministic mode executes host primitives directly and does not apply ai.permissions flags. Accept only trusted workflows and parameters.
  • Cleanup: Call ai.destroy() when the owning runtime ends.
for await (const step of ai.runWorkflow('mark-ready')) console.log(step);

Reference: src/ai/wu-ai.js.

ai.context.configure

Configures context selection and budget.

ai.context.configure(config): void

  • Parameters: budget, charRatio, and sources with store, events, and custom.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.context.configure({ budget: 1500, sources: { store: { include: ['cart'] } } });

Reference: src/ai/wu-ai.js.

ai.context.register

Adds a custom context collector.

ai.context.register(name, config): void

  • Parameters: Name and {collector,priority}; collector may be asynchronous.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.context.register('build', { collector: () => ({ release: 'demo' }), priority: 'high' });

Reference: src/ai/wu-ai.js.

ai.context.collect

Collects apps, state, events, and configured collectors.

ai.context.collect(): Promise<ContextSnapshot>

  • Parameters: No parameters.
  • Returns: Promise
  • Errors: Individual collector failures are logged and do not stop the others.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
await ai.context.collect();

Reference: src/ai/wu-ai.js.

ai.context.getSnapshot

Returns the last collected context without querying sources again.

ai.context.getSnapshot(): ContextSnapshot | null

  • Parameters: No parameters.
  • Returns: ContextSnapshot | null
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.context.getSnapshot();

Reference: src/ai/wu-ai.js.

ai.conversation.getHistory

Reads a conversation’s history.

ai.conversation.getHistory(namespace?): Message[]

  • Parameters: Namespace; default when omitted.
  • Returns: Message[]
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.conversation.getHistory('help');

Reference: src/ai/wu-ai.js.

ai.conversation.clear

Empties a conversation’s messages.

ai.conversation.clear(namespace?): void

  • Parameters: Namespace; not equivalent to aborting an active request.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.conversation.clear('help');

Reference: src/ai/wu-ai.js.

ai.conversation.clearAll

Empties messages in every existing namespace.

ai.conversation.clearAll(): void

  • Parameters: No parameters.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.conversation.clearAll();

Reference: src/ai/wu-ai.js.

ai.conversation.inject

Adds a history message without sending it to the provider.

ai.conversation.inject(role, content, options?): void

  • Parameters: role, content, and {namespace}.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.conversation.inject('user', 'Necesito ayuda con el catálogo', { namespace: 'help' });

Reference: src/ai/wu-ai.js.

ai.conversation.getNamespaces

Lists created conversations.

ai.conversation.getNamespaces(): string[]

  • Parameters: No parameters.
  • Returns: string[]
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.conversation.getNamespaces();

Reference: src/ai/wu-ai.js.

ai.conversation.deleteNamespace

Aborts and deletes a namespace.

ai.conversation.deleteNamespace(namespace): void

  • Parameters: Exact name.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.conversation.deleteNamespace('help');

Reference: src/ai/wu-ai.js.

ai.permissions.configure

Updates recognized AI boolean flags.

ai.permissions.configure(flags): void

  • Parameters: Flag object; ignores unknown names and nonboolean values.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.permissions.configure({ executeActions: true, network: false });

Reference: src/ai/wu-ai.js.

ai.permissions.check

Checks whether an AI flag is enabled.

ai.permissions.check(permission): boolean

  • Parameters: Permission name; unknown produces false.
  • Returns: boolean
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.permissions.check('executeActions');

Reference: src/ai/wu-ai.js.

ai.permissions.getPermissions

Returns a copy of AI flags.

ai.permissions.getPermissions(): Record<string, boolean>

  • Parameters: No parameters.
  • Returns: Record<string, boolean>
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.permissions.getPermissions();

A flag copy does not authorize a scoped application.

Reference: src/ai/wu-ai.js.

ai.permissions.setAllowedDomains

Replaces allowed domains for AI-controlled transport.

ai.permissions.setAllowedDomains(domains): void

  • Parameters: String list; filters invalid entries.
  • Returns: void
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.permissions.setAllowedDomains(["api.example.com"]);

Reference: src/ai/wu-ai.js.

ai.tools

Describes actions in tool format.

ai.tools(): ToolSchema[]

  • Parameters: No parameters.
  • Returns: ToolSchema[]
  • Errors: May initialize the subsystem if not ready; read-only methods do not request the provider.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.tools();

Reference: src/ai/wu-ai.js.

ai.expose

Registers actions in navigator.modelContext when the browser offers it.

ai.expose(): Promise<boolean>

  • Parameters: No parameters; experimental WebMCP integration.
  • Returns: Promise
  • Errors: Returns false without navigator.modelContext; catches individual registration errors. true does not guarantee all tools were registered.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
await ai.expose();

Reference: src/ai/wu-ai.js.

ai.confirmTool

Accepts a pending tool confirmation.

ai.confirmTool(confirmationId): void

  • Parameters: Identifier emitted by the confirmation flow.
  • Returns: void
  • Errors: Returns without initializing an uninitialized instance; makes no provider request.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.confirmTool(confirmationId);

Reference: src/ai/wu-ai.js.

ai.rejectTool

Rejects a pending tool confirmation.

ai.rejectTool(confirmationId): void

  • Parameters: Identifier emitted by the confirmation flow.
  • Returns: void
  • Errors: Returns without initializing an uninitialized instance; makes no provider request.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.rejectTool(confirmationId);

Reference: src/ai/wu-ai.js.

ai.getStats

Summarizes AI coordinator modules and counters.

ai.getStats(): object

  • Parameters: No parameters.
  • Returns: {initialized:false} or an object with initialized:true and module statistics.
  • Errors: Returns {initialized:false} when uninitialized; does not initialize modules.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The coordinator owner calls ai.destroy() on closure.
ai.getStats();

Reference: src/ai/wu-ai.js.

ai.destroy

Aborts conversations, removes triggers, and releases coordinator modules.

ai.destroy(): void

  • Parameters: No parameters.
  • Returns: void
  • Errors: Returns without initializing an uninitialized instance; makes no provider request.
  • Permissions: AI policy is independent of microfrontend grants. Configure only necessary operations.
  • Cleanup: The object can be initialized again; resources from the previous execution are released.
ai.destroy();

Reference: src/ai/wu-ai.js.

In 4.0 deterministic workflows, emit steps require emitEvents and cannot target wu:, system: or app: events. setState steps require writeStore. These flags remain host AI controls, independent of apps’ technical grants.

BUILD WU WITH US

Found a bug? Have an idea?

Your experience improves WU. Tell us what went wrong or help support its development.