@augmentcode/auggie-sdk

中文文档
0.2.0发布于 2026/07/08TypeScriptES Module近 30 天下载 6240

TypeScript SDK for Auggie

原始使用文档
文档目录40 节
  1. Features
  2. 🎯 AI SDK Provider (Vercel AI SDK)
  3. 🤖 Agent Interaction (ACP)
  4. 🔍 Context Modes
  5. Installation
  6. Install Auggie CLI
  7. Install the SDK
  8. Usage
  9. AI SDK Provider (Vercel AI SDK)
  10. Agent Interaction (ACP)
  11. Authentication
  12. Using Custom Tools
  13. Excluding Tools
  14. Getting Only the Final Response
  15. Streaming Session Updates
  16. Running the Examples
  17. Custom Auggie Path and Workspace
  18. Advanced CLI Arguments
  19. Context Modes
  20. Direct Context
  21. FileSystem Context
  22. API Reference
  23. Auggie
  24. How It Works
  25. ACP Protocol
  26. MCP Integration
  27. Connection Flow
  28. Client Implementation
  29. Examples
  30. Complete Example with Tools and Streaming
  31. Error Handling
  32. Requirements
  33. All Features
  34. Agent Interaction (ACP) & FileSystem Context
  35. Direct Context Only
  36. Building the Package
  37. Launching Auggie as ACP Server
  38. Available CLI Options
  39. References
  40. License

Auggie SDK

A TypeScript SDK for building AI-powered developer tools with Auggie.

Features

🎯 AI SDK Provider (Vercel AI SDK)

Requires: API credentials only (no local Auggie needed)

  • Use Augment as a language model provider with Vercel's AI SDK
  • Compatible with generateText, streamText, and other AI SDK functions
  • Full support for tool calling (function calling) with automatic execution
  • Multi-turn conversations with context retention
  • Streaming responses for real-time output

🤖 Agent Interaction (ACP)

Requires: Local Auggie installation

  • Launch Auggie in ACP mode and communicate bidirectionally
  • Send prompts and receive streaming responses
  • Integrate custom tools using the AI SDK tool format
  • Handle session updates and permission requests

🔍 Context Modes

Two different ways to index and search code:

  1. Direct Context - API-based indexing with state persistence Requires: API credentials only (no local Auggie needed)

    • Explicitly add files to the index
    • Export/import state to avoid re-indexing
    • Perfect for embedded search in applications
  2. FileSystem Context - Local directory retrieval via MCP Requires: Local Auggie installation

    • Automatically index a workspace directory
    • Spawns auggie --mcp for local search
    • Ideal for IDE extensions and local tools

Installation

Install Auggie CLI

Install the Auggie CLI:

npm install -g @augmentcode/auggie

Install the SDK

npm install @augmentcode/auggie-sdk
# or
pnpm add @augmentcode/auggie-sdk

From tarball

npm install /path/to/augmentcode-auggie-sdk-0.1.0.tgz
# or
pnpm add /path/to/augmentcode-auggie-sdk-0.1.0.tgz

From local directory (for development)

npm install /path/to/auggie-sdk
# or
pnpm add /path/to/auggie-sdk

Usage

AI SDK Provider (Vercel AI SDK)

✅ No Local Auggie Required - API Only

Use Augment as a language model provider with Vercel's AI SDK:

import { AugmentLanguageModel, resolveAugmentCredentials } from "@augmentcode/auggie-sdk";
import { generateText } from "ai";

// Resolve credentials from environment or ~/.augment/session.json
const credentials = await resolveAugmentCredentials();

// Create the Augment language model
const model = new AugmentLanguageModel("claude-sonnet-4-5", credentials);

// Use with AI SDK functions
const { text } = await generateText({
  model,
  prompt: "Explain TypeScript in one sentence.",
});

console.log(text);

Streaming Responses

import { streamText } from "ai";

