# AgenticDriver Go client

Connect a Go 1.22+ application to its local or remote AgenticDriver host. This module has no external Go dependencies. Provider credentials and native agent processes stay on the host. The client uses an application-scoped driver bearer token and explicit provider/model selection.

Optional [detached jobs](/docs/jobs) use `SubmitJob`, `ReadJob`, `CancelJob`
and `JobEvents` with typed requests/results. Cancelling the HTTP context does not
cancel accepted background work; call `CancelJob` explicitly. Reconnect using
`JobEventPage.NextCursor`; pages never automatically execute tool actions.

Install the current published preview:

```sh
go get github.com/agenticdriver/agenticdriver/clients/go@v0.2.0-rc.2
```

Your application's `go.mod` and `go.sum` record the dependency. No sibling checkout or `replace` directive is needed. The repository is public. Installation uses the public Go module proxy and checksum database without GitHub credentials or a `GOPRIVATE` setting. The installation check below uses a fresh module cache and does not change your global Go configuration.

```go
package main

import (
    "context"
    "errors"
    "fmt"
    "os"
    "os/signal"

    "github.com/agenticdriver/agenticdriver/clients/go"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    client, err := agenticdriver.New(os.Getenv("AGENTICDRIVER_URL"), os.Getenv("AGENTICDRIVER_TOKEN"))
    if err != nil { panic(err) }
    providers, err := client.RefreshProviders(ctx)
    if err != nil { panic(err) }
    fmt.Printf("Authorized provider instances: %d\n", len(providers))
    request := agenticdriver.Request{
        Provider: os.Getenv("AGENTICDRIVER_PROVIDER"),
        Model: os.Getenv("AGENTICDRIVER_MODEL"),
        Input: "Summarize the selected evidence.",
    }
    err = client.Stream(ctx, request, func(event agenticdriver.Event) error {
        switch event.Type {
        case "text.delta": fmt.Print(event.Text)
        case "run.progress": fmt.Printf("Progress: %s\n", event.Phase)
        case "run.completed": fmt.Printf("\nRun: %s\n", event.Result.RunID)
        }
        return nil // Return an application error to stop consuming and cancel the run.
    })
    if err != nil {
        var driverError *agenticdriver.Error
        if errors.As(err, &driverError) {
            fmt.Printf("%s: %s\n", driverError.Code, driverError.Message)
            // Outcome == "uncertain" requires reconciliation before replacing work.
            // Retryable is advisory; the client never replays a run automatically.
        } else if errors.Is(err, context.Canceled) {
            fmt.Println("Cancelled")
        } else { panic(err) }
    }
}
```

`Run(ctx, request)` returns a typed `Result`; `Stream` exposes typed model, step, progress, tool, usage, error and result fields plus each validated event's `Raw` JSON. Check the event type before reading its associated fields. Pointer token counters distinguish a reported zero from an unknown measurement. Callback errors return unchanged. The callback runs synchronously, so applications control buffering/backpressure and must return promptly when they want cancellation to finish; the SDK cannot interrupt arbitrary application code.

A stream owns its response body and derived cancellation context. Terminal success, malformed frames, transport failures, context cancellation and callback termination close that body. A nil callback is rejected before HTTP with `INVALID_CALLBACK`. SSE supports UTF-8, BOM, LF/CR/CRLF, multiline data and any network-read boundaries, including bytes returned together with EOF. EOF without a terminal event remains an error; it never turns an incomplete answer into success. There is no reconnection or implicit replay.

`SearchContext`, `IndexContext`, `IngestContext` and `DeleteContext` expose the shared retrieval/ingestion contract. Their inputs include corpus and exact source/revision; manifests preserve extraction coverage and source provenance. Canonical data, access control and citation validity remain application-owned.

HTTPS is required away from loopback, and redirects never forward credentials. For a custom CA, mTLS or proxy policy, configure a verified `http.Transport` and pass it to `NewWithTransport`. The caller owns that transport and any `CloseIdleConnections` lifecycle. Do not disable TLS verification. No HTTP-client execution timeout is installed. Caller context deadlines are explicit application choices; runs can separately opt in to host-enforced `IdleTimeoutMs` based on real model/tool/context progress. Discovery has a bounded ten-second I/O timeout. A background context gives an execution request no default deadline.

`npm run test:clients` builds and installs the actual language packages, compiles
examples and runs pure contracts. It does not simulate connections or model answers.
Use [real connection checks](/docs/real-connections) for provider execution.

## Interactive approvals

Set `Request.Approvals` to `&ApprovalPolicy{Mode: "interactive", IdlePolicy: "pause"}` and consume `Stream`. `Event.Approval` contains the reviewed call; submit `DecideApproval(ctx, ApprovalDecision{ApprovalID: approval.ApprovalID, RunID: approval.RunID, Call: approval.Call, Decision: "approve"})` using the same authenticated subject with a separate approval grant. Decisions may also be `deny` or `cancel`; inspect `Event.Resolution` and the terminal run outcome.

The host must enable this feature and grant `approveTools`. `run` rejects
interactive mode because it cannot deliver review requests. There is no default
approval expiry; choose `expiresAfterMs` / the typed equivalent when needed.
Decisions are single-use and are never retried automatically. A receipt does not
confirm a tool effect. See the [approval contract](/docs/approvals).

## Functions in your application

Set `Request.ApplicationTools` to your `[]ApplicationToolDefinition` and select
the same names in `Tools`. In `Stream`, dispatch only `tool.execution.requested`:
`event.Execution` contains the call arguments and `Identity()` for replies.
Use `ReportToolProgress(ctx, identity)` after real work and
`CompleteTool(ctx, ToolExecutionResult{ToolExecutionIdentity: identity, Output: jsonBytes})`
to submit the JSON result once. Output is `json.RawMessage`; encode a JSON null
as `json.RawMessage("null")`. On callback failure set only
`Error: "APPLICATION_TOOL_FAILED"`, without private exception text.

Host opt-in and named token grants are required; review defaults to required.
Pass the stream's context to your application function so cancellation propagates
through its I/O. Cancelled runs invalidate pending tickets but cannot undo effects.
No default inactivity deadline or automatic retries apply. See the
[full contract](/docs/application-tools).

## Conversation sessions

Create/read/delete methods and typed session models support explicit conversation
continuation. Pass only the returned session ID and revision on each run, then
use the next revision from the successful result. Provider/account/model changes
require an explicitly created conversation with exported visible history.
Host opt-in, account binding and per-operation token grants are required. Idle
retention pauses during active work; no default execution deadline is introduced.
See the [session contract and binding examples](/docs/sessions).

## Provider settings component

The [provider and connection panel](/docs/provider-panel) supplies provider/model settings, remote management and local/remote setup through the existing SDK client. TypeScript, Python, Go and Rust packages share the same embeddable browser component and provide native backend bindings. These additions are available on `sdk-roadmap` and are not in the published 0.1.0 packages.
