@mupt-ai/dari-gateway 1.0.321 → 1.0.323
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 +1 -1
- package/dist/ingress/anthropic_messages.js +13 -7
- package/dist/ingress/codex.js +9 -4
- package/dist/link/budget.d.ts +6 -3
- package/dist/link/budget.js +6 -2
- package/dist/link/endpoints.d.ts +14 -1
- package/dist/link/endpoints.js +120 -36
- package/dist/link/errors.d.ts +20 -1
- package/dist/link/errors.js +35 -0
- package/dist/link/grants.d.ts +3 -1
- package/dist/link/grants.js +3 -0
- package/dist/link/key_providers.d.ts +2 -0
- package/dist/link/key_providers.js +4 -0
- package/dist/link/self_hosted.js +2 -2
- package/dist/link/service.d.ts +21 -1
- package/dist/link/service.js +25 -8
- package/dist/link/sqlite_store.d.ts +1 -0
- package/dist/link/sqlite_store.js +12 -11
- package/dist/platform/platform.d.ts +25 -4
- package/dist/runtime/harness_identity/extract.js +6 -1
- package/dist/self_host/resolve.js +6 -32
- package/package.json +2 -2
- package/src/ingress/anthropic_messages.ts +13 -6
- package/src/ingress/codex.ts +8 -2
- package/src/link/budget.ts +12 -4
- package/src/link/endpoints.ts +130 -39
- package/src/link/errors.ts +53 -1
- package/src/link/grants.ts +6 -1
- package/src/link/key_providers.ts +5 -0
- package/src/link/self_hosted.ts +2 -2
- package/src/link/service.ts +33 -9
- package/src/link/sqlite_store.ts +27 -19
- package/src/platform/platform.ts +22 -4
- package/src/runtime/harness_identity/extract.ts +6 -1
- package/src/self_host/resolve.ts +10 -47
package/dist/link/service.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkPlanAdded, LinkPlatform, LinkSubscription } from "../platform/platform.js";
|
|
1
|
+
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkPlanAdded, LinkPlatform, LinkSignIn, LinkSubscription } from "../platform/platform.js";
|
|
2
2
|
import type { SubscriptionKind } from "../types.js";
|
|
3
3
|
import { type BudgetUse } from "./budget.js";
|
|
4
4
|
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo } from "./grants.js";
|
|
@@ -48,6 +48,8 @@ export type LinkStore = LinkRepo & {
|
|
|
48
48
|
export type LinkUsers = {
|
|
49
49
|
/** Signs the pages' cookies; throws HttpError(503, `link_not_configured`) without one. */
|
|
50
50
|
sessionSecret(): string;
|
|
51
|
+
/** See `LinkApprovalPage.signIn`. */
|
|
52
|
+
signIn?: LinkSignIn;
|
|
51
53
|
connectable: readonly SubscriptionKind[];
|
|
52
54
|
keyProviders: readonly LinkKeyProvider[];
|
|
53
55
|
/** See `LinkPlatform.httpRedirectHosts`. */
|
|
@@ -82,6 +84,24 @@ export type LinkUsers = {
|
|
|
82
84
|
removePlan(subject: string, credentialId: string): Promise<boolean>;
|
|
83
85
|
};
|
|
84
86
|
export declare function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform;
|
|
87
|
+
/**
|
|
88
|
+
* A new app: its client id, and for a confidential one a client secret,
|
|
89
|
+
* returned this once, of which only the hash is kept. Every app is made here,
|
|
90
|
+
* whichever way it registers (hosted Dari's console included).
|
|
91
|
+
*/
|
|
92
|
+
export declare function newLinkApp(request: {
|
|
93
|
+
name: string;
|
|
94
|
+
redirectUris: string[];
|
|
95
|
+
confidential: boolean;
|
|
96
|
+
}): {
|
|
97
|
+
record: LinkAppRecord;
|
|
98
|
+
clientSecret?: string;
|
|
99
|
+
};
|
|
100
|
+
/** A confidential app's client secret, and the hash that is kept of it. */
|
|
101
|
+
export declare function newLinkClientSecret(): {
|
|
102
|
+
secret: string;
|
|
103
|
+
hash: string;
|
|
104
|
+
};
|
|
85
105
|
/**
|
|
86
106
|
* The grant a link token serves a request for: null when the key is no link
|
|
87
107
|
* token. Throws the 401 a dead token gets, and the 424 a grant at its budget
|
package/dist/link/service.js
CHANGED
|
@@ -25,6 +25,7 @@ export function linkPlatform(store, users) {
|
|
|
25
25
|
httpRedirectHosts: users.httpRedirectHosts ?? [],
|
|
26
26
|
approval: {
|
|
27
27
|
sessionSecret: () => users.sessionSecret(),
|
|
28
|
+
...(users.signIn === undefined ? {} : { signIn: users.signIn }),
|
|
28
29
|
connectable: users.connectable,
|
|
29
30
|
keyProviders: users.keyProviders,
|
|
30
31
|
subscriptions: (subject) => users.plans(subject),
|
|
@@ -108,14 +109,9 @@ export function linkPlatform(store, users) {
|
|
|
108
109
|
if (apiKey === undefined && !users.openRegistration) {
|
|
109
110
|
throw new HttpError(401, "Register with a Dari API key, so the app belongs to an organization.", "authentication_error");
|
|
110
111
|
}
|
|
111
|
-
const clientSecret = confidential === true
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
name,
|
|
115
|
-
redirectUris,
|
|
116
|
-
confidential: clientSecret !== undefined,
|
|
117
|
-
};
|
|
118
|
-
await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
|
|
112
|
+
const { record, clientSecret } = newLinkApp({ name, redirectUris, confidential: confidential === true });
|
|
113
|
+
await users.registerApp(record, apiKey);
|
|
114
|
+
const { clientSecretHash: _, ...app } = record;
|
|
119
115
|
return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
|
|
120
116
|
},
|
|
121
117
|
async app(clientId) {
|
|
@@ -164,6 +160,27 @@ export function linkPlatform(store, users) {
|
|
|
164
160
|
},
|
|
165
161
|
};
|
|
166
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* A new app: its client id, and for a confidential one a client secret,
|
|
165
|
+
* returned this once, of which only the hash is kept. Every app is made here,
|
|
166
|
+
* whichever way it registers (hosted Dari's console included).
|
|
167
|
+
*/
|
|
168
|
+
export function newLinkApp(request) {
|
|
169
|
+
const secret = request.confidential ? newLinkClientSecret() : null;
|
|
170
|
+
const record = {
|
|
171
|
+
clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
|
|
172
|
+
name: request.name,
|
|
173
|
+
redirectUris: request.redirectUris,
|
|
174
|
+
confidential: secret !== null,
|
|
175
|
+
clientSecretHash: secret?.hash ?? null,
|
|
176
|
+
};
|
|
177
|
+
return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
|
|
178
|
+
}
|
|
179
|
+
/** A confidential app's client secret, and the hash that is kept of it. */
|
|
180
|
+
export function newLinkClientSecret() {
|
|
181
|
+
const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
|
|
182
|
+
return { secret, hash: linkHash(secret) };
|
|
183
|
+
}
|
|
167
184
|
/**
|
|
168
185
|
* The grant a link token serves a request for: null when the key is no link
|
|
169
186
|
* token. Throws the 401 a dead token gets, and the 424 a grant at its budget
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { openWithoutKey } from "../self_host/secret_box.js";
|
|
3
|
-
import { LINK_TOKEN_RETENTION_MS, } from "./grants.js";
|
|
4
3
|
// Where a stored API key belongs, which its encryption is bound to.
|
|
5
4
|
function keyPlace(id) {
|
|
6
5
|
return `link_api_keys:${id}:api_key`;
|
|
@@ -149,10 +148,10 @@ export class SqliteLinkStore {
|
|
|
149
148
|
}
|
|
150
149
|
budgetUses(grantId, since) {
|
|
151
150
|
return this.db
|
|
152
|
-
.query(`SELECT received_at, input_tokens
|
|
151
|
+
.query(`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
|
|
153
152
|
FROM link_usage WHERE grant_id = ? AND received_at > ?`)
|
|
154
153
|
.all(grantId, since)
|
|
155
|
-
.map((row) => ({ at: new Date(row.received_at),
|
|
154
|
+
.map((row) => ({ at: new Date(row.received_at), ...tokenCounts(row) }));
|
|
156
155
|
}
|
|
157
156
|
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
158
157
|
recordUsage(entry) {
|
|
@@ -185,10 +184,7 @@ export class SqliteLinkStore {
|
|
|
185
184
|
model: row.model,
|
|
186
185
|
thinking: row.thinking,
|
|
187
186
|
tags: JSON.parse(row.tags),
|
|
188
|
-
|
|
189
|
-
outputTokens: row.output_tokens,
|
|
190
|
-
cacheReadTokens: row.cache_read_tokens,
|
|
191
|
-
cacheWriteTokens: row.cache_write_tokens,
|
|
187
|
+
...tokenCounts(row),
|
|
192
188
|
}));
|
|
193
189
|
}
|
|
194
190
|
addApp(app, now = new Date()) {
|
|
@@ -311,10 +307,7 @@ export class SqliteLinkStore {
|
|
|
311
307
|
if (rotated === 0)
|
|
312
308
|
return "race";
|
|
313
309
|
}
|
|
314
|
-
|
|
315
|
-
// Rotated refresh tokens stay while the grant lives (revoking it deletes
|
|
316
|
-
// them): presenting one again is how a stolen refresh token is caught.
|
|
317
|
-
this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
|
|
310
|
+
this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND (expires_at < ? OR (rotated_at < ? AND kind != 'refresh'))", [request.grantId, request.forgetBefore, request.forgetBefore]);
|
|
318
311
|
this.insertTokens(request.grantId, request.tokens, request.now);
|
|
319
312
|
return "ok";
|
|
320
313
|
})();
|
|
@@ -351,6 +344,14 @@ export class SqliteLinkStore {
|
|
|
351
344
|
return true;
|
|
352
345
|
}
|
|
353
346
|
}
|
|
347
|
+
function tokenCounts(row) {
|
|
348
|
+
return {
|
|
349
|
+
inputTokens: row.input_tokens,
|
|
350
|
+
outputTokens: row.output_tokens,
|
|
351
|
+
cacheReadTokens: row.cache_read_tokens,
|
|
352
|
+
cacheWriteTokens: row.cache_write_tokens,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
354
355
|
// A child token's models. One minted before `pins` existed kept its one model
|
|
355
356
|
// in `model` and `thinking`.
|
|
356
357
|
function childPins(row) {
|
|
@@ -174,10 +174,11 @@ export type LinkPlatform = {
|
|
|
174
174
|
}): Promise<boolean>;
|
|
175
175
|
};
|
|
176
176
|
/**
|
|
177
|
-
* What the gateway's approval and connections pages need. The
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
177
|
+
* What the gateway's approval and connections pages need. The gateway
|
|
178
|
+
* remembers the user in a signed cookie as a subject, so their plans are there
|
|
179
|
+
* the next time an app asks and they manage their connections there. With
|
|
180
|
+
* `signIn` the subject is the account they signed in with; without it the
|
|
181
|
+
* pages need no account, and a user's first plan makes their subject.
|
|
181
182
|
*/
|
|
182
183
|
export type LinkApprovalPage = {
|
|
183
184
|
/**
|
|
@@ -185,6 +186,11 @@ export type LinkApprovalPage = {
|
|
|
185
186
|
* `link_not_configured`) when the platform has none.
|
|
186
187
|
*/
|
|
187
188
|
sessionSecret(): string;
|
|
189
|
+
/**
|
|
190
|
+
* Set on a platform whose users have accounts: the page then acts only for
|
|
191
|
+
* a user who signed in with one, so their plans follow them to any browser.
|
|
192
|
+
*/
|
|
193
|
+
signIn?: LinkSignIn;
|
|
188
194
|
/** The kinds of plan a user can connect on the page, in the order offered. */
|
|
189
195
|
connectable: readonly SubscriptionKind[];
|
|
190
196
|
/** The providers and gateways a user can add an API key for, in the order offered. */
|
|
@@ -229,6 +235,21 @@ export type LinkApprovalPage = {
|
|
|
229
235
|
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
230
236
|
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
231
237
|
};
|
|
238
|
+
/**
|
|
239
|
+
* The platform's own sign-in. The page sends the user to `url()` with `state`
|
|
240
|
+
* and `next`; the platform signs them in and returns them to
|
|
241
|
+
* `/v1/link/session` with the same `next` and a ticket for that state.
|
|
242
|
+
*/
|
|
243
|
+
export type LinkSignIn = {
|
|
244
|
+
/** Throws HttpError(503, `link_not_configured`) when the platform has none. */
|
|
245
|
+
url(): string;
|
|
246
|
+
/** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
|
|
247
|
+
redeem(ticket: string): Promise<{
|
|
248
|
+
subject: string;
|
|
249
|
+
state: string;
|
|
250
|
+
issuedAt: number;
|
|
251
|
+
} | null>;
|
|
252
|
+
};
|
|
232
253
|
/** A plan or API key the user added, and who they are now. */
|
|
233
254
|
export type LinkPlanAdded = {
|
|
234
255
|
subject: string;
|
|
@@ -24,7 +24,12 @@ export function piRequestContext(headers) {
|
|
|
24
24
|
}
|
|
25
25
|
const kind = headers.get("x-pi-request-kind")?.trim();
|
|
26
26
|
return {
|
|
27
|
-
requestClass: kind === "turn" ? "main"
|
|
27
|
+
requestClass: kind === "turn" ? "main"
|
|
28
|
+
: kind === "compaction" ? "compaction"
|
|
29
|
+
// The Dari extension's web search tool: one request beside the turn,
|
|
30
|
+
// served as background work like Claude Code's own search.
|
|
31
|
+
: kind === "search" ? "auxiliary"
|
|
32
|
+
: "unknown",
|
|
28
33
|
};
|
|
29
34
|
}
|
|
30
35
|
// OpenCode names the session behind every request, and a subagent's parent
|
|
@@ -2,10 +2,10 @@ import { timingSafeEqual } from "node:crypto";
|
|
|
2
2
|
import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
|
|
3
3
|
import { HttpError } from "../http/errors.js";
|
|
4
4
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
5
|
-
import { codexModelConfig,
|
|
5
|
+
import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
6
6
|
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
7
7
|
import { gatewayFor } from "../models/gateways.js";
|
|
8
|
-
import {
|
|
8
|
+
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
9
9
|
import { registeredModelPrice } from "../providers/pi.js";
|
|
10
10
|
import { allRouterModels, routerModelsFor, } from "./config.js";
|
|
11
11
|
import { linkTokenGrant } from "../link/service.js";
|
|
@@ -87,9 +87,10 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
87
87
|
// A model-specific hold tries the pool's other plans before removing the
|
|
88
88
|
// model. Its provider's active plan and conversation pin stay unchanged.
|
|
89
89
|
const modelCredentials = {};
|
|
90
|
+
// A provider the request wanted that no granted plan served.
|
|
90
91
|
const linkUnavailable = grant === null
|
|
91
92
|
? {}
|
|
92
|
-
:
|
|
93
|
+
: providersUnavailable(granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })), [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider), request.clientHarness, now);
|
|
93
94
|
const models = [];
|
|
94
95
|
for (const model of listed) {
|
|
95
96
|
const credential = credentials.get(providerForModel(model.id));
|
|
@@ -120,11 +121,8 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
120
121
|
// A grant with a gateway key serves the gateway's models by name, listed or not.
|
|
121
122
|
const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
|
|
122
123
|
if (models.length === 0 && !gatewayKeyed) {
|
|
123
|
-
if (grant !== null)
|
|
124
|
-
throw grant.pins
|
|
125
|
-
? modelNotServed({ link_unavailable: linkUnavailable }, grant.pins[0].model)
|
|
126
|
-
: linkGrantUnavailableError(linkUnavailable);
|
|
127
|
-
}
|
|
124
|
+
if (grant !== null)
|
|
125
|
+
throw linkNothingServed(linkUnavailable, grant.pins);
|
|
128
126
|
const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
|
|
129
127
|
throw unavailableRouterError(request.routerId, exhausted, missing);
|
|
130
128
|
}
|
|
@@ -241,30 +239,6 @@ function grantModels(grant, routed, granted, grantedKeys) {
|
|
|
241
239
|
const pinned = new Set(grant.pins.map((pin) => pin.model));
|
|
242
240
|
return models.filter((model) => pinned.has(model.id)).map((model) => ({ id: model.id }));
|
|
243
241
|
}
|
|
244
|
-
/**
|
|
245
|
-
* Why each provider with a granted plan serves nothing now: its plans serve
|
|
246
|
-
* only another client, or are all at their usage limits.
|
|
247
|
-
*/
|
|
248
|
-
function grantUnavailable(granted, credentials, clientHarness, now) {
|
|
249
|
-
const unavailable = {};
|
|
250
|
-
for (const provider of new Set(granted.map((credential) => subscriptionModelProvider(credential.provider)))) {
|
|
251
|
-
// Only a provider the request wanted and no plan served.
|
|
252
|
-
if (credentials.get(provider) !== null)
|
|
253
|
-
continue;
|
|
254
|
-
const plans = granted.filter((credential) => subscriptionModelProvider(credential.provider) === provider);
|
|
255
|
-
const usable = plans.filter((credential) => {
|
|
256
|
-
const client = subscriptionClient(credential.provider);
|
|
257
|
-
return client === undefined || client === clientHarness;
|
|
258
|
-
});
|
|
259
|
-
if (usable.length === 0) {
|
|
260
|
-
unavailable[provider] = plansForAnotherClient(plans.map((credential) => credential.provider));
|
|
261
|
-
continue;
|
|
262
|
-
}
|
|
263
|
-
const held = usable.flatMap((credential) => credential.unavailableUntil !== null && credential.unavailableUntil > now ? [credential.unavailableUntil] : []);
|
|
264
|
-
unavailable[provider] = plansExhausted(usable.map((credential) => credential.provider), held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null);
|
|
265
|
-
}
|
|
266
|
-
return unavailable;
|
|
267
|
-
}
|
|
268
242
|
// Configured endpoints read their own key variable, or send a placeholder
|
|
269
243
|
// when they take none; known providers use their standard variable.
|
|
270
244
|
export async function configuredProviderApiKey(deps, provider) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.323",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
55
|
-
"@mupt-ai/dari-router": "1.0.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.323",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -13,6 +13,7 @@ import { claudeCodeRequestContext } from "./claude_code/request_context.js";
|
|
|
13
13
|
import { claimedClientHarness } from "./client_harness.js";
|
|
14
14
|
import {
|
|
15
15
|
claudeCodeConversationIdentity,
|
|
16
|
+
piRequestContext,
|
|
16
17
|
} from "../runtime/harness_identity/index.js";
|
|
17
18
|
import { parseJsonRequest } from "./json.js";
|
|
18
19
|
import { anthropicWebSearchTool } from "../interaction/capabilities.js";
|
|
@@ -43,11 +44,15 @@ export async function handleAnthropicMessages(
|
|
|
43
44
|
const isClaudeCode = isClaudeCodeRequest(request.headers);
|
|
44
45
|
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
45
46
|
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
46
|
-
|
|
47
|
+
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
48
|
+
// tool sends its search here, marked as Pi's.
|
|
49
|
+
const piContext = isClaudeCode ? undefined : piRequestContext(request.headers);
|
|
50
|
+
const agentContext = isClaudeCode ? claudeCodeRequestContext(request.headers) : piContext;
|
|
47
51
|
// Claude Code runs a web search as a background request that names one of
|
|
48
|
-
// the session's models
|
|
49
|
-
//
|
|
50
|
-
// Link token keeps the
|
|
52
|
+
// the session's models, and Pi's search tool as one that asks for routing.
|
|
53
|
+
// Like other background work, Dari serves it on the cheapest model that
|
|
54
|
+
// can: a Claude model on Anthropic's API. A Dari Link token keeps the
|
|
55
|
+
// model it names.
|
|
51
56
|
const backgroundWebSearch = agentContext !== undefined
|
|
52
57
|
&& isBackgroundRequest({ ...interaction, agentContext })
|
|
53
58
|
&& anthropicWebSearchTool(interaction) !== undefined
|
|
@@ -69,7 +74,7 @@ export async function handleAnthropicMessages(
|
|
|
69
74
|
? { requestPurpose: "tool_continuation" as const } : {}),
|
|
70
75
|
claudeCodeUserAgent: request.headers.get("user-agent")!.trim(),
|
|
71
76
|
}
|
|
72
|
-
: forwarded;
|
|
77
|
+
: { ...forwarded, ...(agentContext === undefined ? {} : { agentContext }) };
|
|
73
78
|
return await handleRoutedCompletion({
|
|
74
79
|
request,
|
|
75
80
|
routerId,
|
|
@@ -79,7 +84,9 @@ export async function handleAnthropicMessages(
|
|
|
79
84
|
streamBody: anthropicMessagesSseStream,
|
|
80
85
|
errorResponse: anthropicErrorResponse,
|
|
81
86
|
selectorBackend,
|
|
82
|
-
clientHarness: isClaudeCode ? "claude_code"
|
|
87
|
+
clientHarness: isClaudeCode ? "claude_code"
|
|
88
|
+
: piContext !== undefined ? "pi"
|
|
89
|
+
: claimedClientHarness(request.headers),
|
|
83
90
|
harnessConversationIdentity: isClaudeCode
|
|
84
91
|
? claudeCodeConversationIdentity(
|
|
85
92
|
request.headers,
|
package/src/ingress/codex.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
codexRequestPurpose,
|
|
16
16
|
codexRequestContext,
|
|
17
17
|
museCodeConversationIdentity,
|
|
18
|
+
piRequestContext,
|
|
18
19
|
} from "../runtime/harness_identity/index.js";
|
|
19
20
|
|
|
20
21
|
export async function handleResponses(
|
|
@@ -27,7 +28,11 @@ export async function handleResponses(
|
|
|
27
28
|
const rawPayload = await parseJsonRequest<Record<string, unknown>>(request);
|
|
28
29
|
const interaction = openAIResponsesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
29
30
|
const requestPurpose = codexRequestPurpose(request.headers, rawPayload);
|
|
30
|
-
const
|
|
31
|
+
const codexContext = codexRequestContext(request.headers, rawPayload);
|
|
32
|
+
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
33
|
+
// tool sends an OpenAI hosted search here, marked as Pi's.
|
|
34
|
+
const piContext = codexContext === undefined ? piRequestContext(request.headers) : undefined;
|
|
35
|
+
const agentContext = codexContext ?? piContext;
|
|
31
36
|
const museClientId = museCodeClientId(request.headers);
|
|
32
37
|
const payload = {
|
|
33
38
|
...interaction,
|
|
@@ -59,7 +64,8 @@ export async function handleResponses(
|
|
|
59
64
|
selectorBackend,
|
|
60
65
|
clientHarness: museClientId !== undefined ? "muse_code"
|
|
61
66
|
// Codex describes every request in its turn metadata.
|
|
62
|
-
:
|
|
67
|
+
: codexContext !== undefined ? "codex"
|
|
68
|
+
: piContext !== undefined ? "pi"
|
|
63
69
|
: claimedClientHarness(request.headers),
|
|
64
70
|
harnessConversationIdentity,
|
|
65
71
|
});
|
package/src/link/budget.ts
CHANGED
|
@@ -10,13 +10,21 @@
|
|
|
10
10
|
A window at its cap is back once enough of its oldest requests roll off to
|
|
11
11
|
bring it under the cap again: `resetsAt` is when that happens. */
|
|
12
12
|
|
|
13
|
-
import type { LinkBudget } from "../platform/platform.js";
|
|
13
|
+
import type { LinkBudget, LinkUsageTotals } from "../platform/platform.js";
|
|
14
14
|
|
|
15
15
|
/** The windows a budget can cap: five hours and one week. */
|
|
16
16
|
export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080] as const;
|
|
17
17
|
|
|
18
|
+
/** The tokens a request used, as each kind is recorded. */
|
|
19
|
+
export type LinkTokenCounts = Pick<LinkUsageTotals, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens">;
|
|
20
|
+
|
|
21
|
+
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
22
|
+
export function linkTokens(counts: LinkTokenCounts): number {
|
|
23
|
+
return counts.inputTokens + counts.outputTokens + counts.cacheReadTokens + counts.cacheWriteTokens;
|
|
24
|
+
}
|
|
25
|
+
|
|
18
26
|
/** Tokens one of a grant's requests used, and when it was received. */
|
|
19
|
-
export type BudgetUse = { at: Date
|
|
27
|
+
export type BudgetUse = LinkTokenCounts & { at: Date };
|
|
20
28
|
|
|
21
29
|
/** A budget window as it stands for a grant; `resetsAt` is set only at the cap. */
|
|
22
30
|
export type BudgetStanding = { windowMinutes: number; maxTokens: number; usedTokens: number; resetsAt: Date | null };
|
|
@@ -28,12 +36,12 @@ export function budgetStandings(budget: readonly LinkBudget[], uses: readonly Bu
|
|
|
28
36
|
const live = uses
|
|
29
37
|
.filter((use) => use.at.getTime() > now.getTime() - windowMs)
|
|
30
38
|
.sort((a, b) => a.at.getTime() - b.at.getTime());
|
|
31
|
-
const usedTokens = live.reduce((sum, use) => sum + use
|
|
39
|
+
const usedTokens = live.reduce((sum, use) => sum + linkTokens(use), 0);
|
|
32
40
|
let resetsAt: Date | null = null;
|
|
33
41
|
let remaining = usedTokens;
|
|
34
42
|
for (const use of live) {
|
|
35
43
|
if (remaining < entry.maxTokens) break;
|
|
36
|
-
remaining -= use
|
|
44
|
+
remaining -= linkTokens(use);
|
|
37
45
|
resetsAt = new Date(use.at.getTime() + windowMs);
|
|
38
46
|
}
|
|
39
47
|
return { windowMinutes: entry.windowMinutes, maxTokens: entry.maxTokens, usedTokens, resetsAt };
|