diff --git a/documentation/.gitignore b/documentation/.gitignore index 113ba2622..17339af9c 100644 --- a/documentation/.gitignore +++ b/documentation/.gitignore @@ -8,6 +8,8 @@ .docusaurus .cache-loader static/goose-docs-map.md +static/docs/gdk/sdk/api-reference-*.md +static/docs/gdk/sdk/*/api-reference-*.md static/skills-manifest.json static/skills-data-zips/ diff --git a/documentation/blog/2026-04-08-how-to-break-up-with-your-agent/index.md b/documentation/blog/2026-04-08-how-to-break-up-with-your-agent/index.md index 000200626..60eaa3453 100644 --- a/documentation/blog/2026-04-08-how-to-break-up-with-your-agent/index.md +++ b/documentation/blog/2026-04-08-how-to-break-up-with-your-agent/index.md @@ -4,6 +4,7 @@ description: "ACP lets you keep your favorite editor but swap the AI agent, or k authors: - codefromthecrypt image: /img/blog/how-to-break-up-with-your-agent.png +tags: [gdk] --- ![Editors connect to Goose via ACP, and Goose connects to multiple agents](/img/blog/how-to-break-up-with-your-agent.png) diff --git a/documentation/blog/2026-09-16-agentic-state-machines/index.md b/documentation/blog/2026-09-16-agentic-state-machines/index.md index f91808206..a425c7755 100644 --- a/documentation/blog/2026-09-16-agentic-state-machines/index.md +++ b/documentation/blog/2026-09-16-agentic-state-machines/index.md @@ -5,6 +5,7 @@ image: /img/blog/agentic-state-machines.jpg authors: - douwe featured: true +tags: [gdk] --- ![A goose walking from a tangled agent loop into an orderly sequence of machines](/img/blog/agentic-state-machines.jpg) diff --git a/documentation/blog/tags.yml b/documentation/blog/tags.yml index bfaa778fb..75387601f 100644 --- a/documentation/blog/tags.yml +++ b/documentation/blog/tags.yml @@ -1,3 +1,8 @@ +gdk: + label: GDK + permalink: /gdk + description: Building agents with the goose Development Kit. + facebook: label: Facebook permalink: /facebook diff --git a/documentation/docs/gdk/acp/index.md b/documentation/docs/gdk/acp/index.md index f6bce8eaa..512a37d99 100644 --- a/documentation/docs/gdk/acp/index.md +++ b/documentation/docs/gdk/acp/index.md @@ -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. diff --git a/documentation/docs/gdk/concepts/authentication.md b/documentation/docs/gdk/concepts/authentication.md new file mode 100644 index 000000000..bd1961080 --- /dev/null +++ b/documentation/docs/gdk/concepts/authentication.md @@ -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>, +} + +#[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/). diff --git a/documentation/docs/gdk/concepts/index.md b/documentation/docs/gdk/concepts/index.md new file mode 100644 index 000000000..24b8e76c2 --- /dev/null +++ b/documentation/docs/gdk/concepts/index.md @@ -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. diff --git a/documentation/docs/gdk/concepts/operations.md b/documentation/docs/gdk/concepts/operations.md new file mode 100644 index 000000000..88d091302 --- /dev/null +++ b/documentation/docs/gdk/concepts/operations.md @@ -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` 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 Operation for TurnLimit +where + S: Send + Sync, + E: From + Send + 'static, +{ + fn name(&self) -> &'static str { + "turn_limit" + } + + async fn run( + &self, + _session: &S, + conversation: &Conversation, + emit: &Emitter, + ) -> Result> { + 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/). diff --git a/documentation/docs/gdk/concepts/providers.md b/documentation/docs/gdk/concepts/providers.md new file mode 100644 index 000000000..2f048ce1e --- /dev/null +++ b/documentation/docs/gdk/concepts/providers.md @@ -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). + + + +## 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). diff --git a/documentation/docs/gdk/concepts/state-machine.md b/documentation/docs/gdk/concepts/state-machine.md new file mode 100644 index 000000000..75698f9f8 --- /dev/null +++ b/documentation/docs/gdk/concepts/state-machine.md @@ -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. + + + +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/). diff --git a/documentation/docs/gdk/demos/berd.md b/documentation/docs/gdk/demos/berd.md new file mode 100644 index 000000000..d20666a7d --- /dev/null +++ b/documentation/docs/gdk/demos/berd.md @@ -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. diff --git a/documentation/docs/gdk/demos/goosebusters.md b/documentation/docs/gdk/demos/goosebusters.md new file mode 100644 index 000000000..7f35cf5a3 --- /dev/null +++ b/documentation/docs/gdk/demos/goosebusters.md @@ -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. diff --git a/documentation/docs/gdk/demos/huddle.md b/documentation/docs/gdk/demos/huddle.md new file mode 100644 index 000000000..e10e344bb --- /dev/null +++ b/documentation/docs/gdk/demos/huddle.md @@ -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. +::: diff --git a/documentation/docs/gdk/demos/index.mdx b/documentation/docs/gdk/demos/index.mdx new file mode 100644 index 000000000..726075830 --- /dev/null +++ b/documentation/docs/gdk/demos/index.mdx @@ -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. + +
+ +
+

Memory you can inspect

+ +## lifewiki + +Turn everyday notes into a cited, evolving personal wiki. Keep the original +record while an agent reconciles what has changed. + +
+GDK + +[Explore →](/docs/gdk/demos/lifewiki) + +
+
+ +
+

An agent that makes phone calls

+ +## GooseBusters + +Plan a call, approve it, and let an agent hold the conversation. Custom +operations supervise the call and collect its outcome. + +
+GDK + +[Explore →](/docs/gdk/demos/goosebusters) + +
+
+ +
+

Voice with a working agent behind it

+ +## Huddle + +Talk naturally while a separate agent handles longer tasks. Live provider events +connect the conversation to an ACP agent. + +
+GDK + ACP + +[Explore →](/docs/gdk/demos/huddle) + +
+
+ +
+

An agent without a chat box

+ +## goose Perception + +Turn desktop activity into a searchable wiki. Short-lived agent sessions share +a lasting memory through ordinary files. + +
+goose over ACP + +[Explore →](/docs/gdk/demos/perception) + +
+
+ +
+

Conversations tied to your work

+ +## Top Goose + +Give each GitHub issue and pull request its own private agent conversation, +with persistent sessions and separate worktrees. + +
+goose over ACP + +[Explore →](/docs/gdk/demos/top-goose) + +
+
+ +
+

Your application, goose's runtime

+ +## Berd + +Build a complete desktop experience around a bundled goose backend. The +interface and agent communicate over ACP. + +
+goose over ACP + +[Explore →](/docs/gdk/demos/berd) + +
+
+ +
+ +These are independent projects at different stages of development. Their source +repositories contain the current setup instructions and dependency versions. diff --git a/documentation/docs/gdk/demos/lifewiki.md b/documentation/docs/gdk/demos/lifewiki.md new file mode 100644 index 000000000..7c3cf2e0c --- /dev/null +++ b/documentation/docs/gdk/demos/lifewiki.md @@ -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> = 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. diff --git a/documentation/docs/gdk/demos/perception.md b/documentation/docs/gdk/demos/perception.md new file mode 100644 index 000000000..07d361d62 --- /dev/null +++ b/documentation/docs/gdk/demos/perception.md @@ -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. +::: diff --git a/documentation/docs/gdk/demos/top-goose.md b/documentation/docs/gdk/demos/top-goose.md new file mode 100644 index 000000000..5f337a459 --- /dev/null +++ b/documentation/docs/gdk/demos/top-goose.md @@ -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. +::: diff --git a/documentation/docs/gdk/hello-world.md b/documentation/docs/gdk/hello-world.md new file mode 100644 index 000000000..8795e1088 --- /dev/null +++ b/documentation/docs/gdk/hello-world.md @@ -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, + model: ModelConfig, + cancel: CancellationToken, +) -> StateMachine<'static, Session, Effect> { + StateMachine::new( + vec![ + Step::Operation(Arc::new( + ToolOperation::::new().with_async_tool::(), + )), + Step::Inference(Arc::new( + InferenceRunner::::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 = 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, +} +``` + +`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> { + 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` implements the actual behavior. It receives the loaded +session, so it can start commands in the session's saved working directory: + +```rust +impl AsyncTool for Shell { + async fn invoke(session: &Session, input: ShellInput) -> Result { + 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::()` 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 for Prompt { + async fn prepare( + &self, + _: &Session, + _: &Conversation, + input: InferenceInput, + ) -> Result { + 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 for Runtime { + async fn load(&self, id: &str) -> Result { + 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 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` 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. diff --git a/documentation/docs/gdk/index.md b/documentation/docs/gdk/index.md index 0e034f435..c5cd7d92d 100644 --- a/documentation/docs/gdk/index.md +++ b/documentation/docs/gdk/index.md @@ -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. diff --git a/documentation/docs/gdk/reference/_category_.json b/documentation/docs/gdk/reference/_category_.json new file mode 100644 index 000000000..91cd0f422 --- /dev/null +++ b/documentation/docs/gdk/reference/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Reference", + "position": 3, + "link": { + "type": "doc", + "id": "gdk/reference/index" + } +} diff --git a/documentation/docs/gdk/reference/index.md b/documentation/docs/gdk/reference/index.md new file mode 100644 index 000000000..b7f1664f8 --- /dev/null +++ b/documentation/docs/gdk/reference/index.md @@ -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). diff --git a/documentation/docs/gdk/sdk/_category_.json b/documentation/docs/gdk/sdk/_category_.json deleted file mode 100644 index 18edbd5d5..000000000 --- a/documentation/docs/gdk/sdk/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "SDK", - "position": 1, - "link": { - "type": "doc", - "id": "gdk/sdk/index" - } -} diff --git a/documentation/docs/gdk/sdk/api-reference.mdx b/documentation/docs/gdk/sdk/api-reference.mdx index e084f1848..389c3a2c4 100644 --- a/documentation/docs/gdk/sdk/api-reference.mdx +++ b/documentation/docs/gdk/sdk/api-reference.mdx @@ -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. + + +For native Rust, use the [crate documentation](/docs/gdk/reference#crates). diff --git a/documentation/docs/gdk/sdk/index.md b/documentation/docs/gdk/sdk/index.md deleted file mode 100644 index 070041b0c..000000000 --- a/documentation/docs/gdk/sdk/index.md +++ /dev/null @@ -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 - - - -### 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:") - 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. - - - -## 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> { - 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` | -| `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. diff --git a/documentation/docs/goose-architecture/goose-architecture.md b/documentation/docs/goose-architecture/goose-architecture.md index 4d5da395b..8e717cd7e 100644 --- a/documentation/docs/goose-architecture/goose-architecture.md +++ b/documentation/docs/goose-architecture/goose-architecture.md @@ -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 diff --git a/documentation/docs/guides/goose-cli-commands.md b/documentation/docs/guides/goose-cli-commands.md index 22b631966..0c251c328 100644 --- a/documentation/docs/guides/goose-cli-commands.md +++ b/documentation/docs/guides/goose-cli-commands.md @@ -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 diff --git a/documentation/docs/gdk/acp/zed.md b/documentation/docs/guides/zed.md similarity index 98% rename from documentation/docs/gdk/acp/zed.md rename to documentation/docs/guides/zed.md index 6ccb314b5..6cccd9814 100644 --- a/documentation/docs/gdk/acp/zed.md +++ b/documentation/docs/guides/zed.md @@ -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. --- diff --git a/documentation/docusaurus.config.ts b/documentation/docusaurus.config.ts index 0e2ab0a99..0cea9b1b0 100644 --- a/documentation/docusaurus.config.ts +++ b/documentation/docusaurus.config.ts @@ -65,7 +65,17 @@ const config: Config = { docs: { sidebarPath: "./sidebars.ts", async sidebarItemsGenerator(args) { - const items = await args.defaultSidebarItemsGenerator(args); + const generatedItems = await args.defaultSidebarItemsGenerator(args); + const items = + args.item.dirName === "." + ? generatedItems.map((item) => + item.type === "category" && + item.link?.type === "doc" && + item.link.id === "gdk/index" + ? { type: "link" as const, label: "GDK", href: "/docs/gdk" } + : item, + ) + : generatedItems; const contextEngineeringItems = [ { @@ -145,6 +155,14 @@ const config: Config = { "@docusaurus/plugin-client-redirects", { redirects: [ + { + from: "/docs/gdk/acp/zed", + to: "/docs/guides/zed", + }, + { + from: "/docs/gdk/sdk", + to: "/docs/gdk/reference", + }, { from: "/docs/getting-started/using-goose-free", to: "/docs/getting-started/providers#using-goose-for-free", @@ -504,6 +522,10 @@ const config: Config = { label: "Extensions", to: "/extensions", }, + { + label: "GDK", + to: "/docs/gdk/", + }, ], }, { @@ -559,14 +581,6 @@ const config: Config = { theme: prismThemes.github, darkTheme: prismThemes.nightOwl, }, - announcementBar: { - id: 'goose-aaif-announcement', // Increment on new announcements to reuse the bar - content: - '✨ goose has moved to the Agentic AI Foundation (AAIF): Learn more! ✨', - backgroundColor: '#20232a', - textColor: '#fff', - isCloseable: true, - }, } satisfies Preset.ThemeConfig, }; diff --git a/documentation/package.json b/documentation/package.json index c881a5ef9..9c20e4a85 100644 --- a/documentation/package.json +++ b/documentation/package.json @@ -4,8 +4,8 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "docusaurus start", - "build": "node scripts/generate-docs-map.js && docusaurus build", + "start": "node scripts/generate-gdk-api-markdown.js && docusaurus start", + "build": "node scripts/generate-docs-map.js && node scripts/generate-gdk-api-markdown.js && docusaurus build", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", "clear": "docusaurus clear", diff --git a/documentation/plugins/markdown-export.cjs b/documentation/plugins/markdown-export.cjs index dbfcfb445..1ffeab49a 100644 --- a/documentation/plugins/markdown-export.cjs +++ b/documentation/plugins/markdown-export.cjs @@ -55,6 +55,7 @@ function stripFrontmatter(content) { // Remove excessive empty lines and trim return withoutImports + .replace(/\]\(pathname:\/\/\//g, '](/') .replace(/\n{3,}/g, '\n\n') .trim(); } diff --git a/documentation/scripts/generate-acp-docs.js b/documentation/scripts/generate-acp-docs.js index 009bd67a1..058a4ef30 100644 --- a/documentation/scripts/generate-acp-docs.js +++ b/documentation/scripts/generate-acp-docs.js @@ -240,7 +240,8 @@ function renderDocumentation(schemas, meta, gooseVersion = 'Preview') { const output = [ '---', 'title: goose ACP Reference', - 'sidebar_label: Reference', + 'sidebar_label: goose extensions', + 'displayed_sidebar: gdkSidebar', 'sidebar_position: 2', '---', '', diff --git a/documentation/scripts/generate-docs-map.js b/documentation/scripts/generate-docs-map.js index 5eafbaaba..609477165 100644 --- a/documentation/scripts/generate-docs-map.js +++ b/documentation/scripts/generate-docs-map.js @@ -46,6 +46,7 @@ async function main() { const sections = [ { name: 'Getting Started', pattern: 'getting-started/*.{md,mdx}' }, { name: 'Guides', pattern: 'guides/**/*.{md,mdx}' }, + { name: 'GDK', pattern: 'gdk/**/*.{md,mdx}' }, ]; let output = `# goose Documentation Map diff --git a/documentation/scripts/generate-gdk-api-markdown.js b/documentation/scripts/generate-gdk-api-markdown.js new file mode 100644 index 000000000..eaabb81c1 --- /dev/null +++ b/documentation/scripts/generate-gdk-api-markdown.js @@ -0,0 +1,133 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { + LANGUAGES, + funcAnchor, + itemAnchor, + memberAnchor, + signature, + variantName, +} = require("../src/components/GdkApiReference/api"); + +const cell = (value) => + String(value).replace(/\|/g, "\\|").replace(/\r?\n/g, "
"); +const heading = (level, anchor, name) => + `\n\n${"#".repeat(level)} ${name}\n`; + +function parameterTable(rows, language, anchor, kind) { + if (rows.length === 0) return ""; + return [ + "| Name | Type | Default | Description |", + "| --- | --- | --- | --- |", + ...rows.map((row) => { + const name = language.field(row.name); + const type = language.type(row.type); + const value = + row.default === null ? "—" : `\`${language.default(row.default)}\``; + return `| \`${name}\` | \`${cell(type)}\` | ${cell(value)} | ${cell(row.docs || "—")} |`; + }), + "", + ].join("\n"); +} + +function renderFunction(func, language, owner) { + const anchor = funcAnchor(func, owner); + return [ + heading(owner ? 4 : 3, anchor, `\`${language.func(func.name)}\``), + ...(func.docs ? [func.docs, ""] : []), + `\`\`\`${language.prism}`, + signature(func, language, owner), + "```", + "", + parameterTable(func.params, language, anchor, "param"), + ...(func.throws + ? [`Raises \`${language.errorType(func.throws)}\`.`, ""] + : []), + ].join("\n"); +} + +function renderMarkdown(doc, language) { + const filename = `api-reference-${language.id}.md`; + const output = [ + `# ${language.label} API reference`, + "", + `Generated from \`${doc.source}\` for \`goose-sdk ${doc.version}\` (documentation series ${doc.docVersion}). Do not edit this file.`, + "", + `This is the in-process provider and compaction API, not the full Rust agent runtime. Read the [crate overview](/docs/gdk/reference/index.md) for native Rust APIs.`, + "", + `[Versioned copy](/docs/gdk/sdk/${doc.version}/${filename}). Match the API snapshot to your installed package before writing code.`, + "", + "## Contents", + "", + "- [Functions](#functions)", + ...doc.items.map((item) => { + const name = + item.kind === "error" ? language.errorType(item.name) : item.name; + return `- [${name}](#${itemAnchor(item)})`; + }), + "", + heading(2, "functions", "Functions"), + ...doc.functions.map((func) => renderFunction(func, language)), + ]; + + for (const item of doc.items) { + const anchor = itemAnchor(item); + const name = + item.kind === "error" ? language.errorType(item.name) : item.name; + output.push( + heading(2, anchor, `\`${name}\``), + `Kind: ${item.kind}.`, + "", + ...(item.docs ? [item.docs, ""] : []), + parameterTable(item.fields, language, anchor, "field"), + ); + for (const variant of item.variants) { + const variantAnchor = memberAnchor(anchor, "variant", variant.name); + output.push( + heading( + 3, + variantAnchor, + `\`${variantName(item, variant, language)}\``, + ), + parameterTable(variant.fields, language, variantAnchor, "field"), + ); + } + output.push( + ...item.methods.map((method) => + renderFunction(method, language, item.name), + ), + ); + } + + return ( + output + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trimEnd() + "\n" + ); +} + +function generateReferences(data, outputDir) { + for (const language of LANGUAGES.filter((entry) => entry.id !== "rust")) { + const filename = `api-reference-${language.id}.md`; + for (const [index, doc] of data.versions.entries()) { + const content = renderMarkdown(doc, language); + const versionDir = path.join(outputDir, doc.version); + fs.mkdirSync(versionDir, { recursive: true }); + fs.writeFileSync(path.join(versionDir, filename), content); + if (index === 0) + fs.writeFileSync(path.join(outputDir, filename), content); + } + } +} + +if (require.main === module) { + const data = require("../src/data/gdk-api.json"); + const outputDir = path.join(__dirname, "../static/docs/gdk/sdk"); + generateReferences(data, outputDir); + console.log( + `[generate-gdk-api-markdown] Generated Python and Kotlin references in ${outputDir}`, + ); +} + +module.exports = { renderMarkdown, generateReferences }; diff --git a/documentation/scripts/generate-gdk-api-markdown.test.js b/documentation/scripts/generate-gdk-api-markdown.test.js new file mode 100644 index 000000000..7c167b524 --- /dev/null +++ b/documentation/scripts/generate-gdk-api-markdown.test.js @@ -0,0 +1,149 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { + generateReferences, + renderMarkdown, +} = require("./generate-gdk-api-markdown"); +const { LANGUAGES } = require("../src/components/GdkApiReference/api"); +const data = require("../src/data/gdk-api.json"); + +test("publishes the linked APIs and preserves versioned snapshots", (t) => { + const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), "gdk-api-markdown-")); + t.after(() => fs.rmSync(outputDir, { recursive: true, force: true })); + const previous = { ...data.versions[0], version: "0.0.1", docVersion: "0.0" }; + const versions = [...data.versions, previous]; + generateReferences({ versions }, outputDir); + + const llms = fs.readFileSync( + path.join(__dirname, "../static/llms.txt"), + "utf8", + ); + const links = [ + ...llms.matchAll( + /\]\((\/docs\/gdk\/sdk\/api-reference-(?:python|kotlin)\.md)(?:#([^)]*))?\)/g, + ), + ]; + assert.ok( + links.length > 0, + "llms.txt must advertise the generated references", + ); + for (const [, target, anchor] of links) { + const content = fs.readFileSync( + path.join(outputDir, path.basename(target)), + "utf8", + ); + if (anchor) + assert.ok( + content.includes(`id="${anchor}"`), + `Missing ${target}#${anchor}`, + ); + } + + for (const language of ["python", "kotlin"]) { + const filename = `api-reference-${language}.md`; + const latest = fs.readFileSync(path.join(outputDir, filename), "utf8"); + for (const [index, doc] of versions.entries()) { + const snapshot = fs.readFileSync( + path.join(outputDir, doc.version, filename), + "utf8", + ); + assert.ok(snapshot.includes(`goose-sdk ${doc.version}`)); + if (index === 0) assert.equal(latest, snapshot); + else assert.notEqual(latest, snapshot); + for (const func of doc.functions) { + const anchor = `fn-${func.name.replaceAll("_", "-")}`; + assert.ok( + snapshot.includes(`id="${anchor}"`), + `Missing function ${func.name}`, + ); + } + for (const item of doc.items) { + assert.ok(snapshot.includes(`id="${item.name.toLowerCase()}"`)); + for (const method of item.methods) { + const anchor = `${item.name}-${method.name}` + .replaceAll("_", "-") + .toLowerCase(); + assert.ok( + snapshot.includes(`id="${anchor}"`), + `Missing method ${item.name}.${method.name}`, + ); + } + } + } + } +}); + +test("renders binding signatures, defaults, error payloads, and field documentation", () => { + const python = renderMarkdown( + data.versions[0], + LANGUAGES.find((entry) => entry.id === "python"), + ); + assert.ok( + python.includes( + "async def Provider.stream(model: ProviderModelConfig, system: str, messages: list[ProviderMessage], tools: list[ProviderTool]) -> ProviderStream", + ), + ); + assert.ok( + python.includes( + "async def ProviderStream.next_chunk() -> StreamChunk | None", + ), + ); + assert.ok( + python.includes( + "async def Provider.compact(model_name: str, messages: list[CompactionMessage], templates: CompactionTemplates | None) -> CompactionSummary", + ), + ); + assert.ok(python.includes("`toolshim` | `bool` | `False`")); + assert.ok( + python.includes("`request_headers` | `dict[str, str] \\| None` | `None`"), + ); + assert.ok( + python.includes( + "Per-request HTTP headers attached to the outgoing provider call.", + ), + ); + assert.ok( + python.includes('id="gooseerror-variant-ratelimited-field-retry-after-ms"'), + ); + assert.ok(python.includes("Raises `GooseError`.")); + assert.ok(!python.includes(" entry.id === "kotlin"), + ); + assert.ok( + kotlin.includes("suspend fun ProviderStream.nextChunk(): StreamChunk?"), + ); + assert.ok( + kotlin.includes( + "suspend fun Provider.listModels(): List", + ), + ); + assert.ok( + kotlin.includes("`requestHeaders` | `Map?` | `null`"), + ); + assert.ok(kotlin.includes("@Throws(GooseException::class)")); + assert.ok(kotlin.includes("### `GooseException.RateLimited`")); +}); + +test("Markdown exports turn static download links into fetchable paths", async (t) => { + const siteDir = fs.mkdtempSync( + path.join(os.tmpdir(), "gdk-markdown-export-"), + ); + t.after(() => fs.rmSync(siteDir, { recursive: true, force: true })); + fs.mkdirSync(path.join(siteDir, "docs")); + fs.writeFileSync( + path.join(siteDir, "docs/reference.mdx"), + '---\ntitle: Reference\n---\nimport Api from "./api";\n\n[Python](pathname:///docs/gdk/sdk/api-reference-python.md)\n', + ); + const plugin = require("../plugins/markdown-export.cjs")({ siteDir }); + await plugin.postBuild({ outDir: path.join(siteDir, "build") }); + assert.equal( + fs.readFileSync(path.join(siteDir, "build/docs/reference.md"), "utf8"), + "[Python](/docs/gdk/sdk/api-reference-python.md)", + ); +}); diff --git a/documentation/sidebars.ts b/documentation/sidebars.ts index 289713975..2a0c8d2ed 100644 --- a/documentation/sidebars.ts +++ b/documentation/sidebars.ts @@ -1,33 +1,41 @@ -import type {SidebarsConfig} from '@docusaurus/plugin-content-docs'; +import type { SidebarsConfig } from "@docusaurus/plugin-content-docs"; -// This runs in Node.js - Don't use client-side code here (browser APIs, JSX...) - -/** - * Creating a sidebar enables you to: - - create an ordered group of docs - - render a sidebar for each doc of that group - - provide next/previous navigation - - The sidebars can be generated from the filesystem, or explicitly defined here. - - Create as many sidebars as you want. - */ const sidebars: SidebarsConfig = { - // By default, Docusaurus generates a sidebar from the docs folder structure - tutorialSidebar: [{type: 'autogenerated', dirName: '.'}], - - // But you can create a sidebar manually - /* - tutorialSidebar: [ - 'intro', - 'hello', + tutorialSidebar: [{ type: "autogenerated", dirName: "." }], + gdkSidebar: [ + { type: "doc", id: "gdk/index", label: "Introduction" }, + "gdk/hello-world", { - type: 'category', - label: 'Tutorial', - items: ['tutorial-basics/create-a-document'], + type: "category", + label: "Demos", + link: { type: "doc", id: "gdk/demos/index" }, + items: [ + "gdk/demos/lifewiki", + "gdk/demos/goosebusters", + "gdk/demos/huddle", + "gdk/demos/perception", + "gdk/demos/top-goose", + "gdk/demos/berd", + ], }, + { + type: "category", + label: "Concepts", + link: { type: "doc", id: "gdk/concepts/index" }, + items: [ + "gdk/concepts/state-machine", + "gdk/concepts/operations", + "gdk/concepts/providers", + "gdk/concepts/authentication", + ], + }, + { + type: "category", + label: "ACP", + items: ["gdk/acp/index", "gdk/acp/reference"], + }, + "gdk/reference/index", ], - */ }; export default sidebars; diff --git a/documentation/src/components/GdkApiReference/api.d.ts b/documentation/src/components/GdkApiReference/api.d.ts new file mode 100644 index 000000000..bfa16a594 --- /dev/null +++ b/documentation/src/components/GdkApiReference/api.d.ts @@ -0,0 +1,66 @@ +export type LanguageId = "rust" | "python" | "kotlin"; + +export type Language = { + id: LanguageId; + label: string; + prism: string; + func: (name: string) => string; + field: (name: string) => string; + variant: (name: string, isDataCarrying: boolean) => string; + type: (type: string) => string; + default: (value: string) => string; + errorType: (name: string) => string; +}; + +export type GdkParam = { + name: string; + type: string; + default: string | null; + docs: string; +}; + +export type GdkFunc = { + name: string; + docs: string; + params: GdkParam[]; + returns: string | null; + throws: string | null; + isAsync: boolean; +}; + +export type GdkItem = { + name: string; + kind: "object" | "callback" | "record" | "enum" | "error"; + docs: string; + fields: GdkParam[]; + variants: { name: string; fields: GdkParam[] }[]; + methods: GdkFunc[]; +}; + +export type GdkApiDoc = { + version: string; + docVersion: string; + source: string; + functions: GdkFunc[]; + items: GdkItem[]; +}; + +export const LANGUAGES: Language[]; +export function slug(...parts: string[]): string; +export function funcAnchor(func: GdkFunc, owner?: string): string; +export function itemAnchor(item: GdkItem): string; +export function memberAnchor( + ownerAnchor: string, + kind: string, + name: string, +): string; +export function signature( + func: GdkFunc, + language: Language, + owner?: string, +): string; +export function variantName( + item: GdkItem, + variant: GdkItem["variants"][number], + language: Language, +): string; diff --git a/documentation/src/components/GdkApiReference/languages.ts b/documentation/src/components/GdkApiReference/api.js similarity index 54% rename from documentation/src/components/GdkApiReference/languages.ts rename to documentation/src/components/GdkApiReference/api.js index a1b59fefa..67c30beda 100644 --- a/documentation/src/components/GdkApiReference/languages.ts +++ b/documentation/src/components/GdkApiReference/api.js @@ -2,20 +2,16 @@ // mirror the uniffi 0.32 code generators, which are the actual source of the // Python and Kotlin bindings. -export type LanguageId = "rust" | "python" | "kotlin"; - -const toSnake = (name: string) => name; -const toCamel = (name: string) => - name.replace(/_([a-z0-9])/g, (_, char: string) => char.toUpperCase()); -const toShoutySnake = (name: string) => +const toSnake = (name) => name; +const toCamel = (name) => + name.replace(/_([a-z0-9])/g, (_, char) => char.toUpperCase()); +const toShoutySnake = (name) => name .replace(/([a-z0-9])([A-Z])/g, "$1_$2") .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2") .toUpperCase(); -type Scalars = Record; - -const PYTHON_SCALARS: Scalars = { +const PYTHON_SCALARS = { String: "str", bool: "bool", i8: "int", @@ -31,7 +27,7 @@ const PYTHON_SCALARS: Scalars = { "()": "None", }; -const KOTLIN_SCALARS: Scalars = { +const KOTLIN_SCALARS = { String: "String", bool: "Boolean", i8: "Byte", @@ -47,10 +43,10 @@ const KOTLIN_SCALARS: Scalars = { "()": "Unit", }; -const generic = (type: string, name: string): string[] | null => { +const generic = (type, name) => { const match = new RegExp(`^${name}\\s*<(.+)>$`, "s").exec(type.trim()); if (!match) return null; - const args: string[] = []; + const args = []; let depth = 0; let current = ""; for (const char of match[1]) { @@ -67,7 +63,7 @@ const generic = (type: string, name: string): string[] | null => { return args; }; -const mapType = (type: string, language: LanguageId): string => { +const mapType = (type, language) => { const trimmed = type.trim(); if (language === "rust") return trimmed; @@ -92,35 +88,28 @@ const mapType = (type: string, language: LanguageId): string => { const map = generic(trimmed, "HashMap"); if (map) { const [key, value] = map.map((arg) => mapType(arg, language)); - return language === "python" ? `dict[${key}, ${value}]` : `Map<${key}, ${value}>`; + return language === "python" + ? `dict[${key}, ${value}]` + : `Map<${key}, ${value}>`; } return trimmed; }; -const mapDefault = (value: string, language: LanguageId): string => { +const mapDefault = (value, language) => { if (language === "rust") return value; if (value === "None") return language === "python" ? "None" : "null"; if (value === "true" || value === "false") { - return language === "python" ? (value === "true" ? "True" : "False") : value; + return language === "python" + ? value === "true" + ? "True" + : "False" + : value; } return value; }; -export type Language = { - id: LanguageId; - label: string; - /** Prism language for syntax highlighting. */ - prism: string; - func: (name: string) => string; - field: (name: string) => string; - variant: (name: string, isDataCarrying: boolean) => string; - type: (type: string) => string; - default: (value: string) => string; - errorType: (name: string) => string; -}; - -export const LANGUAGES: Language[] = [ +const LANGUAGES = [ { id: "rust", label: "Rust", @@ -140,7 +129,8 @@ export const LANGUAGES: Language[] = [ field: toSnake, // Flat enums become `enum.Enum` members; data-carrying variants become // nested dataclasses that keep their Rust casing. - variant: (name, isDataCarrying) => (isDataCarrying ? name : toShoutySnake(name)), + variant: (name, isDataCarrying) => + isDataCarrying ? name : toShoutySnake(name), type: (type) => mapType(type, "python"), default: (value) => mapDefault(value, "python"), errorType: (name) => name, @@ -153,9 +143,73 @@ export const LANGUAGES: Language[] = [ field: toCamel, // Flat enums become `enum class` entries; data-carrying variants become // `sealed class` subclasses that keep their Rust casing. - variant: (name, isDataCarrying) => (isDataCarrying ? name : toShoutySnake(name)), + variant: (name, isDataCarrying) => + isDataCarrying ? name : toShoutySnake(name), type: (type) => mapType(type, "kotlin"), default: (value) => mapDefault(value, "kotlin"), errorType: (name) => name.replace(/Error$/, "Exception"), }, ]; + +const slug = (...parts) => + parts + .join("-") + .replace(/[^a-zA-Z0-9]+/g, "-") + .toLowerCase(); + +const funcAnchor = (func, owner) => slug(owner ?? "fn", func.name); +const itemAnchor = (item) => slug(item.name); +const memberAnchor = (ownerAnchor, kind, name) => slug(ownerAnchor, kind, name); + +function signature(func, language, owner) { + const params = func.params + .map((param) => { + const type = language.type(param.type); + const suffix = param.default + ? ` = ${language.default(param.default)}` + : ""; + return `${language.field(param.name)}: ${type}${suffix}`; + }) + .join(", "); + + const name = language.func(func.name); + const returns = func.returns ? language.type(func.returns) : null; + const prefix = owner ? `${owner}.` : ""; + + if (language.id === "rust") { + const asyncKeyword = func.isAsync ? "async " : ""; + const result = func.throws + ? `Result<${returns ?? "()"}, ${func.throws}>` + : returns; + return `${asyncKeyword}fn ${prefix}${name}(${params})${result ? ` -> ${result}` : ""}`; + } + + if (language.id === "python") { + const asyncKeyword = func.isAsync ? "async " : ""; + return `${asyncKeyword}def ${prefix}${name}(${params})${returns ? ` -> ${returns}` : ""}`; + } + + const suspend = func.isAsync ? "suspend " : ""; + const throwsAnnotation = func.throws + ? `@Throws(${language.errorType(func.throws)}::class)\n` + : ""; + return `${throwsAnnotation}${suspend}fun ${prefix}${name}(${params})${returns ? `: ${returns}` : ""}`; +} + +function variantName(item, variant, language) { + if (item.kind === "error" && language.id === "kotlin") { + return `${language.errorType(item.name)}.${variant.name}`; + } + const dataCarrying = item.variants.some((entry) => entry.fields.length > 0); + return language.variant(variant.name, dataCarrying); +} + +module.exports = { + LANGUAGES, + slug, + funcAnchor, + itemAnchor, + memberAnchor, + signature, + variantName, +}; diff --git a/documentation/src/components/GdkApiReference/index.tsx b/documentation/src/components/GdkApiReference/index.tsx index 46942beb7..167ce1980 100644 --- a/documentation/src/components/GdkApiReference/index.tsx +++ b/documentation/src/components/GdkApiReference/index.tsx @@ -6,42 +6,23 @@ import { useHistory, useLocation } from "@docusaurus/router"; import { useAnchorTargetClassName } from "@docusaurus/theme-common"; import CodeBlock from "@theme/CodeBlock"; import apiData from "@site/src/data/gdk-api.json"; -import { LANGUAGES, Language, LanguageId } from "./languages"; +import { + LANGUAGES, + slug, + funcAnchor, + itemAnchor, + memberAnchor, + signature, + variantName, + type Language, + type LanguageId, + type GdkParam, + type GdkFunc, + type GdkItem, + type GdkApiDoc, +} from "./api"; import styles from "./styles.module.css"; -type GdkParam = { - name: string; - type: string; - default: string | null; - docs: string; -}; - -type GdkFunc = { - name: string; - docs: string; - params: GdkParam[]; - returns: string | null; - throws: string | null; - isAsync: boolean; -}; - -type GdkItem = { - name: string; - kind: "object" | "callback" | "record" | "enum" | "error"; - docs: string; - fields: GdkParam[]; - variants: { name: string; fields: GdkParam[] }[]; - methods: GdkFunc[]; -}; - -type GdkApiDoc = { - version: string; - docVersion: string; - source: string; - functions: GdkFunc[]; - items: GdkItem[]; -}; - const VERSIONS = (apiData as { versions: GdkApiDoc[] }).versions; const DEFAULT_VERSION = VERSIONS[0].docVersion; @@ -64,8 +45,12 @@ const readSelection = (search: string): Selection => { const requestedVersion = params.get(VERSION_PARAM); const requestedLanguage = params.get(LANGUAGE_PARAM); return { - docVersion: isKnownVersion(requestedVersion) ? requestedVersion : DEFAULT_VERSION, - languageId: isKnownLanguage(requestedLanguage) ? requestedLanguage : DEFAULT_LANGUAGE, + docVersion: isKnownVersion(requestedVersion) + ? requestedVersion + : DEFAULT_VERSION, + languageId: isKnownLanguage(requestedLanguage) + ? requestedLanguage + : DEFAULT_LANGUAGE, }; }; @@ -96,19 +81,12 @@ const KIND_HEADINGS: Record = { error: "Errors", }; -const slug = (...parts: string[]) => - parts.join("-").replace(/[^a-zA-Z0-9]+/g, "-").toLowerCase(); - -// Anchors use the canonical Rust names so a link keeps working when the reader -// switches the language or version toggle. -const funcAnchor = (func: GdkFunc, owner?: string) => slug(owner ?? "fn", func.name); -const itemAnchor = (item: GdkItem) => slug(item.name); -const memberAnchor = (ownerAnchor: string, kind: string, name: string) => - slug(ownerAnchor, kind, name); - function anchorsForFunc(func: GdkFunc, owner?: string): string[] { const anchor = funcAnchor(func, owner); - return [anchor, ...func.params.map((param) => memberAnchor(anchor, "param", param.name))]; + return [ + anchor, + ...func.params.map((param) => memberAnchor(anchor, "param", param.name)), + ]; } function anchorsForDoc(doc: GdkApiDoc): string[] { @@ -118,56 +96,20 @@ function anchorsForDoc(doc: GdkApiDoc): string[] { doc.items.forEach((item) => { const anchor = itemAnchor(item); anchors.push(anchor, slug(item.kind, "types")); - item.fields.forEach((field) => anchors.push(memberAnchor(anchor, "field", field.name))); + item.fields.forEach((field) => + anchors.push(memberAnchor(anchor, "field", field.name)), + ); item.variants.forEach((variant) => anchors.push(memberAnchor(anchor, "variant", variant.name)), ); - item.methods.forEach((method) => anchors.push(...anchorsForFunc(method, item.name))); + item.methods.forEach((method) => + anchors.push(...anchorsForFunc(method, item.name)), + ); }); return anchors; } -function signature(func: GdkFunc, language: Language, owner?: string): string { - const params = func.params - .map((param) => { - const type = language.type(param.type); - const suffix = param.default ? ` = ${language.default(param.default)}` : ""; - switch (language.id) { - case "rust": - return `${param.name}: ${type}${suffix}`; - case "python": - return `${language.field(param.name)}: ${type}${suffix}`; - default: - return `${language.field(param.name)}: ${type}${suffix}`; - } - }) - .join(", "); - - const name = language.func(func.name); - const returns = func.returns ? language.type(func.returns) : null; - const prefix = owner ? `${owner}.` : ""; - - if (language.id === "rust") { - const asyncKeyword = func.isAsync ? "async " : ""; - const result = func.throws - ? `Result<${returns ?? "()"}, ${func.throws}>` - : returns; - return `${asyncKeyword}fn ${prefix}${name}(${params})${result ? ` -> ${result}` : ""}`; - } - - if (language.id === "python") { - const asyncKeyword = func.isAsync ? "async " : ""; - return `${asyncKeyword}def ${prefix}${name}(${params})${returns ? ` -> ${returns}` : ""}`; - } - - const suspend = func.isAsync ? "suspend " : ""; - const throwsAnnotation = func.throws - ? `@Throws(${language.errorType(func.throws)}::class)\n` - : ""; - return `${throwsAnnotation}${suspend}fun ${prefix}${name}(${params})${returns ? `: ${returns}` : ""}`; -} - function HashLink({ anchor, label }: { anchor: string; label: string }) { const search = useContext(SelectionSearchContext); const title = `Direct link to ${label}`; @@ -199,7 +141,10 @@ function Anchored({ }) { const anchorTargetClassName = useAnchorTargetClassName(anchor); return ( - + {children} @@ -248,7 +193,13 @@ function ParamTable({ {language.type(row.type)} {hasDefaults && ( - {row.default ? {language.default(row.default)} : "—"} + + {row.default ? ( + {language.default(row.default)} + ) : ( + "—" + )} + )} {row.docs || "—"} @@ -272,11 +223,18 @@ function FuncEntry({ const name = language.func(func.name); return (
- + {name} {func.docs &&

{func.docs}

} - {signature(func, language, owner)} + + {signature(func, language, owner)} + variant.fields.length > 0); const anchor = itemAnchor(item); - const name = item.kind === "error" ? language.errorType(item.name) : item.name; + const name = + item.kind === "error" ? language.errorType(item.name) : item.name; return (
- + {name} {KIND_LABELS[item.kind]} @@ -323,19 +286,16 @@ function ItemEntry({ item, language }: { item: GdkItem; language: Language }) { {item.variants.map((variant) => { - const variantName = - item.kind === "error" && language.id === "kotlin" - ? `${language.errorType(item.name)}.${variant.name}` - : language.variant(variant.name, dataCarrying); + const name = variantName(item, variant, language); return ( - {variantName} + {name} {variant.fields.length === 0 @@ -343,7 +303,8 @@ function ItemEntry({ item, language }: { item: GdkItem; language: Language }) { : variant.fields.map((field) => (
- {language.field(field.name)}: {language.type(field.type)} + {language.field(field.name)}:{" "} + {language.type(field.type)}
))} @@ -356,7 +317,12 @@ function ItemEntry({ item, language }: { item: GdkItem; language: Language }) { )} {item.methods.map((method) => ( - + ))}
); @@ -390,11 +356,14 @@ export default function GdkApiReference() { const language = LANGUAGES.find((entry) => entry.id === languageId)!; const doc = useMemo( - () => VERSIONS.find((entry) => entry.docVersion === docVersion) ?? VERSIONS[0], + () => + VERSIONS.find((entry) => entry.docVersion === docVersion) ?? VERSIONS[0], [docVersion], ); - anchorsForDoc(VERSIONS[0]).forEach((anchor) => brokenLinks.collectAnchor(anchor)); + anchorsForDoc(VERSIONS[0]).forEach((anchor) => + brokenLinks.collectAnchor(anchor), + ); useEffect(() => { const anchor = location.hash.slice(1); @@ -403,14 +372,25 @@ export default function GdkApiReference() { }, [docVersion, languageId, location.hash]); const grouped = useMemo(() => { - const order: GdkItem["kind"][] = ["object", "callback", "record", "enum", "error"]; + const order: GdkItem["kind"][] = [ + "object", + "callback", + "record", + "enum", + "error", + ]; return order - .map((kind) => ({ kind, items: doc.items.filter((item) => item.kind === kind) })) + .map((kind) => ({ + kind, + items: doc.items.filter((item) => item.kind === kind), + })) .filter((group) => group.items.length > 0); }, [doc]); return ( - +
@@ -420,7 +400,9 @@ export default function GdkApiReference() { type="button" role="tab" aria-selected={entry.id === languageId} - className={entry.id === languageId ? styles.tabActive : styles.tab} + className={ + entry.id === languageId ? styles.tabActive : styles.tab + } onClick={() => select({ languageId: entry.id })} > {entry.label} @@ -445,7 +427,8 @@ export default function GdkApiReference() {

- Generated from {doc.source} at goose-sdk {doc.version}. + Generated from {doc.source} at{" "} + goose-sdk {doc.version}.

diff --git a/documentation/src/components/GdkNavigation/index.tsx b/documentation/src/components/GdkNavigation/index.tsx new file mode 100644 index 000000000..69757fbba --- /dev/null +++ b/documentation/src/components/GdkNavigation/index.tsx @@ -0,0 +1,33 @@ +import { createContext, useContext } from "react"; +import { useLocation } from "@docusaurus/router"; +import useBaseUrl from "@docusaurus/useBaseUrl"; +import type { Props as NavbarItemConfig } from "@theme/NavbarItem"; + +export const GdkBlogContext = createContext(false); + +export function useGdkNavigation(): boolean { + const { pathname } = useLocation(); + const gdkPath = useBaseUrl("/docs/gdk"); + const blogPath = useBaseUrl("/blog/tags/gdk"); + const isGdkPost = useContext(GdkBlogContext); + + return ( + isGdkPost || + [gdkPath, blogPath].some( + (path) => pathname === path || pathname.startsWith(`${path}/`), + ) + ); +} + +export const gdkNavbarItems = [ + { + to: "/blog/tags/gdk", + label: "Blog", + activeBasePath: "blog", + }, + { + href: "https://github.com/aaif-goose/goose", + label: "GitHub", + }, + { to: "/", label: "Back to goose", exact: true }, +] satisfies NavbarItemConfig[]; diff --git a/documentation/src/css/custom.css b/documentation/src/css/custom.css index f8dd0ac73..983115f8f 100644 --- a/documentation/src/css/custom.css +++ b/documentation/src/css/custom.css @@ -498,3 +498,21 @@ main { [data-theme="dark"] .scrollbar-visible::-webkit-scrollbar-thumb:hover { background-color: var(--dark-grey-60); } + +html:has(.gdk-navigation) { + --gdk-accent: #6d28d9; + --ifm-link-color: var(--gdk-accent); + --ifm-breadcrumb-color-active: var(--gdk-accent); + --ifm-menu-color-active: var(--gdk-accent); + --ifm-menu-color-background-active: rgba(109, 40, 217, 0.08); + --ifm-navbar-link-hover-color: var(--gdk-accent); +} + +html[data-theme="dark"]:has(.gdk-navigation) { + --gdk-accent: #c4b5fd; + --ifm-menu-color-background-active: rgba(196, 181, 253, 0.1); +} + +html:has(.gdk-navigation) .table-of-contents { + --ifm-color-primary: var(--gdk-accent); +} diff --git a/documentation/src/css/gdk-demos.module.css b/documentation/src/css/gdk-demos.module.css new file mode 100644 index 000000000..84ae0ed80 --- /dev/null +++ b/documentation/src/css/gdk-demos.module.css @@ -0,0 +1,70 @@ +.grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1rem; + margin: 2rem 0; +} + +.card { + display: flex; + flex-direction: column; + height: 100%; + padding: 1.5rem; + border: 1px solid var(--ifm-color-emphasis-300); + border-radius: 8px; + color: var(--ifm-font-color-base); +} + +.card:focus-within { + border-color: var(--ifm-color-primary); +} + +.card a:focus-visible { + outline: 2px solid var(--ifm-color-primary); + outline-offset: 3px; +} + +.focus { + margin: 0 0 0.75rem; + color: var(--ifm-color-emphasis-700); + font-size: 0.8rem; +} + +.card h2 { + margin: 0 0 0.75rem; + font-size: 1.5rem; +} + +.card > p:not(.focus) { + margin: 0 0 1.5rem; + line-height: 1.6; +} + +.footer { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + margin-top: auto; + font-size: 0.8rem; +} + +.footer > span { + color: var(--ifm-color-emphasis-700); +} + +.footer p { + margin: 0; +} + +.footer a { + color: var(--ifm-link-color); + font-weight: 500; +} + +@media (max-width: 700px) { + .grid { + grid-template-columns: 1fr; + } +} diff --git a/documentation/src/pages/index.tsx b/documentation/src/pages/index.tsx index e313f7b3a..73dc9f98c 100644 --- a/documentation/src/pages/index.tsx +++ b/documentation/src/pages/index.tsx @@ -222,7 +222,7 @@ function StandardsSection() { an ACP server — connect from Zed, JetBrains, or VS Code — and can use ACP agents like Claude Code and Codex as providers.

- goose as ACP server → + Set up goose in Zed →

Agentic AI Foundation

diff --git a/documentation/src/theme/BlogPostPage/index.tsx b/documentation/src/theme/BlogPostPage/index.tsx new file mode 100644 index 000000000..77f086c80 --- /dev/null +++ b/documentation/src/theme/BlogPostPage/index.tsx @@ -0,0 +1,21 @@ +import React, { type ReactNode } from "react"; +import useBaseUrl from "@docusaurus/useBaseUrl"; +import OriginalBlogPostPage from "@theme-original/BlogPostPage"; +import type { Props } from "@theme/BlogPostPage"; +import { GdkBlogContext } from "@site/src/components/GdkNavigation"; + +export default function BlogPostPage(props: Props): ReactNode { + const gdkTag = useBaseUrl("/blog/tags/gdk"); + const isGdk = props.content.metadata.tags.some( + (tag) => tag.permalink === gdkTag, + ); + + return ( + + + + ); +} diff --git a/documentation/src/theme/BlogTagsPostsPage/index.tsx b/documentation/src/theme/BlogTagsPostsPage/index.tsx new file mode 100644 index 000000000..35eb4a096 --- /dev/null +++ b/documentation/src/theme/BlogTagsPostsPage/index.tsx @@ -0,0 +1,15 @@ +import React, { type ReactNode } from "react"; +import OriginalBlogTagsPostsPage from "@theme-original/BlogTagsPostsPage"; +import type { Props } from "@theme/BlogTagsPostsPage"; +import { useGdkNavigation } from "@site/src/components/GdkNavigation"; + +export default function BlogTagsPostsPage(props: Props): ReactNode { + const isGdk = useGdkNavigation(); + + return ( + + ); +} diff --git a/documentation/src/theme/DocItem/Layout/index.tsx b/documentation/src/theme/DocItem/Layout/index.tsx index 39f8fc64d..488118ee8 100644 --- a/documentation/src/theme/DocItem/Layout/index.tsx +++ b/documentation/src/theme/DocItem/Layout/index.tsx @@ -452,15 +452,15 @@ function PageActionsMenu(): ReactNode { ); } -// Hook to determine if we should show the copy button function useShouldShowCopyButton(): boolean { const {metadata} = useDoc(); - // Show copy button only on actual content pages (not category/index pages) - // A content page should have a source file (.md file) + if (metadata.id.startsWith('gdk/')) { + return false; + } + const hasSource = metadata?.source && metadata.source.includes('.md'); - // Don't show on category pages (they typically have /category/ in the permalink) const isNotCategoryPage = !metadata?.permalink?.includes('/category/'); return hasSource && isNotCategoryPage; diff --git a/documentation/src/theme/DocItem/Metadata/index.tsx b/documentation/src/theme/DocItem/Metadata/index.tsx new file mode 100644 index 000000000..ebafe7d69 --- /dev/null +++ b/documentation/src/theme/DocItem/Metadata/index.tsx @@ -0,0 +1,20 @@ +import React, { type ReactNode } from "react"; +import { PageMetadata } from "@docusaurus/theme-common"; +import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import OriginalDocItemMetadata from "@theme-original/DocItem/Metadata"; + +export default function DocItemMetadata(): ReactNode { + const { metadata, frontMatter, assets } = useDoc(); + if (!metadata.id.startsWith("gdk/")) { + return ; + } + + return ( + + ); +} diff --git a/documentation/src/theme/Navbar/Content/index.tsx b/documentation/src/theme/Navbar/Content/index.tsx new file mode 100644 index 000000000..7619d51e3 --- /dev/null +++ b/documentation/src/theme/Navbar/Content/index.tsx @@ -0,0 +1,33 @@ +import React, { type ReactNode } from "react"; +import OriginalNavbarContent from "@theme-original/Navbar/Content"; +import NavbarItem from "@theme/NavbarItem"; +import NavbarLogo from "@theme/Navbar/Logo"; +import NavbarColorModeToggle from "@theme/Navbar/ColorModeToggle"; +import NavbarMobileSidebarToggle from "@theme/Navbar/MobileSidebar/Toggle"; +import { + gdkNavbarItems, + useGdkNavigation, +} from "@site/src/components/GdkNavigation"; +import styles from "./styles.module.css"; + +export default function NavbarContent(): ReactNode { + const isGdk = useGdkNavigation(); + if (!isGdk) { + return ; + } + + return ( +
+
+ + +
+
+ {gdkNavbarItems.map((item) => ( + + ))} + +
+
+ ); +} diff --git a/documentation/src/theme/Navbar/Content/styles.module.css b/documentation/src/theme/Navbar/Content/styles.module.css new file mode 100644 index 000000000..b6198516e --- /dev/null +++ b/documentation/src/theme/Navbar/Content/styles.module.css @@ -0,0 +1,5 @@ +@media (max-width: 996px) { + .colorModeToggle { + display: none; + } +} diff --git a/documentation/src/theme/Navbar/Logo/index.tsx b/documentation/src/theme/Navbar/Logo/index.tsx new file mode 100644 index 000000000..5b4c163bb --- /dev/null +++ b/documentation/src/theme/Navbar/Logo/index.tsx @@ -0,0 +1,23 @@ +import React, { type ReactNode } from "react"; +import Link from "@docusaurus/Link"; +import GooseLogo from "@site/static/img/goose.svg"; +import OriginalNavbarLogo from "@theme-original/Navbar/Logo"; +import { useGdkNavigation } from "@site/src/components/GdkNavigation"; +import styles from "./styles.module.css"; + +export default function NavbarLogo(): ReactNode { + const isGdk = useGdkNavigation(); + return isGdk ? ( + +