const { textStream } = await streamText({
  model,
  prompt: "Write a haiku about coding.",
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}

Tool Calling (Function Calling)

import { generateText, tool } from "ai";
import { z } from "zod";

const weatherTool = tool({
  description: "Get the current weather in a location",
  parameters: z.object({
    location: z.string(),
  }),
  execute: async ({ location }) => {
    // Your implementation
    return { temperature: 72, conditions: "sunny" };
  },
});

const { text } = await generateText({
  model,
  tools: {
    getWeather: weatherTool,
  },
  maxSteps: 5, // Enable multi-step agentic loop
  prompt: "What's the weather in San Francisco?",
});

Multi-turn Conversations

import { type CoreMessage } from "ai";

const messages: CoreMessage[] = [
  { role: "user", content: "What is TypeScript?" },
];

const response1 = await generateText({ model, messages });
messages.push({ role: "assistant", content: response1.text });

messages.push({ role: "user", content: "What are its benefits?" });
const response2 = await generateText({ model, messages });

See examples/ai-sdk-README.md for more detailed examples.

Agent Interaction (ACP)

⚠️ Requires Local Auggie Installation

For complex agent tasks with tools and codebase context:

import { Auggie } from "@augmentcode/auggie-sdk";

async function main() {
  // Create and initialize Auggie instance
  const client = await Auggie.create({
    model: "sonnet4.5",     // Optional: haiku4.5, opus4.1, sonnet4.5, sonnet4
    apiKey: "your-api-key", // Optional: API key for authentication
    apiUrl: "https://your-tenant.api.augmentcode.com", // Required when apiKey is provided
  });

  try {
    // Listen for session updates
    client.onSessionUpdate((update) => {
      console.log("Received update:", update);
    });

    // Send a prompt
    const response = await client.prompt("What files are in the current directory?");
    console.log("Response:", response);

    // Close the connection
    await client.close();
  } catch (error) {
    console.error("Error:", error);
    await client.close();
  }
}

main();

Authentication

There are three ways to authenticate with Auggie:

auggie login

This stores your OAuth session and is automatically used by the SDK.

2. Passing API Key Directly

const client = await Auggie.create({
  apiKey: "your-api-key",
  apiUrl: "https://your-tenant.api.augmentcode.com", // Your tenant-specific URL
  model: "sonnet4.5",
});

3. Using Environment Variables

export AUGMENT_API_TOKEN="your-api-key"
export AUGMENT_API_URL="https://your-tenant.api.augmentcode.com"  # Your tenant-specific URL

Then create the client without specifying credentials:

const client = await Auggie.create({
  model: "sonnet4.5",
});

Note: If you pass apiKey and apiUrl to the constructor, they will override any environment variables.

Using Custom Tools

You can provide custom tools to Auggie using the AI SDK tool format:

import { Auggie } from "@augmentcode/auggie-sdk";
import { tool } from "ai";
import z from "zod";

const weatherTool = tool({
  name: "get_weather",
  description: "Get the weather in a location",
  inputSchema: z.object({
    location: z.string().describe("The location to get the weather for"),
  }),
  execute: async ({ location }) => {
    // Your tool implementation
    return `The weather in ${location} is sunny.`;
  },
});

async function main() {
  // Create the instance with tools
  const client = await Auggie.create({
    model: "sonnet4.5",
    tools: { weather_tool: weatherTool },
  });

  try {
    const response = await client.prompt("What's the weather in San Francisco?");
    console.log(response);

    await client.close();
  } catch (error) {
    console.error("Error:", error);
    await client.close();
  }
}

main();

Excluding Tools

You can disable specific tools by providing a list of tool identifiers to exclude. This is useful when you want to restrict the agent's capabilities or prevent it from using certain integrations.

import { Auggie } from "@augmentcode/auggie-sdk";

async function main() {
  // Exclude integration tools
  const client = await Auggie.create({
    model: "sonnet4.5",
    excludedTools: ["web-search", "linear", "notion"],
  });

  try {
    const response = await client.prompt("What tools do you have available?");
    console.log(response);

    await client.close();
  } catch (error) {
    console.error("Error:", error);
    await client.close();
  }
}

main();

Available Tool Types

The SDK provides TypeScript types for all predefined tools:

import { Auggie, type PredefinedToolType, type ToolIdentifier } from "@augmentcode/auggie-sdk";

// PredefinedToolType includes:
// File operation tools: "remove-files", "save-file", "str-replace-editor", "view"
// Process management tools: "launch-process", "kill-process", "read-process", "write-process", "list-processes"
// Integration tools: "web-search"
// Task management tools: "add_tasks", "update_tasks", "reorganize_tasklist", "view_tasklist"

// You can also exclude custom tool names (strings)
const client = await Auggie.create({
  excludedTools: ["launch-process", "my-custom-tool"],
});

Common Use Cases

Disable process execution tools for security:

const client = await Auggie.create({
  excludedTools: ["launch-process", "kill-process", "read-process", "write-process", "list-processes"],
});

Disable integration tools:

const INTEGRATION_TOOLS = ["web-search"];

const client = await Auggie.create({
  excludedTools: INTEGRATION_TOOLS,
});

Disable file modification tools:

const client = await Auggie.create({
  excludedTools: ["save-file", "str-replace-editor", "remove-files"],
});

Getting Only the Final Response

When the agent uses tools (like file operations, web searches, etc.), you can choose to get only the final answer after all tool executions complete:

// Get all agent responses (default behavior)
const fullResponse = await client.prompt("List all TypeScript files in this project");

// Get only the final response after tool calls
const finalAnswer = await client.prompt(
  "List all TypeScript files in this project",
  { isAnswerOnly: true }
);

This is useful when you want to:

  • Display only the final answer to users, hiding intermediate thinking
  • Process only the conclusive response in automated workflows
  • Reduce token usage by ignoring intermediate agent messages

Streaming Session Updates

You can listen to real-time updates from the agent:

client.onSessionUpdate((event) => {
  switch (event.update.sessionUpdate) {
    case "agent_message_chunk":
      if (event.update.content.type === "text") {
        process.stdout.write(event.update.content.text);
      }
      break;
    case "tool_call":
      console.log("Tool called:", event.update.title);
      console.log("Input:", event.update.rawInput);
      break;
    case "tool_call_update":
      console.log("Tool output:", event.update.rawOutput);
      break;
  }
});

Running the Examples

# Run the dev example with streaming output
npm run dev "What's the weather in Tokyo?"

# Run the silent example (no streaming)
npm run silent "What's the weather in Paris?"

# Run with API key authentication
AUGMENT_API_TOKEN=your-key AUGMENT_API_URL=https://your-tenant.api.augmentcode.com npm run with-api-key "List files"

Custom Auggie Path and Workspace

const client = await Auggie.create({
  auggiePath: "/path/to/auggie",
  workspaceRoot: "/path/to/workspace",
  model: "sonnet4.5",
  allowIndexing: true,
  apiKey: "your-api-key",  // Optional
  apiUrl: "https://your-tenant.api.augmentcode.com",  // Required when apiKey is provided
  cliArgs: ["--verbose", "--timeout=30"],  // Optional: Additional CLI arguments
});

Advanced CLI Arguments

The cliArgs option allows you to pass additional command-line arguments directly to the Auggie CLI process. These arguments are appended after all SDK-generated flags.

// Pass custom CLI flags
const client = await Auggie.create({
  model: "sonnet4.5",
  cliArgs: ["--verbose", "--log-level=debug"]
});

// Arguments can use either format:
// 1. Separate flag and value: ["--timeout", "30"]
// 2. Combined with equals: ["--timeout=30"]
const client2 = await Auggie.create({
  model: "sonnet4.5",
  cliArgs: ["--timeout=60", "--retries", "3"]
});

Use this option for advanced configurations or experimental flags not exposed through standard SDK options. Refer to auggie --help for available CLI flags.

Context Modes

The SDK provides two context modes for codebase indexing and search.

Direct Context

✅ No Local Auggie Required - API Only

API-based indexing with state persistence:

import { DirectContext } from "@augmentcode/auggie-sdk";

// Authentication is automatic via:
// 1. Environment variables (AUGMENT_API_TOKEN, AUGMENT_API_URL)
// 2. ~/.augment/session.json (created by `auggie login`)
// 3. Or pass credentials directly in options
const context = await DirectContext.create();

// Add files to index (waits indefinitely by default)
await context.addToIndex([
  { path: "src/main.ts", contents: "..." }
]);

// Optionally set a timeout
await context.addToIndex(files, {
  timeout: 10 * 60 * 1000  // 10 minutes in milliseconds
});

// Track progress during indexing
await context.addToIndex(files, {
  onProgress: (progress) => {
    console.log(`[${progress.stage}] Uploaded: ${progress.uploaded}/${progress.total}, Indexed: ${progress.indexed}/${progress.total}`);
    if (progress.stage === 'uploading') {
      console.log(`  Current file: ${progress.currentFile}`);
      console.log(`  Bytes uploaded: ${progress.bytesUploaded}`);
    }
  }
});

// Search - returns results in a formatted string ready for LLM use or display
const results = await context.search("authentication logic");
console.log(results);

// Or use searchAndAsk for one-step Q&A
const answer = await context.searchAndAsk(
  "authentication logic",
  "How does authentication work?"
);
console.log(answer);

// Export state to avoid re-indexing
await context.exportToFile("/tmp/state.json");

// For search-only use cases, export lightweight state
await context.exportToFile("/tmp/search-state.json", { mode: "search-only" });

Search-Only Export (Optimized for Storage)

For applications that only need to search an existing index (without adding or removing files), you can export a lightweight search-only state that excludes the large blobs array:

import { DirectContext } from "@augmentcode/auggie-sdk";

// Create and index files normally
const context = await DirectContext.create();
await context.addToIndex(files);

// Export search-only state (much smaller for large codebases)
const searchState = context.export({ mode: "search-only" });
// or
await context.exportToFile("search-state.json", { mode: "search-only" });

// Later, import the search-only state
const searchContext = await DirectContext.import(searchState);
// or
const searchContext = await DirectContext.importFromFile("search-state.json");

// Search operations work normally
const results = await searchContext.search("authentication logic");

// But indexing operations will throw errors
// await searchContext.addToIndex(files); // ❌ Error: requires full state
// await searchContext.removeFromIndex(paths); // ❌ Error: requires full state
// searchContext.getIndexedPaths(); // ❌ Error: requires full state

When to use search-only export:

  • ✅ Search-only applications (e.g., documentation search, code Q&A)
  • ✅ Distributed systems where indexing happens centrally
  • ✅ Reducing index size for large codebases
  • ❌ Applications that need to add/remove files from the index

Importing a Context Connectors export

import() and importFromFile() also accept the wrapped export format produced by @augmentcode/context-connectors (the state.json file):

{
  "version": 1,
  "contextState": { ... },
  "source": { ... }
}

The SDK automatically detects this wrapper, extracts contextState, and restores it. Raw DirectContextState exports continue to work unchanged.

FileSystem Context

⚠️ Requires Local Auggie Installation

Local directory retrieval via MCP:

import { FileSystemContext } from "@augmentcode/auggie-sdk";

const context = await FileSystemContext.create({
  directory: "/path/to/workspace",
});

// Search workspace - returns formatted string ready for LLM use or display
const results = await context.search("authentication logic");
console.log(results);

// Or use searchAndAsk for one-step Q&A
const answer = await context.searchAndAsk(
  "authentication logic",
  "How does authentication work?"
);
console.log(answer);

await context.close();

API Reference

Auggie

Static Factory Method

static async create(options?: AuggieOptions): Promise<Auggie>

Creates and initializes a new Auggie instance. This method automatically connects to the ACP server and creates a session before returning.

Options:

  • auggiePath?: string - Path to the Auggie executable (default: "auggie")
  • workspaceRoot?: string - Working directory for the Auggie process (default: process.cwd())
  • model?: "haiku4.5" | "opus4.1" | "sonnet4.5" | "sonnet4" - Model to use (default: "haiku4.5")
  • allowIndexing?: boolean - Allow codebase indexing (default: true)
  • tools?: Record<string, Tool> - Custom tools to provide to Auggie (optional)
  • toolsMap?: Record<string, Tool> - Deprecated: Use tools instead. Kept for backwards compatibility.
  • apiKey?: string - API key for authentication (optional, sets AUGMENT_API_TOKEN)
  • apiUrl?: string - API URL for authentication (optional, sets AUGMENT_API_URL)
  • excludedTools?: ToolIdentifier[] - List of tool identifiers to exclude/disable (optional)
  • cliArgs?: string[] - Additional command-line arguments to pass to the Auggie CLI process (optional, default: [])

⚠️ Security: auggiePath must be a trusted, developer-controlled value. It is trimmed and split on whitespace, and each part is passed as a separate argument to the spawned process. The process is spawned without a shell, but the whitespace-splitting means an untrusted value could inject extra commands or CLI flags. Never populate auggiePath from user input or any other untrusted source. The same applies to the auggiePath option on FileSystem Context.

When tools (or toolsMap) is provided, an MCP server is automatically started and connected to the session.

Note: The constructor is private. Always use Auggie.create() to instantiate the class.

Methods

prompt(message: string, options?: { isAnswerOnly?: boolean }): Promise<string>

Sends a prompt to the agent and waits for completion.

  • message: The text prompt to send
  • options.isAnswerOnly: Optional boolean (default: false). When set to true, returns only the final response after all tool calls complete. When false or omitted, returns all agent message chunks including any intermediate responses.
  • Returns: The accumulated text response from the agent
onSessionUpdate(callback: (update: SessionNotification) => void): void

Registers a callback to receive session updates from the agent.

  • callback: Function to handle session updates
cancel(): Promise<void>

Cancels the current ongoing request.

close(): Promise<void>

Closes the connection and terminates the Auggie process:

  • Attempts a graceful session/close if the connected agent advertised support during initialize (via agentCapabilities.sessionCapabilities.close)
  • Always falls through to SIGKILL + MCP server cleanup, regardless of whether session/close succeeded or was skipped

This means close() is safe to call against any Auggie CLI version, including versions that do not implement session/close.

How It Works

ACP Protocol

The Agent Client Protocol (ACP) is a standardized protocol for communication between code editors and AI coding agents. This SDK implements the client side of the protocol.

MCP Integration

When you provide custom tools, the SDK automatically:

  1. Starts a local MCP (Model Context Protocol) server
  2. Wraps your AI SDK tools to work with Mastra's MCP implementation
  3. Registers the MCP server with the Auggie session
  4. Handles tool execution requests from Auggie
  5. Cleans up the MCP server when the session closes

Connection Flow

  1. Launch: Spawns Auggie with the --acp flag and optional parameters
  2. Streams: Creates bidirectional streams using stdio
  3. Initialize: Negotiates protocol version and capabilities. The initialize response is captured and used to determine agent capabilities (specifically sessionCapabilities.close) for the lifetime of the session
  4. MCP Setup: If tools are provided, starts an MCP server on a free port
  5. Session: Creates a conversation session with MCP server configuration
  6. Prompt: Sends prompts and receives responses
  7. Updates: Receives real-time updates via callbacks
  8. Cleanup: Closes connections and terminates processes

Client Implementation

The SDK implements the Client interface required by ACP:

  • sessionUpdate: Handles real-time updates from the agent
  • requestPermission: Handles permission requests (auto-selects first option)

On close(), the SDK checks the captured initialize response for sessionCapabilities.close and, if present, calls session/close before the process-kill fallback.

Examples

Complete Example with Tools and Streaming

import { Auggie } from "@augmentcode/auggie-sdk";
import { tool } from "ai";
import z from "zod";

const weatherTool = tool({
  name: "get_weather",
  description: "Get the weather in a location",
  inputSchema: z.object({
    location: z.string().describe("The location to get the weather for"),
  }),
  execute: async ({ location }) => {
    console.log(`Weather tool called for: ${location}`);
    return `The weather in ${location} is sunny.`;
  },
});

async function main() {
  const client = await Auggie.create({
    model: "sonnet4.5",
    tools: { weather_tool: weatherTool },
  });

  try {
    // Stream updates in real-time
    client.onSessionUpdate((event) => {
      switch (event.update.sessionUpdate) {
        case "agent_message_chunk":
          if (event.update.content.type === "text") {
            process.stdout.write(event.update.content.text);
          }
          break;
        case "tool_call":
          console.log(`\nTool: ${event.update.title}`);
          console.log("Input:", event.update.rawInput);
          break;
        case "tool_call_update":
          console.log("Output:", event.update.rawOutput);
          break;
      }
    });

    const response = await client.prompt(
      "What's the weather in Tokyo?",
      { isAnswerOnly: true }
    );

    console.log("\nFinal answer:", response);
  } catch (error) {
    console.error("Error:", error);
  } finally {
    await client.close();
  }
}

main();

Error Handling

try {
  const client = await Auggie.create();
  await client.prompt("Hello!");
  await client.close();
} catch (error) {
  if (error instanceof Error) {
    console.error("Error:", error.message);
  }
}

Requirements

All Features

  • Node.js 18+

Agent Interaction (ACP) & FileSystem Context

  • Auggie CLI installed and accessible in PATH (or provide custom path via auggiePath option)

⚠️ Security — debug logging: Enabling the debug option (on the AI SDK provider, FileSystem Context, or the internal context API client) prints full request payloads and API responses, which may contain sensitive prompt and response content. The Authorization header is deliberately never logged. Do not enable debug in production or when logs are shared or persisted.

  • Auggie must be authenticated (auggie login) or provide API credentials

Direct Context Only

  • API credentials (via auggie login, environment variables, or passed directly)
  • No local Auggie installation required

Building the Package

To build the TypeScript SDK:

npm run build

This compiles the TypeScript source to JavaScript in the dist/ directory with:

  • ES2020 module format
  • Type declaration files (.d.ts)
  • Source maps for debugging

To create a distributable tarball:

npm pack

This creates augmentcode-auggie-sdk-0.1.0.tgz which can be shared and installed.

Launching Auggie as ACP Server

To launch Auggie in ACP mode manually:

auggie --acp

This starts Auggie in ACP server mode, communicating via stdio using newline-delimited JSON (ndjson).

Available CLI Options

  • --acp: Enable ACP mode
  • --model <model>: Specify model (haiku4.5, opus4.1, sonnet4.5, sonnet4)
  • --workspace-root <path>: Set workspace directory
  • --allow-indexing: Enable codebase indexing

References

License

See the main repository license.

版本与发布记录

@augmentcode/auggie-sdk 共发布 18 个版本,首次发布于 2025/11/11;过去 12 个月发布了 18 个版本。

版本发布日期距今
0.2.0latest2026/07/084 个月前
0.1.182026/07/084 个月前
0.1.152026/02/039 个月前
0.1.142026/01/309 个月前
0.1.132026/01/099 个月前
0.1.122026/01/089 个月前

关于 @augmentcode/auggie-sdk 的常见问题

@augmentcode/auggie-sdk 是什么?

TypeScript SDK for Auggie

如何安装 @augmentcode/auggie-sdk?

在项目目录运行 npm install @augmentcode/auggie-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(^5)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@augmentcode/auggie-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@augmentcode/auggie-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@augmentcode/auggie-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@augmentcode/auggie-sdk 可以商用吗?

@augmentcode/auggie-sdk 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@augmentcode/auggie-sdk 的下载量有多少?

根据 npm 官方下载统计,@augmentcode/auggie-sdk 在 2026/10/07 – 2026/11/05 这 30 天内被下载 6,240 次,日均约 208 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@augmentcode/auggie-sdk 还在维护吗?

最新版本 0.2.0 发布于 2026/07/08(4 个月前);至今共发布 18 个版本,其中过去 12 个月发布了 18 个;首次发布于 2025/11/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。