> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lyzr.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

> Programmatic access to GitAgent via query(), tool(), and buildTool().

## Pick your starting point

Two paths — both use the same `query()` function.

### Path 1 — With a GitAgent repo URL

```ts theme={null}
import { query } from "@open-gitagent/gitagent";

for await (const msg of query({
  repo: "https://github.com/your-gitagent",
  prompt: "Summarise the open pull requests",
})) {
  if (msg.type === "assistant") console.log(msg.content);
}
```

GitAgent clones the repo, reads `agent.yaml` + `SOUL.md` + skills. Zero config — the repo is your agent.

### Path 2 — Without a repo

```ts theme={null}
import { query } from "@open-gitagent/gitagent";

for await (const msg of query({
  prompt: "Refactor the auth module in src/auth.ts",
  model: "anthropic:claude-sonnet-4-6",
  dir: "./my-project",
})) {
  if (msg.type === "assistant") console.log(msg.content);
}
```

Pure SDK — point at an existing directory. No agent repo needed. Ideal for embedding in an app you already have.

## API Reference

### query()

```ts theme={null}
import { query } from "@open-gitagent/gitagent";

for await (const msg of query({
  prompt: "Refactor the auth module",
  dir: "/path/to/agent",
  model: "anthropic:claude-sonnet-4-6",
})) {
  switch (msg.type) {
    case "delta":       // streaming text chunk
      process.stdout.write(msg.content); break;
    case "assistant":   // complete response
      console.log(`\nTokens: ${msg.usage?.totalTokens}`); break;
    case "tool_use":    // tool invocation
      console.log(`Tool: ${msg.toolName}(${JSON.stringify(msg.args)})`); break;
    case "tool_result": // tool output
      console.log(`Result: ${msg.content}`); break;
    case "system":      // lifecycle events & errors
      console.log(`[${msg.subtype}] ${msg.content}`); break;
  }
}
```

### tool()

```ts theme={null}
import { query, tool } from "@open-gitagent/gitagent";

const search = tool(
  "search_docs",
  "Search the documentation",
  {
    properties: {
      query: { type: "string", description: "Search query" },
      limit: { type: "number", description: "Max results" },
    },
    required: ["query"],
  },
  async (args) => {
    const results = await mySearchEngine(args.query, args.limit ?? 10);
    return { text: JSON.stringify(results), details: { count: results.length } };
  },
);

for await (const msg of query({ prompt: "Find auth docs", tools: [search] })) {
  // agent can now call search_docs
}
```

### buildTool()

```ts theme={null}
import { buildTool } from "@open-gitagent/gitagent";

const myTool = buildTool({
  name: "search_docs",
  description: "Search documentation",
  parameters: {
    properties: { query: { type: "string" } },
    required: ["query"],
  },
  execute: async (args) => {
    return "Results: ...";
  },
  metadata: {
    isConcurrencySafe: true,   // safe to run in parallel
    isReadOnly: true,           // no side effects
    maxResultSizeChars: 20000,  // truncate large results
  },
});
```

### hooks

```ts theme={null}
const result = query({
  prompt: "Deploy to production",
  dir: "/path/to/agent",
  hooks: {
    onSessionStart: async (ctx) => ({ action: "allow" }),
    preToolUse: async (ctx) => {
      if (ctx.toolName === "cli" && ctx.args.command.includes("deploy")) {
        return { action: "block", reason: "Manual approval required" };
      }
      return { action: "allow" };
    },
    postToolFailure: async (ctx) => {
      console.error(`Tool ${ctx.toolName} failed: ${ctx.error}`);
    },
    preQuery: async (ctx) => {
      console.log(`Sending prompt to LLM: ${ctx.sessionId}`);
      return { action: "allow" };
    },
    postResponse: async (ctx) => {
      console.log(`Session ${ctx.sessionId} responded`);
    },
    fileChanged: async (ctx) => {
      console.log(`File changed: ${ctx.path}`);
    },
    onError: async (ctx) => {
      console.error(`Error in ${ctx.sessionId}: ${ctx.error}`);
    },
  },
});
```

