@augmentcode/auggie-sdk
v0.1.15
Published
TypeScript SDK for Auggie
Keywords
Readme
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:
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
FileSystem Context - Local directory retrieval via MCP Requires: Local Auggie installation
- Automatically index a workspace directory
- Spawns
auggie --mcpfor local search - Ideal for IDE extensions and local tools
Installation
Install Auggie CLI
Install the Auggie CLI:
npm install -g @augmentcode/auggieInstall the SDK
From tarball (recommended for distribution)
npm install /path/to/augmentcode-auggie-sdk-0.1.0.tgz
# or
pnpm add /path/to/augmentcode-auggie-sdk-0.1.0.tgzFrom local directory (for development)
npm install /path/to/auggie-sdk
# or
pnpm add /path/to/auggie-sdkUsage
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:
1. Using auggie login (Recommended)
auggie loginThis 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 URLThen 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 stateWhen 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
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: Usetoolsinstead. 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: [])
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 sendoptions.isAnswerOnly: Optional boolean (default:false). When set totrue, returns only the final response after all tool calls complete. Whenfalseor 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, stops the MCP server (if running), and terminates the Auggie process.
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:
- Starts a local MCP (Model Context Protocol) server
- Wraps your AI SDK tools to work with Mastra's MCP implementation
- Registers the MCP server with the Auggie session
- Handles tool execution requests from Auggie
- Cleans up the MCP server when the session closes
Connection Flow
- Launch: Spawns Auggie with the
--acpflag and optional parameters - Streams: Creates bidirectional streams using stdio
- Initialize: Negotiates protocol version and capabilities
- MCP Setup: If tools are provided, starts an MCP server on a free port
- Session: Creates a conversation session with MCP server configuration
- Prompt: Sends prompts and receives responses
- Updates: Receives real-time updates via callbacks
- Cleanup: Closes connections and terminates processes
Client Implementation
The SDK implements the Client interface required by ACP:
sessionUpdate: Handles real-time updates from the agentrequestPermission: Handles permission requests (auto-selects first option)
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
auggiePathoption) - 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 buildThis 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 packThis 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 --acpThis 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.
