@shawnstack/quickforge 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +131 -0
- package/bin/quickforge.mjs +172 -0
- package/dist/assets/anthropic-u1nbNXhV.js +39 -0
- package/dist/assets/azure-openai-responses-DQ6xSOmb.js +1 -0
- package/dist/assets/chunk-62oNxeRG.js +1 -0
- package/dist/assets/confirm-dialog-DSmrqQ60.js +1 -0
- package/dist/assets/github-copilot-headers-C0toI16e.js +1 -0
- package/dist/assets/google-OeyKMN12.js +1 -0
- package/dist/assets/google-gemini-cli-SnPixyBu.js +2 -0
- package/dist/assets/google-shared-CXUHW-9O.js +11 -0
- package/dist/assets/google-vertex-y0o2eCZV.js +1 -0
- package/dist/assets/hash-fDQBJsbb.js +1 -0
- package/dist/assets/headers-Drkm68SQ.js +1 -0
- package/dist/assets/index-BQJ8qi1U.css +3 -0
- package/dist/assets/index-CK_34smc.js +3048 -0
- package/dist/assets/mistral-DzE_jn-B.js +44 -0
- package/dist/assets/openai-CuiHR4mv.js +16 -0
- package/dist/assets/openai-codex-responses-MtFRvp_b.js +7 -0
- package/dist/assets/openai-completions-C2dhwzO8.js +5 -0
- package/dist/assets/openai-responses-C4n0VhzY.js +1 -0
- package/dist/assets/openai-responses-shared-D2RkRvTj.js +10 -0
- package/dist/assets/pdf.worker.min-Cpi8b8z3.mjs +28 -0
- package/dist/assets/prompt-dialog-B4BD09Oc.js +1 -0
- package/dist/assets/transform-messages-BFwlToJ0.js +1 -0
- package/dist/favicon.svg +1 -0
- package/dist/index.html +15 -0
- package/package.json +80 -0
- package/server/index.mjs +145 -0
- package/server/project-config.mjs +125 -0
- package/server/routes/filesystem.mjs +87 -0
- package/server/routes/instructions.mjs +31 -0
- package/server/routes/project.mjs +76 -0
- package/server/routes/static.mjs +57 -0
- package/server/routes/storage.mjs +97 -0
- package/server/routes/tools.mjs +31 -0
- package/server/storage.mjs +217 -0
- package/server/tools/index.mjs +236 -0
- package/server/utils/platform.mjs +131 -0
- package/server/utils/response.mjs +35 -0
- package/server/utils/workspace.mjs +135 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 QuickForge
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# 速构 QuickForge
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img alt="Version" src="https://img.shields.io/badge/version-1.0.0-blue" />
|
|
5
|
+
<img alt="License" src="https://img.shields.io/badge/license-MIT-green" />
|
|
6
|
+
<img alt="Node" src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" />
|
|
7
|
+
<img alt="React" src="https://img.shields.io/badge/react-19-61DAFB?logo=react" />
|
|
8
|
+
<img alt="Vite" src="https://img.shields.io/badge/vite-8-646CFF?logo=vite" />
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
AI chat application with YOLO-mode local workspace tools — the agent can read, write, and edit files in your project, plus run shell commands.
|
|
12
|
+
|
|
13
|
+
Built with React 19, Vite 8, Tailwind CSS 4, and shadcn-style UI primitives. Uses `@mariozechner/pi-web-ui` for chat components and `@mariozechner/pi-ai` for model orchestration. All data stays local in `~/.quickforge/storage/`.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Features
|
|
18
|
+
|
|
19
|
+
- **ChatGPT-like UI** — collapsible conversation list, streaming responses, model settings.
|
|
20
|
+
- **Local-first** — all API keys, settings, and chat history stored in local JSON files. No cloud, no telemetry.
|
|
21
|
+
- **YOLO mode** — grant the agent access to your workspace: list files, read/write/edit, grep, and run commands.
|
|
22
|
+
- **Multi-provider** — OpenAI-compatible `/v1/chat/completions` and Anthropic Messages API. Bring your own endpoint.
|
|
23
|
+
- **Data migration** — auto-migrates from legacy FastCode folders on first run.
|
|
24
|
+
- **IndexedDB import** — existing browser data for the same origin is copied to local files on startup.
|
|
25
|
+
|
|
26
|
+
## Quick Start
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# Install
|
|
30
|
+
npm install
|
|
31
|
+
|
|
32
|
+
# Development (server + Vite, port 5176)
|
|
33
|
+
npm run dev
|
|
34
|
+
|
|
35
|
+
# Production
|
|
36
|
+
npm run build
|
|
37
|
+
npm start
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Open [http://localhost:5176](http://localhost:5176).
|
|
41
|
+
|
|
42
|
+
### Windows
|
|
43
|
+
|
|
44
|
+
Double-click `dev-quickforge.bat` for development, or `start-quickforge.bat` for production mode.
|
|
45
|
+
|
|
46
|
+
## Tech Stack
|
|
47
|
+
|
|
48
|
+
| Layer | Technology |
|
|
49
|
+
|---|---|
|
|
50
|
+
| Frontend | React 19, Vite 8, Tailwind CSS 4 |
|
|
51
|
+
| UI | shadcn-style primitives, Lucide icons |
|
|
52
|
+
| Chat engine | `@mariozechner/pi-web-ui`, `@mariozechner/pi-agent-core`, `@mariozechner/pi-ai` |
|
|
53
|
+
| Server | Node.js (ESM), plain `http` module |
|
|
54
|
+
| Storage | Local JSON files at `~/.quickforge/storage/` |
|
|
55
|
+
|
|
56
|
+
## Project Structure
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
├── bin/quickforge.mjs # CLI entry point
|
|
60
|
+
├── server/index.mjs # Local API + storage server
|
|
61
|
+
├── src/ # React frontend
|
|
62
|
+
├── public/ # Static assets
|
|
63
|
+
├── index.html # HTML entry
|
|
64
|
+
├── vite.config.ts # Vite + Tailwind config
|
|
65
|
+
└── package.json
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Configuration
|
|
69
|
+
|
|
70
|
+
### Environment Variables
|
|
71
|
+
|
|
72
|
+
| Variable | Default | Description |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| `QUICKFORGE_DATA_DIR` | `~/.quickforge` | Data storage directory |
|
|
75
|
+
| `QUICKFORGE_WORKSPACE_DIR` | project root | Workspace for YOLO tools |
|
|
76
|
+
| `QUICKFORGE_HOST` | `127.0.0.1` | Server bind address |
|
|
77
|
+
| `QUICKFORGE_PORT` | `32176` (dev) / `5176` (prod) | Server port |
|
|
78
|
+
| `QUICKFORGE_VITE_PORT` | `5176` | Vite dev server port |
|
|
79
|
+
| `QUICKFORGE_MAX_BODY_BYTES` | `52428800` (50MB) | Max request body size |
|
|
80
|
+
|
|
81
|
+
Legacy `FASTCODE_*` variants are still accepted for existing setups.
|
|
82
|
+
|
|
83
|
+
### Storage Files
|
|
84
|
+
|
|
85
|
+
Located at `~/.quickforge/storage/` (or `%USERPROFILE%\.quickforge\storage` on Windows):
|
|
86
|
+
|
|
87
|
+
- `custom-providers.json` — custom model/provider configs
|
|
88
|
+
- `provider-keys.json` — API keys
|
|
89
|
+
- `settings.json` — active model, YOLO mode, app preferences
|
|
90
|
+
- `sessions.json` — full chat history
|
|
91
|
+
- `sessions-metadata.json` — conversation list metadata
|
|
92
|
+
|
|
93
|
+
### Default Model
|
|
94
|
+
|
|
95
|
+
Comes pre-configured for a LiteLLM proxy:
|
|
96
|
+
|
|
97
|
+
- **Base URL**: `http://localhost:4000/v1`
|
|
98
|
+
- **Model**: `anthropic/claude-sonnet-4`
|
|
99
|
+
- **API**: OpenAI-compatible `/v1/chat/completions`
|
|
100
|
+
|
|
101
|
+
Change providers and models in the Settings panel.
|
|
102
|
+
|
|
103
|
+
## YOLO Mode
|
|
104
|
+
|
|
105
|
+
Toggle YOLO from the bottom bar. When enabled, the agent gains these local tools:
|
|
106
|
+
|
|
107
|
+
| Tool | Description |
|
|
108
|
+
|---|---|
|
|
109
|
+
| `list_dir` | List directory contents |
|
|
110
|
+
| `read_file` | Read file contents |
|
|
111
|
+
| `grep_files` | Search files by text/regex |
|
|
112
|
+
| `write_file` | Create or overwrite a file |
|
|
113
|
+
| `edit_file` | Replace text in a file |
|
|
114
|
+
| `run_command` | Execute shell commands |
|
|
115
|
+
|
|
116
|
+
All tools are restricted to the workspace root. YOLO runs **without per-tool confirmations** — only enable it for trusted models and workspaces.
|
|
117
|
+
|
|
118
|
+
## Verification
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
npm run lint
|
|
122
|
+
npm run build
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Contributing
|
|
126
|
+
|
|
127
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and PR guidelines.
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { promises as fs } from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
import { fileURLToPath } from 'node:url'
|
|
7
|
+
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
9
|
+
const __dirname = path.dirname(__filename)
|
|
10
|
+
|
|
11
|
+
const pidFile = path.join(os.homedir(), '.quickforge', 'quickforge.pid')
|
|
12
|
+
const serverScript = path.resolve(__dirname, '..', 'server', 'index.mjs')
|
|
13
|
+
|
|
14
|
+
async function readPid() {
|
|
15
|
+
try {
|
|
16
|
+
const text = await fs.readFile(pidFile, 'utf8')
|
|
17
|
+
return Number(text.trim()) || null
|
|
18
|
+
} catch {
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function writePid(pid) {
|
|
24
|
+
await fs.mkdir(path.dirname(pidFile), { recursive: true })
|
|
25
|
+
await fs.writeFile(pidFile, String(pid), 'utf8')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function removePid() {
|
|
29
|
+
try {
|
|
30
|
+
await fs.unlink(pidFile)
|
|
31
|
+
} catch {
|
|
32
|
+
// ignore
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function isProcessRunning(pid) {
|
|
37
|
+
try {
|
|
38
|
+
process.kill(pid, 0)
|
|
39
|
+
return true
|
|
40
|
+
} catch {
|
|
41
|
+
return false
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function cmdStop() {
|
|
46
|
+
const pid = await readPid()
|
|
47
|
+
if (!pid) {
|
|
48
|
+
console.log('QuickForge is not running (no PID file found).')
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (!isProcessRunning(pid)) {
|
|
53
|
+
console.log(`QuickForge PID ${pid} is not running. Cleaning up PID file.`)
|
|
54
|
+
await removePid()
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
console.log(`Stopping QuickForge (PID ${pid})...`)
|
|
59
|
+
try {
|
|
60
|
+
process.kill(pid, 'SIGTERM')
|
|
61
|
+
} catch {
|
|
62
|
+
// force kill on Windows
|
|
63
|
+
try {
|
|
64
|
+
process.kill(pid, 'SIGKILL')
|
|
65
|
+
} catch {
|
|
66
|
+
// ignore
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
await removePid()
|
|
71
|
+
console.log('QuickForge stopped.')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function cmdStart() {
|
|
75
|
+
const existingPid = await readPid()
|
|
76
|
+
if (existingPid && isProcessRunning(existingPid)) {
|
|
77
|
+
console.log(`QuickForge is already running (PID ${existingPid}).`)
|
|
78
|
+
console.log('Use "quickforge stop" to stop it first, or "quickforge restart".')
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Clean up stale PID file
|
|
83
|
+
if (existingPid) await removePid()
|
|
84
|
+
|
|
85
|
+
const child = spawn(process.execPath, [serverScript], {
|
|
86
|
+
detached: true,
|
|
87
|
+
stdio: 'ignore',
|
|
88
|
+
windowsHide: true,
|
|
89
|
+
env: { ...process.env, QUICKFORGE_NO_OPEN: '0' },
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
await writePid(child.pid)
|
|
93
|
+
child.unref()
|
|
94
|
+
|
|
95
|
+
console.log(`QuickForge started (PID ${child.pid}).`)
|
|
96
|
+
console.log(`Open: http://localhost:5176`)
|
|
97
|
+
console.log(`Data: ${path.join(os.homedir(), '.quickforge', 'storage')}`)
|
|
98
|
+
console.log('')
|
|
99
|
+
console.log('Commands:')
|
|
100
|
+
console.log(' quickforge stop Stop the background service')
|
|
101
|
+
console.log(' quickforge restart Restart the background service')
|
|
102
|
+
console.log(' quickforge status Check if the service is running')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function cmdRestart() {
|
|
106
|
+
await cmdStop()
|
|
107
|
+
// Small delay to let the port free up
|
|
108
|
+
await new Promise((resolve) => setTimeout(resolve, 500))
|
|
109
|
+
await cmdStart()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function cmdStatus() {
|
|
113
|
+
const pid = await readPid()
|
|
114
|
+
if (!pid) {
|
|
115
|
+
console.log('QuickForge is not running.')
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (isProcessRunning(pid)) {
|
|
120
|
+
console.log(`QuickForge is running (PID ${pid}).`)
|
|
121
|
+
console.log(`URL: http://localhost:5176`)
|
|
122
|
+
} else {
|
|
123
|
+
console.log(`QuickForge PID ${pid} is stale (not running).`)
|
|
124
|
+
await removePid()
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function main() {
|
|
129
|
+
const command = process.argv[2] || 'start'
|
|
130
|
+
|
|
131
|
+
switch (command) {
|
|
132
|
+
case 'start':
|
|
133
|
+
await cmdStart()
|
|
134
|
+
break
|
|
135
|
+
case 'stop':
|
|
136
|
+
await cmdStop()
|
|
137
|
+
break
|
|
138
|
+
case 'restart':
|
|
139
|
+
await cmdRestart()
|
|
140
|
+
break
|
|
141
|
+
case 'status':
|
|
142
|
+
await cmdStatus()
|
|
143
|
+
break
|
|
144
|
+
case '--help':
|
|
145
|
+
case '-h':
|
|
146
|
+
case 'help':
|
|
147
|
+
console.log('QuickForge CLI')
|
|
148
|
+
console.log('')
|
|
149
|
+
console.log('Usage:')
|
|
150
|
+
console.log(' quickforge Start as background service (default)')
|
|
151
|
+
console.log(' quickforge start Start as background service')
|
|
152
|
+
console.log(' quickforge stop Stop the background service')
|
|
153
|
+
console.log(' quickforge restart Restart the background service')
|
|
154
|
+
console.log(' quickforge status Check if the service is running')
|
|
155
|
+
console.log('')
|
|
156
|
+
console.log('Config:')
|
|
157
|
+
console.log(' QUICKFORGE_PORT=5176 Server port')
|
|
158
|
+
console.log(' QUICKFORGE_HOST=127.0.0.1 Bind address')
|
|
159
|
+
console.log(' QUICKFORGE_DATA_DIR=/path Data storage directory')
|
|
160
|
+
console.log(' QUICKFORGE_NO_OPEN=1 Don\'t auto-open browser')
|
|
161
|
+
break
|
|
162
|
+
default:
|
|
163
|
+
console.log(`Unknown command: ${command}`)
|
|
164
|
+
console.log('Use "quickforge --help" for usage.')
|
|
165
|
+
break
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
main().catch((err) => {
|
|
170
|
+
console.error('QuickForge error:', err.message)
|
|
171
|
+
process.exit(1)
|
|
172
|
+
})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import{a as e,c as t,o as n,s as r,u as i}from"./index-CK_34smc.js";import{t as a}from"./headers-Drkm68SQ.js";import{a as o,n as s,r as c,t as l}from"./transform-messages-BFwlToJ0.js";import{n as u,t as ee}from"./github-copilot-headers-C0toI16e.js";function d(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 f(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)}var p=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return p=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 m(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var h=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)},g=class extends Error{},_=class e extends g{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 te({message:r,cause:h(n)});let a=n,o=a?.error?.type;return t===400?new re(t,a,r,i,o):t===401?new ie(t,a,r,i,o):t===403?new ae(t,a,r,i,o):t===404?new oe(t,a,r,i,o):t===409?new se(t,a,r,i,o):t===422?new ce(t,a,r,i,o):t===429?new le(t,a,r,i,o):t>=500?new ue(t,a,r,i,o):new e(t,a,r,i,o)}},v=class extends _{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},te=class extends _{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},ne=class extends te{constructor({message:e}={}){super({message:e??`Request timed out.`})}},re=class extends _{},ie=class extends _{},ae=class extends _{},oe=class extends _{},se=class extends _{},ce=class extends _{},le=class extends _{},ue=class extends _{},de=/^[a-z][a-z0-9+.-]*:/i,fe=e=>de.test(e),pe=e=>(pe=Array.isArray,pe(e)),me=pe;function he(e){return typeof e==`object`?e??{}:{}}function ge(e){if(!e)return!0;for(let t in e)return!1;return!0}function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var ve=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t},ye=e=>{try{return JSON.parse(e)}catch{return}},be=e=>new Promise(t=>setTimeout(t,e)),y=`0.90.0`,xe=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Se(){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`}var Ce=()=>{let e=Se();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":Ee(Deno.build.os),"X-Stainless-Arch":Te(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":y,"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":y,"X-Stainless-OS":Ee(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Te(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=we();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"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":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function we(){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}var Te=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Ee=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`),De,Oe=()=>De??=Ce();function ke(){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 Ae(...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 je(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ae({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Me(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 Ne(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}var Pe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Fe(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 g(`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 Ie(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}var Le;function Re(e){let t;return(Le??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var ze;function Be(e){let t;return(ze??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var b,x,Ve=class{constructor(){b.set(this,void 0),x.set(this,void 0),d(this,b,new Uint8Array,`f`),d(this,x,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Re(e):e;d(this,b,Ie([f(this,b,`f`),t]),`f`);let n=[],r;for(;(r=He(f(this,b,`f`),f(this,x,`f`)))!=null;){if(r.carriage&&f(this,x,`f`)==null){d(this,x,r.index,`f`);continue}if(f(this,x,`f`)!=null&&(r.index!==f(this,x,`f`)+1||r.carriage)){n.push(Be(f(this,b,`f`).subarray(0,f(this,x,`f`)-1))),d(this,b,f(this,b,`f`).subarray(f(this,x,`f`)),`f`),d(this,x,null,`f`);continue}let e=f(this,x,`f`)===null?r.preceding:r.preceding-1,t=Be(f(this,b,`f`).subarray(0,e));n.push(t),d(this,b,f(this,b,`f`).subarray(r.index),`f`),d(this,x,null,`f`)}return n}flush(){return f(this,b,`f`).length?this.decode(`
|
|
2
|
+
`):[]}};b=new WeakMap,x=new WeakMap,Ve.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),Ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function He(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 Ue(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}var We={off:0,error:200,warn:300,info:400,debug:500},Ge=(e,t,n)=>{if(e){if(_e(We,e))return e;S(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};function Ke(){}function qe(e,t,n){return!t||We[e]>We[n]?Ke:t[e].bind(t)}var Je={error:Ke,warn:Ke,info:Ke,debug:Ke},Ye=new WeakMap;function S(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Je;let r=Ye.get(t);if(r&&r[0]===n)return r[1];let i={error:qe(`error`,t,n),warn:qe(`warn`,t,n),info:qe(`info`,t,n),debug:qe(`debug`,t,n)};return Ye.set(t,[n,i]),i}var C=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),Xe,Ze=class e{constructor(e,t,n){this.iterator=e,Xe.set(this,void 0),this.controller=t,d(this,Xe,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?S(r):console;async function*o(){if(i)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of Qe(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=ye(e.data)??e.data,r=n?.error?.type;throw new _(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(m(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 Ve,n=Me(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 g("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(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Xe=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,f(this,Xe,`f`)),new e(()=>i(n),this.controller,f(this,Xe,`f`))]}toReadableStream(){let e=this,t;return Ae({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=Re(JSON.stringify(n)+`
|
|
4
|
+
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*Qe(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new g(`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 g(`Attempted to iterate over a response with no body`);let n=new et,r=new Ve,i=Me(e.body);for await(let e of $e(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*$e(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`?Re(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ue(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var et=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(`
|
|
5
|
+
`),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]=tt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function tt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function nt(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return S(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):Ze.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:rt(await n.json(),n):await n.text()})();return S(e).debug(`[${r}] response parsed`,C({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function rt(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 it,at=class e extends Promise{constructor(e,t,n=nt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,it.set(this,void 0),d(this,it,e,`f`)}_thenUnwrap(t){return new e(f(this,it,`f`),this.responsePromise,async(e,n)=>rt(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(f(this,it,`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)}};it=new WeakMap;var ot,st=class{constructor(e,t,n,r){ot.set(this,void 0),d(this,ot,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 g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await f(this,ot,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ot=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends at{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await nt(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},lt=class extends st{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:{...he(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...he(this.options.query),after_id:e}}:null}},w=class extends st{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:{...he(this.options.query),page:e}}:null}},ut=()=>{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 T(e,t,n){return ut(),new File(e,t??`unknown_file`,n)}function dt(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}var ft=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,pt=async(e,t,n=!0)=>({...e,body:await gt(e.body,t,n)}),mt=new WeakMap;function ht(e){let t=typeof e==`function`?e:e.fetch,n=mt.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 mt.set(t,r),r}var gt=async(e,t,n=!0)=>{if(!await ht(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])=>vt(r,e,t,n))),r},_t=e=>e instanceof Blob&&`name`in e,vt=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,T([await n.blob()],dt(n,r),i))}else if(ft(n))e.append(t,T([await new Response(je(n)).blob()],dt(n,r)));else if(_t(n))e.append(t,T([n],dt(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>vt(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>vt(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`)}},yt=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`,bt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&yt(e),xt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function St(e,t,n){if(ut(),e=await e,t||=dt(e,!0),bt(e))return e instanceof File&&t==null&&n==null?e:T([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(xt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),T(await Ct(r),t,n)}let r=await Ct(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 T(r,t,n)}async function Ct(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(yt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(ft(e))for await(let n of e)t.push(...await Ct(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${wt(e)}`)}return t}function wt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var E=class{constructor(e){this._client=e}},Tt=Symbol.for(`brand.privateNullableHeaders`);function*Et(e){if(!e)return;if(Tt 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():me(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=me(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])}}var D=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Et(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{[Tt]:!0,values:t,nulls:n}};function Dt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ot=Object.freeze(Object.create(null)),O=((e=Dt)=>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??Ot)??Ot)?.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 g(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
6
|
+
`)}\n${a}\n${t}`)}return a})(Dt),kt=class extends E{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/environments/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/environments/${e}?beta=true`,{body:i,...n,headers:D([{"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`,w,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(O`/v1/environments/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(O`/v1/environments/${e}/archive?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},At=Symbol(`anthropic.sdk.stainlessHelper`);function jt(e){return typeof e==`object`&&!!e&&At in e}function Mt(e,t){let n=new Set;if(e)for(let t of e)jt(t)&&n.add(t[At]);if(t){for(let e of t)if(jt(e)&&n.add(e[At]),Array.isArray(e.content))for(let t of e.content)jt(t)&&n.add(t[At])}return Array.from(n)}function Nt(e,t){let n=Mt(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function Pt(e){return jt(e)?{"x-stainless-helper":e[At]}:{}}var Ft=class extends E{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files`,lt,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(O`/v1/files/${e}`,{...n,headers:D([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/files/${e}/content`,{...n,headers:D([{"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(O`/v1/files/${e}`,{...n,headers:D([{"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`,pt({body:r,...t,headers:D([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},Pt(r.file),t?.headers])},this._client))}},It=class extends E{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/models/${e}?beta=true`,{...n,headers:D([{...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`,lt,{query:r,...t,headers:D([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},Lt=class extends E{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/user_profiles/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:D([{"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`,w,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post(O`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},Rt=class extends E{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(O`/v1/agents/${e}/versions?beta=true`,w,{query:i,...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},zt=class extends E{constructor(){super(...arguments),this.versions=new Rt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(O`/v1/agents/${e}?beta=true`,{query:i,...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/agents/${e}?beta=true`,{body:i,...n,headers:D([{"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`,w,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(O`/v1/agents/${e}/archive?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};zt.Versions=Rt;var Bt={"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 Vt(e){return e?.output_format??e?.output_config?.format}function Ht(e,t,n){let r=Vt(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}:Ut(e,t,n)}function Ut(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=Wt(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 Wt(e,t){let n=Vt(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new g(`Failed to parse structured output: ${e}`)}}var Gt=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},Kt=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),Kt(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),Kt(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),Kt(e);break;case`delimiter`:return e=e.slice(0,e.length-1),Kt(e)}return e},qt=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},Jt=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},Yt=e=>JSON.parse(Jt(qt(Kt(Gt(e))))),k,A,j,M,Xt,N,P,Zt,F,I,L,Qt,$t,R,en,tn,nn,rn,an,on,sn,cn,ln,un,dn=`__json_buf`;function fn(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var pn=class e{constructor(e,t){k.add(this),this.messages=[],this.receivedMessages=[],A.set(this,void 0),j.set(this,null),this.controller=new AbortController,M.set(this,void 0),Xt.set(this,()=>{}),N.set(this,()=>{}),P.set(this,void 0),Zt.set(this,()=>{}),F.set(this,()=>{}),I.set(this,{}),L.set(this,!1),Qt.set(this,!1),$t.set(this,!1),R.set(this,!1),en.set(this,void 0),tn.set(this,void 0),nn.set(this,void 0),on.set(this,e=>{if(d(this,Qt,!0,`f`),m(e)&&(e=new v),e instanceof v)return d(this,$t,!0,`f`),this._emit(`abort`,e);if(e instanceof g)return this._emit(`error`,e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new g(String(e)))}),d(this,M,new Promise((e,t)=>{d(this,Xt,e,`f`),d(this,N,t,`f`)}),`f`),d(this,P,new Promise((e,t)=>{d(this,Zt,e,`f`),d(this,F,t,`f`)}),`f`),f(this,M,`f`).catch(()=>{}),f(this,P,`f`).catch(()=>{}),d(this,j,e,`f`),d(this,nn,t?.logger??console,`f`)}get response(){return f(this,en,`f`)}get request_id(){return f(this,tn,`f`)}async withResponse(){d(this,R,!0,`f`);let e=await f(this,M,`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 d(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`)},f(this,on,`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{f(this,k,`m`,sn).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)f(this,k,`m`,cn).call(this,e);if(i.controller.signal?.aborted)throw new v;f(this,k,`m`,ln).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(d(this,en,e,`f`),d(this,tn,e?.headers.get(`request-id`),`f`),f(this,Xt,`f`).call(this,e),this._emit(`connect`))}get ended(){return f(this,L,`f`)}get errored(){return f(this,Qt,`f`)}get aborted(){return f(this,$t,`f`)}abort(){this.controller.abort()}on(e,t){return(f(this,I,`f`)[e]||(f(this,I,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=f(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(f(this,I,`f`)[e]||(f(this,I,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{d(this,R,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){d(this,R,!0,`f`),await f(this,P,`f`)}get currentMessage(){return f(this,A,`f`)}async finalMessage(){return await this.done(),f(this,k,`m`,rn).call(this)}async finalText(){return await this.done(),f(this,k,`m`,an).call(this)}_emit(e,...t){if(f(this,L,`f`))return;e===`end`&&(d(this,L,!0,`f`),f(this,Zt,`f`).call(this));let n=f(this,I,`f`)[e];if(n&&(f(this,I,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!f(this,R,`f`)&&!n?.length&&Promise.reject(e),f(this,N,`f`).call(this,e),f(this,F,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!f(this,R,`f`)&&!n?.length&&Promise.reject(e),f(this,N,`f`).call(this,e),f(this,F,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,f(this,k,`m`,rn).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{f(this,k,`m`,sn).call(this),this._connected(null);let t=Ze.fromReadableStream(e,this.controller);for await(let e of t)f(this,k,`m`,cn).call(this,e);if(t.controller.signal?.aborted)throw new v;f(this,k,`m`,ln).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(A=new WeakMap,j=new WeakMap,M=new WeakMap,Xt=new WeakMap,N=new WeakMap,P=new WeakMap,Zt=new WeakMap,F=new WeakMap,I=new WeakMap,L=new WeakMap,Qt=new WeakMap,$t=new WeakMap,R=new WeakMap,en=new WeakMap,tn=new WeakMap,nn=new WeakMap,on=new WeakMap,k=new WeakSet,rn=function(){if(this.receivedMessages.length===0)throw new g(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},an=function(){if(this.receivedMessages.length===0)throw new g(`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 g(`stream ended without producing a content block with type=text`);return e.join(` `)},sn=function(){this.ended||d(this,A,void 0,`f`)},cn=function(e){if(this.ended)return;let t=f(this,k,`m`,un).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`:fn(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(Ht(t,f(this,j,`f`),{logger:f(this,nn,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:d(this,A,t,`f`);break;case`content_block_start`:case`message_delta`:break}},ln=function(){if(this.ended)throw new g(`stream has ended, this shouldn't happen`);let e=f(this,A,`f`);if(!e)throw new g(`request ended without sending any chunks`);return d(this,A,void 0,`f`),Ht(e,f(this,j,`f`),{logger:f(this,nn,`f`)})},un=function(e){let t=f(this,A,`f`);if(e.type===`message_start`){if(t)throw new g(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new g(`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&&fn(n)){let r=n[dn]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,dn,{value:r,enumerable:!1,writable:!0}),r)try{i.input=Yt(r)}catch(e){let t=new g(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);f(this,on,`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 Ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},mn=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}},hn=`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:
|
|
7
|
+
1. Task Overview
|
|
8
|
+
The user's core request and success criteria
|
|
9
|
+
Any clarifications or constraints they specified
|
|
10
|
+
2. Current State
|
|
11
|
+
What has been completed so far
|
|
12
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
13
|
+
Key outputs or artifacts produced
|
|
14
|
+
3. Important Discoveries
|
|
15
|
+
Technical constraints or requirements uncovered
|
|
16
|
+
Decisions made and their rationale
|
|
17
|
+
Errors encountered and how they were resolved
|
|
18
|
+
What approaches were tried that didn't work (and why)
|
|
19
|
+
4. Next Steps
|
|
20
|
+
Specific actions needed to complete the task
|
|
21
|
+
Any blockers or open questions to resolve
|
|
22
|
+
Priority order if multiple steps remain
|
|
23
|
+
5. Context to Preserve
|
|
24
|
+
User preferences or style requirements
|
|
25
|
+
Domain-specific details that aren't obvious
|
|
26
|
+
Any promises made to the user
|
|
27
|
+
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.
|
|
28
|
+
Wrap your summary in <summary></summary> tags.`,gn,z,B,V,H,U,W,G,_n,vn,yn;function bn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var xn=class{constructor(e,t,n){gn.add(this),this.client=e,z.set(this,!1),B.set(this,!1),V.set(this,void 0),H.set(this,void 0),U.set(this,void 0),W.set(this,void 0),G.set(this,void 0),_n.set(this,0),d(this,V,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...Mt(t.tools,t.messages)].join(`, `);d(this,H,{...n,headers:D([{"x-stainless-helper":r},n?.headers])},`f`),d(this,G,bn(),`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*[(z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,_n=new WeakMap,gn=new WeakSet,vn=async function(){let e=f(this,V,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(f(this,U,`f`)!==void 0)try{let e=await f(this,U,`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??f(this,V,`f`).params.model,i=e.summaryPrompt??hn,a=f(this,V,`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:f(this,V,`f`).params.max_tokens},{signal:f(this,H,`f`).signal,headers:D([f(this,H,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new g(`Expected text response for compaction`);return f(this,V,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(f(this,z,`f`))throw new g(`Cannot iterate over a consumed stream`);d(this,z,!0,`f`),d(this,B,!0,`f`),d(this,W,void 0,`f`);try{for(;;){let t;try{if(f(this,V,`f`).params.max_iterations&&f(this,_n,`f`)>=f(this,V,`f`).params.max_iterations)break;d(this,B,!1,`f`),d(this,W,void 0,`f`),d(this,_n,(e=f(this,_n,`f`),e++,e),`f`),d(this,U,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=f(this,V,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},f(this,H,`f`)),d(this,U,t.finalMessage(),`f`),f(this,U,`f`).catch(()=>{}),yield t):(d(this,U,this.client.beta.messages.create({...i,stream:!1},f(this,H,`f`)),`f`),yield f(this,U,`f`)),!await f(this,gn,`m`,vn).call(this)){if(!f(this,B,`f`)){let{role:e,content:t}=await f(this,U,`f`);f(this,V,`f`).params.messages.push({role:e,content:t})}let e=await f(this,gn,`m`,yn).call(this,f(this,V,`f`).params.messages.at(-1));if(e)f(this,V,`f`).params.messages.push(e);else if(!f(this,B,`f`))break}}finally{t&&t.abort()}}if(!f(this,U,`f`))throw new g(`ToolRunner concluded without a message from the server`);f(this,G,`f`).resolve(await f(this,U,`f`))}catch(e){throw d(this,z,!1,`f`),f(this,G,`f`).promise.catch(()=>{}),f(this,G,`f`).reject(e),d(this,G,bn(),`f`),e}}setMessagesParams(e){typeof e==`function`?f(this,V,`f`).params=e(f(this,V,`f`).params):f(this,V,`f`).params=e,d(this,B,!0,`f`),d(this,W,void 0,`f`)}setRequestOptions(e){typeof e==`function`?d(this,H,e(f(this,H,`f`)),`f`):d(this,H,{...f(this,H,`f`),...e},`f`)}async generateToolResponse(e=f(this,H,`f`).signal){let t=await f(this,U,`f`)??this.params.messages.at(-1);return t?f(this,gn,`m`,yn).call(this,t,e):null}done(){return f(this,G,`f`).promise}async runUntilDone(){if(!f(this,z,`f`))for await(let e of this);return this.done()}get params(){return f(this,V,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};yn=async function(e,t=f(this,H,`f`).signal){return f(this,W,`f`)===void 0&&d(this,W,Sn(f(this,V,`f`).params,e,{...f(this,H,`f`),signal:t}),`f`),f(this,W,`f`)};async function Sn(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 mn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var Cn=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new Ve;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 g(`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 g(`Attempted to iterate over a response with no body`);return new e(Me(t.body),n)}},wn=class extends E{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/messages/batches/${e}?beta=true`,{...n,headers:D([{"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`,lt,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(O`/v1/messages/batches/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(O`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:D([{"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 g(`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:D([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Cn.fromResponse(t.response,t.controller))}},Tn={"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`},En=[`claude-mythos-preview`,`claude-opus-4-6`],Dn=class extends E{constructor(){super(...arguments),this.batches=new wn(this._client)}create(e,t){let n=On(e),{betas:r,...i}=n;i.model in Tn&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Tn[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),En.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=Bt[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=Nt(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:D([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:D([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Ut(t,e,{logger:this._client.logger??console}))}stream(e,t){return pn.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=On(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new xn(this._client,e,t)}};function On(e){if(!e.output_format)return e;if(e.output_config?.format)throw new g(`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}}}Dn.Batches=wn,Dn.BetaToolRunner=xn,Dn.ToolError=mn;var kn=class extends E{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(O`/v1/sessions/${e}/events?beta=true`,w,{query:i,...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},An=class extends E{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get(O`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:D([{"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(O`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:D([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(O`/v1/sessions/${e}/resources?beta=true`,w,{query:i,...n,headers:D([{"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(O`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},jn=class extends E{constructor(){super(...arguments),this.events=new kn(this._client),this.resources=new An(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/sessions/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:D([{"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`,w,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(O`/v1/sessions/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(O`/v1/sessions/${e}/archive?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};jn.Events=kn,jn.Resources=An;var Mn=class extends E{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post(O`/v1/skills/${e}/versions?beta=true`,pt({body:i,...n,headers:D([{"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(O`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(O`/v1/skills/${e}/versions?beta=true`,w,{query:i,...n,headers:D([{"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(O`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},Nn=class extends E{constructor(){super(...arguments),this.versions=new Mn(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,pt({body:r,...t,headers:D([{"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(O`/v1/skills/${e}?beta=true`,{...n,headers:D([{"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`,w,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(O`/v1/skills/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};Nn.Versions=Mn;var Pn=class extends E{create(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:D([{"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(O`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:D([{"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(O`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:D([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(O`/v1/vaults/${e}/credentials?beta=true`,w,{query:i,...n,headers:D([{"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(O`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:D([{"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(O`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:D([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Fn=class extends E{constructor(){super(...arguments),this.credentials=new Pn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/vaults/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(O`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:D([{"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`,w,{query:r,...t,headers:D([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(O`/v1/vaults/${e}?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(O`/v1/vaults/${e}/archive?beta=true`,{...n,headers:D([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Fn.Credentials=Pn;var K=class extends E{constructor(){super(...arguments),this.models=new It(this._client),this.messages=new Dn(this._client),this.agents=new zt(this._client),this.environments=new kt(this._client),this.sessions=new jn(this._client),this.vaults=new Fn(this._client),this.files=new Ft(this._client),this.skills=new Nn(this._client),this.userProfiles=new Lt(this._client)}};K.Models=It,K.Messages=Dn,K.Agents=zt,K.Environments=kt,K.Sessions=jn,K.Vaults=Fn,K.Files=Ft,K.Skills=Nn,K.UserProfiles=Lt;var In=class extends E{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:D([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function Ln(e){return e?.output_config?.format}function Rn(e,t,n){let r=Ln(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}:zn(e,t,n)}function zn(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=Bn(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 Bn(e,t){let n=Ln(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new g(`Failed to parse structured output: ${e}`)}}var q,J,Y,Vn,Hn,Un,Wn,Gn,Kn,X,qn,Jn,Yn,Z,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or=`__json_buf`;function sr(e){return e.type===`tool_use`||e.type===`server_tool_use`}var cr=class e{constructor(e,t){q.add(this),this.messages=[],this.receivedMessages=[],J.set(this,void 0),Y.set(this,null),this.controller=new AbortController,Vn.set(this,void 0),Hn.set(this,()=>{}),Un.set(this,()=>{}),Wn.set(this,void 0),Gn.set(this,()=>{}),Kn.set(this,()=>{}),X.set(this,{}),qn.set(this,!1),Jn.set(this,!1),Yn.set(this,!1),Z.set(this,!1),Xn.set(this,void 0),Zn.set(this,void 0),Qn.set(this,void 0),tr.set(this,e=>{if(d(this,Jn,!0,`f`),m(e)&&(e=new v),e instanceof v)return d(this,Yn,!0,`f`),this._emit(`abort`,e);if(e instanceof g)return this._emit(`error`,e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new g(String(e)))}),d(this,Vn,new Promise((e,t)=>{d(this,Hn,e,`f`),d(this,Un,t,`f`)}),`f`),d(this,Wn,new Promise((e,t)=>{d(this,Gn,e,`f`),d(this,Kn,t,`f`)}),`f`),f(this,Vn,`f`).catch(()=>{}),f(this,Wn,`f`).catch(()=>{}),d(this,Y,e,`f`),d(this,Qn,t?.logger??console,`f`)}get response(){return f(this,Xn,`f`)}get request_id(){return f(this,Zn,`f`)}async withResponse(){d(this,Z,!0,`f`);let e=await f(this,Vn,`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 d(a,Y,{...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`)},f(this,tr,`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{f(this,q,`m`,nr).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)f(this,q,`m`,rr).call(this,e);if(i.controller.signal?.aborted)throw new v;f(this,q,`m`,ir).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(d(this,Xn,e,`f`),d(this,Zn,e?.headers.get(`request-id`),`f`),f(this,Hn,`f`).call(this,e),this._emit(`connect`))}get ended(){return f(this,qn,`f`)}get errored(){return f(this,Jn,`f`)}get aborted(){return f(this,Yn,`f`)}abort(){this.controller.abort()}on(e,t){return(f(this,X,`f`)[e]||(f(this,X,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=f(this,X,`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(f(this,X,`f`)[e]||(f(this,X,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{d(this,Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){d(this,Z,!0,`f`),await f(this,Wn,`f`)}get currentMessage(){return f(this,J,`f`)}async finalMessage(){return await this.done(),f(this,q,`m`,$n).call(this)}async finalText(){return await this.done(),f(this,q,`m`,er).call(this)}_emit(e,...t){if(f(this,qn,`f`))return;e===`end`&&(d(this,qn,!0,`f`),f(this,Gn,`f`).call(this));let n=f(this,X,`f`)[e];if(n&&(f(this,X,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!f(this,Z,`f`)&&!n?.length&&Promise.reject(e),f(this,Un,`f`).call(this,e),f(this,Kn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!f(this,Z,`f`)&&!n?.length&&Promise.reject(e),f(this,Un,`f`).call(this,e),f(this,Kn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,f(this,q,`m`,$n).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{f(this,q,`m`,nr).call(this),this._connected(null);let t=Ze.fromReadableStream(e,this.controller);for await(let e of t)f(this,q,`m`,rr).call(this,e);if(t.controller.signal?.aborted)throw new v;f(this,q,`m`,ir).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(J=new WeakMap,Y=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,X=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Z=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,tr=new WeakMap,q=new WeakSet,$n=function(){if(this.receivedMessages.length===0)throw new g(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},er=function(){if(this.receivedMessages.length===0)throw new g(`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 g(`stream ended without producing a content block with type=text`);return e.join(` `)},nr=function(){this.ended||d(this,J,void 0,`f`)},rr=function(e){if(this.ended)return;let t=f(this,q,`m`,ar).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`:sr(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(Rn(t,f(this,Y,`f`),{logger:f(this,Qn,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:d(this,J,t,`f`);break;case`content_block_start`:case`message_delta`:break}},ir=function(){if(this.ended)throw new g(`stream has ended, this shouldn't happen`);let e=f(this,J,`f`);if(!e)throw new g(`request ended without sending any chunks`);return d(this,J,void 0,`f`),Rn(e,f(this,Y,`f`),{logger:f(this,Qn,`f`)})},ar=function(e){let t=f(this,J,`f`);if(e.type===`message_start`){if(t)throw new g(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new g(`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&&sr(n)){let r=n[or]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,or,{value:r,enumerable:!1,writable:!0}),r&&(i.input=Yt(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 Ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},lr=class extends E{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(O`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,lt,{query:e,...t})}delete(e,t){return this._client.delete(O`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(O`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new g(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:D([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Cn.fromResponse(t.response,t.controller))}},ur=class extends E{constructor(){super(...arguments),this.batches=new lr(this._client)}create(e,t){e.model in dr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${dr[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),fr.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=Bt[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=Nt(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:D([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>zn(t,e,{logger:this._client.logger??console}))}stream(e,t){return cr.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}},dr={"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`},fr=[`claude-mythos-preview`,`claude-opus-4-6`];ur.Batches=lr;var pr=class extends E{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(O`/v1/models/${e}`,{...n,headers:D([{...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`,lt,{query:r,...t,headers:D([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},mr=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},hr,gr,_r,vr,yr=`\\n\\nHuman:`,br=`\\n\\nAssistant:`,Q=class{constructor({baseURL:e=mr(`ANTHROPIC_BASE_URL`),apiKey:t=mr(`ANTHROPIC_API_KEY`)??null,authToken:n=mr(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){hr.add(this),_r.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&xe())throw new g(`It looks like you're running in a browser-like environment.
|
|
29
|
+
|
|
30
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
31
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
32
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
33
|
+
|
|
34
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
35
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??gr.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Ge(i.logLevel,`ClientOptions.logLevel`,this)??Ge(mr(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ke(),d(this,_r,Pe,`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 D([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return D([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return D([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Fe(e)}getUserAgent(){return`${this.constructor.name}/JS ${y}`}defaultIdempotencyKey(){return`stainless-node-retry-${p()}`}makeStatusError(e,t,n,r){return _.generate(e,t,n,r)}buildURL(e,t,n){let r=!f(this,hr,`m`,vr).call(this)&&n||this.baseURL,i=fe(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!ge(a)||!ge(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 g(`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 at(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(S(this).debug(`[${c}] sending request`,C({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new v;let ee=new AbortController,d=await this.fetchWithTimeout(o,a,s,ee).catch(h),f=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new v;let i=m(d)||/timed? ?out/i.test(String(d)+(`cause`in d?String(d.cause):``));if(t)return S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),this.retryRequest(r,t,n??c);throw S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),i?new ne:new te({cause:d})}let p=`[${c}${l}${[...d.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${d.ok?`succeeded`:`failed`} with status ${d.status} in ${f-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Ne(d.body),S(this).info(`${p} - ${e}`),S(this).debug(`[${c}] response error (${e})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),this.retryRequest(r,t,n??c,d.headers)}let i=e?`error; no more retries left`:`error; not retryable`;S(this).info(`${p} - ${i}`);let a=await d.text().catch(e=>h(e).message),o=ye(a),s=o?void 0:a;throw S(this).debug(`[${c}] response error (${i})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(d.status,o,s,d.headers)}return S(this).info(p),S(this).debug(`[${c}] response start`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),{response:d,options:r,controller:ee,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 ct(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 be(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 g(`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&&ve(`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=D([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))}:{},...Oe(),...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=D([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:je(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)}:f(this,_r,`f`).call(this,{body:e,headers:n})}};gr=Q,_r=new WeakMap,hr=new WeakSet,vr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=gr,Q.HUMAN_PROMPT=yr,Q.AI_PROMPT=br,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=g,Q.APIError=_,Q.APIConnectionError=te,Q.APIConnectionTimeoutError=ne,Q.APIUserAbortError=v,Q.NotFoundError=oe,Q.ConflictError=se,Q.RateLimitError=le,Q.BadRequestError=re,Q.AuthenticationError=ie,Q.InternalServerError=ue,Q.PermissionDeniedError=ae,Q.UnprocessableEntityError=ce,Q.toFile=St;var $=class extends Q{constructor(){super(...arguments),this.completions=new In(this),this.messages=new ur(this),this.models=new pr(this),this.beta=new K(this)}};$.Completions=In,$.Messages=ur,$.Models=pr,$.Beta=K;function xr(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function Sr(e,t){let n=xr(t);if(n===`none`)return{retention:n};let r=n===`long`&&Ar(e).supportsLongCacheRetention?`1h`:void 0;return{retention:n,cacheControl:{type:`ephemeral`,...r&&{ttl:r}}}}var Cr=`2.1.75`,wr=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),Tr=e=>wr.get(e.toLowerCase())??e,Er=(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 Dr(e){if(!e.some(e=>e.type===`image`))return o(e.map(e=>e.text).join(`
|
|
36
|
+
`));let t=e.map(e=>e.type===`text`?{type:`text`,text:o(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}var Or=`fine-grained-tool-streaming-2025-05-14`,kr=`interleaved-thinking-2025-05-14`;function Ar(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function jr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}var Mr=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Nr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
|
|
37
|
+
`),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Pr(e,t){if(e===``)return Nr(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 Fr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
38
|
+
`);return t===-1?n:n===-1?t:Math.min(t,n)}function Ir(e){let t=Fr(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
|
|
39
|
+
`&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Lr(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=Ir(a);for(;s;){a=s.rest;let e=Pr(s.line,i);e&&(yield e),s=Ir(a)}}a+=r.decode();let e=Ir(a);for(;e;){a=e.rest;let t=Pr(e.line,i);t&&(yield t),e=Ir(a)}if(a.length>0){let e=Pr(a,i);e&&(yield e)}let o=Nr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Rr(t,n){if(!t.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);for await(let r of Lr(t.body,n)){if(r.event===`error`)throw Error(r.data);if(Mr.has(r.event??``))try{yield e(r.data)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${r.event}: ${t}; data=${r.data}; raw=${r.raw.join(`\\n`)}`)}}}var zr=(e,o,s)=>{let c=new r;return(async()=>{let r={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l,d;if(s?.client)l=s.client,d=!1;else{let t=s?.apiKey??i(e.provider)??``,n;if(e.provider===`github-copilot`){let e=u(o.messages);n=ee({messages:o.messages,hasImages:e})}let r=Wr(e,t,s?.interleavedThinking??!0,Jr(e,o),s?.headers,n);l=r.client,d=r.isOAuthToken}let f=Gr(e,o,d,s),p=await s?.onPayload?.(f,e);p!==void 0&&(f=p);let m={...s?.signal?{signal:s.signal}:{},...s?.timeoutMs===void 0?{}:{timeout:s.timeoutMs},...s?.maxRetries===void 0?{}:{maxRetries:s.maxRetries}},h=await l.messages.create({...f,stream:!0},m).asResponse();await s?.onResponse?.({status:h.status,headers:a(h.headers)},e),c.push({type:`start`,partial:r});let g=r.content;for await(let i of Rr(h,s?.signal))if(i.type===`message_start`)r.responseId=i.message.id,r.usage.input=i.message.usage.input_tokens||0,r.usage.output=i.message.usage.output_tokens||0,r.usage.cacheRead=i.message.usage.cache_read_input_tokens||0,r.usage.cacheWrite=i.message.usage.cache_creation_input_tokens||0,r.usage.totalTokens=r.usage.input+r.usage.output+r.usage.cacheRead+r.usage.cacheWrite,t(e,r.usage);else if(i.type===`content_block_start`){if(i.content_block.type===`text`){let e={type:`text`,text:``,index:i.index};r.content.push(e),c.push({type:`text_start`,contentIndex:r.content.length-1,partial:r})}else if(i.content_block.type===`thinking`){let e={type:`thinking`,thinking:``,thinkingSignature:``,index:i.index};r.content.push(e),c.push({type:`thinking_start`,contentIndex:r.content.length-1,partial:r})}else if(i.content_block.type===`redacted_thinking`){let e={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:i.content_block.data,redacted:!0,index:i.index};r.content.push(e),c.push({type:`thinking_start`,contentIndex:r.content.length-1,partial:r})}else if(i.content_block.type===`tool_use`){let e={type:`toolCall`,id:i.content_block.id,name:d?Er(i.content_block.name,o.tools):i.content_block.name,arguments:i.content_block.input??{},partialJson:``,index:i.index};r.content.push(e),c.push({type:`toolcall_start`,contentIndex:r.content.length-1,partial:r})}}else if(i.type===`content_block_delta`){if(i.delta.type===`text_delta`){let e=g.findIndex(e=>e.index===i.index),t=g[e];t&&t.type===`text`&&(t.text+=i.delta.text,c.push({type:`text_delta`,contentIndex:e,delta:i.delta.text,partial:r}))}else if(i.delta.type===`thinking_delta`){let e=g.findIndex(e=>e.index===i.index),t=g[e];t&&t.type===`thinking`&&(t.thinking+=i.delta.thinking,c.push({type:`thinking_delta`,contentIndex:e,delta:i.delta.thinking,partial:r}))}else if(i.delta.type===`input_json_delta`){let e=g.findIndex(e=>e.index===i.index),t=g[e];t&&t.type===`toolCall`&&(t.partialJson+=i.delta.partial_json,t.arguments=n(t.partialJson),c.push({type:`toolcall_delta`,contentIndex:e,delta:i.delta.partial_json,partial:r}))}else if(i.delta.type===`signature_delta`){let e=g[g.findIndex(e=>e.index===i.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=i.delta.signature)}}else if(i.type===`content_block_stop`){let e=g.findIndex(e=>e.index===i.index),t=g[e];t&&(delete t.index,t.type===`text`?c.push({type:`text_end`,contentIndex:e,content:t.text,partial:r}):t.type===`thinking`?c.push({type:`thinking_end`,contentIndex:e,content:t.thinking,partial:r}):t.type===`toolCall`&&(t.arguments=n(t.partialJson),delete t.partialJson,c.push({type:`toolcall_end`,contentIndex:e,toolCall:t,partial:r})))}else i.type===`message_delta`&&(i.delta.stop_reason&&(r.stopReason=Xr(i.delta.stop_reason)),i.usage.input_tokens!=null&&(r.usage.input=i.usage.input_tokens),i.usage.output_tokens!=null&&(r.usage.output=i.usage.output_tokens),i.usage.cache_read_input_tokens!=null&&(r.usage.cacheRead=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens!=null&&(r.usage.cacheWrite=i.usage.cache_creation_input_tokens),r.usage.totalTokens=r.usage.input+r.usage.output+r.usage.cacheRead+r.usage.cacheWrite,t(e,r.usage));if(s?.signal?.aborted)throw Error(`Request was aborted`);if(r.stopReason===`aborted`||r.stopReason===`error`)throw Error(`An unknown error occurred`);c.push({type:`done`,reason:r.stopReason,message:r}),c.end()}catch(e){for(let e of r.content)delete e.index,delete e.partialJson;r.stopReason=s?.signal?.aborted?`aborted`:`error`,r.errorMessage=e instanceof Error?e.message:JSON.stringify(e),c.push({type:`error`,reason:r.stopReason,error:r}),c.end()}})(),c};function Br(e){return e.includes(`opus-4-6`)||e.includes(`opus-4.6`)||e.includes(`opus-4-7`)||e.includes(`opus-4.7`)||e.includes(`sonnet-4-6`)||e.includes(`sonnet-4.6`)}function Vr(e,t){switch(e){case`minimal`:return`low`;case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;case`xhigh`:return t.includes(`opus-4-6`)||t.includes(`opus-4.6`)?`max`:t.includes(`opus-4-7`)||t.includes(`opus-4.7`)?`xhigh`:`high`;default:return`high`}}var Hr=(e,t,n)=>{let r=n?.apiKey||i(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let a=c(e,n,r);if(!n?.reasoning)return zr(e,t,{...a,thinkingEnabled:!1});if(Br(e.id)){let r=Vr(n.reasoning,e.id);return zr(e,t,{...a,thinkingEnabled:!0,effort:r})}let o=s(a.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return zr(e,t,{...a,maxTokens:o.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:o.thinkingBudget})};function Ur(e){return e.includes(`sk-ant-oat`)}function Wr(e,t,n,r,i,a){let o=n&&!Br(e.id);if(e.provider===`github-copilot`){let n=[];return r&&n.push(Or),o&&n.push(kr),{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:jr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...n.length>0?{"anthropic-beta":n.join(`,`)}:{}},e.headers,a,i)}),isOAuthToken:!1}}let s=[];return r&&s.push(Or),o&&s.push(kr),Ur(t)?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:jr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...s].join(`,`),"user-agent":`claude-cli/${Cr}`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0}:{client:new $({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:jr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}}function Gr(e,t,n,r){let{cacheControl:i}=Sr(e,r?.cacheRetention),a={model:e.id,messages:qr(t.messages,e,n,i),max_tokens:r?.maxTokens||e.maxTokens/3|0,stream:!0};if(n?(a.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...i?{cache_control:i}:{}}],t.systemPrompt&&a.system.push({type:`text`,text:o(t.systemPrompt),...i?{cache_control:i}:{}})):t.systemPrompt&&(a.system=[{type:`text`,text:o(t.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&(a.temperature=r.temperature),t.tools&&t.tools.length>0&&(a.tools=Yr(t.tools,n,Ar(e).supportsEagerToolInputStreaming,i)),e.reasoning)if(r?.thinkingEnabled){let t=r.thinkingDisplay??`summarized`;Br(e.id)?(a.thinking={type:`adaptive`,display:t},r.effort&&(a.output_config=(r.effort,{effort:r.effort}))):a.thinking={type:`enabled`,budget_tokens:r.thinkingBudgetTokens||1024,display:t}}else r?.thinkingEnabled===!1&&(a.thinking={type:`disabled`});if(r?.metadata){let e=r.metadata.user_id;typeof e==`string`&&(a.metadata={user_id:e})}return r?.toolChoice&&(typeof r.toolChoice==`string`?a.tool_choice={type:r.toolChoice}:a.tool_choice=r.toolChoice),a}function Kr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function qr(e,t,n,r){let i=[],a=l(e,t,Kr);for(let e=0;e<a.length;e++){let t=a[e];if(t.role===`user`)if(typeof t.content==`string`)t.content.trim().length>0&&i.push({role:`user`,content:o(t.content)});else{let e=t.content.map(e=>e.type===`text`?{type:`text`,text:o(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;i.push({role:`user`,content:e})}else if(t.role===`assistant`){let e=[];for(let r of t.content)if(r.type===`text`){if(r.text.trim().length===0)continue;e.push({type:`text`,text:o(r.text)})}else if(r.type===`thinking`){if(r.redacted){e.push({type:`redacted_thinking`,data:r.thinkingSignature});continue}if(r.thinking.trim().length===0)continue;!r.thinkingSignature||r.thinkingSignature.trim().length===0?e.push({type:`text`,text:o(r.thinking)}):e.push({type:`thinking`,thinking:o(r.thinking),signature:r.thinkingSignature})}else r.type===`toolCall`&&e.push({type:`tool_use`,id:r.id,name:n?Tr(r.name):r.name,input:r.arguments??{}});if(e.length===0)continue;i.push({role:`assistant`,content:e})}else if(t.role===`toolResult`){let n=[];n.push({type:`tool_result`,tool_use_id:t.toolCallId,content:Dr(t.content),is_error:t.isError});let r=e+1;for(;r<a.length&&a[r].role===`toolResult`;){let e=a[r];n.push({type:`tool_result`,tool_use_id:e.toolCallId,content:Dr(e.content),is_error:e.isError}),r++}e=r-1,i.push({role:`user`,content:n})}}if(r&&i.length>0){let e=i[i.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=r)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:r}])}return i}function Jr(e,t){return!!t.tools?.length&&!Ar(e).supportsEagerToolInputStreaming}function Yr(e,t,n,r){return e?e.map((i,a)=>{let o=i.parameters;return{name:t?Tr(i.name):i.name,description:i.description,...n?{eager_input_streaming:!0}:{},input_schema:{type:`object`,properties:o.properties??{},required:o.required??[]},...r&&a===e.length-1?{cache_control:r}:{}}}):[]}function Xr(e){switch(e){case`end_turn`:return`stop`;case`max_tokens`:return`length`;case`tool_use`:return`toolUse`;case`refusal`:return`error`;case`pause_turn`:return`stop`;case`stop_sequence`:return`stop`;case`sensitive`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{zr as streamAnthropic,Hr as streamSimpleAnthropic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as e,s as t,u as n}from"./index-CK_34smc.js";import{t as r}from"./headers-Drkm68SQ.js";import{i,r as a}from"./transform-messages-BFwlToJ0.js";import{t as o}from"./openai-CuiHR4mv.js";import{n as s,r as c,t as l}from"./openai-responses-shared-D2RkRvTj.js";var u=`v1`,d=new Set([`openai`,`openai-codex`,`opencode`,`azure-openai-responses`]);function f(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 p(e,t){return t?.azureDeploymentName?t.azureDeploymentName:f({}.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(e.id)||e.id}var m=(e,i,a)=>{let o=new t;return(async()=>{let t=p(e,a),s={role:`assistant`,content:[],api:`azure-openai-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l=y(e,a?.apiKey||n(e.provider)||``,a),u=b(e,i,a,t),d=await a?.onPayload?.(u,e);d!==void 0&&(u=d);let f={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},...a?.maxRetries===void 0?{}:{maxRetries:a.maxRetries}},{data:p,response:m}=await l.responses.create(u,f).withResponse();if(await a?.onResponse?.({status:m.status,headers:r(m.headers)},e),o.push({type:`start`,partial:s}),await c(p,s,o,e),a?.signal?.aborted)throw Error(`Request was aborted`);if(s.stopReason===`aborted`||s.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:s.stopReason,message:s}),o.end()}catch(e){for(let e of s.content)delete e.index,delete e.partialJson;s.stopReason=a?.signal?.aborted?`aborted`:`error`,s.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:s.stopReason,error:s}),o.end()}})(),o},h=(t,r,o)=>{let s=o?.apiKey||n(t.provider);if(!s)throw Error(`No API key for provider: ${t.provider}`);let c=a(t,o,s),l=e(t)?o?.reasoning:i(o?.reasoning);return m(t,r,{...c,reasoningEffort:l})};function g(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`),i=n.pathname.replace(/\/+$/,``);return r&&(i===``||i===`/`||i===`/openai`)&&(n.pathname=`/openai/v1`,n.search=``),n.toString().replace(/\/+$/,``)}function _(e){return`https://${e}.openai.azure.com/openai/v1`}function v(e,t){let n=t?.azureApiVersion||{}.AZURE_OPENAI_API_VERSION||u,r=t?.azureBaseUrl?.trim()||{}.AZURE_OPENAI_BASE_URL?.trim()||void 0,i=t?.azureResourceName||{}.AZURE_OPENAI_RESOURCE_NAME,a=r;if(!a&&i&&(a=_(i)),!a&&e.baseUrl&&(a=e.baseUrl),!a)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:g(a),apiVersion:n}}function y(e,t,n){if(!t){if(!{}.AZURE_OPENAI_API_KEY)throw Error(`Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.`);t={}.AZURE_OPENAI_API_KEY}let r={...e.headers};n?.headers&&Object.assign(r,n.headers);let{baseUrl:i,apiVersion:a}=v(e,n);return new o({apiKey:t,apiVersion:a,dangerouslyAllowBrowser:!0,defaultHeaders:r,baseURL:i})}function b(e,t,n,r){let i={model:r,input:l(e,t,d),stream:!0,prompt_cache_key:n?.sessionId};return n?.maxTokens&&(i.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(i.temperature=n?.temperature),t.tools&&t.tools.length>0&&(i.tools=s(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(i.reasoning={effort:n?.reasoningEffort||`medium`,summary:n?.reasoningSummary||`auto`},i.include=[`reasoning.encrypted_content`]):i.reasoning={effort:`none`}),i}export{m as streamAzureOpenAIResponses,h as streamSimpleAzureOpenAIResponses};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{l as i,s as n,u as r,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./chunk-62oNxeRG.js";import{f as t,m as n,n as r,p as i,r as a,t as o}from"./index-CK_34smc.js";var s=e(n(),1),c=i(),l=t(),u=r();function d({options:e,onResolve:t}){let n=(0,s.useRef)(null);return(0,s.useEffect)(()=>{n.current?.focus();let e=e=>{e.key===`Escape`&&t(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t]),(0,c.createPortal)((0,u.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/50`,onClick:e=>{e.target===e.currentTarget&&t(!1)},children:(0,u.jsxs)(`div`,{className:a(`w-full max-w-sm rounded-lg border border-border bg-background p-6 shadow-lg`,`mx-4`),children:[(0,u.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:e.title}),(0,u.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:e.description}),(0,u.jsxs)(`div`,{className:`mt-5 flex justify-end gap-2`,children:[(0,u.jsx)(o,{ref:n,variant:`outline`,size:`sm`,onClick:()=>t(!1),children:e.cancelLabel??`Cancel`}),(0,u.jsx)(o,{variant:`destructive`,size:`sm`,onClick:()=>t(!0),children:e.confirmLabel??`Delete`})]})]})}),document.body)}function f(e){return new Promise(t=>{let n=document.createElement(`div`);document.body.appendChild(n);let r=(0,l.createRoot)(n);function i(){r.unmount(),setTimeout(()=>n.remove(),0)}function a(e){i(),t(e)}r.render((0,u.jsx)(d,{options:e,onResolve:a}))})}export{f as showConfirm};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){let t=e[e.length-1];return t&&t.role!==`user`?`agent`:`user`}function t(e){return e.some(e=>e.role===`user`&&Array.isArray(e.content)||e.role===`toolResult`&&Array.isArray(e.content)?e.content.some(e=>e.type===`image`):!1)}function n(t){let n={"X-Initiator":e(t.messages),"Openai-Intent":`conversation-edits`};return t.hasImages&&(n[`Copilot-Vision-Request`]=`true`),n}export{t as n,n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as e,s as t,u as n}from"./index-CK_34smc.js";import{a as r,i,r as a}from"./transform-messages-BFwlToJ0.js";import{c as o,i as s,n as c,o as l,r as u,s as d,t as f}from"./google-shared-CXUHW-9O.js";var p=0,m=(r,i,a)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:`google-generative-ai`,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:`stop`,timestamp:Date.now()};try{let c=g(r,a?.apiKey||n(r.provider)||``,a?.headers),l=_(r,i,a),f=await a?.onPayload?.(l,r);f!==void 0&&(l=f);let m=await c.models.generateContentStream(l);o.push({type:`start`,partial:t});let h=null,v=t.content,y=()=>v.length-1;for await(let n of m){t.responseId||=n.responseId;let i=n.candidates?.[0];if(i?.content?.parts)for(let e of i.content.parts){if(e.text!==void 0){let n=u(e);(!h||n&&h.type!==`thinking`||!n&&h.type!==`text`)&&(h&&(h.type===`text`?o.push({type:`text_end`,contentIndex:v.length-1,content:h.text,partial:t}):o.push({type:`thinking_end`,contentIndex:y(),content:h.thinking,partial:t})),n?(h={type:`thinking`,thinking:``,thinkingSignature:void 0},t.content.push(h),o.push({type:`thinking_start`,contentIndex:y(),partial:t})):(h={type:`text`,text:``},t.content.push(h),o.push({type:`text_start`,contentIndex:y(),partial:t}))),h.type===`thinking`?(h.thinking+=e.text,h.thinkingSignature=d(h.thinkingSignature,e.thoughtSignature),o.push({type:`thinking_delta`,contentIndex:y(),delta:e.text,partial:t})):(h.text+=e.text,h.textSignature=d(h.textSignature,e.thoughtSignature),o.push({type:`text_delta`,contentIndex:y(),delta:e.text,partial:t}))}if(e.functionCall){h&&=(h.type===`text`?o.push({type:`text_end`,contentIndex:y(),content:h.text,partial:t}):o.push({type:`thinking_end`,contentIndex:y(),content:h.thinking,partial:t}),null);let n=e.functionCall.id,r={type:`toolCall`,id:!n||t.content.some(e=>e.type===`toolCall`&&e.id===n)?`${e.functionCall.name}_${Date.now()}_${++p}`:n,name:e.functionCall.name||``,arguments:e.functionCall.args??{},...e.thoughtSignature&&{thoughtSignature:e.thoughtSignature}};t.content.push(r),o.push({type:`toolcall_start`,contentIndex:y(),partial:t}),o.push({type:`toolcall_delta`,contentIndex:y(),delta:JSON.stringify(r.arguments),partial:t}),o.push({type:`toolcall_end`,contentIndex:y(),toolCall:r,partial:t})}}i?.finishReason&&(t.stopReason=s(i.finishReason),t.content.some(e=>e.type===`toolCall`)&&(t.stopReason=`toolUse`)),n.usageMetadata&&(t.usage={input:(n.usageMetadata.promptTokenCount||0)-(n.usageMetadata.cachedContentTokenCount||0),output:(n.usageMetadata.candidatesTokenCount||0)+(n.usageMetadata.thoughtsTokenCount||0),cacheRead:n.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:n.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},e(r,t.usage))}if(h&&(h.type===`text`?o.push({type:`text_end`,contentIndex:y(),content:h.text,partial:t}):o.push({type:`thinking_end`,contentIndex:y(),content:h.thinking,partial:t})),a?.signal?.aborted)throw Error(`Request was aborted`);if(t.stopReason===`aborted`||t.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end()}catch(e){for(let e of t.content)`index`in e&&delete e.index;t.stopReason=a?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},h=(e,t,r)=>{let o=r?.apiKey||n(e.provider);if(!o)throw Error(`No API key for provider: ${e.provider}`);let s=a(e,r,o);if(!r?.reasoning)return m(e,t,{...s,thinking:{enabled:!1}});let c=i(r.reasoning),l=e;return y(l)||b(l)||v(l)?m(e,t,{...s,thinking:{enabled:!0,level:S(c,l)}}):m(e,t,{...s,thinking:{enabled:!0,budgetTokens:C(l,c,r.thinkingBudgets)}})};function g(e,t,n){let r={};return e.baseUrl&&(r.baseUrl=e.baseUrl,r.apiVersion=``),(e.headers||n)&&(r.headers={...e.headers,...n}),new o({apiKey:t,httpOptions:Object.keys(r).length>0?r:void 0})}function _(e,t,n={}){let i=f(e,t),a={};n.temperature!==void 0&&(a.temperature=n.temperature),n.maxTokens!==void 0&&(a.maxOutputTokens=n.maxTokens);let o={...Object.keys(a).length>0&&a,...t.systemPrompt&&{systemInstruction:r(t.systemPrompt)},...t.tools&&t.tools.length>0&&{tools:c(t.tools)}};if(t.tools&&t.tools.length>0&&n.toolChoice?o.toolConfig={functionCallingConfig:{mode:l(n.toolChoice)}}:o.toolConfig=void 0,n.thinking?.enabled&&e.reasoning){let e={includeThoughts:!0};n.thinking.level===void 0?n.thinking.budgetTokens!==void 0&&(e.thinkingBudget=n.thinking.budgetTokens):e.thinkingLevel=n.thinking.level,o.thinkingConfig=e}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(o.thinkingConfig=x(e));if(n.signal){if(n.signal.aborted)throw Error(`Request aborted`);o.abortSignal=n.signal}return{model:e.id,contents:i,config:o}}function v(e){return/gemma-?4/.test(e.id.toLowerCase())}function y(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function b(e){return/gemini-3(?:\.\d+)?-flash/.test(e.id.toLowerCase())}function x(e){return y(e)?{thinkingLevel:`LOW`}:b(e)||v(e)?{thinkingLevel:`MINIMAL`}:{thinkingBudget:0}}function S(e,t){if(y(t))switch(e){case`minimal`:case`low`:return`LOW`;case`medium`:case`high`:return`HIGH`}if(v(t))switch(e){case`minimal`:case`low`:return`MINIMAL`;case`medium`:case`high`:return`HIGH`}switch(e){case`minimal`:return`MINIMAL`;case`low`:return`LOW`;case`medium`:return`MEDIUM`;case`high`:return`HIGH`}}function C(e,t,n){return n?.[t]===void 0?e.id.includes(`2.5-pro`)?{minimal:128,low:2048,medium:8192,high:32768}[t]:e.id.includes(`2.5-flash-lite`)?{minimal:512,low:2048,medium:8192,high:24576}[t]:e.id.includes(`2.5-flash`)?{minimal:128,low:2048,medium:8192,high:24576}[t]:-1:n[t]}export{m as streamGoogle,h as streamSimpleGoogle};
|