<Tip>
  These are the same lifecycle hooks used by the [Hooks](/open-source/gitagent/capabilities/hooks) capability — the SDK just lets you register them in code instead of `hooks/hooks.yaml`.
</Tip>

## QueryOptions

Parameters accepted by `query()`

| Name                  | Type                      | Required | Description                                                                                               |
| --------------------- | ------------------------- | -------- | --------------------------------------------------------------------------------------------------------- |
| `prompt`              | string \| AsyncIterable   | Yes      | User prompt or multi-turn stream                                                                          |
| `dir`                 | string                    |          | Agent directory (default: cwd)                                                                            |
| `model`               | string                    |          | "provider:model-id"                                                                                       |
| `env`                 | string                    |          | Environment config (`config/<env>.yaml`)                                                                  |
| `systemPrompt`        | string                    |          | Override discovered system prompt                                                                         |
| `systemPromptSuffix`  | string                    |          | Append to discovered system prompt                                                                        |
| `tools`               | GCToolDefinition\[]       |          | Additional tools                                                                                          |
| `replaceBuiltinTools` | boolean                   |          | Skip cli/read/write/memory                                                                                |
| `allowedTools`        | string\[]                 |          | Tool name allowlist                                                                                       |
| `disallowedTools`     | string\[]                 |          | Tool name denylist                                                                                        |
| `maxTurns`            | number                    |          | Max agent turns                                                                                           |
| `abortController`     | AbortController           |          | Cancellation signal                                                                                       |
| `constraints`         | object                    |          | temperature, maxTokens, topP, topK                                                                        |
| `hooks`               | object                    |          | onSessionStart, preToolUse, postToolFailure, preQuery, postResponse, fileChanged, onError lifecycle hooks |
| `repo`                | object                    |          | Work on a remote git repo — clone, run agent, auto-commit changes to session branch                       |
| `sandbox`             | SandboxOptions \| boolean |          | Run agent inside an E2B cloud VM (true uses defaults)                                                     |
| `sessionId`           | string                    |          | Tag or resume a specific session                                                                          |

## Message Types

Emitted by the `query()` async iterator

| Type          | Fields                                 | Description                   |
| ------------- | -------------------------------------- | ----------------------------- |
| `delta`       | deltaType, content                     | Streaming text/thinking chunk |
| `assistant`   | content, model, usage, stopReason      | Complete LLM response         |
| `tool_use`    | toolName, args, toolCallId             | Tool invocation               |
| `tool_result` | toolName, content, isError, toolCallId | Tool output                   |
| `system`      | subtype, content, metadata             | Lifecycle events              |
| `user`        | content                                | User message (multi-turn)     |

## Cost Tracking

```ts theme={null}
const result = query({ prompt: "...", dir: "..." });

for await (const msg of result) { /* handle messages */ }

const costs = result.costs();
console.log(`Cost: $${costs.totalCostUsd.toFixed(4)}`);
console.log(`Tokens: ${costs.totalInputTokens} in / ${costs.totalOutputTokens} out`);
```

<Note>
  See [Utilities](/open-source/gitagent/sdk/utilities) for the full shape of the `costs()` result and for context-compaction helpers.
</Note>

<CardGroup cols={2}>
  <Card title="SDK Quickstart" icon="rocket" href="/open-source/gitagent/sdk/quickstart">
    Install the SDK and run your first query()
  </Card>

  <Card title="Utilities" icon="wrench" href="/open-source/gitagent/sdk/utilities">
    Context compaction and cost tracking helpers
  </Card>

  <Card title="Telemetry" icon="chart-line" href="/open-source/gitagent/sdk/telemetry">
    OpenTelemetry spans, metrics, and Jaeger setup
  </Card>

  <Card title="Capabilities: Tools" icon="wrench" href="/open-source/gitagent/capabilities/tools">
    Built-in tools available to every agent
  </Card>
</CardGroup>
