zidane 7.0.17 → 7.0.19
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/dist/{acp-DTnq3bda.js → acp-BgNj1-gv.js} +2 -2
- package/dist/{acp-DTnq3bda.js.map → acp-BgNj1-gv.js.map} +1 -1
- package/dist/acp-cli.js +4 -4
- package/dist/acp.d.ts +1 -1
- package/dist/acp.js +1 -1
- package/dist/{agent-C5xr7lqh.js → agent-Djzx-1kD.js} +123 -22
- package/dist/agent-Djzx-1kD.js.map +1 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{anthropic-D_aMBEj8.js → anthropic-DATE-m9f.js} +23 -8
- package/dist/anthropic-DATE-m9f.js.map +1 -0
- package/dist/{approvals-D3P3Wz58.js → approvals-Jztqzqjk.js} +31 -5
- package/dist/approvals-Jztqzqjk.js.map +1 -0
- package/dist/{auth-893jSFew.js → auth-DhkLW1Wu.js} +5 -5
- package/dist/{auth-893jSFew.js.map → auth-DhkLW1Wu.js.map} +1 -1
- package/dist/chat/pure.d.ts +3 -3
- package/dist/chat.d.ts +5 -5
- package/dist/chat.js +3 -3
- package/dist/contexts/daytona.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/daemon-cli.js +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/extensions.d.ts +2 -2
- package/dist/extensions.js +2 -2
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +1 -1
- package/dist/{index-CyOGLSQN.d.ts → index-498gAVpL.d.ts} +5 -5
- package/dist/index-498gAVpL.d.ts.map +1 -0
- package/dist/{index-D7H81_kd.d.ts → index-CfEJ5Vf9.d.ts} +52 -4
- package/dist/index-CfEJ5Vf9.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +6 -6
- package/dist/{ipc-DY40IbcP.js → ipc-B4p0P2tz.js} +2 -2
- package/dist/{ipc-DY40IbcP.js.map → ipc-B4p0P2tz.js.map} +1 -1
- package/dist/ipc.d.ts +5 -5
- package/dist/ipc.js +3 -3
- package/dist/mcp.d.ts +1 -1
- package/dist/{oauth-EIBUuSDK.js → oauth-D-LZ4ic-.js} +29 -2
- package/dist/oauth-D-LZ4ic-.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +1 -1
- package/dist/{providers-CTkZSxvp.js → providers-Bjdvmpfu.js} +2 -2
- package/dist/{providers-CTkZSxvp.js.map → providers-Bjdvmpfu.js.map} +1 -1
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +4 -4
- package/dist/restate.d.ts +1 -1
- package/dist/restate.js +1 -1
- package/dist/{server-DaZqNd61.js → server-Cccx5jES.js} +4 -4
- package/dist/{server-DaZqNd61.js.map → server-Cccx5jES.js.map} +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session-23Stp71-.js.map +1 -1
- package/dist/session.d.ts +2 -2
- package/dist/session.js +2 -2
- package/dist/skills.d.ts +1 -1
- package/dist/{tool-formatters-9_ABHXRG.d.ts → tool-formatters-D1rdZOe3.d.ts} +2 -2
- package/dist/{tool-formatters-9_ABHXRG.d.ts.map → tool-formatters-D1rdZOe3.d.ts.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +1 -1
- package/dist/{transcript-anchors-CbZkEMIN.d.ts → transcript-anchors-pHga6mOC.d.ts} +2 -2
- package/dist/{transcript-anchors-CbZkEMIN.d.ts.map → transcript-anchors-pHga6mOC.d.ts.map} +1 -1
- package/dist/tui.d.ts +3 -3
- package/dist/tui.js +99 -36
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-DsVjoO3S.d.ts → turn-operations-Dzo-8TKC.d.ts} +3 -3
- package/dist/{turn-operations-DsVjoO3S.d.ts.map → turn-operations-Dzo-8TKC.d.ts.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
- package/dist/agent-C5xr7lqh.js.map +0 -1
- package/dist/anthropic-D_aMBEj8.js.map +0 -1
- package/dist/approvals-D3P3Wz58.js.map +0 -1
- package/dist/index-CyOGLSQN.d.ts.map +0 -1
- package/dist/index-D7H81_kd.d.ts.map +0 -1
- package/dist/oauth-EIBUuSDK.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-D-LZ4ic-.js","names":[],"sources":["../src/providers/oauth-registry.ts","../src/providers/oauth.ts"],"sourcesContent":["/**\n * Local OAuth provider registry.\n *\n * pi-ai 0.80.8 removed its global OAuth registry (`registerOAuthProvider`,\n * `getOAuthApiKey`, `OAuthProviderInterface`) and the public low-level\n * refresh helpers in favor of canonical `Provider.auth.oauth` objects\n * resolved through a `Models` collection + `CredentialStore`. zidane's\n * credential architecture (shared `.credentials.json`, cross-process refresh\n * locks in `./oauth.ts`, themed login flows in `src/chat/oauth-page/`)\n * predates that and owns storage itself, so this module reproduces the\n * removed registry surface locally with the same semantics.\n *\n * Nothing protocol-level is duplicated here: token refresh for the built-in\n * providers delegates to pi-ai's canonical `auth.oauth.refresh` flows via the\n * public `providers/*` subpaths (lazily imported, so processes that never\n * authenticate don't load provider code).\n */\n\nimport type { OAuthAuth } from '@earendil-works/pi-ai'\nimport type { OAuthCredentials, OAuthLoginCallbacks } from '@earendil-works/pi-ai/oauth'\nimport { errorMessage } from '../errors'\n\n/**\n * Provider-owned OAuth flow. Mirrors the interface pi-ai exported from\n * `@earendil-works/pi-ai/oauth` up to 0.80.6 — kept as a local type so\n * zidane's descriptor seam (`ProviderDescriptor.oauthProvider`) and provider\n * extensions (e.g. `extensions/bolt`) stay source-compatible across the\n * upstream removal.\n */\nexport interface OAuthProviderInterface {\n readonly id: string\n readonly name: string\n\n /** Run the login flow, return credentials to persist. */\n login: (callbacks: OAuthLoginCallbacks) => Promise<OAuthCredentials>\n\n /** Whether login uses a local callback server and supports manual code input. */\n usesCallbackServer?: boolean\n\n /** Refresh expired credentials, return updated credentials to persist. */\n refreshToken: (credentials: OAuthCredentials) => Promise<OAuthCredentials>\n\n /** Convert credentials to an API key string for the provider. */\n getApiKey: (credentials: OAuthCredentials) => string\n}\n\n/**\n * Run a canonical pi-ai `OAuthAuth.refresh` from a bare refresh token.\n * pi-ai's built-in refresh implementations only read `credential.refresh`,\n * so the placeholder access/expires fields are never observed.\n *\n * The canonical result is an `OAuthCredential` tagged `type: 'oauth'`. Strip\n * the tag before returning: refresh results get merged into stored\n * `.credentials.json` entries and `onOAuthRefresh` hook payloads (see\n * `resolveCredentialSource` in `./oauth.ts`), whose documented shape carries\n * zidane's own `kind` tag — letting pi-ai's `type` leak through would\n * silently drift the on-disk shape.\n */\nasync function refreshViaCanonicalFlow(\n providerId: string,\n oauth: OAuthAuth | undefined,\n refreshToken: string,\n): Promise<OAuthCredentials> {\n if (!oauth)\n throw new Error(`pi-ai provider ${providerId} exposes no OAuth flow`)\n // pi-ai 0.84 made `signal` a required second argument. These refreshers are\n // called from token-expiry paths that carry no cancellation of their own, so\n // a never-aborting signal keeps the pre-0.84 behavior exactly — same idiom as\n // `completion-core.ts`.\n const { type: _type, ...credentials }\n = await oauth.refresh(\n { type: 'oauth', access: '', refresh: refreshToken, expires: 0 },\n new AbortController().signal,\n )\n return credentials\n}\n\n/**\n * pi-ai ≥ 0.85 loads each OAuth flow module through a VARIABLE specifier\n * (`auth/oauth/load.js`: `import(rewrite(\"./anthropic.ts\"))`) precisely so\n * bundlers cannot follow it. Fine under plain Node/Bun where the file sits\n * next to `load.js`; fatal inside anything bundled — the compiled `zidane`\n * binary, the packaged Electron main — where the refresh path died with\n * `Cannot find module './anthropic.js'` and the user was told to re-run auth\n * for a token that was perfectly renewable.\n *\n * pi-ai ships the escape hatch for exactly this: `bun-oauth` statically\n * imports every flow and registers them with the loader. We call it lazily,\n * once, right before the first refresh — a static specifier the bundler DOES\n * follow — so every host (TUI binary, GUI, daemon, SDK) refreshes the same\n * way. Idempotent; failure to register falls through to the loader's own\n * behavior (works unbundled, so nothing gets worse).\n */\nlet bundledFlowsReady: Promise<void> | null = null\nexport function ensureBundledOAuthFlows(): Promise<void> {\n bundledFlowsReady ??= import('@earendil-works/pi-ai/bun-oauth')\n .then(({ registerBunOAuthFlows }) => {\n registerBunOAuthFlows()\n })\n .catch(() => {\n bundledFlowsReady = null\n })\n return bundledFlowsReady\n}\n\n/**\n * Refresh an Anthropic (Claude Pro/Max) OAuth token. Drop-in replacement for\n * the `refreshAnthropicToken` pi-ai exported until 0.80.6; delegates to the\n * canonical flow on `anthropicProvider().auth.oauth`.\n */\nexport async function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredentials> {\n await ensureBundledOAuthFlows()\n const { anthropicProvider } = await import('@earendil-works/pi-ai/providers/anthropic')\n return refreshViaCanonicalFlow('anthropic', anthropicProvider().auth.oauth, refreshToken)\n}\n\n/**\n * Refresh an OpenAI Codex (ChatGPT) OAuth token. Drop-in replacement for the\n * removed `refreshOpenAICodexToken`; the canonical flow still derives\n * `accountId` from the refreshed access token's JWT claims, so the returned\n * credentials keep the extra field older callers persisted.\n */\nexport async function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials> {\n await ensureBundledOAuthFlows()\n const { openaiCodexProvider } = await import('@earendil-works/pi-ai/providers/openai-codex')\n return refreshViaCanonicalFlow('openai-codex', openaiCodexProvider().auth.oauth, refreshToken)\n}\n\n/**\n * Built-in registry seeds. Every id whose stored credential can expire has to\n * be seeded here, because zidane's lazy token refresh (`getOAuthApiKey` inside\n * `resolveOAuthApiKey`) resolves through the registry — an unseeded id is not a\n * degraded path but a dead end, with no way to renew the session. That is wider\n * than the Anthropic / OpenAI Codex pair pi-ai's removed registry pre-seeded:\n * flows zidane implements itself (xAI) need seeding just as much.\n *\n * Login is intentionally unsupported here: interactive login always goes\n * through `ProviderDescriptor.oauthProvider` (the themed flows in\n * `src/chat/oauth-page/`), never through the registry.\n */\nfunction builtinProvider(\n id: string,\n name: string,\n refreshToken: (credentials: OAuthCredentials) => Promise<OAuthCredentials>,\n): OAuthProviderInterface {\n return {\n id,\n name,\n login: async () => {\n throw new Error(`OAuth login for ${id} must run through a provider descriptor flow, not the registry`)\n },\n refreshToken,\n getApiKey: credentials => credentials.access,\n }\n}\n\n/**\n * Seed id for the xAI Grok OAuth flow. Duplicated from\n * `XAI_OAUTH_PROVIDER_ID` in `../chat/oauth-page/xai` rather than imported:\n * that module pulls in `node:http` and the PKCE helpers at module scope, and\n * this registry is loaded by every consumer that resolves a credential. The\n * ids are pinned together by a test, so the duplication cannot drift.\n */\nconst XAI_SEED_ID = 'xai-oauth'\n\n/**\n * Refresh an xAI Grok token. Imported lazily so seeding the registry does not\n * drag the login flow's `node:http` callback server into every consumer —\n * and so the static import edge back to this module stays type-only, leaving\n * no runtime cycle.\n *\n * Unlike the Anthropic / Codex seeds, this receives the FULL credential rather\n * than a bare refresh token: xAI stores its resolved `token_endpoint` (and the\n * cached discovery doc) alongside the tokens, and dropping them would force a\n * fresh OIDC discovery round-trip on every refresh — and discard the validated\n * endpoint that `refreshXaiToken` re-checks before posting the refresh token\n * to it.\n */\nasync function refreshXaiTokenSeed(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const { refreshXaiToken } = await import('../chat/oauth-page/xai')\n return refreshXaiToken(credentials)\n}\n\n/**\n * Seed id for the Cursor OAuth flow. Duplicated from\n * `CURSOR_OAUTH_PROVIDER_ID` for the same reason as {@link XAI_SEED_ID}, and\n * pinned to it by a test.\n */\nconst CURSOR_SEED_ID = 'cursor'\n\n/**\n * Refresh a Cursor token. Lazy for the same reason as the xAI seed: the login\n * module owns a callback server, and seeding must not drag it into every\n * consumer that merely resolves a credential.\n */\nasync function refreshCursorTokenSeed(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const { refreshCursorToken } = await import('../chat/oauth-page/cursor')\n return refreshCursorToken(credentials)\n}\n\n/**\n * The registry map is anchored on a process-wide `globalThis` slot rather\n * than module state. The pi-ai registry this replaces lived in pi-ai's own\n * module, so every copy of zidane code in a process shared one map — and two\n * copies is a real configuration, not a hypothetical: a host running from\n * `src` while a disk-loaded extension resolves `'zidane'` to `dist` through\n * ordinary node_modules resolution (see `import()` in\n * `src/extensions/discovery.ts`). The extension registers its flow at setup;\n * `resolveOAuthApiKey` looks it up only once a stored token expires — with\n * per-module maps that fails as a deferred \"Unknown OAuth provider\", which is\n * nasty to debug. `Symbol.for` restores the process-wide sharing. Whichever\n * copy touches the slot first seeds the built-ins, so a `dist` consumer can end\n * up refreshing through the `src` copy's closure (and vice versa). That is\n * harmless because the seeds are STATELESS refresh delegations — they close over\n * no module state and no configuration, so the two copies compute the same\n * result from the same stored credential. It is that property, not where the\n * refresh happens to be implemented, that makes first-copy-wins safe: it holds\n * equally for the seeds that delegate to pi-ai's canonical flows and for the\n * xAI one implemented in `../chat/oauth-page/xai`.\n */\n/**\n * Exported so tests that register a throwaway provider can remove it from the\n * same slot rather than re-deriving the key with a copied string: the registry\n * exposes no unregister, and a `Symbol.for` looked up from a duplicated literal\n * would silently stop matching if this key were ever renamed, leaving the test\n * provider resident in shared state. Deliberately kept out of the package's\n * public surface — `./index.ts` re-exports this module by explicit name list.\n */\nexport const REGISTRY_SLOT = Symbol.for('zidane.oauth-provider-registry')\n\nfunction oauthProviderRegistry(): Map<string, OAuthProviderInterface> {\n const slots = globalThis as { [key: symbol]: Map<string, OAuthProviderInterface> | undefined }\n slots[REGISTRY_SLOT] ??= new Map(\n [\n builtinProvider('anthropic', 'Anthropic (Claude Pro/Max)', c => refreshAnthropicToken(c.refresh)),\n builtinProvider('openai-codex', 'OpenAI (ChatGPT Plus/Pro)', c => refreshOpenAICodexToken(c.refresh)),\n // xAI is NOT built into pi-ai, so unlike the two above there is no\n // canonical flow to delegate to — `../chat/oauth-page/xai` implements it.\n // It is seeded here anyway because seeding is what makes refresh work for\n // consumers that never import `chat/providers.ts` or `auth.ts`, whose\n // module-scope `registerXaiOAuthProvider()` call was previously the ONLY\n // thing that registered it. A library consumer resolving a stored\n // credential through `getOAuthApiKey` got `Unknown OAuth provider:\n // xai-oauth` and had no way to renew a session — a dead end rather than a\n // degraded path. The interactive login half still comes from\n // `registerXaiOAuthProvider(renderPage)`, which replaces this seed.\n builtinProvider(XAI_SEED_ID, 'xAI Grok (SuperGrok / X Premium+)', refreshXaiTokenSeed),\n // Cursor has the identical shape and had the identical defect: its flow\n // lives in `../chat/oauth-page/cursor` and was registered only as a\n // module-scope side effect of importing `chat/providers.ts` / `auth.ts`.\n builtinProvider(CURSOR_SEED_ID, 'Cursor', refreshCursorTokenSeed),\n ].map(provider => [provider.id, provider]),\n )\n return slots[REGISTRY_SLOT]\n}\n\n/** Register (or replace) an OAuth provider by id. */\nexport function registerOAuthProvider(provider: OAuthProviderInterface): void {\n oauthProviderRegistry().set(provider.id, provider)\n}\n\n/** Get a registered OAuth provider by id. */\nexport function getOAuthProvider(id: string): OAuthProviderInterface | undefined {\n return oauthProviderRegistry().get(id)\n}\n\n/**\n * Get an API key for a provider from OAuth credentials, refreshing expired\n * tokens through the registered flow. Same contract as the pi-ai original\n * (`null` when no credentials are stored for the provider, throws on unknown\n * provider or refresh failure), with two deliberate additions:\n *\n * - refresh failures keep the underlying reason — the original discarded it,\n * leaving invalid_grant (needs re-login) indistinguishable from a transient\n * network error.\n * - `options.force` rotates regardless of the local expiry, for 401 recovery\n * when the server revoked the grant before our stored timestamp said so.\n * Expressed as a flag rather than by handing this function a credential\n * with a doctored `expires`: callers persist whatever comes back, so a\n * fabricated expiry that a provider echoes through would land in the\n * credential store. See `resolveCredentialSource` in `./oauth.ts`.\n */\nexport async function getOAuthApiKey(\n providerId: string,\n credentials: Record<string, OAuthCredentials>,\n options?: { force?: boolean },\n): Promise<{ newCredentials: OAuthCredentials, apiKey: string } | null> {\n const provider = oauthProviderRegistry().get(providerId)\n if (!provider)\n throw new Error(`Unknown OAuth provider: ${providerId}`)\n\n let creds = credentials[providerId]\n if (!creds)\n return null\n\n if (options?.force || Date.now() >= creds.expires) {\n try {\n creds = await provider.refreshToken(creds)\n }\n catch (err) {\n throw new Error(`Failed to refresh OAuth token for ${providerId}: ${errorMessage(err)}`, { cause: err })\n }\n }\n\n return { newCredentials: creds, apiKey: provider.getApiKey(creds) }\n}\n","import type { OAuthCredentials } from '@earendil-works/pi-ai/oauth'\nimport type { StreamCallbacks } from '.'\nimport type { OAuthRefreshHookContext } from '../types'\nimport { Buffer } from 'node:buffer'\nimport { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { resolve } from 'node:path'\nimport { writeFileAtomic } from '../atomic-write'\nimport { errorMessage } from '../errors'\nimport { getOAuthApiKey, registerOAuthProvider } from './oauth-registry'\n\ntype GetOAuthApiKey = typeof getOAuthApiKey\n\n/**\n * Resolve the creds-file path at call time rather than module-load time, so\n * env changes between import and first OAuth use (test suites, multi-project\n * CLIs) are honored.\n *\n * Order:\n * 1. `ZIDANE_CREDENTIALS_PATH` — explicit override. The TUI sets this at\n * launch to point at `<storageDir>/credentials.json` so the harness\n * providers find the same file the TUI manages.\n * 2. `~/.credentials.json` — home-anchored default.\n *\n * The historic `cwd/.credentials.json` fallback was deliberately dropped:\n * launching zidane inside an untrusted checkout would let that repo plant a\n * `.credentials.json` and become the credential source (and receive rotated\n * refresh tokens on the next refresh persist). Same trust model as the TUI's\n * legacy-file migration in `chat/credentials.ts`, which only honors the\n * home-anchored location. The only \"trusted\" cwd under that model is `$HOME`\n * itself — where the cwd-relative path resolves to `~/.credentials.json`\n * anyway, so anchoring at home preserves the legitimate legacy case.\n */\nexport function credentialsFilePath(): string {\n return process.env.ZIDANE_CREDENTIALS_PATH ?? resolve(homedir(), '.credentials.json')\n}\n\n/**\n * POSIX mode for credentials on disk. Read+write for the owner only — refresh\n * tokens and API keys leak if the file is world-readable on a shared box.\n * Ignored on Windows.\n */\nconst CREDENTIALS_FILE_MODE = 0o600\n\n/**\n * In-process mutex table keyed by provider id. Concurrent `resolveOAuthApiKey`\n * calls for the same provider (typical when a host fans out multiple streams\n * at once) coalesce onto a single refresh. Without this, N concurrent calls\n * each hit `getOAuthApiKey`, producing N writes to `.credentials.json` with\n * last-write-wins semantics — and, in worst-case interleaving, a corrupted\n * file.\n */\nconst refreshLocks = new Map<string, Promise<string>>()\n\n/**\n * Register a custom OAuth flow with the local registry (`./oauth-registry`)\n * so lazy refresh through {@link resolveOAuthApiKey} can resolve `providerId`.\n *\n * Public because provider extensions need it: without registration,\n * `getOAuthApiKey('<id>', …)` throws `Unknown OAuth provider` the first time a\n * stored token expires. Idempotent per id (the registry is a keyed map). Kept\n * async for API stability — it awaited a dynamic pi-ai import before pi-ai\n * 0.80.8 removed its global registry and this moved in-repo.\n */\nexport async function registerCustomOAuthProvider(\n provider: import('./oauth-registry').OAuthProviderInterface,\n): Promise<void> {\n registerOAuthProvider(provider)\n}\n\nexport interface OAuthParams {\n apiKey?: string\n access?: string\n refresh?: string\n expires?: number\n}\n\n/**\n * Pull a complete `{ access, refresh, expires }` triple out of provider params\n * when (and only when) all three OAuth fields are present and well-typed.\n * Returns `undefined` for the static-api-key path. Shared by the OAuth-capable\n * providers so the runtime-credential guard can't drift between them.\n */\n/**\n * Whether a credential string is an OAuth *access token* rather than a real,\n * static API key. Anthropic OAuth tokens are prefixed `sk-ant-oat`; OpenAI\n * Codex OAuth access tokens are JWTs (`eyJ...`). Used to decide whether an\n * env-provided value can be refreshed (OAuth) or must be sent verbatim (API key).\n */\nexport function isOAuthAccessToken(value: string): boolean {\n return value.startsWith('sk-ant-oat') || isJwtLikeAccessToken(value)\n}\n\nfunction isJwtLikeAccessToken(value: string): boolean {\n const parts = value.split('.')\n if (parts.length !== 3 || !parts[0]?.startsWith('eyJ'))\n return false\n try {\n const header = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8')) as unknown\n return Boolean(header && typeof header === 'object' && 'alg' in header)\n }\n catch {\n return false\n }\n}\n\nexport function extractRuntimeCredentials(\n params?: OAuthParams,\n): { access: string, refresh: string, expires: number } | undefined {\n if (\n typeof params?.access === 'string'\n && typeof params.refresh === 'string'\n && typeof params.expires === 'number'\n ) {\n return { access: params.access, refresh: params.refresh, expires: params.expires }\n }\n return undefined\n}\n\nexport interface ResolveOAuthApiKeyOptions<TParams extends OAuthParams = OAuthParams> {\n provider: string\n providerId: string\n params?: TParams\n envKey?: string\n extraCredentialKeys?: (keyof TParams & string)[]\n missingError: string\n refreshError: (reason: string) => string\n readCredentials?: () => Record<string, OAuthCredentials | undefined>\n writeCredentials?: (credentials: Record<string, OAuthCredentials | undefined>) => void\n getOAuthApiKey?: GetOAuthApiKey\n /**\n * Force a refresh even when the credential's local expiry is still in the\n * future (for one-shot 401 recovery). Reaches the refresh helper as an\n * explicit flag, so no credential with a fabricated expiry ever exists to\n * leak into the store — see {@link getOAuthApiKey}.\n */\n forceRefresh?: boolean\n /** Access token rejected by the server; a different token found under lock is reused instead of rotated again. */\n rejectedAccess?: string\n}\n\n/**\n * Read the shared credentials file.\n *\n * Returns `{}` when the file is missing OR when the file exists but is corrupted\n * / not valid JSON. Corrupt-file tolerance is important: the refresh-then-persist\n * path below writes atomically, but older builds wrote in place and could have\n * truncated the file on a crash. Treating corruption as \"no stored creds\" lets\n * users re-auth without manually deleting the file.\n *\n * Supports two on-disk shapes:\n * 1. **Legacy** (untagged): `{ \"anthropic\": { access, refresh, expires, ... } }`\n * — written by older `bun run auth`.\n * 2. **New** (kind-tagged): `{ \"anthropic\": { kind: 'oauth', access, refresh, expires, ... } }`\n * — written by the TUI. Entries with `kind: 'apikey'` are skipped — those\n * reach providers via env vars set at TUI launch (see `applyApiKeyEnv`).\n */\nexport function readOAuthCredentials(): Record<string, OAuthCredentials | undefined> {\n const path = credentialsFilePath()\n if (!existsSync(path))\n return {}\n\n try {\n const raw = readFileSync(path, 'utf-8')\n const parsed = JSON.parse(raw)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n return {}\n const result: Record<string, OAuthCredentials | undefined> = {}\n for (const [key, value] of Object.entries(parsed)) {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n continue\n const v = value as Record<string, unknown>\n // New schema: explicit `kind` tag.\n if (v.kind === 'apikey')\n continue\n // Both new (`kind: 'oauth'`) and legacy (untagged) entries have `access`;\n // the harmless `kind` field is allowed by `OAuthCredentials`'s\n // `[key: string]: unknown` index signature. Validate the required\n // fields explicitly so the assignment doesn't need a double-cast.\n if (\n typeof v.access === 'string'\n && typeof v.refresh === 'string'\n && typeof v.expires === 'number'\n ) {\n result[key] = { ...v, access: v.access, refresh: v.refresh, expires: v.expires }\n }\n }\n return result\n }\n catch {\n return {}\n }\n}\n\n/**\n * Cross-process lockfile parameters for the credentials read-merge-write.\n * A holder normally completes in well under a millisecond (read + JSON merge\n * + atomic write of a tiny file), so the stale threshold is generous and the\n * total wait short — on timeout we proceed without the lock rather than fail\n * the refresh (degrades to the historic last-write-wins behavior).\n */\nconst CREDENTIALS_LOCK_STALE_MS = 5000\nconst CREDENTIALS_LOCK_RETRY_MS = 20\nconst CREDENTIALS_LOCK_MAX_WAIT_MS = 2000\n\n/** Synchronous sleep without spinning — works on Bun and Node main threads. */\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n}\n\n/**\n * Best-effort exclusive lock via `O_EXCL` create of `<file>.lock`. Returns\n * `true` when the lock was acquired (caller must release), `false` on\n * timeout (caller proceeds unlocked — see threshold rationale above). Locks\n * older than {@link CREDENTIALS_LOCK_STALE_MS} are treated as leftovers from\n * a crashed process and broken.\n */\nfunction acquireCredentialsLock(lockPath: string): boolean {\n const deadline = Date.now() + CREDENTIALS_LOCK_MAX_WAIT_MS\n while (true) {\n try {\n writeFileSync(lockPath, String(process.pid), { flag: 'wx', mode: CREDENTIALS_FILE_MODE })\n return true\n }\n catch (err) {\n // Only EEXIST means \"lock held\" — anything else (EPERM, ENOENT for a\n // missing parent dir, read-only fs) won't resolve by waiting, so bail\n // immediately and let the subsequent write surface the real error.\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST')\n return false\n try {\n const age = Date.now() - statSync(lockPath).mtimeMs\n if (age > CREDENTIALS_LOCK_STALE_MS) {\n unlinkSync(lockPath)\n continue\n }\n }\n catch { /* lock vanished between create-fail and stat — retry */ }\n if (Date.now() >= deadline)\n return false\n sleepSync(CREDENTIALS_LOCK_RETRY_MS)\n }\n }\n}\n\nfunction releaseCredentialsLock(lockPath: string): void {\n try {\n unlinkSync(lockPath)\n }\n catch { /* already gone */ }\n}\n\n/**\n * Cross-process lock parameters for the REFRESH critical section (read →\n * check expiry → refresh → persist), held per provider around file-backed\n * resolves in {@link resolveOAuthApiKey}.\n *\n * This is a different beast from the write lock above: the holder performs a\n * network call, so it can legitimately hold the lock for seconds. Hence its\n * own generous thresholds — and async waiting, because blocking the event\n * loop for a peer's refresh round-trip is not acceptable. The stakes are\n * higher too: providers with single-use rotating refresh tokens (Bolt) treat\n * a replayed token as theft and revoke the WHOLE grant, so two processes\n * refreshing the same provider concurrently don't just race a write — they\n * self-revoke. A process that loses the race re-reads under the lock, finds\n * the winner's fresh token, and skips its own refresh entirely.\n *\n * On timeout we proceed without the lock (degrades to the pre-lock racy\n * behavior) rather than fail a resolve that would probably have succeeded.\n */\nconst REFRESH_LOCK_STALE_MS = 60_000\nconst REFRESH_LOCK_RETRY_MS = 50\nconst REFRESH_LOCK_MAX_WAIT_MS = 30_000\n\nfunction refreshLockPath(providerId: string): string {\n return `${credentialsFilePath()}.refresh-${providerId.replace(/[^\\w.-]/g, '_')}.lock`\n}\n\n/** Async sibling of {@link acquireCredentialsLock} with refresh-scale thresholds. */\nasync function acquireRefreshLock(lockPath: string): Promise<boolean> {\n const deadline = Date.now() + REFRESH_LOCK_MAX_WAIT_MS\n while (true) {\n try {\n writeFileSync(lockPath, String(process.pid), { flag: 'wx', mode: CREDENTIALS_FILE_MODE })\n return true\n }\n catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST')\n return false\n try {\n const age = Date.now() - statSync(lockPath).mtimeMs\n if (age > REFRESH_LOCK_STALE_MS) {\n unlinkSync(lockPath)\n continue\n }\n }\n catch { /* lock vanished between create-fail and stat — retry */ }\n if (Date.now() >= deadline)\n return false\n await new Promise(resolve => setTimeout(resolve, REFRESH_LOCK_RETRY_MS))\n }\n }\n}\n\n/**\n * Atomically write `.credentials.json` with mode 0o600.\n *\n * Writes to a sibling temp file first, then renames. `rename(2)` is atomic on\n * the same filesystem, so readers either see the old file or the new one —\n * never a half-written one. This matters when a host has multiple processes\n * pointed at the same creds file.\n *\n * Merges the incoming OAuth entries on top of the raw file contents so that\n * entries this layer doesn't manage (e.g. `kind: 'apikey'` from the TUI\n * wizard) survive an OAuth refresh cycle. Without this merge,\n * `readOAuthCredentials` filters those entries out, and a naive overwrite\n * would delete them.\n *\n * The read-merge-write runs under a best-effort cross-process lockfile\n * (`<file>.lock`) so two processes refreshing different providers at the\n * same moment can't drop each other's rotated refresh tokens. On lock\n * timeout the write proceeds unlocked (last-write-wins, the pre-lock\n * behavior) rather than failing the refresh.\n */\nexport function writeOAuthCredentials(credentials: Record<string, OAuthCredentials | undefined>) {\n const path = credentialsFilePath()\n const lockPath = `${path}.lock`\n const locked = acquireCredentialsLock(lockPath)\n\n try {\n let existing: Record<string, unknown> = {}\n try {\n if (existsSync(path)) {\n const raw = readFileSync(path, 'utf-8')\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))\n existing = parsed as Record<string, unknown>\n }\n }\n catch { /* corrupt file — start fresh */ }\n\n const merged = { ...existing, ...credentials }\n // Remove keys explicitly set to undefined (provider was deleted).\n for (const [key, value] of Object.entries(merged)) {\n if (value === undefined)\n delete merged[key]\n }\n\n writeFileAtomic(path, JSON.stringify(merged, null, 2), { mode: CREDENTIALS_FILE_MODE })\n }\n finally {\n if (locked)\n releaseCredentialsLock(lockPath)\n }\n}\n\nexport function credentialsFromParams<TParams extends OAuthParams>(params?: TParams, extraKeys: (keyof TParams & string)[] = []): OAuthCredentials | undefined {\n if (typeof params?.access !== 'string' || typeof params.refresh !== 'string' || typeof params.expires !== 'number')\n return undefined\n\n const extras = Object.fromEntries(\n extraKeys\n .map(key => [key, params[key]])\n .filter(([, value]) => value !== undefined),\n )\n\n return {\n access: params.access,\n refresh: params.refresh,\n expires: params.expires,\n ...extras,\n }\n}\n\nexport async function resolveOAuthApiKey<TParams extends OAuthParams>(\n options: ResolveOAuthApiKeyOptions<TParams>,\n callbacks?: Pick<StreamCallbacks, 'onOAuthRefresh'>,\n): Promise<string> {\n if (typeof options.params?.apiKey === 'string')\n return options.params.apiKey\n\n const paramsCredentials = credentialsFromParams(options.params, options.extraCredentialKeys)\n if (paramsCredentials) {\n return await withRefreshLock(\n `params:${options.providerId}`,\n () => resolveCredentialSource('params', paramsCredentials),\n )\n }\n\n if (typeof options.params?.access === 'string')\n return options.params.access\n\n const readCredentials = options.readCredentials ?? readOAuthCredentials\n const writeCredentials = options.writeCredentials ?? writeOAuthCredentials\n // The cross-process refresh lock only means something when we're actually\n // backed by the shared credentials file; injected stores (tests, embedders)\n // have no cross-process story to protect and must not touch real lock files.\n const usingDefaultStore = !options.readCredentials && !options.writeCredentials\n\n // Env key handling. A real API key (e.g. `sk-ant-api…`) is used as-is. But an\n // OAuth *access token* (`sk-ant-oat…`) pasted into the API-key env var can't\n // be refreshed and will 401 once expired — so if refreshable OAuth creds for\n // this provider exist on disk, prefer those (they self-heal via refresh).\n const envValue = options.envKey ? process.env[options.envKey] : undefined\n if (envValue) {\n if (!isOAuthAccessToken(envValue))\n return envValue\n if (!readCredentials()[options.providerId])\n return envValue // no refreshable creds — fall back to the raw token\n return await withRefreshLock(`file:${options.providerId}`, () => withCrossProcessRefreshLock(async () => {\n // Re-read under the locks — a concurrent resolve (in this process or\n // another) may have rotated the refresh token between the pre-check\n // above and lock acquisition, and refreshing with the stale token would\n // invalidate the new one.\n const allCredentials = readCredentials()\n const stored = allCredentials[options.providerId]\n if (!stored)\n return envValue\n return await resolveCredentialSource('file', stored, allCredentials, writeCredentials)\n }))\n }\n\n return await withRefreshLock(`file:${options.providerId}`, () => withCrossProcessRefreshLock(async () => {\n // Read under the locks so we're always operating on the latest file state\n // and never interleave read/refresh/write against another concurrent\n // resolve — in-process (withRefreshLock) or cross-process (the lockfile).\n const allCredentials = readCredentials()\n const storedCredentials = allCredentials[options.providerId]\n if (!storedCredentials)\n throw new Error(options.missingError)\n\n return await resolveCredentialSource('file', storedCredentials, allCredentials, writeCredentials)\n }))\n\n /**\n * Hold the per-provider cross-process lockfile across the WHOLE file-backed\n * critical section, not just the persist. Guarding only the write (as\n * `writeOAuthCredentials` does) still lets two processes both spend a\n * single-use rotating refresh token — which self-revokes providers with\n * replay-detecting rotation. See the {@link REFRESH_LOCK_STALE_MS} note.\n */\n async function withCrossProcessRefreshLock(fn: () => Promise<string>): Promise<string> {\n if (!usingDefaultStore)\n return fn()\n const lockPath = refreshLockPath(options.providerId)\n const locked = await acquireRefreshLock(lockPath)\n try {\n return await fn()\n }\n finally {\n if (locked)\n releaseCredentialsLock(lockPath)\n }\n }\n\n async function resolveCredentialSource(\n source: OAuthRefreshHookContext['source'],\n current: OAuthCredentials,\n allCredentials?: Record<string, OAuthCredentials | undefined>,\n persistCredentials?: (credentials: Record<string, OAuthCredentials | undefined>) => void,\n ): Promise<string> {\n // Only the refresh call itself maps to `refreshError` — a throwing\n // persist or onOAuthRefresh hook after a SUCCESSFUL refresh must not be\n // misreported as a refresh failure, so those run outside the try.\n let result: Awaited<ReturnType<GetOAuthApiKey>>\n try {\n const refreshOAuthApiKey = options.getOAuthApiKey ?? getOAuthApiKey\n // A 401 can mean server-side revocation/expiry before our local timestamp,\n // so ask the helper to rotate regardless of what `expires` claims. Passed\n // as a flag rather than by handing it `{ ...current, expires: 0 }`: the\n // persist gate below is an identity check against `current`, so a\n // fabricated credential that a provider echoes back (a no-op refresh in a\n // custom flow, or an injected `getOAuthApiKey`) would read as a real\n // rotation and write `expires: 0` into the credential store — poisoning\n // every later resolve into refreshing on every turn.\n const stillRejectedGeneration = options.rejectedAccess === undefined || current.access === options.rejectedAccess\n const force = options.forceRefresh === true && stillRejectedGeneration\n result = await refreshOAuthApiKey(\n options.providerId,\n { [options.providerId]: current } as Record<string, OAuthCredentials>,\n { force },\n )\n }\n catch (err) {\n throw new Error(options.refreshError(errorMessage(err)))\n }\n if (!result)\n throw new Error(options.refreshError(options.missingError))\n\n if (result.newCredentials !== current) {\n // pi-ai's refresh returns only `{ access, refresh, expires }`. Merge it\n // onto the current credential so the persisted entry keeps its on-disk\n // `kind: 'oauth'` tag and any provider extras (e.g. openai-codex\n // `accountId`). A bare overwrite strips `kind`, and the TUI's auth-state\n // detection keys on `kind === 'oauth'` — so without this the provider\n // reads as signed out after every token refresh, forcing a daily re-login.\n const refreshed = { ...current, ...result.newCredentials }\n if (source === 'file' && allCredentials && persistCredentials) {\n allCredentials[options.providerId] = refreshed\n persistCredentials(allCredentials)\n }\n\n await callbacks?.onOAuthRefresh?.({\n provider: options.provider,\n providerId: options.providerId,\n source,\n previousCredentials: { ...current },\n credentials: { ...refreshed },\n })\n }\n\n return result.apiKey\n }\n}\n\n/**\n * Coalesce concurrent refresh calls onto a single in-flight promise per key.\n * The key combines the source (`params` vs `file`) and provider id, so a\n * per-agent param-only refresh does not starve a separate file-backed one.\n */\nasync function withRefreshLock(key: string, fn: () => Promise<string>): Promise<string> {\n const existing = refreshLocks.get(key)\n if (existing)\n return existing\n\n const task = (async () => {\n try {\n return await fn()\n }\n finally {\n refreshLocks.delete(key)\n }\n })()\n refreshLocks.set(key, task)\n return task\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0DA,eAAe,wBACb,YACA,OACA,cAC2B;CAC3B,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,kBAAkB,WAAW,uBAAuB;CAKtE,MAAM,EAAE,MAAM,OAAO,GAAG,gBACpB,MAAM,MAAM,QACZ;EAAE,MAAM;EAAS,QAAQ;EAAI,SAAS;EAAc,SAAS;CAAE,GAC/D,IAAI,gBAAgB,CAAC,CAAC,MACxB;CACF,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,IAAI,oBAA0C;AAC9C,SAAgB,0BAAyC;CACvD,sBAAsB,OAAO,kCAAkC,CAC5D,MAAM,EAAE,4BAA4B;EACnC,sBAAsB;CACxB,CAAC,CAAC,CACD,YAAY;EACX,oBAAoB;CACtB,CAAC;CACH,OAAO;AACT;;;;;;AAOA,eAAsB,sBAAsB,cAAiD;CAC3F,MAAM,wBAAwB;CAC9B,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,wBAAwB,aAAa,kBAAkB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC1F;;;;;;;AAQA,eAAsB,wBAAwB,cAAiD;CAC7F,MAAM,wBAAwB;CAC9B,MAAM,EAAE,wBAAwB,MAAM,OAAO;CAC7C,OAAO,wBAAwB,gBAAgB,oBAAoB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC/F;;;;;;;;;;;;;AAcA,SAAS,gBACP,IACA,MACA,cACwB;CACxB,OAAO;EACL;EACA;EACA,OAAO,YAAY;GACjB,MAAM,IAAI,MAAM,mBAAmB,GAAG,+DAA+D;EACvG;EACA;EACA,YAAW,gBAAe,YAAY;CACxC;AACF;;;;;;;;AASA,MAAM,cAAc;;;;;;;;;;;;;;AAepB,eAAe,oBAAoB,aAA0D;CA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WAAW,iBAAiB;IAChC,UAAU,QAAQ;IAClB,YAAY,QAAQ;IACpB;IACA,qBAAqB,EAAE,GAAG,QAAQ;IAClC,aAAa,EAAE,GAAG,UAAU;GAC9B,CAAC;EACH;EAEA,OAAO,OAAO;CAChB;AACF;;;;;;AAOA,eAAe,gBAAgB,KAAa,IAA4C;CACtF,MAAM,WAAW,aAAa,IAAI,GAAG;CACrC,IAAI,UACF,OAAO;CAET,MAAM,QAAQ,YAAY;EACxB,IAAI;GACF,OAAO,MAAM,GAAG;EAClB,UACQ;GACN,aAAa,OAAO,GAAG;EACzB;CACF,EAAA,CAAG;CACH,aAAa,IAAI,KAAK,IAAI;CAC1B,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $n as HeadlessResult, Jn as FormattedHeadlessTurnEvent, Qn as HeadlessOutputFormat, Xn as HeadlessEvent, qi as Agent, qn as FormattedHeadlessResult } from "../index-
|
|
1
|
+
import { $n as HeadlessResult, Jn as FormattedHeadlessTurnEvent, Qn as HeadlessOutputFormat, Xn as HeadlessEvent, qi as Agent, qn as FormattedHeadlessResult } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
|
|
3
3
|
//#region src/output/stream-json.d.ts
|
|
4
4
|
type StreamJsonOutputFormat = HeadlessOutputFormat;
|
package/dist/plugins.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Ac as
|
|
1
|
+
import { Ac as PLUGIN_MANIFEST_FILE, Bc as PluginSchemaKind, Dc as ManifestValidation, Ec as expandPluginVars, Fc as LoadedPlugin, Hc as agentPluginsSchemaId, Ic as PluginAuthor, Lc as PluginComponentStatus, Mc as loadAgentPlugin, Nc as AgentPluginsVersion, Oc as parsePluginManifest, Pc as LoadAgentPluginOptions, Rc as PluginDiagnostic, Tc as PLUGIN_MCP_FILE, Uc as isSupportedAgentPluginsVersion, Vc as SUPPORTED_AGENT_PLUGINS_VERSIONS, Wc as parseSchemaId, jc as defaultPluginDataRoot, kc as validatePluginManifest, wc as PLUGIN_SKILLS_DIR, zc as PluginManifest } from "./index-CfEJ5Vf9.js";
|
|
2
2
|
export { type AgentPluginsVersion, type LoadAgentPluginOptions, type LoadedPlugin, type ManifestValidation, PLUGIN_MANIFEST_FILE, PLUGIN_MCP_FILE, PLUGIN_SKILLS_DIR, type PluginAuthor, type PluginComponentStatus, type PluginDiagnostic, type PluginManifest, type PluginSchemaKind, SUPPORTED_AGENT_PLUGINS_VERSIONS, agentPluginsSchemaId, defaultPluginDataRoot, expandPluginVars, isSupportedAgentPluginsVersion, loadAgentPlugin, parsePluginManifest, parseSchemaId, validatePluginManifest };
|
package/dist/presets.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Ji as AgentHookMap, Ki as _default, a as basicTools, i as _default$1, n as composePresets, r as definePreset, t as Preset } from "./index-
|
|
1
|
+
import { Ji as AgentHookMap, Ki as _default, a as basicTools, i as _default$1, n as composePresets, r as definePreset, t as Preset } from "./index-CfEJ5Vf9.js";
|
|
2
2
|
export { type AgentHookMap, Preset, _default as artifacts, _default$1 as basic, basicTools, composePresets, definePreset };
|
package/dist/presets.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Jt as artifacts_default, bt as basicTools, vt as composePresets, xt as basic_default, yt as definePreset } from "./agent-
|
|
1
|
+
import { Jt as artifacts_default, bt as basicTools, vt as composePresets, xt as basic_default, yt as definePreset } from "./agent-Djzx-1kD.js";
|
|
2
2
|
export { artifacts_default as artifacts, basic_default as basic, basicTools, composePresets, definePreset };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Ah as
|
|
1
|
+
import { Ah as anthropic, Bh as resolveAnthropicMaxOutput, Dh as AnthropicParams, Eh as AnthropicContextManagement, Fh as credentialIdentity, Ih as defaultAnthropicMaxTokens, Lh as planAnthropicThinking, Mh as buildAnthropicClientOptions, Nh as cacheWriteTtlMultiplier, Oh as AnthropicThinkingPlan, Ph as classifyAnthropicError, Rh as resolveAnthropicAuthShape, Th as AnthropicBedrockConfig, jh as applyAnthropicCacheBreakpoints, kh as EXTENDED_CACHE_TTL_BETA, zh as resolveAnthropicBetas } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { AnthropicBedrockConfig, AnthropicContextManagement, AnthropicParams, AnthropicThinkingPlan, EXTENDED_CACHE_TTL_BETA, anthropic, applyAnthropicCacheBreakpoints, buildAnthropicClientOptions, cacheWriteTtlMultiplier, classifyAnthropicError, credentialIdentity, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicAuthShape, resolveAnthropicBetas, resolveAnthropicMaxOutput };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as cacheWriteTtlMultiplier, c as defaultAnthropicMaxTokens, d as resolveAnthropicBetas, f as resolveAnthropicMaxOutput, i as buildAnthropicClientOptions, l as planAnthropicThinking, n as anthropic, o as classifyAnthropicError, r as applyAnthropicCacheBreakpoints, s as credentialIdentity, t as EXTENDED_CACHE_TTL_BETA, u as resolveAnthropicAuthShape } from "../anthropic-
|
|
1
|
+
import { a as cacheWriteTtlMultiplier, c as defaultAnthropicMaxTokens, d as resolveAnthropicBetas, f as resolveAnthropicMaxOutput, i as buildAnthropicClientOptions, l as planAnthropicThinking, n as anthropic, o as classifyAnthropicError, r as applyAnthropicCacheBreakpoints, s as credentialIdentity, t as EXTENDED_CACHE_TTL_BETA, u as resolveAnthropicAuthShape } from "../anthropic-DATE-m9f.js";
|
|
2
2
|
export { EXTENDED_CACHE_TTL_BETA, anthropic, applyAnthropicCacheBreakpoints, buildAnthropicClientOptions, cacheWriteTtlMultiplier, classifyAnthropicError, credentialIdentity, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicAuthShape, resolveAnthropicBetas, resolveAnthropicMaxOutput };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ch as ArceeParams, wh as arcee } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { ArceeParams, arcee };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Sh as planBasetenReasoning, bh as BasetenParams, xh as baseten } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { BasetenParams, baseten, planBasetenReasoning };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { vh as CerebrasParams, yh as cerebras } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { CerebrasParams, cerebras };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { hh as local, mh as LocalParams } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { LocalParams, local };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $m as
|
|
1
|
+
import { $m as formatTools, Bm as OAIMessage, Gm as OpenAICompatStreamError, Hm as OpenAICompatAuthHeader, Jm as applyOAIToolCacheBreakpoint, Km as TOOL_RESULTS_TAG, Qm as consumeSSE, Um as OpenAICompatHttpError, Vm as OAITool, Wm as OpenAICompatParams, Xm as buildAssistantContent, Ym as assistantMessage, Zm as classifyOpenAICompatError, ah as userMessage, eh as mapOAIFinishReason, ih as toolResultsMessage, nh as openaiCompat, qm as applyOAICacheBreakpoints, rh as toOAIMessages, th as openAICompatPromptMessage, zm as ASSISTANT_TOOL_CALLS_TAG } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { ASSISTANT_TOOL_CALLS_TAG, OAIMessage, OAITool, OpenAICompatAuthHeader, OpenAICompatHttpError, OpenAICompatParams, OpenAICompatStreamError, TOOL_RESULTS_TAG, applyOAICacheBreakpoints, applyOAIToolCacheBreakpoint, assistantMessage, buildAssistantContent, classifyOpenAICompatError, consumeSSE, formatTools, mapOAIFinishReason, openAICompatPromptMessage, openaiCompat, toOAIMessages, toolResultsMessage, userMessage };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ch as mapCodexStopReason, lh as openai, oh as OpenAIParams, sh as classifyOpenAIError, uh as toPiMessages } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { OpenAIParams, classifyOpenAIError, mapCodexStopReason, openai, toPiMessages };
|
package/dist/providers/openai.js
CHANGED
|
@@ -3,7 +3,7 @@ import { a as documentBlockMarker, r as assertResolvedMediaBlock } from "../type
|
|
|
3
3
|
import { f as isRetryableHttpStatus, h as matchesToolPairingError, l as classifyErrorPrelude, m as matchesContextExceeded } from "../errors-DKiMrOKq.js";
|
|
4
4
|
import { renderSystemForWire } from "../prompt.js";
|
|
5
5
|
import { f as reasoningWireAction, n as SYNTHETIC_TOOL_RESULT_PLACEHOLDER } from "../messages-aORUmIKe.js";
|
|
6
|
-
import { r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-
|
|
6
|
+
import { r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-D-LZ4ic-.js";
|
|
7
7
|
import { stream } from "@earendil-works/pi-ai/api/openai-codex-responses";
|
|
8
8
|
import { stream as stream$1 } from "@earendil-works/pi-ai/api/openai-responses";
|
|
9
9
|
import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Im as OpenRouterParams, Lm as normalizeOpenRouterModelId, Rm as openrouter } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { OpenRouterParams, normalizeOpenRouterModelId, openrouter };
|
package/dist/providers/xai.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Am as xai, km as XaiParams } from "../index-CfEJ5Vf9.js";
|
|
2
2
|
export { XaiParams, xai };
|
package/dist/providers/xai.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { m as openaiCompat } from "../openai-compat-cIeLSED_.js";
|
|
2
|
-
import { i as isOAuthAccessToken, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-
|
|
2
|
+
import { i as isOAuthAccessToken, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "../oauth-D-LZ4ic-.js";
|
|
3
3
|
import { r as xaiBaseUrl, t as XAI_OAUTH_PROVIDER_ID } from "../xai-CazjStOK.js";
|
|
4
4
|
//#region src/providers/xai.ts
|
|
5
5
|
const DEFAULT_MODEL = "grok-4.6";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { m as openaiCompat } from "./openai-compat-cIeLSED_.js";
|
|
2
|
-
import { s as resolveOAuthApiKey } from "./oauth-
|
|
2
|
+
import { s as resolveOAuthApiKey } from "./oauth-D-LZ4ic-.js";
|
|
3
3
|
import { t as CURSOR_OAUTH_PROVIDER_ID } from "./cursor-iojRXHF9.js";
|
|
4
4
|
//#region src/providers/cursor.ts
|
|
5
5
|
const DEFAULT_MODEL = "claude-4.6-sonnet";
|
|
@@ -134,4 +134,4 @@ function zai(params) {
|
|
|
134
134
|
//#endregion
|
|
135
135
|
export { cursor as a, planMistralReasoning as i, zai as n, mistral as r, planZaiReasoning as t };
|
|
136
136
|
|
|
137
|
-
//# sourceMappingURL=providers-
|
|
137
|
+
//# sourceMappingURL=providers-Bjdvmpfu.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers-CTkZSxvp.js","names":["BASE_URL","getApiKey"],"sources":["../src/providers/cursor.ts","../src/providers/mistral.ts","../src/providers/zai.ts"],"sourcesContent":["import type { Provider, StreamCallbacks } from '.'\nimport { CURSOR_OAUTH_PROVIDER_ID } from '../chat/oauth-page/cursor'\nimport { resolveOAuthApiKey } from './oauth'\nimport { openaiCompat } from './openai-compat'\n\n/**\n * Cursor provider (OAuth).\n *\n * Auth is fully wired: `bun run auth --cursor` (or the TUI wizard) logs in via\n * Cursor's poll-based PKCE flow and persists credentials; this provider resolves\n * + refreshes the OAuth token on every turn via {@link resolveOAuthApiKey}.\n *\n * Inference is **not** wired yet. Cursor does not expose an OpenAI-compatible\n * HTTP endpoint — it speaks a protobuf/Connect agent protocol over HTTP/2 to\n * `api2.cursor.sh`. Implementing `stream()` requires porting that transport\n * (generated protobuf schemas + an HTTP/2 streaming client) in-process, which\n * is intentionally left as a follow-up. Until then `stream()` resolves the\n * token (proving auth works) and then throws a clear, actionable error.\n *\n * The `openaiCompat` base supplies the message-format helpers (`formatTools`,\n * `userMessage`, `toolResultsMessage`, …) so the provider satisfies the full\n * `Provider` contract and slots into the registry; only `stream` is overridden.\n */\nexport interface CursorParams {\n /** Bypass OAuth resolution with an explicit token (mainly for tests). */\n apiKey?: string\n defaultModel?: string\n /**\n * Extra HTTP headers for the eventual Cursor transport. Accepted for API\n * parity with the other providers and forwarded to the openai-compat base,\n * but inert until Cursor inference is implemented (the `stream` override\n * currently throws before any request is made).\n */\n extraHeaders?: Record<string, string>\n}\n\nconst DEFAULT_MODEL = 'claude-4.6-sonnet'\n\nconst NOT_IMPLEMENTED_MESSAGE\n = 'Cursor OAuth login works, but inference over Cursor is not implemented yet. '\n + 'Cursor uses a protobuf/HTTP-2 agent protocol (not an OpenAI-compatible API), '\n + 'so the streaming transport still needs to be ported. Use another provider for now.'\n\nexport function cursor(params?: CursorParams): Provider {\n const defaultModel = params?.defaultModel || DEFAULT_MODEL\n\n // Base only provides the format/serialization methods; `baseURL` is never\n // hit because we override `stream` below.\n const base = openaiCompat({\n name: 'cursor',\n apiKey: params?.apiKey ?? 'oauth',\n baseURL: 'https://api2.cursor.sh',\n defaultModel,\n capabilities: { vision: true, imageInToolResult: false },\n extraHeaders: params?.extraHeaders,\n })\n\n return {\n ...base,\n meta: { ...base.meta, defaultModel },\n async stream(options, callbacks: StreamCallbacks) {\n // Resolve (and lazily refresh) the OAuth token so auth failures surface\n // here with the right remediation, distinct from the not-implemented path.\n await resolveOAuthApiKey(\n {\n provider: 'cursor',\n providerId: CURSOR_OAUTH_PROVIDER_ID,\n params,\n missingError: 'No Cursor credentials found. Run `bun run auth --cursor` first.',\n refreshError: reason => `Cursor OAuth token refresh failed. Run \\`bun run auth --cursor\\` again. ${reason}`,\n },\n callbacks,\n )\n void options\n throw new Error(NOT_IMPLEMENTED_MESSAGE)\n },\n }\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Mistral La Plateforme — OpenAI-compatible `/v1/chat/completions`. Model ids\n// are plain slugs (`mistral-medium-latest`, `devstral-2512`, …). Reasoning is\n// NOT a separate wire field here: with `reasoning_effort: 'high'` the response\n// `content` becomes a list of `thinking` / `text` chunks (handled by\n// `openaiCompat`'s content-chunk path), and with `'none'` it stays a plain\n// string. See https://docs.mistral.ai/studio-api/conversations/reasoning.\nconst BASE_URL = 'https://api.mistral.ai/v1'\n\nexport interface MistralParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at a regional endpoint or a gateway in\n * front of La Plateforme.\n */\n baseURL?: string\n /**\n * Provider capability flags. The `mistral-medium` / `mistral-large` /\n * `pixtral` families accept `image_url` parts — default:\n * `{ vision: true, imageInToolResult: false }`. Set `vision: false` when\n * pinning a text-only model (`codestral`, `devstral`, `ministral`).\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: MistralParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.MISTRAL_API_KEY)\n return process.env.MISTRAL_API_KEY\n\n throw new Error('No Mistral API key found. Pass `apiKey` or set MISTRAL_API_KEY in your environment.')\n}\n\n/**\n * Model ids that accept `reasoning_effort`. Mistral rejects unknown request\n * fields on some routes, so the knob is sent only for the families that\n * document it (`mistral-small-*`, `mistral-medium-3.5` / `-2604`, and the\n * deprecated-but-live `magistral-*`); `codestral` / `devstral` / `ministral`\n * requests stay byte-identical to what they were without this planner.\n */\nconst REASONING_MODELS = /^(?:magistral-|mistral-small-|mistral-medium-(?:3\\.5|2604))/\n\n/**\n * Map zidane's thinking level to Mistral's `reasoning_effort`. Only the two\n * documented values are emitted — `'none'` (thinking chunk omitted, `content`\n * stays a plain string) and `'high'` (full thinking chunk). `adaptive` sends\n * nothing so the model's own default applies.\n *\n * Exported for tests.\n */\nexport function planMistralReasoning(\n ctx: { model: string, thinking?: ThinkingLevel },\n): Record<string, unknown> | undefined {\n if (!REASONING_MODELS.test(ctx.model))\n return undefined\n if (ctx.thinking === undefined || ctx.thinking === 'adaptive')\n return undefined\n return { reasoning_effort: ctx.thinking === 'off' ? 'none' : 'high' }\n}\n\n/**\n * Mistral provider (La Plateforme).\n *\n * Thin wrapper around {@link openaiCompat} with Mistral-specific defaults\n * (base URL, default model, `reasoning_effort` planner). `supportsReasoning`\n * stays off: Mistral carries thinking inside `content` chunks rather than a\n * `reasoning_content` field, so there is nothing to echo back upstream —\n * thinking streams to the UI and is dropped from subsequent requests.\n */\nexport function mistral(params?: MistralParams): Provider {\n return openaiCompat({\n name: 'mistral',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'mistral-medium-latest',\n capabilities: params?.capabilities ?? { vision: true, imageInToolResult: false },\n planReasoningRequest: planMistralReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Z.ai (Zhipu) GLM Open Platform — OpenAI-compatible endpoint. Model ids are\n// plain lowercase slugs (`glm-4.7`, `glm-4.7-flash`, …), reasoning streams in\n// the `reasoning_content` delta field, and thinking is toggled via an\n// `extra_body.thinking` object rather than a `reasoning_effort` string.\n// See https://docs.z.ai/guides/develop/http/introduction and\n// https://docs.z.ai/guides/capabilities/thinking-mode.\nconst BASE_URL = 'https://api.z.ai/api/paas/v4'\n\nexport interface ZaiParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at the dedicated Coding Plan endpoint\n * instead of the standard API endpoint.\n */\n baseURL?: string\n /**\n * Provider capability flags. GLM text models are text-only — default:\n * `{ vision: false, imageInToolResult: false }`.\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: ZaiParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.ZAI_API_KEY)\n return process.env.ZAI_API_KEY\n\n throw new Error('No Z.ai API key found. Pass `apiKey` or set ZAI_API_KEY in your environment.')\n}\n\n/**\n * Map zidane's thinking level to Z.ai's `extra_body.thinking` request shape.\n * GLM has no depth knob — thinking is a binary switch — so any non-`off`\n * level enables it and `off` explicitly disables it (GLM-5.x/4.7 think by\n * default, so a silent omission would not turn thinking off).\n *\n * Exported for tests.\n */\nexport function planZaiReasoning(\n ctx: { thinking?: ThinkingLevel },\n): Record<string, unknown> {\n const enabled = !!ctx.thinking && ctx.thinking !== 'off'\n return { thinking: { type: enabled ? 'enabled' : 'disabled' } }\n}\n\n/**\n * Z.ai (Zhipu) GLM provider.\n *\n * Thin wrapper around {@link openaiCompat} pinned to the `reasoning_content`\n * round-trip mode: thinking arrives in the `reasoning_content` delta field and\n * is echoed back on assistant messages under the same name, keeping GLM's\n * interleaved/preserved thinking coherent across tool calls.\n */\nexport function zai(params?: ZaiParams): Provider {\n return openaiCompat({\n name: 'zai',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'glm-5.3-flash',\n capabilities: params?.capabilities ?? { vision: false, imageInToolResult: false },\n supportsReasoning: true,\n reasoningMode: 'reasoning_content',\n reasoningContentField: 'reasoning_content',\n planReasoningRequest: planZaiReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n"],"mappings":";;;;AAoCA,MAAM,gBAAgB;AAEtB,MAAM,0BACF;A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QAA4B;CAE7C,IAAI,OAAO,QAAQ,WAAW,YAAY,OAAO,OAAO,SAAS,GAC/D,OAAO,OAAO;CAEhB,IAAI,QAAQ,IAAI,aACd,OAAO,QAAQ,IAAI;CAErB,MAAM,IAAI,MAAM,8EAA8E;AAChG;;;;;;;;;AAUA,SAAgB,iBACd,KACyB;CAEzB,OAAO,EAAE,UAAU,EAAE,MADL,CAAC,CAAC,IAAI,YAAY,IAAI,aAAa,QACd,YAAY,WAAW,EAAE;AAChE;;;;;;;;;AAUA,SAAgB,IAAI,QAA8B;CAChD,OAAO,aAAa;EAClB,MAAM;EACN,QAAQ,UAAU,MAAM;EACxB,SAAS,QAAQ,WAAW;EAC5B,cAAc,QAAQ,gBAAgB;EACtC,cAAc,QAAQ,gBAAgB;GAAE,QAAQ;GAAO,mBAAmB;EAAM;EAChF,mBAAmB;EACnB,eAAe;EACf,uBAAuB;EACvB,sBAAsB;EACtB,cAAc,QAAQ;CACxB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"providers-Bjdvmpfu.js","names":["BASE_URL","getApiKey"],"sources":["../src/providers/cursor.ts","../src/providers/mistral.ts","../src/providers/zai.ts"],"sourcesContent":["import type { Provider, StreamCallbacks } from '.'\nimport { CURSOR_OAUTH_PROVIDER_ID } from '../chat/oauth-page/cursor'\nimport { resolveOAuthApiKey } from './oauth'\nimport { openaiCompat } from './openai-compat'\n\n/**\n * Cursor provider (OAuth).\n *\n * Auth is fully wired: `bun run auth --cursor` (or the TUI wizard) logs in via\n * Cursor's poll-based PKCE flow and persists credentials; this provider resolves\n * + refreshes the OAuth token on every turn via {@link resolveOAuthApiKey}.\n *\n * Inference is **not** wired yet. Cursor does not expose an OpenAI-compatible\n * HTTP endpoint — it speaks a protobuf/Connect agent protocol over HTTP/2 to\n * `api2.cursor.sh`. Implementing `stream()` requires porting that transport\n * (generated protobuf schemas + an HTTP/2 streaming client) in-process, which\n * is intentionally left as a follow-up. Until then `stream()` resolves the\n * token (proving auth works) and then throws a clear, actionable error.\n *\n * The `openaiCompat` base supplies the message-format helpers (`formatTools`,\n * `userMessage`, `toolResultsMessage`, …) so the provider satisfies the full\n * `Provider` contract and slots into the registry; only `stream` is overridden.\n */\nexport interface CursorParams {\n /** Bypass OAuth resolution with an explicit token (mainly for tests). */\n apiKey?: string\n defaultModel?: string\n /**\n * Extra HTTP headers for the eventual Cursor transport. Accepted for API\n * parity with the other providers and forwarded to the openai-compat base,\n * but inert until Cursor inference is implemented (the `stream` override\n * currently throws before any request is made).\n */\n extraHeaders?: Record<string, string>\n}\n\nconst DEFAULT_MODEL = 'claude-4.6-sonnet'\n\nconst NOT_IMPLEMENTED_MESSAGE\n = 'Cursor OAuth login works, but inference over Cursor is not implemented yet. '\n + 'Cursor uses a protobuf/HTTP-2 agent protocol (not an OpenAI-compatible API), '\n + 'so the streaming transport still needs to be ported. Use another provider for now.'\n\nexport function cursor(params?: CursorParams): Provider {\n const defaultModel = params?.defaultModel || DEFAULT_MODEL\n\n // Base only provides the format/serialization methods; `baseURL` is never\n // hit because we override `stream` below.\n const base = openaiCompat({\n name: 'cursor',\n apiKey: params?.apiKey ?? 'oauth',\n baseURL: 'https://api2.cursor.sh',\n defaultModel,\n capabilities: { vision: true, imageInToolResult: false },\n extraHeaders: params?.extraHeaders,\n })\n\n return {\n ...base,\n meta: { ...base.meta, defaultModel },\n async stream(options, callbacks: StreamCallbacks) {\n // Resolve (and lazily refresh) the OAuth token so auth failures surface\n // here with the right remediation, distinct from the not-implemented path.\n await resolveOAuthApiKey(\n {\n provider: 'cursor',\n providerId: CURSOR_OAUTH_PROVIDER_ID,\n params,\n missingError: 'No Cursor credentials found. Run `bun run auth --cursor` first.',\n refreshError: reason => `Cursor OAuth token refresh failed. Run \\`bun run auth --cursor\\` again. ${reason}`,\n },\n callbacks,\n )\n void options\n throw new Error(NOT_IMPLEMENTED_MESSAGE)\n },\n }\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Mistral La Plateforme — OpenAI-compatible `/v1/chat/completions`. Model ids\n// are plain slugs (`mistral-medium-latest`, `devstral-2512`, …). Reasoning is\n// NOT a separate wire field here: with `reasoning_effort: 'high'` the response\n// `content` becomes a list of `thinking` / `text` chunks (handled by\n// `openaiCompat`'s content-chunk path), and with `'none'` it stays a plain\n// string. See https://docs.mistral.ai/studio-api/conversations/reasoning.\nconst BASE_URL = 'https://api.mistral.ai/v1'\n\nexport interface MistralParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at a regional endpoint or a gateway in\n * front of La Plateforme.\n */\n baseURL?: string\n /**\n * Provider capability flags. The `mistral-medium` / `mistral-large` /\n * `pixtral` families accept `image_url` parts — default:\n * `{ vision: true, imageInToolResult: false }`. Set `vision: false` when\n * pinning a text-only model (`codestral`, `devstral`, `ministral`).\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: MistralParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.MISTRAL_API_KEY)\n return process.env.MISTRAL_API_KEY\n\n throw new Error('No Mistral API key found. Pass `apiKey` or set MISTRAL_API_KEY in your environment.')\n}\n\n/**\n * Model ids that accept `reasoning_effort`. Mistral rejects unknown request\n * fields on some routes, so the knob is sent only for the families that\n * document it (`mistral-small-*`, `mistral-medium-3.5` / `-2604`, and the\n * deprecated-but-live `magistral-*`); `codestral` / `devstral` / `ministral`\n * requests stay byte-identical to what they were without this planner.\n */\nconst REASONING_MODELS = /^(?:magistral-|mistral-small-|mistral-medium-(?:3\\.5|2604))/\n\n/**\n * Map zidane's thinking level to Mistral's `reasoning_effort`. Only the two\n * documented values are emitted — `'none'` (thinking chunk omitted, `content`\n * stays a plain string) and `'high'` (full thinking chunk). `adaptive` sends\n * nothing so the model's own default applies.\n *\n * Exported for tests.\n */\nexport function planMistralReasoning(\n ctx: { model: string, thinking?: ThinkingLevel },\n): Record<string, unknown> | undefined {\n if (!REASONING_MODELS.test(ctx.model))\n return undefined\n if (ctx.thinking === undefined || ctx.thinking === 'adaptive')\n return undefined\n return { reasoning_effort: ctx.thinking === 'off' ? 'none' : 'high' }\n}\n\n/**\n * Mistral provider (La Plateforme).\n *\n * Thin wrapper around {@link openaiCompat} with Mistral-specific defaults\n * (base URL, default model, `reasoning_effort` planner). `supportsReasoning`\n * stays off: Mistral carries thinking inside `content` chunks rather than a\n * `reasoning_content` field, so there is nothing to echo back upstream —\n * thinking streams to the UI and is dropped from subsequent requests.\n */\nexport function mistral(params?: MistralParams): Provider {\n return openaiCompat({\n name: 'mistral',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'mistral-medium-latest',\n capabilities: params?.capabilities ?? { vision: true, imageInToolResult: false },\n planReasoningRequest: planMistralReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Z.ai (Zhipu) GLM Open Platform — OpenAI-compatible endpoint. Model ids are\n// plain lowercase slugs (`glm-4.7`, `glm-4.7-flash`, …), reasoning streams in\n// the `reasoning_content` delta field, and thinking is toggled via an\n// `extra_body.thinking` object rather than a `reasoning_effort` string.\n// See https://docs.z.ai/guides/develop/http/introduction and\n// https://docs.z.ai/guides/capabilities/thinking-mode.\nconst BASE_URL = 'https://api.z.ai/api/paas/v4'\n\nexport interface ZaiParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at the dedicated Coding Plan endpoint\n * instead of the standard API endpoint.\n */\n baseURL?: string\n /**\n * Provider capability flags. GLM text models are text-only — default:\n * `{ vision: false, imageInToolResult: false }`.\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: ZaiParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.ZAI_API_KEY)\n return process.env.ZAI_API_KEY\n\n throw new Error('No Z.ai API key found. Pass `apiKey` or set ZAI_API_KEY in your environment.')\n}\n\n/**\n * Map zidane's thinking level to Z.ai's `extra_body.thinking` request shape.\n * GLM has no depth knob — thinking is a binary switch — so any non-`off`\n * level enables it and `off` explicitly disables it (GLM-5.x/4.7 think by\n * default, so a silent omission would not turn thinking off).\n *\n * Exported for tests.\n */\nexport function planZaiReasoning(\n ctx: { thinking?: ThinkingLevel },\n): Record<string, unknown> {\n const enabled = !!ctx.thinking && ctx.thinking !== 'off'\n return { thinking: { type: enabled ? 'enabled' : 'disabled' } }\n}\n\n/**\n * Z.ai (Zhipu) GLM provider.\n *\n * Thin wrapper around {@link openaiCompat} pinned to the `reasoning_content`\n * round-trip mode: thinking arrives in the `reasoning_content` delta field and\n * is echoed back on assistant messages under the same name, keeping GLM's\n * interleaved/preserved thinking coherent across tool calls.\n */\nexport function zai(params?: ZaiParams): Provider {\n return openaiCompat({\n name: 'zai',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'glm-5.3-flash',\n capabilities: params?.capabilities ?? { vision: false, imageInToolResult: false },\n supportsReasoning: true,\n reasoningMode: 'reasoning_content',\n reasoningContentField: 'reasoning_content',\n planReasoningRequest: planZaiReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n"],"mappings":";;;;AAoCA,MAAM,gBAAgB;AAEtB,MAAM,0BACF;AAIJ,SAAgB,OAAO,QAAiC;CACtD,MAAM,eAAe,QAAQ,gBAAgB;CAI7C,MAAM,OAAO,aAAa;EACxB,MAAM;EACN,QAAQ,QAAQ,UAAU;EA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,IAAI;CAErB,MAAM,IAAI,MAAM,8EAA8E;AAChG;;;;;;;;;AAUA,SAAgB,iBACd,KACyB;CAEzB,OAAO,EAAE,UAAU,EAAE,MADL,CAAC,CAAC,IAAI,YAAY,IAAI,aAAa,QACd,YAAY,WAAW,EAAE;AAChE;;;;;;;;;AAUA,SAAgB,IAAI,QAA8B;CAChD,OAAO,aAAa;EAClB,MAAM;EACN,QAAQ,UAAU,MAAM;EACxB,SAAS,QAAQ,WAAW;EAC5B,cAAc,QAAQ,gBAAgB;EACtC,cAAc,QAAQ,gBAAgB;GAAE,QAAQ;GAAO,mBAAmB;EAAM;EAChF,mBAAmB;EACnB,eAAe;EACf,uBAAuB;EACvB,sBAAsB;EACtB,cAAc,QAAQ;CACxB,CAAC;AACH"}
|
package/dist/providers.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $h as
|
|
2
|
-
export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, HistoryRepair, type LocalParams, type MistralParams, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogSource, type OAuthParams, type OAuthProviderInterface, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, type PromptCacheKeyContext, type PromptCacheKeyOption, Provider, ProviderCapabilities, ProviderMeta, type ResolveOAuthApiKeyOptions, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, type XaiParams, type ZaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, extractRuntimeCredentials, getModelCatalog, getOAuthApiKey, getOAuthProvider, isOAuthAccessToken, local, mapOAIFinishReason, mistral, openai, openaiCompat, openrouter, planBasetenReasoning, planMistralReasoning, planZaiReasoning, readOAuthCredentials, refreshAnthropicToken, refreshOpenAICodexToken, registerCustomOAuthProvider, registerOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
|
|
1
|
+
import { $h as resolveOAuthApiKey, Ah as anthropic, Am as xai, Ch as ArceeParams, Cm as ToolResult, Dh as AnthropicParams, Dm as planZaiReasoning, Em as ZaiParams, Fm as sanitizeToolSpecs, Gh as OAuthParams, Hh as PromptCacheKeyOption, Hm as OpenAICompatAuthHeader, Im as OpenRouterParams, Jh as credentialsFromParams, Kh as ResolveOAuthApiKeyOptions, Mm as SchemaSanitizeProfile, Nm as SchemaSanitizeResult, Om as zai, Pm as sanitizeToolSchema, Qh as registerCustomOAuthProvider, Rm as openrouter, Sh as planBasetenReasoning, Sm as ToolCall, Sy as setModelCatalog, Tm as TurnResult, Uh as derivePromptCacheKey, Um as OpenAICompatHttpError, Vh as PromptCacheKeyContext, Wh as resolvePromptCacheKey, Wm as OpenAICompatParams, Xh as isOAuthAccessToken, Yh as extractRuntimeCredentials, Zh as readOAuthCredentials, Zm as classifyOpenAICompatError, _h as cursor, _m as ProviderCapabilities, ag as refreshAnthropicToken, bh as BasetenParams, bm as StreamOptions, by as ModelCatalogSource, dh as MistralParams, eg as writeOAuthCredentials, eh as mapOAIFinishReason, fh as mistral, gh as CursorParams, gm as Provider, hh as local, hm as HistoryRepair, ig as getOAuthProvider, jh as applyAnthropicCacheBreakpoints, jm as SchemaSanitizeOptions, km as XaiParams, lh as openai, mh as LocalParams, ng as ensureBundledOAuthFlows, nh as openaiCompat, og as refreshOpenAICodexToken, oh as OpenAIParams, ph as planMistralReasoning, qh as credentialsFilePath, rg as getOAuthApiKey, sg as registerOAuthProvider, tg as OAuthProviderInterface, vh as CerebrasParams, vm as ProviderMeta, vy as ModelCatalog, wh as arcee, wm as ToolSpec, xh as baseten, xm as TokenCountPayload, xy as getModelCatalog, yh as cerebras, ym as StreamCallbacks, yy as ModelCatalogEntry } from "./index-CfEJ5Vf9.js";
|
|
2
|
+
export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, HistoryRepair, type LocalParams, type MistralParams, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogSource, type OAuthParams, type OAuthProviderInterface, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, type PromptCacheKeyContext, type PromptCacheKeyOption, Provider, ProviderCapabilities, ProviderMeta, type ResolveOAuthApiKeyOptions, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, type XaiParams, type ZaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, ensureBundledOAuthFlows, extractRuntimeCredentials, getModelCatalog, getOAuthApiKey, getOAuthProvider, isOAuthAccessToken, local, mapOAIFinishReason, mistral, openai, openaiCompat, openrouter, planBasetenReasoning, planMistralReasoning, planZaiReasoning, readOAuthCredentials, refreshAnthropicToken, refreshOpenAICodexToken, registerCustomOAuthProvider, registerOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
|
package/dist/providers.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { E as getModelCatalog, S as resolvePromptCacheKey, b as sanitizeToolSpecs, f as mapOAIFinishReason, j as setModelCatalog, l as classifyOpenAICompatError, m as openaiCompat, n as OpenAICompatHttpError, x as derivePromptCacheKey, y as sanitizeToolSchema } from "./openai-compat-cIeLSED_.js";
|
|
2
|
-
import { n as anthropic, r as applyAnthropicCacheBreakpoints } from "./anthropic-
|
|
3
|
-
import { a as readOAuthCredentials, c as writeOAuthCredentials, d as
|
|
2
|
+
import { n as anthropic, r as applyAnthropicCacheBreakpoints } from "./anthropic-DATE-m9f.js";
|
|
3
|
+
import { a as readOAuthCredentials, c as writeOAuthCredentials, d as getOAuthProvider, f as refreshAnthropicToken, i as isOAuthAccessToken, l as ensureBundledOAuthFlows, m as registerOAuthProvider, n as credentialsFromParams, o as registerCustomOAuthProvider, p as refreshOpenAICodexToken, r as extractRuntimeCredentials, s as resolveOAuthApiKey, t as credentialsFilePath, u as getOAuthApiKey } from "./oauth-D-LZ4ic-.js";
|
|
4
4
|
import { arcee } from "./providers/arcee.js";
|
|
5
5
|
import { baseten, planBasetenReasoning } from "./providers/baseten.js";
|
|
6
6
|
import { cerebras } from "./providers/cerebras.js";
|
|
7
|
-
import { a as cursor, i as planMistralReasoning, n as zai, r as mistral, t as planZaiReasoning } from "./providers-
|
|
7
|
+
import { a as cursor, i as planMistralReasoning, n as zai, r as mistral, t as planZaiReasoning } from "./providers-Bjdvmpfu.js";
|
|
8
8
|
import { local } from "./providers/local.js";
|
|
9
9
|
import { openai } from "./providers/openai.js";
|
|
10
10
|
import { openrouter } from "./providers/openrouter.js";
|
|
11
11
|
import { xai } from "./providers/xai.js";
|
|
12
|
-
export { OpenAICompatHttpError, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, extractRuntimeCredentials, getModelCatalog, getOAuthApiKey, getOAuthProvider, isOAuthAccessToken, local, mapOAIFinishReason, mistral, openai, openaiCompat, openrouter, planBasetenReasoning, planMistralReasoning, planZaiReasoning, readOAuthCredentials, refreshAnthropicToken, refreshOpenAICodexToken, registerCustomOAuthProvider, registerOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
|
|
12
|
+
export { OpenAICompatHttpError, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, ensureBundledOAuthFlows, extractRuntimeCredentials, getModelCatalog, getOAuthApiKey, getOAuthProvider, isOAuthAccessToken, local, mapOAIFinishReason, mistral, openai, openaiCompat, openrouter, planBasetenReasoning, planMistralReasoning, planZaiReasoning, readOAuthCredentials, refreshAnthropicToken, refreshOpenAICodexToken, registerCustomOAuthProvider, registerOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
|
package/dist/restate.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $i as McpToolWrap,
|
|
1
|
+
import { $i as McpToolWrap, L_ as ToolStateStore, Qi as McpToolMeta, S_ as ToolDef, Yg as SessionTurn, bm as StreamOptions, c_ as ToolResultContent, cg as AgentBehavior, dg as AgentStats, ev as SessionStore, gm as Provider, i_ as ToolBatchExecutor, lg as AgentClock, x_ as ToolContext } from "./index-CfEJ5Vf9.js";
|
|
2
2
|
import { g as TaskExitInfo, h as TaskEntry, l as ExecutionHandle, o as DetachedTasksCapability } from "./types-U-rIVUDw.js";
|
|
3
3
|
|
|
4
4
|
//#region src/restate/types.d.ts
|
package/dist/restate.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { L as buildAliasMaps } from "./openai-compat-cIeLSED_.js";
|
|
2
2
|
import { i as coerceToolResultContent, l as toolOutputByteLength, u as toolResultToText } from "./types-CWgENVLY.js";
|
|
3
|
-
import { Ot as reserveChildLabel, a as stagedToolState,
|
|
3
|
+
import { Ot as reserveChildLabel, a as stagedToolState, ar as hydrateReadStateFromSessionAsync, i as isToolStateOps } from "./agent-Djzx-1kD.js";
|
|
4
4
|
import { r as formatTokenUsage } from "./stats-DAKBEKjc.js";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
//#region src/restate/awakeable.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Fn as createExtensionBus, In as serializedPayloadBytes, at as createExtensionHud, gt as createExtensionHostRuntimeBridge, ot as discoverAndBuildExtensionRegistry } from "./agent-
|
|
1
|
+
import { Fn as createExtensionBus, In as serializedPayloadBytes, at as createExtensionHud, gt as createExtensionHostRuntimeBridge, ot as discoverAndBuildExtensionRegistry } from "./agent-Djzx-1kD.js";
|
|
2
2
|
import { S as resolveInlineSuggestion, b as createPathAutocompleteProvider } from "./src-DzzhE2YO.js";
|
|
3
3
|
import { l as normalizeArtifactInput } from "./artifacts-CV2hUKnL.js";
|
|
4
4
|
import { t as writeFileAtomic } from "./atomic-write-B7zr1ddF.js";
|
|
@@ -6,8 +6,8 @@ import { p as resolveStorageDirs } from "./plugins-B531Tz5b.js";
|
|
|
6
6
|
import { a as successResponse, i as errorResponse, n as JsonRpcRemoteError, r as createJsonRpcConnection } from "./json-rpc-rSWMUh9b.js";
|
|
7
7
|
import { It as isMainSession } from "./turn-operations-Dt5L8smX.js";
|
|
8
8
|
import { c as searchSessionHistoryIndexAsync, n as buildSessionSearchIndexAsync, u as searchSessionIndexAsync } from "./history-search-C4bk1Wz_.js";
|
|
9
|
-
import { Gt as modelChainMetadata, In as resolveConfig, It as createChatHost, Kt as sessionModelFallbacks, Lt as toTodosSnapshot, cn as DEFAULT_SETTINGS,
|
|
10
|
-
import { d as BUILTIN_PROVIDERS, n as applyApiKeyEnv, r as credentialsPath } from "./auth-
|
|
9
|
+
import { Gt as modelChainMetadata, In as resolveConfig, It as createChatHost, Kt as sessionModelFallbacks, Lt as toTodosSnapshot, cn as DEFAULT_SETTINGS, fi as deriveSessionTitle, fn as SETTINGS_TOGGLES, ft as createFileMcpCredentialStore, hn as enforceSettingsInvariants, pi as eventsFromTurns } from "./approvals-Jztqzqjk.js";
|
|
10
|
+
import { d as BUILTIN_PROVIDERS, n as applyApiKeyEnv, r as credentialsPath } from "./auth-DhkLW1Wu.js";
|
|
11
11
|
import { basename, dirname, join } from "node:path";
|
|
12
12
|
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
13
13
|
import { spawn } from "node:child_process";
|
|
@@ -1387,4 +1387,4 @@ async function startIpcDaemon(options) {
|
|
|
1387
1387
|
//#endregion
|
|
1388
1388
|
export { connectIpcClient as a, IpcErrorCode as c, defaultSocketPath as d, ensureDaemonRunning as f, IpcVersionMismatchError as i, IPC_BUILD_ID as l, selfDaemonSpawnCommand as m, createDaemonEnvironment as n, connectOrSpawnDaemon as o, probeSocket as p, createFileApprovalsStore as r, IPC_PROTOCOL_VERSION as s, startIpcDaemon as t, daemonSocketName as u };
|
|
1389
1389
|
|
|
1390
|
-
//# sourceMappingURL=server-
|
|
1390
|
+
//# sourceMappingURL=server-Cccx5jES.js.map
|