docs: give GDK its own navigation and developer guides (#13165)

This commit is contained in:
Douwe Osinga
2026-10-29 21:29:35 +00:00
committed by GitHub
parent 361003ea32
commit 9fbb9a48e1
56 changed files with 3066 additions and 633 deletions
+150 -76
View File
@@ -1,104 +1,178 @@
---
sidebar_position: 1
title: Use goose as an ACP agent
sidebar_label: Overview
description: Build clients that connect to goose over stdio, HTTP, or WebSocket.
title: Build an app with goose
sidebar_label: Build an app with goose
description: Launch goose from your application, send prompts, and stream responses over ACP.
displayed_sidebar: gdkSidebar
---
# Use goose as an ACP agent
# Build an app with goose
Use the [Agent Client Protocol (ACP)](https://agentclientprotocol.com/) to build
clients that connect to goose's agent runtime, tools, extensions, and configured
models. These clients can be code editors, desktop, web, or mobile apps,
automated services, or other custom integrations.
If your application needs an agent, you do not have to assemble one from GDK
components. You can launch the pre-built goose binary and talk to it over the
[Agent Client Protocol (ACP)](https://agentclientprotocol.com/).
For methods provided by goose in addition to the standard ACP methods, see the
[goose ACP Reference](/docs/gdk/acp/reference).
Your application owns the interface and workflow. goose supplies the agent,
model connections, tools, and saved conversations. ACP connects them: your app
sends prompts and receives streamed responses, tool activity, and permission
requests. This is also how goose Desktop talks to its backend.
## Install
Choose one installation method based on how your ACP client runs goose.
### Install the goose CLI
Install the [goose CLI](/docs/getting-started/installation) to configure a client
to launch `goose acp` or to run `goose serve` yourself.
### Install from the ACP Registry
Supported ACP clients can install and manage goose for you through the
[goose entry in the ACP Registry](https://agentclientprotocol.com/get-started/registry#goose).
This does not require a separate goose CLI installation.
## Run the agent
### Connect over stdio
Configure your ACP client to launch goose as a subprocess with this command:
The example below uses Node.js 22 or later and the
[ACP TypeScript SDK](https://github.com/agentclientprotocol/typescript-sdk),
with JavaScript so it can run without a build step. Install the
[goose CLI](/docs/getting-started/installation) and configure a
[model provider](/docs/getting-started/providers) first. Use a working directory
and configured tools appropriate for the access you want the agent to have.
```bash
goose acp
npm install @agentclientprotocol/sdk@1.5.0
```
The client communicates with goose through stdin and stdout and manages the
process for the lifetime of the connection.
Put the following three JavaScript blocks, in order, in a file named `app.mjs`.
### Connect over HTTP or WebSocket
## Connect over stdio
Run `goose serve` when your ACP client connects over HTTP or WebSocket:
Launch `goose acp` as a subprocess. Its stdin and stdout carry ACP messages;
stderr is for logs. The SDK turns those pipes into a bidirectional connection.
```javascript
import { spawn } from "node:child_process";
import { Readable, Writable } from "node:stream";
import * as acp from "@agentclientprotocol/sdk";
const goose = spawn("goose", ["acp"], {
stdio: ["pipe", "pipe", "inherit"],
});
const stream = acp.ndJsonStream(
Writable.toWeb(goose.stdin),
Readable.toWeb(goose.stdout),
);
```
Your application manages the process lifetime. Keep it running while the user
works with the agent, and close the connection and process when finished.
## Stream updates into your interface
Register handlers before sending a prompt. While a turn is running, goose sends
`session/update` notifications with the session ID and an update payload.
Append text chunks as they arrive, and use tool call IDs to update the matching
tool activity in your interface.
```javascript
const app = acp
.client({ name: "my-app" })
.onNotification(acp.methods.client.session.update, ({ params }) => {
const update = params.update;
if (
update.sessionUpdate === "agent_message_chunk" &&
update.content.type === "text"
) {
process.stdout.write(update.content.text);
} else if (update.sessionUpdate === "tool_call") {
console.error(`Tool: ${update.title} (${update.toolCallId})`);
} else if (update.sessionUpdate === "tool_call_update") {
console.error(`Tool ${update.toolCallId}: ${update.status}`);
}
})
.onRequest(acp.methods.client.session.requestPermission, () => ({
outcome: { outcome: "cancelled" },
}));
```
This example cancels permission requests rather than automatically approving
them. In your app, show the supplied choices to the user and return their
selection. Permission callbacks are not a sandbox: goose's configured mode
determines when approval is requested, and its tools run with the backend's
access to the machine.
## Create a session and send a prompt
Initialize the connection to negotiate the protocol version and capabilities.
Then create a session with an absolute working directory on the machine running
goose. The returned session ID identifies the conversation for subsequent
prompts and notifications.
```javascript
try {
const result = await app.connectWith(stream, async (agent) => {
const initialized = await agent.request(acp.methods.agent.initialize, {
protocolVersion: acp.PROTOCOL_VERSION,
clientCapabilities: {},
});
if (initialized.protocolVersion !== acp.PROTOCOL_VERSION) {
throw new Error("Unsupported ACP protocol version");
}
const session = await agent.request(acp.methods.agent.session.new, {
cwd: process.cwd(),
mcpServers: [],
});
return agent.request(acp.methods.agent.session.prompt, {
sessionId: session.sessionId,
prompt: [{ type: "text", text: "Say hello in one sentence." }],
});
});
console.log(`\nTurn finished: ${result.stopReason}`);
} finally {
goose.kill();
}
```
Run it from the directory you want the session to work in:
```bash
GOOSE_SERVER__SECRET_KEY='a-long-random-secret' goose serve
node app.mjs
```
`GOOSE_SERVER__SECRET_KEY` sets the secret your clients use to authenticate.
When you run `goose serve` directly, it listens on `127.0.0.1:3284` and exposes
the ACP endpoint at `/acp`. To use a different address, pass `--host` and
`--port`.
The prompt response reports why the turn stopped; the assistant's text arrives
through notifications while that request is pending. Do not wait for the prompt
response before displaying output. One turn may include several model calls
and tool calls before it completes.
#### Authentication
`connectWith` closes the connection when its callback finishes. This example
ends after one prompt; an interactive app keeps that callback running, or uses
the SDK's `connect` API to manage a longer-lived connection.
HTTP clients authenticate with the `X-Secret-Key` header. WebSocket clients can
use the same header, but browser-based WebSocket clients must pass the secret in
the `?token=` query parameter. Requests without the correct secret receive a
`401 Unauthorized` response.
## Keep the conversation going
:::warning Local development only
Passing `--dangerously-unauthenticated` starts `goose serve` without
authentication. Use it only when the server is isolated from untrusted traffic.
:::
Send follow-up prompts with the same session ID to retain context. Create a new
session for a separate conversation. Route updates by session ID if your
application supports more than one conversation.
#### Browser origins
To resume after reconnecting, save the session ID and working directory. Check
the `loadSession` capability returned by initialization, then use `session/load`.
History is replayed through the same notification handler. A stop button sends
`session/cancel` for the active turn rather than killing the backend.
Most clients do not need to configure origins. Browser-based clients served from
a non-loopback origin must allow that origin when starting goose. To allow both
a local development client and a deployed web client, specify both origins:
## Use a server instead
If a subprocess is not the right fit, `goose serve` exposes ACP over HTTP and
WebSocket. Your app uses the same session and prompt concepts through a
different transport.
```bash
GOOSE_SERVER__SECRET_KEY='a-long-random-secret' goose serve \
--allowed-origin 'http://localhost:5173' \
--allowed-origin 'https://app.example'
GOOSE_SERVER__SECRET_KEY='replace-with-a-long-random-secret' goose serve
```
Specifying any `--allowed-origin` values replaces the default loopback origins,
so include every origin your clients need, including localhost origins used for
development. Origins must match exactly, including the scheme and port.
By default, the endpoint is `http://127.0.0.1:3284/acp` (or `ws://` for
WebSocket). Authenticate with `X-Secret-Key`, or the `token` query parameter
when a browser WebSocket cannot set that header. Keep the backend secret out of
public frontend code. Browser origins may also need to be allowed explicitly.
For remote deployment, TLS, and certificate setup, see
[Running a Remote goose Server](/docs/guides/remote-goose-server).
Run `goose serve --help` for the complete list of options.
See the [server command options](/docs/guides/goose-cli-commands#serve-options)
for authentication and origin flags, and the
[remote server guide](/docs/guides/remote-goose-server) for deployment and TLS.
## ACP client examples
## Examples and reference
### Clients over stdio
Browse the [official ACP clients directory](https://agentclientprotocol.com/get-started/clients)
for clients that can run local ACP agents. For a worked example of installing
and configuring goose as a stdio agent, see the
[Zed setup example](/docs/gdk/acp/zed).
### goose Desktop over WebSocket
[goose Desktop](https://github.com/aaif-goose/goose/tree/main/ui/desktop) is an
ACP client that uses WebSocket. It starts `goose serve` locally on an available
loopback port and connects to its `/acp` endpoint over WebSocket.
- [Top Goose](/docs/gdk/demos/top-goose) maps GitHub issues and pull requests to
persistent conversations with a `goose acp` subprocess.
- [Berd](/docs/gdk/demos/berd) builds a custom desktop interface around a bundled
`goose serve` backend over WebSocket.
- The [ACP protocol reference](https://agentclientprotocol.com/protocol/v1/overview)
defines initialization, sessions, prompts, updates, permissions, and cancellation.
- The [goose ACP reference](/docs/gdk/acp/reference) documents goose-specific
methods and types.
@@ -0,0 +1,112 @@
---
title: Authentication
description: Supply credentials to model providers without coupling the agent runtime to a login flow or secret store.
displayed_sidebar: gdkSidebar
---
# Authentication
A provider needs a way to authenticate requests to its backend. Where the
credential comes from is an application decision: an environment variable, a
secret store, an existing user login, or an organization-specific credential
service. That choice should not require changing the agent's operations or
conversation format.
GDK separates the HTTP authentication mechanism from the provider's request
format. `ApiClient` accepts an `AuthMethod`; a custom method can ask your
application for the current credential whenever it prepares a request. Provider
implementations can also have their own authentication flows where a service
requires them.
## Authentication mechanisms
The following mechanisms are defined in `goose-providers::api_client`:
| Mechanism | Use |
| ------------------------- | ------------------------------------------------------------------------------------ |
| `AuthMethod::NoAuth` | An endpoint that needs no authentication, such as a suitably isolated local service. |
| `AuthMethod::BearerToken` | A token sent in the `Authorization: Bearer ...` header. |
| `AuthMethod::ApiKey` | A credential sent under a specified header name. |
| `AuthMethod::Custom` | An `AuthProvider` that supplies a header name and value at request time. |
For example, an application can pass a key directly rather than rely on the
goose CLI configuration:
```rust
let client = ApiClient::new_with_tls(
"https://api.openai.com".into(),
AuthMethod::BearerToken(std::env::var("OPENAI_API_KEY")?),
None,
)?;
```
This configures how the credential is sent; it does not install a secret store
or start a login flow. The TLS argument is separate from HTTP authentication.
Use a TLS-enabled build for HTTPS, and supply `TlsConfig` if your environment
requires custom certificate authorities or a client certificate.
## Provider-specific and declarative authentication
The Databricks implementation supports token and OAuth configurations through
`DatabricksAuth`. Its auth provider accepts application-supplied callbacks for
obtaining tokens; GDK does not assume every host has the same browser login or
credential storage.
[Declarative providers](/docs/gdk/concepts/providers#declarative-providers) can
name an API-key variable and resolve it through `KeyResolver`. The supplied
`EnvKeyResolver` uses the process environment. A definition can alternatively
configure a command that obtains a credential, with caching and refresh
settings. Those commands are executable configuration, so only load definitions
you trust.
## Supplying your own authentication
Use `AuthProvider` when the credential can change during the application's
lifetime or comes from a source the built-in mechanisms do not cover. For
example, the host can keep the token from its own login flow in shared state:
```rust
use std::sync::{Arc, RwLock};
use anyhow::Result;
use async_trait::async_trait;
use goose_providers::api_client::AuthProvider;
struct AppAuth {
token: Arc<RwLock<String>>,
}
#[async_trait]
impl AuthProvider for AppAuth {
async fn get_auth_header(&self) -> Result<(String, String)> {
let token = self.token.read().unwrap();
Ok(("Authorization".into(), format!("Bearer {token}")))
}
}
```
Pass it to `ApiClient` as `AuthMethod::Custom(Box::new(AppAuth { token }))`.
The host can update the shared token after login or rotation without rebuilding
the agent. A real credential store can replace the shared string while keeping
the same trait boundary.
`AuthProvider` also has a `refresh_credentials` method. Its default reports that
refresh is unsupported; implement it when your flow can refresh credentials.
The provider or application decides when to invoke it. A custom header callback
alone does not implement OAuth or automatic refresh.
## Keep the boundaries separate
Credentials should not be part of the conversation, prompts, tool output, or
saved effects. Keep them in the application's credential handling, and avoid
logging their values. A working directory is not a boundary around what an
agent or its tools can access.
Authenticating a model request is also different from authenticating a client
connection to goose. If your application uses the pre-built binary over ACP,
the backend's provider credentials belong on the backend; a `goose serve`
connection has its own authentication. See
[Build an app with goose](/docs/gdk/acp#use-a-server-instead) for that path.
The full HTTP authentication and TLS APIs are in
[`goose-providers::api_client`](https://docs.rs/goose-providers/latest/goose_providers/api_client/).
+39
View File
@@ -0,0 +1,39 @@
---
title: Concepts
description: How GDK's state machine, operations, providers, and authentication fit together.
displayed_sidebar: gdkSidebar
---
# Concepts
GDK gives you components for building an agent, rather than one fixed agent
with a set of configuration options. Your application decides what work is
allowed, how state is stored, which models to use, and how the agent interacts
with the outside world.
The execution model is a state machine composed from operations. An operation
can run a tool, add context, enforce a limit, or pause for input. Inference is a
specialized step that reaches a model through a provider. The machine applies
the resulting effects through your runtime, then loads the updated session
before deciding what to do next.
## Start here
- [State machine](/docs/gdk/concepts/state-machine): how the execution cycle
works, what yielding means, and how persistence makes resuming possible.
- [Operations](/docs/gdk/concepts/operations): the units you compose into that
machine, a worked example, the operations available today, and when to write
your own.
- [Providers](/docs/gdk/concepts/providers): the model interface, built-in and
declarative implementations, and the difference between local inference and
talking to a local model server.
- [Authentication](/docs/gdk/concepts/authentication): how a provider gets its
credentials, which mechanisms ship with GDK, and how to supply your own.
Read [Hello World](/docs/gdk/hello-world) for a concrete assembly of these
pieces. These pages explain the design; the [reference](/docs/gdk/reference)
links to the full APIs. Examples here follow the GDK APIs in this checkout
(`0.1.0-alpha.13`); Hello World follows the example's pinned alpha.12 release.
If you want an existing agent behind your own interface instead, you can
[build an app with goose over ACP](/docs/gdk/acp) without assembling the runtime.
@@ -0,0 +1,195 @@
---
title: Operations
description: Compose agent behavior from operations, with a worked example and an inventory of existing implementations.
displayed_sidebar: gdkSidebar
---
# Operations
An operation is a unit of agent behavior. It looks at the current session and
conversation, decides whether it has work to do, and returns effects or yields
control to the caller. The state machine decides when to ask it; the runtime
decides how its effects are stored.
This is broader than a tool. A tool is a capability the model can request, such
as reading a file. An operation decides how the agent proceeds: execute a
pending tool call, require approval, add project context, compact the history,
or stop after a budget is reached. Some operations also provide tools or prompt
content to inference.
## The operation contract
Implement `Operation<S, E>` for your session type `S` and effect type `E`. Its
main entry point, `run`, receives the loaded session, conversation, and emitter.
The result controls what the machine does next:
| Result helper | Meaning |
| ----------------------- | ----------------------------------------------------------------------------- |
| `not_applicable()` | This operation has nothing to do; try the next step. |
| `applied(effects)` | Apply these effects, reload the session, and start again from the first step. |
| `yielded()` | Return control to the caller without adding effects. |
| `yielded_with(effects)` | Save these effects, then return control to the caller. |
Operations can implement `inference_tools` to advertise tools, `prompt_parts`
to contribute system-prompt sections, and `moim_parts` for context the request
preparer can place near the current turn. These contributions are collected
before inference, independently of which operation last applied. The request
preparer decides how to use them.
An `Inference` also implements `Operation`, but is placed in `Step::Inference`
so the machine calls its inference methods and gathers those contributions.
An ordinary operation does not have to call a model at all.
## Worked example: a turn budget
Suppose an application should allow at most three assistant turns for each
user request. Once the current tool results have been saved, it should hand
control back to the user instead of making another model call.
We can implement this without changing inference or the state machine. This
native Rust operation works with any session and any effect type that can
represent a `Message`:
```rust
use anyhow::Result;
use async_trait::async_trait;
use goose_agent::operation::{
assistant_turn_count, ends_turn, messages_since_kickoff,
not_applicable, yielded_with, Emitter, Operation, OperationResult,
};
use goose_provider_types::conversation::{message::Message, Conversation};
struct TurnLimit {
max_turns: u32,
}
#[async_trait]
impl<S, E> Operation<S, E> for TurnLimit
where
S: Send + Sync,
E: From<Message> + Send + 'static,
{
fn name(&self) -> &'static str {
"turn_limit"
}
async fn run(
&self,
_session: &S,
conversation: &Conversation,
emit: &Emitter,
) -> Result<OperationResult<E>> {
let messages = messages_since_kickoff(conversation)?;
if ends_turn(messages) || assistant_turn_count(messages) < self.max_turns {
return not_applicable();
}
let message = Message::assistant()
.with_text("I've reached this request's turn limit. Would you like me to continue?");
yielded_with([emit.message(message).into()])
}
}
```
`messages_since_kickoff` selects the current user request and the messages that
follow it. `assistant_turn_count` counts assistant message blocks, rather than
individual streamed chunks. The operation declines when the agent has already
finished naturally or is still within budget. Otherwise, it emits a visible
message and returns that same message as an effect to be saved before yielding.
Add it after the tool operation and before inference in your assembly:
```rust
let machine = StateMachine::new(
vec![
Step::Operation(Arc::new(tools)),
Step::Operation(Arc::new(TurnLimit { max_turns: 3 })),
Step::Inference(Arc::new(inference)),
],
cancel,
);
```
Here `tools`, `inference`, and the runtime come from your agent assembly, as in
[Hello World](/docs/gdk/hello-world). The ordering is intentional: a tool request
from the third assistant turn still gets a response. After that response is
saved, the budget operation yields before a fourth inference call can start.
Putting the limit before tools would stop earlier but could leave unanswered
tool calls that need separate handling.
When the user sends a new message, it becomes the next kickoff and the count
starts again. No mutable counter needs to survive a restart. This is a limit
on assistant turns, not a dollar, token, or tool-call budget. The complete goose
application has its own `MaxTurnsOperation` with additional prompt context.
## Operations available today
### Reusable GDK components
These are public APIs in `goose-agent`; your application supplies the required
tools, provider, or subagent runner:
| Component | Purpose |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| [`ToolOperation`](https://docs.rs/goose-agent/latest/goose_agent/tool/struct.ToolOperation.html) | Advertise and execute typed synchronous or asynchronous tools, or tools supplied dynamically by a `ToolProvider`. |
| [`SubagentOperation`](https://docs.rs/goose-agent/latest/goose_agent/subagent/struct.SubagentOperation.html) | Run requested subagent sessions through your `SubagentRunner`, deliver their updates, and handle concurrency and cancellation. |
| [`InferenceRunner`](https://docs.rs/goose-agent/latest/goose_agent/inference/struct.InferenceRunner.html) | Prepare provider requests, stream inference, and return message and usage effects. Register it as an inference step. |
### Operations in goose
goose composes a larger agent from the same interfaces. The following are
implementations in the goose application, **not stable, reusable GDK APIs**.
They depend on goose's session, configuration, extensions, and hooks. Use them
as examples of the behavior an operation can own, not as an import list for
your application.
| Operation | Purpose |
| ----------------------------- | ------------------------------------------------------------------------------------------------- |
| `ToolApprovalOperation` | Inspect pending tool requests and record whether they can execute or need approval. |
| `ToolExecutionOperation` | Execute eligible extension tool calls, including tool hooks and streamed output. |
| `RemainingToolCallsOperation` | Answer declined, invalid, or unhandled calls, and yield while approval is pending. |
| `SkillOperation` | Discover and load skills, contribute their context, and handle skill commands. |
| `RecipeOperation` | Apply recipe instructions and tools, handle recipe commands, and collect structured final output. |
| `SteerOperation` | Incorporate queued user guidance between model and tool turns. |
| `BangShellOperation` | Turn a user message beginning with `!` into a direct shell tool request. |
| `CompactionOperation` | Compact conversation history automatically or through a command. |
| `ToolPairCompactionOperation` | Summarize older tool request/response pairs to reduce context size. |
| `DoctorOperation` | Run session diagnostics and provide repair context through `/doctor`. |
| `ProjectOperation` | Contribute the selected project's instructions to the model request. |
| `RetryOperation` | Evaluate recipe success checks and goal/grind continuation or retry behavior. |
| `EmptyResponseOperation` | Make an empty-response fallback visible when another operation has not taken over. |
| `StopHookOperation` | Let configured stop hooks accept or block the end of a turn. |
| `ExitOnErrorOperation` | Yield when an error remains at the end of the conversation. |
| `MaxTurnsOperation` | Enforce goose's autonomous turn budget and contribute remaining-budget context. |
| `AutoEffortOperation` | Select and record thinking effort for a turn when automatic effort selection is enabled. |
| `SlashCommandOperation` | Route a recognized slash command to operations' command handlers. |
| `StatusOperation` | Report the current session, model, and usage through `/status`. |
The [state machine builder](https://github.com/aaif-goose/goose/blob/main/crates/goose/src/agents/state_machine_builder.rs)
shows the main composition and ordering. The
[operation modules](https://github.com/aaif-goose/goose/tree/main/crates/goose/src/agents/state_machine)
contain the implementations; some operations are only active with the relevant
configuration or are invoked through command handlers.
## How and why to write your own
Write an operation when the application needs a rule or lifecycle step that
should not depend on the model choosing the right tool. Examples include
enforcing a spending limit, waiting for an external event, validating a result,
or adding domain-specific context. If you only need a new capability that the
model may call, add a tool to `ToolOperation` instead.
Start with the condition under which your operation applies. Make its effects
change that condition, or yield, so it cannot keep selecting itself without
progress. Choose its position relative to the other steps: an approval gate
must precede tool execution, while our budget example deliberately follows it.
Keep durable decisions in the session, conversation metadata, or another store
loaded by the runtime. `set_message_meta` and `message_meta` can help mark what
an operation has already done. If a step holds received output across an await,
implement `finalize_cancellation` to return output that has not yet been saved.
Cancellation does not roll back external actions.
For a larger example, [GooseBusters](/docs/gdk/demos/goosebusters) uses custom
operations to coordinate a phone call. The full contract and result types are
in [`goose-agent::operation`](https://docs.rs/goose-agent/latest/goose_agent/operation/).
@@ -0,0 +1,174 @@
---
title: Providers
description: Choose a model backend, use declarative definitions, or implement the provider contract yourself.
displayed_sidebar: gdkSidebar
---
import ProvidersDiagram from "@site/static/img/gdk/providers.svg";
# Providers
A provider connects your application to a model backend. It translates GDK
messages and tool definitions into the backend's request format, and translates
the response back into shared message and usage types. The rest of your agent
does not need to speak each service's wire protocol.
The provider and model are separate choices. A provider knows how to reach a
service; `ModelConfig` selects a model and request settings. You can use a
provider directly for a completion, or pass it to an `InferenceRunner` in a
[state machine](/docs/gdk/concepts/state-machine).
<ProvidersDiagram />
## The provider contract
The `Provider` trait lives in `goose-provider-types`. Its central method is
`stream`: given a model configuration, system prompt, conversation messages,
and tool schemas, it returns a `MessageStream`. Text can arrive in small chunks;
tool calls are emitted once their arguments have been assembled. The stream can
also carry usage information and errors.
The default `complete` method collects the stream into one message and usage
record. Providers can also report model inventories, context limits, reasoning
capabilities, and whether they manage their own context. A common interface
does not mean every model supports the same content or tools: choose a model
that supports the capabilities your application needs.
For example, inside an async Rust function returning `anyhow::Result`, a direct
completion can look like this. Enable a TLS feature on `goose-providers` for
the HTTPS connection:
```rust
use goose_provider_types::{
base::Provider,
conversation::message::Message,
model::ModelConfig,
};
use goose_providers::{
api_client::{ApiClient, AuthMethod},
openai::OpenAiProvider,
};
let client = ApiClient::new_with_tls(
"https://api.openai.com".into(),
AuthMethod::BearerToken(std::env::var("OPENAI_API_KEY")?),
None,
)?;
let provider = OpenAiProvider::new(client);
let model = ModelConfig::new(std::env::var("OPENAI_MODEL")?);
let messages = [Message::user().with_text("Say hello in one sentence.")];
let (reply, usage) = provider
.complete(&model, "Answer concisely.", &messages, &[])
.await?;
```
This is a model call, not an agent run. Supplying tool schemas lets a model
request tools; it does not execute them. Tool execution belongs to your
application or an [operation](/docs/gdk/concepts/operations).
## Implementations that ship with GDK
`goose-providers` includes implementations for OpenAI, Anthropic, Google Gemini,
Azure AI Foundry, Databricks, Snowflake, OpenRouter, Ollama, and OpenAI-compatible
endpoints. It re-exports the shared provider types, so applications using these
implementations can import their common types from the same crate.
Many additional services use bundled declarative definitions, including Groq,
Mistral, Together, Cerebras, DeepSeek, and LM Studio. The crate also has separate
interfaces for live sessions and voice, and for typed decision requests. Those
serve different interaction patterns; they are not all interchangeable calls
to the text-completion `Provider` trait.
The [provider reference](https://docs.rs/goose-providers/latest/goose_providers/)
lists the available modules and feature flags. Credentials and HTTP authentication
are covered in [Authentication](/docs/gdk/concepts/authentication).
## Declarative providers
If a service already speaks a supported protocol, an endpoint definition may be
enough. A declarative provider selects an OpenAI, Anthropic, or Ollama engine,
then supplies the endpoint, configuration keys, model metadata, and optional
headers or behavior flags. This avoids writing a Rust implementation for each
service that shares the same protocol.
Definitions can be bundled with your application or loaded at runtime. For
example, this definition describes an application-controlled OpenAI-compatible
endpoint. Replace the example URL and model metadata with the real values:
```json
{
"name": "my-service",
"display_name": "My model service",
"engine": "openai",
"base_url": "https://models.example/v1/chat/completions",
"api_key_env": "MY_SERVICE_API_KEY",
"models": [
{
"name": "my-model",
"context_limit": 32768
}
],
"dynamic_models": false
}
```
Create the provider with `declarative::from_json`, or inspect definitions with
`deserialize_provider_config`. `EnvKeyResolver` reads credentials from the
environment; your application can supply another `KeyResolver` for its own
credential store. `load_custom_providers` reads definitions from a directory.
Treat definitions as trusted configuration: they choose where requests and
credentials go, and can include a credential-fetching command.
## Local models and providers
There are two ways to use models running on the same machine:
| Approach | What your application connects to |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local model server | An Ollama or OpenAI-compatible HTTP endpoint, such as one exposed by LM Studio. The server owns model loading and inference. |
| In-process local inference | `LocalInferenceProvider` from `goose-local-inference`, available through the `local-inference` feature on `goose-providers`. Your process loads and runs the model. |
In-process inference uses llama.cpp for GGUF models, with optional MLX support
on Apple silicon. Models can be selected by a local file path; optional Hugging
Face support adds discovery, downloads, and a cached-model inventory. CUDA,
Vulkan, and MLX features select the relevant backends and have native build
requirements.
With local inference enabled, the provider still implements the same contract:
```rust
use goose_providers::local_inference::LocalInferenceProvider;
let provider = LocalInferenceProvider::from_env().await?;
let model = ModelConfig::new("/absolute/path/to/model.gguf");
```
You can call `stream` or `complete`, or use it for agent inference as above.
Local placement does not guarantee a model fits in memory or supports reliable
tool calling. The local-inference crate handles chat templates, parsing, model
residency, and eviction; your application still chooses the model and when to
use it. [lifewiki](/docs/gdk/demos/lifewiki) is an example with an offline path.
See the [local-inference reference](/docs/gdk/reference#goose-local-inference)
for the engine, features, and model-management APIs.
## Implementing your own provider
Write a provider when a backend's protocol or behavior cannot be represented
by an existing implementation or declarative definition. Implement `get_name`
and `stream`; `complete` and several discovery methods have defaults. Depend on
`goose-provider-types` if you only need that contract, and use the request and
formatting helpers from `goose-providers` where they fit.
Normalize the backend's output into GDK messages, assemble tool calls before
emitting them, preserve usage information, and map failures into `ProviderError`.
Report capabilities and context limits honestly rather than assuming that a
successful text response implies support for tools, images, or reasoning.
Provider-specific authentication can remain separate through `ApiClient` and
`AuthProvider`.
The full trait is in
[`goose-provider-types::base`](https://docs.rs/goose-provider-types/latest/goose_provider_types/base/).
For an existing implementation to read, start with the
[provider source](https://github.com/aaif-goose/goose/tree/main/crates/goose-providers/src).
@@ -0,0 +1,117 @@
---
title: State machine
description: Compose operations into an agent whose next action is determined by its loaded state.
displayed_sidebar: gdkSidebar
---
import StateMachineDiagram from "@site/static/img/gdk/state-machine.svg";
# State machine
An agent often starts as a loop: call a model, run the tools it requests, and
repeat. That works until the application also needs approvals, retries,
compaction, external events, or a way to stop and resume. Those concerns need
places in the execution order, not just more instructions in a prompt.
GDK represents execution as an ordered list of steps. You compose a
`StateMachine` from [operations](/docs/gdk/concepts/operations) and inference
steps. Changing the agent means changing that composition or writing an
operation, not extending the state machine itself.
## The execution cycle
For each pass, the machine:
1. Loads the session through your `SessionLoader`.
2. Tries the steps in order until one applies.
3. Passes that step's effects to your `EffectHandler`.
4. Starts again with the updated session, or returns control to the caller.
A step can decline, apply effects and continue, or apply effects and yield.
If no step applies, the machine yields. A step is not a program counter: the
next pass starts at the top of the list, not at the following step.
<StateMachineDiagram />
A simple composition looks like this. `tools` and `inference` are instances
configured by your application, using the same session and effect types:
```rust
let machine = StateMachine::new(
vec![
Step::Operation(Arc::new(tools)),
Step::Inference(Arc::new(inference)),
],
cancel,
);
```
After a user message, the tool operation has nothing to do and inference runs.
If the model requests a tool, that request becomes part of the conversation.
On the next pass, the tool operation executes it and returns its result as an
effect. The following pass reaches inference with that result in context.
When the model finishes without further work, the inference step declines and
the machine returns control to the application.
Before inference, the machine also asks the operations for their tool
definitions and prompt contributions. A component can therefore influence the
model request even when its `run` method has no action to take.
## State belongs to the application
`MachineSession` exposes the session ID and conversation. Your session type
can also hold application data, such as a working directory, approval state,
or a business record. Effects describe changes to apply: appending a message,
replacing a compacted history, or updating application-specific state.
The machine does not prescribe a database. You implement loading and applying
effects against files, a database, or an in-memory store. `Emitter` events are
separate: they let a client display output while work is running, but displaying
an event does not persist its effects.
Because decisions are made from loaded state, a fresh machine can continue a
saved conversation without remembering which branch of a loop it was in.
Operations must record decisions that matter to subsequent runs rather than
keep them only in local variables. The
[Hello World session store](/docs/gdk/hello-world#own-the-session-and-its-effects)
shows a file-backed version of this boundary.
## Yielding and resuming
Yielding means returning control to the caller. It can mean the agent has
finished, needs human approval, or must wait for an external event. It does not
start a background worker or automatically schedule a later run.
Your application persists the new input or decision, constructs the appropriate
operations, and invokes the machine again. For example, an approval operation
can yield while a tool request is awaiting a decision, then allow execution
after that decision has been saved. It must appear before any step that would
execute the unapproved request or infer past it.
Persistence alone does not make external actions exactly-once. If a process
stops between making a payment or sending a message and saving the result,
the application still needs a way to reconcile that action. Store identifiers
and use idempotent external APIs where the workflow requires them.
## Running, stepping, and stopping
Use `run` to let the machine load, step, and apply until it yields or is
cancelled:
```rust
let session = machine.run(&runtime, &session_id, &emitter).await?;
```
Applications that need tighter control can drive `step` and `apply` themselves.
The returned `StepResult` identifies the step that applied and whether the run
is continuing, yielded, or cancelled. Callers driving those methods themselves
must also call `finalize` when leaving the run.
Cancellation drops the running step's future, then gives operations a chance
to preserve received output and finalize interrupted tool responses. `run`
handles that finalization before returning. This cannot undo external side
effects or guarantee that work started outside the async task has stopped.
Next, read [Operations](/docs/gdk/concepts/operations) to see how to compose a
policy into this cycle. The full API is in
[`goose-agent::machine`](https://docs.rs/goose-agent/latest/goose_agent/machine/).
+82
View File
@@ -0,0 +1,82 @@
---
title: Berd
description: A custom desktop application with a bundled goose backend connected over ACP.
displayed_sidebar: gdkSidebar
---
# Berd
Berd is a desktop application for working with AI agents, built with Tauri and
React. It provides its own interface and distribution while using a bundled
goose process as its agent backend.
Built with **goose over ACP**, using a WebSocket connection to `goose serve`.
[Source](https://github.com/block/berd)
![Berd's desktop interface with projects, conversations, and a prompt composer](https://raw.githubusercontent.com/block/berd/main/src/features/onboarding/assets/tour-1.png)
_An onboarding image from the [Berd repository](https://github.com/block/berd/blob/main/src/features/onboarding/assets/tour-1.png)._
## The clever bit
You can build a different desktop product without forking the agent runtime.
Berd owns its interface, application lifecycle, and packaging. The bundled
goose backend provides the agent execution behind an ACP boundary.
The backend is pinned to a specific revision, so a distribution can ship a
known frontend/backend pair instead of relying on whatever goose version is on
the user's `PATH`. The same repository also has distribution hooks for managed
settings and private resources without putting those resources in the public tree.
This is the application-level route: use the complete goose binary, rather than
assemble a runtime from individual GDK crates.
## How it works
1. During setup, prepare the goose revision recorded in `goose-backend.lock.json`
and build the vendored TypeScript SDK.
2. Start a long-lived `goose serve` child process on a local port, with a
per-launch authentication secret.
3. Connect to its `/acp` endpoint over WebSocket and route session updates to
the application.
4. Package the backend as a Tauri sidecar for distribution.
The [process service](https://github.com/block/berd/blob/main/src-tauri/src/services/acp/goose_serve.rs)
starts the backend with an explicit local address and port:
```rust
command
.arg("serve")
.arg("--enable-scheduler")
.arg("--host")
.arg(LOCALHOST)
.arg("--port")
.arg(port.to_string());
```
It also passes `GOOSE_SERVER__SECRET_KEY` and manages the child process lifetime.
The [ACP commands](https://github.com/block/berd/blob/main/src-tauri/src/commands/acp.rs)
and [SDK](https://github.com/block/berd/tree/main/sdk) show the connection from the
application side. For the underlying transport, see
[using goose over ACP](/docs/gdk/acp).
## Run it yourself
You need the Rust, JavaScript, and native dependencies for a Tauri desktop build.
Setup builds the pinned goose backend as well, so allow time for the initial
build. Consult the [README](https://github.com/block/berd#getting-started) and
[development commands](https://github.com/block/berd/blob/main/justfile) for
platform-specific requirements.
```bash
git clone https://github.com/block/berd.git
cd berd
just setup
just dev
```
Configure a model provider in the application before starting an agent session.
For a packaged build, the repository's
[bundling instructions](https://github.com/block/berd#bundling-and-distributions)
explain how to stage and include the backend.
@@ -0,0 +1,80 @@
---
title: GooseBusters
description: A phone-call assistant with custom operations for approval, supervision, and structured outcomes.
displayed_sidebar: gdkSidebar
---
# GooseBusters
Give GooseBusters a phone number and a task. It proposes a plan, asks for your
approval, conducts the call, and reports what happened with supporting quotes
from the conversation. A CLI and a Tauri desktop app expose the same workflow.
Built with **GDK**: `goose-agent` and the provider components, without depending
on the complete goose application.
[Source](https://github.com/DOsinga/goose-busters) ·
[Design](https://github.com/DOsinga/goose-busters/blob/main/GooseBusters.md)
## The clever bit
A phone call is not a sequence of model responses and tool calls. Speech and
webhooks arrive while other work is running. An earlier suggestion can become
stale as soon as the person on the phone says something new.
GooseBusters expresses this as custom state-machine operations: planning,
approval, dialing, call events, supervision, and final extraction. Incoming
speech can preempt a supervisor turn. The application checks whether an action
is still current before applying it.
The model is one part of the workflow, rather than the owner of its lifecycle.
Application code controls approval, the call record, and the effects applied to it.
## How it works
1. A planning turn produces voice-agent instructions and fields to collect.
2. The user approves, aborts, or gives feedback for a revised plan.
3. A Telnyx call connects to an OpenAI voice backend. The supervisor processes
events and tracks progress while the conversation happens.
4. After hangup, extraction checks the transcript for the requested fields and
the callee's supporting quotes. The call record is saved as YAML.
The [supervisor](https://github.com/DOsinga/goose-busters/blob/main/src/supervisor.rs)
rebuilds the machine for each turn from a snapshot of the application's record:
```rust
let snapshot = record.snapshot();
let turn = call_cancel.child_token();
pipeline.handle.set_turn_token(turn.clone());
let machine = StateMachine::new(build_steps(pipeline), turn.clone());
let emit = Emitter::new(tx.clone(), turn.clone());
```
It calls `machine.step`, applies the returned effects to its own record, and
emits UI events. The CLI and desktop app render those events differently without
implementing separate agent workflows. Read the
[operations](https://github.com/DOsinga/goose-busters/blob/main/src/ops.rs)
alongside the supervisor to see where the application controls execution.
## Run it yourself
This is an end-to-end prototype. Real calls need Rust, Telnyx and OpenAI
accounts, and a publicly reachable webhook endpoint. The repository documents
a Cloudflare tunnel setup and the credentials for each voice backend.
```bash
git clone https://github.com/DOsinga/goose-busters.git
cd goose-busters
```
Complete the [account and webhook setup](https://github.com/DOsinga/goose-busters#setup)
before starting the desktop app:
```bash
cargo run -p goosebusters
```
Use a number and recipient you have permission to call. Calls send audio and
transcripts to external services and may incur charges. See the repository's
[responsible-use notes](https://github.com/DOsinga/goose-busters#responsible-use)
before making a real call.
+78
View File
@@ -0,0 +1,78 @@
---
title: Huddle
description: A voice interface that delegates longer tasks to an ACP agent through GDK live provider events.
displayed_sidebar: gdkSidebar
---
# Huddle
Huddle is a small desktop application for talking to a local agent. A live voice
model handles the conversation. When a request needs work, Huddle passes it to
an ACP agent and sends the result back to the voice model to speak aloud.
Built with **GDK + ACP**: the live provider interface from `goose-providers`,
with goose or another ACP agent doing the delegated work.
[Source](https://github.com/jamadeo/goose-huddle)
## The clever bit
The voice conversation and the working agent have different jobs. The voice
model handles speech; a separate agent has the tools and context to carry out
the task. They do not need to be the same model or run in the same process.
Delegation events identify a position in the spoken conversation. Huddle turns
the transcript up to that point into an agent prompt, then returns the answer
to the corresponding delegation. Requests queue while the working agent is busy.
This is a small example of composing provider capabilities with an existing
agent instead of rebuilding the entire stack for a new interface.
## How it works
1. The webview captures microphone audio and plays the response over WebRTC.
2. Rust starts the live session through GDK and listens on its sideband control
connection for transcript and delegation events.
3. A delegation becomes a prompt to the persistent ACP session.
4. The agent's result is returned through the live provider connection.
In [`voice.rs`](https://github.com/jamadeo/goose-huddle/blob/main/src-tauri/src/voice.rs),
the return path uses the provider's delegation interface:
```rust
let delivery = connection
.send_delegation_update(DelegationUpdate {
provider_delegation_id: delegation_id.clone(),
text: text.clone(),
})
.await?;
```
The [transcript code](https://github.com/jamadeo/goose-huddle/blob/main/src-tauri/src/transcript.rs)
chooses the context for each request. The
[ACP client](https://github.com/jamadeo/goose-huddle/blob/main/src-tauri/src/acp.rs)
owns the agent subprocess and serializes prompts.
## Run it yourself
You need Rust 1.94 or later, an OpenAI API key with GPT-Live access, microphone
permission, and an ACP agent on your `PATH`. The default is `goose acp`.
Configure goose's model provider separately if you use that default.
With `OPENAI_API_KEY` set in your environment:
```bash
git clone https://github.com/jamadeo/goose-huddle.git
cd goose-huddle/src-tauri
cargo run
```
Open Settings to choose the agent command and working directory, then start a
huddle. See the [README](https://github.com/jamadeo/goose-huddle#running) for
packaging and configuration details.
:::warning Prototype permissions
Huddle automatically approves agent tool requests and can save the API key in
browser local storage. Try it in a disposable working directory with credentials
and resources appropriate for a prototype.
:::
+120
View File
@@ -0,0 +1,120 @@
---
title: Demos
description: Explore applications built with GDK and goose, and the design choices behind them.
displayed_sidebar: gdkSidebar
hide_table_of_contents: true
---
import styles from "@site/src/css/gdk-demos.module.css";
# Demos
A personal wiki, a phone-call assistant, a voice interface, and more.
Explore what these applications do, then look inside to see how they work.
Some embed GDK components directly. Others build on the pre-built goose agent
over [ACP](/docs/gdk/acp). Each demo explains which approach it takes and the
design choice worth borrowing for your own application.
<div className={styles.grid}>
<article className={styles.card}>
<p className={styles.focus}>Memory you can inspect</p>
## lifewiki
Turn everyday notes into a cited, evolving personal wiki. Keep the original
record while an agent reconciles what has changed.
<div className={styles.footer}>
<span>GDK</span>
[Explore →](/docs/gdk/demos/lifewiki)
</div>
</article>
<article className={styles.card}>
<p className={styles.focus}>An agent that makes phone calls</p>
## GooseBusters
Plan a call, approve it, and let an agent hold the conversation. Custom
operations supervise the call and collect its outcome.
<div className={styles.footer}>
<span>GDK</span>
[Explore →](/docs/gdk/demos/goosebusters)
</div>
</article>
<article className={styles.card}>
<p className={styles.focus}>Voice with a working agent behind it</p>
## Huddle
Talk naturally while a separate agent handles longer tasks. Live provider events
connect the conversation to an ACP agent.
<div className={styles.footer}>
<span>GDK + ACP</span>
[Explore →](/docs/gdk/demos/huddle)
</div>
</article>
<article className={styles.card}>
<p className={styles.focus}>An agent without a chat box</p>
## goose Perception
Turn desktop activity into a searchable wiki. Short-lived agent sessions share
a lasting memory through ordinary files.
<div className={styles.footer}>
<span>goose over ACP</span>
[Explore →](/docs/gdk/demos/perception)
</div>
</article>
<article className={styles.card}>
<p className={styles.focus}>Conversations tied to your work</p>
## Top Goose
Give each GitHub issue and pull request its own private agent conversation,
with persistent sessions and separate worktrees.
<div className={styles.footer}>
<span>goose over ACP</span>
[Explore →](/docs/gdk/demos/top-goose)
</div>
</article>
<article className={styles.card}>
<p className={styles.focus}>Your application, goose's runtime</p>
## Berd
Build a complete desktop experience around a bundled goose backend. The
interface and agent communicate over ACP.
<div className={styles.footer}>
<span>goose over ACP</span>
[Explore →](/docs/gdk/demos/berd)
</div>
</article>
</div>
These are independent projects at different stages of development. Their source
repositories contain the current setup instructions and dependency versions.
+86
View File
@@ -0,0 +1,86 @@
---
title: lifewiki
description: A personal wiki that reconciles changing facts while preserving the original notes.
displayed_sidebar: gdkSidebar
---
# lifewiki
Tell lifewiki something about your life and an agent turns it into a personal
wiki. Add a later note that contradicts an earlier one, and the agent updates
the relevant pages while keeping the original notes and their history.
Built with **GDK**: `goose-agent`, `goose-providers`, and optional local inference.
[Source](https://github.com/jamadeo/lifewiki) ·
[Watch the recording](https://github.com/jamadeo/lifewiki/blob/main/demo/demo.mov)
## The clever bit
The agent can rewrite the wiki because the wiki is not the source of truth.
The append-only log is. Every generated claim can cite the note behind it,
and git records the changes. If the prompts or model improve, the wiki can be
rebuilt from the original log.
Building and asking use the same agent loop with different capabilities.
A build can search, read, and write pages. A question opens the workspace
read-only and does not offer write tools. The distinction is enforced by the
application, not just an instruction asking the model to behave.
## How it works
1. Capture a note as plain text in the log.
2. Run a build. The agent searches and reads the wiki, then reconciles the new
information with existing pages.
3. Commit the wiki changes and processing cursor together.
4. Answer questions from the resulting wiki with a separate, read-only role.
The application supplies its own operations to GDK's state machine. In
[`src/agent.rs`](https://github.com/jamadeo/lifewiki/blob/main/src/agent.rs),
the steps put limits, completion, and tool execution ahead of inference:
```rust
let steps: Vec<Step<'_, Session, ConversationEffect>> = vec![
Step::Operation(Arc::new(MaxTurnsOperation)),
Step::Operation(Arc::new(TerminalOperation)),
Step::Operation(Arc::new(EndTurnOperation)),
Step::Operation(Arc::new(ToolExecutionOperation)),
Step::Inference(Arc::new(InferenceRunner {
backend: self.backend.clone(),
})),
];
```
GDK supplies the execution machinery; lifewiki owns the tools, roles, storage,
and rules for finishing a run. See also the
[tool implementation](https://github.com/jamadeo/lifewiki/blob/main/src/tools.rs)
and [design notes](https://github.com/jamadeo/lifewiki/blob/main/docs/design.md).
## Run it yourself
You need Rust and either an Anthropic API key or a configured local model.
Local inference has extra build and hardware requirements; follow the
[repository's instructions](https://github.com/jamadeo/lifewiki#local-inference)
for that path.
For a hosted-model build without the optional local backend:
```bash
git clone https://github.com/jamadeo/lifewiki.git
cd lifewiki
cargo install --path . --no-default-features
lw init
```
With `ANTHROPIC_API_KEY` set in your environment:
```bash
lw add "Ada lives in Lisbon."
lw add "Ada moved to Porto last month."
lw build
lw ask "Where does Ada live?"
```
The [recorded walkthrough](https://github.com/jamadeo/lifewiki/blob/main/demo/README.md)
shows reconciliation, citations, questions, and git history. Its local model is
pre-warmed and playback pauses are shortened; it does not show first-run loading time.
@@ -0,0 +1,76 @@
---
title: goose Perception
description: A background application that turns desktop activity into a personal wiki using goose over ACP.
displayed_sidebar: gdkSidebar
---
# goose Perception
Perception periodically captures the desktop and turns what it observes into a
linked personal wiki about projects, people, and daily activity. A local web
interface lets you browse, search, and edit the result.
Built with **goose over ACP**, using the TypeScript `@aaif/goose-sdk` client.
The application does not embed the Rust GDK runtime.
[Source](https://github.com/DOsinga/goose_perception)
## The clever bit
An agent does not need to wait for a chat message. Here, desktop observations
drive the work, and the wiki provides continuity between runs.
Perception uses fresh agent sessions rather than accumulating screenshots in an
ever-growing conversation. A fast model can describe a screenshot, and a
separate model can reconcile batches of observations into the wiki. The lasting
memory is in files the user can inspect and edit, not in a single chat history.
This also separates the application's scheduling and capture logic from the
agent's tools, provider configuration, and execution.
## How it works
1. Capture screenshots and extract descriptions of relevant changes.
2. Batch those observations for the wiki-maintenance agent.
3. Start a session in the wiki directory, supplying the current wiki context.
4. Update pages and cross-references. During idle periods, review existing
pages using a separate lint prompt.
The [agent client](https://github.com/DOsinga/goose_perception/blob/main/src/agent.ts)
creates sessions with the wiki as their working directory:
```typescript
const session = await client.newSession({
cwd: config.wikiDir,
mcpServers: [],
...(provider ? { _meta: { provider } } : {}),
});
```
The same client sends image content to the extraction session and text
observations to the wiki session. The
[main loop](https://github.com/DOsinga/goose_perception/blob/main/src/main.ts)
handles batching, change detection, and scheduling; the
[prompts](https://github.com/DOsinga/goose_perception/blob/main/src/prompt.ts)
define what the agent should preserve.
## Run it yourself
You need Node.js 20 or later, macOS or Linux with a supported screenshot tool,
and goose configured with a vision-capable model. The package can install goose
if it is not already available.
```bash
npx goose_perception
```
This starts desktop capture and opens the wiki browser at
`http://localhost:8112`. Stop the process to stop capture. See the
[README](https://github.com/DOsinga/goose_perception#options) for capture intervals,
storage location, and connection options.
:::warning Desktop capture
Screenshots can contain private information and are sent to your configured
model provider. Start with a non-sensitive desktop, check your provider settings,
and review the files stored in the Perception directory.
:::
+80
View File
@@ -0,0 +1,80 @@
---
title: Top Goose
description: GitHub issues and pull requests with persistent private goose conversations over ACP.
displayed_sidebar: gdkSidebar
---
# Top Goose
Top Goose brings GitHub issues, pull requests, and private agent conversations
into one desktop application. Select an issue or PR to read the public
discussion alongside an agent working against your local clone.
Built with **goose over ACP**: an Electron application that runs `goose acp`
as a subprocess.
[Source](https://github.com/DOsinga/top-goose)
## The clever bit
The conversation belongs to the piece of work, not to whichever chat window
happens to be open. Each issue or pull request maps to a persistent goose
session. Switching views does not cancel another session's running turn, and
returning after an application restart loads the existing conversation.
The application owns the GitHub context and interface; goose owns the agent's
conversation history and tool execution. Separate git worktrees let sessions
work concurrently without sharing a checkout.
An application-provided MCP tool can place a draft reply in the composer for
review, giving the agent a way to participate in the interface rather than
only returning chat text.
## How it works
1. Read issues and PRs from GitHub and show their discussions in the app.
2. On the first prompt, create a goose session and, when enabled, its worktree.
3. Supply the public discussion as untrusted context for the agent.
4. Route streamed updates to the matching conversation. Load the stored
session when the user returns.
The [session manager](https://github.com/DOsinga/top-goose/blob/main/src/main/goose/sessions.ts)
resumes a mapped session and applies the replay to the UI:
```typescript
const cwd = await sessionCwd(mapping);
const replay = await acp.loadSession(mapping.sessionId, cwd, []);
applyReplay(live, replay);
live.currentAgent = undefined;
await attachDraftServer(mapping.sessionId, issueNodeId, cwd);
await applyInstructions(mapping.sessionId, mapping.kind ?? "issue");
```
See the [ACP transport](https://github.com/DOsinga/top-goose/blob/main/src/main/goose/acp.ts),
[context synchronization](https://github.com/DOsinga/top-goose/blob/main/src/main/goose/contextSync.ts),
and [draft-reply MCP server](https://github.com/DOsinga/top-goose/blob/main/src/main/mcp/draftServer.ts)
for the other sides of that integration.
## Run it yourself
You need Node.js 22.12 or later, a local repository clone, a GitHub classic
personal access token, and goose 1.41 or later with a configured provider.
The project is developed and tested on macOS.
```bash
git clone https://github.com/DOsinga/top-goose.git
cd top-goose
npm install
npm run dev
```
First-run settings guide you through GitHub authentication, locating goose, and
choosing a local clone. Follow the
[setup instructions](https://github.com/DOsinga/top-goose#setup) for token scopes
and optional Projects integration.
:::warning Agent access
Top Goose runs sessions in automatic mode and approves tool requests. Worktrees
separate git state; they are not a security sandbox. Use a repository and
credentials appropriate for that level of access.
:::
+425
View File
@@ -0,0 +1,425 @@
---
title: Hello World
sidebar_label: Getting Started
description: Build a small Rust agent with one shell tool, streaming responses, and a saved conversation.
displayed_sidebar: gdkSidebar
---
# Hello World
Let's build a small coding agent. It can inspect a directory, run shell
commands, and keep a conversation across turns and application restarts.
This is an annotated walkthrough of Jack's
[`ngrc` example](https://github.com/jamadeo/ngrc/tree/dc25c579cd40d85f8d90b61e80cbf02b8838564f).
GDK handles inference, tool dispatch, and the model/tool loop. The application
chooses the provider, tools, prompt, storage, and interface.
The code blocks below are selected excerpts, with some setup shortened for
clarity. Use the linked repository for the complete runnable program, imports,
and session store. This walkthrough uses revision `dc25c57`, which pins GDK
`0.1.0-alpha.12`; newer alpha releases may have different APIs.
## Run it first
You need Rust 1.94.1 or later, macOS or Linux with `/bin/bash`, and an OpenAI
API key. Choose a model that supports tool calling. You do not need the goose
CLI, a goose configuration file, or an MCP server.
:::warning Shell access
This example executes shell commands without approval or sandboxing, with your
user permissions and inherited environment. Use a disposable workspace without
sensitive files or credentials. Choosing a working directory does not restrict
what the shell can access. Model requests may incur charges.
:::
```bash
git clone https://github.com/jamadeo/ngrc.git
cd ngrc
git switch --detach dc25c579cd40d85f8d90b61e80cbf02b8838564f
```
Set these to your own API key and a tool-capable OpenAI model available to your
account, then send an initial prompt:
```bash
export OPENAI_API_KEY="your-api-key"
export NGRC_MODEL="your-tool-capable-openai-model"
cargo run --locked -- "Inspect this directory and summarize it without changing files."
```
The agent prints its response and returns to a `>` prompt. Ask a follow-up
question to use the same conversation. Ctrl-D on an empty line exits; Ctrl-C
cancels the agent and exits. Starting without a prompt waits for your first
message rather than making a model request immediately.
The application also prints the path to its session file. Keep that path to
[resume the conversation](#resume-the-conversation) later.
## Assemble the agent
The central function in
[`src/main.rs`](https://github.com/jamadeo/ngrc/blob/dc25c579cd40d85f8d90b61e80cbf02b8838564f/src/main.rs)
is small enough to read in one go:
```rust
fn agent(
provider: Arc<dyn Provider>,
model: ModelConfig,
cancel: CancellationToken,
) -> StateMachine<'static, Session, Effect> {
StateMachine::new(
vec![
Step::Operation(Arc::new(
ToolOperation::<Session>::new().with_async_tool::<Shell>(),
)),
Step::Inference(Arc::new(
InferenceRunner::<Session, Effect>::new(provider, model)
.with_request_preparer(Arc::new(Prompt)),
)),
],
cancel,
)
}
```
The machine has two steps, in order:
- `ToolOperation` exposes the shell tool to the model and executes pending
calls to it.
- `InferenceRunner` calls the provider with the conversation, prompt, and
available tools.
After a step produces effects, the runtime saves them and the machine reloads
the session before the next pass. A model response can request a shell command;
the next pass executes it, and another inference call sees the result. When
the assistant finishes its turn, control returns to the application.
There is no second, application-written model/tool loop hidden around this
function. The application only needs a loop for accepting new user messages.
## Choose a provider and model
The example uses three GDK crates:
```toml
[dependencies]
goose-agent = "=0.1.0-alpha.12"
goose-provider-types = "=0.1.0-alpha.12"
goose-providers = { version = "=0.1.0-alpha.12", features = ["rustls-tls"] }
```
`goose-agent` provides the state machine and operations. `goose-provider-types`
provides shared interfaces and message types. `goose-providers` supplies the
OpenAI implementation. The `rustls-tls` feature enables HTTPS for this setup.
The [full manifest](https://github.com/jamadeo/ngrc/blob/dc25c579cd40d85f8d90b61e80cbf02b8838564f/Cargo.toml)
also includes Tokio, serialization, and the typed tool dependencies.
Provider setup is explicit:
```rust
let key = std::env::var("OPENAI_API_KEY")?;
let model_name = std::env::var("NGRC_MODEL")?;
let client = ApiClient::new_with_tls(
"https://api.openai.com".into(),
AuthMethod::BearerToken(key),
Some(Default::default()),
)?;
let provider: Arc<dyn Provider> = Arc::new(OpenAiProvider::new(client));
let model = ModelConfig::new(model_name);
```
The provider handles communication with the model service. `ModelConfig`
selects the model. Passing both into the machine keeps that choice separate
from the rest of the application.
## Give it one tool
The model only gets one tool: `shell`. Its input and output are ordinary Rust
types with generated JSON schemas:
```rust
#[derive(Default, Deserialize, JsonSchema)]
struct ShellInput {
command: String,
}
#[derive(Serialize, JsonSchema)]
struct ShellOutput {
stdout: String,
stderr: String,
exit_code: Option<i32>,
}
```
`ToolBase` gives the tool its model-facing name and description, and connects
those types to the tool interface:
```rust
struct Shell;
impl ToolBase for Shell {
type Parameter = ShellInput;
type Output = ShellOutput;
type Error = ErrorData;
fn name() -> Cow<'static, str> {
"shell".into()
}
fn description() -> Option<Cow<'static, str>> {
Some("Execute a non-interactive Bash command in the project directory. Commands time out after 120 seconds; cwd changes do not persist between calls.".into())
}
}
```
`AsyncTool<Session>` implements the actual behavior. It receives the loaded
session, so it can start commands in the session's saved working directory:
```rust
impl AsyncTool<Session> for Shell {
async fn invoke(session: &Session, input: ShellInput) -> Result<ShellOutput, ErrorData> {
let mut command = tokio::process::Command::new("/bin/bash");
command
.arg("-c")
.arg(input.command)
.current_dir(&session.metadata.cwd)
.stdin(Stdio::null())
.kill_on_drop(true);
let output = tokio::time::timeout(Duration::from_secs(120), command.output())
.await
.map_err(|_| ErrorData::internal_error("shell timed out after 120 seconds", None))?
.map_err(|error| ErrorData::internal_error(error.to_string(), None))?;
Ok(ShellOutput {
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
exit_code: output.status.code(),
})
}
}
```
Registering it with `with_async_tool::<Shell>()` makes both its schema and
implementation available to `ToolOperation`. The `rmcp` traits are used for
typed tool definitions; this tool runs in-process, without an MCP server.
Each call starts a new shell. A `cd` command or shell variable from one call
does not carry into the next. A nonzero exit code is returned to the model
alongside stdout and stderr so it can decide what to do next.
## Prepare the model request
The `Prompt` request preparer supplies the system prompt and forwards the tools
collected from the machine's operations:
```rust
struct Prompt;
#[async_trait]
impl InferenceRequestPreparer<Session> for Prompt {
async fn prepare(
&self,
_: &Session,
_: &Conversation,
input: InferenceInput,
) -> Result<PreparedInferenceRequest> {
Ok(PreparedInferenceRequest {
system_prompt: SYSTEM_PROMPT.into(),
tools: input.tools,
additional_messages: vec![],
})
}
}
```
The example's system prompt tells the agent to use the shell to inspect, edit,
and test code, treat file contents and command output as untrusted data, and
report its changes and verification concisely. These instructions guide the
model; they do not enforce a security boundary.
The preparer also receives the current session and conversation. This example
does not use them, but that is where an application can add request-specific
context instead of relying on one fixed prompt.
## Own the session and its effects
GDK does not require a particular database or session format. The application
provides a session that exposes its ID and conversation:
```rust
impl MachineSession for Session {
fn id(&self) -> &str {
&self.id
}
fn conversation(&self) -> Option<&Conversation> {
Some(&self.conversation)
}
}
```
In `ngrc`, that session also contains creation time, working directory, provider,
model, and recorded usage. A `Runtime` wraps the file-backed store. It implements
`SessionLoader` to return a snapshot of the session for each machine pass:
```rust
#[async_trait]
impl SessionLoader<Session> for Runtime {
async fn load(&self, id: &str) -> Result<Session> {
let session = self.snapshot();
if session.id != id {
bail!("unknown session {id}");
}
Ok(session)
}
}
```
The machine produces effects rather than writing to the file directly. This
example uses two kinds:
```rust
enum Effect {
Message(Message),
Usage(ProviderUsage),
}
impl From<Message> for Effect {
fn from(message: Message) -> Self {
Self::Message(message)
}
}
impl InferenceEffect for Effect {
fn record_usage(usage: ProviderUsage) -> Self {
Self::Usage(usage)
}
}
impl MachineEffect for Effect {
fn ensure_message_ids(&mut self) {
if let Self::Message(message) = self {
*message = message.clone().with_generated_id_if_missing();
}
}
}
```
`From<Message>` lets tool and inference results become application effects.
`InferenceEffect` preserves provider usage alongside messages. `MachineEffect`
ensures messages have IDs before persistence.
The runtime's `EffectHandler` converts those effects to records for its store.
The core of that implementation is:
```rust
let records = effects
.iter()
.map(|effect| match effect {
Effect::Message(message) => Record::Message {
message: message.clone(),
},
Effect::Usage(usage) => Record::Usage {
usage: usage.clone(),
},
})
.collect();
store.append(records)?;
```
[`src/session.rs`](https://github.com/jamadeo/ngrc/blob/dc25c579cd40d85f8d90b61e80cbf02b8838564f/src/session.rs)
implements the append-only JSONL store. It writes and syncs records before
updating the in-memory session. Reopening the file replays those records to
reconstruct the conversation, metadata, and usage. Assistant messages, tool
results, and usage are persisted as effects, not on every streamed token.
## Run a turn and stream the response
Before running the machine, save the user's message:
```rust
runtime.append_message(Message::user().with_text(prompt))?;
```
The machine emits events while it works. An event channel lets the interface
display output before the turn finishes. Here is a shortened version of the
example's `run_turn` function:
```rust
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let emitter = Emitter::new(tx, cancel.clone());
let display = tokio::spawn(async move {
while let Some(event) = rx.recv().await {
if let AgentEvent::Message(message) = event {
for content in message.content {
match content {
MessageContent::Text(text) => {
print!("{}", text.text);
io::stdout().flush()?;
}
MessageContent::Error(error) => eprintln!("{}", error.message),
_ => {}
}
}
}
}
Ok::<_, io::Error>(())
});
let machine = agent(provider, model, cancel);
let id = runtime.snapshot().id;
let result = machine.run(runtime, &id, &emitter).await;
drop(emitter);
display.await??;
let session = result?;
```
Streaming and persistence have separate jobs: the emitter updates the UI, while
the effect handler records the session. Printing an event does not save it.
For each input line, the chat loop appends a user message and runs a fresh
machine around the same stored session. The machine has no conversation of its
own to carry between turns.
The application also connects Ctrl-C to the shared `CancellationToken`. It
awaits the machine after cancellation so GDK can finalize interrupted tool
responses before the display task finishes.
## Resume the conversation
By default, new sessions are stored in `~/.ngrc/sessions`. On startup, the
application prints the exact file path. To reopen one, keep your API key and
model environment variables set and replace the path below with that file:
```bash
cargo run --locked -- --resume /absolute/path/to/session.jsonl
```
The application loads the prior messages, shell results, usage, and saved
working directory, then waits for your next prompt. It does not rerun old shell
commands. `--session-dir DIR` chooses a different directory for new sessions.
This demonstrates persistent conversation state, not recovery of a running shell
process or exactly-once external actions. A crash can lose output that has only
been streamed, and an incomplete log record needs attention before reopening.
## Where to go next
The example deliberately leaves out tool approval, sandboxing, output limits,
context compaction, and a model-turn or cost budget. Its shell timeout does not
guarantee cleanup of descendant processes. Keep these limits in mind before
turning it into an application that works on real data.
To change the agent, start with one of the choices already visible here: add a
tool, replace the request preparer, choose another provider, or implement a
different session store. More specialized behavior can become another
operation in the machine's ordered list.
Explore the [demos](/docs/gdk/demos) for larger applications, or use the
[reference](/docs/gdk/reference) to find the component APIs. For this example,
select version `0.1.0-alpha.12` in the generated Rust documentation.
+63 -17
View File
@@ -1,24 +1,70 @@
---
title: GDK Overview
sidebar_label: Overview
description: Build on goose with the SDK and ACP.
title: GDK
displayed_sidebar: gdkSidebar
hide_table_of_contents: true
description: Build agents with GDK.
---
# GDK
The goose Development Kit (GDK) provides the core components developers need to
build agentic applications, including agent orchestration, model access, context
management, tools, memory, remote execution, automations, and routing. There are
two ways to use it:
Build agents that run across native applications, servers, and the browser,
resume from persisted state, and give you control over how they work.
- [SDK](/docs/gdk/sdk) — use goose's native Rust crates or the shared
provider bindings for Python and Kotlin as in-process libraries.
- [ACP](/docs/gdk/acp) — connect to goose as a separate agent process over
stdio, HTTP, or WebSocket.
GDK is the set of reusable agent-runtime components used to build goose. It
provides model integrations, a composable state machine, tools, context
management, and the interfaces needed to run an agent inside your application.
For Rust, start with the crate documentation on docs.rs:
[`goose-agent`](https://docs.rs/goose-agent/latest/goose_agent/),
[`goose-providers`](https://docs.rs/goose-providers/latest/goose_providers/), and
[`goose-context-management`](https://docs.rs/goose-context-management/latest/goose_context_management/).
See the [Rust API reference](/docs/gdk/sdk/api-reference#rust-api-reference) for
the full list of GDK crates.
## Explore GDK
### [Getting Started](/docs/gdk/hello-world)
Build a [small Rust agent](https://github.com/jamadeo/ngrc/tree/dc25c579cd40d85f8d90b61e80cbf02b8838564f)
that can run shell commands, stream responses, and save its conversation between
runs. The walkthrough explains how to connect a provider, tools, and a state
machine, and which parts your application owns. Start here to see the pieces
working together before choosing how to adapt them.
### [Demos](/docs/gdk/demos)
Explore working projects that use GDK for [personal wikis](/docs/gdk/demos/lifewiki),
[phone calls](/docs/gdk/demos/goosebusters),
[screen understanding](/docs/gdk/demos/perception),
[voice conversations](/docs/gdk/demos/huddle), and
[custom interfaces to goose](/docs/gdk/demos/berd). Each demo links to its source
and explains the architectural idea behind it, along with what you need to run
it. Use them to see how the same components fit very different applications.
### [Concepts](/docs/gdk/concepts)
Understand the [state machine](/docs/gdk/concepts/state-machine),
[operations](/docs/gdk/concepts/operations),
[providers](/docs/gdk/concepts/providers), and
[authentication](/docs/gdk/concepts/authentication), and how they fit together.
These guides explain the problems each component solves, the choices behind its
design, and the implementations available today. Worked examples show how to
compose agent behavior and when to write your own operation or provider.
### [Reference](/docs/gdk/reference)
Look up the generated Rust APIs for the
[agent runtime](https://docs.rs/goose-agent/latest/goose_agent/),
[providers](https://docs.rs/goose-providers/latest/goose_providers/), and
[context management](https://docs.rs/goose-context-management/latest/goose_context_management/).
Explore the shared provider bindings through the
[Python API](/docs/gdk/sdk/api-reference?language=python) and
[Kotlin API](/docs/gdk/sdk/api-reference?language=kotlin), with runnable examples in
[Python](https://github.com/aaif-goose/goose/blob/main/crates/goose-sdk/examples/uniffi/provider.py)
and [Kotlin](https://github.com/aaif-goose/goose/blob/main/crates/goose-sdk/examples/uniffi/kotlin/src/main/kotlin/Main.kt).
For apps using goose as a backend, consult the [ACP reference](/docs/gdk/acp/reference).
Use the reference when you need exact types, methods, and configuration details
while building.
## GDK and goose
[goose](/docs/quickstart) is a complete agent application and the main reference
implementation for GDK. Use goose when you want a ready-to-run agent. Use GDK
when you want to build agent behavior into your own product.
The pre-built goose binary can also serve as the agent behind any
[ACP application](/docs/gdk/acp) you build. goose Desktop works this way,
connecting to a local goose server over ACP.
@@ -0,0 +1,8 @@
{
"label": "Reference",
"position": 3,
"link": {
"type": "doc",
"id": "gdk/reference/index"
}
}
+171
View File
@@ -0,0 +1,171 @@
---
title: GDK Reference
sidebar_label: Reference
description: GDK crates and generated API documentation for Rust, Python, and Kotlin.
---
# GDK Reference
GDK is a set of Rust crates. Use the crates your application needs, or use the
Python and Kotlin bindings provided by `goose-sdk`.
## Crates
Each crate links to its generated Rust documentation on docs.rs.
### [goose-agent](https://docs.rs/goose-agent/latest/goose_agent/)
The agent runtime: a state machine built from an ordered list of operations and
inference steps. Each step can inspect the conversation, produce effects, or
yield control to the application. `StateMachine` can run the sequence for you,
or let you drive individual steps. Events stream out while work is running,
and cancellation finalizes interrupted steps and unanswered tool requests.
Use this crate when you want to assemble your own agent rather than run the
complete goose application. `InferenceRunner` connects the machine to a model
provider, and `ToolOperation` exposes and executes your typed tools. You supply
the session type, a `SessionLoader`, and an `EffectHandler`, so storage and
application-specific behavior stay under your control. Persistence is supplied
by your runtime, not an embedded database. The core also supports WebAssembly
hosts, with platform-specific differences described in the crate documentation.
### [goose-provider-types](https://docs.rs/goose-provider-types/latest/goose_provider_types/)
The common language between an application and a model backend. It defines the
`Provider` trait, `ModelConfig`, `Conversation`, messages and their content,
tool requests and responses, token usage, and provider errors. It also supplies
shared model metadata and helpers for context limits, prompt caching, and
reasoning content, so these concepts do not need a different representation for
every provider.
Depend on this crate when implementing a provider or working with GDK messages
without needing the provider implementations or agent runtime. A provider
implements streaming through `MessageStream`; the default `complete` method
collects that stream into a message and usage. Text can arrive incrementally,
while tool calls are emitted once their arguments are assembled.
`goose-providers` re-exports these modules when you also need a working backend.
### [goose-providers](https://docs.rs/goose-providers/latest/goose_providers/)
The model backend implementations. It includes providers for services such as
OpenAI, Anthropic, Google Gemini, Azure AI Foundry, and Databricks, as well as
Ollama and OpenAI-compatible endpoints. They translate service-specific requests
and responses into the shared provider interface. The supporting `ApiClient`
handles HTTP requests and authentication, while shared helpers cover response
errors and request formatting. You can use these providers directly without
building an agent.
Many compatible services can be configured through a declarative JSON definition
that selects an engine, endpoint, configuration keys, and models. Use the bundled
definitions or load your own rather than write another provider implementation.
Optional features add local inference and its hardware backends; live-session
and voice interfaces support applications beyond text completions, with an
optional WebSocket transport. For native HTTPS connections, enable either
`rustls-tls` or `native-tls`; neither is enabled by default.
### [goose-context-management](https://docs.rs/goose-context-management/latest/goose_context_management/)
Summarization and conversation compaction for histories that are getting too
large for a model's context window. `summarize` turns a slice of messages into
a summary message and records the model usage. The higher-level `compact`
function reads and writes through `CompactionInput` and `CompactionOutput`, so
your application can keep its own conversation representation and storage.
Use `ProviderModel` to summarize with an existing GDK provider, or implement
`CompactionModel` to control model selection yourself. Prompt templates and an
optional `TokenEstimator` let you shape the summary and limit its input; the
crate also defines structured summaries with file activity. For a simpler
fallback, `CompactingProvider` wraps a provider and retries a context-length
error once with a summarized history. Compaction does not require the agent
state machine, and the trait-based API leaves saving the result to your app.
### [goose-local-inference](https://docs.rs/goose-local-inference/latest/goose_local_inference/)
Runs models on the user's machine, using llama.cpp for GGUF models and an
optional MLX backend on Apple silicon. It handles loading models, sharing loaded
instances, evicting them from memory, and applying chat templates. It also
interprets model output, including tool calls and reasoning blocks, and handles
image input for supported models. This is the inference engine, not a separate
model server your application must launch.
Use it through `goose-providers`' `local-inference` feature to get a
`LocalInferenceProvider` that implements the same `Provider` interface as remote
backends. Models can be loaded from local paths; the optional `hf-hub` feature
adds Hugging Face discovery, downloads, cache inventory, and model-management
APIs. CUDA, Vulkan, and MLX are selected through features. These backends have
native build requirements, and the models you can run depend on available
memory and hardware.
### [goose-download-manager](https://docs.rs/goose-download-manager/latest/goose_download_manager/)
Background downloads for model files, with progress that an application can
display. A `DownloadManager` tracks jobs by model ID and exposes status, bytes
downloaded, total size, speed, estimated time remaining, and errors. It supports
single files and groups of model shards, with combined progress across the
files, cancellation, and an optional completion callback.
The downloader writes to partial files, uses HTTP range requests to continue
partial transfers, retries transient failures, and renames completed files into
place. Bearer-token support lets it fetch files from authenticated endpoints.
Use this crate when your application already knows the download URLs and
destination paths. Model discovery and cache inventory belong to the
`hf-hub` layer in `goose-local-inference`; the download manager itself does not
choose a model or load it for inference.
### [goose-sdk-types](https://docs.rs/goose-sdk-types/latest/goose_sdk_types/)
The shared wire types for goose's additions to ACP. Its request, response, and
notification types describe methods under `_goose/*`, including extension and
tool management, provider configuration, recipes, and local-model management.
Custom notifications carry information such as session usage, status messages,
per-message timing, and provider authentication updates alongside standard ACP
events.
Use this crate in Rust code that needs to exchange those goose-specific
messages without depending on the goose application. The types include
serialization and JSON-schema definitions, keeping the wire format in one place
for the server, clients, and generated documentation. It does not start an agent
or establish a connection: use an ACP client library for transport and standard
protocol methods, and the [goose ACP reference](/docs/gdk/acp/reference) for the
additional methods.
### [goose-sdk](https://docs.rs/goose-sdk/latest/goose_sdk/)
The cross-language bindings package and a small Rust entry point for the shared
wire types. With default features, it re-exports `custom_requests` and
`custom_notifications` from `goose-sdk-types`. It is not an umbrella crate that
automatically assembles an agent or exposes every GDK component; Rust
applications building an in-process runtime use the component crates above.
The optional `uniffi` feature exposes native APIs to Python and Kotlin. These
bindings let you construct providers, list models, send typed message and tool
content, stream or collect completions, and compact conversations. They also
include typed decision requests and observability hooks for provider calls.
This is in-process access to the native library, not a connection to a running
goose process. The full agent state machine is not exposed through these
bindings; see the generated language references below for the available API.
## API documentation
- **Rust:** follow the crate links above for the full native APIs.
- **[Python](/docs/gdk/sdk/api-reference?language=python):** generated bindings reference.
- **[Kotlin](/docs/gdk/sdk/api-reference?language=kotlin):** generated bindings reference.
For coding agents or other clients without JavaScript, use the generated
[Python Markdown reference](pathname:///docs/gdk/sdk/api-reference-python.md) or
[Kotlin Markdown reference](pathname:///docs/gdk/sdk/api-reference-kotlin.md).
Both include method anchors and links to their versioned API snapshots.
The Python and Kotlin bindings currently expose model providers, streaming
completions, and conversation compaction. They do not expose the full agent
runtime available in Rust.
Select the documentation version that matches your dependencies. GDK is in alpha;
APIs may change between releases.
## ACP
For apps that connect to the pre-built goose agent, see the
[ACP walkthrough](/docs/gdk/acp), the
[standard protocol reference](https://agentclientprotocol.com/protocol/v1/overview),
and the generated reference for [goose extensions](/docs/gdk/acp/reference).
@@ -1,8 +0,0 @@
{
"label": "SDK",
"position": 1,
"link": {
"type": "doc",
"id": "gdk/sdk/index"
}
}
+13 -32
View File
@@ -1,44 +1,25 @@
---
sidebar_position: 2
title: SDK Reference
sidebar_label: API Reference
description: Rust GDK crate documentation on docs.rs and the shared Python and Kotlin bindings reference.
title: Python and Kotlin API Reference
description: Generated API documentation for the Python and Kotlin bindings.
displayed_sidebar: gdkSidebar
pagination_prev: null
pagination_next: null
---
import GdkApiReference from '@site/src/components/GdkApiReference';
import GdkApiReference from "@site/src/components/GdkApiReference";
# SDK Reference
## Rust API reference
For Rust, use the native GDK crate documentation on **docs.rs** as the primary
API reference. These crates expose the full Rust APIs, beyond the shared
`goose-sdk` bindings shown below.
| Crate | API |
| --- | --- |
| [`goose-agent`](https://docs.rs/goose-agent/latest/goose_agent/) | Agent state machine, operations, inference, and tools |
| [`goose-providers`](https://docs.rs/goose-providers/latest/goose_providers/) | Model provider implementations and declarative providers |
| [`goose-provider-types`](https://docs.rs/goose-provider-types/latest/goose_provider_types/) | Provider traits, messages, model configuration, and shared types |
| [`goose-context-management`](https://docs.rs/goose-context-management/latest/goose_context_management/) | Conversation compaction and summarization |
| [`goose-local-inference`](https://docs.rs/goose-local-inference/latest/goose_local_inference/) | On-device model inference and model management |
| [`goose-download-manager`](https://docs.rs/goose-download-manager/latest/goose_download_manager/) | Model downloads and download progress |
| [`goose-sdk-types`](https://docs.rs/goose-sdk-types/latest/goose_sdk_types/) | Shared goose ACP wire types |
| [`goose-sdk`](https://docs.rs/goose-sdk/latest/goose_sdk/) | Shared wire type re-exports and optional UniFFI bindings |
The links open the latest published crate documentation. Use the docs.rs version
selector to match the version in your project.
## Shared bindings reference
# Python and Kotlin API Reference {#shared-bindings-reference}
The generated reference below covers the `goose-sdk` UniFFI API used by Python
and Kotlin, with Rust signatures also available for that bindings layer. It is
not the full native Rust GDK API.
Use the toggles to switch language and bindings version — names and types are
shown using each language's own conventions.
This reference is also available as generated Markdown for
[Python](pathname:///docs/gdk/sdk/api-reference-python.md) and
[Kotlin](pathname:///docs/gdk/sdk/api-reference-kotlin.md), without JavaScript.
New to the SDK? Start with the [SDK overview](/docs/gdk/sdk) for
installation and runnable examples.
<span id="rust-api-reference" />
For native Rust, use the [crate documentation](/docs/gdk/reference#crates).
<GdkApiReference />
-240
View File
@@ -1,240 +0,0 @@
---
sidebar_position: 1
title: SDK
sidebar_label: Overview
description: Build with the native Rust GDK crates or shared provider bindings for Python and Kotlin.
---
# SDK
The SDK provides native Rust crates for agent orchestration, model providers,
and context management. Python and Kotlin access the provider layer through
shared bindings, so you can call models, stream completions, and compact
conversations from your own application.
For Rust, the primary API reference is the crate documentation on docs.rs:
- [`goose-agent`](https://docs.rs/goose-agent/latest/goose_agent/) — agent state machine and tools
- [`goose-providers`](https://docs.rs/goose-providers/latest/goose_providers/) — model providers
- [`goose-context-management`](https://docs.rs/goose-context-management/latest/goose_context_management/) — conversation compaction
- [All GDK crates](/docs/gdk/sdk/api-reference#rust-api-reference)
The `goose-sdk` crate is the source of the Python and Kotlin bindings, generated
with [UniFFI](https://github.com/mozilla/uniffi-rs). The
[shared bindings reference](/docs/gdk/sdk/api-reference#shared-bindings-reference)
documents that API in Python, Kotlin, and Rust; it does not cover the full native
Rust GDK API. The installation and examples below focus on this shared bindings
layer.
:::info Alpha
The SDK is in alpha. The surface may change between `0.x` releases. Pin an
exact version and select the matching version on docs.rs or in the shared
bindings reference when upgrading.
:::
## What you can do
- Construct providers for OpenAI, Anthropic, Groq, Databricks, or any
[declarative provider](#declarative-providers) defined in JSON
- Stream a completion chunk by chunk, including tool calls and reasoning output
- Request a single non-streaming completion
- Compact a long conversation into a summary so it can continue past the
model's context window
- Capture provider request logs as JSONL
## Install
<!-- prettier-ignore-start -->
### Rust
For native Rust, depend directly on the
[GDK crates](/docs/gdk/sdk/api-reference#rust-api-reference) your application needs
and follow their docs.rs documentation. To use the shared bindings API from Rust:
```bash
cargo add goose-sdk --features uniffi
```
The `uniffi` feature enables the in-process provider API documented here.
### Python
```bash
pip install goose-sdk
```
The package installs as `goose-sdk` and imports as `goose`. Wheels bundle the
native library, so there is nothing else to build. Requires Python 3.9+.
```python
import goose
```
### Kotlin / JVM
```kotlin
dependencies {
implementation("io.github.aaif-goose:gdk:<version>")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
}
```
The artifact version matches the Rust crate version. Classes live in the
`io.github.aaif_goose` package. The jar bundles native libraries for
macOS (arm64, x86-64), Linux (arm64, x86-64), and Windows (x86-64).
On JDK 24+, add `--enable-native-access=ALL-UNNAMED` because the GDK loads its
native library through JNA.
<!-- prettier-ignore-end -->
## Quickstart
Each example builds a provider, sends one message, and prints the streamed
response.
### Python
```python
import asyncio
from goose import (
MessageContent,
MessageRole,
ProviderMessage,
ProviderModelConfig,
StreamChunk,
openai_default_model,
openai_provider,
)
async def main() -> None:
provider = openai_provider(api_key="...")
model = ProviderModelConfig(model_name=openai_default_model())
messages = [
ProviderMessage(
role=MessageRole.USER,
content=[MessageContent.Text(text="What is the capital of France?")],
)
]
stream = await provider.stream(model, "You are a geography expert.", messages, [])
while chunk := await stream.next_chunk():
if isinstance(chunk, StreamChunk.TextChunk):
print(chunk.text, end="")
asyncio.run(main())
```
### Kotlin
```kotlin
import io.github.aaif_goose.MessageContent
import io.github.aaif_goose.MessageRole
import io.github.aaif_goose.ProviderMessage
import io.github.aaif_goose.ProviderModelConfig
import io.github.aaif_goose.StreamChunk
import io.github.aaif_goose.streamFlow
import io.github.aaif_goose.providers.openai.defaultModel
import io.github.aaif_goose.providers.openai.provider as openAiProvider
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val provider = openAiProvider(System.getenv("OPENAI_API_KEY"))
val model = ProviderModelConfig(modelName = defaultModel())
val messages = listOf(
ProviderMessage(
role = MessageRole.USER,
content = listOf(MessageContent.Text(text = "What is the capital of France?")),
),
)
provider.streamFlow(model, "You are a geography expert.", messages)
.collect { chunk ->
if (chunk is StreamChunk.TextChunk) print(chunk.text)
}
}
```
### Rust
```rust
use goose_sdk::bindings::{
openai_default_model, openai_provider, MessageContent, MessageRole, ProviderMessage,
ProviderModelConfig, StreamChunk,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider = openai_provider(std::env::var("OPENAI_API_KEY")?)?;
let model = ProviderModelConfig {
model_name: openai_default_model(),
..Default::default()
};
let messages = vec![ProviderMessage {
role: MessageRole::User,
content: vec![MessageContent::Text {
text: "What is the capital of France?".to_string(),
}],
}];
let stream = provider
.stream(model, "You are a geography expert.".to_string(), messages, vec![])
.await?;
while let Some(chunk) = stream.next_chunk().await? {
if let StreamChunk::TextChunk { text } = chunk {
print!("{text}");
}
}
Ok(())
}
```
## Kotlin idioms
The Kotlin package adds a few conveniences on top of the generated bindings:
| Kotlin API | Equivalent generated call |
| --- | --- |
| `provider.streamFlow(model, system, messages, tools)` | `stream(...)` plus a `nextChunk()` loop, as a `Flow<StreamChunk>` |
| `providers.openai.provider(apiKey)` | `openaiProvider(apiKey)` |
| `providers.openai.defaultModel()` | `openaiDefaultModel()` |
| `providers.anthropic.provider(apiKey, baseUrl, betaHeaders)` | `anthropicProvider(...)` |
| `providers.groq.provider(apiKey)` | `groqProvider(apiKey)` |
| `providers.databricks.provider(host, token)` | `databricksProvider(host, token)` |
`tools` defaults to an empty list in the Kotlin helpers, and suspending
functions map to Kotlin coroutines. Errors surface as `GooseException`
subclasses.
## Declarative providers
Any provider that speaks an OpenAI- or Anthropic-compatible API can be defined
in JSON and loaded without new Rust code:
```python
provider = goose.declarative_provider_from_json(open("deepseek.json").read())
```
Environment variable placeholders such as `${DEEPSEEK_API_KEY}` in the JSON are
resolved when the provider is constructed.
## Streaming model
`stream()` returns a `ProviderStream`. Call `next_chunk()` until it returns
`None` to consume the response:
| Chunk | Meaning |
| --- | --- |
| `TextChunk` | Assistant text |
| `ToolChunk` | A tool call request with JSON arguments and the provider's tool-call `index` |
| `ThinkingChunk` / `RedactedThinkingChunk` | Reasoning output |
| `EndChunk` | Stream finished, carries final token `Usage` |
| `ErrorChunk` | Mid-stream failure, carries a `GooseStreamError` |
Errors raised before the stream starts are thrown as `GooseError`
(`GooseException` in Kotlin). Errors that occur mid-stream arrive as an
`ErrorChunk` instead.
@@ -35,7 +35,7 @@ goose supports the [Agent Client Protocol (ACP)](https://agentclientprotocol.com
### goose as an ACP Server
`goose acp` starts goose as an ACP server over stdio, letting editors like JetBrains and Zed connect to it directly. See [Using goose in ACP Clients](/docs/gdk/acp).
`goose acp` starts goose as an ACP server over stdio, letting editors like JetBrains and Zed connect to it directly. See [Set up goose in Zed](/docs/guides/zed) for an editor setup example. To create your own client, see [Build an app with goose](/docs/gdk/acp).
### ACP Agents as Providers
@@ -713,7 +713,7 @@ goose acp
```
:::info
This command is automatically invoked by ACP-compatible clients and is not typically run directly by users. The client manages the lifecycle of the `goose acp` process. See [Using goose in ACP Clients](/docs/gdk/acp) for details.
This command is automatically invoked by ACP-compatible clients and is not typically run directly by users. The client manages the lifecycle of the `goose acp` process. See [Set up goose in Zed](/docs/guides/zed) for an editor setup example, or [Build an app with goose](/docs/gdk/acp) to create your own client.
:::
:::warning Unattended environments
@@ -1,6 +1,7 @@
---
title: Set up goose in Zed
sidebar_position: 3
sidebar_position: 10
displayed_sidebar: tutorialSidebar
description: See how Zed installs and configures goose as an ACP agent.
---