奥吉 SDK
一个TypeScript SDK,用于与Auggie一起构建AI动力开发工具.
特征
AI SDK 提供者(Vercel AI SDK)
要求:仅限 API 证书(不需要本地 Auggie)
- 以 Vercel 的 AI SDK 作为语言模型提供者
- 兼容
generateText, (中文(简体) ),streamText,以及其他 AI SDK 函数 - 对自动调用工具(功能调用)的全力支持
- 多回合对话与上下文保留
- 简化对实时产出的回应
++ 代理交互( ACP)
要求: 本地Auggie安装
- ACP模式下启动 Auggie 并双向通信
- 发送提示并接收流媒体回复
- 使用 AI SDK 工具格式整合自定义工具
- 处理会话更新和权限请求
\\ 背景模式
索引和搜索代码的两种不同方式:
-
直接背景 - 以API为基础的指数化和状态持久性 要求:仅限 API 证书(不需要本地 Auggie)
- 在索引中明确添加文件
- 避免重新索引的进出口状态
- 适合应用程序的嵌入式搜索
-
文件系统上下文 - 通过MCP检索本地目录 要求: 本地Auggie安装
- 自动索引工作空间目录
- 双胞胎
auggie --mcp用于本地搜索 - IDE 扩展和本地工具的理想
安装
安装 Auggie CLI
安装 Auggie CLI :
npm install -g @augmentcode/auggie
安装 SDK
从 npm( 建议)
npm install @augmentcode/auggie-sdk
# or
pnpm add @augmentcode/auggie-sdk
从柏油球
npm install /path/to/augmentcode-auggie-sdk-0.1.0.tgz
# or
pnpm add /path/to/augmentcode-auggie-sdk-0.1.0.tgz
从本地目录( 用于开发)
npm install /path/to/auggie-sdk
# or
pnpm add /path/to/auggie-sdk
使用量
AI SDK 提供商(Vercel AI SDK)
不需要本地 Auggie - 只有 API
使用Advancment作为语言模型提供者并配有Vercel的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);
简化答复
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);
}
工具调用( 功能调用)
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?",
});
多回合对话
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 });
见 实例/ai-sdk-README.md 更详细的例子.
代理交互( ACP)
需要安装本地奥吉
对于具有工具和代码库背景的复杂代理任务:
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();
认证
Auggie有三种认证方法:
1. 使用 auggie login (建议)
auggie login
此保存您的 OAuth 会话, 并自动为 SDK 使用 .
2. 直接通过 API 密钥
const client = await Auggie.create({
apiKey: "your-api-key",
apiUrl: "https://your-tenant.api.augmentcode.com", // Your tenant-specific URL
model: "sonnet4.5",
});
3. 使用环境变量
export AUGMENT_API_TOKEN="your-api-key"
export AUGMENT_API_URL="https://your-tenant.api.augmentcode.com" # Your tenant-specific URL
然后创建客户端而不指定证书 :
const client = await Auggie.create({
model: "sonnet4.5",
});
说明: 如果你通过了 apiKey 财务报告和审定财务报表 apiUrl 对构造器,它们将覆盖任何环境变量.
使用自定义工具
您可以使用 AI SDK 工具格式为 Auggie 提供自定义工具 :
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();
不包括工具
您可以通过提供用于排除的工具标识符列表来禁用特定工具 。 这在想要限制代理的能力或阻止其使用某些集成时是有用的.
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();
可用工具类型
SDK为所有预定义的工具提供了类型Script类型:
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"],
});
常用案例
禁用安全处理执行工具 :
const client = await Auggie.create({
excludedTools: ["launch-process", "kill-process", "read-process", "write-process", "list-processes"],
});
禁用集成工具 :
const INTEGRATION_TOOLS = ["web-search"];
const client = await Auggie.create({
excludedTools: INTEGRATION_TOOLS,
});
禁用文件修改工具 :
const client = await Auggie.create({
excludedTools: ["save-file", "str-replace-editor", "remove-files"],
});
仅获得最后答复
当代理使用工具(如文件操作,网页搜索等)时,您可以选择在所有工具执行完成后只获得最终答案:
// 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 }
);
当您想要时, 这是有用的 :
- 只向用户显示最后的答案, 隐藏中间思维
- 只处理自动工作流程中的结论性反应
- 忽略中间代理消息而减少符号使用
流出会话更新
您可以收听代理服务器的实时更新 :
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;
}
});
运行示例
# 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"
自定义 Auggie 路径和工作空间
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
});
高级 CLI 参数
这个 cliArgs 选项允许您直接向 Auggie CLI 进程传递额外的命令行参数。 这些参数会在所有 SDK 生成的旗帜后附上 .
// 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"]
});
对于不通过标准SDK选项被曝光的高级配置或实验旗使用此选项. 参见 auggie --help 用于可用的 CLI 旗帜.
背景模式
SDK提供了两种上下文模式,用于代码基索引和搜索.
直接背景
不需要本地 Auggie - 只有 API
基于 API 的指数化状态持久性 :
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" });
仅搜索导出( 为存储而优化)
对于只需要搜索已存在的索引(不添加或删除文件)的应用程序,您可以导出一个轻量级只搜索状态,该状态排除了大块块阵列:
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
何时使用只搜索导出 :
- QQ 只搜索应用程序(例如文档搜索,代码QQA)
- 中央编制索引的分布式系统
- · 缩小大代码库的索引大小
- 需要从索引中添加/删除文件的应用程序
导入上下文连接符导出
import() 财务报告和审定财务报表 importFromFile() 并接受由 @augmentcode/context-connectors (单位:千美元) state.json 文件名 :
{
"version": 1,
"contextState": { ... },
"source": { ... }
}
SDK自动检测到这个包装器,提取器 contextState,并恢复它。 原始内容 DirectContextState 出口继续维持不变.
文件系统上下文
需要安装本地奥吉
通过 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 参考
Auggie
静态工厂方法
static async create(options?: AuggieOptions): Promise<Auggie>
创建并初始化一个新的 Auggie 实例 。 这种方法会自动连接到ACP服务器,并在返回前创建一个会话.
选项 :
auggiePath?: string- Auggie可执行文件的路径( 默认: "Auggie")workspaceRoot?: string- Auggie进程的工作目录(默认:process.cwd()(中文(简体) )model?: "haiku4.5" | "opus4.1" | "sonnet4.5" | "sonnet4"- 要使用的模式( 默认: “haiku4.5 ” )allowIndexing?: boolean- 允许代码库索引( 默认: 真)tools?: Record<string, Tool>- 向Auggie提供自定义工具(可选)toolsMap?: Record<string, Tool>- 说吧 折旧: 使用tools换句话说 用于后向兼容 .apiKey?: string- 认证的 API 密钥( 可选, 设置为 AUPENT API TOKEN)apiUrl?: string- 用于认证的 API URL(可选,设置为 AUGMENT API URL)excludedTools?: ToolIdentifier[]- 排除/残疾的工具识别器清单(可选)cliArgs?: string[]- 要传递到 Auggie CLI 进程的附加命令行参数(可选,默认:[])
* 安全:
auggiePath一定是个 信任、开发者控制 数值。 它被修剪并被分解在白空间上,每个部分被作为单独的论据传递到产卵过程. 过程产出 没有壳,但"白空相分"表示一个不可信值可以注入额外的命令或CLI旗. 从不填充auggiePath从用户输入或任何其他不可信来源获取。 这同样适用于auggiePath选项.
何时 tools (或 toolsMap),自动启动MCP服务器并与会话连接.
说明: 建筑师是私人的。 总是使用 Auggie.create() {\fn黑体\fs22\bord1\shad0\3ahbe\4ah00\fscx67\fscy66\2chffffff\3ch808080}把班级搞成一团.
方法
prompt(message: string, options?: { isAnswerOnly?: boolean }): Promise<string>
向代理发送提示并等待完成.
message: 要发送的文本提示options.isAnswerOnly: 可选布尔( 默认 ):false) (中文(简体) ). 设定为true,仅返回所有工具呼叫完成后的最后响应。 何时false或省略,返回所有代理信件块,包括任何中间响应.- 回返情况: 代理人的累积文本回复
onSessionUpdate(callback: (update: SessionNotification) => void): void
注册回调以接收代理服务器的会话更新.
callback: 处理会话更新的函数
cancel(): Promise<void>
取消当前进行中的请求.
close(): Promise<void>
关闭连接并终止 Auggie 进程 :
- 尝试优雅
session/close如果连接代理在initialize(通过)agentCapabilities.sessionCapabilities.close(中文(简体) ) - 总是通过SIGKILL + MCP 服务器清理,无论是否
session/close成功或被跳过
这意味着 close() 安全地调用任何 Auggie CLI 版本,包括未执行的版本 session/close。 。 。 .
如何运作
非加太议定书
代理客户协议(ACP)是用于代码编辑器与AI编码代理之间通信的标准化协议. 这个SDK执行协议的客户端.
MCP 一体化
当您提供自定义工具时, SDK 自动:
- 启动本地的 MCP( 模式上下文协议) 服务器
- 包装您的 AI SDK 工具, 以配合 Mastra 的 MCP 执行
- 用 Auggie 会话注册 MCP 服务器
- 处理来自 Auggie 的工具执行请求
- 会话关闭时清理 MCP 服务器
连接流程
- 发射: 孙子奥吉与
--acp旗帜和可选参数 - 流线: 使用 stdio 创建双向流
- 初始化:谈判协议版本和能力。 初始化反应被捕获并用于确定剂能(具体而言)
sessionCapabilities.close会期 - MCP 设置: 如果提供了工具, 在自由端口启动 MCP 服务器
- 会议: 创建与 MCP 服务器配置的对话会话
- 提示: 发送提示并接收回复
- 更新: 通过召回接收实时更新
- 清理: 关闭连接并终止进程
客户执行
SDK执行 Client 非加太公司所需的接口:
sessionUpdate: 处理代理服务器的实时更新requestPermission: 处理权限请求( 自动选择第一选项)
打开 close(),SDK检查捕获的初始化反应,用于 sessionCapabilities.close 如果有电话的话 session/close 在过程杀退之前.
实例
附有工具和流式的完整示例
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();
处理错误
try {
const client = await Auggie.create();
await client.prompt("Hello!");
await client.close();
} catch (error) {
if (error instanceof Error) {
console.error("Error:", error.message);
}
}
所需资源
所有特性
- 节点.js 18+
代理交互( ACP) 文件系统上下文( F)
- Auggie CLI 在 PATH 中安装和可访问(或提供自定义路径通过)
auggiePath选项)
• 安全——调试记录: 启用
debug选项(在 AI SDK 提供者、 FileSystem 上下文或内部上下文 API 客户端上) 打印完整的请求有效载荷和 API 回复,其中可能包含敏感的即时响应内容。 这个Authorization信头是故意的 从来没有记录。 不启用debug在生产中或在共享或持续使用原木时.
- Auggie必须经过认证(
auggie login)或提供API证书
仅直接背景
- API 证书(通过
auggie login,环境变量,或直接通过) - 无需安装本地 Auggie
构建软件包
要构建 TypeScript SDK :
npm run build
将 TypeScript 源编译为 JavaScript dist/ 以 :
- ES2020模块格式
- 类型声明文件( E)
.d.ts(中文(简体) ) - 调试的源地图
要创建可分配的柏油球:
npm pack
这创造了 augmentcode-auggie-sdk-0.1.0.tgz 可以共享和安装.
启动 Auggie 作为 ACP 服务器
手动启动 Auggie 模式 :
auggie --acp
这在ACP服务器模式中开始Auggie,通过stdio使用新线限定JSON(ndjson)进行通信.
可用的 CLI 选项
--acp: 启用非加太模式--model <model>: 指定型号(haiku4.5, opus4.1, sonnet4.5, sonnet4)--workspace-root <path>: 设置工作空间目录--allow-indexing: 启用代码库索引
参考资料
许可证
见主寄存许可证.