# Programmatic Control

> Drive agent runs from code in a React Native app, with no chat UI required.

## What is this? [#what-is-this]

Programmatic control is what you reach for when you want to drive an agent run from code rather than from a chat composer: a button, a form, a push notification, a voice transcript, or a background task. CopilotKit gives you three primitives that cover every trigger:

- `agent.addMessage(...)`: add a message to the conversation without running the agent. Pair it with `copilotkit.runAgent({ agent })` when the message should start a turn.
- `copilotkit.runAgent({ agent })`: the same entry point the prebuilt chat calls. It runs frontend tools, follow-up runs, and the subscriber lifecycle.
- `agent.subscribe(subscriber)`: a low-level AG-UI event subscription (`onCustomEvent`, `onRunStartedEvent`, `onRunFinalized`, `onRunFailed`, and more). Use it with `copilotkit.runAgent({ agent, resume })` for standard AG-UI interrupts, or with `copilotkit.runAgent({ agent, forwardedProps: { command: { resume, interruptEvent } } })` for the `on_interrupt` custom events that the LangGraph adapter sends.

## When should I use this? [#when-should-i-use-this]

Use programmatic control when you want to:

- Start agent runs from buttons, forms, or other views
- Run one of your frontend tools directly, without an LLM turn
- Build agent features without a chat screen (to build your own chat, see [Headless UI](/react-native/google-adk/custom-look-and-feel/headless-ui))
- Read agent state and results from code
- Send a speech-to-text transcript as a user turn

## Sending a message from code [#sending-a-message-from-code]

<Steps>
  <Step>
    ### Install the ADK + AG-UI bridge

    ```bash
    pip install ag-ui-adk
    ```

  </Step>
  <Step>
    ### Add `AGUIToolset()` to your agent

    Programmatic control (`copilotkit.runAgent`, `agent.subscribe`,
    `agent.addMessage`) drives runs through the same agent your chat UI
    uses, so the backend wiring is the same — wire `AGUIToolset()` once and
    every entry point sees the same forwarded tools and state.

~~~~python title="hitl_in_chat_agent.py"
from google.adk.agents import LlmAgent
from ag_ui_adk import AGUIToolset

from agents.shared_chat import get_model, stop_on_terminal_text

# CopilotKit wires into ADK via the `AGUIToolset()` tool: pass it in the
# `tools=` list of your `LlmAgent` to expose CopilotKit's frontend-tool
# channel to the model. `stop_on_terminal_text` is a small ADK callback
# that lets CopilotKit's UI know when the agent has finished its turn.
_INSTRUCTION = (
    "You are a planning assistant. When the user asks you to plan something, "
    "always call generate_task_steps with the proposed list of steps (each "
    "with description + status='enabled'). The frontend will render the "
    "steps inline and the user will confirm or reject — your job is to plan "
    "and call the tool, then summarise the user's decision once they "
    "respond."
)

hitl_in_chat_agent = LlmAgent(
    name="HitlInChatAgent",
    model=get_model(),
    instruction=_INSTRUCTION,
    tools=[AGUIToolset()],
    after_model_callback=stop_on_terminal_text,
)
~~~~

    ADK doesn't ship a native `interrupt(...)` primitive — for the headless
    interrupt-resolver pattern, use the frontend `useFrontendTool`
    Promise-based handler instead.

  </Step>
</Steps>

Add a user message with `agent.addMessage`, then call `copilotkit.runAgent({ agent })`. Call `copilotkit.stopAgent({ agent })` to cancel a run in flight.

