# How the Gravity‑Index Tool Optimizes File Discovery in Freebuff

> Discover how the gravity-index tool optimizes file discovery in Freebuff by delegating search queries, attaching metadata, and providing deterministic link resolution. Streamline service discovery now.

- Repository: [Codebuff/freebuff](https://github.com/CodebuffAI/freebuff)
- Tags: deep-dive
- Published: 2026-08-20

---

**The gravity‑index tool streamlines service discovery by delegating search queries to a dedicated Gravity Index API, attaching rich metadata for accurate attribution, and providing deterministic link resolution—eliminating the need for agents to hard‑code or repeatedly look up third‑party services.**

In the Freebuff agent runtime, `gravity_index` serves as the single source of truth for locating developer services such as databases, authentication providers, and hosting platforms. By centralizing discovery logic in a reusable handler and integrating with a web‑based service catalog, the tool reduces agent complexity while ensuring every recommendation is trackable and up‑to‑date.

## Architecture: Handler, API Call, and Metadata Pipeline

The gravity‑index tool follows a clear three‑stage pipeline: input normalization, enriched API invocation, and result wrapping.

### Handler Entry Point: `handleGravityIndex`

When an agent calls `gravity_index`, execution enters `handleGravityIndex` in [[`packages/agent-runtime/src/tools/handlers/tool/gravity-index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/handlers/tool/gravity-index.ts)](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/handlers/tool/gravity-index.ts#L52-L86). This function orchestrates the entire flow:

1. Validates the tool input (action type, query string).
2. Builds a `metadata` object containing request context.
3. Invokes `callGravityIndexAPI` from the shared web API package.
4. Wraps the response or error in a standardized tool result.

The handler keeps agent code free of HTTP logic and retry policies, which are managed centrally.

### Surface Attribution via `gravitySurface`

Accurate analytics requires distinguishing where requests originate. The helper `gravitySurface` (lines 30‑44) maps the execution context to one of three labels:

- `codebuff_cli` – Requests from the command‑line interface.
- `freebuff_chat` – Requests from the chat‑based Freebuff surface.
- `freebuff_web` – Requests from the web dashboard.

This label is embedded in the metadata payload (lines 111‑123), preventing attribution collapse under a single service account and enabling per‑product conversion tracking.

### Per‑User Deduplication for Shared Surfaces

For shared surfaces (`freebuff_chat` and `freebuff_web`), the handler generates an `external_user_id` from the stable `fingerprintId` (lines 32‑35). This allows the Gravity backend to:

- De‑duplicate repeat searches by the same user.
- Maintain accurate usage metrics without exposing internal user identifiers.

## Invoking Gravity‑Index from Agents

Agents declare `gravity_index` in their `toolNames` array to opt into service discovery. Both `base2` and `base-chat` agents include it:

- [[`agents/base2/base2.ts`](https://github.com/CodebuffAI/freebuff/blob/main/agents/base2/base2.ts) line 156](https://github.com/CodebuffAI/freebuff/blob/main/agents/base2/base2.ts#L156)
- [[`agents/base-chat.ts`](https://github.com/CodebuffAI/freebuff/blob/main/agents/base-chat.ts) line 28](https://github.com/CodebuffAI/freebuff/blob/main/agents/base-chat.ts#L28)

When an agent determines the user needs a service recommendation, it issues a `search` action:

```typescript
await agent.callTool('gravity_index', {
  action: 'search',
  query: 'managed Redis with persistence for Python workloads',
});

```

The handler forwards this query to the Gravity Index API, which returns ranked services with metadata including `search_id`, `service_slug`, and tracked click URLs.

## Link Resolution: From Reference to Renderable URL

Agents never hard‑code service URLs. Instead, they embed a **gravity‑index reference**—a lightweight token containing `search_id` and `service_slug`. The UI layer resolves this to the actual click‑tracking URL via `resolveGravityIndexLink` in [[`packages/agent-runtime/src/tools/gravity-index-cta.ts`](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/gravity-index-cta.ts)](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/gravity-index-cta.ts#L48-L92).

### Resolution Flow

The function performs three steps:

1. **Scan chat history** for the matching `gravity_index` tool message.
2. **Match** the reference's `search_id` and `service_slug` against stored results.
3. **Return** the exact `click_url` provided by the Gravity backend, or `null` if absent.

This guarantees that every rendered link carries correct attribution and that outdated URLs cannot be accidentally served.

```typescript
import { resolveGravityIndexLink } from '@codebuff/agent-runtime';

const link = resolveGravityIndexLink({
  reference: {
    source: 'gravity_index',
    search_id: 'srch_9f8e7d6c',
    service_slug: 'upstash-redis'
  },
  messages: conversationHistory
});

// link === 'https://gravity.example.com/click/abc123?track=xyz789'

```

If resolution fails—due to truncated history or missing metadata—the function returns `null`, allowing the UI to gracefully degrade rather than display broken links.

## Error Handling and Resilient Execution

The gravity‑index handler implements defensive error management (lines 46‑62). When the Gravity API reports a failure, the handler:

- Logs the error via the runtime's structured logging.
- Returns a `jsonToolResult` containing an error code and message.
- Allows the agent to continue execution and potentially retry or suggest alternatives.

This prevents transient service outages from halting agent workflows.

## Practical Integration Example

A complete agent interaction demonstrating gravity‑index optimization:

```typescript
// Agent searches for a service
const searchResult = await agent.callTool('gravity_index', {
  action: 'search',
  query: 'serverless Postgres with connection pooling',
});

// Agent selects 'neon' from results and renders a CTA
await agent.callTool('render_ui', {
  source: 'gravity_index',
  search_id: searchResult.search_id,
  service_slug: 'neon'
});

```

The `render_ui` tool internally calls `resolveGravityIndexLink`, producing a UI element with a properly attributed, tracked URL—no agent code touches raw URLs.

## Key Source Files

- **[[`packages/agent-runtime/src/tools/handlers/tool/gravity-index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/handlers/tool/gravity-index.ts)](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/handlers/tool/gravity-index.ts)** – Core handler implementing request building, attribution, and response normalization.
- **[[`packages/agent-runtime/src/tools/gravity-index-cta.ts`](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/gravity-index-cta.ts)](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/tools/gravity-index-cta.ts)** – Link resolution logic for safe UI rendering.
- **[[`common/src/tools/params/tool/render-ui.ts`](https://github.com/CodebuffAI/freebuff/blob/main/common/src/tools/params/tool/render-ui.ts)](https://github.com/CodebuffAI/freebuff/blob/main/common/src/tools/params/tool/render-ui.ts)** – Schema definition for gravity‑index references.
- **[[`agents/base2/base2.ts`](https://github.com/CodebuffAI/freebuff/blob/main/agents/base2/base2.ts)](https://github.com/CodebuffAI/freebuff/blob/main/agents/base2/base2.ts)** and **[[`agents/base-chat.ts`](https://github.com/CodebuffAI/freebuff/blob/main/agents/base-chat.ts)](https://github.com/CodebuffAI/freebuff/blob/main/agents/base-chat.ts)** – Agent configurations declaring `gravity_index` availability.
- **[[`packages/agent-runtime/src/compact-history.ts`](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/compact-history.ts) line 333](https://github.com/CodebuffAI/freebuff/blob/main/packages/agent-runtime/src/compact-history.ts#L333)** – Serialization of tool results for history retention and later resolution.

## Summary

The gravity‑index tool optimizes file discovery in Freebuff by centralizing service queries through a dedicated API pipeline. Key optimizations include:

- **Delegated search** – Agents issue high‑level queries without implementing discovery logic.
- **Rich attribution metadata** – Surface labels and user identifiers enable accurate analytics.
- **Deterministic link resolution** – References guarantee correct, trackable URLs without hard‑coding.
- **Resilient error handling** – API failures are captured and returned structurally, preserving agent execution.
- **Zero URL maintenance** – Agents work with opaque references; the runtime resolves actual links at render time.

## Frequently Asked Questions

### How does gravity‑index differ from a simple web search tool?

Unlike generic search, gravity‑index targets curated developer services with structured metadata and built‑in conversion tracking. The tool returns `service_slug` identifiers and tracked click URLs rather than raw links, enabling the runtime to attribute referrals correctly and update destination URLs without agent changes.

### What happens if the Gravity Index API is unavailable?

The `handleGravityIndex` handler catches API errors (lines 46‑62) and returns a structured error object to the agent. The agent can detect this condition via the tool result's `error` field and either retry, suggest an alternative discovery method, or proceed with reduced functionality—no unhandled exceptions occur.

### Why does gravity‑index use references instead of returning direct URLs?

References decouple the agent from URL lifecycle changes. If a service updates its landing page or tracking parameters, the Gravity backend updates the stored `click_url`; existing agent conversations continue to resolve correctly via `resolveGravityIndexLink`. This also prevents agents from embedding outdated or manipulated URLs.

### Which Freebuff surfaces support gravity‑index attribution?

All three primary surfaces are supported: `codebuff_cli` for command‑line usage, `freebuff_chat` for conversational interactions, and `freebuff_web` for dashboard‑based workflows. The `gravitySurface` function (lines 30‑44) determines the correct label automatically based on execution context.