[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-74836":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":14,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":22,"hasPages":22,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":29,"readmeContent":30,"aiSummary":31,"trendingCount":16,"starSnapshotCount":16,"syncStatus":32,"lastSyncTime":33,"discoverSource":34},74836,"open-agent-sdk-typescript","codeany-ai\u002Fopen-agent-sdk-typescript","codeany-ai","Agent-SDK without CLI dependencies, as an alternative to claude-agent-sdk, completely open source","",null,"TypeScript",2697,949,12,5,0,6,31,18,82.03,"MIT License",false,"main",[25,26,27,28],"agent-sdk","claude-agent-sdk","claude-code","open-agent-sdk","2026-06-12 04:01:16","# Open Agent SDK (TypeScript)\n\n[![npm version](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002F@codeany\u002Fopen-agent-sdk)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@codeany\u002Fopen-agent-sdk)\n[![Node.js](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fnode-%3E%3D18-brightgreen)](https:\u002F\u002Fnodejs.org)\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-MIT-blue)](.\u002FLICENSE)\n\nOpen-source Agent SDK that runs the full agent loop **in-process** — no subprocess or CLI required. Supports both **Anthropic** and **OpenAI-compatible** APIs. Deploy anywhere: cloud, serverless, Docker, CI\u002FCD.\n\nAlso available in **Go**: [open-agent-sdk-go](https:\u002F\u002Fgithub.com\u002Fcodeany-ai\u002Fopen-agent-sdk-go)\n\n## Get started\n\n```bash\nnpm install @codeany\u002Fopen-agent-sdk\n```\n\nSet your API key:\n\n```bash\nexport CODEANY_API_KEY=your-api-key\n```\n\n### OpenAI-compatible models\n\nWorks with OpenAI, DeepSeek, Qwen, Mistral, or any OpenAI-compatible endpoint:\n\n```bash\nexport CODEANY_API_TYPE=openai-completions\nexport CODEANY_API_KEY=sk-...\nexport CODEANY_BASE_URL=https:\u002F\u002Fapi.openai.com\u002Fv1\nexport CODEANY_MODEL=gpt-4o\n```\n\n### Third-party Anthropic-compatible providers\n\n```bash\nexport CODEANY_BASE_URL=https:\u002F\u002Fopenrouter.ai\u002Fapi\nexport CODEANY_API_KEY=sk-or-...\nexport CODEANY_MODEL=anthropic\u002Fclaude-sonnet-4\n```\n\n## Quick start\n\n### One-shot query (streaming)\n\n```typescript\nimport { query } from \"@codeany\u002Fopen-agent-sdk\";\n\nfor await (const message of query({\n  prompt: \"Read package.json and tell me the project name.\",\n  options: {\n    allowedTools: [\"Read\", \"Glob\"],\n    permissionMode: \"bypassPermissions\",\n  },\n})) {\n  if (message.type === \"assistant\") {\n    for (const block of message.message.content) {\n      if (\"text\" in block) console.log(block.text);\n    }\n  }\n}\n```\n\n### Simple blocking prompt\n\n```typescript\nimport { createAgent } from \"@codeany\u002Fopen-agent-sdk\";\n\nconst agent = createAgent({ model: \"claude-sonnet-4-6\" });\nconst result = await agent.prompt(\"What files are in this project?\");\n\nconsole.log(result.text);\nconsole.log(\n  `Turns: ${result.num_turns}, Tokens: ${result.usage.input_tokens + result.usage.output_tokens}`,\n);\n```\n\n### OpenAI \u002F GPT models\n\n```typescript\nimport { createAgent } from \"@codeany\u002Fopen-agent-sdk\";\n\nconst agent = createAgent({\n  apiType: \"openai-completions\",\n  model: \"gpt-4o\",\n  apiKey: \"sk-...\",\n  baseURL: \"https:\u002F\u002Fapi.openai.com\u002Fv1\",\n});\n\nconst result = await agent.prompt(\"What files are in this project?\");\nconsole.log(result.text);\n```\n\nThe `apiType` is auto-detected from model name — models containing `gpt-`, `o1`, `o3`, `deepseek`, `qwen`, `mistral`, etc. automatically use `openai-completions`.\n\n### Multi-turn conversation\n\n```typescript\nimport { createAgent } from \"@codeany\u002Fopen-agent-sdk\";\n\nconst agent = createAgent({ maxTurns: 5 });\n\nconst r1 = await agent.prompt(\n  'Create a file \u002Ftmp\u002Fhello.txt with \"Hello World\"',\n);\nconsole.log(r1.text);\n\nconst r2 = await agent.prompt(\"Read back the file you just created\");\nconsole.log(r2.text);\n\nconsole.log(`Session messages: ${agent.getMessages().length}`);\n```\n\n### Custom tools (Zod schema)\n\n```typescript\nimport { z } from \"zod\";\nimport { query, tool, createSdkMcpServer } from \"@codeany\u002Fopen-agent-sdk\";\n\nconst getWeather = tool(\n  \"get_weather\",\n  \"Get the temperature for a city\",\n  { city: z.string().describe(\"City name\") },\n  async ({ city }) => ({\n    content: [{ type: \"text\", text: `${city}: 22°C, sunny` }],\n  }),\n);\n\nconst server = createSdkMcpServer({ name: \"weather\", tools: [getWeather] });\n\nfor await (const msg of query({\n  prompt: \"What is the weather in Tokyo?\",\n  options: { mcpServers: { weather: server } },\n})) {\n  if (msg.type === \"result\")\n    console.log(`Done: $${msg.total_cost_usd?.toFixed(4)}`);\n}\n```\n\n### Custom tools (low-level)\n\n```typescript\nimport {\n  createAgent,\n  getAllBaseTools,\n  defineTool,\n} from \"@codeany\u002Fopen-agent-sdk\";\n\nconst calculator = defineTool({\n  name: \"Calculator\",\n  description: \"Evaluate a math expression\",\n  inputSchema: {\n    type: \"object\",\n    properties: { expression: { type: \"string\" } },\n    required: [\"expression\"],\n  },\n  isReadOnly: true,\n  async call(input) {\n    const result = Function(`'use strict'; return (${input.expression})`)();\n    return `${input.expression} = ${result}`;\n  },\n});\n\nconst agent = createAgent({ tools: [...getAllBaseTools(), calculator] });\nconst r = await agent.prompt(\"Calculate 2**10 * 3\");\nconsole.log(r.text);\n```\n\n### Skills\n\nSkills are reusable prompt templates that extend agent capabilities. Five bundled skills are included: `simplify`, `commit`, `review`, `debug`, `test`.\n\n```typescript\nimport {\n  createAgent,\n  registerSkill,\n  getAllSkills,\n} from \"@codeany\u002Fopen-agent-sdk\";\n\n\u002F\u002F Register a custom skill\nregisterSkill({\n  name: \"explain\",\n  description: \"Explain a concept in simple terms\",\n  userInvocable: true,\n  async getPrompt(args) {\n    return [\n      {\n        type: \"text\",\n        text: `Explain in simple terms: ${args || \"Ask what to explain.\"}`,\n      },\n    ];\n  },\n});\n\nconsole.log(`${getAllSkills().length} skills registered`);\n\n\u002F\u002F The model can invoke skills via the Skill tool\nconst agent = createAgent();\nconst result = await agent.prompt('Use the \"explain\" skill to explain git rebase');\nconsole.log(result.text);\n```\n\n### Hooks (lifecycle events)\n\n```typescript\nimport { createAgent, createHookRegistry } from \"@codeany\u002Fopen-agent-sdk\";\n\nconst hooks = createHookRegistry({\n  PreToolUse: [\n    {\n      handler: async (input) => {\n        console.log(`About to use: ${input.toolName}`);\n        \u002F\u002F Return { block: true } to prevent tool execution\n      },\n    },\n  ],\n  PostToolUse: [\n    {\n      handler: async (input) => {\n        console.log(`Tool ${input.toolName} completed`);\n      },\n    },\n  ],\n});\n```\n\n20 lifecycle events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStart`, `SubagentStop`, `UserPromptSubmit`, `PermissionRequest`, `PermissionDenied`, `TaskCreated`, `TaskCompleted`, `ConfigChange`, `CwdChanged`, `FileChanged`, `Notification`, `PreCompact`, `PostCompact`, `TeammateIdle`.\n\n### MCP server integration\n\n```typescript\nimport { createAgent } from \"@codeany\u002Fopen-agent-sdk\";\n\nconst agent = createAgent({\n  mcpServers: {\n    filesystem: {\n      command: \"npx\",\n      args: [\"-y\", \"@modelcontextprotocol\u002Fserver-filesystem\", \"\u002Ftmp\"],\n    },\n  },\n});\n\nconst result = await agent.prompt(\"List files in \u002Ftmp\");\nconsole.log(result.text);\nawait agent.close();\n```\n\n### Subagents\n\n```typescript\nimport { query } from \"@codeany\u002Fopen-agent-sdk\";\n\nfor await (const msg of query({\n  prompt: \"Use the code-reviewer agent to review src\u002Findex.ts\",\n  options: {\n    agents: {\n      \"code-reviewer\": {\n        description: \"Expert code reviewer\",\n        prompt: \"Analyze code quality. Focus on security and performance.\",\n        tools: [\"Read\", \"Glob\", \"Grep\"],\n      },\n    },\n  },\n})) {\n  if (msg.type === \"result\") console.log(\"Done\");\n}\n```\n\n### Permissions\n\n```typescript\nimport { query } from \"@codeany\u002Fopen-agent-sdk\";\n\n\u002F\u002F Read-only agent — can only analyze, not modify\nfor await (const msg of query({\n  prompt: \"Review the code in src\u002F for best practices.\",\n  options: {\n    allowedTools: [\"Read\", \"Glob\", \"Grep\"],\n    permissionMode: \"dontAsk\",\n  },\n})) {\n  \u002F\u002F ...\n}\n```\n\n### Web UI\n\nA built-in web chat interface is included for testing:\n\n```bash\nnpx tsx examples\u002Fweb\u002Fserver.ts\n# Open http:\u002F\u002Flocalhost:8081\n```\n\n## API reference\n\n### Top-level functions\n\n| Function                              | Description                                                    |\n| ------------------------------------- | -------------------------------------------------------------- |\n| `query({ prompt, options })`          | One-shot streaming query, returns `AsyncGenerator\u003CSDKMessage>` |\n| `createAgent(options)`                | Create a reusable agent with session persistence               |\n| `tool(name, desc, schema, handler)`   | Create a tool with Zod schema validation                       |\n| `createSdkMcpServer({ name, tools })` | Bundle tools into an in-process MCP server                     |\n| `defineTool(config)`                  | Low-level tool definition helper                               |\n| `getAllBaseTools()`                   | Get all 35+ built-in tools                                     |\n| `registerSkill(definition)`           | Register a custom skill                                        |\n| `getAllSkills()`                       | Get all registered skills                                      |\n| `createProvider(apiType, opts)`        | Create an LLM provider directly                                |\n| `createHookRegistry(config)`          | Create a hook registry for lifecycle events                    |\n| `listSessions()`                      | List persisted sessions                                        |\n| `forkSession(id)`                     | Fork a session for branching                                   |\n\n### Agent methods\n\n| Method                          | Description                                           |\n| ------------------------------- | ----------------------------------------------------- |\n| `agent.query(prompt)`           | Streaming query, returns `AsyncGenerator\u003CSDKMessage>` |\n| `agent.prompt(text)`            | Blocking query, returns `Promise\u003CQueryResult>`        |\n| `agent.getMessages()`           | Get conversation history                              |\n| `agent.clear()`                 | Reset session                                         |\n| `agent.interrupt()`             | Abort current query                                   |\n| `agent.setModel(model)`         | Change model mid-session                              |\n| `agent.setPermissionMode(mode)` | Change permission mode                                |\n| `agent.getApiType()`            | Get current API type                                  |\n| `agent.close()`                 | Close MCP connections, persist session                |\n\n### Options\n\n| Option               | Type                                    | Default                | Description                                                          |\n| -------------------- | --------------------------------------- | ---------------------- | -------------------------------------------------------------------- |\n| `apiType`            | `string`                                | auto-detected          | `'anthropic-messages'` or `'openai-completions'`                     |\n| `model`              | `string`                                | `claude-sonnet-4-6`    | LLM model ID                                                         |\n| `apiKey`             | `string`                                | `CODEANY_API_KEY`      | API key                                                              |\n| `baseURL`            | `string`                                | —                      | Custom API endpoint                                                  |\n| `cwd`                | `string`                                | `process.cwd()`        | Working directory                                                    |\n| `systemPrompt`       | `string`                                | —                      | System prompt override                                               |\n| `appendSystemPrompt` | `string`                                | —                      | Append to default system prompt                                      |\n| `tools`              | `ToolDefinition[]`                      | All built-in           | Available tools                                                      |\n| `allowedTools`       | `string[]`                              | —                      | Tool allow-list                                                      |\n| `disallowedTools`    | `string[]`                              | —                      | Tool deny-list                                                       |\n| `permissionMode`     | `string`                                | `bypassPermissions`    | `default` \u002F `acceptEdits` \u002F `dontAsk` \u002F `bypassPermissions` \u002F `plan` |\n| `canUseTool`         | `function`                              | —                      | Custom permission callback                                           |\n| `maxTurns`           | `number`                                | `10`                   | Max agentic turns                                                    |\n| `maxBudgetUsd`       | `number`                                | —                      | Spending cap                                                         |\n| `thinking`           | `ThinkingConfig`                        | `{ type: 'adaptive' }` | Extended thinking                                                    |\n| `effort`             | `string`                                | `high`                 | Reasoning effort: `low` \u002F `medium` \u002F `high` \u002F `max`                  |\n| `mcpServers`         | `Record\u003Cstring, McpServerConfig>`       | —                      | MCP server connections                                               |\n| `agents`             | `Record\u003Cstring, AgentDefinition>`       | —                      | Subagent definitions                                                 |\n| `hooks`              | `Record\u003Cstring, HookCallbackMatcher[]>` | —                      | Lifecycle hooks                                                      |\n| `resume`             | `string`                                | —                      | Resume session by ID                                                 |\n| `continue`           | `boolean`                               | `false`                | Continue most recent session                                         |\n| `persistSession`     | `boolean`                               | `true`                 | Persist session to disk                                              |\n| `sessionId`          | `string`                                | auto                   | Explicit session ID                                                  |\n| `outputFormat`       | `{ type: 'json_schema', schema }`       | —                      | Structured output                                                    |\n| `sandbox`            | `SandboxSettings`                       | —                      | Filesystem\u002Fnetwork sandbox                                           |\n| `settingSources`     | `SettingSource[]`                       | —                      | Load AGENT.md, project settings                                      |\n| `env`                | `Record\u003Cstring, string>`                | —                      | Environment variables                                                |\n| `abortController`    | `AbortController`                       | —                      | Cancellation controller                                              |\n\n### Environment variables\n\n| Variable             | Description                                              |\n| -------------------- | -------------------------------------------------------- |\n| `CODEANY_API_KEY`    | API key (required)                                       |\n| `CODEANY_API_TYPE`   | `anthropic-messages` (default) or `openai-completions`   |\n| `CODEANY_MODEL`      | Default model override                                   |\n| `CODEANY_BASE_URL`   | Custom API endpoint                                      |\n| `CODEANY_AUTH_TOKEN` | Alternative auth token                                   |\n\n## Built-in tools\n\n| Tool                                       | Description                                  |\n| ------------------------------------------ | -------------------------------------------- |\n| **Bash**                                   | Execute shell commands                       |\n| **Read**                                   | Read files with line numbers                 |\n| **Write**                                  | Create \u002F overwrite files                     |\n| **Edit**                                   | Precise string replacement in files          |\n| **Glob**                                   | Find files by pattern                        |\n| **Grep**                                   | Search file contents with regex              |\n| **WebFetch**                               | Fetch and parse web content                  |\n| **WebSearch**                              | Search the web                               |\n| **NotebookEdit**                           | Edit Jupyter notebook cells                  |\n| **Agent**                                  | Spawn subagents for parallel work            |\n| **Skill**                                  | Invoke registered skills                     |\n| **TaskCreate\u002FList\u002FUpdate\u002FGet\u002FStop\u002FOutput** | Task management system                       |\n| **TeamCreate\u002FDelete**                      | Multi-agent team coordination                |\n| **SendMessage**                            | Inter-agent messaging                        |\n| **EnterWorktree\u002FExitWorktree**             | Git worktree isolation                       |\n| **EnterPlanMode\u002FExitPlanMode**             | Structured planning workflow                 |\n| **AskUserQuestion**                        | Ask the user for input                       |\n| **ToolSearch**                             | Discover lazy-loaded tools                   |\n| **ListMcpResources\u002FReadMcpResource**       | MCP resource access                          |\n| **CronCreate\u002FDelete\u002FList**                 | Scheduled task management                    |\n| **RemoteTrigger**                          | Remote agent triggers                        |\n| **LSP**                                    | Language Server Protocol (code intelligence) |\n| **Config**                                 | Dynamic configuration                        |\n| **TodoWrite**                              | Session todo list                            |\n\n## Bundled skills\n\n| Skill        | Description                                                    |\n| ------------ | -------------------------------------------------------------- |\n| `simplify`   | Review changed code for reuse, quality, and efficiency         |\n| `commit`     | Create a git commit with a well-crafted message                |\n| `review`     | Review code changes for correctness, security, and performance |\n| `debug`      | Systematic debugging using structured investigation            |\n| `test`       | Run tests and analyze failures                                 |\n\nRegister custom skills with `registerSkill()`.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│                   Your Application                    │\n│                                                       │\n│   import { createAgent } from '@codeany\u002Fopen-agent-sdk' │\n└────────────────────────┬─────────────────────────────┘\n                         │\n              ┌──────────▼──────────┐\n              │       Agent         │  Session state, tool pool,\n              │  query() \u002F prompt() │  MCP connections, hooks\n              └──────────┬──────────┘\n                         │\n              ┌──────────▼──────────┐\n              │    QueryEngine      │  Agentic loop:\n              │   submitMessage()   │  API call → tools → repeat\n              └──────────┬──────────┘\n                         │\n         ┌───────────────┼───────────────┐\n         │               │               │\n   ┌─────▼─────┐  ┌─────▼─────┐  ┌─────▼─────┐\n   │  Provider  │  │  35 Tools │  │    MCP     │\n   │ Anthropic  │  │ Bash,Read │  │  Servers   │\n   │  OpenAI    │  │ Edit,...  │  │ stdio\u002FSSE\u002F │\n   │ DeepSeek   │  │ + Skills  │  │ HTTP\u002FSDK   │\n   └───────────┘  └───────────┘  └───────────┘\n```\n\n**Key internals:**\n\n| Component             | Description                                                        |\n| --------------------- | ------------------------------------------------------------------ |\n| **Provider layer**    | Abstracts Anthropic \u002F OpenAI API differences                       |\n| **QueryEngine**       | Core agentic loop with auto-compact, retry, tool orchestration     |\n| **Skill system**      | Reusable prompt templates with 5 bundled skills                    |\n| **Hook system**       | 20 lifecycle events integrated into the engine                     |\n| **Auto-compact**      | Summarizes conversation when context window fills up               |\n| **Micro-compact**     | Truncates oversized tool results                                   |\n| **Retry**             | Exponential backoff for rate limits and transient errors            |\n| **Token estimation**  | Rough token counting with pricing for Claude, GPT, DeepSeek models |\n| **File cache**        | LRU cache (100 entries, 25 MB) for file reads                      |\n| **Session storage**   | Persist \u002F resume \u002F fork sessions on disk                           |\n| **Context injection** | Git status + AGENT.md automatically injected into system prompt    |\n\n## Examples\n\n| #   | File                                  | Description                            |\n| --- | ------------------------------------- | -------------------------------------- |\n| 01  | `examples\u002F01-simple-query.ts`         | Streaming query with event handling    |\n| 02  | `examples\u002F02-multi-tool.ts`           | Multi-tool orchestration (Glob + Bash) |\n| 03  | `examples\u002F03-multi-turn.ts`           | Multi-turn session persistence         |\n| 04  | `examples\u002F04-prompt-api.ts`           | Blocking `prompt()` API                |\n| 05  | `examples\u002F05-custom-system-prompt.ts` | Custom system prompt                   |\n| 06  | `examples\u002F06-mcp-server.ts`           | MCP server integration                 |\n| 07  | `examples\u002F07-custom-tools.ts`         | Custom tools with `defineTool()`       |\n| 08  | `examples\u002F08-official-api-compat.ts`  | `query()` API pattern                  |\n| 09  | `examples\u002F09-subagents.ts`            | Subagent delegation                    |\n| 10  | `examples\u002F10-permissions.ts`          | Read-only agent with tool restrictions |\n| 11  | `examples\u002F11-custom-mcp-tools.ts`     | `tool()` + `createSdkMcpServer()`      |\n| 12  | `examples\u002F12-skills.ts`              | Skill system usage                     |\n| 13  | `examples\u002F13-hooks.ts`               | Lifecycle hooks                        |\n| 14  | `examples\u002F14-openai-compat.ts`       | OpenAI \u002F DeepSeek models               |\n| web | `examples\u002Fweb\u002F`                       | Web chat UI for testing                |\n\nRun any example:\n\n```bash\nnpx tsx examples\u002F01-simple-query.ts\n```\n\nStart the web UI:\n\n```bash\nnpx tsx examples\u002Fweb\u002Fserver.ts\n```\n\n## Star History\n\n\u003Ca href=\"https:\u002F\u002Fwww.star-history.com\u002F?repos=codeany-ai%2Fopen-agent-sdk-typescript&type=timeline&legend=top-left\">\n \u003Cpicture>\n   \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"https:\u002F\u002Fapi.star-history.com\u002Fimage?repos=codeany-ai\u002Fopen-agent-sdk-typescript&type=timeline&theme=dark&legend=top-left\" \u002F>\n   \u003Csource media=\"(prefers-color-scheme: light)\" srcset=\"https:\u002F\u002Fapi.star-history.com\u002Fimage?repos=codeany-ai\u002Fopen-agent-sdk-typescript&type=timeline&legend=top-left\" \u002F>\n   \u003Cimg alt=\"Star History Chart\" src=\"https:\u002F\u002Fapi.star-history.com\u002Fimage?repos=codeany-ai\u002Fopen-agent-sdk-typescript&type=timeline&legend=top-left\" \u002F>\n \u003C\u002Fpicture>\n\u003C\u002Fa>\n\n## License\n\nMIT\n","Open Agent SDK 是一个完全开源的代理开发工具包，用于替代claude-agent-sdk，且不依赖CLI。它支持Anthropic和OpenAI兼容的API，允许在进程内运行完整的代理循环，无需子进程或CLI。该SDK使用TypeScript编写，易于部署到云、无服务器环境、Docker或CI\u002FCD管道中。适用于需要与语言模型进行交互的各种应用场景，如自动化任务处理、代码生成、文档分析等。通过简单的配置即可快速集成不同供应商的语言模型服务，提供流式查询和多轮对话功能，满足开发者灵活调用的需求。",2,"2026-06-11 03:51:03","high_star"]