@pen.dev/cli 0.3.6 → 0.3.8
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 +29 -5
- package/dist/browserAll-D_luQzBO.mjs +2 -0
- package/dist/dist-CbU0Evuc.mjs +4 -0
- package/dist/{esm-Dupm_ZuQ.mjs → esm-DBgQcoAH.mjs} +1 -1
- package/dist/index.mjs +2 -2
- package/dist/node_modules/@highagency/pencil-wasm/enums.gen.d.ts +44 -0
- package/dist/node_modules/@highagency/pencil-wasm/package.json +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/pencil.d.ts +22 -6
- package/dist/node_modules/@highagency/pencil-wasm/pencil.js +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/pencil.wasm +0 -0
- package/dist/out/mcp-server-darwin-arm64 +0 -0
- package/dist/out/mcp-server-darwin-x64 +0 -0
- package/dist/out/mcp-server-linux-arm64 +0 -0
- package/dist/out/mcp-server-linux-x64 +0 -0
- package/dist/out/mcp-server-windows-arm64.exe +0 -0
- package/dist/out/mcp-server-windows-x64.exe +0 -0
- package/dist/out/skills/pen-dev/SKILL.md +1 -0
- package/dist/out/skills/pen-dev/execute.md +10 -73
- package/dist/out/skills/pen-dev/generate.md +124 -0
- package/dist/out/skills/pen-dev/pen-schema.md +15 -2
- package/dist/webworkerAll-BPqqt3nL.mjs +2 -0
- package/package.json +5 -3
- package/dist/anthropic-messages-xcJLXjiT.mjs +0 -40
- package/dist/azure-openai-responses-CoA9_5_J.mjs +0 -2
- package/dist/browserAll-8jKh1NRi.mjs +0 -2
- package/dist/deferred-tools-CozAnCQL.mjs +0 -2
- package/dist/diagnostics-B0j2bfEp.mjs +0 -2
- package/dist/dist-BnoSGZKP.mjs +0 -10
- package/dist/dist-CMxAZjfo.mjs +0 -1581
- package/dist/dist-L3CkgNK3.mjs +0 -4
- package/dist/error-body-BBlqjbe7.mjs +0 -2
- package/dist/from-py2TfO8m.mjs +0 -15
- package/dist/github-copilot-headers-DCj7hJoC.mjs +0 -2
- package/dist/google-generative-ai-CFHCNDEQ.mjs +0 -2
- package/dist/google-shared-DolBdAGX.mjs +0 -318
- package/dist/google-vertex-tT_ymu8S.mjs +0 -2
- package/dist/hash-DNYCELl4.mjs +0 -2
- package/dist/headers-DlpC0ues.mjs +0 -2
- package/dist/json-parse-BzRcyI3e.mjs +0 -4
- package/dist/lib-EA7A-_Pc.mjs +0 -9
- package/dist/mistral-conversations-BryMfnnw.mjs +0 -5
- package/dist/models-BBd5zwn6.mjs +0 -2
- package/dist/multipart-parser-DX5ZDxQv.mjs +0 -3
- package/dist/openai-CbFQ5q5I.mjs +0 -18
- package/dist/openai-codex-responses-BIh-ZL5a.mjs +0 -8
- package/dist/openai-completions-DKf2R9kY.mjs +0 -6
- package/dist/openai-prompt-cache-tVHrB8oW.mjs +0 -2
- package/dist/openai-responses-DKbl253t.mjs +0 -2
- package/dist/openai-responses-shared-Brqyk2bc.mjs +0 -11
- package/dist/openrouter-images-C8mOFqx9.mjs +0 -2
- package/dist/photon_rs-o0nbTM4F.mjs +0 -2
- package/dist/pi-messages-CucvyzBS.mjs +0 -8
- package/dist/provider-env-CL5ShLlj.mjs +0 -2
- package/dist/provider-retry-GaV_ioT7.mjs +0 -2
- package/dist/sanitize-unicode-D-15laVS.mjs +0 -2
- package/dist/src-B_lvnEtX.mjs +0 -4
- package/dist/transform-messages-1ulTEFY1.mjs +0 -2
- package/dist/typescript-D0uAMumm.mjs +0 -6
- package/dist/uuid-CwuSNv96.mjs +0 -2
- package/dist/webworkerAll-BD-7VH16.mjs +0 -2
- /package/dist/{emscripten-module.browser-F76W5DM6-CNibWX-6.mjs → emscripten-module.browser-F76W5DM6-CQ3fNT5V.mjs} +0 -0
- /package/dist/{emscripten-module.browser-XIKQQPVU-BNfdGnMe.mjs → emscripten-module.browser-XIKQQPVU-C295tmz_.mjs} +0 -0
- /package/dist/{ffi-BuJ13coi.mjs → ffi-CUJpv82f.mjs} +0 -0
- /package/dist/{ffi-C5tLdQO9.mjs → ffi-Cplg1Nas.mjs} +0 -0
- /package/dist/{html-GGJ1fTRB.mjs → html-BzzLf-XM.mjs} +0 -0
- /package/dist/{init-B9LSomNH.mjs → init-B5EVeDge.mjs} +0 -0
- /package/dist/{module-ES6BEMUI-DwQ9nTMF.mjs → module-ES6BEMUI-2G5oIxui.mjs} +0 -0
- /package/dist/{module-asyncify-2EFITU5U-B54Mkt6K.mjs → module-asyncify-2EFITU5U-CqIYQibj.mjs} +0 -0
- /package/dist/{standalone-DYT2Zg6I.mjs → standalone-BxPYxoeE.mjs} +0 -0
|
@@ -37,7 +37,11 @@ function Update(path: string, updateData: Child): void;
|
|
|
37
37
|
function Replace(path: string, nodeData: Child): string; // returns the replacement node's id
|
|
38
38
|
function Move(path: string, parent: string | undefined, index?: number): void;
|
|
39
39
|
function Delete(path: string): void;
|
|
40
|
-
function Generate(
|
|
40
|
+
function Generate(type: "ai" | "svg", nodeId: string, prompt: string): void; // generate an image fill or an SVG drawing - see generate.md
|
|
41
|
+
function Generate(type: "stock", nodeId: string, query: string): void;
|
|
42
|
+
function Generate(type: "vectorize-image", nodeId: string, imageUrl: string): void;
|
|
43
|
+
function Generate(type: "remove-background", imageUrl: string): string; // returns the new asset url
|
|
44
|
+
function Generate(type: "replace-background", imageUrl: string, prompt: string): string;
|
|
41
45
|
function SetVariables(variables: Record<string, VariableDefinition>, replace?: boolean): void;
|
|
42
46
|
|
|
43
47
|
// Reading
|
|
@@ -228,79 +232,12 @@ Export([heroId, pricingId], "png", "./exports")
|
|
|
228
232
|
Export([pageId], "html-tailwind", "./landing.html")
|
|
229
233
|
```
|
|
230
234
|
|
|
231
|
-
### Generate
|
|
232
|
-
|
|
233
|
-
- IMPORTANT: There is NO `image` node type! Images are applied as FILLS to
|
|
234
|
-
existing nodes; SVGs are transformed into paths and added to a parent frame.
|
|
235
|
-
- For `"ai"` and `"svg"`, Generate is an async, non-blocking operation. It
|
|
236
|
-
returns nothing and finishes independently of the execute progress.
|
|
237
|
-
(`"stock"` is the exception: its fill is applied during the call itself.)
|
|
238
|
-
- The result lands in the document after the `execute` call that started it has
|
|
239
|
-
already returned. The target node stays empty or unfilled until then, and
|
|
240
|
-
screenshots taken right away will not show it. That is expected. Never
|
|
241
|
-
re-generate it, draw it by hand, or add children to a frame you generated an
|
|
242
|
-
SVG into.
|
|
243
|
-
- The frame an SVG is generated into keeps `placeholder: true` while the
|
|
244
|
-
drawing is in progress; the flag is cleared when the generation finishes.
|
|
245
|
-
Check on it with a cheap read in a later `execute` call - never with
|
|
246
|
-
screenshots: `Print(Get(logoFrameId, {depth: 0}).placeholder)`.
|
|
247
|
-
- Generations are slow: SVGs can take multiple minutes. While the placeholder
|
|
248
|
-
flag is still set, don't wait idly: continue with the rest of the design and
|
|
249
|
-
re-check only occasionally, e.g. after finishing another section - not after
|
|
250
|
-
every execute call.
|
|
251
|
-
- Only when no other work is left, poll with that tiny Get/Print call, leaving
|
|
252
|
-
a generous interval between checks (do other verification passes in
|
|
253
|
-
between). Never fire checks back-to-back.
|
|
254
|
-
- Screenshot the generated result only after the placeholder flag is cleared.
|
|
255
|
-
If the flag is cleared but the frame is still empty, the generation failed -
|
|
256
|
-
that is the one case where calling Generate again on the same node is
|
|
257
|
-
correct.
|
|
258
|
-
|
|
259
|
-
#### Generating an image (`type: "ai"` or `type: "stock"`)
|
|
260
|
-
|
|
261
|
-
- Never guess or invent URLs for image fills. Always use the Generate function
|
|
262
|
-
to get an image from a stock or AI service.
|
|
263
|
-
- To display an image: first Insert a frame or rectangle, then use Generate to
|
|
264
|
-
apply the image as a fill to that node.
|
|
265
|
-
- `nodeId`: The ID of the node to apply the image fill to.
|
|
266
|
-
- `type`: "ai" for AI-generated images, "stock" for stock photos from Unsplash.
|
|
267
|
-
- `prompt`:
|
|
268
|
-
- For "ai": a detailed descriptive prompt.
|
|
269
|
-
- For "stock": a 1-3 keyword search query following the Stock query rules
|
|
270
|
-
(simple, concrete, no use-case or abstract terms).
|
|
271
|
-
- `"stock"` fills are applied during the call; if no matching photo is found,
|
|
272
|
-
a warning is returned and the node is left without an image fill.
|
|
235
|
+
### Generate
|
|
273
236
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
#### Generating an SVG (`type: "svg"`)
|
|
281
|
-
|
|
282
|
-
- SVG generation is the only way to produce freeform vector artwork, and it is currently the slowest and most expensive operation in Pencil. Use it deliberately - it is not the default way to fill visual space.
|
|
283
|
-
- Generate an SVG only when the artwork itself is the point:
|
|
284
|
-
- the user asks you to draw, illustrate, or create a logo, mark, mascot, or illustration,
|
|
285
|
-
- the design is for a brand or product that needs its own logo mark and the document doesn't already contain one,
|
|
286
|
-
- a section is carried by a custom illustration or diagram that cannot be assembled from icons, shapes, or an image.
|
|
287
|
-
- Do NOT generate an SVG for these - each has a cheaper, better option:
|
|
288
|
-
- icons, arrows, chevrons, checkmarks, UI glyphs -> an `icon` node (`lucide`, `feather`, `Material Symbols`, `phosphor`)
|
|
289
|
-
- photos, textures, hero and background imagery, avatars, product shots -> an image fill via `Generate` with `type: "stock"` or `type: "ai"`
|
|
290
|
-
- badges, tags, pills, buttons, cards, dividers, blobs, glows, gradient backgrounds, abstract patterns, charts -> frames, shapes, strokes, gradient fills, and layout
|
|
291
|
-
- artwork that already exists in the document -> `Copy` it or instance it
|
|
292
|
-
- Budget: be mindful about the number of generated SVG per design. Turn it into a component and reuse it whenever needed. Never generate a variant per screen, section, or card.
|
|
293
|
-
- When you're unsure whether artwork is needed, build the design without it first. Adding one generated graphic afterwards is cheap; deleting several that weren't wanted is not.
|
|
294
|
-
- To display an SVG: first Insert a frame with the desired width and height (no other element type is allowed), then use Generate. The resulting path elements are scaled to fit the frame's bounding box and inserted as its children.
|
|
295
|
-
- `nodeId`: The ID of the frame to insert the SVG into.
|
|
296
|
-
- `type`: "svg".
|
|
297
|
-
- `prompt`: a detailed descriptive prompt. The generator sees nothing of the document, so state the subject, composition, line/fill style, and colors explicitly. One generation per prompt - don't ask for a set of variants.
|
|
298
|
-
|
|
299
|
-
```js
|
|
300
|
-
const pos = FindEmptySpace({width: 400, height: 400, padding: 80})
|
|
301
|
-
logoFrameId = Insert(document, {type: "frame", name: "Logo", x: pos.x, y: pos.y, width: 400, height: 400, placeholder: true})
|
|
302
|
-
Generate(logoFrameId, "svg", "A cute fox logo, minimalist vector style, colourful, simple, clean, modern flat design, suitable for a brand logo.")
|
|
303
|
-
```
|
|
237
|
+
- Brings imagery and vector artwork into the document: `"ai"` and `"stock"` for a new image, `"svg"` for new vector artwork, and `"remove-background"`, `"replace-background"`, and `"vectorize-image"` for an image the document ALREADY has.
|
|
238
|
+
- IMPORTANT: There is NO `image` node type. Images are applied as FILLS to existing nodes; SVGs become paths inside a parent frame.
|
|
239
|
+
- Every type is async: the result lands after the `execute` call that started it has returned, so a screenshot taken right away will not show it. Never re-generate it, draw the result by hand, or add children to a frame you generated into.
|
|
240
|
+
- Read [generate.md](./generate.md) before calling it.
|
|
304
241
|
|
|
305
242
|
### FindEmptySpace
|
|
306
243
|
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Generate: images and vector artwork
|
|
2
|
+
|
|
3
|
+
`Generate` is an `execute` function - see [execute.md](./execute.md) for the rest of the API.
|
|
4
|
+
Read this file before calling it.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
function Generate(type: "ai" | "svg", nodeId: string, prompt: string): void;
|
|
8
|
+
function Generate(type: "stock", nodeId: string, query: string): void;
|
|
9
|
+
function Generate(type: "vectorize-image", nodeId: string, imageUrl: string): void;
|
|
10
|
+
function Generate(type: "remove-background", imageUrl: string): string; // returns the new asset url
|
|
11
|
+
function Generate(type: "replace-background", imageUrl: string, prompt: string): string; // returns the new asset url
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
- `"ai"` and `"stock"` bring in a new image, `"svg"` draws new vector artwork, and `"remove-background"`, `"replace-background"`, and `"vectorize-image"` transform an image the document ALREADY has.
|
|
15
|
+
- IMPORTANT: There is NO `image` node type. Images are applied as FILLS to existing nodes; SVGs become paths inside a parent frame.
|
|
16
|
+
- `type` comes first. The four types that write into the document take the target `nodeId` next - the node receiving the image fill, or the frame the artwork is drawn into. `"remove-background"` and `"replace-background"` target no node: they RETURN an asset url for you to apply, so the source url follows the type directly. Last comes the input: a prompt for `"ai"` and `"svg"`, a query for `"stock"`, `imageUrl` for the transforms, plus a prompt after it for `"replace-background"`. Leave unused arguments out - never pass `undefined`.
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
Generate("ai", nodeId, "A dew-covered fern frond, macro, soft morning light")
|
|
20
|
+
Generate("stock", nodeId, "fern frond")
|
|
21
|
+
Generate("vectorize-image", frameId, url)
|
|
22
|
+
Generate("remove-background", url)
|
|
23
|
+
Generate("replace-background", url, "On a wet slate slab, muted sage background")
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Waiting for a result
|
|
27
|
+
|
|
28
|
+
- EVERY type is async. Only the bookkeeping happens during the call - the fill is written, or the url returned; the image or drawing itself lands after the `execute` call that started it has returned. Screenshots taken right away will not show it. Never re-generate it, draw the result by hand, or add children to a frame you generated into.
|
|
29
|
+
- Check with a cheap read in a LATER `execute` call, never with a screenshot:
|
|
30
|
+
- frame types (`"svg"`, `"vectorize-image"`): Insert the frame with `placeholder: true`; the generator clears that flag when it finishes. `Print(Get(logoFrameId, {depth: 0}).placeholder)`
|
|
31
|
+
- fill types (`"ai"`, `"stock"`, and both background transforms): the url is a `pencil:pending-image-...` placeholder until the image arrives, then rewritten in place to the real asset path. `Print(Get(heroId, {depth: 0}).fill)`
|
|
32
|
+
- Generations are slow - SVGs take minutes. Keep designing while one is pending and re-check occasionally, e.g. after finishing a section, not after every call. Never call Generate again for pending work. Only when no other work is left, poll with that tiny read, generously spaced - never back to back.
|
|
33
|
+
- Failures are silent: a `placeholder` flag cleared on a frame that still has no children, or a fill whose `url` has disappeared. That is the one case where calling Generate again for the same result is correct.
|
|
34
|
+
- Screenshot only once a check says the result arrived.
|
|
35
|
+
|
|
36
|
+
## `"ai"` and `"stock"`: a new image
|
|
37
|
+
|
|
38
|
+
- Never guess or invent an image url - it only ever comes from `Generate`.
|
|
39
|
+
- Insert the frame or rectangle first, then `Generate` applies the image as its fill.
|
|
40
|
+
- `"ai"` takes a detailed descriptive prompt. `"stock"` takes a 1-3 keyword Unsplash query following the Stock query rules: simple, concrete, no use-case or abstract terms.
|
|
41
|
+
- Both write the fill during the call and resolve the image afterwards. If no stock photo matches the query, the fill's `url` ends up gone and the node shows nothing - nothing is reported back to you, so check the fill.
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
const pos = FindEmptySpace({width: 1440, height: 800, padding: 80, nodeId: logoFrameId})
|
|
45
|
+
heroId = Insert(document, {type: "frame", name: "Section", x: pos.x, y: pos.y, width: 1440, height: 800, placeholder: true})
|
|
46
|
+
Generate("ai", heroId, "Tropical jungle canopy, dense green foliage, sunlight filtering through trees, cinematic aerial view, vibrant greens, moody atmospheric lighting, nature photography")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## `"svg"`: new vector artwork
|
|
50
|
+
|
|
51
|
+
- The only way to produce freeform vector artwork, and the slowest and most expensive operation in Pencil. It is not the default way to fill visual space.
|
|
52
|
+
- Generate one only when the artwork itself is the point:
|
|
53
|
+
- the user asks you to draw, illustrate, or create a logo, mark, mascot, or illustration,
|
|
54
|
+
- the design is for a brand or product that needs its own logo mark and the document doesn't already contain one,
|
|
55
|
+
- a section is carried by a custom illustration or diagram that cannot be assembled from icons, shapes, or an image.
|
|
56
|
+
- Everything else has a cheaper, better option:
|
|
57
|
+
- icons, arrows, chevrons, checkmarks, UI glyphs -> an `icon` node (`lucide`, `feather`, `Material Symbols`, `phosphor`)
|
|
58
|
+
- photos, textures, hero and background imagery, avatars, product shots -> `"stock"` or `"ai"`
|
|
59
|
+
- badges, tags, pills, buttons, cards, dividers, blobs, glows, gradient backgrounds, abstract patterns, charts -> frames, shapes, strokes, gradient fills, and layout
|
|
60
|
+
- artwork already in the document -> `Copy` it or instance it
|
|
61
|
+
- Budget it: turn a generated SVG into a component and reuse it. Never generate a variant per screen, section, or card. When unsure, build the design without artwork first - adding one afterwards is cheap, deleting several is not.
|
|
62
|
+
- Insert a frame with the desired width and height and `placeholder: true` first (no other node type is allowed) and pass its id as `nodeId`; the resulting paths are scaled to the frame's bounding box and inserted as its children.
|
|
63
|
+
- The generator sees nothing of the document, so the prompt must state the subject, composition, line/fill style, and colors. One generation per prompt - don't ask for a set of variants.
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
const pos = FindEmptySpace({width: 400, height: 400, padding: 80})
|
|
67
|
+
logoFrameId = Insert(document, {type: "frame", name: "Logo", x: pos.x, y: pos.y, width: 400, height: 400, placeholder: true})
|
|
68
|
+
Generate("svg", logoFrameId, "A cute fox logo, minimalist vector style, colourful, simple, clean, modern flat design, suitable for a brand logo.")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Transforming an image the document already has
|
|
72
|
+
|
|
73
|
+
- `"vectorize-image"` draws into a frame you insert first, so that frame's `nodeId` follows the type, and it returns nothing. `"remove-background"` and `"replace-background"` write nothing and target no node: they produce a new asset and RETURN its url - nothing in the document moves until you apply it.
|
|
74
|
+
- `imageUrl` is the last argument of all three and must ALREADY be in the document: `Get` the node, pick the `{type: "image"}` fill you actually mean, and pass its `url`. A node's `fill` may be a list drawn in list order, so the visible image is usually the last image fill. Never invent, guess, or hand-write this url.
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
const imageUrl = n => [Get(n, {depth: 0}).fill].flat().filter(f => f?.type === "image").pop()?.url
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- The source must have ARRIVED: a url still starting with `pencil:pending-image-` fails, so a generated image or an earlier transform's output has to resolve in a previous `execute` call before you can transform it.
|
|
81
|
+
- Apply a returned url with `Update` on the node's `fill` (it holds one fill or a list), in the SAME execute call - no `TakeScreenshot`, `Export`, or further `Generate` in between. Those hand control back to the editor, and once the transform resolves the url you are still holding stops referring to anything. Never carry it into a later call through a global.
|
|
82
|
+
|
|
83
|
+
```js
|
|
84
|
+
Update(nodeId, {fill: {type: "image", url: Generate("remove-background", sourceUrl)}})
|
|
85
|
+
|
|
86
|
+
const cutoutUrl = Generate("remove-background", sourceUrl)
|
|
87
|
+
Update(cardId, {fill: [{type: "image", url: cutoutUrl}, ...]})
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- The returned url is a pending placeholder like any other generated image, rewritten in place once the transform resolves. Until then the node renders the SOURCE image, so an early screenshot looks like the transform did nothing - check the url instead.
|
|
91
|
+
- Nothing else on the node is touched: the fill you passed as `imageUrl` changes only if you `Update` it with the returned url, and other fills stay as they are.
|
|
92
|
+
- The source must be a JPEG, PNG or WEBP, at most 16MB, and between 256px and 4096px in both dimensions - the image's own pixels, not the size of the node showing it.
|
|
93
|
+
|
|
94
|
+
### `"remove-background"`
|
|
95
|
+
|
|
96
|
+
- Returns a transparent cutout of the subject.
|
|
97
|
+
- Use it when a photo's own background is in the way: a product shot, mascot, portrait, or object that has to sit on a design background, overlap another section, or bleed outside its frame.
|
|
98
|
+
- Whatever is behind the node shows through the cutout, so give it a transparent or design-colored backdrop rather than leaving an unrelated solid fill behind it.
|
|
99
|
+
|
|
100
|
+
### `"replace-background"`
|
|
101
|
+
|
|
102
|
+
- Keeps the subject and generates a new background around it, returning the composed image. The one transform type that takes a prompt.
|
|
103
|
+
- Use it when the subject is right but its surroundings are not: a product in a styled scene, a portrait on a different backdrop, or stock photos across a design made to share one setting.
|
|
104
|
+
- The prompt describes the background, not the subject: state the setting, surface, lighting, and colors, consistent with the design's palette.
|
|
105
|
+
- Reach for `"remove-background"` instead when the design itself should show through behind the subject. The result here is a normal opaque image and needs no backdrop of its own.
|
|
106
|
+
|
|
107
|
+
### `"vectorize-image"`
|
|
108
|
+
|
|
109
|
+
- Traces the image into vector paths. Insert a frame with the desired width and height and `placeholder: true` FIRST (no other node type is allowed) and pass its id as `nodeId`; the traced paths are scaled to its bounding box and inserted as its children, exactly like `"svg"`.
|
|
110
|
+
- Use it to turn an existing raster logo, mark, or flat illustration into clean, resolution-independent artwork. For artwork that does not exist yet, generate an SVG directly - never generate an image just to vectorize it.
|
|
111
|
+
- Works on flat, high-contrast artwork; photographs trace into a mess of paths.
|
|
112
|
+
|
|
113
|
+
```js
|
|
114
|
+
Update(productShotId,{fill:{type:"image",url:Generate("remove-background",imageUrl(productShotId))}})
|
|
115
|
+
|
|
116
|
+
const pos = FindEmptySpace({width: 400, height: 400, padding: 80, nodeId: logoId})
|
|
117
|
+
tracedLogoId = Insert(document,{type:"frame",name:"Logo",x:pos.x,y:pos.y,width:400,height:400,placeholder:true})
|
|
118
|
+
Generate("vectorize-image",tracedLogoId,imageUrl(logoId))
|
|
119
|
+
|
|
120
|
+
const bottleUrl = Generate("replace-background",imageUrl(bottleId),"On a wet slate slab, soft morning light from the left, muted sage background, shallow depth of field")
|
|
121
|
+
for (const id of [bottleHeroId, bottleThumbId]) {
|
|
122
|
+
Update(id,{fill:{type:"image",url:bottleUrl}})
|
|
123
|
+
}
|
|
124
|
+
```
|
|
@@ -185,6 +185,19 @@ export interface Script extends Entity, Size {
|
|
|
185
185
|
/** Input values by name. */
|
|
186
186
|
inputs?: { [key: string]: string | number | boolean | Variable };
|
|
187
187
|
}
|
|
188
|
+
/** Live web page shown on the canvas. */
|
|
189
|
+
export interface Browser extends Entity, Size, CanHaveEffects, CanHaveStroke {
|
|
190
|
+
type: "browser";
|
|
191
|
+
/** Page URL. Empty shows a URL prompt. */
|
|
192
|
+
url?: string;
|
|
193
|
+
/** Device emulation preset id. Omit for responsive. */
|
|
194
|
+
deviceId?: string;
|
|
195
|
+
/** Page zoom factor. Default 1. */
|
|
196
|
+
zoom?: number;
|
|
197
|
+
scrollX?: number;
|
|
198
|
+
scrollY?: number;
|
|
199
|
+
cornerRadius?: NumberOrVariable | [NumberOrVariable, NumberOrVariable, NumberOrVariable, NumberOrVariable];
|
|
200
|
+
}
|
|
188
201
|
/** Reuses another object. */
|
|
189
202
|
export interface Ref extends Entity {
|
|
190
203
|
type: "ref";
|
|
@@ -196,7 +209,7 @@ export interface Ref extends Entity {
|
|
|
196
209
|
- `type` is present = replacement: the descendant node is fully replaced with a new node tree. */ };
|
|
197
210
|
[key: string]: any;
|
|
198
211
|
}
|
|
199
|
-
export type Child = Frame | Group | Rectangle | Ellipse | Path | Polygon | Text | Note | Prompt | Context | Icon | Script | Ref;
|
|
212
|
+
export type Child = Frame | Group | Rectangle | Ellipse | Path | Polygon | Text | Note | Prompt | Context | Icon | Script | Browser | Ref;
|
|
200
213
|
export type IdPath = string;
|
|
201
|
-
export interface Document { version: "2.
|
|
214
|
+
export interface Document { version: "2.18"; themes?: { [key: string /** RegEx: [^:]+ */]: string[] }; imports?: { [key: string]: string /** Value: relative URI of imported .pen file. Key: short alias. */ }; variables?: { [key: string /** RegEx: [^:]+ */]: { type: "boolean"; value: BooleanOrVariable | { value: BooleanOrVariable; theme?: Theme }[] } | { type: "color"; value: ColorOrVariable | { value: ColorOrVariable; theme?: Theme }[] } | { type: "number"; value: NumberOrVariable | { value: NumberOrVariable; theme?: Theme }[] } | { type: "string"; value: StringOrVariable | { value: StringOrVariable; theme?: Theme }[] } }; children: (Frame | Group | Rectangle | Ellipse | Polygon | Path | Text | Note | Context | Prompt | Icon | Script | Browser | Ref)[]; }
|
|
202
215
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pen.dev/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.8",
|
|
4
4
|
"description": "CLI tool for running the pen.dev AI agent manipulating .pen design files",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -36,9 +36,10 @@
|
|
|
36
36
|
"license": "UNLICENSED",
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@anthropic-ai/claude-agent-sdk": "^0.3.257",
|
|
39
|
+
"@earendil-works/pi-coding-agent": "^0.85.1",
|
|
39
40
|
"@inquirer/prompts": "^8.3.0",
|
|
40
41
|
"@node-ipc/node-ipc": "^11.0.3",
|
|
41
|
-
"@openai/codex-sdk": "^0.
|
|
42
|
+
"@openai/codex-sdk": "^0.153.4",
|
|
42
43
|
"eventemitter3": "^5.0.1",
|
|
43
44
|
"semver": "^7.7.4",
|
|
44
45
|
"sharp": "^0.34.5",
|
|
@@ -47,6 +48,7 @@
|
|
|
47
48
|
"devDependencies": {
|
|
48
49
|
"@biomejs/biome": "^2.4.5",
|
|
49
50
|
"@ha/agent": "file:../../lib/agent",
|
|
51
|
+
"@ha/device-auth": "file:../../lib/device-auth",
|
|
50
52
|
"@ha/ipc": "file:../../lib/ipc",
|
|
51
53
|
"@ha/mcp": "file:../../lib/mcp",
|
|
52
54
|
"@ha/pencil-editor": "file:../../lib/pencil-editor",
|
|
@@ -61,7 +63,7 @@
|
|
|
61
63
|
"typescript": "^5.0.0"
|
|
62
64
|
},
|
|
63
65
|
"engines": {
|
|
64
|
-
"node": ">=22.
|
|
66
|
+
"node": ">=22.19.0"
|
|
65
67
|
},
|
|
66
68
|
"files": [
|
|
67
69
|
"dist",
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{t}from"./models-BBd5zwn6.mjs";import{n,t as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./provider-env-CL5ShLlj.mjs";import{t as a}from"./deferred-tools-CozAnCQL.mjs";import{t as o}from"./headers-DlpC0ues.mjs";import{f as s,i as c,n as l,p as u,r as d,t as f,u as p}from"./transform-messages-1ulTEFY1.mjs";import{t as m}from"./provider-retry-GaV_ioT7.mjs";import{t as h}from"./sanitize-unicode-D-15laVS.mjs";import{n as ee,t as te}from"./github-copilot-headers-DCj7hJoC.mjs";function g(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function _(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let ne=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ne=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function re(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const ie=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var v=class extends Error{},y=class e extends v{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new ae({message:r,cause:ie(n)});let a=n,o=a?.error?.type;return t===400?new se(t,a,r,i,o):t===401?new ce(t,a,r,i,o):t===403?new le(t,a,r,i,o):t===404?new ue(t,a,r,i,o):t===409?new de(t,a,r,i,o):t===422?new fe(t,a,r,i,o):t===429?new pe(t,a,r,i,o):t>=500?new me(t,a,r,i,o):new e(t,a,r,i,o)}},b=class extends y{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ae=class extends y{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},oe=class extends ae{constructor({message:e}={}){super({message:e??`Request timed out.`})}},se=class extends y{},ce=class extends y{},le=class extends y{},ue=class extends y{},de=class extends y{},fe=class extends y{},pe=class extends y{},me=class extends y{};const he=/^[a-z][a-z0-9+.-]*:/i,ge=e=>he.test(e);let _e=e=>(_e=Array.isArray,_e(e)),ve=_e;function ye(e){return typeof e==`object`?e??{}:{}}function be(e){if(!e)return!0;for(let t in e)return!1;return!0}function xe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const Se=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new v(`${e} must be an integer`);if(t<0)throw new v(`${e} must be a positive integer`);return t},Ce=e=>{try{return JSON.parse(e)}catch{return}},we=e=>new Promise(t=>setTimeout(t,e)),x=`0.91.1`,Te=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Ee(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const De=()=>{let e=Ee();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":x,"X-Stainless-OS":Ae(Deno.build.os),"X-Stainless-Arch":ke(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":x,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":x,"X-Stainless-OS":Ae(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ke(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Oe();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":x,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":x,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Oe(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const ke=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Ae=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let je;const Me=()=>je??=De();function Ne(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Pe(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Fe(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Pe({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ie(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Le(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Re=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function ze(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new v(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}function Be(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let Ve;function He(e){let t;return(Ve??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Ue;function We(e){let t;return(Ue??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var S,C,Ge=class{constructor(){S.set(this,void 0),C.set(this,void 0),g(this,S,new Uint8Array,`f`),g(this,C,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?He(e):e;g(this,S,Be([_(this,S,`f`),t]),`f`);let n=[],r;for(;(r=Ke(_(this,S,`f`),_(this,C,`f`)))!=null;){if(r.carriage&&_(this,C,`f`)==null){g(this,C,r.index,`f`);continue}if(_(this,C,`f`)!=null&&(r.index!==_(this,C,`f`)+1||r.carriage)){n.push(We(_(this,S,`f`).subarray(0,_(this,C,`f`)-1))),g(this,S,_(this,S,`f`).subarray(_(this,C,`f`)),`f`),g(this,C,null,`f`);continue}let e=_(this,C,`f`)===null?r.preceding:r.preceding-1,t=We(_(this,S,`f`).subarray(0,e));n.push(t),g(this,S,_(this,S,`f`).subarray(r.index),`f`),g(this,C,null,`f`)}return n}flush(){return _(this,S,`f`).length?this.decode(`
|
|
3
|
-
`):[]}};S=new WeakMap,C=new WeakMap,Ge.NEWLINE_CHARS=new Set([`
|
|
4
|
-
`,`\r`]),Ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ke(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function qe(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const Je={off:0,error:200,warn:300,info:400,debug:500},Ye=(e,t,n)=>{if(e){if(xe(Je,e))return e;w(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Je))}`)}};function Xe(){}function Ze(e,t,n){return!t||Je[e]>Je[n]?Xe:t[e].bind(t)}const Qe={error:Xe,warn:Xe,info:Xe,debug:Xe};let $e=new WeakMap;function w(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Qe;let r=$e.get(t);if(r&&r[0]===n)return r[1];let i={error:Ze(`error`,t,n),warn:Ze(`warn`,t,n),info:Ze(`info`,t,n),debug:Ze(`debug`,t,n)};return $e.set(t,[n,i]),i}const T=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var et,tt=class e{constructor(e,t,n){this.iterator=e,et.set(this,void 0),this.controller=t,g(this,et,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?w(r):console;async function*o(){if(i)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of nt(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=Ce(e.data)??e.data,r=n?.error?.type;throw new y(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(re(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Ge,n=Ie(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(re(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(et=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,_(this,et,`f`)),new e(()=>i(n),this.controller,_(this,et,`f`))]}toReadableStream(){let e=this,t;return Pe({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=He(JSON.stringify(n)+`
|
|
5
|
-
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*nt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new v(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new v(`Attempted to iterate over a response with no body`);let n=new it,r=new Ge,i=Ie(e.body);for await(let e of rt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*rt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?He(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=qe(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var it=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
6
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=at(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function at(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function ot(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return w(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):tt.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:st(await n.json(),n):await n.text()})();return w(e).debug(`[${r}] response parsed`,T({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function st(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`request-id`),enumerable:!1})}var ct,lt=class e extends Promise{constructor(e,t,n=ot){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,ct.set(this,void 0),g(this,ct,e,`f`)}_thenUnwrap(t){return new e(_(this,ct,`f`),this.responsePromise,async(e,n)=>st(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(_(this,ct,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ct=new WeakMap;var ut,dt=class{constructor(e,t,n,r){ut.set(this,void 0),g(this,ut,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,ut,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ut=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ft=class extends lt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await ot(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},pt=class extends dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...ye(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...ye(this.options.query),after_id:e}}:null}},E=class extends dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...ye(this.options.query),page:e}}:null}};const mt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function D(e,t,n){return mt(),new File(e,t??`unknown_file`,n)}function ht(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}const gt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,_t=async(e,t,n=!0)=>({...e,body:await bt(e.body,t,n)}),vt=new WeakMap;function yt(e){let t=typeof e==`function`?e:e.fetch,n=vt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return vt.set(t,r),r}const bt=async(e,t,n=!0)=>{if(!await yt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>St(r,e,t,n))),r},xt=e=>e instanceof Blob&&`name`in e,St=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,D([await n.blob()],ht(n,r),i))}else if(gt(n))e.append(t,D([await new Response(Fe(n)).blob()],ht(n,r)));else if(xt(n))e.append(t,D([n],ht(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>St(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>St(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Ct=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,wt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Ct(e),Tt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Et(e,t,n){if(mt(),e=await e,t||=ht(e,!0),wt(e))return e instanceof File&&t==null&&n==null?e:D([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(Tt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),D(await Dt(r),t,n)}let r=await Dt(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return D(r,t,n)}async function Dt(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ct(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(gt(e))for await(let n of e)t.push(...await Dt(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Ot(e)}`)}return t}function Ot(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var O=class{constructor(e){this._client=e}};const kt=Symbol.for(`brand.privateNullableHeaders`);function*At(e){if(!e)return;if(kt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ve(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ve(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const k=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of At(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[kt]:!0,values:t,nulls:n}};function jt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Mt=Object.freeze(Object.create(null)),A=((e=jt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Mt)??Mt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new v(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
7
|
-
`)}\n${a}\n${t}`)}return a})(jt);var Nt=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/environments/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/environments/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};const Pt=Symbol(`anthropic.sdk.stainlessHelper`);function Ft(e){return typeof e==`object`&&!!e&&Pt in e}function It(e,t){let n=new Set;if(e)for(let t of e)Ft(t)&&n.add(t[Pt]);if(t){for(let e of t)if(Ft(e)&&n.add(e[Pt]),Array.isArray(e.content))for(let t of e.content)Ft(t)&&n.add(t[Pt])}return Array.from(n)}function Lt(e,t){let n=It(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function Rt(e){return Ft(e)?{"x-stainless-helper":e[Pt]}:{}}var zt=class extends O{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,pt,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}/content?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,_t({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},Rt(r.file),t?.headers])},this._client))}},Bt=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}?beta=true`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,pt,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},Vt=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/user_profiles/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},Ht=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/agents/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Ut=class extends O{constructor(){super(...arguments),this.versions=new Ht(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(A`/v1/agents/${e}?beta=true`,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/agents/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/agents/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Ut.Versions=Ht;var Wt=class extends O{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post(A`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memories?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Gt=class extends O{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memory_versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post(A`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Kt=class extends O{constructor(){super(...arguments),this.memories=new Wt(this._client),this.memoryVersions=new Gt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Kt.Memories=Wt,Kt.MemoryVersions=Gt;const qt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Jt(e){return e?.output_format??e?.output_config?.format}function Yt(e,t,n){let r=Jt(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1});return Object.defineProperty(t,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:Xt(e,t,n)}function Xt(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=Zt(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},`parsed_output`,{value:i,enumerable:!1});return Object.defineProperty(a,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Zt(e,t){let n=Jt(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new v(`Failed to parse structured output: ${e}`)}}const Qt=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},$t=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),$t(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),$t(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),$t(e);break;case`delimiter`:return e=e.slice(0,e.length-1),$t(e)}return e},en=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},tn=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},nn=e=>JSON.parse(tn(en($t(Qt(e)))));var j,M,N,rn,an,on,P,sn,F,I,cn,ln,un,L,dn,fn,pn,mn,hn,gn,_n,vn,yn,bn;const xn=`__json_buf`;function Sn(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var Cn=class e{constructor(e,t){j.add(this),this.messages=[],this.receivedMessages=[],M.set(this,void 0),N.set(this,null),this.controller=new AbortController,rn.set(this,void 0),an.set(this,()=>{}),on.set(this,()=>{}),P.set(this,void 0),sn.set(this,()=>{}),F.set(this,()=>{}),I.set(this,{}),cn.set(this,!1),ln.set(this,!1),un.set(this,!1),L.set(this,!1),dn.set(this,void 0),fn.set(this,void 0),pn.set(this,void 0),gn.set(this,e=>{if(g(this,ln,!0,`f`),re(e)&&(e=new b),e instanceof b)return g(this,un,!0,`f`),this._emit(`abort`,e);if(e instanceof v)return this._emit(`error`,e);if(e instanceof Error){let t=new v(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new v(String(e)))}),g(this,rn,new Promise((e,t)=>{g(this,an,e,`f`),g(this,on,t,`f`)}),`f`),g(this,P,new Promise((e,t)=>{g(this,sn,e,`f`),g(this,F,t,`f`)}),`f`),_(this,rn,`f`).catch(()=>{}),_(this,P,`f`).catch(()=>{}),g(this,N,e,`f`),g(this,pn,t?.logger??console,`f`)}get response(){return _(this,dn,`f`)}get request_id(){return _(this,fn,`f`)}async withResponse(){g(this,L,!0,`f`);let e=await _(this,rn,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return g(a,N,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},_(this,gn,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{_(this,j,`m`,_n).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)_(this,j,`m`,vn).call(this,e);if(i.controller.signal?.aborted)throw new b;_(this,j,`m`,yn).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(g(this,dn,e,`f`),g(this,fn,e?.headers.get(`request-id`),`f`),_(this,an,`f`).call(this,e),this._emit(`connect`))}get ended(){return _(this,cn,`f`)}get errored(){return _(this,ln,`f`)}get aborted(){return _(this,un,`f`)}abort(){this.controller.abort()}on(e,t){return(_(this,I,`f`)[e]||(_(this,I,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=_(this,I,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(_(this,I,`f`)[e]||(_(this,I,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{g(this,L,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){g(this,L,!0,`f`),await _(this,P,`f`)}get currentMessage(){return _(this,M,`f`)}async finalMessage(){return await this.done(),_(this,j,`m`,mn).call(this)}async finalText(){return await this.done(),_(this,j,`m`,hn).call(this)}_emit(e,...t){if(_(this,cn,`f`))return;e===`end`&&(g(this,cn,!0,`f`),_(this,sn,`f`).call(this));let n=_(this,I,`f`)[e];if(n&&(_(this,I,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!_(this,L,`f`)&&!n?.length&&Promise.reject(e),_(this,on,`f`).call(this,e),_(this,F,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!_(this,L,`f`)&&!n?.length&&Promise.reject(e),_(this,on,`f`).call(this,e),_(this,F,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,_(this,j,`m`,mn).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{_(this,j,`m`,_n).call(this),this._connected(null);let t=tt.fromReadableStream(e,this.controller);for await(let e of t)_(this,j,`m`,vn).call(this,e);if(t.controller.signal?.aborted)throw new b;_(this,j,`m`,yn).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(M=new WeakMap,N=new WeakMap,rn=new WeakMap,an=new WeakMap,on=new WeakMap,P=new WeakMap,sn=new WeakMap,F=new WeakMap,I=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,L=new WeakMap,dn=new WeakMap,fn=new WeakMap,pn=new WeakMap,gn=new WeakMap,j=new WeakSet,mn=function(){if(this.receivedMessages.length===0)throw new v(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},hn=function(){if(this.receivedMessages.length===0)throw new v(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new v(`stream ended without producing a content block with type=text`);return e.join(` `)},_n=function(){this.ended||g(this,M,void 0,`f`)},vn=function(e){if(this.ended)return;let t=_(this,j,`m`,bn).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:Sn(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Yt(t,_(this,N,`f`),{logger:_(this,pn,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:g(this,M,t,`f`);break;case`content_block_start`:case`message_delta`:break}},yn=function(){if(this.ended)throw new v(`stream has ended, this shouldn't happen`);let e=_(this,M,`f`);if(!e)throw new v(`request ended without sending any chunks`);return g(this,M,void 0,`f`),Yt(e,_(this,N,`f`),{logger:_(this,pn,`f`)})},bn=function(e){let t=_(this,M,`f`);if(e.type===`message_start`){if(t)throw new v(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new v(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&Sn(n)){let r=n[xn]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,xn,{value:r,enumerable:!1,writable:!0}),r)try{i.input=nn(r)}catch(e){let t=new v(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);_(this,gn,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},wn=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},Tn,R,z,B,V,H,U,W,En,Dn,On;function kn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var An=class{constructor(e,t,n){Tn.add(this),this.client=e,R.set(this,!1),z.set(this,!1),B.set(this,void 0),V.set(this,void 0),H.set(this,void 0),U.set(this,void 0),W.set(this,void 0),En.set(this,0),g(this,B,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...It(t.tools,t.messages)].join(`, `);g(this,V,{...n,headers:k([{"x-stainless-helper":r},n?.headers])},`f`),g(this,W,kn(),`f`),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(R=new WeakMap,z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,En=new WeakMap,Tn=new WeakSet,Dn=async function(){let e=_(this,B,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(_(this,H,`f`)!==void 0)try{let e=await _(this,H,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??_(this,B,`f`).params.model,i=e.summaryPrompt??`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
8
|
-
1. Task Overview
|
|
9
|
-
The user's core request and success criteria
|
|
10
|
-
Any clarifications or constraints they specified
|
|
11
|
-
2. Current State
|
|
12
|
-
What has been completed so far
|
|
13
|
-
Files created, modified, or analyzed (with paths if relevant)
|
|
14
|
-
Key outputs or artifacts produced
|
|
15
|
-
3. Important Discoveries
|
|
16
|
-
Technical constraints or requirements uncovered
|
|
17
|
-
Decisions made and their rationale
|
|
18
|
-
Errors encountered and how they were resolved
|
|
19
|
-
What approaches were tried that didn't work (and why)
|
|
20
|
-
4. Next Steps
|
|
21
|
-
Specific actions needed to complete the task
|
|
22
|
-
Any blockers or open questions to resolve
|
|
23
|
-
Priority order if multiple steps remain
|
|
24
|
-
5. Context to Preserve
|
|
25
|
-
User preferences or style requirements
|
|
26
|
-
Domain-specific details that aren't obvious
|
|
27
|
-
Any promises made to the user
|
|
28
|
-
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
29
|
-
Wrap your summary in <summary></summary> tags.`,a=_(this,B,`f`).params.messages;if(a[a.length-1].role===`assistant`){let e=a[a.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?a.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...a,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:_(this,B,`f`).params.max_tokens},{signal:_(this,V,`f`).signal,headers:k([_(this,V,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new v(`Expected text response for compaction`);return _(this,B,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(_(this,R,`f`))throw new v(`Cannot iterate over a consumed stream`);g(this,R,!0,`f`),g(this,z,!0,`f`),g(this,U,void 0,`f`);try{for(;;){let t;try{if(_(this,B,`f`).params.max_iterations&&_(this,En,`f`)>=_(this,B,`f`).params.max_iterations)break;g(this,z,!1,`f`),g(this,U,void 0,`f`),g(this,En,(e=_(this,En,`f`),e++,e),`f`),g(this,H,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=_(this,B,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},_(this,V,`f`)),g(this,H,t.finalMessage(),`f`),_(this,H,`f`).catch(()=>{}),yield t):(g(this,H,this.client.beta.messages.create({...i,stream:!1},_(this,V,`f`)),`f`),yield _(this,H,`f`)),!await _(this,Tn,`m`,Dn).call(this)){if(!_(this,z,`f`)){let{role:e,content:t}=await _(this,H,`f`);_(this,B,`f`).params.messages.push({role:e,content:t})}let e=await _(this,Tn,`m`,On).call(this,_(this,B,`f`).params.messages.at(-1));if(e)_(this,B,`f`).params.messages.push(e);else if(!_(this,z,`f`))break}}finally{t&&t.abort()}}if(!_(this,H,`f`))throw new v(`ToolRunner concluded without a message from the server`);_(this,W,`f`).resolve(await _(this,H,`f`))}catch(e){throw g(this,R,!1,`f`),_(this,W,`f`).promise.catch(()=>{}),_(this,W,`f`).reject(e),g(this,W,kn(),`f`),e}}setMessagesParams(e){typeof e==`function`?_(this,B,`f`).params=e(_(this,B,`f`).params):_(this,B,`f`).params=e,g(this,z,!0,`f`),g(this,U,void 0,`f`)}setRequestOptions(e){typeof e==`function`?g(this,V,e(_(this,V,`f`)),`f`):g(this,V,{..._(this,V,`f`),...e},`f`)}async generateToolResponse(e=_(this,V,`f`).signal){let t=await _(this,H,`f`)??this.params.messages.at(-1);return t?_(this,Tn,`m`,On).call(this,t,e):null}done(){return _(this,W,`f`).promise}async runUntilDone(){if(!_(this,R,`f`))for await(let e of this);return this.done()}get params(){return _(this,B,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};On=async function(e,t=_(this,V,`f`).signal){return _(this,U,`f`)===void 0&&g(this,U,jn(_(this,B,`f`).params,e,{..._(this,V,`f`),signal:t}),`f`),_(this,U,`f`)};async function jn(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);return r.length===0?null:{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r))return{type:`tool_result`,tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof wn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var Mn=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new Ge;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new v(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new v(`Attempted to iterate over a response with no body`);return new e(Ie(t.body),n)}},Nn=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,pt,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new v(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:k([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Mn.fromResponse(t.response,t.controller))}};const Pn={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`},Fn=[`claude-mythos-preview`,`claude-opus-4-6`];var In=class extends O{constructor(){super(...arguments),this.batches=new Nn(this._client)}create(e,t){let n=Ln(e),{betas:r,...i}=n;i.model in Pn&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Pn[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Fn.includes(i.model)&&i.thinking&&i.thinking.type===`enabled`&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!i.stream&&a==null){let e=qt[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=Lt(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:k([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Xt(t,e,{logger:this._client.logger??console}))}stream(e,t){return Cn.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=Ln(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new An(this._client,e,t)}};function Ln(e){if(!e.output_format)return e;if(e.output_config?.format)throw new v(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}In.Batches=Nn,In.BetaToolRunner=An,In.ToolError=wn;var Rn=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/events?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},zn=class extends O{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post(A`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/resources?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Bn=class extends O{constructor(){super(...arguments),this.events=new Rn(this._client),this.resources=new zn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/sessions/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Bn.Events=Rn,Bn.Resources=zn;var Vn=class extends O{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post(A`/v1/skills/${e}/versions?beta=true`,_t({body:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/skills/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},Hn=class extends O{constructor(){super(...arguments),this.versions=new Vn(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,_t({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};Hn.Versions=Vn;var Un=class extends O{create(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/vaults/${e}/credentials?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Wn=class extends O{constructor(){super(...arguments),this.credentials=new Un(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/vaults/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Wn.Credentials=Un;var G=class extends O{constructor(){super(...arguments),this.models=new Bt(this._client),this.messages=new In(this._client),this.agents=new Ut(this._client),this.environments=new Nt(this._client),this.sessions=new Bn(this._client),this.vaults=new Wn(this._client),this.memoryStores=new Kt(this._client),this.files=new zt(this._client),this.skills=new Hn(this._client),this.userProfiles=new Vt(this._client)}};G.Models=Bt,G.Messages=In,G.Agents=Ut,G.Environments=Nt,G.Sessions=Bn,G.Vaults=Wn,G.MemoryStores=Kt,G.Files=zt,G.Skills=Hn,G.UserProfiles=Vt;var Gn=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function Kn(e){return e?.output_config?.format}function qn(e,t,n){let r=Kn(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1}):e),parsed_output:null}:Jn(e,t,n)}function Jn(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=Yn(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},`parsed_output`,{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Yn(e,t){let n=Kn(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new v(`Failed to parse structured output: ${e}`)}}var K,q,J,Xn,Zn,Qn,$n,er,tr,Y,X,nr,rr,Z,ir,ar,or,sr,cr,lr,ur,dr,fr,pr;const mr=`__json_buf`;function hr(e){return e.type===`tool_use`||e.type===`server_tool_use`}var gr=class e{constructor(e,t){K.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),J.set(this,null),this.controller=new AbortController,Xn.set(this,void 0),Zn.set(this,()=>{}),Qn.set(this,()=>{}),$n.set(this,void 0),er.set(this,()=>{}),tr.set(this,()=>{}),Y.set(this,{}),X.set(this,!1),nr.set(this,!1),rr.set(this,!1),Z.set(this,!1),ir.set(this,void 0),ar.set(this,void 0),or.set(this,void 0),lr.set(this,e=>{if(g(this,nr,!0,`f`),re(e)&&(e=new b),e instanceof b)return g(this,rr,!0,`f`),this._emit(`abort`,e);if(e instanceof v)return this._emit(`error`,e);if(e instanceof Error){let t=new v(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new v(String(e)))}),g(this,Xn,new Promise((e,t)=>{g(this,Zn,e,`f`),g(this,Qn,t,`f`)}),`f`),g(this,$n,new Promise((e,t)=>{g(this,er,e,`f`),g(this,tr,t,`f`)}),`f`),_(this,Xn,`f`).catch(()=>{}),_(this,$n,`f`).catch(()=>{}),g(this,J,e,`f`),g(this,or,t?.logger??console,`f`)}get response(){return _(this,ir,`f`)}get request_id(){return _(this,ar,`f`)}async withResponse(){g(this,Z,!0,`f`);let e=await _(this,Xn,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return g(a,J,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},_(this,lr,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{_(this,K,`m`,ur).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)_(this,K,`m`,dr).call(this,e);if(i.controller.signal?.aborted)throw new b;_(this,K,`m`,fr).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(g(this,ir,e,`f`),g(this,ar,e?.headers.get(`request-id`),`f`),_(this,Zn,`f`).call(this,e),this._emit(`connect`))}get ended(){return _(this,X,`f`)}get errored(){return _(this,nr,`f`)}get aborted(){return _(this,rr,`f`)}abort(){this.controller.abort()}on(e,t){return(_(this,Y,`f`)[e]||(_(this,Y,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=_(this,Y,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(_(this,Y,`f`)[e]||(_(this,Y,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{g(this,Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){g(this,Z,!0,`f`),await _(this,$n,`f`)}get currentMessage(){return _(this,q,`f`)}async finalMessage(){return await this.done(),_(this,K,`m`,sr).call(this)}async finalText(){return await this.done(),_(this,K,`m`,cr).call(this)}_emit(e,...t){if(_(this,X,`f`))return;e===`end`&&(g(this,X,!0,`f`),_(this,er,`f`).call(this));let n=_(this,Y,`f`)[e];if(n&&(_(this,Y,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!_(this,Z,`f`)&&!n?.length&&Promise.reject(e),_(this,Qn,`f`).call(this,e),_(this,tr,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!_(this,Z,`f`)&&!n?.length&&Promise.reject(e),_(this,Qn,`f`).call(this,e),_(this,tr,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,_(this,K,`m`,sr).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{_(this,K,`m`,ur).call(this),this._connected(null);let t=tt.fromReadableStream(e,this.controller);for await(let e of t)_(this,K,`m`,dr).call(this,e);if(t.controller.signal?.aborted)throw new b;_(this,K,`m`,fr).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(q=new WeakMap,J=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,er=new WeakMap,tr=new WeakMap,Y=new WeakMap,X=new WeakMap,nr=new WeakMap,rr=new WeakMap,Z=new WeakMap,ir=new WeakMap,ar=new WeakMap,or=new WeakMap,lr=new WeakMap,K=new WeakSet,sr=function(){if(this.receivedMessages.length===0)throw new v(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},cr=function(){if(this.receivedMessages.length===0)throw new v(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new v(`stream ended without producing a content block with type=text`);return e.join(` `)},ur=function(){this.ended||g(this,q,void 0,`f`)},dr=function(e){if(this.ended)return;let t=_(this,K,`m`,pr).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:hr(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(qn(t,_(this,J,`f`),{logger:_(this,or,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:g(this,q,t,`f`);break;case`content_block_start`:case`message_delta`:break}},fr=function(){if(this.ended)throw new v(`stream has ended, this shouldn't happen`);let e=_(this,q,`f`);if(!e)throw new v(`request ended without sending any chunks`);return g(this,q,void 0,`f`),qn(e,_(this,J,`f`),{logger:_(this,or,`f`)})},pr=function(e){let t=_(this,q,`f`);if(e.type===`message_start`){if(t)throw new v(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new v(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&hr(n)){let r=n[mr]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,mr,{value:r,enumerable:!1,writable:!0}),r&&(i.input=nn(r)),t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},_r=class extends O{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(A`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,pt,{query:e,...t})}delete(e,t){return this._client.delete(A`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(A`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new v(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:k([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Mn.fromResponse(t.response,t.controller))}},vr=class extends O{constructor(){super(...arguments),this.batches=new _r(this._client)}create(e,t){e.model in yr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${yr[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),br.includes(e.model)&&e.thinking&&e.thinking.type===`enabled`&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let n=this._client._options.timeout;if(!e.stream&&n==null){let t=qt[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=Lt(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:k([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Jn(t,e,{logger:this._client.logger??console}))}stream(e,t){return gr.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}};const yr={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`,"claude-3-5-haiku-latest":`February 19th, 2026`,"claude-3-5-haiku-20241022":`February 19th, 2026`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`},br=[`claude-mythos-preview`,`claude-opus-4-6`];vr.Batches=_r;var xr=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,pt,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}};const Sr=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var Cr,wr,Tr,Er,Q=class{constructor({baseURL:e=Sr(`ANTHROPIC_BASE_URL`),apiKey:t=Sr(`ANTHROPIC_API_KEY`)??null,authToken:n=Sr(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){Cr.add(this),Tr.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&Te())throw new v(`It looks like you're running in a browser-like environment.
|
|
30
|
-
|
|
31
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
32
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
33
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
34
|
-
|
|
35
|
-
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
36
|
-
`);this.baseURL=i.baseURL,this.timeout=i.timeout??wr.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Ye(i.logLevel,`ClientOptions.logLevel`,this)??Ye(Sr(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Ne(),g(this,Tr,Re,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return k([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return k([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return k([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return ze(e)}getUserAgent(){return`${this.constructor.name}/JS ${x}`}defaultIdempotencyKey(){return`stainless-node-retry-${ne()}`}makeStatusError(e,t,n,r){return y.generate(e,t,n,r)}buildURL(e,t,n){let r=!_(this,Cr,`m`,Er).call(this)&&n||this.baseURL,i=ge(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!be(a)||!be(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new v(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new lt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(w(this).debug(`[${c}] sending request`,T({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new b;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(ie),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new b;let i=re(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return w(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),w(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,T({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw w(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),w(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,T({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new oe:new ae({cause:f})}let m=`[${c}${l}${[...f.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Le(f.body),w(this).info(`${m} - ${e}`),w(this).debug(`[${c}] response error (${e})`,T({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;w(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>ie(e).message),o=Ce(a),s=o?void 0:a;throw w(this).debug(`[${c}] response error (${i})`,T({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return w(this).info(m),w(this).debug(`[${c}] response start`,T({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new ft(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await we(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new v(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&Se(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=k([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Me(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=k([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Fe(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:_(this,Tr,`f`).call(this,{body:e,headers:n})}};wr=Q,Tr=new WeakMap,Cr=new WeakSet,Er=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=wr,Q.HUMAN_PROMPT=`\\n\\nHuman:`,Q.AI_PROMPT=`\\n\\nAssistant:`,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=v,Q.APIError=y,Q.APIConnectionError=ae,Q.APIConnectionTimeoutError=oe,Q.APIUserAbortError=b,Q.NotFoundError=ue,Q.ConflictError=de,Q.RateLimitError=pe,Q.BadRequestError=se,Q.AuthenticationError=ce,Q.InternalServerError=me,Q.PermissionDeniedError=le,Q.UnprocessableEntityError=fe,Q.toFile=Et;var $=class extends Q{constructor(){super(...arguments),this.completions=new Gn(this),this.messages=new vr(this),this.models=new xr(this),this.beta=new G(this)}};$.Completions=Gn,$.Messages=vr,$.Models=xr,$.Beta=G;function Dr(e,t){return e||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function Or(e,t,n){let r=Dr(t,n);if(r===`none`)return{retention:r};let i=r===`long`&&Pr(e).supportsLongCacheRetention?`1h`:void 0;return{retention:r,cacheControl:{type:`ephemeral`,...i&&{ttl:i}}}}const kr=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),Ar=e=>kr.get(e.toLowerCase())??e,jr=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function Mr(e){if(!e.some(e=>e.type===`image`))return h(e.map(e=>e.text).join(`
|
|
37
|
-
`));let t=e.map(e=>e.type===`text`?{type:`text`,text:h(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}});return t.some(e=>e.type===`text`)||t.unshift({type:`text`,text:`(see attached image)`}),t}function Nr(e){return(e.compat?.allowedFallbackModels?.length??0)>0}function Pr(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??!1,supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1,supportsStrictTools:e.compat?.supportsStrictTools??!1,supportsToolReferences:e.compat?.supportsToolReferences??Fr(e)}}function Fr(e){if(e.provider!==`anthropic`||e.id.includes(`haiku`))return!1;let t=e.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);if(!t)return!1;let n=Number(t[1]),r=t[2]&&t[2].length<8?Number(t[2]):0;return n>4||n===4&&r>=5}function Ir(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}function Lr(...e){return Ir({"User-Agent":u()},...e)}function Rr(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function zr(e,t,n){if(!t&&!(Rr(n,`authorization`)||Rr(n,`x-api-key`)||Rr(n,`cf-aig-authorization`)))throw Error(`No API key for provider: ${e}`)}const Br=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Vr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
|
|
38
|
-
`),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Hr(e,t){if(e===``)return Vr(t);if(t.raw.push(e),e.startsWith(`:`))return null;let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);return i.startsWith(` `)&&(i=i.slice(1)),r===`event`?t.event=i:r===`data`&&t.data.push(i),null}function Ur(e){let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
39
|
-
`);return t===-1?n:n===-1?t:Math.min(t,n)}function Wr(e){let t=Ur(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
|
|
40
|
-
`&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Gr(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Wr(a);for(;s;){a=s.rest;let e=Hr(s.line,i);e&&(yield e),s=Wr(a)}}a+=r.decode();let e=Wr(a);for(;e;){a=e.rest;let t=Hr(e.line,i);t&&(yield t),e=Wr(a)}if(a.length>0){let e=Hr(a,i);e&&(yield e)}let o=Vr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Kr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,i=!1;for await(let a of Gr(e.body,t)){if(a.event===`error`)throw Error(a.data);if(Br.has(a.event??``))try{let e=r(a.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(i=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${a.event}: ${t}; data=${a.data}; raw=${a.raw.join(`\\n`)}`)}}if(n&&!i)throw Error(`Anthropic stream ended before message_stop`)}const qr=(r,i,a)=>{let s=new e;return(async()=>{let e={role:`assistant`,content:[],api:r.api,provider:r.provider,model:r.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let c,l,u=r;if(a?.client)c=a.client,l=!1;else{let e=a?.apiKey;zr(r.provider,e,a?.headers);let t;if(r.provider===`github-copilot`){let e=ee(i.messages);t=te({messages:i.messages,hasImages:e})}let n=Dr(a?.cacheRetention,a?.env)===`none`?void 0:a?.sessionId,o=Zr(r,e,a?.interleavedThinking??!0,ni(r,i),Nr(r),a?.headers,a?.fetch,t,n);c=o.client,l=o.isOAuthToken}let d=Qr(r,i,l,a),f=await a?.onPayload?.(d,r);f!==void 0&&(d=f);let p={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},maxRetries:0},h=await m(()=>c.messages.create({...d,stream:!0},p).asResponse(),{maxRetries:a?.maxRetries,maxRetryDelayMs:a?.maxRetryDelayMs,signal:a?.signal});await a?.onResponse?.({status:h.status,headers:o(h.headers)},r),s.push({type:`start`,partial:e});let g=e.content;for await(let o of Kr(h,a?.signal))if(o.type===`message_start`){e.responseId=o.message.id,e.model=o.message.model;let n=e.model===r.id?void 0:r.compat?.allowedFallbackModels?.find(t=>t.provider===r.provider&&t.model===e.model)?.cost;u=n?{...r,id:e.model,cost:n}:r,e.usage.input=o.message.usage.input_tokens||0,e.usage.output=o.message.usage.output_tokens||0,e.usage.cacheRead=o.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=o.message.usage.cache_creation_input_tokens||0,e.usage.cacheWrite1h=o.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,t(u,e.usage)}else if(o.type===`content_block_start`){if(o.content_block.type===`text`){let t={type:`text`,text:o.content_block.text??``,index:o.index};e.content.push(t),s.push({type:`text_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`thinking`){let t={type:`thinking`,thinking:o.content_block.thinking??``,thinkingSignature:o.content_block.signature??``,index:o.index};e.content.push(t),s.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`redacted_thinking`){let t={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:o.content_block.data,redacted:!0,index:o.index};e.content.push(t),s.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`tool_use`){let t={type:`toolCall`,id:o.content_block.id,name:l?jr(o.content_block.name,i.tools):o.content_block.name,arguments:o.content_block.input??{},partialJson:``,index:o.index};e.content.push(t),s.push({type:`toolcall_start`,contentIndex:e.content.length-1,partial:e})}}else if(o.type===`content_block_delta`){if(o.delta.type===`text_delta`){let t=g.findIndex(e=>e.index===o.index),n=g[t];n&&n.type===`text`&&(n.text+=o.delta.text,s.push({type:`text_delta`,contentIndex:t,delta:o.delta.text,partial:e}))}else if(o.delta.type===`thinking_delta`){let t=g.findIndex(e=>e.index===o.index),n=g[t];n&&n.type===`thinking`&&(n.thinking+=o.delta.thinking,s.push({type:`thinking_delta`,contentIndex:t,delta:o.delta.thinking,partial:e}))}else if(o.delta.type===`input_json_delta`){let t=g.findIndex(e=>e.index===o.index),r=g[t];r&&r.type===`toolCall`&&(r.partialJson+=o.delta.partial_json,r.arguments=n(r.partialJson),s.push({type:`toolcall_delta`,contentIndex:t,delta:o.delta.partial_json,partial:e}))}else if(o.delta.type===`signature_delta`){let e=g[g.findIndex(e=>e.index===o.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=o.delta.signature)}}else if(o.type===`content_block_stop`){let t=g.findIndex(e=>e.index===o.index),r=g[t];r&&(delete r.index,r.type===`text`?s.push({type:`text_end`,contentIndex:t,content:r.text,partial:e}):r.type===`thinking`?s.push({type:`thinking_end`,contentIndex:t,content:r.thinking,partial:e}):r.type===`toolCall`&&(r.arguments=n(r.partialJson),delete r.partialJson,s.push({type:`toolcall_end`,contentIndex:t,toolCall:r,partial:e})))}else if(o.type===`message_delta`){if(o.delta.stop_reason){e.rawStopReason=o.delta.stop_reason;let t=ii(o.delta.stop_reason,o.delta.stop_details);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage)}if(o.usage){o.usage.input_tokens!=null&&(e.usage.input=o.usage.input_tokens),o.usage.output_tokens!=null&&(e.usage.output=o.usage.output_tokens),o.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=o.usage.cache_read_input_tokens),o.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=o.usage.cache_creation_input_tokens);let t=o.usage.output_tokens_details?.thinking_tokens;t!=null&&(e.usage.reasoning=t)}e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,t(u,e.usage)}if(a?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`Anthropic stream ended without a stop reason`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);s.push({type:`done`,reason:e.stopReason,message:e}),s.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:JSON.stringify(t),s.push({type:`error`,reason:e.stopReason,error:e}),s.end()}})(),s};function Jr(e,t){let n=t?e.thinkingLevelMap?.[t]:void 0;if(typeof n==`string`)return n;switch(t){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;default:return`high`}}const Yr=(e,t,n)=>{zr(e.provider,n?.apiKey,n?.headers);let r={...d(e,t,n,n?.apiKey),toolChoice:n?.toolChoice};if(!n?.reasoning)return qr(e,t,{...r,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let i=Jr(e,n.reasoning);return qr(e,t,{...r,thinkingEnabled:!0,effort:i})}let i=l(r.maxTokens,e.maxTokens,n.reasoning,n.thinkingBudgets),a=c(e,t,i.maxTokens);return qr(e,t,{...r,maxTokens:a,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(i.thinkingBudget,Math.max(0,a-1024))})};function Xr(e){return e.includes(`sk-ant-oat`)}function Zr(e,t,n,r,i,a,o,s,c){let l=n&&e.compat?.forceAdaptiveThinking!==!0,u=[];if(r&&u.push(`fine-grained-tool-streaming-2025-05-14`),l&&u.push(`interleaved-thinking-2025-05-14`),i&&u.push(`server-side-fallback-2026-07-01`),e.provider===`github-copilot`)return{client:new $({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:o,defaultHeaders:Lr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...u.length>0?{"anthropic-beta":u.join(`,`)}:{}},e.headers,s,a)}),isOAuthToken:!1};if(t&&Xr(t))return{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:o,defaultHeaders:Lr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...u].join(`,`),"user-agent":`claude-cli/2.1.75`,"x-app":`cli`},e.headers,a)}),isOAuthToken:!0};let d=c&&Pr(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},f=Lr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...u.length>0?{"anthropic-beta":u.join(`,`)}:{}},d,e.headers,a);return{client:new $({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:o,defaultHeaders:f}),isOAuthToken:!1}}function Qr(e,t,n,r){let{cacheControl:i}=Or(e,r?.cacheRetention,r?.env),o=Pr(e),s=f(t.messages,e,$r),c=n?Ar:e=>e,l=a({...t,messages:s},o.supportsToolReferences,c),u=l.immediate,d=[...l.deferred.values()];u.length===0&&d.length>0&&(u=d,d=[]);let p=new Set(d.map(e=>c(e.name))),m={model:e.id,messages:ti(s,n,i,o.allowEmptySignature,p,c),max_tokens:r?.maxTokens??e.maxTokens,stream:!0};if(n?(m.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...i?{cache_control:i}:{}}],t.systemPrompt&&m.system.push({type:`text`,text:h(t.systemPrompt),...i?{cache_control:i}:{}})):t.systemPrompt&&(m.system=[{type:`text`,text:h(t.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&o.supportsTemperature&&(m.temperature=r.temperature),(u.length>0||d.length>0)&&(m.tools=[...ri(u,n,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?i:void 0),...ri(d,n,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)]),e.reasoning)if(r?.thinkingEnabled){let t=r.thinkingDisplay??`summarized`;e.compat?.forceAdaptiveThinking===!0?(m.thinking={type:`adaptive`,display:t},r.effort&&(m.output_config=(r.effort,{effort:r.effort}))):m.thinking={type:`enabled`,budget_tokens:r.thinkingBudgetTokens||1024,display:t}}else r?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null&&(m.thinking={type:`disabled`});if(r?.metadata){let e=r.metadata.user_id;typeof e==`string`&&(m.metadata={user_id:e})}r?.toolChoice&&(typeof r.toolChoice==`string`?m.tool_choice={type:r.toolChoice}:m.tool_choice=r.toolChoice);let ee=e.compat?.allowedFallbackModels;return ee&&ee.length>0&&(m.fallbacks=ee.map(e=>({model:e.model}))),m}function $r(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function ei(e,t,n,r,i){let a=[];for(let o of e.addedToolNames??[]){let e=i(o);!n.has(e)||r.has(e)||(r.add(e),a.push({type:`tool_reference`,tool_name:t?Ar(o):o}))}let o=Mr(e.content);return{toolResult:{type:`tool_result`,tool_use_id:e.toolCallId,content:a.length>0?a:o,is_error:e.isError},siblingContent:a.length===0?[]:typeof o==`string`?[{type:`text`,text:o}]:o}}function ti(e,t,n,r=!1,i=new Set,a=e=>e){let o=[],s=new Set;for(let n=0;n<e.length;n++){let c=e[n];if(c.role===`user`)if(typeof c.content==`string`)c.content.trim().length>0&&o.push({role:`user`,content:h(c.content)});else{let e=c.content.map(e=>e.type===`text`?{type:`text`,text:h(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}}).filter(e=>e.type===`text`?e.text.trim().length>0:!0);if(e.length===0)continue;o.push({role:`user`,content:e})}else if(c.role===`assistant`){let e=[];for(let n of c.content)if(n.type===`text`){if(n.text.trim().length===0)continue;e.push({type:`text`,text:h(n.text)})}else if(n.type===`thinking`){if(n.redacted){e.push({type:`redacted_thinking`,data:n.thinkingSignature});continue}let t=n.thinkingSignature,i=!!t&&t.trim().length>0;if(n.thinking.trim().length===0&&!i)continue;i?e.push({type:`thinking`,thinking:h(n.thinking),signature:t}):e.push(r?{type:`thinking`,thinking:h(n.thinking),signature:``}:{type:`text`,text:h(n.thinking)})}else n.type===`toolCall`&&e.push({type:`tool_use`,id:n.id,name:t?Ar(n.name):n.name,input:n.arguments??{}});if(e.length===0)continue;o.push({role:`assistant`,content:e})}else if(c.role===`toolResult`){let r=[],c=[],l=n;for(;l<e.length&&e[l].role===`toolResult`;){let n=ei(e[l],t,i,s,a);r.push(n.toolResult),c.push(...n.siblingContent),l++}n=l-1,o.push({role:`user`,content:[...r,...c]})}}if(n&&o.length>0){let e=o[o.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=n)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:n}])}return o}function ni(e,t){return!!t.tools?.length&&!Pr(e).supportsEagerToolInputStreaming}function ri(e,t,n,r,i,a=!1){return e?e.map((o,c)=>{let l=s(o,r),u=p(o,l),d=u,f={type:`object`,properties:d.properties??{},required:d.required??[]},m=l===!0?{...u,...f}:f;return{name:t?Ar(o.name):o.name,description:o.description,...n?{eager_input_streaming:!0}:{},...l===!0?{strict:!0}:{},input_schema:m,...a?{defer_loading:!0}:{},...i&&c===e.length-1?{cache_control:i}:{}}}):[]}function ii(e,t){switch(e){case`end_turn`:return{stopReason:`stop`};case`max_tokens`:return{stopReason:`length`};case`tool_use`:return{stopReason:`toolUse`};case`refusal`:return{stopReason:`error`,errorMessage:t?.explanation||`The model refused to complete the request`};case`pause_turn`:return{stopReason:`stop`};case`stop_sequence`:return{stopReason:`stop`};case`sensitive`:return{stopReason:`error`,errorMessage:`Provider stopped with: sensitive`};default:throw Error(`Unhandled stop reason: ${e}`)}}export{qr as stream,Yr as streamSimple};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t}from"./models-BBd5zwn6.mjs";import"./json-parse-BzRcyI3e.mjs";import{t as n}from"./provider-env-CL5ShLlj.mjs";import{t as r}from"./headers-DlpC0ues.mjs";import{c as i,p as a,r as o}from"./transform-messages-1ulTEFY1.mjs";import{t as s}from"./provider-retry-GaV_ioT7.mjs";import{t as c}from"./openai-CbFQ5q5I.mjs";import{n as l,t as u}from"./error-body-BBlqjbe7.mjs";import{t as d}from"./openai-prompt-cache-tVHrB8oW.mjs";import{n as f,r as p,t as m}from"./openai-responses-shared-Brqyk2bc.mjs";const h=new Set([`openai`,`openai-codex`,`opencode`,`azure-openai-responses`]);function g(e){let t=new Map;if(!e)return t;for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let[r,i]=e.split(`=`,2);!r||!i||t.set(r.trim(),i.trim())}return t}function _(e,t){return t?.azureDeploymentName?t.azureDeploymentName:g(n(`AZURE_OPENAI_DEPLOYMENT_NAME_MAP`,t?.env)).get(e.id)||e.id}function v(e){return u(l(e),`Azure OpenAI API error`)}const y=(t,n,a)=>{let o=new e;return(async()=>{let e=_(t,a),c={role:`assistant`,content:[],api:`azure-openai-responses`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let l=a?.apiKey;if(!l)throw Error(`No API key for provider: ${t.provider}`);let u=w(t,l,a),d=i(n.tools,t.compat?.supportsOpenAIGrammarTools??!1),f=T(t,n,a,e,d),m=await a?.onPayload?.(f,t);m!==void 0&&(f=m);let h={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},maxRetries:0},{data:g,response:_}=await s(()=>u.responses.create(f,h).withResponse(),{maxRetries:a?.maxRetries,maxRetryDelayMs:a?.maxRetryDelayMs,signal:a?.signal});if(await a?.onResponse?.({status:_.status,headers:r(_.headers)},t),o.push({type:`start`,partial:c}),await p(g,c,o,t,{grammarToolInputProperties:d}),a?.signal?.aborted)throw Error(`Request was aborted`);if(c.stopReason===`pending`)throw Error(`Azure OpenAI Responses stream ended without a stop reason`);if(c.stopReason===`aborted`||c.stopReason===`error`)throw Error(c.errorMessage||`An unknown error occurred`);o.push({type:`done`,reason:c.stopReason,message:c}),o.end()}catch(e){for(let e of c.content)delete e.index,delete e.partialJson,delete e.customInput;c.stopReason=a?.signal?.aborted?`aborted`:`error`,c.errorMessage=v(e),o.push({type:`error`,reason:c.stopReason,error:c}),o.end()}})(),o},b=(e,n,r)=>{let i=r?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let a={...o(e,n,r,i),toolChoice:r?.toolChoice},s=r?.reasoning?t(e,r.reasoning):void 0,c=s===`off`?void 0:s;return y(e,n,{...a,reasoningEffort:c})};function x(e){let t=e.trim().replace(/\/+$/,``),n;try{n=new URL(t)}catch{throw Error(`Invalid Azure OpenAI base URL: ${e}`)}let r=n.hostname.endsWith(`.openai.azure.com`)||n.hostname.endsWith(`.cognitiveservices.azure.com`)||n.hostname.endsWith(`.ai.azure.com`),i=n.pathname.replace(/\/+$/,``);return r&&(i===``||i===`/`||i===`/openai`||i===`/openai/v1/responses`)&&(n.pathname=`/openai/v1`,n.search=``),n.toString().replace(/\/+$/,``)}function S(e){return`https://${e}.openai.azure.com/openai/v1`}function C(e,t){let r=t?.azureApiVersion||n(`AZURE_OPENAI_API_VERSION`,t?.env)||`v1`,i=t?.azureBaseUrl?.trim()||n(`AZURE_OPENAI_BASE_URL`,t?.env)?.trim()||void 0,a=t?.azureResourceName||n(`AZURE_OPENAI_RESOURCE_NAME`,t?.env),o=i;if(!o&&a&&(o=S(a)),!o&&e.baseUrl&&(o=e.baseUrl),!o)throw Error(`Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.`);return{baseUrl:x(o),apiVersion:r}}function w(e,t,n){let r={"User-Agent":a(),...e.headers};n?.headers&&Object.assign(r,n.headers);let{baseUrl:i,apiVersion:o}=C(e,n);return new c({apiKey:t,apiVersion:o,dangerouslyAllowBrowser:!0,fetch:n?.fetch,defaultHeaders:r,baseURL:i})}function T(e,t,n,r,a=i(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o={model:r,input:m(e,t,h,{grammarToolInputProperties:a}),stream:!0,prompt_cache_key:d(n?.sessionId),store:!1};return n?.maxTokens&&(o.max_output_tokens=Math.max(n.maxTokens,16)),n?.temperature!==void 0&&(o.temperature=n?.temperature),t.tools&&t.tools.length>0&&(o.tools=f(t.tools,{supportsStrictMode:e.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1})),n?.toolChoice!==void 0&&(o.tool_choice=n.toolChoice),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),n?.samplingParams&&Object.assign(o,n.samplingParams),o}export{y as stream,b as streamSimple};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
const e=e=>e;function t(t,n,r=e){let i=new Map;for(let e of t.tools??[])i.set(r(e.name),e);if(!n)return{immediate:[...i.values()],deferred:new Map};let a=new Set,o=new Set;for(let e of t.messages)if(e.role===`assistant`)for(let t of e.content)t.type===`toolCall`&&o.add(r(t.name));else if(e.role===`toolResult`)for(let t of e.addedToolNames??[]){let e=r(t);o.has(e)||a.add(e)}let s=[],c=new Map;for(let[e,t]of i)a.has(e)?c.set(e,t):s.push(t);return{immediate:s,deferred:c}}export{t};
|