@morphllm/gitmorph-sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +429 -0
- package/dist/ai/index.d.ts +48 -0
- package/dist/ai/index.js +25 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/anthropic/index.d.ts +85 -0
- package/dist/anthropic/index.js +64 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/chunk-A3AOZFPE.js +474 -0
- package/dist/chunk-A3AOZFPE.js.map +1 -0
- package/dist/chunk-FXEX72CO.js +43 -0
- package/dist/chunk-FXEX72CO.js.map +1 -0
- package/dist/chunk-JXXUBMF6.js +61 -0
- package/dist/chunk-JXXUBMF6.js.map +1 -0
- package/dist/chunk-QT3Y4ZIS.js +547 -0
- package/dist/chunk-QT3Y4ZIS.js.map +1 -0
- package/dist/{types.d.ts → client-B_I_0i1T.d.ts} +69 -37
- package/dist/index.d.ts +21 -5
- package/dist/index.js +3 -547
- package/dist/index.js.map +1 -0
- package/dist/instructions-BE0g1eFs.d.ts +284 -0
- package/dist/mcp/bin.d.ts +1 -0
- package/dist/mcp/bin.js +21 -0
- package/dist/mcp/bin.js.map +1 -0
- package/dist/mcp/index.d.ts +29 -0
- package/dist/mcp/index.js +5 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/openai/index.d.ts +60 -0
- package/dist/openai/index.js +75 -0
- package/dist/openai/index.js.map +1 -0
- package/package.json +56 -8
- package/dist/api.d.ts +0 -10
- package/dist/api.d.ts.map +0 -1
- package/dist/client.d.ts +0 -13
- package/dist/client.d.ts.map +0 -1
- package/dist/config.d.ts +0 -8
- package/dist/config.d.ts.map +0 -1
- package/dist/errors.d.ts +0 -18
- package/dist/errors.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/mirror.d.ts +0 -6
- package/dist/mirror.d.ts.map +0 -1
- package/dist/repo.d.ts +0 -28
- package/dist/repo.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/utils.d.ts +0 -5
- package/dist/utils.d.ts.map +0 -1
package/README.md
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
# @morphllm/gitmorph-sdk
|
|
2
|
+
|
|
3
|
+
Agent-native TypeScript SDK for reading, searching, and navigating Git repositories through [GitMorph](https://gitmorph.com). No cloning. Every operation is a single HTTP call against a server-side mirror.
|
|
4
|
+
|
|
5
|
+
Built for AI coding agents that need to understand codebases: read files with line ranges, grep across repos, glob for file patterns, list directories, walk commits. All server-side, all fast.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @morphllm/gitmorph-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
15
|
+
|
|
16
|
+
const gm = new GitMorph();
|
|
17
|
+
const repo = gm.repo("facebook/react");
|
|
18
|
+
|
|
19
|
+
// Read a file
|
|
20
|
+
const file = await repo.readFile("package.json");
|
|
21
|
+
|
|
22
|
+
// Grep for a pattern
|
|
23
|
+
const results = await repo.grep({ pattern: "useState" });
|
|
24
|
+
|
|
25
|
+
// Glob for files
|
|
26
|
+
const tsFiles = await repo.glob({ patterns: ["**/*.ts"] });
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Give your agent access to any repo
|
|
30
|
+
|
|
31
|
+
Paste this into Claude Code (or any agent with tool-use) to give it read access to any mirrored repository:
|
|
32
|
+
|
|
33
|
+
````
|
|
34
|
+
You have access to the @morphllm/gitmorph-sdk for reading Git repositories without cloning.
|
|
35
|
+
The SDK is already installed and authenticated via ~/.config/gm/config.json.
|
|
36
|
+
|
|
37
|
+
To use it, write a quick TypeScript script and run it with `npx tsx`:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
41
|
+
const gm = new GitMorph();
|
|
42
|
+
const repo = gm.repo("owner/repo");
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Available methods on `repo`:
|
|
46
|
+
- `repo.readFile(path, { ref?, lines?: [{ start, end }] })` - read a file, optionally specific line ranges (1-indexed, inclusive)
|
|
47
|
+
- `repo.getFileContents(paths[], { ref? })` - batch read multiple files in one call
|
|
48
|
+
- `repo.grep({ pattern, language?, caseSensitive?, maxMatches?, page? })` - server-side code search within the repo
|
|
49
|
+
- `repo.glob({ patterns[], ref?, prefix?, sizes?, limit? })` - find files matching glob patterns (e.g. `["**/*.ts", "!**/*.test.ts"]`)
|
|
50
|
+
- `repo.listDir({ path?, ref?, recursive? })` - list directory contents
|
|
51
|
+
- `repo.listBranches({ page?, limit? })` - list branches
|
|
52
|
+
- `repo.listCommits({ sha?, path?, since?, until?, page?, limit? })` - list commits
|
|
53
|
+
|
|
54
|
+
Available methods on `gm` (instance-wide):
|
|
55
|
+
- `gm.grepAll({ pattern, language?, page?, limit?, sortByStars? })` - search code across ALL repos
|
|
56
|
+
- `gm.mirror(source, options?)` - mirror a GitHub/GitLab/Gitea repo (e.g. `gm.mirror("facebook/react")`)
|
|
57
|
+
- `gm.getRepositoryInfo("owner/repo")` - get repo metadata
|
|
58
|
+
|
|
59
|
+
Use these to explore, search, and read code. Prefer grep and glob over listing directories manually.
|
|
60
|
+
````
|
|
61
|
+
|
|
62
|
+
## Drop-in LLM tools
|
|
63
|
+
|
|
64
|
+
The SDK ships framework-native tool adapters under subpath exports. Import, pass to your agent, go. No hand-written schemas, no dispatcher wiring.
|
|
65
|
+
|
|
66
|
+
Every adapter exposes the same factories:
|
|
67
|
+
|
|
68
|
+
- `createGitmorphTools(gm, opts?)` — multi-repo; every tool takes `repo: "owner/name"`.
|
|
69
|
+
- `createGitmorphRepoTools(gm, "owner/name", opts?)` — pinned to one repo; tools drop the `repo` arg.
|
|
70
|
+
|
|
71
|
+
Each adapter is an optional peer dependency — you only install what you use.
|
|
72
|
+
|
|
73
|
+
### Vercel AI SDK
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npm install ai zod
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
81
|
+
import { createGitmorphRepoTools, GITMORPH_SYSTEM_PROMPT } from "@morphllm/gitmorph-sdk/ai";
|
|
82
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
83
|
+
import { generateText } from "ai";
|
|
84
|
+
|
|
85
|
+
const gm = new GitMorph();
|
|
86
|
+
const { text } = await generateText({
|
|
87
|
+
model: anthropic("claude-sonnet-4-6"),
|
|
88
|
+
system: GITMORPH_SYSTEM_PROMPT,
|
|
89
|
+
tools: createGitmorphRepoTools(gm, "facebook/react"),
|
|
90
|
+
prompt: "What testing framework does this repo use? Read package.json to confirm.",
|
|
91
|
+
maxSteps: 5,
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Pass `only` as a `const` tuple to narrow the return type — autocomplete shows exactly the tools you asked for:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const tools = createGitmorphTools(gm, { only: ["gm_grep", "gm_read_file"] as const });
|
|
99
|
+
// tools has exactly { gm_grep: Tool; gm_read_file: Tool }
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Anthropic SDK
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
npm install @anthropic-ai/sdk zod zod-to-json-schema
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
110
|
+
import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
111
|
+
import { createGitmorphTools, GITMORPH_SYSTEM_PROMPT } from "@morphllm/gitmorph-sdk/anthropic";
|
|
112
|
+
|
|
113
|
+
const anthropic = new Anthropic();
|
|
114
|
+
const gm = new GitMorph();
|
|
115
|
+
const { tools, handleToolUse } = createGitmorphTools(gm, { cacheControl: true });
|
|
116
|
+
|
|
117
|
+
const messages: Anthropic.Messages.MessageParam[] = [
|
|
118
|
+
{ role: "user", content: "Find every useEffect in facebook/react" },
|
|
119
|
+
];
|
|
120
|
+
|
|
121
|
+
let msg = await anthropic.messages.create({
|
|
122
|
+
model: "claude-sonnet-4-6",
|
|
123
|
+
max_tokens: 4096,
|
|
124
|
+
system: GITMORPH_SYSTEM_PROMPT,
|
|
125
|
+
tools,
|
|
126
|
+
messages,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
while (msg.stop_reason === "tool_use") {
|
|
130
|
+
const uses = msg.content.filter((b): b is Anthropic.Messages.ToolUseBlock => b.type === "tool_use");
|
|
131
|
+
const results = await Promise.all(uses.map(handleToolUse));
|
|
132
|
+
messages.push({ role: "assistant", content: msg.content });
|
|
133
|
+
messages.push({ role: "user", content: results });
|
|
134
|
+
msg = await anthropic.messages.create({
|
|
135
|
+
model: "claude-sonnet-4-6",
|
|
136
|
+
max_tokens: 4096,
|
|
137
|
+
system: GITMORPH_SYSTEM_PROMPT,
|
|
138
|
+
tools,
|
|
139
|
+
messages,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`handleToolUse` never throws. Errors become `tool_result` blocks with `is_error: true` so the model can recover in the next turn. `cacheControl: true` attaches Anthropic prompt caching to the tool list — stable tool sets become a cached prefix of every request.
|
|
145
|
+
|
|
146
|
+
### OpenAI SDK
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
npm install openai zod zod-to-json-schema
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import OpenAI from "openai";
|
|
154
|
+
import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
155
|
+
import { createGitmorphTools, GITMORPH_SYSTEM_PROMPT } from "@morphllm/gitmorph-sdk/openai";
|
|
156
|
+
|
|
157
|
+
const openai = new OpenAI();
|
|
158
|
+
const gm = new GitMorph();
|
|
159
|
+
const { tools, handleToolCall } = createGitmorphTools(gm);
|
|
160
|
+
|
|
161
|
+
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
|
162
|
+
{ role: "system", content: GITMORPH_SYSTEM_PROMPT },
|
|
163
|
+
{ role: "user", content: "Find every useEffect in facebook/react" },
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
for (let step = 0; step < 10; step++) {
|
|
167
|
+
const res = await openai.chat.completions.create({ model: "gpt-4o", tools, messages });
|
|
168
|
+
const msg = res.choices[0]!.message;
|
|
169
|
+
messages.push(msg);
|
|
170
|
+
if (!msg.tool_calls?.length) break;
|
|
171
|
+
const results = await Promise.all(msg.tool_calls.map(handleToolCall));
|
|
172
|
+
messages.push(...results);
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### MCP (Claude Desktop / Cursor / Claude Code)
|
|
177
|
+
|
|
178
|
+
Zero-code path. Add GitMorph to your MCP client's config:
|
|
179
|
+
|
|
180
|
+
```json
|
|
181
|
+
{
|
|
182
|
+
"mcpServers": {
|
|
183
|
+
"gitmorph": {
|
|
184
|
+
"command": "npx",
|
|
185
|
+
"args": ["-y", "@morphllm/gitmorph-sdk", "mcp"],
|
|
186
|
+
"env": { "GM_TOKEN": "gm_..." }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
No install. No global CLI. The `bin` entry in this package registers `gitmorph-mcp`, and `npx -y` runs it directly. Auth resolves from the `env` block, from `~/.config/gm/config.json`, or from your shell environment.
|
|
193
|
+
|
|
194
|
+
To embed the MCP server in your own Node process:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
198
|
+
import { startGitmorphMcpServer } from "@morphllm/gitmorph-sdk/mcp";
|
|
199
|
+
|
|
200
|
+
await startGitmorphMcpServer(new GitMorph());
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Tool reference
|
|
204
|
+
|
|
205
|
+
All adapters expose the same 9 tools by default (`gm_mirror` is opt-in via `includeMirror: true`):
|
|
206
|
+
|
|
207
|
+
| Tool | Purpose |
|
|
208
|
+
|------|---------|
|
|
209
|
+
| `gm_read_file` | Read a file, optionally a specific line range |
|
|
210
|
+
| `gm_read_files` | Batch-read multiple files in one call |
|
|
211
|
+
| `gm_grep` | Search file contents within one repo (regex or keyword) |
|
|
212
|
+
| `gm_glob` | Find files by path pattern (`**/*.ts`) |
|
|
213
|
+
| `gm_list_dir` | List entries in a directory |
|
|
214
|
+
| `gm_list_branches` | List branches with head commits |
|
|
215
|
+
| `gm_list_commits` | List commits, filterable by path or date range |
|
|
216
|
+
| `gm_grep_all` | Search code across all mirrored repositories |
|
|
217
|
+
| `gm_get_repo_info` | Fetch metadata for a repository |
|
|
218
|
+
| `gm_mirror` | *Opt-in.* Mirror a GitHub/GitLab/Gitea repo into GitMorph |
|
|
219
|
+
|
|
220
|
+
### Customizing
|
|
221
|
+
|
|
222
|
+
Every factory accepts the same options:
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
createGitmorphTools(gm, {
|
|
226
|
+
only: ["gm_grep", "gm_read_file"] as const, // whitelist (narrows the return type)
|
|
227
|
+
exclude: ["gm_list_branches"], // drop specific tools
|
|
228
|
+
rename: { gm_grep: "search_code" }, // rename to match your agent's naming scheme
|
|
229
|
+
includeMirror: false, // enable the opt-in gm_mirror tool
|
|
230
|
+
maxOutputBytes: 262_144, // cap per-call output (Anthropic/OpenAI/MCP)
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
`GITMORPH_SYSTEM_PROMPT` is re-exported from every subpath — append it to your system message to give the model explicit guidance on when to reach for each tool.
|
|
235
|
+
|
|
236
|
+
## Auth
|
|
237
|
+
|
|
238
|
+
Credentials resolve in order:
|
|
239
|
+
|
|
240
|
+
1. Constructor options: `new GitMorph({ token: "...", host: "..." })`
|
|
241
|
+
2. Environment variables: `GM_TOKEN`, `GM_HOST`
|
|
242
|
+
3. Config file: `~/.config/gm/config.json`
|
|
243
|
+
|
|
244
|
+
The host defaults to `gitmorph.com` if not set.
|
|
245
|
+
|
|
246
|
+
## API reference
|
|
247
|
+
|
|
248
|
+
### `GitMorph` (client)
|
|
249
|
+
|
|
250
|
+
| Method | Description |
|
|
251
|
+
|--------|-------------|
|
|
252
|
+
| `gm.repo("owner/repo")` | Get a repo handle for file/search operations |
|
|
253
|
+
| `gm.getRepositoryInfo("owner/repo")` | Repo metadata (branches, stars, language, etc.) |
|
|
254
|
+
| `gm.mirror(source, opts?)` | Mirror a repo from GitHub/GitLab/Gitea into GitMorph |
|
|
255
|
+
| `gm.grepAll({ pattern, ... })` | Search code across all repos on the instance |
|
|
256
|
+
|
|
257
|
+
### `GitMorphRepo` (per-repo operations)
|
|
258
|
+
|
|
259
|
+
| Method | Description |
|
|
260
|
+
|--------|-------------|
|
|
261
|
+
| `repo.readFile(path, opts?)` | Read a file, optionally specific line ranges |
|
|
262
|
+
| `repo.getFileContents(paths[], opts?)` | Batch read multiple files in one call |
|
|
263
|
+
| `repo.grep({ pattern, ... })` | Server-side code search within this repo |
|
|
264
|
+
| `repo.glob({ patterns[], ... })` | Find files matching glob patterns |
|
|
265
|
+
| `repo.listDir(opts?)` | List directory contents (optionally recursive) |
|
|
266
|
+
| `repo.listBranches(opts?)` | List branches with latest commit info |
|
|
267
|
+
| `repo.listCommits(opts?)` | List commits with filtering by path, date range |
|
|
268
|
+
|
|
269
|
+
### Read files
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
// Full file
|
|
273
|
+
const file = await repo.readFile("src/index.ts");
|
|
274
|
+
// file.content, file.totalLines
|
|
275
|
+
|
|
276
|
+
// Specific line ranges (1-indexed, inclusive)
|
|
277
|
+
const snippet = await repo.readFile("src/index.ts", {
|
|
278
|
+
ref: "main",
|
|
279
|
+
lines: [{ start: 10, end: 25 }, { start: 100, end: 110 }],
|
|
280
|
+
});
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
### Batch read
|
|
284
|
+
|
|
285
|
+
```ts
|
|
286
|
+
const files = await repo.getFileContents([
|
|
287
|
+
"package.json",
|
|
288
|
+
"tsconfig.json",
|
|
289
|
+
"src/index.ts",
|
|
290
|
+
]);
|
|
291
|
+
// Returns (FileContentEntry | null)[] -- null for files that don't exist
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
### Grep (single repo)
|
|
295
|
+
|
|
296
|
+
```ts
|
|
297
|
+
const result = await repo.grep({
|
|
298
|
+
pattern: "createServer",
|
|
299
|
+
language: "TypeScript",
|
|
300
|
+
caseSensitive: true,
|
|
301
|
+
maxMatches: 20,
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
for (const match of result.matches) {
|
|
305
|
+
console.log(`${match.path}:${match.lineNumber} ${match.lineContent}`);
|
|
306
|
+
// match.submatches[] has character offsets within the line
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
### Grep all (cross-repo)
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
const result = await gm.grepAll({
|
|
314
|
+
pattern: "fastApply",
|
|
315
|
+
language: "TypeScript",
|
|
316
|
+
sortByStars: true,
|
|
317
|
+
limit: 10,
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
for (const match of result.matches) {
|
|
321
|
+
console.log(`${match.repoName} ${match.filename}`);
|
|
322
|
+
for (const line of match.lines) {
|
|
323
|
+
console.log(` L${line.num}: ${line.content}`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
### Glob
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
const result = await repo.glob({
|
|
332
|
+
patterns: ["src/**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"],
|
|
333
|
+
prefix: "src/",
|
|
334
|
+
limit: 500,
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
for (const entry of result.entries) {
|
|
338
|
+
console.log(`${entry.path} ${entry.size} bytes`);
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### List directory
|
|
343
|
+
|
|
344
|
+
```ts
|
|
345
|
+
// Top-level
|
|
346
|
+
const root = await repo.listDir();
|
|
347
|
+
|
|
348
|
+
// Subdirectory, recursive
|
|
349
|
+
const src = await repo.listDir({ path: "src", recursive: true, ref: "develop" });
|
|
350
|
+
|
|
351
|
+
for (const entry of src.entries) {
|
|
352
|
+
console.log(`${entry.type === "dir" ? "d" : "f"} ${entry.path}`);
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
### Branches
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
const branches = await repo.listBranches({ limit: 50 });
|
|
360
|
+
for (const b of branches) {
|
|
361
|
+
console.log(`${b.name} ${b.commit.id.slice(0, 8)} ${b.commit.message}`);
|
|
362
|
+
}
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### Commits
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
const commits = await repo.listCommits({
|
|
369
|
+
sha: "main",
|
|
370
|
+
path: "src/",
|
|
371
|
+
since: "2025-01-01T00:00:00Z",
|
|
372
|
+
limit: 20,
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
for (const c of commits) {
|
|
376
|
+
console.log(`${c.sha.slice(0, 8)} ${c.author.name} ${c.message}`);
|
|
377
|
+
}
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
### Mirror
|
|
381
|
+
|
|
382
|
+
```ts
|
|
383
|
+
// Shorthand (defaults to GitHub)
|
|
384
|
+
const { repository, repo } = await gm.mirror("facebook/react");
|
|
385
|
+
|
|
386
|
+
// Full URL with options
|
|
387
|
+
const { repository } = await gm.mirror("https://gitlab.com/org/repo", {
|
|
388
|
+
private: true,
|
|
389
|
+
issues: true,
|
|
390
|
+
pullRequests: true,
|
|
391
|
+
releases: true,
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// repo is a GitMorphRepo handle, ready to use immediately
|
|
395
|
+
const files = await repo.glob({ patterns: ["**/*.ts"] });
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
## Error handling
|
|
399
|
+
|
|
400
|
+
All errors extend `GitMorphError`:
|
|
401
|
+
|
|
402
|
+
```ts
|
|
403
|
+
import {
|
|
404
|
+
GitMorphError,
|
|
405
|
+
ApiError,
|
|
406
|
+
AuthenticationError,
|
|
407
|
+
GrepError,
|
|
408
|
+
MirrorError,
|
|
409
|
+
} from "@morphllm/gitmorph-sdk";
|
|
410
|
+
|
|
411
|
+
try {
|
|
412
|
+
await repo.readFile("missing.txt");
|
|
413
|
+
} catch (err) {
|
|
414
|
+
if (err instanceof ApiError) {
|
|
415
|
+
console.log(err.status, err.url); // 404, https://gitmorph.com/api/v1/...
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
| Error class | When |
|
|
421
|
+
|-------------|------|
|
|
422
|
+
| `AuthenticationError` | No token found in options, env, or config file |
|
|
423
|
+
| `ApiError` | HTTP error from the API (has `.status` and `.url`) |
|
|
424
|
+
| `GrepError` | Invalid grep pattern or search failure |
|
|
425
|
+
| `MirrorError` | Mirror/migrate operation failed |
|
|
426
|
+
|
|
427
|
+
## License
|
|
428
|
+
|
|
429
|
+
MIT
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Tool } from 'ai';
|
|
2
|
+
import { G as GitMorph } from '../client-B_I_0i1T.js';
|
|
3
|
+
import { G as GitmorphToolName, D as DEFAULT_TOOL_NAMES, C as CreateToolsOptions } from '../instructions-BE0g1eFs.js';
|
|
4
|
+
export { a as DefaultGitmorphToolName, b as GITMORPH_SYSTEM_PROMPT } from '../instructions-BE0g1eFs.js';
|
|
5
|
+
import 'zod';
|
|
6
|
+
|
|
7
|
+
/** Map a tuple of tool names to a `{ name: Tool }` record. */
|
|
8
|
+
type AiToolMap<Names extends string> = {
|
|
9
|
+
readonly [K in Names]: Tool;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Create Vercel AI SDK tools for a {@link GitMorph} client.
|
|
13
|
+
*
|
|
14
|
+
* Repo-scoped tools take a `repo: "owner/name"` argument. For a single-repo
|
|
15
|
+
* chat, pin the repo with {@link createGitmorphRepoTools} to drop that field.
|
|
16
|
+
*
|
|
17
|
+
* Pass `only` as a `const` tuple to narrow the return type to exactly those
|
|
18
|
+
* tools — autocomplete will show just what you asked for.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
23
|
+
* import { createGitmorphTools } from "@morphllm/gitmorph-sdk/ai";
|
|
24
|
+
* import { anthropic } from "@ai-sdk/anthropic";
|
|
25
|
+
* import { generateText } from "ai";
|
|
26
|
+
*
|
|
27
|
+
* const gm = new GitMorph();
|
|
28
|
+
* const { text } = await generateText({
|
|
29
|
+
* model: anthropic("claude-sonnet-4-6"),
|
|
30
|
+
* tools: createGitmorphTools(gm),
|
|
31
|
+
* prompt: "What testing framework does facebook/react use?",
|
|
32
|
+
* maxSteps: 5,
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
declare function createGitmorphTools<const Only extends readonly GitmorphToolName[] = typeof DEFAULT_TOOL_NAMES>(gm: GitMorph, opts?: CreateToolsOptions<Only>): AiToolMap<Only[number]>;
|
|
37
|
+
/**
|
|
38
|
+
* Pinned variant — every tool operates on a single repository; no `repo`
|
|
39
|
+
* argument in any tool's schema.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* const tools = createGitmorphRepoTools(gm, "facebook/react");
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
declare function createGitmorphRepoTools<const Only extends readonly GitmorphToolName[] = typeof DEFAULT_TOOL_NAMES>(gm: GitMorph, slug: string, opts?: CreateToolsOptions<Only>): AiToolMap<Only[number]>;
|
|
47
|
+
|
|
48
|
+
export { CreateToolsOptions, DEFAULT_TOOL_NAMES, GitmorphToolName, createGitmorphRepoTools, createGitmorphTools };
|
package/dist/ai/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { resolveToolSet } from '../chunk-A3AOZFPE.js';
|
|
2
|
+
export { DEFAULT_TOOL_NAMES, GITMORPH_SYSTEM_PROMPT } from '../chunk-A3AOZFPE.js';
|
|
3
|
+
import { tool } from 'ai';
|
|
4
|
+
|
|
5
|
+
function createGitmorphTools(gm, opts = {}) {
|
|
6
|
+
return toAiTools(resolveToolSet(gm, opts));
|
|
7
|
+
}
|
|
8
|
+
function createGitmorphRepoTools(gm, slug, opts = {}) {
|
|
9
|
+
return toAiTools(resolveToolSet(gm, opts, slug));
|
|
10
|
+
}
|
|
11
|
+
function toAiTools(normalized) {
|
|
12
|
+
const out = {};
|
|
13
|
+
for (const t of normalized) {
|
|
14
|
+
out[t.name] = tool({
|
|
15
|
+
description: t.description,
|
|
16
|
+
inputSchema: t.schema,
|
|
17
|
+
execute: (input) => t.execute(input)
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export { createGitmorphRepoTools, createGitmorphTools };
|
|
24
|
+
//# sourceMappingURL=index.js.map
|
|
25
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/ai/index.ts"],"names":[],"mappings":";;;;AA8CO,SAAS,mBAAA,CAGd,EAAA,EACA,IAAA,GAAiC,EAAC,EACT;AACzB,EAAA,OAAO,SAAA,CAAU,cAAA,CAAe,EAAA,EAAI,IAAI,CAAC,CAAA;AAC3C;AAWO,SAAS,uBAAA,CAGd,EAAA,EACA,IAAA,EACA,IAAA,GAAiC,EAAC,EACT;AACzB,EAAA,OAAO,SAAA,CAAU,cAAA,CAAe,EAAA,EAAI,IAAA,EAAM,IAAI,CAAC,CAAA;AACjD;AAEA,SAAS,UAAU,UAAA,EAAoD;AACrE,EAAA,MAAM,MAA4B,EAAC;AACnC,EAAA,KAAA,MAAW,KAAK,UAAA,EAAY;AAC1B,IAAA,GAAA,CAAI,CAAA,CAAE,IAAI,CAAA,GAAI,IAAA,CAAK;AAAA,MACjB,aAAa,CAAA,CAAE,WAAA;AAAA,MACf,aAAa,CAAA,CAAE,MAAA;AAAA,MACf,OAAA,EAAS,CAAC,KAAA,KAAmB,CAAA,CAAE,QAAQ,KAAK;AAAA,KAC7C,CAAA;AAAA,EACH;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["import { tool, type Tool } from \"ai\";\nimport type { GitMorph } from \"../client.js\";\nimport {\n resolveToolSet,\n type CreateToolsOptions,\n type NormalizedTool,\n} from \"../tools/core.js\";\nimport {\n DEFAULT_TOOL_NAMES,\n type DefaultGitmorphToolName,\n type GitmorphToolName,\n} from \"../tools/registry.js\";\n\nexport { GITMORPH_SYSTEM_PROMPT } from \"../tools/instructions.js\";\nexport { DEFAULT_TOOL_NAMES } from \"../tools/registry.js\";\nexport type { CreateToolsOptions } from \"../tools/core.js\";\nexport type { GitmorphToolName, DefaultGitmorphToolName } from \"../tools/registry.js\";\n\n/** Map a tuple of tool names to a `{ name: Tool }` record. */\ntype AiToolMap<Names extends string> = { readonly [K in Names]: Tool };\n\n/**\n * Create Vercel AI SDK tools for a {@link GitMorph} client.\n *\n * Repo-scoped tools take a `repo: \"owner/name\"` argument. For a single-repo\n * chat, pin the repo with {@link createGitmorphRepoTools} to drop that field.\n *\n * Pass `only` as a `const` tuple to narrow the return type to exactly those\n * tools — autocomplete will show just what you asked for.\n *\n * @example\n * ```ts\n * import { GitMorph } from \"@morphllm/gitmorph-sdk\";\n * import { createGitmorphTools } from \"@morphllm/gitmorph-sdk/ai\";\n * import { anthropic } from \"@ai-sdk/anthropic\";\n * import { generateText } from \"ai\";\n *\n * const gm = new GitMorph();\n * const { text } = await generateText({\n * model: anthropic(\"claude-sonnet-4-6\"),\n * tools: createGitmorphTools(gm),\n * prompt: \"What testing framework does facebook/react use?\",\n * maxSteps: 5,\n * });\n * ```\n */\nexport function createGitmorphTools<\n const Only extends readonly GitmorphToolName[] = typeof DEFAULT_TOOL_NAMES,\n>(\n gm: GitMorph,\n opts: CreateToolsOptions<Only> = {},\n): AiToolMap<Only[number]> {\n return toAiTools(resolveToolSet(gm, opts)) as AiToolMap<Only[number]>;\n}\n\n/**\n * Pinned variant — every tool operates on a single repository; no `repo`\n * argument in any tool's schema.\n *\n * @example\n * ```ts\n * const tools = createGitmorphRepoTools(gm, \"facebook/react\");\n * ```\n */\nexport function createGitmorphRepoTools<\n const Only extends readonly GitmorphToolName[] = typeof DEFAULT_TOOL_NAMES,\n>(\n gm: GitMorph,\n slug: string,\n opts: CreateToolsOptions<Only> = {},\n): AiToolMap<Only[number]> {\n return toAiTools(resolveToolSet(gm, opts, slug)) as AiToolMap<Only[number]>;\n}\n\nfunction toAiTools(normalized: NormalizedTool[]): Record<string, Tool> {\n const out: Record<string, Tool> = {};\n for (const t of normalized) {\n out[t.name] = tool({\n description: t.description,\n inputSchema: t.schema,\n execute: (input: unknown) => t.execute(input),\n });\n }\n return out;\n}\n"]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
2
|
+
import { G as GitMorph } from '../client-B_I_0i1T.js';
|
|
3
|
+
import { G as GitmorphToolName, C as CreateToolsOptions } from '../instructions-BE0g1eFs.js';
|
|
4
|
+
export { D as DEFAULT_TOOL_NAMES, a as DefaultGitmorphToolName, b as GITMORPH_SYSTEM_PROMPT } from '../instructions-BE0g1eFs.js';
|
|
5
|
+
import 'zod';
|
|
6
|
+
|
|
7
|
+
/** Extra options for the Anthropic adapter on top of the shared set. */
|
|
8
|
+
interface AnthropicToolOptions<Only extends readonly GitmorphToolName[] = readonly GitmorphToolName[]> extends CreateToolsOptions<Only> {
|
|
9
|
+
/**
|
|
10
|
+
* Attach `cache_control: { type: "ephemeral" }` to the last tool so the
|
|
11
|
+
* tool definitions become a cached prefix of every request. Stable tool
|
|
12
|
+
* sets benefit from this for free — default off, flip on for production
|
|
13
|
+
* agent loops that send many messages.
|
|
14
|
+
*
|
|
15
|
+
* See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
|
|
16
|
+
*/
|
|
17
|
+
cacheControl?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** One element of `msg.content` when `msg.stop_reason === "tool_use"`. */
|
|
20
|
+
interface ToolUseBlock {
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly name: string;
|
|
23
|
+
readonly input: unknown;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Return value of {@link createGitmorphTools} for Anthropic. `tools` is a
|
|
27
|
+
* drop-in for `messages.create({ tools })`; `handleToolUse` consumes one
|
|
28
|
+
* `tool_use` block and returns a ready-to-send `tool_result`.
|
|
29
|
+
*/
|
|
30
|
+
interface GitmorphAnthropicTools {
|
|
31
|
+
readonly tools: Anthropic.Messages.Tool[];
|
|
32
|
+
/**
|
|
33
|
+
* Execute a tool_use block and return a tool_result content block. Never
|
|
34
|
+
* throws — errors become `is_error: true` results the model can recover
|
|
35
|
+
* from in the next turn.
|
|
36
|
+
*/
|
|
37
|
+
handleToolUse(block: ToolUseBlock): Promise<Anthropic.Messages.ToolResultBlockParam>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Create Anthropic SDK tools + dispatcher for a {@link GitMorph} client.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* import Anthropic from "@anthropic-ai/sdk";
|
|
45
|
+
* import { GitMorph } from "@morphllm/gitmorph-sdk";
|
|
46
|
+
* import { createGitmorphTools, GITMORPH_SYSTEM_PROMPT } from "@morphllm/gitmorph-sdk/anthropic";
|
|
47
|
+
*
|
|
48
|
+
* const anthropic = new Anthropic();
|
|
49
|
+
* const gm = new GitMorph();
|
|
50
|
+
* const { tools, handleToolUse } = createGitmorphTools(gm, { cacheControl: true });
|
|
51
|
+
*
|
|
52
|
+
* const messages: Anthropic.Messages.MessageParam[] = [
|
|
53
|
+
* { role: "user", content: "Find every useEffect in facebook/react" },
|
|
54
|
+
* ];
|
|
55
|
+
*
|
|
56
|
+
* let msg = await anthropic.messages.create({
|
|
57
|
+
* model: "claude-sonnet-4-6",
|
|
58
|
+
* max_tokens: 4096,
|
|
59
|
+
* system: GITMORPH_SYSTEM_PROMPT,
|
|
60
|
+
* tools,
|
|
61
|
+
* messages,
|
|
62
|
+
* });
|
|
63
|
+
*
|
|
64
|
+
* while (msg.stop_reason === "tool_use") {
|
|
65
|
+
* const toolUses = msg.content.filter((b): b is Anthropic.Messages.ToolUseBlock => b.type === "tool_use");
|
|
66
|
+
* const results = await Promise.all(toolUses.map(handleToolUse));
|
|
67
|
+
* messages.push({ role: "assistant", content: msg.content });
|
|
68
|
+
* messages.push({ role: "user", content: results });
|
|
69
|
+
* msg = await anthropic.messages.create({ model: "claude-sonnet-4-6", max_tokens: 4096, system: GITMORPH_SYSTEM_PROMPT, tools, messages });
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
declare function createGitmorphTools<const Only extends readonly GitmorphToolName[] = readonly GitmorphToolName[]>(gm: GitMorph, opts?: AnthropicToolOptions<Only>): GitmorphAnthropicTools;
|
|
74
|
+
/**
|
|
75
|
+
* Pinned variant — every tool operates on a single repository. Tools drop
|
|
76
|
+
* the `repo` argument.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const { tools, handleToolUse } = createGitmorphRepoTools(gm, "facebook/react");
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
declare function createGitmorphRepoTools<const Only extends readonly GitmorphToolName[] = readonly GitmorphToolName[]>(gm: GitMorph, slug: string, opts?: AnthropicToolOptions<Only>): GitmorphAnthropicTools;
|
|
84
|
+
|
|
85
|
+
export { type AnthropicToolOptions, CreateToolsOptions, type GitmorphAnthropicTools, GitmorphToolName, type ToolUseBlock, createGitmorphRepoTools, createGitmorphTools };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { toJsonSchema, clampOutput } from '../chunk-FXEX72CO.js';
|
|
2
|
+
import { resolveToolSet } from '../chunk-A3AOZFPE.js';
|
|
3
|
+
export { DEFAULT_TOOL_NAMES, GITMORPH_SYSTEM_PROMPT } from '../chunk-A3AOZFPE.js';
|
|
4
|
+
|
|
5
|
+
// src/anthropic/index.ts
|
|
6
|
+
function createGitmorphTools(gm, opts = {}) {
|
|
7
|
+
return build(resolveToolSet(gm, opts), opts);
|
|
8
|
+
}
|
|
9
|
+
function createGitmorphRepoTools(gm, slug, opts = {}) {
|
|
10
|
+
return build(resolveToolSet(gm, opts, slug), opts);
|
|
11
|
+
}
|
|
12
|
+
function build(normalized, opts) {
|
|
13
|
+
const byName = new Map(normalized.map((t) => [t.name, t]));
|
|
14
|
+
const maxBytes = opts.maxOutputBytes;
|
|
15
|
+
const tools = normalized.map((t) => ({
|
|
16
|
+
name: t.name,
|
|
17
|
+
description: t.description,
|
|
18
|
+
input_schema: toJsonSchema(t.schema)
|
|
19
|
+
}));
|
|
20
|
+
if (opts.cacheControl && tools.length > 0) {
|
|
21
|
+
tools[tools.length - 1].cache_control = { type: "ephemeral" };
|
|
22
|
+
}
|
|
23
|
+
const handleToolUse = async (block) => {
|
|
24
|
+
const def = byName.get(block.name);
|
|
25
|
+
if (!def) return errorResult(block.id, `Unknown tool: ${block.name}`);
|
|
26
|
+
const parsed = def.schema.safeParse(block.input);
|
|
27
|
+
if (!parsed.success) {
|
|
28
|
+
return errorResult(
|
|
29
|
+
block.id,
|
|
30
|
+
`Invalid input for ${block.name}: ${parsed.error.message}`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const result = await def.execute(parsed.data);
|
|
35
|
+
return {
|
|
36
|
+
type: "tool_result",
|
|
37
|
+
tool_use_id: block.id,
|
|
38
|
+
content: clampOutput(result, maxBytes)
|
|
39
|
+
};
|
|
40
|
+
} catch (err) {
|
|
41
|
+
return errorResult(block.id, describeError(err));
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
return { tools, handleToolUse };
|
|
45
|
+
}
|
|
46
|
+
function errorResult(tool_use_id, message) {
|
|
47
|
+
return {
|
|
48
|
+
type: "tool_result",
|
|
49
|
+
tool_use_id,
|
|
50
|
+
is_error: true,
|
|
51
|
+
content: message
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function describeError(err) {
|
|
55
|
+
if (err instanceof Error) {
|
|
56
|
+
const name = err.name && err.name !== "Error" ? `${err.name}: ` : "";
|
|
57
|
+
return `${name}${err.message}`;
|
|
58
|
+
}
|
|
59
|
+
return typeof err === "string" ? err : JSON.stringify(err);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { createGitmorphRepoTools, createGitmorphTools };
|
|
63
|
+
//# sourceMappingURL=index.js.map
|
|
64
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/anthropic/index.ts"],"names":[],"mappings":"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","file":"index.js","sourcesContent":["import type Anthropic from \"@anthropic-ai/sdk\";\nimport type { GitMorph } from \"../client.js\";\nimport {\n resolveToolSet,\n type CreateToolsOptions,\n type NormalizedTool,\n} from \"../tools/core.js\";\nimport { toJsonSchema } from \"../tools/json-schema.js\";\nimport { clampOutput } from \"../tools/truncate.js\";\nimport type { GitmorphToolName } from \"../tools/registry.js\";\n\nexport { GITMORPH_SYSTEM_PROMPT } from \"../tools/instructions.js\";\nexport { DEFAULT_TOOL_NAMES } from \"../tools/registry.js\";\nexport type { CreateToolsOptions } from \"../tools/core.js\";\nexport type { GitmorphToolName, DefaultGitmorphToolName } from \"../tools/registry.js\";\n\n/** Extra options for the Anthropic adapter on top of the shared set. */\nexport interface AnthropicToolOptions<\n Only extends readonly GitmorphToolName[] = readonly GitmorphToolName[],\n> extends CreateToolsOptions<Only> {\n /**\n * Attach `cache_control: { type: \"ephemeral\" }` to the last tool so the\n * tool definitions become a cached prefix of every request. Stable tool\n * sets benefit from this for free — default off, flip on for production\n * agent loops that send many messages.\n *\n * See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cacheControl?: boolean;\n}\n\n/** One element of `msg.content` when `msg.stop_reason === \"tool_use\"`. */\nexport interface ToolUseBlock {\n readonly id: string;\n readonly name: string;\n readonly input: unknown;\n}\n\n/**\n * Return value of {@link createGitmorphTools} for Anthropic. `tools` is a\n * drop-in for `messages.create({ tools })`; `handleToolUse` consumes one\n * `tool_use` block and returns a ready-to-send `tool_result`.\n */\nexport interface GitmorphAnthropicTools {\n readonly tools: Anthropic.Messages.Tool[];\n /**\n * Execute a tool_use block and return a tool_result content block. Never\n * throws — errors become `is_error: true` results the model can recover\n * from in the next turn.\n */\n handleToolUse(\n block: ToolUseBlock,\n ): Promise<Anthropic.Messages.ToolResultBlockParam>;\n}\n\n/**\n * Create Anthropic SDK tools + dispatcher for a {@link GitMorph} client.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { GitMorph } from \"@morphllm/gitmorph-sdk\";\n * import { createGitmorphTools, GITMORPH_SYSTEM_PROMPT } from \"@morphllm/gitmorph-sdk/anthropic\";\n *\n * const anthropic = new Anthropic();\n * const gm = new GitMorph();\n * const { tools, handleToolUse } = createGitmorphTools(gm, { cacheControl: true });\n *\n * const messages: Anthropic.Messages.MessageParam[] = [\n * { role: \"user\", content: \"Find every useEffect in facebook/react\" },\n * ];\n *\n * let msg = await anthropic.messages.create({\n * model: \"claude-sonnet-4-6\",\n * max_tokens: 4096,\n * system: GITMORPH_SYSTEM_PROMPT,\n * tools,\n * messages,\n * });\n *\n * while (msg.stop_reason === \"tool_use\") {\n * const toolUses = msg.content.filter((b): b is Anthropic.Messages.ToolUseBlock => b.type === \"tool_use\");\n * const results = await Promise.all(toolUses.map(handleToolUse));\n * messages.push({ role: \"assistant\", content: msg.content });\n * messages.push({ role: \"user\", content: results });\n * msg = await anthropic.messages.create({ model: \"claude-sonnet-4-6\", max_tokens: 4096, system: GITMORPH_SYSTEM_PROMPT, tools, messages });\n * }\n * ```\n */\nexport function createGitmorphTools<\n const Only extends readonly GitmorphToolName[] = readonly GitmorphToolName[],\n>(\n gm: GitMorph,\n opts: AnthropicToolOptions<Only> = {},\n): GitmorphAnthropicTools {\n return build(resolveToolSet(gm, opts), opts);\n}\n\n/**\n * Pinned variant — every tool operates on a single repository. Tools drop\n * the `repo` argument.\n *\n * @example\n * ```ts\n * const { tools, handleToolUse } = createGitmorphRepoTools(gm, \"facebook/react\");\n * ```\n */\nexport function createGitmorphRepoTools<\n const Only extends readonly GitmorphToolName[] = readonly GitmorphToolName[],\n>(\n gm: GitMorph,\n slug: string,\n opts: AnthropicToolOptions<Only> = {},\n): GitmorphAnthropicTools {\n return build(resolveToolSet(gm, opts, slug), opts);\n}\n\n// ── Internals ────────────────────────────────────────────────────────────────\n\nfunction build(\n normalized: NormalizedTool[],\n opts: AnthropicToolOptions,\n): GitmorphAnthropicTools {\n const byName = new Map(normalized.map((t) => [t.name, t]));\n const maxBytes = opts.maxOutputBytes;\n\n const tools: Anthropic.Messages.Tool[] = normalized.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: toJsonSchema(t.schema) as Anthropic.Messages.Tool[\"input_schema\"],\n }));\n\n if (opts.cacheControl && tools.length > 0) {\n // Anthropic caches up to and including the first tool marked with\n // cache_control. Mark the last one so the entire tools array is cached.\n (tools[tools.length - 1] as Anthropic.Messages.Tool & {\n cache_control?: { type: \"ephemeral\" };\n }).cache_control = { type: \"ephemeral\" };\n }\n\n const handleToolUse: GitmorphAnthropicTools[\"handleToolUse\"] = async (\n block,\n ) => {\n const def = byName.get(block.name);\n if (!def) return errorResult(block.id, `Unknown tool: ${block.name}`);\n\n const parsed = def.schema.safeParse(block.input);\n if (!parsed.success) {\n return errorResult(\n block.id,\n `Invalid input for ${block.name}: ${parsed.error.message}`,\n );\n }\n\n try {\n const result = await def.execute(parsed.data);\n return {\n type: \"tool_result\",\n tool_use_id: block.id,\n content: clampOutput(result, maxBytes),\n };\n } catch (err) {\n return errorResult(block.id, describeError(err));\n }\n };\n\n return { tools, handleToolUse };\n}\n\nfunction errorResult(\n tool_use_id: string,\n message: string,\n): Anthropic.Messages.ToolResultBlockParam {\n return {\n type: \"tool_result\",\n tool_use_id,\n is_error: true,\n content: message,\n };\n}\n\nfunction describeError(err: unknown): string {\n if (err instanceof Error) {\n const name = err.name && err.name !== \"Error\" ? `${err.name}: ` : \"\";\n return `${name}${err.message}`;\n }\n return typeof err === \"string\" ? err : JSON.stringify(err);\n}\n"]}
|