offrouter-core 0.0.0

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.
Files changed (41) hide show
  1. package/package.json +21 -0
  2. package/src/audit.test.ts +302 -0
  3. package/src/audit.ts +553 -0
  4. package/src/auth/credential-chain.test.ts +202 -0
  5. package/src/auth/credential-chain.ts +181 -0
  6. package/src/auth/index.ts +32 -0
  7. package/src/auth/keychain.test.ts +75 -0
  8. package/src/auth/keychain.ts +39 -0
  9. package/src/auth/oauth-pkce.test.ts +184 -0
  10. package/src/auth/oauth-pkce.ts +409 -0
  11. package/src/config.test.ts +415 -0
  12. package/src/config.ts +484 -0
  13. package/src/delegation.test.ts +368 -0
  14. package/src/delegation.ts +605 -0
  15. package/src/index.ts +261 -0
  16. package/src/policy.test.ts +634 -0
  17. package/src/policy.ts +418 -0
  18. package/src/protocol.ts +7 -0
  19. package/src/providers/adapter.test.ts +293 -0
  20. package/src/providers/adapter.ts +324 -0
  21. package/src/providers/catalog-data.test.ts +258 -0
  22. package/src/providers/catalog-data.ts +498 -0
  23. package/src/providers/catalog.test.ts +84 -0
  24. package/src/providers/catalog.ts +483 -0
  25. package/src/providers/fake.ts +312 -0
  26. package/src/providers/openai-compatible.test.ts +366 -0
  27. package/src/providers/openai-compatible.ts +554 -0
  28. package/src/proxy/responses-mapper.test.ts +290 -0
  29. package/src/proxy/responses-mapper.ts +736 -0
  30. package/src/proxy/responses-server.test.ts +322 -0
  31. package/src/proxy/responses-server.ts +469 -0
  32. package/src/router.test.ts +562 -0
  33. package/src/router.ts +323 -0
  34. package/src/schemas.test.ts +240 -0
  35. package/src/schemas.ts +203 -0
  36. package/src/secrets.test.ts +271 -0
  37. package/src/secrets.ts +461 -0
  38. package/src/types.ts +167 -0
  39. package/src/usage.test.ts +283 -0
  40. package/src/usage.ts +669 -0
  41. package/tsconfig.json +9 -0
package/src/policy.ts ADDED
@@ -0,0 +1,418 @@
1
+ /**
2
+ * Profile and candidate policy engine for OffRouter V1.
3
+ * Hard filters first; subscription-first rules gate API-key candidates.
4
+ */
5
+ import type {
6
+ PolicyDecision,
7
+ PolicyDenial,
8
+ ProviderCandidate,
9
+ RouteRequest,
10
+ SubscriptionStatus,
11
+ } from "./types.js";
12
+
13
+ export interface PolicyConfig {
14
+ /** Profiles explicitly allowed to route through OffRouter. */
15
+ allowlistedProfiles: string[];
16
+ /**
17
+ * Glob-like patterns for denied profiles (supports `*` wildcards).
18
+ * Default use case: `*-work`.
19
+ */
20
+ deniedProfilePatterns?: string[];
21
+ /**
22
+ * When false (default), subscription-tier candidates must be first-party.
23
+ * Third-party subscription adapters are denied unless opted in.
24
+ */
25
+ allowThirdPartySubscriptionAdapters?: boolean;
26
+ /** Optional explicit provider deny list by providerId. */
27
+ deniedProviders?: string[];
28
+ }
29
+
30
+ const HEALTHY_SUBSCRIPTION_STATUSES: ReadonlySet<SubscriptionStatus> = new Set([
31
+ "active",
32
+ ]);
33
+
34
+ const UNAVAILABLE_SUBSCRIPTION_STATUSES: ReadonlySet<SubscriptionStatus> =
35
+ new Set(["exhausted", "rate-limited", "expired", "unconfigured", "unknown"]);
36
+
37
+ function candidateId(c: ProviderCandidate): string {
38
+ return `${c.providerId}:${c.modelId}`;
39
+ }
40
+
41
+ function matchesGlob(pattern: string, value: string): boolean {
42
+ // Escape regex special chars except *, then turn * into .*
43
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
44
+ const re = new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);
45
+ return re.test(value);
46
+ }
47
+
48
+ function isWorkProfileDenied(
49
+ profile: string,
50
+ patterns: string[] | undefined,
51
+ ): boolean {
52
+ // Work profiles are denied by default. Custom patterns are additive.
53
+ // Align with the Claude installer: a profile is work-like if it ends with
54
+ // "-work" (e.g. claude-work) or contains "-work-" (e.g. claude-work-staging).
55
+ const effectivePatterns = ["*-work", ...(patterns ?? [])];
56
+ return (
57
+ profile.endsWith("-work") ||
58
+ profile.includes("-work-") ||
59
+ effectivePatterns.some((pattern) => matchesGlob(pattern, profile))
60
+ );
61
+ }
62
+
63
+ function isAllowedProfile(profile: string, config: PolicyConfig): boolean {
64
+ return config.allowlistedProfiles.includes(profile);
65
+ }
66
+
67
+ /**
68
+ * Whether a candidate meets hard capability requirements from the task.
69
+ */
70
+ export function meetsCapabilities(
71
+ candidate: ProviderCandidate,
72
+ request: RouteRequest,
73
+ ): boolean {
74
+ const { task } = request;
75
+ if (task.requiresTools && !candidate.supportsTools) return false;
76
+ if (task.requiresImages && !candidate.supportsImages) return false;
77
+ if (task.requiresStreaming && !candidate.supportsStreaming) return false;
78
+ if (task.requiresJson && !candidate.supportsJson) return false;
79
+ // Task kind shortcuts when requires* not set explicitly
80
+ if (task.kind === "tools" && task.requiresTools !== false && !candidate.supportsTools) {
81
+ return false;
82
+ }
83
+ if (task.kind === "image" && task.requiresImages !== false && !candidate.supportsImages) {
84
+ return false;
85
+ }
86
+ return true;
87
+ }
88
+
89
+ function missingCapabilityMessage(
90
+ candidate: ProviderCandidate,
91
+ request: RouteRequest,
92
+ ): string {
93
+ const missing: string[] = [];
94
+ if (
95
+ (request.task.requiresTools || request.task.kind === "tools") &&
96
+ !candidate.supportsTools
97
+ ) {
98
+ missing.push("tools");
99
+ }
100
+ if (
101
+ (request.task.requiresImages || request.task.kind === "image") &&
102
+ !candidate.supportsImages
103
+ ) {
104
+ missing.push("images");
105
+ }
106
+ if (request.task.requiresStreaming && !candidate.supportsStreaming) {
107
+ missing.push("streaming");
108
+ }
109
+ if (request.task.requiresJson && !candidate.supportsJson) {
110
+ missing.push("json");
111
+ }
112
+ return `Candidate ${candidateId(candidate)} missing required capabilities: ${missing.join(", ") || "unknown"}.`;
113
+ }
114
+
115
+ /**
116
+ * Healthy subscription capacity: active status (or omitted treated carefully)
117
+ * with non-dead health, and policy/capability eligible.
118
+ *
119
+ * Degraded health is still "usable" for routing later but is not treated as
120
+ * fully healthy capacity for blocking API-key candidates when another healthy
121
+ * subscription exists — that nuance lives in the router score. For policy
122
+ * gatekeeping "can a healthy subscription satisfy the task?", we accept
123
+ * health === "healthy" and subscriptionStatus in active (defaulting missing
124
+ * status on subscription tier to unknown, not healthy).
125
+ */
126
+ export function isHealthySubscriptionCapacity(
127
+ candidate: ProviderCandidate,
128
+ request: RouteRequest,
129
+ config: PolicyConfig,
130
+ ): boolean {
131
+ if (candidate.authTier !== "subscription") return false;
132
+ if (candidate.health !== "healthy") return false;
133
+
134
+ const status = candidate.subscriptionStatus ?? "unknown";
135
+ if (!HEALTHY_SUBSCRIPTION_STATUSES.has(status)) return false;
136
+
137
+ if (
138
+ candidate.authScope === "third-party" &&
139
+ !config.allowThirdPartySubscriptionAdapters
140
+ ) {
141
+ return false;
142
+ }
143
+ if (candidate.authScope === "unknown") {
144
+ return false;
145
+ }
146
+
147
+ if (!meetsCapabilities(candidate, request)) return false;
148
+
149
+ // Subscription positions are never local; localOnly excludes them.
150
+ if (request.constraints.localOnly) {
151
+ return false;
152
+ }
153
+
154
+ if (
155
+ request.constraints.maxCostUsd !== undefined &&
156
+ candidate.estimatedCostUsd !== undefined &&
157
+ candidate.estimatedCostUsd > request.constraints.maxCostUsd
158
+ ) {
159
+ return false;
160
+ }
161
+
162
+ if (config.deniedProviders?.includes(candidate.providerId)) {
163
+ return false;
164
+ }
165
+
166
+ return true;
167
+ }
168
+
169
+ /**
170
+ * Whether any remaining subscription candidate has healthy capacity after hard
171
+ * filters, so API-key stays blocked only while a healthy subscription route can
172
+ * satisfy the task.
173
+ */
174
+ function hasUsableSubscriptionForTask(
175
+ candidates: ProviderCandidate[],
176
+ request: RouteRequest,
177
+ config: PolicyConfig,
178
+ ): boolean {
179
+ return candidates.some((c) => {
180
+ if (c.authTier !== "subscription") return false;
181
+ if (c.health !== "healthy") return false;
182
+ const status = c.subscriptionStatus ?? "unknown";
183
+ // Only active + healthy subscription capacity blocks API-key candidates
184
+ // under subscription-first.
185
+ if (!HEALTHY_SUBSCRIPTION_STATUSES.has(status)) return false;
186
+ if (
187
+ c.authScope === "third-party" &&
188
+ !config.allowThirdPartySubscriptionAdapters
189
+ ) {
190
+ return false;
191
+ }
192
+ if (c.authScope === "unknown") return false;
193
+ if (!meetsCapabilities(c, request)) return false;
194
+ if (request.constraints.localOnly) return false;
195
+ if (
196
+ request.constraints.maxCostUsd !== undefined &&
197
+ c.estimatedCostUsd !== undefined &&
198
+ c.estimatedCostUsd > request.constraints.maxCostUsd
199
+ ) {
200
+ return false;
201
+ }
202
+ if (config.deniedProviders?.includes(c.providerId)) return false;
203
+ return true;
204
+ });
205
+ }
206
+
207
+ function hardFilterDenial(
208
+ candidate: ProviderCandidate,
209
+ request: RouteRequest,
210
+ config: PolicyConfig,
211
+ ): PolicyDenial | null {
212
+ const id = candidateId(candidate);
213
+
214
+ if (config.deniedProviders?.includes(candidate.providerId)) {
215
+ return {
216
+ code: "provider_denied",
217
+ target: "provider",
218
+ id: candidate.providerId,
219
+ message: `Provider ${candidate.providerId} is denied by policy.`,
220
+ };
221
+ }
222
+
223
+ if (request.constraints.localOnly && candidate.authTier !== "local") {
224
+ return {
225
+ code: "local_only_required",
226
+ target: "candidate",
227
+ id,
228
+ message: `Candidate ${id} is not a local runtime; localOnly is required.`,
229
+ };
230
+ }
231
+
232
+ if (
233
+ request.constraints.maxCostUsd !== undefined &&
234
+ candidate.authTier === "api-key" &&
235
+ candidate.estimatedCostUsd === undefined
236
+ ) {
237
+ return {
238
+ code: "cost_cap_exceeded",
239
+ target: "candidate",
240
+ id,
241
+ message: `API-key candidate ${id} has unknown cost and cannot satisfy maxCostUsd ${request.constraints.maxCostUsd}.`,
242
+ };
243
+ }
244
+
245
+ if (
246
+ request.constraints.maxCostUsd !== undefined &&
247
+ candidate.estimatedCostUsd !== undefined &&
248
+ candidate.estimatedCostUsd > request.constraints.maxCostUsd
249
+ ) {
250
+ return {
251
+ code: "cost_cap_exceeded",
252
+ target: "candidate",
253
+ id,
254
+ message: `Candidate ${id} estimated cost ${candidate.estimatedCostUsd} exceeds maxCostUsd ${request.constraints.maxCostUsd}.`,
255
+ };
256
+ }
257
+
258
+ if (!meetsCapabilities(candidate, request)) {
259
+ return {
260
+ code: "capability_missing",
261
+ target: "candidate",
262
+ id,
263
+ message: missingCapabilityMessage(candidate, request),
264
+ };
265
+ }
266
+
267
+ // First-party subscription surface via third-party adapter
268
+ if (
269
+ candidate.authTier === "subscription" &&
270
+ candidate.authScope === "third-party" &&
271
+ !config.allowThirdPartySubscriptionAdapters
272
+ ) {
273
+ return {
274
+ code: "subscription_scope_denied",
275
+ target: "candidate",
276
+ id,
277
+ message: `Subscription candidate ${id} uses a third-party adapter surface without policy allow.`,
278
+ };
279
+ }
280
+
281
+ if (
282
+ candidate.authTier === "subscription" &&
283
+ candidate.authScope === "unknown"
284
+ ) {
285
+ return {
286
+ code: "subscription_scope_denied",
287
+ target: "candidate",
288
+ id,
289
+ message: `Subscription candidate ${id} has unknown auth scope and cannot route until the adapter proves support.`,
290
+ };
291
+ }
292
+
293
+ // Dead candidates never route
294
+ if (candidate.health === "dead") {
295
+ // Treat as policy-ineligible for selection; keep as structured denial so
296
+ // explain paths can show why. Prefer provider_denied-ish message without
297
+ // inventing a new code — map to provider_denied for dead health is
298
+ // slightly imprecise; capability isn't right. Use provider_denied for
299
+ // explicit denylist only. For dead, we skip without adding denial so
300
+ // they simply don't appear as allowed. Router will then handle empty set.
301
+ // Actually: don't allow them, no denial needed for "dead" — just exclude.
302
+ return {
303
+ code: "provider_denied",
304
+ target: "candidate",
305
+ id,
306
+ message: `Candidate ${id} is dead and cannot be selected.`,
307
+ };
308
+ }
309
+
310
+ // Exhausted/rate-limited/expired subscription tiers are not allowed as primary
311
+ if (candidate.authTier === "subscription") {
312
+ const status = candidate.subscriptionStatus ?? "unknown";
313
+ if (UNAVAILABLE_SUBSCRIPTION_STATUSES.has(status)) {
314
+ return {
315
+ code: "provider_denied",
316
+ target: "candidate",
317
+ id,
318
+ message: `Subscription candidate ${id} is ${status} and cannot satisfy the task.`,
319
+ };
320
+ }
321
+ }
322
+
323
+ return null;
324
+ }
325
+
326
+ /**
327
+ * Evaluate profile and candidate policy.
328
+ * Returns allowed candidates plus structured denials (never string-only).
329
+ */
330
+ export function evaluatePolicy(
331
+ request: RouteRequest,
332
+ candidates: ProviderCandidate[],
333
+ config: PolicyConfig,
334
+ ): PolicyDecision {
335
+ const denials: PolicyDenial[] = [];
336
+ const profile = request.harness.profile;
337
+
338
+ // 1. Profile gates
339
+ if (isWorkProfileDenied(profile, config.deniedProfilePatterns)) {
340
+ denials.push({
341
+ code: "work_profile_denied",
342
+ target: "profile",
343
+ id: profile,
344
+ message: `Work profile ${profile} is denied by default. OffRouter V1 only routes allowlisted personal profiles.`,
345
+ });
346
+ return { allowed: [], denials };
347
+ }
348
+
349
+ if (!isAllowedProfile(profile, config)) {
350
+ denials.push({
351
+ code: "profile_not_allowlisted",
352
+ target: "profile",
353
+ id: profile,
354
+ message: `Profile ${profile} is not allowlisted. Add it explicitly before installing or routing.`,
355
+ });
356
+ return { allowed: [], denials };
357
+ }
358
+
359
+ // Workspace trust is a hard filter when untrusted
360
+ if (!request.workspace.trusted) {
361
+ denials.push({
362
+ code: "project_untrusted",
363
+ target: "workspace",
364
+ id: request.workspace.cwd,
365
+ message: `Workspace ${request.workspace.cwd} is untrusted; routing is blocked.`,
366
+ });
367
+ return { allowed: [], denials };
368
+ }
369
+
370
+ // 2. Hard filters per candidate
371
+ const hardPassed: ProviderCandidate[] = [];
372
+ for (const c of candidates) {
373
+ const denial = hardFilterDenial(c, request, config);
374
+ if (denial) {
375
+ denials.push(denial);
376
+ } else {
377
+ hardPassed.push(c);
378
+ }
379
+ }
380
+
381
+ // 3. Subscription-first: gate API-key when usable subscription capacity exists,
382
+ // or when allowApiKeyFallback is false.
383
+ const subscriptionFirst = request.constraints.subscriptionFirst !== false;
384
+ const allowApiKeyFallback = request.constraints.allowApiKeyFallback === true;
385
+
386
+ const usableSubscription = hasUsableSubscriptionForTask(
387
+ hardPassed,
388
+ request,
389
+ config,
390
+ );
391
+
392
+ const allowed: ProviderCandidate[] = [];
393
+ for (const c of hardPassed) {
394
+ if (c.authTier === "api-key") {
395
+ if (subscriptionFirst && usableSubscription) {
396
+ denials.push({
397
+ code: "api_key_blocked_by_subscription_first_policy",
398
+ target: "candidate",
399
+ id: candidateId(c),
400
+ message: `API-key candidate ${candidateId(c)} blocked while healthy subscription capacity remains.`,
401
+ });
402
+ continue;
403
+ }
404
+ if (subscriptionFirst && !allowApiKeyFallback) {
405
+ denials.push({
406
+ code: "api_key_blocked_by_subscription_first_policy",
407
+ target: "candidate",
408
+ id: candidateId(c),
409
+ message: `API-key candidate ${candidateId(c)} blocked: allowApiKeyFallback is false.`,
410
+ });
411
+ continue;
412
+ }
413
+ }
414
+ allowed.push(c);
415
+ }
416
+
417
+ return { allowed, denials };
418
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * OffRouter V1 route protocol constants.
3
+ * Wire vocabulary: docs/contracts/v1-routing-contract.md
4
+ */
5
+ export const ROUTE_PROTOCOL_VERSION = "offrouter.route.v1" as const;
6
+
7
+ export type RouteProtocolVersion = typeof ROUTE_PROTOCOL_VERSION;