zidane 6.2.36 → 6.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -5
- package/dist/{acp-DZNCQaTQ.js → acp-Cs86McDR.js} +6 -6
- package/dist/{acp-DZNCQaTQ.js.map → acp-Cs86McDR.js.map} +1 -1
- package/dist/acp-cli.js +7 -7
- package/dist/acp.d.ts +2 -2
- package/dist/acp.js +1 -1
- package/dist/{agent-CrPwqpLI.js → agent-AZ_crMfB.js} +168 -23
- package/dist/agent-AZ_crMfB.js.map +1 -0
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +4 -4
- package/dist/{anthropic-asnZVFS_.js → anthropic-CWwySM3p.js} +59 -24
- package/dist/anthropic-CWwySM3p.js.map +1 -0
- package/dist/{auth-C5YTniaq.js → auth-BPSnotuN.js} +5 -5
- package/dist/auth-BPSnotuN.js.map +1 -0
- package/dist/{cache-telemetry-BhTryxFT.js → cache-telemetry-DzyfqSds.js} +87 -5
- package/dist/cache-telemetry-DzyfqSds.js.map +1 -0
- package/dist/chat/pure.d.ts +3 -3
- package/dist/chat.d.ts +43 -5
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +31 -3
- package/dist/chat.js.map +1 -1
- package/dist/context-transport-64EeXTAQ.js +84 -0
- package/dist/context-transport-64EeXTAQ.js.map +1 -0
- package/dist/contexts/daytona.d.ts +33 -4
- package/dist/contexts/daytona.d.ts.map +1 -1
- package/dist/contexts/daytona.js +136 -0
- package/dist/contexts/daytona.js.map +1 -1
- package/dist/contexts/docker.d.ts +1 -1
- package/dist/contexts/docker.d.ts.map +1 -1
- package/dist/contexts/docker.js +85 -2
- package/dist/contexts/docker.js.map +1 -1
- package/dist/contexts/e2b.d.ts +34 -4
- package/dist/contexts/e2b.d.ts.map +1 -1
- package/dist/contexts/e2b.js +92 -0
- package/dist/contexts/e2b.js.map +1 -1
- package/dist/contexts/sandbox.d.ts +1 -1
- package/dist/contexts/sandbox.js +4 -2
- package/dist/contexts/sandbox.js.map +1 -1
- package/dist/{contexts-o8y5B3Tm.js → contexts-DbMuUPjS.js} +92 -5
- package/dist/contexts-DbMuUPjS.js.map +1 -0
- package/dist/contexts.d.ts +4 -4
- package/dist/contexts.js +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +3 -3
- package/dist/{exec-file-size-PXkr-MGA.js → exec-file-size-BRpoB6Io.js} +3 -32
- package/dist/exec-file-size-BRpoB6Io.js.map +1 -0
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +4 -4
- package/dist/{index-DsPQbyUn.d.ts → index-B9jSo84a.d.ts} +2 -2
- package/dist/index-B9jSo84a.d.ts.map +1 -0
- package/dist/{index-CohO0oaX.d.ts → index-D-PvuMCb.d.ts} +5607 -5188
- package/dist/index-D-PvuMCb.d.ts.map +1 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.js +13 -13
- package/dist/{login-CWwu9Sex.js → login-fgr9zD6z.js} +2 -2
- package/dist/{login-CWwu9Sex.js.map → login-fgr9zD6z.js.map} +1 -1
- package/dist/{mcp-Ct5tF4oj.js → mcp-DolMi7WV.js} +77 -34
- package/dist/mcp-DolMi7WV.js.map +1 -0
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +2 -2
- package/dist/{messages-Cpb4g_KV.js → messages-CLkUdPeG.js} +2 -2
- package/dist/{messages-Cpb4g_KV.js.map → messages-CLkUdPeG.js.map} +1 -1
- package/dist/{oauth-CBi9eymX.js → oauth-CuFPhsHY.js} +117 -11
- package/dist/oauth-CuFPhsHY.js.map +1 -0
- package/dist/{openai-compat-C77gOaHh.js → openai-compat-DHlBIjj9.js} +186 -42
- package/dist/openai-compat-DHlBIjj9.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/prompt.d.ts +1 -1
- package/dist/prompt.js +14 -0
- package/dist/prompt.js.map +1 -1
- package/dist/providers/anthropic.d.ts +2 -2
- package/dist/providers/anthropic.js +2 -2
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/arcee.js +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/baseten.js +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/cerebras.js +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/local.js +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai-compat.js +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +5 -5
- package/dist/providers/openai.js.map +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/openrouter.js +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +1 -1
- package/dist/{providers-DnHPW-dL.js → providers-Nu5ysnXN.js} +4 -4
- package/dist/providers-Nu5ysnXN.js.map +1 -0
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +5 -5
- package/dist/{read-state-rDmfeLmz.js → read-state-CNyeMG7W.js} +7 -4
- package/dist/read-state-CNyeMG7W.js.map +1 -0
- package/dist/restate.d.ts +2 -2
- package/dist/restate.js +2 -2
- package/dist/restate.js.map +1 -1
- package/dist/{sandbox-CgjG2VvQ.d.ts → sandbox-DqwpKX18.d.ts} +14 -2
- package/dist/{sandbox-CgjG2VvQ.d.ts.map → sandbox-DqwpKX18.d.ts.map} +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/{session-DpDBnktP.js → session-vmy9jTVM.js} +2 -2
- package/dist/{session-DpDBnktP.js.map → session-vmy9jTVM.js.map} +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/session.js +2 -2
- package/dist/shell-quote-BmnhZmdM.js +33 -0
- package/dist/shell-quote-BmnhZmdM.js.map +1 -0
- package/dist/skills.d.ts +1 -1
- package/dist/{stdio-loader-Ce68wUmM.js → stdio-D0v-W5w7.js} +8 -215
- package/dist/stdio-D0v-W5w7.js.map +1 -0
- package/dist/stdio-loader-BPUedHxT.js +217 -0
- package/dist/stdio-loader-BPUedHxT.js.map +1 -0
- package/dist/stream-queue-Cd9OJxl7.js +71 -0
- package/dist/stream-queue-Cd9OJxl7.js.map +1 -0
- package/dist/{system-prompt-BlsdjcUi.d.ts → system-prompt-MNVHatSD.d.ts} +15 -1
- package/dist/system-prompt-MNVHatSD.d.ts.map +1 -0
- package/dist/{tool-formatters-bZYz74qU.d.ts → tool-formatters-BPKA2if5.d.ts} +2 -2
- package/dist/{tool-formatters-bZYz74qU.d.ts.map → tool-formatters-BPKA2if5.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 +2 -2
- package/dist/{transcript-anchors-ZZYwCTjo.js → transcript-anchors-6-uB2Xvl.js} +19 -8
- package/dist/transcript-anchors-6-uB2Xvl.js.map +1 -0
- package/dist/{transcript-anchors-EBchHUMo.d.ts → transcript-anchors-DzuIcJpm.d.ts} +2 -2
- package/dist/{transcript-anchors-EBchHUMo.d.ts.map → transcript-anchors-DzuIcJpm.d.ts.map} +1 -1
- package/dist/tui.d.ts +3 -3
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +124 -45
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-DygcPreU.d.ts → turn-operations-Dzr3QhDD.d.ts} +3 -3
- package/dist/{turn-operations-DygcPreU.d.ts.map → turn-operations-Dzr3QhDD.d.ts.map} +1 -1
- package/dist/types-BIarq1qE.js.map +1 -1
- package/dist/{types-BDccavwj.d.ts → types-DdZMQxfT.d.ts} +117 -2
- package/dist/types-DdZMQxfT.d.ts.map +1 -0
- package/dist/types.d.ts +3 -3
- package/dist/{xai-B2hIs5We.js → xai-Cn0LsHRt.js} +3 -3
- package/dist/xai-Cn0LsHRt.js.map +1 -0
- package/docs/ARCHITECTURE.md +62 -4
- package/docs/CHAT.md +12 -5
- package/docs/EXTENSIONS.md +1 -1
- package/docs/RESTATE.md +1 -1
- package/docs/SKILL.md +21 -1
- package/docs/TUI.md +2 -0
- package/package.json +2 -2
- package/dist/agent-CrPwqpLI.js.map +0 -1
- package/dist/anthropic-asnZVFS_.js.map +0 -1
- package/dist/auth-C5YTniaq.js.map +0 -1
- package/dist/cache-telemetry-BhTryxFT.js.map +0 -1
- package/dist/contexts-o8y5B3Tm.js.map +0 -1
- package/dist/exec-file-size-PXkr-MGA.js.map +0 -1
- package/dist/index-CohO0oaX.d.ts.map +0 -1
- package/dist/index-DsPQbyUn.d.ts.map +0 -1
- package/dist/mcp-Ct5tF4oj.js.map +0 -1
- package/dist/oauth-CBi9eymX.js.map +0 -1
- package/dist/openai-compat-C77gOaHh.js.map +0 -1
- package/dist/providers-DnHPW-dL.js.map +0 -1
- package/dist/read-state-rDmfeLmz.js.map +0 -1
- package/dist/stdio-loader-Ce68wUmM.js.map +0 -1
- package/dist/system-prompt-BlsdjcUi.d.ts.map +0 -1
- package/dist/transcript-anchors-ZZYwCTjo.js.map +0 -1
- package/dist/types-BDccavwj.d.ts.map +0 -1
- package/dist/xai-B2hIs5We.js.map +0 -1
|
@@ -1,12 +1,119 @@
|
|
|
1
|
-
import { t as lazyAsync } from "./lazy-DLOurOC_.js";
|
|
2
1
|
import { l as errorMessage } from "./errors-DJUxZg9b.js";
|
|
3
2
|
import { t as writeFileAtomic } from "./atomic-write-B7zr1ddF.js";
|
|
4
3
|
import { resolve } from "node:path";
|
|
5
4
|
import { Buffer } from "node:buffer";
|
|
6
5
|
import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
6
|
import { homedir } from "node:os";
|
|
7
|
+
//#region src/providers/oauth-registry.ts
|
|
8
|
+
/**
|
|
9
|
+
* Run a canonical pi-ai `OAuthAuth.refresh` from a bare refresh token.
|
|
10
|
+
* pi-ai's built-in refresh implementations only read `credential.refresh`,
|
|
11
|
+
* so the placeholder access/expires fields are never observed.
|
|
12
|
+
*
|
|
13
|
+
* The canonical result is an `OAuthCredential` tagged `type: 'oauth'`. Strip
|
|
14
|
+
* the tag before returning: refresh results get merged into stored
|
|
15
|
+
* `.credentials.json` entries and `onOAuthRefresh` hook payloads (see
|
|
16
|
+
* `resolveCredentialSource` in `./oauth.ts`), whose documented shape carries
|
|
17
|
+
* zidane's own `kind` tag — letting pi-ai's `type` leak through would
|
|
18
|
+
* silently drift the on-disk shape.
|
|
19
|
+
*/
|
|
20
|
+
async function refreshViaCanonicalFlow(providerId, oauth, refreshToken) {
|
|
21
|
+
if (!oauth) throw new Error(`pi-ai provider ${providerId} exposes no OAuth flow`);
|
|
22
|
+
const { type: _type, ...credentials } = await oauth.refresh({
|
|
23
|
+
type: "oauth",
|
|
24
|
+
access: "",
|
|
25
|
+
refresh: refreshToken,
|
|
26
|
+
expires: 0
|
|
27
|
+
});
|
|
28
|
+
return credentials;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Refresh an Anthropic (Claude Pro/Max) OAuth token. Drop-in replacement for
|
|
32
|
+
* the `refreshAnthropicToken` pi-ai exported until 0.80.6; delegates to the
|
|
33
|
+
* canonical flow on `anthropicProvider().auth.oauth`.
|
|
34
|
+
*/
|
|
35
|
+
async function refreshAnthropicToken(refreshToken) {
|
|
36
|
+
const { anthropicProvider } = await import("@earendil-works/pi-ai/providers/anthropic");
|
|
37
|
+
return refreshViaCanonicalFlow("anthropic", anthropicProvider().auth.oauth, refreshToken);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Refresh an OpenAI Codex (ChatGPT) OAuth token. Drop-in replacement for the
|
|
41
|
+
* removed `refreshOpenAICodexToken`; the canonical flow still derives
|
|
42
|
+
* `accountId` from the refreshed access token's JWT claims, so the returned
|
|
43
|
+
* credentials keep the extra field older callers persisted.
|
|
44
|
+
*/
|
|
45
|
+
async function refreshOpenAICodexToken(refreshToken) {
|
|
46
|
+
const { openaiCodexProvider } = await import("@earendil-works/pi-ai/providers/openai-codex");
|
|
47
|
+
return refreshViaCanonicalFlow("openai-codex", openaiCodexProvider().auth.oauth, refreshToken);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Built-in registry seeds. pi-ai's removed registry pre-seeded Anthropic and
|
|
51
|
+
* OpenAI Codex, and zidane's lazy token refresh (`getOAuthApiKey` inside
|
|
52
|
+
* `resolveOAuthApiKey`) relied on that — so the local registry seeds the same
|
|
53
|
+
* ids. Login is intentionally unsupported here: interactive login always goes
|
|
54
|
+
* through `ProviderDescriptor.oauthProvider` (the themed flows in
|
|
55
|
+
* `src/chat/oauth-page/`), never through the registry.
|
|
56
|
+
*/
|
|
57
|
+
function builtinProvider(id, name, refreshToken) {
|
|
58
|
+
return {
|
|
59
|
+
id,
|
|
60
|
+
name,
|
|
61
|
+
login: async () => {
|
|
62
|
+
throw new Error(`OAuth login for ${id} must run through a provider descriptor flow, not the registry`);
|
|
63
|
+
},
|
|
64
|
+
refreshToken: (credentials) => refreshToken(credentials.refresh),
|
|
65
|
+
getApiKey: (credentials) => credentials.access
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The registry map is anchored on a process-wide `globalThis` slot rather
|
|
70
|
+
* than module state. The pi-ai registry this replaces lived in pi-ai's own
|
|
71
|
+
* module, so every copy of zidane code in a process shared one map — and two
|
|
72
|
+
* copies is a real configuration, not a hypothetical: a host running from
|
|
73
|
+
* `src` while a disk-loaded extension resolves `'zidane'` to `dist` through
|
|
74
|
+
* ordinary node_modules resolution (see `import()` in
|
|
75
|
+
* `src/extensions/discovery.ts`). The extension registers its flow at setup;
|
|
76
|
+
* `resolveOAuthApiKey` looks it up only once a stored token expires — with
|
|
77
|
+
* per-module maps that fails as a deferred "Unknown OAuth provider", which is
|
|
78
|
+
* nasty to debug. `Symbol.for` restores the process-wide sharing. Whichever
|
|
79
|
+
* copy touches the slot first seeds the built-ins; the seeds are pure
|
|
80
|
+
* delegations to pi-ai's canonical flows, so first-copy-wins is harmless.
|
|
81
|
+
*/
|
|
82
|
+
const REGISTRY_SLOT = Symbol.for("zidane.oauth-provider-registry");
|
|
83
|
+
function oauthProviderRegistry() {
|
|
84
|
+
const slots = globalThis;
|
|
85
|
+
slots[REGISTRY_SLOT] ??= new Map([builtinProvider("anthropic", "Anthropic (Claude Pro/Max)", refreshAnthropicToken), builtinProvider("openai-codex", "OpenAI (ChatGPT Plus/Pro)", refreshOpenAICodexToken)].map((provider) => [provider.id, provider]));
|
|
86
|
+
return slots[REGISTRY_SLOT];
|
|
87
|
+
}
|
|
88
|
+
/** Register (or replace) an OAuth provider by id. */
|
|
89
|
+
function registerOAuthProvider(provider) {
|
|
90
|
+
oauthProviderRegistry().set(provider.id, provider);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Get an API key for a provider from OAuth credentials, refreshing expired
|
|
94
|
+
* tokens through the registered flow. Same contract as the pi-ai original
|
|
95
|
+
* (`null` when no credentials are stored for the provider, throws on unknown
|
|
96
|
+
* provider or refresh failure), except refresh failures keep the underlying
|
|
97
|
+
* reason — the original discarded it, leaving invalid_grant (needs re-login)
|
|
98
|
+
* indistinguishable from a transient network error.
|
|
99
|
+
*/
|
|
100
|
+
async function getOAuthApiKey(providerId, credentials) {
|
|
101
|
+
const provider = oauthProviderRegistry().get(providerId);
|
|
102
|
+
if (!provider) throw new Error(`Unknown OAuth provider: ${providerId}`);
|
|
103
|
+
let creds = credentials[providerId];
|
|
104
|
+
if (!creds) return null;
|
|
105
|
+
if (Date.now() >= creds.expires) try {
|
|
106
|
+
creds = await provider.refreshToken(creds);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
throw new Error(`Failed to refresh OAuth token for ${providerId}: ${errorMessage(err)}`, { cause: err });
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
newCredentials: creds,
|
|
112
|
+
apiKey: provider.getApiKey(creds)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
8
116
|
//#region src/providers/oauth.ts
|
|
9
|
-
const loadGetOAuthApiKey = lazyAsync(async () => (await import("@earendil-works/pi-ai/oauth")).getOAuthApiKey);
|
|
10
117
|
/**
|
|
11
118
|
* Resolve the creds-file path at call time rather than module-load time, so
|
|
12
119
|
* env changes between import and first OAuth use (test suites, multi-project
|
|
@@ -46,17 +153,16 @@ const CREDENTIALS_FILE_MODE = 384;
|
|
|
46
153
|
*/
|
|
47
154
|
const refreshLocks = /* @__PURE__ */ new Map();
|
|
48
155
|
/**
|
|
49
|
-
* Register a custom OAuth flow with
|
|
50
|
-
* {@link resolveOAuthApiKey} can resolve `providerId`.
|
|
156
|
+
* Register a custom OAuth flow with the local registry (`./oauth-registry`)
|
|
157
|
+
* so lazy refresh through {@link resolveOAuthApiKey} can resolve `providerId`.
|
|
51
158
|
*
|
|
52
159
|
* Public because provider extensions need it: without registration,
|
|
53
160
|
* `getOAuthApiKey('<id>', …)` throws `Unknown OAuth provider` the first time a
|
|
54
|
-
* stored token expires. Idempotent per id (the registry is a keyed map)
|
|
55
|
-
*
|
|
56
|
-
*
|
|
161
|
+
* stored token expires. Idempotent per id (the registry is a keyed map). Kept
|
|
162
|
+
* async for API stability — it awaited a dynamic pi-ai import before pi-ai
|
|
163
|
+
* 0.80.8 removed its global registry and this moved in-repo.
|
|
57
164
|
*/
|
|
58
165
|
async function registerCustomOAuthProvider(provider) {
|
|
59
|
-
const { registerOAuthProvider } = await import("@earendil-works/pi-ai/oauth");
|
|
60
166
|
registerOAuthProvider(provider);
|
|
61
167
|
}
|
|
62
168
|
/**
|
|
@@ -320,7 +426,7 @@ async function resolveOAuthApiKey(options, callbacks) {
|
|
|
320
426
|
async function resolveCredentialSource(source, current, allCredentials, persistCredentials) {
|
|
321
427
|
let result;
|
|
322
428
|
try {
|
|
323
|
-
result = await (options.getOAuthApiKey ??
|
|
429
|
+
result = await (options.getOAuthApiKey ?? getOAuthApiKey)(options.providerId, { [options.providerId]: current });
|
|
324
430
|
} catch (err) {
|
|
325
431
|
throw new Error(options.refreshError(errorMessage(err)));
|
|
326
432
|
}
|
|
@@ -364,6 +470,6 @@ async function withRefreshLock(key, fn) {
|
|
|
364
470
|
return task;
|
|
365
471
|
}
|
|
366
472
|
//#endregion
|
|
367
|
-
export { readOAuthCredentials as a, writeOAuthCredentials as c, isOAuthAccessToken as i, credentialsFromParams as n, registerCustomOAuthProvider as o, extractRuntimeCredentials as r, resolveOAuthApiKey as s, credentialsFilePath as t };
|
|
473
|
+
export { readOAuthCredentials as a, writeOAuthCredentials as c, registerOAuthProvider as d, isOAuthAccessToken as i, refreshAnthropicToken as l, credentialsFromParams as n, registerCustomOAuthProvider as o, extractRuntimeCredentials as r, resolveOAuthApiKey as s, credentialsFilePath as t, refreshOpenAICodexToken as u };
|
|
368
474
|
|
|
369
|
-
//# sourceMappingURL=oauth-
|
|
475
|
+
//# sourceMappingURL=oauth-CuFPhsHY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-CuFPhsHY.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 const { type: _type, ...credentials }\n = await oauth.refresh({ type: 'oauth', access: '', refresh: refreshToken, expires: 0 })\n return credentials\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 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 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. pi-ai's removed registry pre-seeded Anthropic and\n * OpenAI Codex, and zidane's lazy token refresh (`getOAuthApiKey` inside\n * `resolveOAuthApiKey`) relied on that — so the local registry seeds the same\n * ids. 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: (token: string) => 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: credentials => refreshToken(credentials.refresh),\n getApiKey: credentials => credentials.access,\n }\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; the seeds are pure\n * delegations to pi-ai's canonical flows, so first-copy-wins is harmless.\n */\nconst 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)', refreshAnthropicToken),\n builtinProvider('openai-codex', 'OpenAI (ChatGPT Plus/Pro)', refreshOpenAICodexToken),\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), except refresh failures keep the underlying\n * reason — the original discarded it, leaving invalid_grant (needs re-login)\n * indistinguishable from a transient network error.\n */\nexport async function getOAuthApiKey(\n providerId: string,\n credentials: Record<string, OAuthCredentials>,\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 (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\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 result = await refreshOAuthApiKey(options.providerId, { [options.providerId]: current } as Record<string, OAuthCredentials>)\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;CACtE,MAAM,EAAE,MAAM,OAAO,GAAG,gBACpB,MAAM,MAAM,QAAQ;EAAE,MAAM;EAAS,QAAQ;EAAI,SAAS;EAAc,SAAS;CAAE,CAAC;CACxF,OAAO;AACT;;;;;;AAOA,eAAsB,sBAAsB,cAAiD;CAC3F,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,wBAAwB,aAAa,kBAAkB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC1F;;;;;;;AAQA,eAAsB,wBAAwB,cAAiD;CAC7F,MAAM,EAAE,wBAAwB,MAAM,OAAO;CAC7C,OAAO,wBAAwB,gBAAgB,oBAAoB,CAAC,CAAC,KAAK,OAAO,YAAY;AAC/F;;;;;;;;;AAUA,SAAS,gBACP,IACA,MACA,cACwB;CACxB,OAAO;EACL;EACA;EACA,OAAO,YAAY;GACjB,MAAM,IAAI,MAAM,mBAAmB,GAAG,+DAA+D;EACvG;EACA,eAAc,gBAAe,aAAa,YAAY,OAAO;EAC7D,YAAW,gBAAe,YAAY;CACxC;AACF;;;;;;;;;;;;;;;AAgBA,MAAM,gBAAgB,OAAO,IAAI,gCAAgC;AAEjE,SAAS,wBAA6D;CACpE,MAAM,QAAQ;CACd,MAAM,mBAAmB,IAAI,IAC3B,CACE,gBAAgB,aAAa,8BAA8B,qBAAqB,GAChF,gBAAgB,gBAAgB,6BAA6B,uBAAuB,CACtF,CAAC,CAAC,KAAI,aAAY,CAAC,SAAS,IAAI,QAAQ,CAAC,CA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a,GAAG,CAAC,CAAC;EACzD;EACA,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,QAAQ,aAAa,QAAQ,YAAY,CAAC;EAE5D,IAAI,OAAO,mBAAmB,SAAS;GAOrC,MAAM,YAAY;IAAE,GAAG;IAAS,GAAG,OAAO;GAAe;GACzD,IAAI,WAAW,UAAU,kBAAkB,oBAAoB;IAC7D,eAAe,QAAQ,cAAc;IACrC,mBAAmB,cAAc;GACnC;GAEA,MAAM,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,7 +1,7 @@
|
|
|
1
1
|
import { a as rewriteMessagesToWire, n as buildAliasMaps, o as toCanonicalName, r as buildSanitizedWireAliases, s as toWireName } from "./aliasing-lVFbm81n.js";
|
|
2
2
|
import { i as documentBlockMarker, n as assertResolvedMediaBlock } from "./types-BIarq1qE.js";
|
|
3
3
|
import { n as estimateTokens } from "./utils-ngQzYzZD.js";
|
|
4
|
-
import { c as classifyErrorPrelude, d as isRetryableHttpStatus, f as matchesContextExceeded,
|
|
4
|
+
import { c as classifyErrorPrelude, d as isRetryableHttpStatus, f as matchesContextExceeded, p as matchesToolPairingError } from "./errors-DJUxZg9b.js";
|
|
5
5
|
import { t as audioFormatFromMediaType } from "./media-sniff-Bn76JxAu.js";
|
|
6
6
|
import { renderSystemForWire, splitSystemPrompt } from "./prompt.js";
|
|
7
7
|
//#region src/prompt.ts
|
|
@@ -222,6 +222,32 @@ const EXTRA_COST_RATES = {
|
|
|
222
222
|
* will drift until the dep updates. An optional `multiplier` scales the
|
|
223
223
|
* base rates for premium modes (e.g. fast mode) before totaling.
|
|
224
224
|
*/
|
|
225
|
+
/**
|
|
226
|
+
* Dollar cost of a prompt-cache break's re-billed prefix.
|
|
227
|
+
*
|
|
228
|
+
* The `rebilledTokens` were WRITTEN at the cache-write rate when a healthy
|
|
229
|
+
* turn would have READ them at the cache-read rate, so the waste is
|
|
230
|
+
* `(write − read) × tokens`. Same registry + fallback-table resolution and
|
|
231
|
+
* the same doctrine as {@link fillEstimatedCost}: returns `undefined` on a
|
|
232
|
+
* rate miss (unknown provider/model, or no published cache-write rate) —
|
|
233
|
+
* better than fabricating a $0. An optional `multiplier` scales the base
|
|
234
|
+
* rates for premium modes (e.g. Anthropic fast mode, 1h-TTL writes at 2x).
|
|
235
|
+
*/
|
|
236
|
+
async function estimateRebilledCostUsd(provider, modelId, rebilledTokens, multiplier) {
|
|
237
|
+
if (!modelId || rebilledTokens <= 0) return void 0;
|
|
238
|
+
const getModel = await loadGetModel();
|
|
239
|
+
let model;
|
|
240
|
+
if (getModel) try {
|
|
241
|
+
model = getModel(provider, modelId);
|
|
242
|
+
} catch {
|
|
243
|
+
model = void 0;
|
|
244
|
+
}
|
|
245
|
+
const rates = model?.cost ?? EXTRA_COST_RATES[`${provider}:${modelId}`];
|
|
246
|
+
if (!rates || rates.cacheWrite === void 0) return void 0;
|
|
247
|
+
const write = rates.cacheWrite * (multiplier?.cacheWrite ?? 1);
|
|
248
|
+
const read = (rates.cacheRead ?? 0) * (multiplier?.cacheRead ?? 1);
|
|
249
|
+
return Math.max(0, (write - read) * rebilledTokens / 1e6);
|
|
250
|
+
}
|
|
225
251
|
async function fillEstimatedCost(usage, provider, multiplier) {
|
|
226
252
|
if (usage.cost !== void 0) return usage;
|
|
227
253
|
if (!usage.modelId) return usage;
|
|
@@ -243,19 +269,6 @@ async function fillEstimatedCost(usage, provider, multiplier) {
|
|
|
243
269
|
};
|
|
244
270
|
}
|
|
245
271
|
//#endregion
|
|
246
|
-
//#region src/providers/openai-tool-names.ts
|
|
247
|
-
function createOpenAIToolNameBoundary(messages, currentToolNames = []) {
|
|
248
|
-
const names = new Set(currentToolNames);
|
|
249
|
-
for (const message of messages) for (const block of message.content) if (block.type === "tool_call") names.add(block.name);
|
|
250
|
-
const maps = buildAliasMaps(buildSanitizedWireAliases(names, void 0), names);
|
|
251
|
-
return {
|
|
252
|
-
messages: rewriteMessagesToWire([...messages], maps),
|
|
253
|
-
toWire: (name) => toWireName(name, maps),
|
|
254
|
-
fromWire: (name) => toCanonicalName(name, maps),
|
|
255
|
-
changed: maps.aliasByCanonical.size > 0
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
//#endregion
|
|
259
272
|
//#region src/providers/schema-sanitize.ts
|
|
260
273
|
/**
|
|
261
274
|
* Provider tool-name constraint. The charset (`[A-Za-z0-9_-]`) is universal
|
|
@@ -607,6 +620,113 @@ function defaultWarn(line) {
|
|
|
607
620
|
console.warn(`[zidane:schema] ${line}`);
|
|
608
621
|
}
|
|
609
622
|
//#endregion
|
|
623
|
+
//#region src/providers/tool-args.ts
|
|
624
|
+
/**
|
|
625
|
+
* Parse a tool-call arguments payload, repairing truncation and trailing
|
|
626
|
+
* garbage when strict parsing fails. Returns `undefined` when no bounded
|
|
627
|
+
* repair produces valid JSON.
|
|
628
|
+
*/
|
|
629
|
+
function parseToolCallArguments(raw) {
|
|
630
|
+
try {
|
|
631
|
+
return {
|
|
632
|
+
input: JSON.parse(raw),
|
|
633
|
+
repaired: false
|
|
634
|
+
};
|
|
635
|
+
} catch {}
|
|
636
|
+
for (const { candidate, fabricated } of repairCandidates(raw)) try {
|
|
637
|
+
const parsed = JSON.parse(candidate);
|
|
638
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
639
|
+
if (fabricated && Object.keys(parsed).length === 0) continue;
|
|
640
|
+
return {
|
|
641
|
+
input: parsed,
|
|
642
|
+
repaired: true
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
} catch {}
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Bounded, ordered repair candidates:
|
|
649
|
+
* 1. longest complete top-level object prefix (trailing-garbage case)
|
|
650
|
+
* 2. payload + structural closers (truncated mid-string / mid-object)
|
|
651
|
+
* 3. payload minus a dangling partial token, + closers (truncated mid-token)
|
|
652
|
+
*
|
|
653
|
+
* `fabricated` marks candidates whose closure was invented here (2 and 3) —
|
|
654
|
+
* the caller holds those to a stricter acceptance bar than a prefix that was
|
|
655
|
+
* complete in the payload itself.
|
|
656
|
+
*/
|
|
657
|
+
function* repairCandidates(raw) {
|
|
658
|
+
const text = raw.trim();
|
|
659
|
+
if (!text.startsWith("{")) return;
|
|
660
|
+
const scan = scanJson(text);
|
|
661
|
+
if (scan.completeAt !== void 0) yield {
|
|
662
|
+
candidate: text.slice(0, scan.completeAt),
|
|
663
|
+
fabricated: false
|
|
664
|
+
};
|
|
665
|
+
yield {
|
|
666
|
+
candidate: close(text, scan),
|
|
667
|
+
fabricated: true
|
|
668
|
+
};
|
|
669
|
+
let trimmed = text;
|
|
670
|
+
for (let step = 0; step < 6; step++) {
|
|
671
|
+
const next = (scanJson(trimmed).inString ? trimmed.replace(/"(?:[^"\\]|\\.)*$/, "") : trimmed.replace(/(?:"(?:[^"\\]|\\.)*"|[^\s{}[\],:"]+|[,:])\s*$/, "")).trimEnd();
|
|
672
|
+
if (next === trimmed || !next.startsWith("{")) break;
|
|
673
|
+
trimmed = next;
|
|
674
|
+
yield {
|
|
675
|
+
candidate: close(trimmed, scanJson(trimmed)),
|
|
676
|
+
fabricated: true
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
function scanJson(text) {
|
|
681
|
+
const stack = [];
|
|
682
|
+
let inString = false;
|
|
683
|
+
let escaped = false;
|
|
684
|
+
let completeAt;
|
|
685
|
+
for (let i = 0; i < text.length; i++) {
|
|
686
|
+
const ch = text[i];
|
|
687
|
+
if (inString) {
|
|
688
|
+
if (escaped) escaped = false;
|
|
689
|
+
else if (ch === "\\") escaped = true;
|
|
690
|
+
else if (ch === "\"") inString = false;
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
if (ch === "\"") inString = true;
|
|
694
|
+
else if (ch === "{") stack.push("}");
|
|
695
|
+
else if (ch === "[") stack.push("]");
|
|
696
|
+
else if (ch === "}" || ch === "]") {
|
|
697
|
+
stack.pop();
|
|
698
|
+
if (stack.length === 0 && completeAt === void 0) completeAt = i + 1;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return {
|
|
702
|
+
stack,
|
|
703
|
+
inString,
|
|
704
|
+
completeAt
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
function close(text, scan) {
|
|
708
|
+
let out = text;
|
|
709
|
+
if (scan.inString) {
|
|
710
|
+
if (/(?:^|[^\\])(?:\\\\)*\\$/.test(out)) out = out.slice(0, -1);
|
|
711
|
+
out += "\"";
|
|
712
|
+
}
|
|
713
|
+
for (let i = scan.stack.length - 1; i >= 0; i--) out += scan.stack[i];
|
|
714
|
+
return out;
|
|
715
|
+
}
|
|
716
|
+
//#endregion
|
|
717
|
+
//#region src/providers/tool-name-boundary.ts
|
|
718
|
+
function createToolNameBoundary(messages, currentToolNames = []) {
|
|
719
|
+
const names = new Set(currentToolNames);
|
|
720
|
+
for (const message of messages) for (const block of message.content) if (block.type === "tool_call") names.add(block.name);
|
|
721
|
+
const maps = buildAliasMaps(buildSanitizedWireAliases(names, void 0), names);
|
|
722
|
+
return {
|
|
723
|
+
messages: rewriteMessagesToWire([...messages], maps),
|
|
724
|
+
toWire: (name) => toWireName(name, maps),
|
|
725
|
+
fromWire: (name) => toCanonicalName(name, maps),
|
|
726
|
+
changed: maps.aliasByCanonical.size > 0
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
//#endregion
|
|
610
730
|
//#region src/providers/openai-compat.ts
|
|
611
731
|
const TOOL_RESULTS_TAG = "__zidane_tool_results__";
|
|
612
732
|
const ASSISTANT_TOOL_CALLS_TAG = "__zidane_assistant_tc__";
|
|
@@ -658,6 +778,7 @@ async function consumeSSE(response, callbacks, signal) {
|
|
|
658
778
|
let text = "";
|
|
659
779
|
let thinking = "";
|
|
660
780
|
let finishReason = "stop";
|
|
781
|
+
let sawTerminator = false;
|
|
661
782
|
let usage = {
|
|
662
783
|
input: 0,
|
|
663
784
|
output: 0
|
|
@@ -678,7 +799,10 @@ async function consumeSSE(response, callbacks, signal) {
|
|
|
678
799
|
for (const line of lines) {
|
|
679
800
|
if (!line.startsWith("data:")) continue;
|
|
680
801
|
const data = line.slice(5).trim();
|
|
681
|
-
if (data === "[DONE]")
|
|
802
|
+
if (data === "[DONE]") {
|
|
803
|
+
sawTerminator = true;
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
682
806
|
let chunk;
|
|
683
807
|
try {
|
|
684
808
|
chunk = JSON.parse(data);
|
|
@@ -690,7 +814,10 @@ async function consumeSSE(response, callbacks, signal) {
|
|
|
690
814
|
const choice = chunk.choices?.[0];
|
|
691
815
|
if (!choice) continue;
|
|
692
816
|
const fr = choice.finish_reason;
|
|
693
|
-
if (fr)
|
|
817
|
+
if (fr) {
|
|
818
|
+
finishReason = fr;
|
|
819
|
+
sawTerminator = true;
|
|
820
|
+
}
|
|
694
821
|
const delta = choice.delta;
|
|
695
822
|
const reasoningDeltaArr = delta?.reasoning_details;
|
|
696
823
|
if (reasoningDeltaArr && reasoningDeltaArr.length > 0) {
|
|
@@ -757,6 +884,7 @@ async function consumeSSE(response, callbacks, signal) {
|
|
|
757
884
|
} finally {
|
|
758
885
|
reader.releaseLock();
|
|
759
886
|
}
|
|
887
|
+
const clipForError = (args) => args.length > 200 ? `${args.slice(0, 200)}… [${args.length} chars]` : args;
|
|
760
888
|
const toolCalls = [];
|
|
761
889
|
for (const tc of tcMap.values()) {
|
|
762
890
|
if (!tc.args) {
|
|
@@ -767,15 +895,14 @@ async function consumeSSE(response, callbacks, signal) {
|
|
|
767
895
|
});
|
|
768
896
|
continue;
|
|
769
897
|
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
}
|
|
898
|
+
const parsed = parseToolCallArguments(tc.args);
|
|
899
|
+
if (!parsed) throw new OpenAICompatStreamError(`Tool call "${tc.name}" (${tc.id}) arguments were truncated or malformed beyond repair: ${clipForError(tc.args)}`);
|
|
900
|
+
if (parsed.repaired && !sawTerminator) throw new OpenAICompatStreamError(`Tool call "${tc.name}" (${tc.id}) arguments were cut off by a truncated stream: ${clipForError(tc.args)}`);
|
|
901
|
+
toolCalls.push({
|
|
902
|
+
id: tc.id,
|
|
903
|
+
name: tc.name,
|
|
904
|
+
input: parsed.input
|
|
905
|
+
});
|
|
779
906
|
}
|
|
780
907
|
const reasoningDetails = Array.from(reasoningMap.entries()).sort(([a], [b]) => a - b).map(([, item]) => item);
|
|
781
908
|
return {
|
|
@@ -1110,6 +1237,21 @@ function toOAIMessages(system, messages, options = {}) {
|
|
|
1110
1237
|
}
|
|
1111
1238
|
const EPHEMERAL = { type: "ephemeral" };
|
|
1112
1239
|
/**
|
|
1240
|
+
* `cache_control` for the requested TTL. Same contract as the Anthropic
|
|
1241
|
+
* provider's `cacheControlFor`: `'5m'`/unset keeps the bare ephemeral shape so
|
|
1242
|
+
* default requests stay byte-identical to every prior zidane version; `'1h'`
|
|
1243
|
+
* adds the `ttl` field, which OpenRouter forwards to Anthropic-family routes
|
|
1244
|
+
* (measured: accepted with normal cache writes/reads, no beta header needed on
|
|
1245
|
+
* that path — OpenRouter manages upstream headers itself). Routes that ignore
|
|
1246
|
+
* `cache_control` entirely ignore the ttl with it.
|
|
1247
|
+
*/
|
|
1248
|
+
function oaiCacheControlFor(ttl) {
|
|
1249
|
+
return ttl === "1h" ? {
|
|
1250
|
+
type: "ephemeral",
|
|
1251
|
+
ttl: "1h"
|
|
1252
|
+
} : EPHEMERAL;
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1113
1255
|
* Add `cache_control: { type: 'ephemeral' }` breakpoints to the system message's
|
|
1114
1256
|
* last text part and the last message's final content part.
|
|
1115
1257
|
*
|
|
@@ -1133,12 +1275,13 @@ const EPHEMERAL = { type: "ephemeral" };
|
|
|
1133
1275
|
* omit it (or pass a marker-free string) for the single-block historic
|
|
1134
1276
|
* behavior.
|
|
1135
1277
|
*/
|
|
1136
|
-
function applyOAICacheBreakpoints(messages, originalSystem) {
|
|
1278
|
+
function applyOAICacheBreakpoints(messages, originalSystem, ttl) {
|
|
1137
1279
|
if (messages.length === 0) return;
|
|
1280
|
+
const cacheControl = oaiCacheControlFor(ttl);
|
|
1138
1281
|
const first = messages[0];
|
|
1139
|
-
if (first.role === "system") markSystemMessage(first, originalSystem);
|
|
1282
|
+
if (first.role === "system") markSystemMessage(first, cacheControl, originalSystem);
|
|
1140
1283
|
const lastIdx = messages.length - 1;
|
|
1141
|
-
if (lastIdx > 0) markLastContentPart(messages[lastIdx]);
|
|
1284
|
+
if (lastIdx > 0) markLastContentPart(messages[lastIdx], cacheControl);
|
|
1142
1285
|
}
|
|
1143
1286
|
/**
|
|
1144
1287
|
* Place the cache marker on the static prefix of the system message. When
|
|
@@ -1152,9 +1295,9 @@ function applyOAICacheBreakpoints(messages, originalSystem) {
|
|
|
1152
1295
|
* that supply pre-built multi-part system messages bypass this branch and
|
|
1153
1296
|
* get the generic last-block treatment.
|
|
1154
1297
|
*/
|
|
1155
|
-
function markSystemMessage(msg, originalSystem) {
|
|
1298
|
+
function markSystemMessage(msg, cacheControl, originalSystem) {
|
|
1156
1299
|
if (typeof msg.content !== "string" || msg.content.length === 0) {
|
|
1157
|
-
markLastContentPart(msg);
|
|
1300
|
+
markLastContentPart(msg, cacheControl);
|
|
1158
1301
|
return;
|
|
1159
1302
|
}
|
|
1160
1303
|
const parts = splitSystemPrompt(originalSystem && originalSystem.length > 0 ? originalSystem : msg.content);
|
|
@@ -1162,7 +1305,7 @@ function markSystemMessage(msg, originalSystem) {
|
|
|
1162
1305
|
msg.content = [{
|
|
1163
1306
|
type: "text",
|
|
1164
1307
|
text: parts.static,
|
|
1165
|
-
cache_control:
|
|
1308
|
+
cache_control: cacheControl
|
|
1166
1309
|
}];
|
|
1167
1310
|
return;
|
|
1168
1311
|
}
|
|
@@ -1170,7 +1313,7 @@ function markSystemMessage(msg, originalSystem) {
|
|
|
1170
1313
|
if (parts.static.length > 0) next.push({
|
|
1171
1314
|
type: "text",
|
|
1172
1315
|
text: parts.static,
|
|
1173
|
-
cache_control:
|
|
1316
|
+
cache_control: cacheControl
|
|
1174
1317
|
});
|
|
1175
1318
|
next.push({
|
|
1176
1319
|
type: "text",
|
|
@@ -1186,13 +1329,13 @@ function markSystemMessage(msg, originalSystem) {
|
|
|
1186
1329
|
* No-op for messages without string or array content (tool-call-only assistant
|
|
1187
1330
|
* messages fall through; the system/tools breakpoints carry the cache prefix).
|
|
1188
1331
|
*/
|
|
1189
|
-
function markLastContentPart(msg) {
|
|
1332
|
+
function markLastContentPart(msg, cacheControl = EPHEMERAL) {
|
|
1190
1333
|
if (typeof msg.content === "string") {
|
|
1191
1334
|
if (msg.content.length === 0) return;
|
|
1192
1335
|
msg.content = [{
|
|
1193
1336
|
type: "text",
|
|
1194
1337
|
text: msg.content,
|
|
1195
|
-
cache_control:
|
|
1338
|
+
cache_control: cacheControl
|
|
1196
1339
|
}];
|
|
1197
1340
|
return;
|
|
1198
1341
|
}
|
|
@@ -1201,7 +1344,7 @@ function markLastContentPart(msg) {
|
|
|
1201
1344
|
const lastBlockIdx = parts.length - 1;
|
|
1202
1345
|
parts[lastBlockIdx] = {
|
|
1203
1346
|
...parts[lastBlockIdx],
|
|
1204
|
-
cache_control:
|
|
1347
|
+
cache_control: cacheControl
|
|
1205
1348
|
};
|
|
1206
1349
|
}
|
|
1207
1350
|
/**
|
|
@@ -1211,12 +1354,13 @@ function markLastContentPart(msg) {
|
|
|
1211
1354
|
* and forwards it when routing to Anthropic/Gemini. Leaves the non-cached tools
|
|
1212
1355
|
* unchanged so the caller's reference is not mutated.
|
|
1213
1356
|
*/
|
|
1214
|
-
function applyOAIToolCacheBreakpoint(tools) {
|
|
1357
|
+
function applyOAIToolCacheBreakpoint(tools, ttl) {
|
|
1215
1358
|
if (tools.length === 0) return tools;
|
|
1359
|
+
const cacheControl = oaiCacheControlFor(ttl);
|
|
1216
1360
|
const lastIdx = tools.length - 1;
|
|
1217
1361
|
return tools.map((tool, i) => i === lastIdx ? {
|
|
1218
1362
|
...tool,
|
|
1219
|
-
cache_control:
|
|
1363
|
+
cache_control: cacheControl
|
|
1220
1364
|
} : tool);
|
|
1221
1365
|
}
|
|
1222
1366
|
function formatTools(tools) {
|
|
@@ -1537,7 +1681,7 @@ function openaiCompat(params) {
|
|
|
1537
1681
|
async stream(options, callbacks) {
|
|
1538
1682
|
const modelId = options.model || defaultModel;
|
|
1539
1683
|
const inputTools = options.tools ?? [];
|
|
1540
|
-
const nameBoundary =
|
|
1684
|
+
const nameBoundary = createToolNameBoundary(options.messages, inputTools.map((tool) => tool.function.name));
|
|
1541
1685
|
const messages = toOAIMessages(options.system, nameBoundary.messages, {
|
|
1542
1686
|
imageInToolResult: capabilities.imageInToolResult === true,
|
|
1543
1687
|
audio: capabilities.audio === true,
|
|
@@ -1550,7 +1694,7 @@ function openaiCompat(params) {
|
|
|
1550
1694
|
model: modelId
|
|
1551
1695
|
});
|
|
1552
1696
|
const shouldCache = cacheBreakpointsEnabled && options.cache !== false;
|
|
1553
|
-
if (shouldCache) applyOAICacheBreakpoints(messages, options.system);
|
|
1697
|
+
if (shouldCache) applyOAICacheBreakpoints(messages, options.system, options.cacheTtl);
|
|
1554
1698
|
const maxTokens = options.maxTokens === void 0 ? void 0 : options.thinkingBudget ? options.thinkingBudget + options.maxTokens : options.maxTokens;
|
|
1555
1699
|
const reasoningBody = params.planReasoningRequest?.({
|
|
1556
1700
|
model: modelId,
|
|
@@ -1584,7 +1728,7 @@ function openaiCompat(params) {
|
|
|
1584
1728
|
name: nameBoundary.toWire(tool.function.name)
|
|
1585
1729
|
}
|
|
1586
1730
|
}));
|
|
1587
|
-
body.tools = shouldCache ? applyOAIToolCacheBreakpoint(tools) : tools;
|
|
1731
|
+
body.tools = shouldCache ? applyOAIToolCacheBreakpoint(tools, options.cacheTtl) : tools;
|
|
1588
1732
|
}
|
|
1589
1733
|
if (options.toolChoice) if (options.toolChoice.type === "tool" && options.toolChoice.name) body.tool_choice = {
|
|
1590
1734
|
type: "function",
|
|
@@ -1652,6 +1796,6 @@ function openaiCompat(params) {
|
|
|
1652
1796
|
};
|
|
1653
1797
|
}
|
|
1654
1798
|
//#endregion
|
|
1655
|
-
export {
|
|
1799
|
+
export { buildPromptMessage as C, unsupportedMediaError as E, fillEstimatedCost as S, defaultPromptMessage as T, userMessage as _, applyOAICacheBreakpoints as a, sanitizeToolSpecs as b, buildAssistantContent as c, formatTools as d, mapOAIFinishReason as f, toolResultsMessage as g, toOAIMessages as h, TOOL_RESULTS_TAG as i, classifyOpenAICompatError as l, openaiCompat as m, OpenAICompatHttpError as n, applyOAIToolCacheBreakpoint as o, openAICompatPromptMessage as p, OpenAICompatStreamError as r, assistantMessage as s, ASSISTANT_TOOL_CALLS_TAG as t, consumeSSE as u, createToolNameBoundary as v, canonicalizePrompt as w, estimateRebilledCostUsd as x, sanitizeToolSchema as y };
|
|
1656
1800
|
|
|
1657
|
-
//# sourceMappingURL=openai-compat-
|
|
1801
|
+
//# sourceMappingURL=openai-compat-DHlBIjj9.js.map
|