@easbot/llm 0.3.27 → 0.3.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +47 -53
- package/README.md +48 -54
- package/dist/assets/txt/model/graph-summary.txt +5 -0
- package/dist/assets/txt/model/knowledge-summary.txt +5 -0
- package/dist/assets/txt/model/memory-summary.txt +5 -0
- package/dist/chunks/chunk-4A6CXMF2.cjs +2 -0
- package/dist/chunks/chunk-QKEOAEWA.mjs +2 -0
- package/dist/chunks/{copilot-TJATIV2S.mjs → copilot-LRTA3GBD.mjs} +1 -1
- package/dist/chunks/copilot-T25BJSTK.cjs +1 -0
- package/dist/chunks/models-snapshot-4CLLJLX6.mjs +2 -0
- package/dist/chunks/models-snapshot-OF5YAGCK.cjs +2 -0
- package/dist/index.cjs +50 -32
- package/dist/index.d.cts +934 -95
- package/dist/index.d.ts +934 -95
- package/dist/index.mjs +50 -32
- package/package.json +9 -7
- package/dist/chunks/chunk-3BANRW36.mjs +0 -2
- package/dist/chunks/chunk-UIFIYRZK.cjs +0 -2
- package/dist/chunks/copilot-R22QW5MH.cjs +0 -1
- package/dist/chunks/models-snapshot-3EXCDFMS.mjs +0 -2
- package/dist/chunks/models-snapshot-L4WLMITS.cjs +0 -2
package/README.en.md
CHANGED
|
@@ -6,8 +6,7 @@ English | [中文](./README.md)
|
|
|
6
6
|
|
|
7
7
|
## Version
|
|
8
8
|
|
|
9
|
-
v0.3.
|
|
10
|
-
|
|
9
|
+
v0.3.29
|
|
11
10
|
## Current Status (after V4 refactor)
|
|
12
11
|
|
|
13
12
|
This package has evolved from an early placeholder of `@easbot/types` into a production-grade AI gateway layer that hosts two core modules: `provider/*` and `model/*`:
|
|
@@ -117,7 +116,7 @@ const reranked = await RerankProvider.rerank({
|
|
|
117
116
|
|
|
118
117
|
// Graph entity extraction
|
|
119
118
|
const graph = await GraphProvider.generateGraph({
|
|
120
|
-
chunks: ['chunk1...', 'chunk2...', '...'],
|
|
119
|
+
chunks: ['chunk1...', 'chunk2...', '...'], // any-length array
|
|
121
120
|
prompt: { maxChunks: 5, maxConcurrency: 3 }, // v0.8: per-call slicing + 3 concurrent
|
|
122
121
|
});
|
|
123
122
|
// graph.entities / relations / summary are directly ingestable
|
|
@@ -189,14 +188,8 @@ export {
|
|
|
189
188
|
PROVIDER_DISPLAY_NAMES,
|
|
190
189
|
} from './provider/definition';
|
|
191
190
|
|
|
192
|
-
// Top-level functions
|
|
193
|
-
export { initModelsRefresh } from './provider/models';
|
|
194
|
-
|
|
195
191
|
// Self-developed GitHub Copilot SDK
|
|
196
|
-
export {
|
|
197
|
-
createOpenaiCompatible,
|
|
198
|
-
openaiCompatible,
|
|
199
|
-
} from './provider/sdk/copilot';
|
|
192
|
+
export { createOpenaiCompatible, openaiCompatible } from './provider/sdk/copilot';
|
|
200
193
|
export type {
|
|
201
194
|
OpenaiCompatibleProvider,
|
|
202
195
|
OpenaiCompatibleProviderSettings,
|
|
@@ -230,17 +223,14 @@ After the V4 refactor, the `Provider` / `ModelsDev` / `ProviderAuth` / `Provider
|
|
|
230
223
|
The agent package calls `setAdapterRegistry(...)` once at startup, injecting all 4 Provider implementations:
|
|
231
224
|
|
|
232
225
|
```typescript
|
|
233
|
-
import {
|
|
234
|
-
setAdapterRegistry,
|
|
235
|
-
type AdapterRegistry,
|
|
236
|
-
} from '@easbot/llm';
|
|
226
|
+
import { setAdapterRegistry, type AdapterRegistry } from '@easbot/llm';
|
|
237
227
|
|
|
238
228
|
// At the agent-package startup entry (e.g. before Instance.provide)
|
|
239
229
|
setAdapterRegistry({
|
|
240
|
-
config: Config,
|
|
241
|
-
instance: Instance,
|
|
242
|
-
global: Global.Path,
|
|
243
|
-
installation: Installation,
|
|
230
|
+
config: Config, // IConfigProvider — get / provider
|
|
231
|
+
instance: Instance, // IInstanceProvider — getDirectory / getWorktree
|
|
232
|
+
global: Global.Path, // IGlobalPathProvider — cache / data / config
|
|
233
|
+
installation: Installation, // IInstallationProvider — getVersion
|
|
244
234
|
// V4: Auth has moved to `@easbot/utils.Auth`, no longer injected via AdapterRegistry.
|
|
245
235
|
// Internally the LLM package calls `import { Auth } from '@easbot/utils'` directly.
|
|
246
236
|
} satisfies AdapterRegistry);
|
|
@@ -257,14 +247,15 @@ Call setAdapterRegistry({ config: ... }) before using LLM.
|
|
|
257
247
|
|
|
258
248
|
### 2. 4 Provider interface contracts
|
|
259
249
|
|
|
260
|
-
| Interface
|
|
261
|
-
|
|
262
|
-
| `IConfigProvider`
|
|
263
|
-
| `IInstanceProvider`
|
|
264
|
-
| `IGlobalPathProvider`
|
|
265
|
-
| `IInstallationProvider` | `getVersion(): string`
|
|
250
|
+
| Interface | Methods | Original agent module | Purpose |
|
|
251
|
+
| ----------------------- | ------------------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------- |
|
|
252
|
+
| `IConfigProvider` | `get<T>(): Promise<T>` / `provider<T>(id): Promise<T \| undefined>` | `Config` | User `~/.config/easbot/config.json` llm block (whitelist / blacklist / variant override) |
|
|
253
|
+
| `IInstanceProvider` | `getDirectory(): string` / `getWorktree(): string` | `Instance` | Instance directory + worktree paths |
|
|
254
|
+
| `IGlobalPathProvider` | `cache: string` / `data: string` / `config: string` | `Global.Path` | Model snapshot cache / user data / global config directory |
|
|
255
|
+
| `IInstallationProvider` | `getVersion(): string` | `Installation` | User-Agent / compatibility checks / version info |
|
|
266
256
|
|
|
267
257
|
> **V4 change**: `IInstanceProvider.state(init)` and `IPluginProvider` have been **decomposed** (ADR 0071).
|
|
258
|
+
>
|
|
268
259
|
> - Provider internal state caching now uses `@easbot/utils.lazyAsync(init)` (per-process singleton + explicit reset)
|
|
269
260
|
> - Plugin registration uses module-level `_pluginAuthRegistry: Map<providerId, methods[]>` + `ProviderAuth.registerPluginAuthProvider()` entry injection
|
|
270
261
|
|
|
@@ -278,7 +269,7 @@ The V3-new `src/config/` module mirrors `packages/gateway/src/config/`:
|
|
|
278
269
|
```typescript
|
|
279
270
|
import { Config, LLMConfig } from '@easbot/llm';
|
|
280
271
|
|
|
281
|
-
const cfg = await Config.get();
|
|
272
|
+
const cfg = await Config.get(); // injected or fallback loader
|
|
282
273
|
const openaiCfg = await Config.provider('openai');
|
|
283
274
|
|
|
284
275
|
// Schema validation (standalone)
|
|
@@ -299,27 +290,28 @@ const parsed = LLMConfig.parse({
|
|
|
299
290
|
|
|
300
291
|
```typescript
|
|
301
292
|
import { Flag, readEnvString, readFlagBool } from '@easbot/llm';
|
|
302
|
-
import { Env } from '@easbot/llm';
|
|
293
|
+
import { Env } from '@easbot/llm'; // equivalent to: import { Env } from '@easbot/utils'
|
|
303
294
|
|
|
304
|
-
Flag.EASBOT_OUTPUT_TOKEN_MAX;
|
|
305
|
-
readEnvString('OPENAI_API_KEY');
|
|
295
|
+
Flag.EASBOT_OUTPUT_TOKEN_MAX; // numeric field, internally dynamic
|
|
296
|
+
readEnvString('OPENAI_API_KEY'); // wraps process.env
|
|
306
297
|
```
|
|
307
298
|
|
|
308
299
|
### 5. Call-site migration table
|
|
309
300
|
|
|
310
|
-
| Module
|
|
311
|
-
|
|
312
|
-
| `provider/auth.ts`
|
|
313
|
-
| `provider/auth.ts`
|
|
314
|
-
| `provider/auth.ts`
|
|
315
|
-
| `provider/provider.ts` | `Instance.state(...)`
|
|
316
|
-
| `config/loader.ts`
|
|
317
|
-
| `provider/models.ts`
|
|
318
|
-
| `config/index.ts`
|
|
301
|
+
| Module | Pre-V3 | V3 | V4 (this refactor) |
|
|
302
|
+
| ---------------------- | ---------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|
|
303
|
+
| `provider/auth.ts` | `Instance.state(...)` | `getIInstanceProvider().state(init)` | `lazyAsync(init)` + module-level `_pluginAuthRegistry` |
|
|
304
|
+
| `provider/auth.ts` | `Auth.set(providerId, info)` | `Auth.set(...)` calls `@easbot/utils.Auth` directly (moved to utils) | `Auth.set(...)` calls `@easbot/utils.Auth` directly (moved to utils) |
|
|
305
|
+
| `provider/auth.ts` | `Plugin.definitions()` | `getIPluginProvider().definitions()` | dependency removed; replaced by `registerPluginAuthProvider()` entry injection |
|
|
306
|
+
| `provider/provider.ts` | `Instance.state(...)` | `getIInstanceProvider().state(init)` | `lazyAsync(createState)` (module-level per-process singleton) |
|
|
307
|
+
| `config/loader.ts` | `Instance.state(...)` | `getIInstanceProvider().state(init)` | `lazyAsync(createState)` (module-level per-process singleton) |
|
|
308
|
+
| `provider/models.ts` | `Global.Path.cache` | `getIGlobalPathProvider().cache` | (same as V3) |
|
|
309
|
+
| `config/index.ts` | `Config.get()` | `getIConfigProvider().get()` | (same as V3) |
|
|
319
310
|
|
|
320
311
|
**V4 refactor motivation**: `IInstanceProvider.state(init)` couples "caching" with "Instance abstraction",
|
|
321
312
|
but state caching is fundamentally a **per-process singleton with explicit reset** — independent of
|
|
322
313
|
`Instance.directory`. After sinking to `@easbot/utils.lazyAsync()`:
|
|
314
|
+
|
|
323
315
|
- **Decoupled**: `IInstanceProvider` shrinks to 2 methods (`getDirectory` / `getWorktree`), single responsibility
|
|
324
316
|
- **Unified**: every subsystem needing state caching (skills / mcp / plugin / etc.) reuses the same utility
|
|
325
317
|
- **Testable**: `lazyAsync().reset()` is more direct than mocking a state factory
|
|
@@ -359,16 +351,16 @@ Test files are in `tests/`:
|
|
|
359
351
|
|
|
360
352
|
**All 75 tests currently green** (across 3 test files). Coverage breakdown:
|
|
361
353
|
|
|
362
|
-
| Category
|
|
363
|
-
|
|
364
|
-
| AdapterRegistry interfaces (V4 new)
|
|
365
|
-
| Provider constants
|
|
366
|
-
| ProviderAuth lazyAsync behavior (V4 new) | 3
|
|
367
|
-
| Model type export stability
|
|
368
|
-
| Env / Flag namespace static fields
|
|
369
|
-
| LLMConfig schema
|
|
370
|
-
| ProviderConfig schema
|
|
371
|
-
| ProviderAuthMethod schema
|
|
354
|
+
| Category | Case count | Validation |
|
|
355
|
+
| ---------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
356
|
+
| AdapterRegistry interfaces (V4 new) | 11 | 4 Provider interface contracts / `setAdapterRegistry` injection / `hasAdapterRegistry` boolean / fail-fast throw / static reader functions |
|
|
357
|
+
| Provider constants | 11 | DEFAULT_ENABLED_PROVIDERS / CUSTOM_PROVIDER_DEFINITIONS / PROVIDER_DISPLAY_NAMES |
|
|
358
|
+
| ProviderAuth lazyAsync behavior (V4 new) | 3 | `registerPluginAuthProvider` triggers `_state.reset()` / `clearPluginAuthProviders` resets cache / `ProviderAuth.resetState()` clears cache |
|
|
359
|
+
| Model type export stability | 6 | RerankInput/Result/Response + Entity/Relation/GraphInput + Note/MemorySummary |
|
|
360
|
+
| Env / Flag namespace static fields | 6 | Env mirrors process.env keys / Flag contains LLM-package internal flags / reader function signatures (empty string vs undefined) |
|
|
361
|
+
| LLMConfig schema | 4 | Empty object passes / Complete fields pass / Invalid model rejected / Non-array enabled_providers rejected |
|
|
362
|
+
| ProviderConfig schema | 3 | Minimal config passes / partial design (all fields optional) / options.apiKey type validation |
|
|
363
|
+
| ProviderAuthMethod schema | 4 | api / oauth types pass / Invalid type rejected / Missing label rejected |
|
|
372
364
|
|
|
373
365
|
**Full integration test boundary**: After the AdapterRegistry decoupling, the llm package can mock all 4 Providers independently, and a complete end-to-end flow of `Provider.list / getModel / parseModel` no longer depends on the agent package. Follow-up task: when the agent package switches LLM implementation, add cross-package integration tests (verifying that real injected Providers match the llm-package contract).
|
|
374
366
|
|
|
@@ -407,17 +399,19 @@ pnpm --filter @easbot/llm test:run
|
|
|
407
399
|
|
|
408
400
|
## Differences from Historical Versions
|
|
409
401
|
|
|
410
|
-
| Version
|
|
411
|
-
|
|
412
|
-
| **Early placeholder (@easbot/types residue)** | Only a 5-line index.ts comment, no business capability
|
|
413
|
-
| **V3 (ADR 0070)**
|
|
414
|
-
| **V4 (ADR 0071)**
|
|
402
|
+
| Version | Key Changes |
|
|
403
|
+
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
404
|
+
| **Early placeholder (@easbot/types residue)** | Only a 5-line index.ts comment, no business capability |
|
|
405
|
+
| **V3 (ADR 0070)** | Added `src/interfaces.ts` (6 Provider interfaces + AdapterRegistry) + `src/config/` three-file module; refactored provider/{auth,models,provider,transform}.ts to use AdapterRegistry throughout |
|
|
406
|
+
| **V4 (ADR 0071)** | Removed `IInstanceProvider.state()` (decomposed to `@easbot/utils.lazyAsync()`) + removed `IPluginProvider` dependency (now module-level `_pluginAuthRegistry` + `ProviderAuth.registerPluginAuthProvider()` entry); Provider interfaces reduced from 6 to 5 |
|
|
415
407
|
|
|
416
408
|
**V3 → V4 refactor motivation**:
|
|
409
|
+
|
|
417
410
|
- `IInstanceProvider.state()` couples "per-process singleton + explicit reset" with the `Instance.directory` abstraction, but state caching has nothing to do with Instance paths
|
|
418
411
|
- After decomposition to `@easbot/utils.lazyAsync()`, `IInstanceProvider` shrinks to 2 methods (`getDirectory` / `getWorktree`), with clean responsibility
|
|
419
412
|
- `ProviderAuth` no longer depends on `IPluginProvider`, instead uses a module-level list + registration entry, with clearer semantics (plugin registration = push to list)
|
|
420
413
|
|
|
421
414
|
See:
|
|
415
|
+
|
|
422
416
|
- [ADR 0070 llm-adapter-registry](../../docs/decisions/0070-llm-adapter-registry.md) — AdapterRegistry injection pattern
|
|
423
|
-
- [ADR 0071 llm-instance-state-decompose](../../docs/decisions/0071-llm-instance-state-decompose.md) — state decomposition
|
|
417
|
+
- [ADR 0071 llm-instance-state-decompose](../../docs/decisions/0071-llm-instance-state-decompose.md) — state decomposition
|
package/README.md
CHANGED
|
@@ -6,11 +6,10 @@
|
|
|
6
6
|
|
|
7
7
|
## 版本
|
|
8
8
|
|
|
9
|
-
v0.3.
|
|
10
|
-
|
|
9
|
+
v0.3.29
|
|
11
10
|
## 当前状态(V4 重构后)
|
|
12
11
|
|
|
13
|
-
本包已从 `@easbot/types` 的早期占位实现演化为承载
|
|
12
|
+
本包已从 `@easbot/types` 的早期占位实现演化为承载 _*provider/* + model/_ 两套核心模块** 的生产级 AI 网关层:
|
|
14
13
|
|
|
15
14
|
- ✅ **`src/provider/`**(7 文件):完整的工业级 provider 抽象
|
|
16
15
|
- `Provider` 命名空间 —— 25+ 内置 SDK(OpenAI / Anthropic / Azure / Bedrock / Vertex / OpenRouter / Copilot / Ollama / 本地模型等)的动态加载器、`ModelsDev` catalog 合并、模型缓存、SDK 实例池化
|
|
@@ -118,7 +117,7 @@ const reranked = await RerankProvider.rerank({
|
|
|
118
117
|
|
|
119
118
|
// 图谱实体提取
|
|
120
119
|
const graph = await GraphProvider.generateGraph({
|
|
121
|
-
chunks: ['chunk1...', 'chunk2...', '...'],
|
|
120
|
+
chunks: ['chunk1...', 'chunk2...', '...'], // 任意长度数组
|
|
122
121
|
prompt: { maxChunks: 5, maxConcurrency: 3 }, // v0.8:per-call 切片 + 3 并发
|
|
123
122
|
});
|
|
124
123
|
// graph.entities / relations / summary 直接入库
|
|
@@ -190,14 +189,8 @@ export {
|
|
|
190
189
|
PROVIDER_DISPLAY_NAMES,
|
|
191
190
|
} from './provider/definition';
|
|
192
191
|
|
|
193
|
-
// 顶层函数
|
|
194
|
-
export { initModelsRefresh } from './provider/models';
|
|
195
|
-
|
|
196
192
|
// 自研 GitHub Copilot SDK
|
|
197
|
-
export {
|
|
198
|
-
createOpenaiCompatible,
|
|
199
|
-
openaiCompatible,
|
|
200
|
-
} from './provider/sdk/copilot';
|
|
193
|
+
export { createOpenaiCompatible, openaiCompatible } from './provider/sdk/copilot';
|
|
201
194
|
export type {
|
|
202
195
|
OpenaiCompatibleProvider,
|
|
203
196
|
OpenaiCompatibleProviderSettings,
|
|
@@ -231,17 +224,14 @@ V4 重构后,`Provider` / `ModelsDev` / `ProviderAuth` / `ProviderTransform` 命
|
|
|
231
224
|
agent 包启动时调用一次 `setAdapterRegistry(...)`,注入 4 个 Provider 实现:
|
|
232
225
|
|
|
233
226
|
```typescript
|
|
234
|
-
import {
|
|
235
|
-
setAdapterRegistry,
|
|
236
|
-
type AdapterRegistry,
|
|
237
|
-
} from '@easbot/llm';
|
|
227
|
+
import { setAdapterRegistry, type AdapterRegistry } from '@easbot/llm';
|
|
238
228
|
|
|
239
229
|
// 在 agent 包启动入口处(例如 Instance.provide 之前)
|
|
240
230
|
setAdapterRegistry({
|
|
241
|
-
config: Config,
|
|
242
|
-
instance: Instance,
|
|
243
|
-
global: Global.Path,
|
|
244
|
-
installation: Installation,
|
|
231
|
+
config: Config, // IConfigProvider — get / provider
|
|
232
|
+
instance: Instance, // IInstanceProvider — getDirectory / getWorktree
|
|
233
|
+
global: Global.Path, // IGlobalPathProvider — cache / data / config
|
|
234
|
+
installation: Installation, // IInstallationProvider — getVersion
|
|
245
235
|
// V4 起 Auth 已下沉到 `@easbot/utils.Auth`,不再通过 AdapterRegistry 注入。
|
|
246
236
|
// LLM 包内部直接 `import { Auth } from '@easbot/utils'` 调用即可。
|
|
247
237
|
} satisfies AdapterRegistry);
|
|
@@ -258,14 +248,15 @@ Call setAdapterRegistry({ config: ... }) before using LLM.
|
|
|
258
248
|
|
|
259
249
|
### 2. 4 个 Provider 接口契约
|
|
260
250
|
|
|
261
|
-
| 接口
|
|
262
|
-
|
|
263
|
-
| `IConfigProvider`
|
|
264
|
-
| `IInstanceProvider`
|
|
265
|
-
| `IGlobalPathProvider`
|
|
266
|
-
| `IInstallationProvider` | `getVersion(): string`
|
|
251
|
+
| 接口 | 方法 | 原 agent 模块 | 用途 |
|
|
252
|
+
| ----------------------- | ------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------- |
|
|
253
|
+
| `IConfigProvider` | `get<T>(): Promise<T>` / `provider<T>(id): Promise<T \| undefined>` | `Config` | 用户 `~/.config/easbot/config.json` 的 llm 块(whitelist / blacklist / variant override) |
|
|
254
|
+
| `IInstanceProvider` | `getDirectory(): string` / `getWorktree(): string` | `Instance` | 实例路径与 worktree 信息 |
|
|
255
|
+
| `IGlobalPathProvider` | `cache: string` / `data: string` / `config: string` | `Global.Path` | 模型快照缓存目录 / 用户数据目录 / 全局配置目录 |
|
|
256
|
+
| `IInstallationProvider` | `getVersion(): string` | `Installation` | User-Agent / 兼容性检查 / 版本信息 |
|
|
267
257
|
|
|
268
258
|
> **V4 变更**:`IInstanceProvider.state(init)` 与 `IPluginProvider` 已被**拆分下沉**(ADR 0071)。
|
|
259
|
+
>
|
|
269
260
|
> - Provider 内部 state 缓存改用 `@easbot/utils.lazyAsync(init)`(per-process 单例 + 显式 reset)
|
|
270
261
|
> - Plugin 注册通过模块级 `_pluginAuthRegistry: Map<providerId, methods[]>` + `ProviderAuth.registerPluginAuthProvider()` 入口注入
|
|
271
262
|
|
|
@@ -279,7 +270,7 @@ V3 新增 `src/config/` 模块,仿 `packages/gateway/src/config/` 模式:
|
|
|
279
270
|
```typescript
|
|
280
271
|
import { Config, LLMConfig } from '@easbot/llm';
|
|
281
272
|
|
|
282
|
-
const cfg = await Config.get();
|
|
273
|
+
const cfg = await Config.get(); // 走注入或 fallback loader
|
|
283
274
|
const openaiCfg = await Config.provider('openai');
|
|
284
275
|
|
|
285
276
|
// Schema 校验(可单独使用)
|
|
@@ -300,27 +291,28 @@ const parsed = LLMConfig.parse({
|
|
|
300
291
|
|
|
301
292
|
```typescript
|
|
302
293
|
import { Flag, readEnvString, readFlagBool } from '@easbot/llm';
|
|
303
|
-
import { Env } from '@easbot/llm';
|
|
294
|
+
import { Env } from '@easbot/llm'; // 等价于 import { Env } from '@easbot/utils'
|
|
304
295
|
|
|
305
|
-
Flag.EASBOT_OUTPUT_TOKEN_MAX;
|
|
306
|
-
readEnvString('OPENAI_API_KEY');
|
|
296
|
+
Flag.EASBOT_OUTPUT_TOKEN_MAX; // 数值字段,内部动态计算
|
|
297
|
+
readEnvString('OPENAI_API_KEY'); // 包装 process.env
|
|
307
298
|
```
|
|
308
299
|
|
|
309
300
|
### 5. 调用点改造对照表
|
|
310
301
|
|
|
311
|
-
| 模块
|
|
312
|
-
|
|
313
|
-
| `provider/auth.ts`
|
|
314
|
-
| `provider/auth.ts`
|
|
315
|
-
| `provider/auth.ts`
|
|
316
|
-
| `provider/provider.ts` | `Instance.state(...)`
|
|
317
|
-
| `config/loader.ts`
|
|
318
|
-
| `provider/models.ts`
|
|
319
|
-
| `config/index.ts`
|
|
302
|
+
| 模块 | V3 之前 | V3 | V4(本次重构) |
|
|
303
|
+
| ---------------------- | ---------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- |
|
|
304
|
+
| `provider/auth.ts` | `Instance.state(...)` | `getIInstanceProvider().state(init)` | `lazyAsync(init)` + `_pluginAuthRegistry` 模块级 list |
|
|
305
|
+
| `provider/auth.ts` | `Auth.set(providerId, info)` | `Auth.set(...)` 直接调用 `@easbot/utils.Auth`(下沉到 utils) | `Auth.set(...)` 直接调用 `@easbot/utils.Auth`(下沉到 utils) |
|
|
306
|
+
| `provider/auth.ts` | `Plugin.definitions()` | `getIPluginProvider().definitions()` | 删除依赖,改用 `registerPluginAuthProvider()` 入口注入 |
|
|
307
|
+
| `provider/provider.ts` | `Instance.state(...)` | `getIInstanceProvider().state(init)` | `lazyAsync(createState)`(模块级 per-process 单例) |
|
|
308
|
+
| `config/loader.ts` | `Instance.state(...)` | `getIInstanceProvider().state(init)` | `lazyAsync(createState)`(模块级 per-process 单例) |
|
|
309
|
+
| `provider/models.ts` | `Global.Path.cache` | `getIGlobalPathProvider().cache` | (同 V3) |
|
|
310
|
+
| `config/index.ts` | `Config.get()` | `getIConfigProvider().get()` | (同 V3) |
|
|
320
311
|
|
|
321
312
|
**V4 重构动机**:`IInstanceProvider.state(init)` 把 "缓存" 与 "Instance 抽象" 耦合在一起,
|
|
322
313
|
但 state 缓存本质上是 **per-process 单例 + 显式 reset**,与 Instance.directory 无关。
|
|
323
314
|
下层到 `@easbot/utils.lazyAsync()` 后:
|
|
315
|
+
|
|
324
316
|
- **解耦**:`IInstanceProvider` 只剩 2 个方法(getDirectory / getWorktree),职责清晰
|
|
325
317
|
- **统一**:Project 所有需要 state 缓存的子系统(skills / mcp / plugin 等)复用同一工具
|
|
326
318
|
- **可测**:`lazyAsync().reset()` 比 mock 一个 state factory 更直接
|
|
@@ -360,16 +352,16 @@ pnpm --filter @easbot/llm test:run
|
|
|
360
352
|
|
|
361
353
|
**当前 75 个测试全绿**(3 test files)。覆盖范围:
|
|
362
354
|
|
|
363
|
-
| 测试大类
|
|
364
|
-
|
|
365
|
-
| AdapterRegistry 接口(V4 新增)
|
|
366
|
-
| Provider 常量纯函数
|
|
367
|
-
| ProviderAuth lazyAsync 行为(V4 新增) | 3
|
|
368
|
-
| 模型类型导出稳定性
|
|
369
|
-
| Env / Flag namespace 静态字段
|
|
370
|
-
| LLMConfig schema
|
|
371
|
-
| ProviderConfig schema
|
|
372
|
-
| ProviderAuthMethod schema
|
|
355
|
+
| 测试大类 | 覆盖 case 数 | 验证要点 |
|
|
356
|
+
| -------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
357
|
+
| AdapterRegistry 接口(V4 新增) | 11 | 4 Provider 接口契约 / `setAdapterRegistry` 注入 / `hasAdapterRegistry` 布尔 / fail-fast 抛错 / 静态读取函数 |
|
|
358
|
+
| Provider 常量纯函数 | 11 | DEFAULT_ENABLED_PROVIDERS / CUSTOM_PROVIDER_DEFINITIONS / PROVIDER_DISPLAY_NAMES |
|
|
359
|
+
| ProviderAuth lazyAsync 行为(V4 新增) | 3 | `registerPluginAuthProvider` 触发 `_state.reset()` / `clearPluginAuthProviders` 重置缓存 / `ProviderAuth.resetState()` 清空缓存 |
|
|
360
|
+
| 模型类型导出稳定性 | 6 | RerankInput/Result/Response + Entity/Relation/GraphInput + Note/MemorySummary |
|
|
361
|
+
| Env / Flag namespace 静态字段 | 6 | Env 镜像 process.env / Flag 包含 LLM 包内部 flag / 读取函数签名(空字符串 vs undefined) |
|
|
362
|
+
| LLMConfig schema | 4 | 空对象通过 / 完整字段通过 / 非法 model 拒绝 / 非数组 enabled_providers 拒绝 |
|
|
363
|
+
| ProviderConfig schema | 3 | 最小 config 通过 / partial 设计(所有字段可选) / options.apiKey 类型校验 |
|
|
364
|
+
| ProviderAuthMethod schema | 4 | api / oauth 类型通过 / 非法 type 拒绝 / 缺 label 拒绝 |
|
|
373
365
|
|
|
374
366
|
**完整集成测试边界**:AdapterRegistry 解耦后,llm 包可独立 mock 全部 4 个 Provider,完整跑 `Provider.list / getModel / parseModel` 的端到端流程不依赖 agent 包。后续任务:在 agent 包切换 LLM 实现时,补跨包集成测试(验证 setAdapterRegistry 真实注入的 Provider 与 llm 包契约匹配)。
|
|
375
367
|
|
|
@@ -408,17 +400,19 @@ pnpm --filter @easbot/llm test:run
|
|
|
408
400
|
|
|
409
401
|
## 与历史版本的差异
|
|
410
402
|
|
|
411
|
-
| 版本
|
|
412
|
-
|
|
413
|
-
| **早期占位(@easbot/types 残留)** | 仅 5 行注释的 index.ts,无业务能力
|
|
414
|
-
| **V3(ADR 0070)**
|
|
415
|
-
| **V4(ADR 0071)**
|
|
403
|
+
| 版本 | 关键差异 |
|
|
404
|
+
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
405
|
+
| **早期占位(@easbot/types 残留)** | 仅 5 行注释的 index.ts,无业务能力 |
|
|
406
|
+
| **V3(ADR 0070)** | 新增 `src/interfaces.ts`(6 Provider 接口 + AdapterRegistry)+ `src/config/` 三文件模块;重构 provider/{auth,models,provider,transform}.ts 全部走 AdapterRegistry |
|
|
407
|
+
| **V4(ADR 0071)** | 删除 `IInstanceProvider.state()`(下沉到 `@easbot/utils.lazyAsync()`)+ 删除 `IPluginProvider` 依赖(改用模块级 `_pluginAuthRegistry` + `ProviderAuth.registerPluginAuthProvider()` 入口);Provider 接口 6→5 个 |
|
|
416
408
|
|
|
417
409
|
**V3 → V4 重构动机**:
|
|
410
|
+
|
|
418
411
|
- `IInstanceProvider.state()` 把"per-process 单例 + 显式 reset"与 `Instance.directory` 抽象耦合在一起,但 state 缓存与 Instance 路径无关
|
|
419
412
|
- 缓存下沉到 `@easbot/utils.lazyAsync()` 后,`IInstanceProvider` 收缩为 2 个方法(`getDirectory` / `getWorktree`),职责清晰
|
|
420
413
|
- `ProviderAuth` 不再依赖 `IPluginProvider`,改用模块级 list + 注册入口,概念清晰化(plugin 注册 = 推入 list)
|
|
421
414
|
|
|
422
415
|
详见:
|
|
416
|
+
|
|
423
417
|
- [ADR 0070 llm-adapter-registry](../../docs/decisions/0070-llm-adapter-registry.md) —— AdapterRegistry 注入模式
|
|
424
|
-
- [ADR 0071 llm-instance-state-decompose](../../docs/decisions/0071-llm-instance-state-decompose.md) —— state 拆分下沉
|
|
418
|
+
- [ADR 0071 llm-instance-state-decompose](../../docs/decisions/0071-llm-instance-state-decompose.md) —— state 拆分下沉
|
|
@@ -10,6 +10,11 @@ Generate ONE combined summary from MULTIPLE knowledge graph entities.
|
|
|
10
10
|
- NEVER guess entity properties
|
|
11
11
|
- If input has no valuable information: ONLY output "No relevant knowledge found."
|
|
12
12
|
|
|
13
|
+
## Length Cap (HARD CONSTRAINT)
|
|
14
|
+
Your **final output MUST be ≤ {{maxChars}} characters** (including all markdown, punctuation, whitespace, and section headings).
|
|
15
|
+
- This cap is derived from the underlying `maxOutputTokens` limit with a safety buffer — exceeding it will trigger a hard truncation by the SDK that leaves your output incomplete.
|
|
16
|
+
- When in doubt, prioritize fewer entities over partial coverage of all.
|
|
17
|
+
|
|
13
18
|
## Input Format
|
|
14
19
|
```
|
|
15
20
|
[Entity 1]
|
|
@@ -10,6 +10,11 @@ Synthesize document chunks into a concise summary relevant to the query.
|
|
|
10
10
|
- NEVER guess or assume user needs
|
|
11
11
|
- If input has no valuable information: ONLY output "No relevant knowledge found."
|
|
12
12
|
|
|
13
|
+
## Length Cap (HARD CONSTRAINT)
|
|
14
|
+
Your **final output MUST be ≤ {{maxChars}} characters** (including all markdown, punctuation, whitespace, and section headings).
|
|
15
|
+
- This cap is derived from the underlying `maxOutputTokens` limit with a safety buffer — exceeding it will trigger a hard truncation by the SDK that leaves your output incomplete.
|
|
16
|
+
- When in doubt, prioritize shorter, denser sentences over verbose explanations. Drop optional sections (Key Insights, Entity & Relation Map) before cutting core facts.
|
|
17
|
+
|
|
13
18
|
## Priority Score
|
|
14
19
|
Priority = 0.6 × relevance + 0.4 × recency
|
|
15
20
|
- Priority > 0.6: high-priority (include)
|
|
@@ -10,6 +10,11 @@ Synthesize memory facts into a concise summary relevant to the query.
|
|
|
10
10
|
- NEVER guess or assume user intent
|
|
11
11
|
- If input has no valuable information: ONLY output "No relevant memory found."
|
|
12
12
|
|
|
13
|
+
## Length Cap (HARD CONSTRAINT)
|
|
14
|
+
Your **final output MUST be ≤ {{maxChars}} characters** (including all markdown, punctuation, whitespace, and section headings).
|
|
15
|
+
- This cap is derived from the underlying `maxOutputTokens` limit with a safety buffer — exceeding it will trigger a hard truncation by the SDK that leaves your output incomplete.
|
|
16
|
+
- When in doubt, prioritize shorter, denser sentences over verbose explanations. Drop optional sections (Key Insights, Entity & Relation Map) before cutting core facts.
|
|
17
|
+
|
|
13
18
|
## Priority Score
|
|
14
19
|
Priority = 0.4 × relevance + 0.3 × recency + 0.3 × importance
|
|
15
20
|
- Priority > 0.6: high-priority (include)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkKFESJR3T_cjs=require('./chunk-KFESJR3T.cjs'),providerUtils=require('@ai-sdk/provider-utils'),utils=require('@easbot/utils'),provider=require('@ai-sdk/provider'),zod=require('zod'),v4=require('zod/v4');function D(n){return n?.providerOptions?.copilot??{}}function oe(n){let r=[];for(let{role:b,content:_,...k}of n){let h=D({...k});switch(b){case "system":{r.push({role:"system",content:_,...h});break}case "user":{let p=_[0];if(_.length===1&&p?.type==="text"){r.push({role:"user",content:p.text,...D(p)});break}r.push({role:"user",content:_.map(i=>{let d=D(i);switch(i.type){case "text":return {type:"text",text:i.text,...d};case "file":if(i.mediaType.startsWith("image/")){let m=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return {type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${m};base64,${providerUtils.convertToBase64(i.data)}`},...d}}else throw new provider.UnsupportedFunctionalityError({functionality:`file part media type ${i.mediaType}`});default:throw new provider.UnsupportedFunctionalityError({functionality:`part type ${i.type}`})}}),...h});break}case "assistant":{let p="",i,d,m=[];for(let o of _){let C=D(o),u=o.providerOptions?.copilot?.reasoningOpaque;switch(u&&!d&&(d=u),o.type){case "text":{p+=o.text;break}case "reasoning":{o.text&&(i=o.text);break}case "tool-call":{m.push({id:o.toolCallId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.input)},...C});break}}}r.push({role:"assistant",content:p||null,tool_calls:m.length>0?m:void 0,reasoning_text:d?i:void 0,reasoning_opaque:d,...h});break}case "tool":{for(let p of _){if(p.type==="tool-approval-response")continue;let i=p.output,d;switch(i.type){case "text":case "error-text":d=i.value;break;case "execution-denied":d=i.reason??"Tool execution denied.";break;case "content":case "json":case "error-json":d=JSON.stringify(i.value);break;default:{d=String(i.value);break}}let m=D(p);r.push({role:"tool",tool_call_id:p.toolCallId,content:d,...m});}break}default:{let p=b;throw new utils.NameErrors.OperationFailedError({message:`Unsupported role: ${String(p)}`,operation:"chat-convert-unsupported-role"})}}}return r}function V({id:n,model:r,created:b}){return {id:n??void 0,modelId:r??void 0,timestamp:b!=null?new Date(b*1e3):void 0}}function B(n){switch(n){case "stop":return {unified:"stop",raw:n||void 0};case "length":return {unified:"length",raw:n||void 0};case "content_filter":return {unified:"content-filter",raw:n||void 0};case "function_call":case "tool_calls":return {unified:"tool-calls",raw:n||void 0};default:return {unified:"other",raw:n||void 0}}}var U=zod.z.object({user:zod.z.string().optional(),reasoningEffort:zod.z.string().optional(),textVerbosity:zod.z.string().optional(),thinking_budget:zod.z.number().optional()});var We=v4.z.object({error:v4.z.object({message:v4.z.string(),type:v4.z.string().nullish(),param:v4.z.any().nullish(),code:v4.z.union([v4.z.string(),v4.z.number()]).nullish()})}),ie={errorSchema:We,errorToMessage:n=>n.error.message};function ae({tools:n,toolChoice:r}){n=(n?.length??0)>0?n:void 0;let b=[];if(n==null)return {tools:void 0,toolChoice:void 0,toolWarnings:b};let _=[];for(let h of n)h.type==="provider"?b.push({type:"unsupported",feature:h.name||"unknown-tool"}):_.push({type:"function",function:{name:h.name,description:h.description,parameters:h.inputSchema}});if(r==null)return {tools:_,toolChoice:void 0,toolWarnings:b};let k=r.type;switch(k){case "auto":case "none":case "required":return {tools:_,toolChoice:k,toolWarnings:b};case "tool":return {tools:_,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:b};default:{let h=k;throw new provider.UnsupportedFunctionalityError({functionality:`tool choice type: ${h}`})}}}var H=class{constructor(r,b){chunkKFESJR3T_cjs.a(this,"specificationVersion","v3");chunkKFESJR3T_cjs.a(this,"supportsStructuredOutputs");chunkKFESJR3T_cjs.a(this,"modelId");chunkKFESJR3T_cjs.a(this,"config");chunkKFESJR3T_cjs.a(this,"failedResponseHandler");chunkKFESJR3T_cjs.a(this,"chunkSchema");this.modelId=r,this.config=b;let _=b.errorStructure??ie;this.chunkSchema=Ge(_.errorSchema),this.failedResponseHandler=providerUtils.createJsonErrorResponseHandler(_),this.supportsStructuredOutputs=b.supportsStructuredOutputs??false;}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0]?.trim()??"openai"}get supportedUrls(){return this.config.supportedUrls?.()??{}}async getArgs({prompt:r,maxOutputTokens:b,temperature:_,topP:k,topK:h,frequencyPenalty:p,presencePenalty:i,providerOptions:d,stopSequences:m,responseFormat:o,seed:C,toolChoice:u,tools:a}){let s=[],c=Object.assign(await providerUtils.parseProviderOptions({provider:"copilot",providerOptions:d,schema:U})??{},await providerUtils.parseProviderOptions({provider:this.providerOptionsName,providerOptions:d,schema:U})??{});h!=null&&s.push({type:"unsupported",feature:"topK"}),o?.type==="json"&&o.schema!=null&&!this.supportsStructuredOutputs&&s.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let{tools:g,toolChoice:I,toolWarnings:l}=ae({tools:a,toolChoice:u});return {args:{model:this.modelId,user:c.user,max_tokens:b,temperature:_,top_p:k,frequency_penalty:p,presence_penalty:i,response_format:o?.type==="json"?this.supportsStructuredOutputs===true&&o.schema!=null?{type:"json_schema",json_schema:{schema:o.schema,name:o.name??"response",description:o.description}}:{type:"json_object"}:void 0,stop:m,seed:C,...Object.fromEntries(Object.entries(d?.[this.providerOptionsName]??{}).filter(([t])=>!Object.keys(U.shape).includes(t))),reasoning_effort:c.reasoningEffort,verbosity:c.textVerbosity,messages:oe(r),tools:g,tool_choice:I,thinking_budget:c.thinking_budget},warnings:[...s,...l]}}async doGenerate(r){let{args:b,warnings:_}=await this.getArgs({...r}),k=JSON.stringify(b),{responseHeaders:h,value:p,rawValue:i}=await providerUtils.postJsonToApi({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:providerUtils.combineHeaders(this.config.headers(),r.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:providerUtils.createJsonResponseHandler(Je),abortSignal:r.abortSignal,fetch:this.config.fetch}),d=p.choices?.[0];if(!d)return {content:[],finishReason:{unified:"error",raw:void 0},usage:{inputTokens:{total:p.usage?.prompt_tokens??void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:p.usage?.completion_tokens??void 0,text:p.usage?.completion_tokens??void 0,reasoning:void 0}},providerMetadata:{},request:{body:k},response:{...V(p),headers:h,body:i},warnings:_};let m=[],o=d.message.content;o!=null&&o.length>0&&m.push({type:"text",text:o,providerMetadata:d.message.reasoning_opaque?{copilot:{reasoningOpaque:d.message.reasoning_opaque}}:void 0});let C=d.message.reasoning_text;if(C!=null&&C.length>0&&m.push({type:"reasoning",text:C,providerMetadata:d.message.reasoning_opaque?{copilot:{reasoningOpaque:d.message.reasoning_opaque}}:void 0}),d.message.tool_calls!=null)for(let s of d.message.tool_calls)m.push({type:"tool-call",toolCallId:s.id??providerUtils.generateId(),toolName:s.function.name,input:s.function.arguments,providerMetadata:d.message.reasoning_opaque?{copilot:{reasoningOpaque:d.message.reasoning_opaque}}:void 0});let u={[this.providerOptionsName]:{},...await this.config.metadataExtractor?.extractMetadata?.({parsedBody:i})},a=p.usage?.completion_tokens_details;if(a?.accepted_prediction_tokens!=null){let s=this.providerOptionsName;u[s]&&(u[s].acceptedPredictionTokens=a?.accepted_prediction_tokens);}if(a?.rejected_prediction_tokens!=null){let s=this.providerOptionsName;u[s]&&(u[s].rejectedPredictionTokens=a?.rejected_prediction_tokens);}return {content:m,finishReason:B(d?.finish_reason),usage:{inputTokens:{total:p.usage?.prompt_tokens??void 0,noCache:void 0,cacheRead:p.usage?.prompt_tokens_details?.cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:p.usage?.completion_tokens??void 0,text:void 0,reasoning:p.usage?.completion_tokens_details?.reasoning_tokens??void 0},raw:p.usage??void 0},providerMetadata:u,request:{body:k},response:{...V(p),headers:h,body:i},warnings:_}}async doStream(r){let{args:b,warnings:_}=await this.getArgs({...r}),k={...b,stream:true,stream_options:this.config.includeUsage?{include_usage:true}:void 0},h=this.config.metadataExtractor?.createStreamExtractor(),{responseHeaders:p,value:i}=await providerUtils.postJsonToApi({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:providerUtils.combineHeaders(this.config.headers(),r.headers),body:k,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:providerUtils.createEventSourceResponseHandler(this.chunkSchema),abortSignal:r.abortSignal,fetch:this.config.fetch}),d=[],m={unified:"other",raw:void 0},o={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0},C=true,u=this.providerOptionsName,a=false,s=false,c;return {stream:i.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:_});},transform(g,I){if(r.includeRawChunks&&I.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){m={unified:"error",raw:void 0},I.enqueue({type:"error",error:g.error});return}let l=g.value;if(h?.processChunk(g.rawValue),"error"in l){m={unified:"error",raw:void 0},I.enqueue({type:"error",error:l.error.message});return}if(C&&(C=false,I.enqueue({type:"response-metadata",...V(l)})),l.usage!=null){let{prompt_tokens:w,completion_tokens:q,total_tokens:T,prompt_tokens_details:v,completion_tokens_details:N}=l.usage;o.promptTokens=w??void 0,o.completionTokens=q??void 0,o.totalTokens=T??void 0,N?.reasoning_tokens!=null&&(o.completionTokensDetails.reasoningTokens=N?.reasoning_tokens),N?.accepted_prediction_tokens!=null&&(o.completionTokensDetails.acceptedPredictionTokens=N?.accepted_prediction_tokens),N?.rejected_prediction_tokens!=null&&(o.completionTokensDetails.rejectedPredictionTokens=N?.rejected_prediction_tokens),v?.cached_tokens!=null&&(o.promptTokensDetails.cachedTokens=v?.cached_tokens);}let t=l.choices[0];if(t?.finish_reason!=null&&(m=B(t.finish_reason)),t?.delta==null)return;let y=t.delta;if(y.reasoning_opaque){if(c!=null)throw new provider.InvalidResponseDataError({data:y,message:"Multiple reasoning_opaque values received in a single response. Only one thinking part per response is supported."});c=y.reasoning_opaque;}let L=y.reasoning_text;if(L&&(a||(I.enqueue({type:"reasoning-start",id:"reasoning-0"}),a=true),I.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:L})),y.content&&(a&&!s&&(I.enqueue({type:"reasoning-end",id:"reasoning-0",providerMetadata:c?{copilot:{reasoningOpaque:c}}:void 0}),a=false),s||(I.enqueue({type:"text-start",id:"txt-0",providerMetadata:c?{copilot:{reasoningOpaque:c}}:void 0}),s=true),I.enqueue({type:"text-delta",id:"txt-0",delta:y.content})),y.tool_calls!=null){a&&(I.enqueue({type:"reasoning-end",id:"reasoning-0",providerMetadata:c?{copilot:{reasoningOpaque:c}}:void 0}),a=false);for(let w of y.tool_calls){let q=w.index;if(d[q]==null){if(w.id==null)throw new provider.InvalidResponseDataError({data:w,message:"Expected 'id' to be a string."});if(w.function?.name==null)throw new provider.InvalidResponseDataError({data:w,message:"Expected 'function.name' to be a string."});I.enqueue({type:"tool-input-start",id:w.id,toolName:w.function.name}),d[q]={id:w.id,type:"function",function:{name:w.function.name,arguments:w.function.arguments??""},hasFinished:false};let v=d[q];v.function?.name!=null&&v.function?.arguments!=null&&(v.function.arguments.length>0&&I.enqueue({type:"tool-input-delta",id:v.id,delta:v.function.arguments}),providerUtils.isParsableJson(v.function.arguments)&&(I.enqueue({type:"tool-input-end",id:v.id}),I.enqueue({type:"tool-call",toolCallId:v.id??providerUtils.generateId(),toolName:v.function.name,input:v.function.arguments,providerMetadata:c?{copilot:{reasoningOpaque:c}}:void 0}),v.hasFinished=true));continue}let T=d[q];T.hasFinished||(w.function?.arguments!=null&&(T.function.arguments+=w.function?.arguments??""),I.enqueue({type:"tool-input-delta",id:T.id,delta:w.function.arguments??""}),T.function?.name!=null&&T.function?.arguments!=null&&providerUtils.isParsableJson(T.function.arguments)&&(I.enqueue({type:"tool-input-end",id:T.id}),I.enqueue({type:"tool-call",toolCallId:T.id??providerUtils.generateId(),toolName:T.function.name,input:T.function.arguments,providerMetadata:c?{copilot:{reasoningOpaque:c}}:void 0}),T.hasFinished=true));}}},flush(g){a&&g.enqueue({type:"reasoning-end",id:"reasoning-0",providerMetadata:c?{copilot:{reasoningOpaque:c}}:void 0}),s&&g.enqueue({type:"text-end",id:"txt-0"});for(let l of d.filter(t=>!t.hasFinished))g.enqueue({type:"tool-input-end",id:l.id}),g.enqueue({type:"tool-call",toolCallId:l.id??providerUtils.generateId(),toolName:l.function.name,input:l.function.arguments});let I={[u]:{},...c?{copilot:{reasoningOpaque:c}}:{},...h?.buildMetadata()};o.completionTokensDetails.acceptedPredictionTokens!=null&&I[u]&&(I[u].acceptedPredictionTokens=o.completionTokensDetails.acceptedPredictionTokens),o.completionTokensDetails.rejectedPredictionTokens!=null&&I[u]&&(I[u].rejectedPredictionTokens=o.completionTokensDetails.rejectedPredictionTokens),g.enqueue({type:"finish",finishReason:m,usage:{inputTokens:{total:o.promptTokens,noCache:o.promptTokens!==void 0&&o.promptTokensDetails.cachedTokens!==void 0?o.promptTokens-o.promptTokensDetails.cachedTokens:void 0,cacheRead:o.promptTokensDetails.cachedTokens,cacheWrite:void 0},outputTokens:{total:o.completionTokens,text:void 0,reasoning:o.completionTokensDetails.reasoningTokens},raw:{prompt_tokens:o.promptTokens??null,completion_tokens:o.completionTokens??null,total_tokens:o.totalTokens??null}},providerMetadata:I});}})),request:{body:k},response:{headers:p}}}},ue=zod.z.object({prompt_tokens:zod.z.number().nullish(),completion_tokens:zod.z.number().nullish(),total_tokens:zod.z.number().nullish(),prompt_tokens_details:zod.z.object({cached_tokens:zod.z.number().nullish()}).nullish(),completion_tokens_details:zod.z.object({reasoning_tokens:zod.z.number().nullish(),accepted_prediction_tokens:zod.z.number().nullish(),rejected_prediction_tokens:zod.z.number().nullish()}).nullish()}).nullish(),Je=zod.z.object({id:zod.z.string().nullish(),created:zod.z.number().nullish(),model:zod.z.string().nullish(),choices:zod.z.array(zod.z.object({message:zod.z.object({role:zod.z.literal("assistant").nullish(),content:zod.z.string().nullish(),reasoning_text:zod.z.string().nullish(),reasoning_opaque:zod.z.string().nullish(),tool_calls:zod.z.array(zod.z.object({id:zod.z.string().nullish(),function:zod.z.object({name:zod.z.string(),arguments:zod.z.string()})})).nullish()}),finish_reason:zod.z.string().nullish()})),usage:ue}),Ge=n=>zod.z.union([zod.z.object({id:zod.z.string().nullish(),created:zod.z.number().nullish(),model:zod.z.string().nullish(),choices:zod.z.array(zod.z.object({delta:zod.z.object({role:zod.z.enum(["assistant"]).nullish(),content:zod.z.string().nullish(),reasoning_text:zod.z.string().nullish(),reasoning_opaque:zod.z.string().nullish(),tool_calls:zod.z.array(zod.z.object({index:zod.z.number(),id:zod.z.string().nullish(),function:zod.z.object({name:zod.z.string().nullish(),arguments:zod.z.string().nullish()})})).nullish()}).nullish(),finish_reason:zod.z.string().nullish()})),usage:ue}),n]);var Ke=zod.z.object({error:zod.z.object({message:zod.z.string(),type:zod.z.string().nullish(),param:zod.z.any().nullish(),code:zod.z.union([zod.z.string(),zod.z.number()]).nullish()})}),Z=providerUtils.createJsonErrorResponseHandler({errorSchema:Ke,errorToMessage:n=>n.error.message});var Xe=zod.z.object({code:zod.z.string().nullish(),containerId:zod.z.string()}),Qe=zod.z.object({outputs:zod.z.array(zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("logs"),logs:zod.z.string()}),zod.z.object({type:zod.z.literal("image"),url:zod.z.string()})])).nullish()}),de=zod.z.object({container:zod.z.union([zod.z.string(),zod.z.object({fileIds:zod.z.array(zod.z.string()).optional()})]).optional()});providerUtils.createProviderToolFactoryWithOutputSchema({id:"openai.code_interpreter",inputSchema:Xe,outputSchema:Qe});var ce=zod.z.object({key:zod.z.string(),type:zod.z.enum(["eq","ne","gt","gte","lt","lte"]),value:zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean()])}),me=zod.z.object({type:zod.z.enum(["and","or"]),filters:zod.z.array(zod.z.union([ce,zod.z.lazy(()=>me)]))}),ge=zod.z.object({vectorStoreIds:zod.z.array(zod.z.string()),maxNumResults:zod.z.number().optional(),ranking:zod.z.object({ranker:zod.z.string().optional(),scoreThreshold:zod.z.number().optional()}).optional(),filters:zod.z.union([ce,me]).optional()}),et=zod.z.object({queries:zod.z.array(zod.z.string()),results:zod.z.array(zod.z.object({attributes:zod.z.record(zod.z.string(),zod.z.unknown()),fileId:zod.z.string(),filename:zod.z.string(),score:zod.z.number(),text:zod.z.string()})).nullable()});providerUtils.createProviderToolFactoryWithOutputSchema({id:"openai.file_search",inputSchema:zod.z.object({}),outputSchema:et});var fe=zod.z.object({background:zod.z.enum(["auto","opaque","transparent"]).optional(),inputFidelity:zod.z.enum(["low","high"]).optional(),inputImageMask:zod.z.object({fileId:zod.z.string().optional(),imageUrl:zod.z.string().optional()}).optional(),model:zod.z.string().optional(),moderation:zod.z.enum(["auto"]).optional(),outputCompression:zod.z.number().int().min(0).max(100).optional(),outputFormat:zod.z.enum(["png","jpeg","webp"]).optional(),partialImages:zod.z.number().int().min(0).max(3).optional(),quality:zod.z.enum(["auto","low","medium","high"]).optional(),size:zod.z.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict(),nt=zod.z.object({result:zod.z.string()});providerUtils.createProviderToolFactoryWithOutputSchema({id:"openai.image_generation",inputSchema:zod.z.object({}),outputSchema:nt});var X=zod.z.object({action:zod.z.object({type:zod.z.literal("exec"),command:zod.z.array(zod.z.string()),timeoutMs:zod.z.number().optional(),user:zod.z.string().optional(),workingDirectory:zod.z.string().optional(),env:zod.z.record(zod.z.string(),zod.z.string()).optional()})}),Q=zod.z.object({output:zod.z.string()});providerUtils.createProviderToolFactoryWithOutputSchema({id:"openai.local_shell",inputSchema:X,outputSchema:Q});function be(n,r){return r?r.some(b=>n.startsWith(b)):false}async function Ce({prompt:n,systemMessageMode:r,fileIdPrefixes:b,store:_,hasLocalShellTool:k=false}){let h=[],p=[],i=new Set;for(let{role:d,content:m}of n)switch(d){case "system":{switch(r){case "system":{h.push({role:"system",content:m});break}case "developer":{h.push({role:"developer",content:m});break}case "remove":{p.push({type:"other",message:"system messages are removed for this model"});break}default:{let o=r;throw new utils.NameErrors.OperationFailedError({message:`Unsupported system message mode: ${String(o)}`,operation:"responses-convert-unsupported-system-mode"})}}break}case "user":{h.push({role:"user",content:m.map((o,C)=>{switch(o.type){case "text":return {type:"input_text",text:o.text};case "file":if(o.mediaType.startsWith("image/")){let u=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return {type:"input_image",...o.data instanceof URL?{image_url:o.data.toString()}:typeof o.data=="string"&&be(o.data,b)?{file_id:o.data}:{image_url:`data:${u};base64,${providerUtils.convertToBase64(o.data)}`},detail:o.providerOptions?.openai?.imageDetail}}else {if(o.mediaType==="application/pdf")return o.data instanceof URL?{type:"input_file",file_url:o.data.toString()}:{type:"input_file",...typeof o.data=="string"&&be(o.data,b)?{file_id:o.data}:{filename:o.filename??`part-${C}.pdf`,file_data:`data:application/pdf;base64,${providerUtils.convertToBase64(o.data)}`}};throw new provider.UnsupportedFunctionalityError({functionality:`file part media type ${o.mediaType}`})}default:throw new provider.UnsupportedFunctionalityError({functionality:`part type ${o.type}`})}})});break}case "assistant":{let o={},C={};for(let u of m)switch(u.type){case "text":{h.push({role:"assistant",content:[{type:"output_text",text:u.text}],id:u.providerOptions?.openai?.itemId??void 0});break}case "tool-call":{if(C[u.toolCallId]=u,u.providerExecuted)break;if(k&&u.toolName==="local_shell"){let a=X.parse(u.input);h.push({type:"local_shell_call",call_id:u.toolCallId,id:u.providerOptions?.openai?.itemId??void 0,action:{type:"exec",command:a.action.command,timeout_ms:a.action.timeoutMs,user:a.action.user,working_directory:a.action.workingDirectory,env:a.action.env}});break}h.push({type:"function_call",call_id:u.toolCallId,name:u.toolName,arguments:JSON.stringify(u.input),id:u.providerOptions?.openai?.itemId??void 0});break}case "tool-result":{_?h.push({type:"item_reference",id:u.toolCallId}):p.push({type:"other",message:`Results for OpenAI tool ${u.toolName} are not sent to the API when store is false`});break}case "reasoning":{let a=await providerUtils.parseProviderOptions({provider:"copilot",providerOptions:u.providerOptions,schema:at}),s=a?.itemId;if(s!=null){let c=o[s];if(_)c===void 0&&(h.push({type:"item_reference",id:s}),o[s]={type:"reasoning",id:s,summary:[]});else {let g=[];u.text.length>0?g.push({type:"summary_text",text:u.text}):c!==void 0&&p.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(u)}.`}),c===void 0?(o[s]={type:"reasoning",id:s,encrypted_content:a?.reasoningEncryptedContent,summary:g},h.push(o[s])):c.summary.push(...g);}}else p.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(u)}.`});break}}break}case "tool":{for(let o of m){if(o.type==="tool-approval-response"){if(i.has(o.approvalId))continue;i.add(o.approvalId),_&&h.push({type:"item_reference",id:o.approvalId}),h.push({type:"mcp_approval_response",approval_request_id:o.approvalId,approve:o.approved});continue}let C=o.output;if(C.type==="execution-denied"&&C.providerOptions?.openai?.approvalId)continue;if(k&&o.toolName==="local_shell"&&C.type==="json"){h.push({type:"local_shell_call_output",call_id:o.toolCallId,output:Q.parse(o.output.value).output});break}let u="";switch(C.type){case "text":case "error-text":u=C.value;break;case "execution-denied":u=C.reason??"Tool execution denied.";break;case "content":case "json":case "error-json":u=JSON.stringify(C.value);break}h.push({type:"function_call_output",call_id:o.toolCallId,output:u});}break}default:{let o=d;throw new utils.NameErrors.OperationFailedError({message:`Unsupported role: ${String(o)}`,operation:"responses-convert-unsupported-role"})}}return {input:h,warnings:p}}var at=zod.z.object({itemId:zod.z.string().nullish(),reasoningEncryptedContent:zod.z.string().nullish()});function ee({finishReason:n,hasFunctionCall:r}){switch(n){case void 0:case null:return {unified:r?"tool-calls":"stop",raw:n||void 0};case "max_output_tokens":return {unified:"length",raw:n};case "content_filter":return {unified:"content-filter",raw:n};default:return {unified:r?"tool-calls":"other",raw:n}}}var ke=zod.z.object({filters:zod.z.object({allowedDomains:zod.z.array(zod.z.string()).optional()}).optional(),searchContextSize:zod.z.enum(["low","medium","high"]).optional(),userLocation:zod.z.object({type:zod.z.literal("approximate"),country:zod.z.string().optional(),city:zod.z.string().optional(),region:zod.z.string().optional(),timezone:zod.z.string().optional()}).optional()});providerUtils.createProviderToolFactory({id:"openai.web_search",inputSchema:zod.z.object({action:zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("search"),query:zod.z.string().nullish()}),zod.z.object({type:zod.z.literal("open_page"),url:zod.z.string()}),zod.z.object({type:zod.z.literal("find"),url:zod.z.string(),pattern:zod.z.string()})]).nullish()})});var Ie=zod.z.object({searchContextSize:zod.z.enum(["low","medium","high"]).optional(),userLocation:zod.z.object({type:zod.z.literal("approximate"),country:zod.z.string().optional(),city:zod.z.string().optional(),region:zod.z.string().optional(),timezone:zod.z.string().optional()}).optional()});providerUtils.createProviderToolFactory({id:"openai.web_search_preview",inputSchema:zod.z.object({action:zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("search"),query:zod.z.string().nullish()}),zod.z.object({type:zod.z.literal("open_page"),url:zod.z.string()}),zod.z.object({type:zod.z.literal("find"),url:zod.z.string(),pattern:zod.z.string()})]).nullish()})});function Se({tools:n,toolChoice:r,strictJsonSchema:b}){n=(n?.length??0)>0?n:void 0;let _=[];if(n==null)return {tools:void 0,toolChoice:void 0,toolWarnings:_};let k=[];for(let p of n)switch(p.type){case "function":k.push({type:"function",name:p.name,description:p.description,parameters:p.inputSchema,strict:b});break;case "provider":{switch(p.id){case "openai.file_search":{let i=ge.parse(p.args);k.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case "openai.local_shell":{k.push({type:"local_shell"});break}case "openai.web_search_preview":{let i=Ie.parse(p.args);k.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case "openai.web_search":{let i=ke.parse(p.args);k.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case "openai.code_interpreter":{let i=de.parse(p.args);k.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case "openai.image_generation":{let i=fe.parse(p.args);k.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,moderation:i.moderation,partial_images:i.partialImages,quality:i.quality,output_compression:i.outputCompression,output_format:i.outputFormat,size:i.size});break}}break}default:_.push({type:"unsupported",feature:"unknown-tool"});break}if(r==null)return {tools:k,toolChoice:void 0,toolWarnings:_};let h=r.type;switch(h){case "auto":case "none":case "required":return {tools:k,toolChoice:h,toolWarnings:_};case "tool":return {tools:k,toolChoice:r.toolName==="code_interpreter"||r.toolName==="file_search"||r.toolName==="image_generation"||r.toolName==="web_search_preview"||r.toolName==="web_search"?{type:r.toolName}:{type:"function",name:r.toolName},toolWarnings:_};default:{let p=h;throw new provider.UnsupportedFunctionalityError({functionality:`tool choice type: ${p}`})}}}var Oe=zod.z.object({type:zod.z.literal("web_search_call"),id:zod.z.string(),status:zod.z.string(),action:zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("search"),query:zod.z.string().nullish()}),zod.z.object({type:zod.z.literal("open_page"),url:zod.z.string()}),zod.z.object({type:zod.z.literal("find"),url:zod.z.string(),pattern:zod.z.string()})]).nullish()}),Me=zod.z.object({type:zod.z.literal("file_search_call"),id:zod.z.string(),queries:zod.z.array(zod.z.string()),results:zod.z.array(zod.z.object({attributes:zod.z.record(zod.z.string(),zod.z.unknown()),file_id:zod.z.string(),filename:zod.z.string(),score:zod.z.number(),text:zod.z.string()})).nullish()}),we=zod.z.object({type:zod.z.literal("code_interpreter_call"),id:zod.z.string(),code:zod.z.string().nullable(),container_id:zod.z.string(),outputs:zod.z.array(zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("logs"),logs:zod.z.string()}),zod.z.object({type:zod.z.literal("image"),url:zod.z.string()})])).nullable()}),Re=zod.z.object({type:zod.z.literal("local_shell_call"),id:zod.z.string(),call_id:zod.z.string(),action:zod.z.object({type:zod.z.literal("exec"),command:zod.z.array(zod.z.string()),timeout_ms:zod.z.number().optional(),user:zod.z.string().optional(),working_directory:zod.z.string().optional(),env:zod.z.record(zod.z.string(),zod.z.string()).optional()})}),Te=zod.z.object({type:zod.z.literal("image_generation_call"),id:zod.z.string(),result:zod.z.string()}),je=20,Ae=zod.z.array(zod.z.object({token:zod.z.string(),logprob:zod.z.number(),top_logprobs:zod.z.array(zod.z.object({token:zod.z.string(),logprob:zod.z.number()}))})),G=class{constructor(r,b){chunkKFESJR3T_cjs.a(this,"specificationVersion","v3");chunkKFESJR3T_cjs.a(this,"modelId");chunkKFESJR3T_cjs.a(this,"config");chunkKFESJR3T_cjs.a(this,"supportedUrls",{"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]});this.modelId=r,this.config=b;}get provider(){return this.config.provider}async getArgs({maxOutputTokens:r,temperature:b,stopSequences:_,topP:k,topK:h,presencePenalty:p,frequencyPenalty:i,seed:d,prompt:m,providerOptions:o,tools:C,toolChoice:u,responseFormat:a}){let s=[],c=Dt(this.modelId);h!=null&&s.push({type:"unsupported",feature:"topK"}),d!=null&&s.push({type:"unsupported",feature:"seed"}),p!=null&&s.push({type:"unsupported",feature:"presencePenalty"}),i!=null&&s.push({type:"unsupported",feature:"frequencyPenalty"}),_!=null&&s.push({type:"unsupported",feature:"stopSequences"});let g=await providerUtils.parseProviderOptions({provider:"copilot",providerOptions:o,schema:Wt}),{input:I,warnings:l}=await Ce({prompt:m,systemMessageMode:c.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:g?.store??true,hasLocalShellTool:w("openai.local_shell")});s.push(...l);let t=g?.strictJsonSchema??false,y=g?.include;function L(z){y=y!=null?[...y,z]:[z];}function w(z){return C?.find(te=>te.type==="provider"&&te.id===z)!=null}let q=typeof g?.logprobs=="number"?g?.logprobs:g?.logprobs===true?je:void 0;q&&L("message.output_text.logprobs");let T=C?.find(z=>z.type==="provider"&&(z.id==="openai.web_search"||z.id==="openai.web_search_preview"))?.name;T&&L("web_search_call.action.sources"),w("openai.code_interpreter")&&L("code_interpreter_call.outputs");let v={model:this.modelId,input:I,temperature:b,top_p:k,max_output_tokens:r,...(a?.type==="json"||g?.textVerbosity)&&{text:{...a?.type==="json"&&{format:a.schema!=null?{type:"json_schema",strict:t,name:a.name??"response",description:a.description,schema:a.schema}:{type:"json_object"}},...g?.textVerbosity&&{verbosity:g.textVerbosity}}},max_tool_calls:g?.maxToolCalls,metadata:g?.metadata,parallel_tool_calls:g?.parallelToolCalls,previous_response_id:g?.previousResponseId,store:g?.store,user:g?.user,instructions:g?.instructions,service_tier:g?.serviceTier,include:y,prompt_cache_key:g?.promptCacheKey,safety_identifier:g?.safetyIdentifier,top_logprobs:q,...c.isReasoningModel&&(g?.reasoningEffort!=null||g?.reasoningSummary!=null)&&{reasoning:{...g?.reasoningEffort!=null&&{effort:g.reasoningEffort},...g?.reasoningSummary!=null&&{summary:g.reasoningSummary}}},...c.requiredAutoTruncation&&{truncation:"auto"}};c.isReasoningModel?(v.temperature!=null&&(v.temperature=void 0,s.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),v.top_p!=null&&(v.top_p=void 0,s.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(g?.reasoningEffort!=null&&s.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),g?.reasoningSummary!=null&&s.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),g?.serviceTier==="flex"&&!c.supportsFlexProcessing&&(s.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete v.service_tier),g?.serviceTier==="priority"&&!c.supportsPriorityProcessing&&(s.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete v.service_tier);let{tools:N,toolChoice:ze,toolWarnings:Ee}=Se({tools:C,toolChoice:u,strictJsonSchema:t});return {webSearchToolName:T,args:{...v,tools:N,tool_choice:ze},warnings:[...s,...Ee]}}async doGenerate(r){let{args:b,warnings:_,webSearchToolName:k}=await this.getArgs(r),h=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:p,value:i,rawValue:d}=await providerUtils.postJsonToApi({url:h,headers:providerUtils.combineHeaders(this.config.headers(),r.headers),body:b,failedResponseHandler:Z,successfulResponseHandler:providerUtils.createJsonResponseHandler(zod.z.object({id:zod.z.string(),created_at:zod.z.number(),error:zod.z.object({code:zod.z.string(),message:zod.z.string()}).nullish(),model:zod.z.string(),output:zod.z.array(zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("message"),role:zod.z.literal("assistant"),id:zod.z.string(),content:zod.z.array(zod.z.object({type:zod.z.literal("output_text"),text:zod.z.string(),logprobs:Ae.nullish(),annotations:zod.z.array(zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("url_citation"),start_index:zod.z.number(),end_index:zod.z.number(),url:zod.z.string(),title:zod.z.string()}),zod.z.object({type:zod.z.literal("file_citation"),file_id:zod.z.string(),filename:zod.z.string().nullish(),index:zod.z.number().nullish(),start_index:zod.z.number().nullish(),end_index:zod.z.number().nullish(),quote:zod.z.string().nullish()}),zod.z.object({type:zod.z.literal("container_file_citation")})]))}))}),Oe,Me,we,Te,Re,zod.z.object({type:zod.z.literal("function_call"),call_id:zod.z.string(),name:zod.z.string(),arguments:zod.z.string(),id:zod.z.string()}),zod.z.object({type:zod.z.literal("computer_call"),id:zod.z.string(),status:zod.z.string().optional()}),zod.z.object({type:zod.z.literal("reasoning"),id:zod.z.string(),encrypted_content:zod.z.string().nullish(),summary:zod.z.array(zod.z.object({type:zod.z.literal("summary_text"),text:zod.z.string()}))})])),service_tier:zod.z.string().nullish(),incomplete_details:zod.z.object({reason:zod.z.string()}).nullish(),usage:Pe})),abortSignal:r.abortSignal,fetch:this.config.fetch});if(i.error)throw new provider.APICallError({message:i.error.message,url:h,requestBodyValues:b,statusCode:400,responseHeaders:p,responseBody:d,isRetryable:false});let m=[],o=[],C=false;for(let a of i.output)switch(a.type){case "reasoning":{a.summary.length===0&&a.summary.push({type:"summary_text",text:""});for(let s of a.summary)m.push({type:"reasoning",text:s.text,providerMetadata:{openai:{itemId:a.id,reasoningEncryptedContent:a.encrypted_content??null}}});break}case "image_generation_call":{m.push({type:"tool-call",toolCallId:a.id,toolName:"image_generation",input:"{}"}),m.push({type:"tool-result",toolCallId:a.id,toolName:"image_generation",result:{result:a.result}});break}case "local_shell_call":{m.push({type:"tool-call",toolCallId:a.call_id,toolName:"local_shell",input:JSON.stringify({action:a.action}),providerMetadata:{openai:{itemId:a.id}}});break}case "message":{for(let s of a.content){r.providerOptions?.openai?.logprobs&&s.logprobs&&o.push(s.logprobs),m.push({type:"text",text:s.text,providerMetadata:{openai:{itemId:a.id}}});for(let c of s.annotations)c.type==="url_citation"?m.push({type:"source",sourceType:"url",id:providerUtils.generateId(),url:c.url,title:c.title}):c.type==="file_citation"&&m.push({type:"source",sourceType:"document",id:this.config.generateId?.()??providerUtils.generateId(),mediaType:"text/plain",title:c.quote??c.filename??"Document",filename:c.filename??c.file_id});}break}case "function_call":{C=true,m.push({type:"tool-call",toolCallId:a.call_id,toolName:a.name,input:a.arguments,providerMetadata:{openai:{itemId:a.id}}});break}case "web_search_call":{m.push({type:"tool-call",toolCallId:a.id,toolName:k??"web_search",input:JSON.stringify({action:a.action}),providerExecuted:true}),m.push({type:"tool-result",toolCallId:a.id,toolName:k??"web_search",result:{status:a.status}});break}case "computer_call":{m.push({type:"tool-call",toolCallId:a.id,toolName:"computer_use",input:"",providerExecuted:true}),m.push({type:"tool-result",toolCallId:a.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:a.status||"completed"}});break}case "file_search_call":{m.push({type:"tool-call",toolCallId:a.id,toolName:"file_search",input:"{}",providerExecuted:true}),m.push({type:"tool-result",toolCallId:a.id,toolName:"file_search",result:{queries:a.queries,results:a.results?.map(s=>({attributes:s.attributes,fileId:s.file_id,filename:s.filename,score:s.score,text:s.text}))??null}});break}case "code_interpreter_call":{m.push({type:"tool-call",toolCallId:a.id,toolName:"code_interpreter",input:JSON.stringify({code:a.code,containerId:a.container_id}),providerExecuted:true}),m.push({type:"tool-result",toolCallId:a.id,toolName:"code_interpreter",result:{outputs:a.outputs}});break}}let u={openai:{responseId:i.id}};return o.length>0&&u.openai&&(u.openai.logprobs=o),typeof i.service_tier=="string"&&u.openai&&(u.openai.serviceTier=i.service_tier),{content:m,finishReason:ee({finishReason:i.incomplete_details?.reason,hasFunctionCall:C}),usage:{inputTokens:{total:i.usage.input_tokens,noCache:i.usage.input_tokens!==void 0&&i.usage.input_tokens_details?.cached_tokens!==void 0?i.usage.input_tokens-(i.usage.input_tokens_details?.cached_tokens??0):void 0,cacheRead:i.usage.input_tokens_details?.cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:i.usage.output_tokens,text:void 0,reasoning:i.usage.output_tokens_details?.reasoning_tokens??void 0},raw:i.usage},request:{body:b},response:{id:i.id,timestamp:new Date(i.created_at*1e3),modelId:i.model,headers:p,body:d},providerMetadata:u,warnings:_}}async doStream(r){let{args:b,warnings:_,webSearchToolName:k}=await this.getArgs(r),{responseHeaders:h,value:p}=await providerUtils.postJsonToApi({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:providerUtils.combineHeaders(this.config.headers(),r.headers),body:{...b,stream:true},failedResponseHandler:Z,successfulResponseHandler:providerUtils.createEventSourceResponseHandler(Ot),abortSignal:r.abortSignal,fetch:this.config.fetch}),i={unified:"other",raw:void 0},d={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}},m=[],o=null,C={},u=false,a={},s=null,c=null,g;return {stream:p.pipeThrough(new TransformStream({start(I){I.enqueue({type:"stream-start",warnings:_});},transform(I,l){if(r.includeRawChunks&&l.enqueue({type:"raw",rawValue:I.rawValue}),!I.success){i={unified:"error",raw:void 0},l.enqueue({type:"error",error:I.error});return}let t=I.value;if(Le(t))t.item.type==="function_call"?(C[t.output_index]={toolName:t.item.name,toolCallId:t.item.call_id},l.enqueue({type:"tool-input-start",id:t.item.call_id,toolName:t.item.name})):t.item.type==="web_search_call"?(C[t.output_index]={toolName:k??"web_search",toolCallId:t.item.id},l.enqueue({type:"tool-input-start",id:t.item.id,toolName:k??"web_search"})):t.item.type==="computer_call"?(C[t.output_index]={toolName:"computer_use",toolCallId:t.item.id},l.enqueue({type:"tool-input-start",id:t.item.id,toolName:"computer_use"})):t.item.type==="code_interpreter_call"?(C[t.output_index]={toolName:"code_interpreter",toolCallId:t.item.id,codeInterpreter:{containerId:t.item.container_id}},l.enqueue({type:"tool-input-start",id:t.item.id,toolName:"code_interpreter"}),l.enqueue({type:"tool-input-delta",id:t.item.id,delta:`{"containerId":"${t.item.container_id}","code":"`})):t.item.type==="file_search_call"?l.enqueue({type:"tool-call",toolCallId:t.item.id,toolName:"file_search",input:"{}",providerExecuted:true}):t.item.type==="image_generation_call"?l.enqueue({type:"tool-call",toolCallId:t.item.id,toolName:"image_generation",input:"{}",providerExecuted:true}):t.item.type==="message"?(c=t.item.id,l.enqueue({type:"text-start",id:t.item.id,providerMetadata:{openai:{itemId:t.item.id}}})):Lt(t)&&(a[t.output_index]={canonicalId:t.item.id,encryptedContent:t.item.encrypted_content,summaryParts:[0]},s=t.output_index,l.enqueue({type:"reasoning-start",id:`${t.item.id}:0`,providerMetadata:{openai:{itemId:t.item.id,reasoningEncryptedContent:t.item.encrypted_content??null}}}));else if(qe(t)){if(t.item.type==="function_call")C[t.output_index]=void 0,u=true,l.enqueue({type:"tool-input-end",id:t.item.call_id}),l.enqueue({type:"tool-call",toolCallId:t.item.call_id,toolName:t.item.name,input:t.item.arguments,providerMetadata:{openai:{itemId:t.item.id}}});else if(t.item.type==="web_search_call")C[t.output_index]=void 0,l.enqueue({type:"tool-input-end",id:t.item.id}),l.enqueue({type:"tool-call",toolCallId:t.item.id,toolName:"web_search",input:JSON.stringify({action:t.item.action}),providerExecuted:true}),l.enqueue({type:"tool-result",toolCallId:t.item.id,toolName:"web_search",result:{status:t.item.status}});else if(t.item.type==="computer_call")C[t.output_index]=void 0,l.enqueue({type:"tool-input-end",id:t.item.id}),l.enqueue({type:"tool-call",toolCallId:t.item.id,toolName:"computer_use",input:"",providerExecuted:true}),l.enqueue({type:"tool-result",toolCallId:t.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:t.item.status||"completed"}});else if(t.item.type==="file_search_call")C[t.output_index]=void 0,l.enqueue({type:"tool-result",toolCallId:t.item.id,toolName:"file_search",result:{queries:t.item.queries,results:t.item.results?.map(y=>({attributes:y.attributes,fileId:y.file_id,filename:y.filename,score:y.score,text:y.text}))??null}});else if(t.item.type==="code_interpreter_call")C[t.output_index]=void 0,l.enqueue({type:"tool-result",toolCallId:t.item.id,toolName:"code_interpreter",result:{outputs:t.item.outputs}});else if(t.item.type==="image_generation_call")l.enqueue({type:"tool-result",toolCallId:t.item.id,toolName:"image_generation",result:{result:t.item.result}});else if(t.item.type==="local_shell_call")C[t.output_index]=void 0,l.enqueue({type:"tool-call",toolCallId:t.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:t.item.action.command,timeoutMs:t.item.action.timeout_ms,user:t.item.action.user,workingDirectory:t.item.action.working_directory,env:t.item.action.env}}),providerMetadata:{openai:{itemId:t.item.id}}});else if(t.item.type==="message")c&&(l.enqueue({type:"text-end",id:c}),c=null);else if(wt(t)){let y=a[t.output_index];if(y){for(let L of y.summaryParts)l.enqueue({type:"reasoning-end",id:`${y.canonicalId}:${L}`,providerMetadata:{openai:{itemId:y.canonicalId,reasoningEncryptedContent:t.item.encrypted_content??null}}});delete a[t.output_index],s===t.output_index&&(s=null);}}}else if(jt(t)){let y=C[t.output_index];y!=null&&l.enqueue({type:"tool-input-delta",id:y.toolCallId,delta:t.delta});}else if(At(t))l.enqueue({type:"tool-result",toolCallId:t.item_id,toolName:"image_generation",result:{result:t.partial_image_b64}});else if(Pt(t)){let y=C[t.output_index];y!=null&&l.enqueue({type:"tool-input-delta",id:y.toolCallId,delta:JSON.stringify(t.delta).slice(1,-1)});}else if(qt(t)){let y=C[t.output_index];y!=null&&(l.enqueue({type:"tool-input-delta",id:y.toolCallId,delta:'"}'}),l.enqueue({type:"tool-input-end",id:y.toolCallId}),l.enqueue({type:"tool-call",toolCallId:y.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:t.code,containerId:y.codeInterpreter.containerId})}));}else if(Tt(t))o=t.response.id,l.enqueue({type:"response-metadata",id:t.response.id,timestamp:new Date(t.response.created_at*1e3),modelId:t.response.model});else if(Mt(t))c||(c=t.item_id,l.enqueue({type:"text-start",id:c,providerMetadata:{openai:{itemId:t.item_id}}})),l.enqueue({type:"text-delta",id:c,delta:t.delta}),r.providerOptions?.openai?.logprobs&&t.logprobs&&m.push(t.logprobs);else if(zt(t)){let y=s!==null?a[s]:null;y&&t.summary_index>0&&(y.summaryParts.push(t.summary_index),l.enqueue({type:"reasoning-start",id:`${y.canonicalId}:${t.summary_index}`,providerMetadata:{openai:{itemId:y.canonicalId,reasoningEncryptedContent:y.encryptedContent??null}}}));}else if(Et(t)){let y=s!==null?a[s]:null;y&&l.enqueue({type:"reasoning-delta",id:`${y.canonicalId}:${t.summary_index}`,delta:t.delta,providerMetadata:{openai:{itemId:y.canonicalId}}});}else Rt(t)?(i=ee({finishReason:t.response.incomplete_details?.reason,hasFunctionCall:u}),d={inputTokens:{total:t.response.usage.input_tokens,noCache:t.response.usage.input_tokens!==void 0&&t.response.usage.input_tokens_details?.cached_tokens!==void 0?t.response.usage.input_tokens-(t.response.usage.input_tokens_details?.cached_tokens??0):void 0,cacheRead:t.response.usage.input_tokens_details?.cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:t.response.usage.output_tokens,text:void 0,reasoning:t.response.usage.output_tokens_details?.reasoning_tokens??void 0},raw:t.response.usage},typeof t.response.service_tier=="string"&&(g=t.response.service_tier)):Nt(t)?t.annotation.type==="url_citation"?l.enqueue({type:"source",sourceType:"url",id:providerUtils.generateId(),url:t.annotation.url,title:t.annotation.title}):t.annotation.type==="file_citation"&&l.enqueue({type:"source",sourceType:"document",id:providerUtils.generateId(),mediaType:"text/plain",title:t.annotation.quote??t.annotation.filename??"Document",filename:t.annotation.filename??t.annotation.file_id}):Ft(t)&&l.enqueue({type:"error",error:t});},flush(I){c&&(I.enqueue({type:"text-end",id:c}),c=null);let l={openai:{responseId:o}};m.length>0&&(l.openai.logprobs=m),g!==void 0&&(l.openai.serviceTier=g),I.enqueue({type:"finish",finishReason:i,usage:d,providerMetadata:l});}})),request:{body:b},response:{headers:h}}}},Pe=zod.z.object({input_tokens:zod.z.number(),input_tokens_details:zod.z.object({cached_tokens:zod.z.number().nullish()}).nullish(),output_tokens:zod.z.number(),output_tokens_details:zod.z.object({reasoning_tokens:zod.z.number().nullish()}).nullish()}),mt=zod.z.object({type:zod.z.literal("response.output_text.delta"),item_id:zod.z.string(),delta:zod.z.string(),logprobs:Ae.nullish()}),gt=zod.z.object({type:zod.z.literal("error"),code:zod.z.string(),message:zod.z.string(),param:zod.z.string().nullish(),sequence_number:zod.z.number()}),ft=zod.z.object({type:zod.z.enum(["response.completed","response.incomplete"]),response:zod.z.object({incomplete_details:zod.z.object({reason:zod.z.string()}).nullish(),usage:Pe,service_tier:zod.z.string().nullish()})}),ht=zod.z.object({type:zod.z.literal("response.created"),response:zod.z.object({id:zod.z.string(),created_at:zod.z.number(),model:zod.z.string(),service_tier:zod.z.string().nullish()})}),yt=zod.z.object({type:zod.z.literal("response.output_item.added"),output_index:zod.z.number(),item:zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("message"),id:zod.z.string()}),zod.z.object({type:zod.z.literal("reasoning"),id:zod.z.string(),encrypted_content:zod.z.string().nullish()}),zod.z.object({type:zod.z.literal("function_call"),id:zod.z.string(),call_id:zod.z.string(),name:zod.z.string(),arguments:zod.z.string()}),zod.z.object({type:zod.z.literal("web_search_call"),id:zod.z.string(),status:zod.z.string(),action:zod.z.object({type:zod.z.literal("search"),query:zod.z.string().optional()}).nullish()}),zod.z.object({type:zod.z.literal("computer_call"),id:zod.z.string(),status:zod.z.string()}),zod.z.object({type:zod.z.literal("file_search_call"),id:zod.z.string()}),zod.z.object({type:zod.z.literal("image_generation_call"),id:zod.z.string()}),zod.z.object({type:zod.z.literal("code_interpreter_call"),id:zod.z.string(),container_id:zod.z.string(),code:zod.z.string().nullable(),outputs:zod.z.array(zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("logs"),logs:zod.z.string()}),zod.z.object({type:zod.z.literal("image"),url:zod.z.string()})])).nullable(),status:zod.z.string()})])}),_t=zod.z.object({type:zod.z.literal("response.output_item.done"),output_index:zod.z.number(),item:zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("message"),id:zod.z.string()}),zod.z.object({type:zod.z.literal("reasoning"),id:zod.z.string(),encrypted_content:zod.z.string().nullish()}),zod.z.object({type:zod.z.literal("function_call"),id:zod.z.string(),call_id:zod.z.string(),name:zod.z.string(),arguments:zod.z.string(),status:zod.z.literal("completed")}),we,Te,Oe,Me,Re,zod.z.object({type:zod.z.literal("computer_call"),id:zod.z.string(),status:zod.z.literal("completed")})])}),bt=zod.z.object({type:zod.z.literal("response.function_call_arguments.delta"),item_id:zod.z.string(),output_index:zod.z.number(),delta:zod.z.string()}),Ct=zod.z.object({type:zod.z.literal("response.image_generation_call.partial_image"),item_id:zod.z.string(),output_index:zod.z.number(),partial_image_b64:zod.z.string()}),kt=zod.z.object({type:zod.z.literal("response.code_interpreter_call_code.delta"),item_id:zod.z.string(),output_index:zod.z.number(),delta:zod.z.string()}),It=zod.z.object({type:zod.z.literal("response.code_interpreter_call_code.done"),item_id:zod.z.string(),output_index:zod.z.number(),code:zod.z.string()}),St=zod.z.object({type:zod.z.literal("response.output_text.annotation.added"),annotation:zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.literal("url_citation"),url:zod.z.string(),title:zod.z.string()}),zod.z.object({type:zod.z.literal("file_citation"),file_id:zod.z.string(),filename:zod.z.string().nullish(),index:zod.z.number().nullish(),start_index:zod.z.number().nullish(),end_index:zod.z.number().nullish(),quote:zod.z.string().nullish()})])}),xt=zod.z.object({type:zod.z.literal("response.reasoning_summary_part.added"),item_id:zod.z.string(),summary_index:zod.z.number()}),vt=zod.z.object({type:zod.z.literal("response.reasoning_summary_text.delta"),item_id:zod.z.string(),summary_index:zod.z.number(),delta:zod.z.string()}),Ot=zod.z.union([mt,ft,ht,yt,_t,bt,Ct,kt,It,St,xt,vt,gt,zod.z.object({type:zod.z.string()}).loose()]);function Mt(n){return n.type==="response.output_text.delta"}function qe(n){return n.type==="response.output_item.done"}function wt(n){return qe(n)&&n.item.type==="reasoning"}function Rt(n){return n.type==="response.completed"||n.type==="response.incomplete"}function Tt(n){return n.type==="response.created"}function jt(n){return n.type==="response.function_call_arguments.delta"}function At(n){return n.type==="response.image_generation_call.partial_image"}function Pt(n){return n.type==="response.code_interpreter_call_code.delta"}function qt(n){return n.type==="response.code_interpreter_call_code.done"}function Le(n){return n.type==="response.output_item.added"}function Lt(n){return Le(n)&&n.item.type==="reasoning"}function Nt(n){return n.type==="response.output_text.annotation.added"}function zt(n){return n.type==="response.reasoning_summary_part.added"}function Et(n){return n.type==="response.reasoning_summary_text.delta"}function Ft(n){return n.type==="error"}function Dt(n){let r=n.startsWith("o3")||n.startsWith("o4-mini")||n.startsWith("gpt-5")&&!n.startsWith("gpt-5-chat"),b=n.startsWith("gpt-4")||n.startsWith("gpt-5-mini")||n.startsWith("gpt-5")&&!n.startsWith("gpt-5-nano")&&!n.startsWith("gpt-5-chat")||n.startsWith("o3")||n.startsWith("o4-mini"),_={requiredAutoTruncation:false,systemMessageMode:"system",supportsFlexProcessing:r,supportsPriorityProcessing:b};return n.startsWith("gpt-5-chat")?{..._,isReasoningModel:false}:n.startsWith("o")||n.startsWith("gpt-5")||n.startsWith("codex-")||n.startsWith("computer-use")?n.startsWith("o1-mini")||n.startsWith("o1-preview")?{..._,isReasoningModel:true,systemMessageMode:"remove"}:{..._,isReasoningModel:true,systemMessageMode:"developer"}:{..._,isReasoningModel:false}}var Wt=zod.z.object({include:zod.z.array(zod.z.enum(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:zod.z.string().nullish(),logprobs:zod.z.union([zod.z.boolean(),zod.z.number().min(1).max(je)]).optional(),maxToolCalls:zod.z.number().nullish(),metadata:zod.z.any().nullish(),parallelToolCalls:zod.z.boolean().nullish(),previousResponseId:zod.z.string().nullish(),promptCacheKey:zod.z.string().nullish(),reasoningEffort:zod.z.string().nullish(),reasoningSummary:zod.z.string().nullish(),safetyIdentifier:zod.z.string().nullish(),serviceTier:zod.z.enum(["auto","flex","priority"]).nullish(),store:zod.z.boolean().nullish(),strictJsonSchema:zod.z.boolean().nullish(),textVerbosity:zod.z.enum(["low","medium","high"]).nullish(),user:zod.z.string().nullish()});var Ht="0.1.0";function Ne(n={}){let r=providerUtils.withoutTrailingSlash(n.baseURL??"https://api.openai.com/v1");if(!r)throw new utils.NameErrors.MissingFieldError({message:"baseURL is required",field:"baseURL"});let b={...n.apiKey&&{Authorization:`Bearer ${n.apiKey}`},...n.headers},_=()=>providerUtils.withUserAgentSuffix(b,`ai-sdk/openai-compatible/${Ht}`),k=d=>new H(d,{provider:`${n.name??"openai-compatible"}.chat`,headers:_,url:({path:m})=>`${r}${m}`,fetch:n.fetch}),h=d=>new G(d,{provider:`${n.name??"openai-compatible"}.responses`,headers:_,url:({path:m})=>`${r}${m}`,fetch:n.fetch}),p=d=>k(d),i=function(d){return k(d)};return i.languageModel=p,i.chat=k,i.responses=h,i}var Jt=Ne();
|
|
2
|
+
exports.a=Ne;exports.b=Jt;
|