```tsx title="src/AgentTrigger.tsx"
import { Button, Text, View } from "react-native";
import { useAgent, useCopilotKit } from "@copilotkit/react-native/headless";

export function AgentTrigger({ agentId }: { agentId: string }) {
  const { agent } = useAgent({ agentId });
  const { copilotkit } = useCopilotKit();

  const run = async () => {
    if (agent.isRunning) return;

    agent.addMessage({ // [!code highlight:5]
      id: `user-${Date.now()}`,
      role: "user",
      content: "Summarize the latest sales data",
    });

    try {
      await copilotkit.runAgent({ agent }); // [!code highlight]
    } catch (error) {
      console.error("CopilotKit runAgent failed:", error);
    }
  };

  const last = agent.messages[agent.messages.length - 1];

  return (
    <View>
      <Button title="Run agent" onPress={run} disabled={agent.isRunning} />
      <Button
        title="Stop"
        onPress={() => copilotkit.stopAgent({ agent })}
        disabled={!agent.isRunning}
      />
      {last?.role === "assistant" && last.content ? <Text>{last.content}</Text> : null}
    </View>
  );
}
```

Tap **Run agent**. The agent's reply streams into `agent.messages`, and the last assistant message shows under the buttons.

The message id comes from a timestamp. The React Native polyfills install `crypto.getRandomValues`, not `crypto.randomUUID`.

### `copilotkit.runAgent()` vs `agent.runAgent()` [#copilotkitrunagent-vs-agentrunagent]

Both methods start the agent, but they work at different levels:

- **`copilotkit.runAgent({ agent })`**: the default. It runs the full lifecycle: it executes frontend tools, handles follow-up runs, and sends errors to the subscriber system and the provider's `onError`.
- **`agent.runAgent(options)`**: the low-level method on the agent instance. It sends the request to the runtime but does **not** execute frontend tools or chain follow-ups. Use it only when you need direct control.

## Running a tool without the model [#running-a-tool-without-the-model]

`copilotkit.runTool()` runs a registered frontend tool directly. The handler runs, the tool's `render` shows in the chat, and both the tool call and its result are added to `agent.messages`. No LLM turn happens unless you ask for one.

```tsx
const { copilotkit } = useCopilotKit();

const { result, error } = await copilotkit.runTool({
  name: "filter_tasks",
  parameters: { status: "open" },
  // false (default): no follow-up. "generate": the agent responds to the result.
  followUp: false,
});
```

The tool must be registered with `useFrontendTool` somewhere under the provider. See [Frontend Tools](/react-native/google-adk/frontend-tools).

## Subscribing to agent events [#subscribing-to-agent-events]

`agent.subscribe(subscriber)` returns `{ unsubscribe }`. The subscriber accepts every AG-UI lifecycle callback: `onCustomEvent`, `onRunStartedEvent`, `onRunFinalized`, `onRunFailed`, and the streaming deltas. Use it to drive your own progress UI, to send events to analytics, or to catch pause and resume events and answer them, as shown below.

Subscribe in an effect and unsubscribe in its cleanup:

```tsx
import { useEffect } from "react";

useEffect(() => {
  const { unsubscribe } = agent.subscribe({
    onRunStartedEvent: () => setStatus("working"),
    onRunFinalized: () => setStatus("done"),
    onRunFailed: () => setStatus("failed"),
  });
  return unsubscribe;
}, [agent]);
```

`useAgent` can swap in a new `agent` object once the runtime connects, so keep `agent` in the effect's dependencies.

## Resolving a pause from a button [#resolving-a-pause-from-a-button]

> **Interrupt-style pause and resume isn't available on this framework.** The headless interrupt pattern needs a runtime with a native `interrupt(...)` primitive (LangGraph) or a Promise-resolving frontend-tool path. For all other integrations, pause with [`useHumanInTheLoop`](/react-native/google-adk/human-in-the-loop) instead. It works on every framework that supports tool calls. The `agent.addMessage`, `copilotkit.runAgent`, and `agent.subscribe` primitives above still apply. Only the interrupt path depends on the framework.

For every method on the core, see the [`useCopilotKit` reference](/reference/react-native/hooks/useCopilotKit).

<IntegrationGrid path="programmatic-control" />
