@mupt-ai/dari-gateway 1.0.311 → 1.0.313
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 +279 -2
- package/dist/context/provider_prompt_accounting.js +7 -0
- package/dist/context/routing_context.js +4 -1
- package/dist/http/handler.d.ts +2 -1
- package/dist/http/handler.js +12 -2
- package/dist/ingress/anthropic_messages.js +15 -3
- package/dist/ingress/chat_completions.js +6 -1
- package/dist/ingress/codex.js +2 -2
- package/dist/ingress/link.d.ts +24 -0
- package/dist/ingress/link.js +1519 -0
- package/dist/ingress/link_assets.d.ts +14 -0
- package/dist/ingress/link_assets.js +49 -0
- package/dist/ingress/link_font.d.ts +1 -0
- package/dist/ingress/link_font.js +6 -0
- package/dist/ingress/models.js +46 -2
- package/dist/interaction/types.d.ts +1 -0
- package/dist/link_client.d.ts +386 -0
- package/dist/link_client.js +579 -0
- package/dist/models/gateways.d.ts +2 -0
- package/dist/models/gateways.js +2 -0
- package/dist/models/link_errors.d.ts +30 -0
- package/dist/models/link_errors.js +120 -0
- package/dist/models/subscriptions.d.ts +8 -1
- package/dist/models/subscriptions.js +13 -2
- package/dist/platform/platform.d.ts +303 -1
- package/dist/protocol/input/router_model.d.ts +4 -0
- package/dist/protocol/input/router_model.js +31 -1
- package/dist/providers/execution.js +31 -5
- package/dist/providers/pi_options.js +57 -1
- package/dist/providers/provider_call.d.ts +4 -0
- package/dist/providers/provider_call.js +9 -2
- package/dist/providers/response_capture.d.ts +4 -1
- package/dist/providers/response_capture.js +81 -2
- package/dist/providers/stream_finalization.d.ts +1 -0
- package/dist/providers/subscription_limits.d.ts +15 -0
- package/dist/providers/subscription_limits.js +45 -0
- package/dist/runtime/explicit_model.js +16 -4
- package/dist/runtime/harness_identity/extract.js +20 -36
- package/dist/runtime/link_budget.d.ts +27 -0
- package/dist/runtime/link_budget.js +62 -0
- package/dist/runtime/link_grant_access.d.ts +7 -0
- package/dist/runtime/link_grant_access.js +99 -0
- package/dist/runtime/link_in_flight.d.ts +4 -0
- package/dist/runtime/link_in_flight.js +43 -0
- package/dist/runtime/prepare_routed_completion.js +5 -1
- package/dist/runtime/routed_runtime.js +8 -0
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +1 -0
- package/dist/self_host/config.d.ts +9 -0
- package/dist/self_host/config.js +11 -1
- package/dist/self_host/link_store.d.ts +167 -0
- package/dist/self_host/link_store.js +564 -0
- package/dist/self_host/main.d.ts +10 -3
- package/dist/self_host/main.js +19 -4
- package/dist/self_host/platform.d.ts +2 -2
- package/dist/self_host/platform.js +284 -10
- package/dist/self_host/resolve.d.ts +8 -0
- package/dist/self_host/resolve.js +146 -15
- package/dist/self_host/secret_box.d.ts +23 -0
- package/dist/self_host/secret_box.js +105 -0
- package/dist/self_host/stub_gateway.d.ts +60 -0
- package/dist/self_host/stub_gateway.js +397 -0
- package/dist/self_host/stub_main.d.ts +2 -0
- package/dist/self_host/stub_main.js +69 -0
- package/dist/self_host/subscription_test_gateway.d.ts +12 -9
- package/dist/self_host/subscription_test_gateway.js +25 -91
- package/dist/self_host/subscriptions/access.d.ts +5 -0
- package/dist/self_host/subscriptions/access.js +5 -1
- package/dist/self_host/subscriptions/http.js +8 -1
- package/dist/self_host/subscriptions/index.d.ts +5 -2
- package/dist/self_host/subscriptions/index.js +5 -2
- package/dist/self_host/subscriptions/store.d.ts +41 -16
- package/dist/self_host/subscriptions/store.js +136 -32
- package/dist/self_host/subscriptions/usage.d.ts +7 -0
- package/dist/self_host/subscriptions/usage.js +52 -0
- package/dist/telemetry/report.js +18 -0
- package/dist/types.d.ts +18 -0
- package/package.json +4 -3
- package/src/context/provider_prompt_accounting.ts +7 -0
- package/src/context/routing_context.ts +3 -1
- package/src/http/handler.ts +14 -2
- package/src/ingress/anthropic_messages.ts +19 -4
- package/src/ingress/chat_completions.ts +6 -1
- package/src/ingress/codex.ts +2 -2
- package/src/ingress/link.ts +1731 -0
- package/src/ingress/link_assets.ts +56 -0
- package/src/ingress/link_font.ts +9 -0
- package/src/ingress/models.ts +48 -2
- package/src/interaction/types.ts +4 -0
- package/src/link_client.ts +796 -0
- package/src/models/gateways.ts +3 -0
- package/src/models/link_errors.ts +157 -0
- package/src/models/subscriptions.ts +15 -1
- package/src/platform/platform.ts +330 -1
- package/src/protocol/input/router_model.ts +36 -1
- package/src/providers/execution.ts +31 -4
- package/src/providers/pi_options.ts +57 -1
- package/src/providers/provider_call.ts +20 -2
- package/src/providers/response_capture.ts +88 -2
- package/src/providers/stream_finalization.ts +1 -0
- package/src/providers/subscription_limits.ts +53 -0
- package/src/runtime/explicit_model.ts +21 -8
- package/src/runtime/harness_identity/extract.ts +21 -60
- package/src/runtime/link_budget.ts +75 -0
- package/src/runtime/link_grant_access.ts +116 -0
- package/src/runtime/link_in_flight.ts +46 -0
- package/src/runtime/prepare_routed_completion.ts +6 -1
- package/src/runtime/routed_runtime.ts +8 -0
- package/src/runtime/runtime_reporter.ts +3 -0
- package/src/self_host/config.ts +24 -1
- package/src/self_host/link_store.ts +782 -0
- package/src/self_host/main.ts +21 -4
- package/src/self_host/platform.ts +305 -11
- package/src/self_host/resolve.ts +172 -15
- package/src/self_host/secret_box.ts +112 -0
- package/src/self_host/stub_gateway.ts +497 -0
- package/src/self_host/stub_main.ts +72 -0
- package/src/self_host/subscription_test_gateway.ts +26 -95
- package/src/self_host/subscriptions/access.ts +10 -1
- package/src/self_host/subscriptions/http.ts +9 -1
- package/src/self_host/subscriptions/index.ts +6 -0
- package/src/self_host/subscriptions/store.ts +167 -36
- package/src/self_host/subscriptions/usage.ts +64 -0
- package/src/telemetry/report.ts +17 -1
- package/src/types.ts +26 -0
- package/dist/self_host/subscriptions/test_support.d.ts +0 -15
- package/dist/self_host/subscriptions/test_support.js +0 -34
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { linkGrantError, modelNotServed } from "../models/link_errors.js";
|
|
2
|
+
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
3
|
+
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
4
|
+
import { modelMetadataLookup } from "../providers/pi.js";
|
|
5
|
+
/* A Dari Link token is served exactly what its request names, never a
|
|
6
|
+
substitute. `dari/routing` chooses among the router's models the grant
|
|
7
|
+
serves. A named model (`dari/model/<id>`; the ingress names every other
|
|
8
|
+
model a link token asks for this way, see `linkTokenModel`) is the catalog
|
|
9
|
+
model it names, by its full id, its bare id, or a dated snapshot of it. It
|
|
10
|
+
is served as that model when a granted plan serves it, at any level the
|
|
11
|
+
model supports, with the client's own thinking settings and no level chosen
|
|
12
|
+
for it; otherwise the request fails with the reason. A grant with an API
|
|
13
|
+
key for a gateway (OpenRouter, Vercel AI Gateway) is also served any model
|
|
14
|
+
of that gateway by its full id, `openrouter/<id>`, which no catalog lists. A
|
|
15
|
+
child token serves only its models, each at its pinned thinking level when
|
|
16
|
+
it has one. */
|
|
17
|
+
export function linkGrantAccess(credentials, interaction) {
|
|
18
|
+
if (!credentials.link_grant_id)
|
|
19
|
+
return { credentials, interaction };
|
|
20
|
+
const pins = credentials.link_pins ?? null;
|
|
21
|
+
const name = explicitModelId(interaction.model);
|
|
22
|
+
// The grant's own models first; a catalog model it does not serve still
|
|
23
|
+
// names the reason it cannot.
|
|
24
|
+
// A gateway's model is named by its full id, which starts with the gateway.
|
|
25
|
+
const gateway = name?.toLowerCase().split("/")[0];
|
|
26
|
+
const viaGateway = gateway !== undefined && credentials.link_key_gateways !== undefined && Object.hasOwn(credentials.link_key_gateways, gateway);
|
|
27
|
+
const named = name === null
|
|
28
|
+
? null
|
|
29
|
+
: catalogModelFor(name, credentials.link_models ?? [])
|
|
30
|
+
?? catalogModelFor(name, CANONICAL_MODELS.map((model) => model.id))
|
|
31
|
+
?? (viaGateway ? name.toLowerCase() : null);
|
|
32
|
+
if (name !== null && named === null) {
|
|
33
|
+
throw linkGrantError("model_not_granted", `Model '${name}' is not a catalog model this Dari Link grant can use. GET /v1/link/grant lists them.`);
|
|
34
|
+
}
|
|
35
|
+
const pin = pins === null ? null : pins.find((candidate) => candidate.model === named) ?? null;
|
|
36
|
+
if (pins !== null && pin === null) {
|
|
37
|
+
throw linkGrantError("model_not_granted", `This Dari Link child token serves only ${pins.map((candidate) => `'${explicitModelSlug(candidate.model)}'`).join(", ")}.`);
|
|
38
|
+
}
|
|
39
|
+
if (named === null) {
|
|
40
|
+
if (credentials.enabled_models.length > 0)
|
|
41
|
+
return { credentials, interaction };
|
|
42
|
+
throw linkGrantError("model_not_granted", "No subscription this Dari Link grant may use serves a model its router lists. Name one of the grant's models as 'dari/model/<id>'; GET /v1/link/grant lists them.");
|
|
43
|
+
}
|
|
44
|
+
if (!credentials.link_models?.includes(named) && !viaGateway)
|
|
45
|
+
throw modelNotServed(credentials, named);
|
|
46
|
+
// The router's own choice of thinking levels narrows only what it routes.
|
|
47
|
+
const { [named]: _routed, ...thinkingLevels } = credentials.model_thinking_levels ?? {};
|
|
48
|
+
const endpoint = viaGateway ? credentials.link_key_gateways[gateway] : null;
|
|
49
|
+
return {
|
|
50
|
+
credentials: {
|
|
51
|
+
...credentials,
|
|
52
|
+
enabled_models: [...new Set([...credentials.enabled_models, named])],
|
|
53
|
+
model_thinking_levels: thinkingLevels,
|
|
54
|
+
// A gateway the platform points elsewhere is called there.
|
|
55
|
+
...(endpoint == null
|
|
56
|
+
? {}
|
|
57
|
+
: {
|
|
58
|
+
model_configs: {
|
|
59
|
+
...credentials.model_configs,
|
|
60
|
+
[named]: { provider: gateway, native_model_id: named.slice(gateway.length + 1), ...endpoint, cost: { input: 0, output: 0 } },
|
|
61
|
+
},
|
|
62
|
+
}),
|
|
63
|
+
},
|
|
64
|
+
interaction: {
|
|
65
|
+
...interaction,
|
|
66
|
+
model: explicitModelSlug(named),
|
|
67
|
+
reasoning: pin?.thinking
|
|
68
|
+
? { effort: pin.thinking, enabled: pin.thinking !== "off", clientOnly: true }
|
|
69
|
+
: clientReasoning(credentials, named, interaction.reasoning),
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
// The client's own thinking settings. Anthropic takes `thinking: disabled` on
|
|
74
|
+
// every model, so a model with no "off" level is still served it exactly
|
|
75
|
+
// rather than refused.
|
|
76
|
+
function clientReasoning(credentials, model, reasoning) {
|
|
77
|
+
if (reasoning?.enabled === false && reasoning.effort === "off") {
|
|
78
|
+
const metadata = modelMetadataLookup(credentials.model_configs)(model);
|
|
79
|
+
if (metadata.model.api === "anthropic-messages" && !metadata.supportedThinkingLevels.includes("off")) {
|
|
80
|
+
return { enabled: false, clientOnly: true };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { ...reasoning, clientOnly: true };
|
|
84
|
+
}
|
|
85
|
+
// A snapshot date: Anthropic's `-20251001`, OpenAI's `-2025-08-07`.
|
|
86
|
+
const SNAPSHOT_DATE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
|
|
87
|
+
/* The model id in `models` a name means: the id itself, the one id it is the
|
|
88
|
+
bare form of (`claude-haiku-4-5` is `anthropic/claude-haiku-4-5`), or either
|
|
89
|
+
of those for a dated snapshot of it. A name two models share means neither. */
|
|
90
|
+
export function catalogModelFor(name, models) {
|
|
91
|
+
for (const candidate of new Set([name.toLowerCase(), name.toLowerCase().replace(SNAPSHOT_DATE, "")])) {
|
|
92
|
+
if (models.includes(candidate))
|
|
93
|
+
return candidate;
|
|
94
|
+
const matches = models.filter((id) => id.endsWith(`/${candidate}`));
|
|
95
|
+
if (matches.length === 1)
|
|
96
|
+
return matches[0];
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function linkRequestStarted(grantId: string, requestId: string, receivedAt: Date): void;
|
|
2
|
+
export declare function linkRequestRecorded(grantId: string, requestId: string): void;
|
|
3
|
+
/** Every request of the grant received before this time has been recorded. */
|
|
4
|
+
export declare function linkCompleteThrough(grantId: string, now?: Date): Date;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/* The Dari Link requests this gateway process is serving and has not yet
|
|
2
|
+
recorded, so a usage read can say up to when its counts are complete.
|
|
3
|
+
|
|
4
|
+
A request is counted from its report (RequestReporter) until its usage is
|
|
5
|
+
recorded. Before its report exists a request is still resolving, so the
|
|
6
|
+
answer also stays RESOLVE_SLACK_MS behind now. An entry older than
|
|
7
|
+
STALE_MS (a child token's longest life) is taken as lost and dropped.
|
|
8
|
+
|
|
9
|
+
This is exact only where one process serves and records every request of
|
|
10
|
+
a grant: the self-hosted gateway. */
|
|
11
|
+
const RESOLVE_SLACK_MS = 30_000;
|
|
12
|
+
const STALE_MS = 12 * 60 * 60_000;
|
|
13
|
+
// Grant id -> request id -> when the request was received (ms).
|
|
14
|
+
const inFlight = new Map();
|
|
15
|
+
export function linkRequestStarted(grantId, requestId, receivedAt) {
|
|
16
|
+
let requests = inFlight.get(grantId);
|
|
17
|
+
if (requests === undefined) {
|
|
18
|
+
requests = new Map();
|
|
19
|
+
inFlight.set(grantId, requests);
|
|
20
|
+
}
|
|
21
|
+
requests.set(requestId, receivedAt.getTime());
|
|
22
|
+
}
|
|
23
|
+
export function linkRequestRecorded(grantId, requestId) {
|
|
24
|
+
const requests = inFlight.get(grantId);
|
|
25
|
+
if (requests === undefined)
|
|
26
|
+
return;
|
|
27
|
+
requests.delete(requestId);
|
|
28
|
+
if (requests.size === 0)
|
|
29
|
+
inFlight.delete(grantId);
|
|
30
|
+
}
|
|
31
|
+
/** Every request of the grant received before this time has been recorded. */
|
|
32
|
+
export function linkCompleteThrough(grantId, now = new Date()) {
|
|
33
|
+
let through = now.getTime() - RESOLVE_SLACK_MS;
|
|
34
|
+
const requests = inFlight.get(grantId);
|
|
35
|
+
for (const [requestId, receivedAt] of requests ?? []) {
|
|
36
|
+
if (receivedAt < now.getTime() - STALE_MS) {
|
|
37
|
+
requests.delete(requestId);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
through = Math.min(through, receivedAt);
|
|
41
|
+
}
|
|
42
|
+
return new Date(through);
|
|
43
|
+
}
|
|
@@ -11,6 +11,7 @@ import { resolveRouter } from "../strategies/routing.js";
|
|
|
11
11
|
import { RequestReporter } from "../telemetry/report.js";
|
|
12
12
|
import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
|
|
13
13
|
import { requestTags } from "./request_tags.js";
|
|
14
|
+
import { linkGrantAccess } from "./link_grant_access.js";
|
|
14
15
|
import { rolePrompt, withRoleModel } from "./role_model.js";
|
|
15
16
|
import { strictProviderAccess } from "./strict_provider_access.js";
|
|
16
17
|
import { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./harness_identity/index.js";
|
|
@@ -89,8 +90,11 @@ export async function prepareRoutedCompletion(args) {
|
|
|
89
90
|
}
|
|
90
91
|
const roleModel = withRoleModel(credentials, args.interaction);
|
|
91
92
|
const prompt = rolePrompt(credentials, args.interaction);
|
|
92
|
-
const
|
|
93
|
+
const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
|
|
94
|
+
const access = linkGrantAccess(strictAccess.credentials, strictAccess.interaction);
|
|
93
95
|
credentials = access.credentials;
|
|
96
|
+
// A child token's tags label every request it makes, whatever the request says.
|
|
97
|
+
Object.assign(tags, credentials.link_tags);
|
|
94
98
|
args = {
|
|
95
99
|
...args,
|
|
96
100
|
interaction: clampRequestedEffort(access.interaction, credentials, modelMetadataLookup(credentials.model_configs)),
|
|
@@ -443,8 +443,16 @@ function providerExecution(prepared, decision) {
|
|
|
443
443
|
promptCacheKey: prepared.interaction.promptCacheKey,
|
|
444
444
|
tags: prepared.tags,
|
|
445
445
|
systemPromptSuffix: prepared.rolePrompt,
|
|
446
|
+
clientThinking: clientThinking(prepared.interaction.reasoning),
|
|
446
447
|
});
|
|
447
448
|
}
|
|
449
|
+
function clientThinking(reasoning) {
|
|
450
|
+
if (reasoning?.clientOnly !== true || reasoning.effort !== undefined)
|
|
451
|
+
return undefined;
|
|
452
|
+
if (reasoning.enabled === false)
|
|
453
|
+
return "off";
|
|
454
|
+
return reasoning.budgetTokens === undefined ? "default" : `budget:${reasoning.budgetTokens}`;
|
|
455
|
+
}
|
|
448
456
|
function tokenCount(value) {
|
|
449
457
|
return typeof value === "number" && Number.isFinite(value)
|
|
450
458
|
? Math.max(0, Math.trunc(value))
|
|
@@ -6,6 +6,7 @@ export type ReportedProviderExecution = {
|
|
|
6
6
|
provider: string;
|
|
7
7
|
model: string;
|
|
8
8
|
providerKeySource: ProviderKeySource;
|
|
9
|
+
thinkingLevel?: string;
|
|
9
10
|
};
|
|
10
11
|
export declare function reportedExecution(execution: ReportedProviderExecution): ReportedProviderExecution;
|
|
11
12
|
export type ReportableProviderOutcome = {
|
|
@@ -3,6 +3,7 @@ export function reportedExecution(execution) {
|
|
|
3
3
|
provider: execution.provider,
|
|
4
4
|
model: execution.model,
|
|
5
5
|
providerKeySource: execution.providerKeySource,
|
|
6
|
+
...(execution.thinkingLevel === undefined ? {} : { thinkingLevel: execution.thinkingLevel }),
|
|
6
7
|
};
|
|
7
8
|
}
|
|
8
9
|
export function createExperimentRoutedRuntimeReporter() {
|
|
@@ -21,10 +21,15 @@ import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../type
|
|
|
21
21
|
* rolePrompts: # optional: append to an agent role's system prompt
|
|
22
22
|
* main: Delegate codebase exploration to subagents.
|
|
23
23
|
* nativeCompaction: false # let Codex compact server-side with the provider's native compaction
|
|
24
|
+
* link: # optional: Dari Link
|
|
25
|
+
* allowHttpRedirectHosts: # http (not https) redirect URIs allowed on these
|
|
26
|
+
* - "*.example.ts.net" # private dev hosts; `*.` matches any subdomain
|
|
24
27
|
* providers: # optional: OpenAI-compatible or self-run endpoints
|
|
25
28
|
* local:
|
|
26
29
|
* baseUrl: http://localhost:8000/v1
|
|
27
30
|
* apiKeyEnv: LOCAL_API_KEY
|
|
31
|
+
* openai-codex: # optional: where ChatGPT plan requests go (a proxy)
|
|
32
|
+
* baseUrl: https://chatgpt.com/backend-api
|
|
28
33
|
* ```
|
|
29
34
|
*
|
|
30
35
|
* Secrets never live here: gateway keys come from `DARI_GATEWAY_KEYS`,
|
|
@@ -36,6 +41,10 @@ import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../type
|
|
|
36
41
|
export type GatewayConfig = {
|
|
37
42
|
routers: Record<string, RouterConfig>;
|
|
38
43
|
providers: Record<string, ProviderEndpointConfig>;
|
|
44
|
+
link?: LinkConfig;
|
|
45
|
+
};
|
|
46
|
+
export type LinkConfig = {
|
|
47
|
+
allowHttpRedirectHosts: string[];
|
|
39
48
|
};
|
|
40
49
|
export type ProviderEndpointConfig = {
|
|
41
50
|
baseUrl: string;
|
package/dist/self_host/config.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isReasoningEffort, isRecord, } from "@mupt-ai/dari-router/policy-engine";
|
|
2
2
|
import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
|
|
3
|
+
const REDIRECT_HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
|
|
3
4
|
const ROUTER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
4
5
|
const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*$/;
|
|
5
6
|
const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*\/\S+$/;
|
|
@@ -67,7 +68,16 @@ export function parseGatewayConfig(raw) {
|
|
|
67
68
|
providers[id] = parseProvider(id, provider);
|
|
68
69
|
}
|
|
69
70
|
}
|
|
70
|
-
return { routers, providers };
|
|
71
|
+
return { routers, providers, ...(raw.link === undefined ? {} : { link: parseLink(raw.link) }) };
|
|
72
|
+
}
|
|
73
|
+
function parseLink(raw) {
|
|
74
|
+
if (!isRecord(raw))
|
|
75
|
+
throw new Error("`link` must be a map.");
|
|
76
|
+
const hosts = raw.allowHttpRedirectHosts ?? [];
|
|
77
|
+
if (!Array.isArray(hosts) || !hosts.every((host) => typeof host === "string" && REDIRECT_HOST_PATTERN.test(host.toLowerCase()))) {
|
|
78
|
+
throw new Error("link.allowHttpRedirectHosts must list host names, each optionally starting with `*.`.");
|
|
79
|
+
}
|
|
80
|
+
return { allowHttpRedirectHosts: hosts.map((host) => host.toLowerCase()) };
|
|
71
81
|
}
|
|
72
82
|
function parseProvider(id, raw) {
|
|
73
83
|
if (!isRecord(raw) || typeof raw.baseUrl !== "string" || !URL.canParse(raw.baseUrl)) {
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite storage for Dari Link: registered apps, the grants users approve for
|
|
3
|
+
* them, and each grant's tokens. A grant names the subscriptions it may use.
|
|
4
|
+
* Every token is its own row holding only the token's SHA-256, so an access
|
|
5
|
+
* token lives until its own expiry whatever is issued after it; revoking the
|
|
6
|
+
* grant stops them all at once.
|
|
7
|
+
*
|
|
8
|
+
* - access tokens last an hour.
|
|
9
|
+
* - refresh tokens do not expire. A public client's rotates on use; a
|
|
10
|
+
* confidential client, which also proves its secret, keeps its own.
|
|
11
|
+
* - child tokens serve one model, for up to twelve hours, and cannot refresh
|
|
12
|
+
* or mint.
|
|
13
|
+
*/
|
|
14
|
+
import type { Database } from "bun:sqlite";
|
|
15
|
+
import { type SecretBox } from "./secret_box.js";
|
|
16
|
+
import type { LinkApp, LinkBudget, LinkChildToken, LinkGrant, LinkTokens, LinkUsage, LinkUsageQuery } from "../platform/platform.js";
|
|
17
|
+
import { type BudgetStanding } from "../runtime/link_budget.js";
|
|
18
|
+
export declare const LINK_ACCESS_TOKEN_TTL_MS: number;
|
|
19
|
+
export declare const LINK_REFRESH_RACE_MS = 60000;
|
|
20
|
+
export type LinkRevoker = "user" | "app" | "reuse_detected";
|
|
21
|
+
export type ActiveLinkGrant = {
|
|
22
|
+
id: string;
|
|
23
|
+
clientId: string;
|
|
24
|
+
credentialIds: ReadonlySet<string>;
|
|
25
|
+
pins?: LinkPin[];
|
|
26
|
+
tags?: Record<string, string>;
|
|
27
|
+
};
|
|
28
|
+
/** What a presented link token is; null when it is not one this store issued. */
|
|
29
|
+
export type LinkPin = {
|
|
30
|
+
model: string;
|
|
31
|
+
thinking: string | null;
|
|
32
|
+
};
|
|
33
|
+
export type LinkTokenAuth = {
|
|
34
|
+
status: "active";
|
|
35
|
+
grant: ActiveLinkGrant;
|
|
36
|
+
} | {
|
|
37
|
+
status: "expired";
|
|
38
|
+
} | {
|
|
39
|
+
status: "revoked";
|
|
40
|
+
revokedBy: string | null;
|
|
41
|
+
revokedAt: string | null;
|
|
42
|
+
};
|
|
43
|
+
/** An API key a user added on the approval page, for one model provider or gateway. */
|
|
44
|
+
export type LinkApiKey = {
|
|
45
|
+
id: string;
|
|
46
|
+
subject: string;
|
|
47
|
+
provider: string;
|
|
48
|
+
apiKey: string;
|
|
49
|
+
};
|
|
50
|
+
export declare class LinkStore {
|
|
51
|
+
private readonly db;
|
|
52
|
+
private readonly box;
|
|
53
|
+
constructor(db: Database, box?: SecretBox | null);
|
|
54
|
+
private encryptStored;
|
|
55
|
+
private seal;
|
|
56
|
+
private key;
|
|
57
|
+
/** Store a user's API key for a provider, replacing their earlier one for it. */
|
|
58
|
+
addKey(subject: string, provider: string, apiKey: string, now?: Date): LinkApiKey;
|
|
59
|
+
/** Delete a user's API key; false when they have none by that id. */
|
|
60
|
+
removeKey(subject: string, id: string): boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Take a deleted plan or key out of every live grant; a grant left with
|
|
63
|
+
* nothing is revoked as the user's doing.
|
|
64
|
+
*/
|
|
65
|
+
dropCredential(credentialId: string, now?: Date): void;
|
|
66
|
+
/** The API keys a user added, oldest first. */
|
|
67
|
+
keys(subject: string): LinkApiKey[];
|
|
68
|
+
/** The API keys with these ids, whoever added them. */
|
|
69
|
+
keysWithIds(ids: ReadonlySet<string>): LinkApiKey[];
|
|
70
|
+
/** A grant's budget; empty when it has none or is unknown. */
|
|
71
|
+
budget(grantId: string): LinkBudget[];
|
|
72
|
+
/** Replace a live grant's budget; false when none is live by that id. */
|
|
73
|
+
setBudget(grantId: string, budget: LinkBudget[]): boolean;
|
|
74
|
+
/** Each of a grant's budget windows as it stands now (see runtime/link_budget.ts). */
|
|
75
|
+
budgetStandings(grantId: string, now?: Date): BudgetStanding[];
|
|
76
|
+
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
77
|
+
recordUsage(entry: LinkUsageEntry): void;
|
|
78
|
+
/** What a grant's requests used, filtered by tags and receive time. */
|
|
79
|
+
usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Omit<LinkUsage, "completeThrough">;
|
|
80
|
+
/** Register an app; a confidential one gets a secret, returned this once. */
|
|
81
|
+
registerApp(name: string, redirectUris: string[], confidential?: boolean, now?: Date): LinkApp & {
|
|
82
|
+
clientSecret?: string;
|
|
83
|
+
};
|
|
84
|
+
app(clientId: string): LinkApp | null;
|
|
85
|
+
/**
|
|
86
|
+
* Create a grant awaiting its code exchange and return the code. With
|
|
87
|
+
* `grantId` (update mode), change that live grant of the app's plans and
|
|
88
|
+
* budget in place instead: its tokens keep working, and the code redeems
|
|
89
|
+
* for more tokens of the same grant.
|
|
90
|
+
*/
|
|
91
|
+
approve(request: {
|
|
92
|
+
subject?: string;
|
|
93
|
+
grantId?: string;
|
|
94
|
+
clientId: string;
|
|
95
|
+
redirectUri: string;
|
|
96
|
+
codeChallenge: string;
|
|
97
|
+
credentialIds: string[];
|
|
98
|
+
budget?: LinkBudget[];
|
|
99
|
+
}, now?: Date): string;
|
|
100
|
+
/** Redeem a code once: the grant's first tokens. */
|
|
101
|
+
exchangeCode(request: {
|
|
102
|
+
clientId: string;
|
|
103
|
+
clientSecret?: string;
|
|
104
|
+
code: string;
|
|
105
|
+
redirectUri: string;
|
|
106
|
+
codeChallenge: string;
|
|
107
|
+
}, now?: Date): LinkTokens;
|
|
108
|
+
/**
|
|
109
|
+
* A new access token for a grant. A public client's refresh token rotates;
|
|
110
|
+
* a confidential client keeps the one it presented.
|
|
111
|
+
*/
|
|
112
|
+
refresh(request: {
|
|
113
|
+
clientId: string;
|
|
114
|
+
clientSecret?: string;
|
|
115
|
+
refreshToken: string;
|
|
116
|
+
}, now?: Date): LinkTokens;
|
|
117
|
+
/** Mint a child token from the grant's access token. */
|
|
118
|
+
exchangeToken(request: {
|
|
119
|
+
clientId: string;
|
|
120
|
+
clientSecret?: string;
|
|
121
|
+
subjectToken: string;
|
|
122
|
+
models: Array<{
|
|
123
|
+
model: string;
|
|
124
|
+
thinking?: string;
|
|
125
|
+
}>;
|
|
126
|
+
expiresIn: number;
|
|
127
|
+
tags: Record<string, string>;
|
|
128
|
+
}, now?: Date): LinkChildToken;
|
|
129
|
+
/** What a presented access or child token is, or null when it is neither. */
|
|
130
|
+
authenticate(token: string, now?: Date): LinkTokenAuth | null;
|
|
131
|
+
/** Revoke the grant any of its tokens names, when the client owns it (RFC 7009). */
|
|
132
|
+
revokeToken(request: {
|
|
133
|
+
clientId: string;
|
|
134
|
+
clientSecret?: string;
|
|
135
|
+
token: string;
|
|
136
|
+
}, now?: Date): void;
|
|
137
|
+
/** The subscriptions a grant may use; empty once it is revoked. */
|
|
138
|
+
credentialIds(grantId: string): ReadonlySet<string>;
|
|
139
|
+
/** The user who approved a grant; null when it has none or is unknown. */
|
|
140
|
+
subject(grantId: string): string | null;
|
|
141
|
+
/** Grants that are not revoked, oldest first. */
|
|
142
|
+
grants(): LinkGrant[];
|
|
143
|
+
/**
|
|
144
|
+
* Revoke a grant: its code and refresh tokens go, and its access and child
|
|
145
|
+
* tokens stop working. False when none is active by that id.
|
|
146
|
+
*/
|
|
147
|
+
revoke(grantId: string, by: LinkRevoker, now?: Date): boolean;
|
|
148
|
+
/**
|
|
149
|
+
* The app a client id names, once it has proven its secret when it has one.
|
|
150
|
+
* A confidential client must send its secret; a public one must not.
|
|
151
|
+
*/
|
|
152
|
+
private authenticateClient;
|
|
153
|
+
private issue;
|
|
154
|
+
}
|
|
155
|
+
export type LinkUsageEntry = {
|
|
156
|
+
requestId: string;
|
|
157
|
+
grantId: string;
|
|
158
|
+
receivedAt: Date;
|
|
159
|
+
model: string | null;
|
|
160
|
+
thinking: string | null;
|
|
161
|
+
tags: Record<string, string>;
|
|
162
|
+
inputTokens: number;
|
|
163
|
+
outputTokens: number;
|
|
164
|
+
cacheReadTokens: number;
|
|
165
|
+
cacheWriteTokens: number;
|
|
166
|
+
status: string;
|
|
167
|
+
};
|