diff --git a/packages/experimental/webworker-runtime/src/node/external_packages/pi-ai.ts b/packages/experimental/webworker-runtime/src/node/external_packages/pi-ai.ts index 76a5ddc5aa..ec2d251a02 100644 --- a/packages/experimental/webworker-runtime/src/node/external_packages/pi-ai.ts +++ b/packages/experimental/webworker-runtime/src/node/external_packages/pi-ai.ts @@ -5,10 +5,11 @@ * statically at module scope, so the row cannot mount without it. * * Every symbol `llm-pi-ai` imports by name is present: a missing CommonJS symbol - * would surface as `undefined` at call time instead of a link error. The four catalog readers - * return empty collections rather than throwing — the row reads them while it - * activates, and "this deployment ships no pi-ai provider" is the truth here. - * Everything on a request path is loud. + * would surface as `undefined` at call time instead of a link error. The row + * reads the catalog while it activates, so the provider reader returns + * providers without models and the two model readers return empty collections + * instead of throwing: this deployment serves no pi-ai model. Everything on a + * request path is loud. */ import { notImplementedFail } from '../notImplementedFail.ts' @@ -26,7 +27,14 @@ export const getSupportedThinkingLevels = notImplementedFail(MODULE, 'getSupport /** Context-overflow predicate (unavailable). */ export const isContextOverflow = notImplementedFail(MODULE, 'isContextOverflow') -/** Builtin provider ids of pi-ai 0.84.2, in catalog order. */ +/** Collection of every builtin provider (unavailable). */ +export const builtinModels = notImplementedFail(MODULE, 'builtinModels') + +/** + * Builtin provider ids as pi-ai 0.84.2 listed them, in catalog order. The list + * is a fixed copy that pi-ai upgrades do not regenerate, so it omits providers + * added since. + */ const BUILTIN_PROVIDER_IDS: readonly string[] = [ 'amazon-bedrock', 'ant-ling', 'anthropic', 'azure-openai-responses', 'baseten', 'cerebras', 'cloudflare-ai-gateway', 'cloudflare-workers-ai', 'deepseek', 'fireworks', 'github-copilot', @@ -39,10 +47,11 @@ const BUILTIN_PROVIDER_IDS: readonly string[] = [ ] /** - * Installed catalog providers, read while `llm-pi-ai` activates. Each carries the - * api-key auth marker the adapter filters on, and no models: the provider - * directory therefore matches the served deployment while every request path - * lands on a loud symbol above. + * Installed catalog providers, read while `llm-pi-ai` activates. `llm-pi-ai` + * registers the whole catalog as configurable the moment it mounts and rejects + * an empty registration, so these carry pi-ai's ids instead of being an empty + * list. Each has the api-key auth marker the adapter filters on, and no + * models, so every request path lands on a loud symbol above. * @returns one entry per builtin provider. */ export function builtinProviders(): unknown[] { @@ -54,16 +63,6 @@ export function builtinProviders(): unknown[] { })) } -/** - * Provider route ids of the installed catalog. `llm-pi-ai` registers the whole - * catalog as configurable the moment it mounts and rejects an empty - * registration, so these are pi-ai's real ids rather than an empty list. - * @returns the builtin provider ids. - */ -export function getBuiltinProviders(): string[] { - return [...BUILTIN_PROVIDER_IDS] -} - /** * Models of one installed catalog provider. * @returns no models. @@ -94,7 +93,6 @@ export const __esModule = true /** CommonJS default export: the members `require()` hands a caller of this module. */ export default { - createProvider, createModels, getSupportedThinkingLevels, isContextOverflow, builtinProviders, - getBuiltinModels, getAllBuiltinModels, getBuiltinProviders, anthropicMessagesApi, openAICompletionsApi, - openAIResponsesApi, + createProvider, createModels, getSupportedThinkingLevels, isContextOverflow, builtinModels, builtinProviders, + getBuiltinModels, getAllBuiltinModels, anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, } diff --git a/packages/experimental/webworker-runtime/tests/node/node-stubs.spec.ts b/packages/experimental/webworker-runtime/tests/node/node-stubs.spec.ts index f193b0dabd..3006a4a0c4 100644 --- a/packages/experimental/webworker-runtime/tests/node/node-stubs.spec.ts +++ b/packages/experimental/webworker-runtime/tests/node/node-stubs.spec.ts @@ -50,7 +50,7 @@ const CALLED: [string, Record, readonly string[]][] = [ ['got', got.default, ['post']], ['@deepseek-ai/pi-ai', piAi, [ 'createProvider', 'createModels', 'openAICompletionsApi', 'openAIResponsesApi', 'anthropicMessagesApi', - 'isContextOverflow', 'getSupportedThinkingLevels', + 'isContextOverflow', 'getSupportedThinkingLevels', 'builtinModels', ]], ] diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index 7578397cb8..84eed99c14 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -87,8 +87,8 @@ en: b6bd570c0159ba08 zh: 7d2d91eea6a8d830 /deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work: - en: 24213b5d80e1b1ea - zh: e7524db2a35f6659 + en: 3ac77ae061cf0683 + zh: c25abff6da8c1a22 /deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work/dev-note: en: 3678dd0f6642c2a5 zh: 75cbdd064cc64282 diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 36cd633219..549310082a 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -216,6 +216,7 @@ These limits define where the adapter stops and future work begins. They are cur - **`maxRequestImageBytes` counts base64 image payload only** — text, tools, descriptors, and JSON structure ride outside the bound, so it must sit below the gateway's request-body cap with headroom. - **A sign-in lives only in the process that started it** — an authorization attempt is not durable, so reloading the page mid-login abandons it and the human starts over. Signing out is `deleteRecord` on the stored record, which forgets it locally without telling the issuer. +- **OpenAI offers no ChatGPT sign-in** — pi-ai's Sign in with ChatGPT identifies the installation to OpenAI with a stable UUID the app supplies, and the harness keeps no installation ID meant for a third-party account sign-in; the `openai` route signs in with an API key. - **Provider-native discovery answers through this plugin's ambient context** — a route naming no credential defers to the catalog provider's own resolution, which asks for environment values (`AZURE_OPENAI_API_KEY`, `AWS_PROFILE`, and each provider's own set) and for local credential files. Both questions are answered here: the credential seam is consulted before the process environment, and file existence is checked against the host process's filesystem with `~` expanded. What it cannot do is *read* a credential file's contents — a provider that parses `~/.aws/credentials` itself does so directly, outside the seam. - **Reset restores inherited configuration** — resetting a route supplied by a lower profile layer restores that route. - **Complete Config replacement can remove inherited dictionary entries** — a field reset instead restores its inherited value. diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index f73a0dd246..19fff091e6 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -216,6 +216,7 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish - **`maxRequestImageBytes` 只计算 base64 图片载荷**,文本、工具、描述符与 JSON 结构在该上限之外,因此它必须留有余量地低于网关请求体上限。 - **登录只存在于发起它的进程中**——授权尝试不持久,因此登录中途刷新页面会放弃它,用户需要重新开始。退出登录是对已存储记录执行 `deleteRecord`,只在本地忘记它,不会告知签发方。 +- **OpenAI 不提供 ChatGPT 登录**——pi-ai 的 Sign in with ChatGPT 用应用提供的稳定 UUID 向 OpenAI 标识安装实例,而 harness 没有用于第三方账号登录的安装 ID;`openai` 路由改用 API key 登录。 - **提供方原生发现经本插件的 ambient context 回答**——不点名凭据的路由交由目录提供方自身解析,它会询问环境值(`AZURE_OPENAI_API_KEY`、`AWS_PROFILE` 及各提供方自有集合)与本地凭据文件。两个问题都在这里得到回答:凭据 seam 先于进程环境被查询,文件存在性则针对宿主进程的文件系统以 `~` 展开后检查。它做不到的是*读取*凭据文件内容——自行解析 `~/.aws/credentials` 的提供方会直接读取,不经该 seam。 - **重置恢复继承配置**——重置下层 profile 提供的路由会恢复该路由。 - **完整替换 Config 可以移除继承的字典条目**——字段重置则恢复其继承值。 diff --git a/packages/llm/llm-pi-ai/src/catalog.ts b/packages/llm/llm-pi-ai/src/catalog.ts index 9ef61c3290..6ccd0cae05 100644 --- a/packages/llm/llm-pi-ai/src/catalog.ts +++ b/packages/llm/llm-pi-ai/src/catalog.ts @@ -12,7 +12,7 @@ * @module dsh-llm-pi-ai/catalog */ -import { builtinProviders, getAllBuiltinModels, getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all' +import { builtinProviders, getAllBuiltinModels, getBuiltinModels } from '@earendil-works/pi-ai/providers/all' import type { BuiltinProvider } from '@earendil-works/pi-ai/providers/all' import type { AnthropicMessagesCompat, @@ -166,41 +166,53 @@ export const CHAT_TEMPLATE_VARS = Object.keys(CHAT_TEMPLATE_VAR_GATE) as readonl let providerIndex: Map | undefined /** - * Installed catalog providers by id, constructed once. Each entry owns the API - * implementations for its own models, which is why a catalog route reuses this - * provider instead of being rebuilt from parts. - * @returns the catalog provider index. + * Whether this adapter serves one installed catalog provider. It dispatches + * chat requests only, so a provider whose catalog lists models but no chat + * model (image-generation or classifier models alone) is not a catalog route; + * a provider whose catalog lists no models at all stays one. + * @param provider - the installed provider. + * @returns whether the provider ships a chat model or lists no models. + */ +function servesChat(provider: Provider): boolean { + const id = provider.id as BuiltinProvider + return getBuiltinModels(id).length > 0 || getAllBuiltinModels(id).length === 0 +} + +/** + * Installed catalog providers this adapter serves, by id, constructed once. + * Each entry owns the API implementations for its own models, which is why a + * catalog route reuses this provider instead of being rebuilt from parts. + * @returns the catalog provider index, in catalog order. */ function catalogProviders(): Map { - providerIndex ??= new Map(builtinProviders().map(provider => [provider.id, provider])) + providerIndex ??= new Map(builtinProviders().filter(servesChat).map(provider => [provider.id, provider])) return providerIndex } /** - * The installed catalog provider for one route, when pi-ai ships one. + * The installed catalog provider for one route, when pi-ai ships one this + * adapter serves. * @param provider - provider route key. - * @returns the catalog provider, or `undefined` for a route pi-ai does not ship. + * @returns the catalog provider, or `undefined` for a route pi-ai does not ship + * or ships without a chat model. */ export function catalogProvider(provider: string): Provider | undefined { return catalogProviders().get(provider) } /** - * Every provider route the installed pi-ai catalog ships, except a provider - * whose catalog lists models but no chat model. This adapter dispatches chat - * requests only, so a provider of image-generation or classifier models alone - * is not a configurable route; a provider whose catalog lists no models stays. + * Every provider route the installed pi-ai catalog ships and this adapter + * serves: a provider whose catalog lists models but no chat model is left out. * @returns the catalog provider ids, in catalog order. */ export function catalogProviderIds(): readonly string[] { - return getBuiltinProviders().filter(provider => - getBuiltinModels(provider).length > 0 || getAllBuiltinModels(provider).length === 0) + return [...catalogProviders().keys()] } /** * The installed catalog models for one route, indexed by model id. * @param provider - provider route key. - * @returns catalog models by id; empty for a route pi-ai does not ship. + * @returns catalog models by id; empty for a route {@link catalogProvider} does not return. */ export function catalogModels(provider: string): Map> { if (!catalogProviders().has(provider)) return new Map() diff --git a/packages/llm/llm-pi-ai/src/login.ts b/packages/llm/llm-pi-ai/src/login.ts index 4bbe7d7850..f7f055dab6 100644 --- a/packages/llm/llm-pi-ai/src/login.ts +++ b/packages/llm/llm-pi-ai/src/login.ts @@ -16,19 +16,30 @@ import { recordKeyFor } from './auth.ts' import type { PiAiAuthInjection } from './adapter.ts' import { createModels } from './models.ts' +/** + * Catalog providers whose OAuth login this adapter does not offer. pi-ai's Sign + * in with ChatGPT (`openai`) identifies the installation to OpenAI with a + * stable UUID that the app supplies through `LoginOptions.getDeviceId`, and it + * refuses to start without one. The harness keeps no installation ID meant for + * a third-party account sign-in, so the route signs in with an API key. + */ +const UNSERVED_OAUTH: ReadonlySet = new Set(['openai']) + /** * The login methods one catalog provider offers. * - * A method appears only when pi-ai can actually run it: `oauth` always carries - * a `login`, while an api-key method has one only when the provider collects - * its key interactively — which every installed one currently does, so a key is - * typed into pi-ai's own prompt rather than into the settings form. + * A method appears only when pi-ai can actually run it: `oauth` carries a + * `login` that runs without app-supplied login options except for the + * providers in {@link UNSERVED_OAUTH}, while an api-key method has one only + * when the provider collects its key interactively — which every installed one + * currently does, so a key is typed into pi-ai's own prompt rather than into + * the settings form. * @param provider - the installed catalog provider, if pi-ai ships one. * @returns its methods, most preferred first; empty when it offers no login. */ function loginMethods(provider: Provider | undefined): AuthorizationMethod[] { const methods: AuthorizationMethod[] = [] - const oauth = provider?.auth.oauth + const oauth = provider === undefined || UNSERVED_OAUTH.has(provider.id) ? undefined : provider.auth.oauth if (oauth !== undefined) methods.push({ id: 'oauth', label: oauth.loginLabel ?? oauth.name }) const apiKey = provider?.auth.apiKey if (apiKey?.login !== undefined) methods.push({ id: 'api-key', label: apiKey.name }) diff --git a/packages/llm/llm-pi-ai/tests/catalog-provider-ids.spec.ts b/packages/llm/llm-pi-ai/tests/catalog-provider-ids.spec.ts index ab14369a42..ba33a42920 100644 --- a/packages/llm/llm-pi-ai/tests/catalog-provider-ids.spec.ts +++ b/packages/llm/llm-pi-ai/tests/catalog-provider-ids.spec.ts @@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest' // no catalog data, such as the browser-worker preview). vi.mock('@earendil-works/pi-ai/providers/all', async importOriginal => ({ ...await importOriginal(), - getBuiltinProviders: () => ['chat-provider', 'classifier-provider', 'uncataloged-provider'], + builtinProviders: () => ['chat-provider', 'classifier-provider', 'uncataloged-provider'].map(id => ({ id })), getBuiltinModels: (provider: string) => provider === 'chat-provider' ? [{ id: 'chat-model' }] : [], getAllBuiltinModels: (provider: string) => { if (provider === 'chat-provider') return [{ id: 'chat-model' }] @@ -16,10 +16,17 @@ vi.mock('@earendil-works/pi-ai/providers/all', async importOriginal => ({ }, })) -import { catalogProviderIds } from '../src/catalog.ts' +import { catalogModels, catalogProvider, catalogProviderIds } from '../src/catalog.ts' describe('catalog provider ids', () => { it('drops a provider that lists only non-chat models and keeps one that lists none', () => { expect(catalogProviderIds()).toEqual(['chat-provider', 'uncataloged-provider']) }) + + it('answers no catalog provider or models for the provider it drops', () => { + expect(catalogProvider('classifier-provider')).toBeUndefined() + expect(catalogModels('classifier-provider').size).toBe(0) + expect(catalogProvider('uncataloged-provider')).toEqual({ id: 'uncataloged-provider' }) + expect([...catalogModels('chat-provider').keys()]).toEqual(['chat-model']) + }) }) diff --git a/packages/llm/llm-pi-ai/tests/catalog.spec.ts b/packages/llm/llm-pi-ai/tests/catalog.spec.ts index 93bc398745..81b1b78e9e 100644 --- a/packages/llm/llm-pi-ai/tests/catalog.spec.ts +++ b/packages/llm/llm-pi-ai/tests/catalog.spec.ts @@ -7,10 +7,11 @@ const configurations = new WeakMap { const offered = ctx.llm.listConfigurableProviders().map(entry => entry.provider) // The installed catalog ships `typesafe` with classifier models only; with - // nothing to dispatch a chat request to, the route is not offered. + // nothing to dispatch a chat request to, the route is not offered and is + // not a catalog route anywhere else either. + expect(getBuiltinProviders()).toContain('typesafe') + expect(getAllBuiltinModels('typesafe').length).toBeGreaterThan(0) expect(getBuiltinModels('typesafe')).toEqual([]) expect(offered).not.toContain('typesafe') + expect(catalogProvider('typesafe')).toBeUndefined() + expect(catalogModels('typesafe').size).toBe(0) }) it('lists a route a stored profile names as a catalog route, not a declared one', async () => { diff --git a/packages/llm/llm-pi-ai/tests/loader-composition.spec.ts b/packages/llm/llm-pi-ai/tests/loader-composition.spec.ts index 6beedfb3fb..ce2ceb8368 100644 --- a/packages/llm/llm-pi-ai/tests/loader-composition.spec.ts +++ b/packages/llm/llm-pi-ai/tests/loader-composition.spec.ts @@ -9,6 +9,7 @@ import { Context } from '@deepseek-ai/cordis' import Loader, { type ModuleLoaderV2 } from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import LlmRuntime, { createMessage, createUserMessage, userAgent } from '@deepseek-ai/dsh-llm' +import AuthorizationService from '@deepseek-ai/dsh-authorization' import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { profileComposition } from '../../../settings/settings/tests/profile-composition.ts' import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai' @@ -50,6 +51,8 @@ async function loadComposition(): Promise<{ ctx: Context; settingsPath: string } ' config:', ` path: ${JSON.stringify(join(root, '.credentials.yaml'))}`, ' debounceMs: 10', + '- id: authorization', + " name: '@deepseek-ai/dsh-authorization'", '- id: llm-pi-ai', " name: '@deepseek-ai/dsh-llm-pi-ai'", '', @@ -63,6 +66,7 @@ async function loadComposition(): Promise<{ ctx: Context; settingsPath: string } const modules = new Map([ ['test-llm-service', LlmRuntime], ['@deepseek-ai/dsh-credentials-local', LocalCredentialProvider], + ['@deepseek-ai/dsh-authorization', AuthorizationService], ['@deepseek-ai/dsh-llm-pi-ai', LlmPiAi], ]) const internal: ModuleLoaderV2 = { @@ -110,6 +114,17 @@ describe('llm-pi-ai real dormant composition', () => { expect(server.headers[0]?.authorization).toBe('Bearer key-from-store') }) + it('offers OpenAI sign-in by API key only, while other subscription logins stay', async () => { + const { ctx } = await loadComposition() + const methods = (provider: string): string[] | undefined => ctx.authorization.list() + .find(entry => entry.key === LlmPiAi.recordKeyFor(provider))?.methods.map(method => method.id) + + // pi-ai's Sign in with ChatGPT needs an installation ID the harness does + // not supply, so the route offers only its key login. + expect(methods('openai')).toEqual(['api-key']) + expect(methods('anthropic')).toEqual(['oauth', 'api-key']) + }) + it('uses settings-only route headers for model discovery', async () => { vi.stubEnv('PI_COMPOSITION_KEY', '') const server = await mockServer([{ body: JSON.stringify({ data: [{ id: 'acme-private' }] }) }]) diff --git a/packages/llm/llm-pi-ai/tests/login.spec.ts b/packages/llm/llm-pi-ai/tests/login.spec.ts index 6074cbd848..a719bd027a 100644 --- a/packages/llm/llm-pi-ai/tests/login.spec.ts +++ b/packages/llm/llm-pi-ai/tests/login.spec.ts @@ -20,6 +20,7 @@ vi.mock('../src/models.ts', async importOriginal => ({ })) const { credentialStoreFrom, authContextFrom, recordKeyFor } = await import('../src/auth.ts') +const { catalogProvider } = await import('../src/catalog.ts') const { registerPiAiFlows } = await import('../src/login.ts') const CODEX = recordKeyFor('openai-codex') @@ -96,6 +97,11 @@ describe('pi-ai login flows', () => { // through its own prompt rather than leaving it to the settings form. expect(offered.find(entry => entry.key === recordKeyFor('deepseek'))?.methods.map(one => one.id)) .toEqual(['api-key']) + // pi-ai ships Sign in with ChatGPT for `openai`, which needs an + // installation ID the harness does not supply; only the key login is offered. + expect(catalogProvider('openai')?.auth.oauth?.loginLabel).toBe('Sign in with ChatGPT') + expect(offered.find(entry => entry.key === recordKeyFor('openai'))?.methods.map(one => one.id)) + .toEqual(['api-key']) }) it('runs the pi-ai auth type the chosen method names', async () => { diff --git a/packages/llm/llm-pi-ai/tests/mock-server.ts b/packages/llm/llm-pi-ai/tests/mock-server.ts index a8d059a45c..f2aef145f1 100644 --- a/packages/llm/llm-pi-ai/tests/mock-server.ts +++ b/packages/llm/llm-pi-ai/tests/mock-server.ts @@ -32,7 +32,8 @@ export const textEvents = [ /** Local provider stand-in: replays scripted behaviors per request. */ export async function mockServer(script: { status?: number - events?: string[] + /** SSE frames: a string is sent as `data:` alone; a pair also names the frame's `event:`. */ + events?: (string | { event: string; data: string })[] body?: string delayMs?: number /** Keep the SSE response open after its scripted events until the client disconnects. */ @@ -79,7 +80,7 @@ export async function mockServer(script: { if (!behavior.holdOpen) response.end() return } - response.write(`data: ${event}\n\n`) + response.write(typeof event === 'string' ? `data: ${event}\n\n` : `event: ${event.event}\ndata: ${event.data}\n\n`) if (behavior.delayMs === undefined) writeNext() else timer = setTimeout(writeNext, behavior.delayMs) } diff --git a/packages/llm/llm-pi-ai/tests/tool-argument-streaming.spec.ts b/packages/llm/llm-pi-ai/tests/tool-argument-streaming.spec.ts index 42d9e28a8b..a9b3451b5a 100644 --- a/packages/llm/llm-pi-ai/tests/tool-argument-streaming.spec.ts +++ b/packages/llm/llm-pi-ai/tests/tool-argument-streaming.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' import type { AssistantMessageEvent, Model } from '@earendil-works/pi-ai' +import { stream as streamAnthropic } from '@earendil-works/pi-ai/api/anthropic-messages' import { stream as streamCompletions } from '@earendil-works/pi-ai/api/openai-completions' import { stream as streamResponses } from '@earendil-works/pi-ai/api/openai-responses' import { normalizeContext } from '@earendil-works/pi-ai/utils/transcript' @@ -12,7 +13,7 @@ const args = { file_path: 'notes.md', content: 'x'.repeat(2048) } const argsJson = JSON.stringify(args) const fragments = argsJson.match(/.{1,7}/gs) ?? [] -function model(api: A, baseUrl: string): Model { +function model(api: A, baseUrl: string): Model { return { id: 'm', name: 'm', api, provider: 'test', baseUrl, reasoning: false, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 1024, @@ -61,6 +62,29 @@ describe('streamed tool-call arguments (patched pi-ai)', () => { expect(final).toEqual(args) }) + it('anthropic-messages parses arguments once, at the end of the call', async () => { + const frame = (data: Record): { event: string; data: string } => + ({ event: String(data['type']), data: JSON.stringify(data) }) + const server = await mockServer([{ events: [ + frame({ type: 'message_start', message: { + id: 'msg_1', type: 'message', role: 'assistant', model: 'm', content: [], + stop_reason: null, stop_sequence: null, usage: { input_tokens: 3, output_tokens: 1 }, + } }), + frame({ type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_1', name: 'write', input: {} } }), + ...fragments.map(fragment => frame({ + type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: fragment }, + })), + frame({ type: 'content_block_stop', index: 0 }), + frame({ type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 } }), + frame({ type: 'message_stop' }), + ] }]) + const events = streamAnthropic(model('anthropic-messages', server.url), context, { apiKey: 'test-key' }) + const { partials, final } = await collect(events) + expect(partials).toHaveLength(fragments.length) + expect(partials.every(partial => JSON.stringify(partial) === '{}')).toBe(true) + expect(final).toEqual(args) + }) + it('openai-responses parses arguments once, at the end of the call', async () => { const item = { type: 'function_call', call_id: 'call_1', id: 'fc_1', name: 'write' } const server = await mockServer([{ events: [