How the Gravity‑Index Tool Optimizes File Discovery in Freebuff

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#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:

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

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.

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#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.

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:

// 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

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.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →