@hasna/switcher 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -499,7 +499,7 @@ function canonicalPolicyJSON(value) {
499
499
  }
500
500
 
501
501
  // src/domain.ts
502
- var VERSION = "0.1.5";
502
+ var VERSION = "0.1.6";
503
503
  var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
504
504
  var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
505
505
  var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -524,11 +524,16 @@ var urlSchema = z3.string().max(2000).superRefine((v, ctx) => {
524
524
  ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
525
525
  }
526
526
  }).transform(endpoint);
527
+ var expiresOnSchema = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
528
+ const day = new Date(`${value}T00:00:00.000Z`);
529
+ return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
530
+ }, "Use a real calendar date in YYYY-MM-DD format.");
527
531
  var modelSchema = z3.object({
528
532
  id: z3.string().min(1).max(300),
529
533
  name: label,
530
534
  description: z3.string().max(8000).optional(),
531
535
  available: z3.boolean().optional(),
536
+ expiresOn: expiresOnSchema.optional(),
532
537
  contextWindow: z3.number().int().positive().optional(),
533
538
  maxOutputTokens: z3.number().int().positive().optional(),
534
539
  inputModalities: z3.array(z3.string().max(50)).max(20).optional(),
@@ -549,7 +554,8 @@ var providerInputSchema = z3.object({
549
554
  catalogCredentialEnv: envRef.optional(),
550
555
  catalogAccountId: z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),
551
556
  modelsPath: z3.string().regex(/^[a-zA-Z0-9_/-]+$/).max(200).default("models"),
552
- manualModels: z3.array(modelSchema).max(1e4).default([])
557
+ manualModels: z3.array(modelSchema).max(1e4).default([]),
558
+ additionalModels: z3.array(modelSchema).max(1e4).optional()
553
559
  }).strict().refine((p) => !p.modelsPath.split("/").includes("..") && !p.modelsPath.startsWith("/"), "modelsPath must be relative");
554
560
  var providerPresetSchema = z3.object({
555
561
  id: idSchema,
@@ -632,11 +638,14 @@ function validateHarnessProvider(harness, provider) {
632
638
  if (harness === "gemini" && provider.authStyle !== "x-api-key")
633
639
  throw new Fault(422, "auth_mismatch", "Gemini CLI requires x-api-key authentication for its native generateContent protocol.");
634
640
  }
641
+ function modelExpired(model, now = new Date) {
642
+ return model.expiresOn !== undefined && now.toISOString().slice(0, 10) > model.expiresOn;
643
+ }
635
644
  function codingEligible(model) {
636
- return model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.outputModalities || model.outputModalities.includes("text")) && (!model.supportedParameters || model.supportedParameters.includes("tools"));
645
+ return !modelExpired(model) && model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.outputModalities || model.outputModalities.includes("text")) && (!model.supportedParameters || model.supportedParameters.includes("tools"));
637
646
  }
638
647
  function harnessEligible(model, harness) {
639
- return harness === "aider" ? model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.inputModalities || model.inputModalities.includes("text")) && (!model.outputModalities || model.outputModalities.includes("text")) : codingEligible(model);
648
+ return !modelExpired(model) && (harness === "aider" ? model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.inputModalities || model.inputModalities.includes("text")) && (!model.outputModalities || model.outputModalities.includes("text")) : codingEligible(model));
640
649
  }
641
650
 
642
651
  // src/kilo.ts
@@ -1155,7 +1164,12 @@ function providerFromPreset(presetId, options = {}) {
1155
1164
  catalogAuthStyle: options.catalogAuthStyle ?? selected.catalogAuthStyle,
1156
1165
  catalogFormat: options.catalogFormat ?? selected.catalogFormat,
1157
1166
  catalogAccountId: options.catalogAccountId,
1158
- modelsPath: options.modelsPath ?? selected.modelsPath
1167
+ modelsPath: options.modelsPath ?? selected.modelsPath,
1168
+ additionalModels: presetId === "deepseek" && new URL(baseUrl).origin === "https://api.deepseek.com" ? [{
1169
+ id: "deepseek-v4.1-flash-expires-on-0910",
1170
+ name: "DeepSeek V4.1 Flash preview",
1171
+ expiresOn: "2026-09-10"
1172
+ }] : []
1159
1173
  });
1160
1174
  }
1161
1175
  function providerCredential(provider, env = process.env) {
@@ -1474,6 +1488,17 @@ function proxyProviderStream(input) {
1474
1488
  } };
1475
1489
  }
1476
1490
 
1491
+ // src/claude-context.ts
1492
+ function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
1493
+ const explicit = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
1494
+ if (explicit !== undefined)
1495
+ return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: explicit };
1496
+ const provider = new URL(providerBaseUrl);
1497
+ if (provider.origin === "https://api.deepseek.com" && /^\/anthropic(?:\/v1)?\/?$/.test(provider.pathname))
1498
+ return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "786432" };
1499
+ return {};
1500
+ }
1501
+
1477
1502
  // src/opencode-model-policy.ts
1478
1503
  var routeForAgent = (agent) => {
1479
1504
  const name = agent.name.toLowerCase();
@@ -1793,7 +1818,7 @@ async function fetchCatalogPage(url, headers, deadline) {
1793
1818
  await waitForCatalogRetry(delay ?? 100 * 2 ** retry, deadline);
1794
1819
  }
1795
1820
  }
1796
- async function discover(provider, env = process.env, resolveCredential) {
1821
+ async function discoverBase(provider, env = process.env, resolveCredential) {
1797
1822
  const refreshedAt = new Date().toISOString();
1798
1823
  if (provider.manualModels.length)
1799
1824
  return { models: provider.manualModels, source: "manual", refreshedAt };
@@ -1851,6 +1876,7 @@ async function discover(provider, env = process.env, resolveCredential) {
1851
1876
  id,
1852
1877
  name: row.displayName ?? row.name ?? row.display_name ?? id,
1853
1878
  available: provider.catalogFormat === "mistral" && typeof row.archived === "boolean" ? !row.archived : undefined,
1879
+ expiresOn: row.expiresOn ?? row.expires_on,
1854
1880
  description: typeof row.description === "string" ? row.description.slice(0, 8000) : undefined,
1855
1881
  contextWindow: positive(row.context_length ?? row.context_window ?? row.contextLength ?? row.inputTokenLimit ?? row.model_info?.context_window ?? (provider.catalogFormat === "mistral" ? row.max_context_length : undefined)),
1856
1882
  maxOutputTokens: positive(row.top_provider?.max_completion_tokens ?? row.max_output_tokens ?? row.outputTokenLimit ?? row.model_info?.max_output_tokens),
@@ -1977,6 +2003,15 @@ async function discover(provider, env = process.env, resolveCredential) {
1977
2003
  }
1978
2004
  throw new Fault(502, "catalog_too_large", "Provider catalog pagination exceeded 100 pages.");
1979
2005
  }
2006
+ async function discover(provider, env = process.env, resolveCredential) {
2007
+ const catalog = await discoverBase(provider, env, resolveCredential);
2008
+ const models = new Map(catalog.models.map((model) => [model.id, model]));
2009
+ for (const additional of provider.additionalModels ?? [])
2010
+ models.set(additional.id, { ...models.get(additional.id), ...additional });
2011
+ if (models.size > 1e4)
2012
+ throw new Fault(502, "catalog_too_large", "Combined catalog exceeds 10,000 models.");
2013
+ return { ...catalog, models: [...models.values()] };
2014
+ }
1980
2015
 
1981
2016
  // src/model-policy.ts
1982
2017
  import { createHash as createHash2 } from "crypto";
@@ -1992,9 +2027,15 @@ function stable(value) {
1992
2027
  }
1993
2028
  function compileModelPolicy(model, catalog, policy) {
1994
2029
  const selected = id(model, "model");
1995
- const available = new Set(catalog.filter((m) => m.available !== false).map((m) => m.id));
1996
- if (!available.has(selected))
1997
- throw new Fault(422, "model_unavailable", "Selected model is not present in the eligible catalog.");
2030
+ const available = new Set(catalog.filter((m) => m.available !== false && !modelExpired(m)).map((m) => m.id));
2031
+ const expired = new Set(catalog.filter((m) => modelExpired(m)).map((m) => m.id));
2032
+ const requireAvailable = (value, message) => {
2033
+ if (expired.has(value))
2034
+ throw new Fault(422, "model_expired", "A selected model has passed its configured expiry date. Select an unexpired model.");
2035
+ if (!available.has(value))
2036
+ throw new Fault(422, "model_unavailable", message);
2037
+ };
2038
+ requireAvailable(selected, "Selected model is not present in the eligible catalog.");
1998
2039
  if (policy && policy.version !== undefined && policy.version !== 1)
1999
2040
  throw new Fault(400, "invalid_model_policy", "Unsupported model policy version.");
2000
2041
  const p = parse2(modelPolicySchema, policy ?? {});
@@ -2003,14 +2044,12 @@ function compileModelPolicy(model, catalog, policy) {
2003
2044
  throw new Fault(400, "invalid_model_policy", "Unknown model policy role.");
2004
2045
  const compiledRoles = Object.fromEntries(roles.map((role) => [role, id(roleInput[role] ?? selected, `roles.${role}`)]));
2005
2046
  for (const value of Object.values(compiledRoles))
2006
- if (!available.has(value))
2007
- throw new Fault(422, "model_unavailable", "A model policy role is not present in the eligible catalog.");
2047
+ requireAvailable(value, "A model policy role is not present in the eligible catalog.");
2008
2048
  const explicitAllowed = (p.allowedModels ?? []).map((v, i) => id(v, `allowedModels[${i}]`));
2009
2049
  if (explicitAllowed.length > 500)
2010
2050
  throw new Fault(400, "invalid_model_policy", "Model policy allowedModels is too large.");
2011
2051
  for (const value of explicitAllowed)
2012
- if (!available.has(value))
2013
- throw new Fault(422, "model_unavailable", "An allowed model is not present in the eligible catalog.");
2052
+ requireAvailable(value, "An allowed model is not present in the eligible catalog.");
2014
2053
  const aliases = Object.create(null);
2015
2054
  for (const [name, target] of Object.entries(p.aliases ?? {})) {
2016
2055
  if (Object.keys(aliases).length >= 200 || !/^[A-Za-z0-9._/-]{1,120}$/.test(name) || ["__proto__", "prototype", "constructor"].includes(name))
@@ -2018,8 +2057,7 @@ function compileModelPolicy(model, catalog, policy) {
2018
2057
  const canonical = id(target, `aliases.${name}`);
2019
2058
  if (available.has(name) && name !== canonical)
2020
2059
  throw new Fault(400, "invalid_model_policy", "A model alias cannot shadow a real model ID.");
2021
- if (!available.has(canonical))
2022
- throw new Fault(422, "model_unavailable", "A model alias target is not present in the eligible catalog.");
2060
+ requireAvailable(canonical, "A model alias target is not present in the eligible catalog.");
2023
2061
  aliases[name] = canonical;
2024
2062
  }
2025
2063
  const fallbacks = Object.create(null);
@@ -2028,8 +2066,8 @@ function compileModelPolicy(model, catalog, policy) {
2028
2066
  if (!allowedSources.has(source) || !available.has(source) || !Array.isArray(targets) || Object.keys(fallbacks).length >= 200 || targets.length > 20)
2029
2067
  throw new Fault(400, "invalid_model_policy", "Fallback source or list is invalid.");
2030
2068
  const values2 = targets.map((v, i) => id(v, `fallbacks.${source}[${i}]`));
2031
- if (values2.some((v) => !available.has(v)))
2032
- throw new Fault(422, "model_unavailable", "A fallback model is not present in the eligible catalog.");
2069
+ for (const value of values2)
2070
+ requireAvailable(value, "A fallback model is not present in the eligible catalog.");
2033
2071
  if (values2.includes(source))
2034
2072
  throw new Fault(400, "invalid_model_policy", "A model cannot fall back to itself.");
2035
2073
  fallbacks[source] = uniq(values2);
@@ -2140,7 +2178,7 @@ var openapi_default = {
2140
2178
  openapi: "3.0.3",
2141
2179
  info: {
2142
2180
  title: "Switcher API",
2143
- version: "0.1.5",
2181
+ version: "0.1.6",
2144
2182
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2145
2183
  },
2146
2184
  security: [
@@ -3541,6 +3579,10 @@ var openapi_default = {
3541
3579
  available: {
3542
3580
  type: "boolean"
3543
3581
  },
3582
+ expiresOn: {
3583
+ type: "string",
3584
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
3585
+ },
3544
3586
  contextWindow: {
3545
3587
  type: "integer",
3546
3588
  exclusiveMinimum: true,
@@ -3593,6 +3635,84 @@ var openapi_default = {
3593
3635
  },
3594
3636
  maxItems: 1e4,
3595
3637
  default: []
3638
+ },
3639
+ additionalModels: {
3640
+ type: "array",
3641
+ items: {
3642
+ type: "object",
3643
+ properties: {
3644
+ id: {
3645
+ type: "string",
3646
+ minLength: 1,
3647
+ maxLength: 300
3648
+ },
3649
+ name: {
3650
+ type: "string",
3651
+ minLength: 1,
3652
+ maxLength: 200
3653
+ },
3654
+ description: {
3655
+ type: "string",
3656
+ maxLength: 8000
3657
+ },
3658
+ available: {
3659
+ type: "boolean"
3660
+ },
3661
+ expiresOn: {
3662
+ type: "string",
3663
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
3664
+ },
3665
+ contextWindow: {
3666
+ type: "integer",
3667
+ exclusiveMinimum: true,
3668
+ minimum: 0
3669
+ },
3670
+ maxOutputTokens: {
3671
+ type: "integer",
3672
+ exclusiveMinimum: true,
3673
+ minimum: 0
3674
+ },
3675
+ inputModalities: {
3676
+ type: "array",
3677
+ items: {
3678
+ type: "string",
3679
+ maxLength: 50
3680
+ },
3681
+ maxItems: 20
3682
+ },
3683
+ outputModalities: {
3684
+ type: "array",
3685
+ items: {
3686
+ type: "string",
3687
+ maxLength: 50
3688
+ },
3689
+ maxItems: 20
3690
+ },
3691
+ supportedParameters: {
3692
+ type: "array",
3693
+ items: {
3694
+ type: "string",
3695
+ maxLength: 100
3696
+ },
3697
+ maxItems: 100
3698
+ },
3699
+ supportedGenerationMethods: {
3700
+ type: "array",
3701
+ items: {
3702
+ type: "string",
3703
+ minLength: 1,
3704
+ maxLength: 100
3705
+ },
3706
+ maxItems: 100
3707
+ }
3708
+ },
3709
+ required: [
3710
+ "id",
3711
+ "name"
3712
+ ],
3713
+ additionalProperties: false
3714
+ },
3715
+ maxItems: 1e4
3596
3716
  }
3597
3717
  },
3598
3718
  required: [
@@ -3703,6 +3823,10 @@ var openapi_default = {
3703
3823
  available: {
3704
3824
  type: "boolean"
3705
3825
  },
3826
+ expiresOn: {
3827
+ type: "string",
3828
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
3829
+ },
3706
3830
  contextWindow: {
3707
3831
  type: "integer",
3708
3832
  exclusiveMinimum: true,
@@ -3756,6 +3880,84 @@ var openapi_default = {
3756
3880
  maxItems: 1e4,
3757
3881
  default: []
3758
3882
  },
3883
+ additionalModels: {
3884
+ type: "array",
3885
+ items: {
3886
+ type: "object",
3887
+ properties: {
3888
+ id: {
3889
+ type: "string",
3890
+ minLength: 1,
3891
+ maxLength: 300
3892
+ },
3893
+ name: {
3894
+ type: "string",
3895
+ minLength: 1,
3896
+ maxLength: 200
3897
+ },
3898
+ description: {
3899
+ type: "string",
3900
+ maxLength: 8000
3901
+ },
3902
+ available: {
3903
+ type: "boolean"
3904
+ },
3905
+ expiresOn: {
3906
+ type: "string",
3907
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
3908
+ },
3909
+ contextWindow: {
3910
+ type: "integer",
3911
+ exclusiveMinimum: true,
3912
+ minimum: 0
3913
+ },
3914
+ maxOutputTokens: {
3915
+ type: "integer",
3916
+ exclusiveMinimum: true,
3917
+ minimum: 0
3918
+ },
3919
+ inputModalities: {
3920
+ type: "array",
3921
+ items: {
3922
+ type: "string",
3923
+ maxLength: 50
3924
+ },
3925
+ maxItems: 20
3926
+ },
3927
+ outputModalities: {
3928
+ type: "array",
3929
+ items: {
3930
+ type: "string",
3931
+ maxLength: 50
3932
+ },
3933
+ maxItems: 20
3934
+ },
3935
+ supportedParameters: {
3936
+ type: "array",
3937
+ items: {
3938
+ type: "string",
3939
+ maxLength: 100
3940
+ },
3941
+ maxItems: 100
3942
+ },
3943
+ supportedGenerationMethods: {
3944
+ type: "array",
3945
+ items: {
3946
+ type: "string",
3947
+ minLength: 1,
3948
+ maxLength: 100
3949
+ },
3950
+ maxItems: 100
3951
+ }
3952
+ },
3953
+ required: [
3954
+ "id",
3955
+ "name"
3956
+ ],
3957
+ additionalProperties: false
3958
+ },
3959
+ maxItems: 1e4
3960
+ },
3759
3961
  version: {
3760
3962
  type: "integer",
3761
3963
  exclusiveMinimum: true,
@@ -4103,6 +4305,10 @@ var openapi_default = {
4103
4305
  available: {
4104
4306
  type: "boolean"
4105
4307
  },
4308
+ expiresOn: {
4309
+ type: "string",
4310
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
4311
+ },
4106
4312
  contextWindow: {
4107
4313
  type: "integer",
4108
4314
  exclusiveMinimum: true,
@@ -4347,6 +4553,10 @@ var openapi_default = {
4347
4553
  available: {
4348
4554
  type: "boolean"
4349
4555
  },
4556
+ expiresOn: {
4557
+ type: "string",
4558
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
4559
+ },
4350
4560
  contextWindow: {
4351
4561
  type: "integer",
4352
4562
  exclusiveMinimum: true,
@@ -4392,12 +4602,16 @@ var openapi_default = {
4392
4602
  },
4393
4603
  codingEligible: {
4394
4604
  type: "boolean"
4605
+ },
4606
+ expired: {
4607
+ type: "boolean"
4395
4608
  }
4396
4609
  },
4397
4610
  required: [
4398
4611
  "id",
4399
4612
  "name",
4400
- "codingEligible"
4613
+ "codingEligible",
4614
+ "expired"
4401
4615
  ],
4402
4616
  additionalProperties: false
4403
4617
  }
@@ -4457,6 +4671,10 @@ var openapi_default = {
4457
4671
  available: {
4458
4672
  type: "boolean"
4459
4673
  },
4674
+ expiresOn: {
4675
+ type: "string",
4676
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
4677
+ },
4460
4678
  contextWindow: {
4461
4679
  type: "integer",
4462
4680
  exclusiveMinimum: true,
@@ -4629,6 +4847,10 @@ var openapi_default = {
4629
4847
  available: {
4630
4848
  type: "boolean"
4631
4849
  },
4850
+ expiresOn: {
4851
+ type: "string",
4852
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
4853
+ },
4632
4854
  contextWindow: {
4633
4855
  type: "integer",
4634
4856
  exclusiveMinimum: true,
@@ -4682,6 +4904,84 @@ var openapi_default = {
4682
4904
  maxItems: 1e4,
4683
4905
  default: []
4684
4906
  },
4907
+ additionalModels: {
4908
+ type: "array",
4909
+ items: {
4910
+ type: "object",
4911
+ properties: {
4912
+ id: {
4913
+ type: "string",
4914
+ minLength: 1,
4915
+ maxLength: 300
4916
+ },
4917
+ name: {
4918
+ type: "string",
4919
+ minLength: 1,
4920
+ maxLength: 200
4921
+ },
4922
+ description: {
4923
+ type: "string",
4924
+ maxLength: 8000
4925
+ },
4926
+ available: {
4927
+ type: "boolean"
4928
+ },
4929
+ expiresOn: {
4930
+ type: "string",
4931
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
4932
+ },
4933
+ contextWindow: {
4934
+ type: "integer",
4935
+ exclusiveMinimum: true,
4936
+ minimum: 0
4937
+ },
4938
+ maxOutputTokens: {
4939
+ type: "integer",
4940
+ exclusiveMinimum: true,
4941
+ minimum: 0
4942
+ },
4943
+ inputModalities: {
4944
+ type: "array",
4945
+ items: {
4946
+ type: "string",
4947
+ maxLength: 50
4948
+ },
4949
+ maxItems: 20
4950
+ },
4951
+ outputModalities: {
4952
+ type: "array",
4953
+ items: {
4954
+ type: "string",
4955
+ maxLength: 50
4956
+ },
4957
+ maxItems: 20
4958
+ },
4959
+ supportedParameters: {
4960
+ type: "array",
4961
+ items: {
4962
+ type: "string",
4963
+ maxLength: 100
4964
+ },
4965
+ maxItems: 100
4966
+ },
4967
+ supportedGenerationMethods: {
4968
+ type: "array",
4969
+ items: {
4970
+ type: "string",
4971
+ minLength: 1,
4972
+ maxLength: 100
4973
+ },
4974
+ maxItems: 100
4975
+ }
4976
+ },
4977
+ required: [
4978
+ "id",
4979
+ "name"
4980
+ ],
4981
+ additionalProperties: false
4982
+ },
4983
+ maxItems: 1e4
4984
+ },
4685
4985
  version: {
4686
4986
  type: "integer",
4687
4987
  exclusiveMinimum: true,
@@ -4885,6 +5185,10 @@ var openapi_default = {
4885
5185
  available: {
4886
5186
  type: "boolean"
4887
5187
  },
5188
+ expiresOn: {
5189
+ type: "string",
5190
+ pattern: "^\\d{4}-\\d{2}-\\d{2}$"
5191
+ },
4888
5192
  contextWindow: {
4889
5193
  type: "integer",
4890
5194
  exclusiveMinimum: true,
@@ -5664,7 +5968,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5664
5968
  const catalog = await store.get("catalogs", id2);
5665
5969
  const p = page();
5666
5970
  const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
5667
- return json({ ...catalog, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m) })), total: filtered.length, ...p });
5971
+ return json({ ...catalog, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
5668
5972
  }
5669
5973
  throw new Fault(404, "not_found", "Route was not found.");
5670
5974
  }
@@ -5750,9 +6054,11 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5750
6054
  const selected = catalog.models.find((m) => m.id === profile.model);
5751
6055
  if (!selected)
5752
6056
  throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
6057
+ if (modelExpired(selected))
6058
+ throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
5753
6059
  if (!harnessEligible(selected, profile.harness))
5754
6060
  throw new Fault(422, "model_ineligible", "Selected model is unavailable or explicitly lacks a required generation method, text output or tool support.");
5755
- compileModelPolicy(profile.model, catalog.models.filter((model) => harnessEligible(model, profile.harness)), profile.modelPolicy);
6061
+ compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
5756
6062
  const warnings = [];
5757
6063
  if (profile.harness !== "aider" && !selected.supportedParameters)
5758
6064
  warnings.push("Provider does not declare tool capabilities; execution compatibility is unverified.");
@@ -5784,6 +6090,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5784
6090
  }
5785
6091
  if (profile.harness !== input.harness || profile.model !== input.model || canonicalPolicyJSON(profile.modelPolicy ?? null) !== canonicalPolicyJSON(input.modelPolicy ?? profile.modelPolicy ?? null) || snapshot(profile, provider, catalog) !== input.planToken)
5786
6092
  throw new Fault(409, "plan_changed", "Provider, profile, model policy or catalog changed; request a fresh launch plan.");
6093
+ compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
5787
6094
  return store.put("runs", { ...input, modelPolicy: profile.modelPolicy, providerId: provider.id, providerVersion: provider.version, profileVersion: profile.version, id: crypto.randomUUID(), status: "running", startedAt: new Date().toISOString() }, undefined, db);
5788
6095
  }
5789
6096
  if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
@@ -6327,6 +6634,51 @@ function compileNativeModelPolicy(input) {
6327
6634
  return { harness: input.harness, env, config, unsupportedRoles };
6328
6635
  }
6329
6636
 
6637
+ // src/provider-error.ts
6638
+ var MAX_ERROR_BYTES = 16 * 1024;
6639
+ var ERROR_READ_TIMEOUT_MS = 1000;
6640
+ var contextCodes = new Set(["context_length_exceeded", "context_window_exceeded", "prompt_too_long"]);
6641
+ async function isContextOverflow(response) {
6642
+ if (![400, 413, 422].includes(response.status) || !response.body) {
6643
+ response.body?.cancel().catch(() => {
6644
+ return;
6645
+ });
6646
+ return false;
6647
+ }
6648
+ const reader = response.body.getReader();
6649
+ let timer;
6650
+ try {
6651
+ const timeout = new Promise((_, reject) => {
6652
+ timer = setTimeout(() => reject(new Error("provider_error_timeout")), ERROR_READ_TIMEOUT_MS);
6653
+ });
6654
+ const decoder = new TextDecoder("utf-8", { fatal: true });
6655
+ let bytes = 0, text = "";
6656
+ while (true) {
6657
+ const { done, value } = await Promise.race([reader.read(), timeout]);
6658
+ if (done)
6659
+ break;
6660
+ bytes += value.byteLength;
6661
+ if (bytes > MAX_ERROR_BYTES)
6662
+ return false;
6663
+ text += decoder.decode(value, { stream: true });
6664
+ }
6665
+ text += decoder.decode();
6666
+ const error = JSON.parse(text)?.error;
6667
+ if (!error || typeof error !== "object" || Array.isArray(error))
6668
+ return false;
6669
+ if ([error.code, error.type].some((code) => typeof code === "string" && contextCodes.has(code)))
6670
+ return true;
6671
+ return typeof error.message === "string" && /^(?:prompt is too long\b|(?:this model['\u2019]s )?maximum context length (?:is|has been exceeded)\b|(?:input|prompt) tokens? (?:exceed|exceeds|exceeded) (?:the )?(?:maximum|model['\u2019]s) context (?:length|window)\b)/i.test(error.message.trim());
6672
+ } catch {
6673
+ return false;
6674
+ } finally {
6675
+ clearTimeout(timer);
6676
+ reader.cancel().catch(() => {
6677
+ return;
6678
+ });
6679
+ }
6680
+ }
6681
+
6330
6682
  // src/inference-gateway.ts
6331
6683
  import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
6332
6684
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
@@ -6347,7 +6699,7 @@ function createInferenceGateway(input) {
6347
6699
  return fail(401, "unauthorized");
6348
6700
  const url = new URL(request.url);
6349
6701
  if (request.method === "GET" && url.pathname === "/v1/models" && !url.search)
6350
- return Response.json({ object: "list", data: input.models.map((m) => ({ ...m, object: "model" })) });
6702
+ return Response.json({ object: "list", data: input.models.filter((m) => !modelExpired(m)).map((m) => ({ ...m, object: "model" })) });
6351
6703
  const gemini = input.protocol === "gemini-generate-content";
6352
6704
  const match = gemini ? /^\/v1beta\/models\/([^/]+):(generateContent|streamGenerateContent|countTokens)$/.exec(url.pathname) : null;
6353
6705
  const prefix = input.protocol === "anthropic-messages" ? "/messages" : input.protocol === "openai-responses" ? "/responses" : "/chat/completions";
@@ -6384,6 +6736,8 @@ function createInferenceGateway(input) {
6384
6736
  if (typeof requested !== "string")
6385
6737
  throw new Fault(400, "model_required", "A model is required.");
6386
6738
  resolved = resolvePolicyModel(policy, requested);
6739
+ if (input.models.some((model) => model.id === resolved && modelExpired(model)))
6740
+ throw new Fault(422, "model_expired", "Selected model has expired.");
6387
6741
  if (gemini) {
6388
6742
  for (const declared of [body.model, body.generateContentRequest?.model])
6389
6743
  if (declared !== undefined && declared !== requested && declared !== `models/${requested}`)
@@ -6432,6 +6786,8 @@ function createInferenceGateway(input) {
6432
6786
  if (signal.aborted)
6433
6787
  throw new Error("aborted");
6434
6788
  const model = candidates[attempt];
6789
+ if (input.models.some((entry) => entry.id === model && modelExpired(entry)))
6790
+ throw new Fault(422, "model_expired", "Selected model has expired.");
6435
6791
  if (attempt) {
6436
6792
  flush();
6437
6793
  current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback" };
@@ -6466,8 +6822,12 @@ function createInferenceGateway(input) {
6466
6822
  if (!response)
6467
6823
  throw new Error("provider_request_failed");
6468
6824
  if (!response.ok) {
6469
- await response.body?.cancel();
6825
+ const overflow = await isContextOverflow(response);
6826
+ if (overflow)
6827
+ current.reason = "context_length_exceeded";
6470
6828
  release();
6829
+ if (overflow)
6830
+ return Response.json({ type: "error", error: { type: "invalid_request_error", code: "context_length_exceeded", message: "prompt is too long: the provider context window was exceeded. Compact the conversation or start a new session." } }, { status: 400 });
6471
6831
  return fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`);
6472
6832
  }
6473
6833
  if (!response.body) {
@@ -8861,6 +9221,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
8861
9221
  if (input.harness === "claude") {
8862
9222
  env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
8863
9223
  Object.assign(env, input.nativePolicy?.env);
9224
+ Object.assign(env, claudeContextEnvironment(providerBaseUrl));
8864
9225
  env.ANTHROPIC_MODEL = input.model;
8865
9226
  env.ANTHROPIC_DEFAULT_MODEL = input.model;
8866
9227
  env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
@@ -9207,6 +9568,7 @@ async function prepareHarnessLaunch(input) {
9207
9568
  if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
9208
9569
  throw new Error("Launch state and working directories must be absolute.");
9209
9570
  const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
9571
+ input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
9210
9572
  const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
9211
9573
  const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
9212
9574
  const unsupported2 = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
@@ -9868,7 +10230,7 @@ async function prepareOriForPlan(plan, options) {
9868
10230
  protocol: plan.provider.protocol,
9869
10231
  authStyle: plan.provider.authStyle,
9870
10232
  model: plan.profile.model,
9871
- models: plan.catalog.models.filter((m) => harnessEligible(m, plan.profile.harness)),
10233
+ models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
9872
10234
  modelPolicy: plan.profile.modelPolicy,
9873
10235
  providerId: plan.provider.id,
9874
10236
  onRoutingEvent: options.onRoutingEvent,
@@ -9978,7 +10340,7 @@ async function launch(client, profileId, options = {}) {
9978
10340
  baseUrl: plan.provider.baseUrl,
9979
10341
  protocol: plan.provider.protocol,
9980
10342
  model: plan.profile.model,
9981
- models: plan.catalog.models.filter((m) => harnessEligible(m, plan.profile.harness)),
10343
+ models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
9982
10344
  modelPolicy: plan.profile.modelPolicy,
9983
10345
  providerId: plan.provider.id,
9984
10346
  onRoutingEvent,
@@ -10136,7 +10498,9 @@ async function resolveLaunchProvider(client, selector, options = {}) {
10136
10498
  }
10137
10499
  }
10138
10500
  const { version, updatedAt, ...input } = existing;
10139
- if (JSON.stringify(parse2(providerInputSchema, input)) !== JSON.stringify(desired))
10501
+ const { additionalModels: _savedAdditions, ...savedSettings } = parse2(providerInputSchema, input);
10502
+ const { additionalModels: _presetAdditions, ...presetSettings } = desired;
10503
+ if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings))
10140
10504
  throw new Fault(409, "provider_conflict", "A saved provider with this preset ID has different settings. Select its ID directly or update it explicitly.");
10141
10505
  return existing;
10142
10506
  }
@@ -10160,7 +10524,7 @@ async function selectModel(models, query = "", harness) {
10160
10524
  const matching = eligible.filter((m) => `${m.id} ${m.name}`.toLowerCase().includes(query.toLowerCase()));
10161
10525
  const visible = matching.slice(0, 30);
10162
10526
  console.error(`Models: ${matching.length} match${matching.length === 1 ? "" : "es"}${matching.length > 30 ? " (first 30 shown; type to narrow)" : ""}.`);
10163
- visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}`));
10527
+ visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}${m.expiresOn ? ` (expires ${m.expiresOn}, inclusive UTC)` : ""}`));
10164
10528
  const answer = (await reader.question("Model number, exact model ID, or search text (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
10165
10529
  throw cancellation.signal.aborted ? cancellation.signal.reason : error;
10166
10530
  })).trim();
@@ -10656,6 +11020,7 @@ var HELP = `switcher \u2014 launch a coding harness with a provider and its mode
10656
11020
  switcher providers update ID --file provider.json --version N
10657
11021
  switcher providers delete ID --version N
10658
11022
  switcher models PROVIDER [--refresh] [--search TEXT] [--limit N]
11023
+ switcher models add PROVIDER MODEL [--name NAME] [--expires-on YYYY-MM-DD]
10659
11024
  switcher profiles list|get [ID]
10660
11025
  switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
10661
11026
  switcher profiles update ID --file profile.json --version N
@@ -10749,6 +11114,7 @@ async function main(args = process.argv.slice(2)) {
10749
11114
  offset: { type: "string" },
10750
11115
  "model-policy-file": { type: "string" },
10751
11116
  "role-model": { type: "string", multiple: true },
11117
+ "expires-on": { type: "string" },
10752
11118
  refresh: { type: "boolean" },
10753
11119
  backend: { type: "string" },
10754
11120
  cwd: { type: "string" },
@@ -10775,6 +11141,12 @@ async function main(args = process.argv.slice(2)) {
10775
11141
  throw new Error("Unknown command. Run switcher --help.");
10776
11142
  const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
10777
11143
  const provided = (names) => names.some((name) => values2[name] !== undefined);
11144
+ const addingModel = command === "models" && action2 === "add";
11145
+ if (values2["expires-on"] !== undefined && !addingModel)
11146
+ throw new Fault(400, "conflicting_options", "--expires-on belongs to models add.");
11147
+ if (addingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(values2).some((name) => !["name", "expires-on", "json"].includes(name))))
11148
+ throw new Fault(400, "invalid_request", "Use models add PROVIDER MODEL with optional --name and --expires-on.");
11149
+ const modelAddition = addingModel ? parse2(modelSchema, { id: positionals[3], name: values2.name ?? positionals[3], expiresOn: values2["expires-on"] }) : undefined;
10778
11150
  const credentialFlags = ["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator", "keychain-service", "keychain-account", "origin"];
10779
11151
  const credentials = new CredentialResolver;
10780
11152
  if (command === "credentials") {
@@ -10895,6 +11267,8 @@ async function main(args = process.argv.slice(2)) {
10895
11267
  const selected = catalog.models.find((m) => m.id === model3);
10896
11268
  if (!selected)
10897
11269
  throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
11270
+ if (modelExpired(selected))
11271
+ throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
10898
11272
  if (!harnessEligible(selected, harness))
10899
11273
  throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
10900
11274
  profileId = (await ensureLaunchProfile(client, provider, harness, model3, modelPolicy)).id;
@@ -10921,6 +11295,15 @@ async function main(args = process.argv.slice(2)) {
10921
11295
  process.exitCode = await launch(client, profileId, { backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
10922
11296
  return;
10923
11297
  }
11298
+ if (modelAddition) {
11299
+ const provider = await client.getProvider(id2);
11300
+ const { version, updatedAt, ...input } = provider;
11301
+ if ((provider.additionalModels ?? []).some((model3) => model3.id === modelAddition.id))
11302
+ throw new Fault(409, "model_exists", "This additional model already exists. Use providers update --file to edit its metadata.");
11303
+ await client.updateProvider({ ...input, additionalModels: [...provider.additionalModels ?? [], modelAddition] }, version);
11304
+ output({ providerId: provider.id, model: modelAddition, expired: modelExpired(modelAddition) });
11305
+ return;
11306
+ }
10924
11307
  if (command === "models" && action2) {
10925
11308
  const provider = await resolveLaunchProvider(client, action2, presetOptions());
10926
11309
  if (values2.refresh)