@f5-sales-demo/xcsh 21.21.1 → 21.21.3
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/CHANGELOG.md +3 -0
- package/package.json +8 -8
- package/src/config/model-registry.ts +59 -12
- package/src/config/model-resolver.ts +106 -6
- package/src/extensibility/extensions/types.ts +1 -1
- package/src/internal-urls/build-info.generated.ts +8 -8
- package/src/internal-urls/docs-index.generated.ts +1 -1
- package/src/main.ts +1 -1
- package/src/mcp/manager.ts +47 -27
- package/src/mcp/oauth-flow.ts +15 -4
- package/src/modes/components/model-selector.ts +11 -2
- package/src/modes/components/oauth-selector.ts +173 -39
- package/src/modes/controllers/login-options.ts +115 -1
- package/src/modes/controllers/selector-controller.ts +19 -6
- package/src/modes/interactive-mode.ts +9 -1
- package/src/sdk.ts +7 -6
- package/src/web/search/providers/gemini.ts +31 -64
package/CHANGELOG.md
CHANGED
|
@@ -48,6 +48,9 @@
|
|
|
48
48
|
|
|
49
49
|
### Fixed
|
|
50
50
|
|
|
51
|
+
- Routed MCP and Gemini web-search OAuth refreshes through the shared durable refresh coordinator,
|
|
52
|
+
including proactive refresh and forced retry after authentication failures
|
|
53
|
+
([#3796](https://github.com/f5-sales-demo/xcsh/issues/3796)).
|
|
51
54
|
- Kept `/login` honest after live validation by reporting reachable keyless vLLM services as
|
|
52
55
|
`keyless configured` and unreachable keyless services as `unreachable`
|
|
53
56
|
([#3783](https://github.com/f5-sales-demo/xcsh/issues/3783)).
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@f5-sales-demo/xcsh",
|
|
4
|
-
"version": "21.21.
|
|
4
|
+
"version": "21.21.3",
|
|
5
5
|
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
|
|
6
6
|
"homepage": "https://github.com/f5-sales-demo/xcsh",
|
|
7
7
|
"author": "Can Boluk",
|
|
@@ -62,13 +62,13 @@
|
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@agentclientprotocol/sdk": "1.3.0",
|
|
65
|
-
"@f5-sales-demo/pi-agent-core": "21.21.
|
|
66
|
-
"@f5-sales-demo/pi-ai": "21.21.
|
|
67
|
-
"@f5-sales-demo/pi-natives": "21.21.
|
|
68
|
-
"@f5-sales-demo/pi-resource-management": "21.21.
|
|
69
|
-
"@f5-sales-demo/pi-tui": "21.21.
|
|
70
|
-
"@f5-sales-demo/pi-utils": "21.21.
|
|
71
|
-
"@f5-sales-demo/xcsh-stats": "21.21.
|
|
65
|
+
"@f5-sales-demo/pi-agent-core": "21.21.3",
|
|
66
|
+
"@f5-sales-demo/pi-ai": "21.21.3",
|
|
67
|
+
"@f5-sales-demo/pi-natives": "21.21.3",
|
|
68
|
+
"@f5-sales-demo/pi-resource-management": "21.21.3",
|
|
69
|
+
"@f5-sales-demo/pi-tui": "21.21.3",
|
|
70
|
+
"@f5-sales-demo/pi-utils": "21.21.3",
|
|
71
|
+
"@f5-sales-demo/xcsh-stats": "21.21.3",
|
|
72
72
|
"@mozilla/readability": "^0.6",
|
|
73
73
|
"@sinclair/typebox": "^0.34",
|
|
74
74
|
"@xterm/headless": "^6.0",
|
|
@@ -445,6 +445,7 @@ export interface ProviderDiscoveryState {
|
|
|
445
445
|
optional: boolean;
|
|
446
446
|
stale: boolean;
|
|
447
447
|
fetchedAt?: number;
|
|
448
|
+
checkedAt?: number;
|
|
448
449
|
models: string[];
|
|
449
450
|
error?: string;
|
|
450
451
|
}
|
|
@@ -466,11 +467,12 @@ export type ProviderAccessStatus =
|
|
|
466
467
|
|
|
467
468
|
export interface ProviderAccessState {
|
|
468
469
|
provider: string;
|
|
470
|
+
configured: boolean;
|
|
469
471
|
credentialSource?: ProviderCredentialSource;
|
|
470
472
|
status: ProviderAccessStatus;
|
|
471
473
|
catalogFreshness: "none" | "fresh" | "stale";
|
|
472
474
|
failureReason?: string;
|
|
473
|
-
|
|
475
|
+
lastCheckedAt?: number;
|
|
474
476
|
selectable: boolean;
|
|
475
477
|
}
|
|
476
478
|
|
|
@@ -496,6 +498,20 @@ function isProviderAuthenticationFailure(reason: string | undefined): boolean {
|
|
|
496
498
|
);
|
|
497
499
|
}
|
|
498
500
|
|
|
501
|
+
/** Locally detectable credential failures that do not make a network-connectivity claim. */
|
|
502
|
+
export function getProviderLocalCredentialFailure(
|
|
503
|
+
provider: string,
|
|
504
|
+
environment: Record<string, string | undefined> = $env,
|
|
505
|
+
now: () => number = Date.now,
|
|
506
|
+
): string | undefined {
|
|
507
|
+
if (provider !== "amazon-bedrock") return undefined;
|
|
508
|
+
const rawExpiration = environment.AWS_CREDENTIAL_EXPIRATION ?? environment.AWS_SESSION_EXPIRATION;
|
|
509
|
+
if (!rawExpiration) return undefined;
|
|
510
|
+
const expiration = Date.parse(rawExpiration);
|
|
511
|
+
if (!Number.isFinite(expiration) || expiration > now()) return undefined;
|
|
512
|
+
return `AWS credentials expired at ${new Date(expiration).toISOString()}`;
|
|
513
|
+
}
|
|
514
|
+
|
|
499
515
|
export interface CanonicalModelQueryOptions {
|
|
500
516
|
availableOnly?: boolean;
|
|
501
517
|
candidates?: readonly Model<Api>[];
|
|
@@ -974,6 +990,7 @@ export class ModelRegistry {
|
|
|
974
990
|
optional: previous?.optional ?? false,
|
|
975
991
|
stale: previous?.stale ?? true,
|
|
976
992
|
fetchedAt: previous?.fetchedAt,
|
|
993
|
+
checkedAt: previous?.checkedAt,
|
|
977
994
|
models: previous?.models ?? [],
|
|
978
995
|
});
|
|
979
996
|
for (const selector of this.#suppressedSelectors.keys()) {
|
|
@@ -1394,6 +1411,7 @@ export class ModelRegistry {
|
|
|
1394
1411
|
providerConfig: DiscoveryProviderConfig,
|
|
1395
1412
|
strategy: ModelRefreshStrategy,
|
|
1396
1413
|
): Promise<Model<Api>[]> {
|
|
1414
|
+
const previous = this.#providerDiscoveryStates.get(providerConfig.provider);
|
|
1397
1415
|
const cached = readModelCache<Api>(providerConfig.provider, 24 * 60 * 60 * 1000, Date.now, this.#cacheDbPath);
|
|
1398
1416
|
const requiresAuth = !this.#keylessProviders.has(providerConfig.provider);
|
|
1399
1417
|
if (requiresAuth) {
|
|
@@ -1405,6 +1423,7 @@ export class ModelRegistry {
|
|
|
1405
1423
|
optional: providerConfig.optional ?? false,
|
|
1406
1424
|
stale: cached !== null,
|
|
1407
1425
|
fetchedAt: cached?.updatedAt,
|
|
1426
|
+
checkedAt: Date.now(),
|
|
1408
1427
|
models: cached?.models.map(model => model.id) ?? [],
|
|
1409
1428
|
});
|
|
1410
1429
|
this.#lastDiscoveryWarnings.delete(providerConfig.provider);
|
|
@@ -1450,6 +1469,7 @@ export class ModelRegistry {
|
|
|
1450
1469
|
optional: providerConfig.optional ?? false,
|
|
1451
1470
|
stale: result.stale || status === "cached",
|
|
1452
1471
|
fetchedAt: discoveryError || strategy === "offline" ? cached?.updatedAt : Date.now(),
|
|
1472
|
+
checkedAt: strategy === "offline" ? previous?.checkedAt : Date.now(),
|
|
1453
1473
|
models: result.models.map(model => model.id),
|
|
1454
1474
|
error: discoveryError,
|
|
1455
1475
|
});
|
|
@@ -1600,6 +1620,7 @@ export class ModelRegistry {
|
|
|
1600
1620
|
optional: false,
|
|
1601
1621
|
stale: true,
|
|
1602
1622
|
fetchedAt: previous?.fetchedAt,
|
|
1623
|
+
checkedAt: Date.now(),
|
|
1603
1624
|
models: previous?.models ?? [],
|
|
1604
1625
|
error: error instanceof Error ? error.message : String(error),
|
|
1605
1626
|
});
|
|
@@ -1628,6 +1649,7 @@ export class ModelRegistry {
|
|
|
1628
1649
|
optional: false,
|
|
1629
1650
|
stale: true,
|
|
1630
1651
|
fetchedAt: previous?.fetchedAt,
|
|
1652
|
+
checkedAt: Date.now(),
|
|
1631
1653
|
models: previous?.models ?? [],
|
|
1632
1654
|
});
|
|
1633
1655
|
}
|
|
@@ -1645,6 +1667,7 @@ export class ModelRegistry {
|
|
|
1645
1667
|
optional: false,
|
|
1646
1668
|
stale: true,
|
|
1647
1669
|
fetchedAt: previous?.fetchedAt,
|
|
1670
|
+
checkedAt: Date.now(),
|
|
1648
1671
|
models: previous?.models ?? [],
|
|
1649
1672
|
});
|
|
1650
1673
|
}
|
|
@@ -1685,12 +1708,20 @@ export class ModelRegistry {
|
|
|
1685
1708
|
const models = result.models.map(model =>
|
|
1686
1709
|
model.provider === options.providerId ? model : { ...model, provider: options.providerId },
|
|
1687
1710
|
);
|
|
1711
|
+
const status: ProviderDiscoveryStatus = discoveryError
|
|
1712
|
+
? isProviderAuthenticationFailure(discoveryError)
|
|
1713
|
+
? "unauthenticated"
|
|
1714
|
+
: "cached"
|
|
1715
|
+
: result.stale
|
|
1716
|
+
? "cached"
|
|
1717
|
+
: "ok";
|
|
1688
1718
|
this.#providerDiscoveryStates.set(options.providerId, {
|
|
1689
1719
|
provider: options.providerId,
|
|
1690
|
-
status
|
|
1720
|
+
status,
|
|
1691
1721
|
optional: false,
|
|
1692
|
-
stale: result.stale,
|
|
1693
|
-
fetchedAt: result.stale ? previous?.fetchedAt : Date.now(),
|
|
1722
|
+
stale: result.stale || status !== "ok",
|
|
1723
|
+
fetchedAt: discoveryError || result.stale ? previous?.fetchedAt : Date.now(),
|
|
1724
|
+
checkedAt: strategy === "offline" ? previous?.checkedAt : Date.now(),
|
|
1694
1725
|
error: discoveryError,
|
|
1695
1726
|
models: models.map(model => model.id),
|
|
1696
1727
|
});
|
|
@@ -1711,6 +1742,7 @@ export class ModelRegistry {
|
|
|
1711
1742
|
optional: false,
|
|
1712
1743
|
stale: true,
|
|
1713
1744
|
fetchedAt: retained?.fetchedAt,
|
|
1745
|
+
checkedAt: Date.now(),
|
|
1714
1746
|
models: retained?.models ?? [],
|
|
1715
1747
|
error: failureReason,
|
|
1716
1748
|
});
|
|
@@ -2283,7 +2315,8 @@ export class ModelRegistry {
|
|
|
2283
2315
|
...this.#configuredProviderIds,
|
|
2284
2316
|
...this.#discoverableProviders
|
|
2285
2317
|
.filter(
|
|
2286
|
-
provider =>
|
|
2318
|
+
provider =>
|
|
2319
|
+
!provider.optional || this.#providerDiscoveryStates.get(provider.provider)?.status === "ok",
|
|
2287
2320
|
)
|
|
2288
2321
|
.map(provider => provider.provider),
|
|
2289
2322
|
...this.#models.filter(model => this.authStorage.hasAuth(model.provider)).map(model => model.provider),
|
|
@@ -2309,12 +2342,25 @@ export class ModelRegistry {
|
|
|
2309
2342
|
.map(([groupProvider]) => this.#providerDiscoveryStates.get(groupProvider))
|
|
2310
2343
|
.find(Boolean)
|
|
2311
2344
|
: undefined);
|
|
2312
|
-
const
|
|
2313
|
-
|
|
2314
|
-
|
|
2345
|
+
const explicitConfiguration = this.#configuredProviderIds.has(provider);
|
|
2346
|
+
const detected = discovery?.status === "ok";
|
|
2347
|
+
const observedCredentialSource =
|
|
2348
|
+
this.authStorage.getCredentialSource(provider) ?? this.#lastCredentialSources.get(provider);
|
|
2349
|
+
const configured =
|
|
2350
|
+
explicitConfiguration || (observedCredentialSource !== undefined && observedCredentialSource !== "keyless");
|
|
2351
|
+
const optionalImplicitProvider = discovery?.optional === true && !explicitConfiguration;
|
|
2352
|
+
const credentialSource: ProviderCredentialSource | undefined =
|
|
2353
|
+
this.#keylessProviders.has(provider) && (explicitConfiguration || detected)
|
|
2354
|
+
? "keyless"
|
|
2355
|
+
: observedCredentialSource === "keyless"
|
|
2356
|
+
? undefined
|
|
2357
|
+
: observedCredentialSource;
|
|
2315
2358
|
const catalogFreshness = discovery?.stale ? "stale" : discovery?.status === "ok" ? "fresh" : "none";
|
|
2359
|
+
const localCredentialFailure = getProviderLocalCredentialFailure(provider);
|
|
2316
2360
|
let status: ProviderAccessStatus;
|
|
2317
|
-
if (
|
|
2361
|
+
if (localCredentialFailure) status = "reauth-required";
|
|
2362
|
+
else if (optionalImplicitProvider && !configured && !detected) status = "unconfigured";
|
|
2363
|
+
else if (!credentialSource && !detected) status = "unconfigured";
|
|
2318
2364
|
else if (discovery?.status === "checking") status = "checking";
|
|
2319
2365
|
else if (discovery?.status === "unauthenticated") status = "reauth-required";
|
|
2320
2366
|
else if (discovery?.status === "unavailable" || discovery?.status === "cached") status = "unreachable";
|
|
@@ -2322,11 +2368,12 @@ export class ModelRegistry {
|
|
|
2322
2368
|
else status = "configured-unverified";
|
|
2323
2369
|
return {
|
|
2324
2370
|
provider,
|
|
2371
|
+
configured,
|
|
2325
2372
|
credentialSource,
|
|
2326
2373
|
status,
|
|
2327
2374
|
catalogFreshness,
|
|
2328
|
-
failureReason: sanitizeProviderFailure(discovery?.error),
|
|
2329
|
-
|
|
2375
|
+
failureReason: localCredentialFailure ?? sanitizeProviderFailure(discovery?.error),
|
|
2376
|
+
lastCheckedAt: localCredentialFailure ? Date.now() : discovery?.checkedAt,
|
|
2330
2377
|
selectable: (status === "connected" || status === "configured-unverified") && !discovery?.stale,
|
|
2331
2378
|
};
|
|
2332
2379
|
}
|
|
@@ -2569,7 +2616,7 @@ export interface ProviderConfigInput {
|
|
|
2569
2616
|
oauth?: {
|
|
2570
2617
|
name: string;
|
|
2571
2618
|
login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials | string>;
|
|
2572
|
-
refreshToken?(credentials: OAuthCredentials): Promise<OAuthCredentials>;
|
|
2619
|
+
refreshToken?(credentials: OAuthCredentials, signal: AbortSignal): Promise<OAuthCredentials>;
|
|
2573
2620
|
getApiKey?(credentials: OAuthCredentials): string;
|
|
2574
2621
|
modifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];
|
|
2575
2622
|
};
|
|
@@ -168,7 +168,9 @@ export type CanonicalModelRegistry = Partial<
|
|
|
168
168
|
Pick<ModelRegistry, "resolveCanonicalModel" | "getCanonicalVariants" | "getCanonicalId">
|
|
169
169
|
>;
|
|
170
170
|
export type ModelLookupRegistry = Pick<ModelRegistry, "getAvailable"> & Partial<CanonicalModelRegistry>;
|
|
171
|
-
type CliModelRegistry = Pick<ModelRegistry, "getAll"> &
|
|
171
|
+
type CliModelRegistry = Pick<ModelRegistry, "getAll"> &
|
|
172
|
+
Partial<Pick<ModelRegistry, "getAvailable" | "getProviderAccessState">> &
|
|
173
|
+
Partial<CanonicalModelRegistry>;
|
|
172
174
|
type InitialModelRegistry = Pick<ModelRegistry, "getAvailable" | "find">;
|
|
173
175
|
type RestorableModelRegistry = Pick<ModelRegistry, "getAvailable" | "find" | "getApiKey">;
|
|
174
176
|
|
|
@@ -898,6 +900,13 @@ export interface ResolveCliModelResult {
|
|
|
898
900
|
thinkingLevel?: ThinkingLevel;
|
|
899
901
|
warning: string | undefined;
|
|
900
902
|
error: string | undefined;
|
|
903
|
+
/** Unknown bare selectors may resolve after extensions register models. */
|
|
904
|
+
deferToExtensions?: boolean;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function formatAmbiguousCliModel(pattern: string, models: readonly Model<Api>[]): string {
|
|
908
|
+
const choices = [...new Set(models.map(formatModelString))].sort();
|
|
909
|
+
return `Model "${pattern}" is ambiguous. Use a qualified selector: ${choices.join(", ")}.`;
|
|
901
910
|
}
|
|
902
911
|
|
|
903
912
|
/**
|
|
@@ -915,8 +924,11 @@ export function resolveCliModel(options: {
|
|
|
915
924
|
return { model: undefined, selector: undefined, warning: undefined, error: undefined };
|
|
916
925
|
}
|
|
917
926
|
|
|
918
|
-
const
|
|
919
|
-
|
|
927
|
+
const allModels = modelRegistry.getAll();
|
|
928
|
+
const availableModels = (modelRegistry.getAvailable?.() ?? allModels).filter(
|
|
929
|
+
model => modelRegistry.getProviderAccessState?.(model.provider).selectable !== false,
|
|
930
|
+
);
|
|
931
|
+
if (allModels.length === 0) {
|
|
920
932
|
return {
|
|
921
933
|
model: undefined,
|
|
922
934
|
selector: undefined,
|
|
@@ -926,7 +938,7 @@ export function resolveCliModel(options: {
|
|
|
926
938
|
}
|
|
927
939
|
|
|
928
940
|
const providerMap = new Map<string, string>();
|
|
929
|
-
for (const model of
|
|
941
|
+
for (const model of allModels) {
|
|
930
942
|
providerMap.set(model.provider.toLowerCase(), model.provider);
|
|
931
943
|
}
|
|
932
944
|
|
|
@@ -943,6 +955,80 @@ export function resolveCliModel(options: {
|
|
|
943
955
|
const trimmedModel = cliModel.trim();
|
|
944
956
|
if (!provider) {
|
|
945
957
|
const lower = trimmedModel.toLowerCase();
|
|
958
|
+
const lastColonIndex = trimmedModel.lastIndexOf(":");
|
|
959
|
+
const thinkingSuffix =
|
|
960
|
+
lastColonIndex === -1 ? undefined : parseThinkingLevel(trimmedModel.slice(lastColonIndex + 1));
|
|
961
|
+
const barePattern = thinkingSuffix ? trimmedModel.slice(0, lastColonIndex) : trimmedModel;
|
|
962
|
+
if (!barePattern.includes("/")) {
|
|
963
|
+
const exactUsable = availableModels.filter(model => model.id.toLowerCase() === barePattern.toLowerCase());
|
|
964
|
+
const canonicalUsable =
|
|
965
|
+
modelRegistry
|
|
966
|
+
.getCanonicalVariants?.(barePattern, { availableOnly: true, candidates: availableModels })
|
|
967
|
+
.map(variant => variant.model) ?? [];
|
|
968
|
+
const usableMatches = [
|
|
969
|
+
...new Map([...exactUsable, ...canonicalUsable].map(model => [formatModelString(model), model])).values(),
|
|
970
|
+
];
|
|
971
|
+
if (usableMatches.length > 1) {
|
|
972
|
+
return {
|
|
973
|
+
model: undefined,
|
|
974
|
+
selector: undefined,
|
|
975
|
+
thinkingLevel: thinkingSuffix,
|
|
976
|
+
warning: undefined,
|
|
977
|
+
error: formatAmbiguousCliModel(barePattern, usableMatches),
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
if (usableMatches.length === 1) {
|
|
981
|
+
return {
|
|
982
|
+
model: usableMatches[0],
|
|
983
|
+
selector: formatModelString(usableMatches[0]),
|
|
984
|
+
thinkingLevel: thinkingSuffix,
|
|
985
|
+
warning: undefined,
|
|
986
|
+
error: undefined,
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
const knownMatches = allModels.filter(model => model.id.toLowerCase() === barePattern.toLowerCase());
|
|
990
|
+
if (knownMatches.length > 0) {
|
|
991
|
+
return {
|
|
992
|
+
model: undefined,
|
|
993
|
+
selector: undefined,
|
|
994
|
+
thinkingLevel: thinkingSuffix,
|
|
995
|
+
warning: undefined,
|
|
996
|
+
error: `Model "${barePattern}" is unavailable. Configure or sign in to one of: ${[
|
|
997
|
+
...new Set(knownMatches.map(formatModelString)),
|
|
998
|
+
]
|
|
999
|
+
.sort()
|
|
1000
|
+
.join(", ")}.`,
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const usableProviders = [...new Set(availableModels.map(model => model.provider))];
|
|
1005
|
+
const fuzzyUsable = usableProviders.flatMap(providerId => {
|
|
1006
|
+
const providerModels = availableModels.filter(model => model.provider === providerId);
|
|
1007
|
+
const match = parseModelPattern(barePattern, providerModels, preferences, {
|
|
1008
|
+
allowInvalidThinkingSelectorFallback: false,
|
|
1009
|
+
modelRegistry,
|
|
1010
|
+
}).model;
|
|
1011
|
+
return match ? [match] : [];
|
|
1012
|
+
});
|
|
1013
|
+
if (fuzzyUsable.length > 1) {
|
|
1014
|
+
return {
|
|
1015
|
+
model: undefined,
|
|
1016
|
+
selector: undefined,
|
|
1017
|
+
thinkingLevel: thinkingSuffix,
|
|
1018
|
+
warning: undefined,
|
|
1019
|
+
error: formatAmbiguousCliModel(barePattern, fuzzyUsable),
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
if (fuzzyUsable.length === 1) {
|
|
1023
|
+
return {
|
|
1024
|
+
model: fuzzyUsable[0],
|
|
1025
|
+
selector: formatModelString(fuzzyUsable[0]),
|
|
1026
|
+
thinkingLevel: thinkingSuffix,
|
|
1027
|
+
warning: undefined,
|
|
1028
|
+
error: undefined,
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
946
1032
|
// When input has provider/id format (e.g. "zai/glm-5"), prefer decomposed
|
|
947
1033
|
// provider+id match over flat id match. Without this, a model with id
|
|
948
1034
|
// "zai/glm-5" on provider "vercel-ai-gateway" wins over provider "zai"
|
|
@@ -955,7 +1041,10 @@ export function resolveCliModel(options: {
|
|
|
955
1041
|
exact = resolveProviderModelReference(prefix, suffix, availableModels);
|
|
956
1042
|
}
|
|
957
1043
|
if (!exact && !trimmedModel.includes(":")) {
|
|
958
|
-
const canonicalMatch = modelRegistry.resolveCanonicalModel?.(trimmedModel, {
|
|
1044
|
+
const canonicalMatch = modelRegistry.resolveCanonicalModel?.(trimmedModel, {
|
|
1045
|
+
availableOnly: true,
|
|
1046
|
+
candidates: availableModels,
|
|
1047
|
+
});
|
|
959
1048
|
if (canonicalMatch) {
|
|
960
1049
|
return {
|
|
961
1050
|
model: canonicalMatch,
|
|
@@ -1022,12 +1111,23 @@ export function resolveCliModel(options: {
|
|
|
1022
1111
|
|
|
1023
1112
|
if (!model) {
|
|
1024
1113
|
const display = provider ? `${provider}/${pattern}` : cliModel;
|
|
1114
|
+
const knownProviderModel = provider
|
|
1115
|
+
? parseModelPattern(
|
|
1116
|
+
pattern,
|
|
1117
|
+
allModels.filter(model => model.provider === provider),
|
|
1118
|
+
preferences,
|
|
1119
|
+
{ allowInvalidThinkingSelectorFallback: false, modelRegistry },
|
|
1120
|
+
).model
|
|
1121
|
+
: undefined;
|
|
1025
1122
|
return {
|
|
1026
1123
|
model: undefined,
|
|
1027
1124
|
selector: undefined,
|
|
1028
1125
|
thinkingLevel: undefined,
|
|
1029
1126
|
warning,
|
|
1030
|
-
error:
|
|
1127
|
+
error: knownProviderModel
|
|
1128
|
+
? `Model "${display}" is unavailable. Configure or sign in to provider "${provider}".`
|
|
1129
|
+
: `Model "${display}" not found. Use --list-models to see available models.`,
|
|
1130
|
+
deferToExtensions: !provider && !display.includes("/"),
|
|
1031
1131
|
};
|
|
1032
1132
|
}
|
|
1033
1133
|
|
|
@@ -1245,7 +1245,7 @@ export interface ProviderConfig {
|
|
|
1245
1245
|
/** Run the provider login flow and return credentials (or a plain API key) to persist. */
|
|
1246
1246
|
login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials | string>;
|
|
1247
1247
|
/** Refresh expired credentials. */
|
|
1248
|
-
refreshToken?(credentials: OAuthCredentials): Promise<OAuthCredentials>;
|
|
1248
|
+
refreshToken?(credentials: OAuthCredentials, signal: AbortSignal): Promise<OAuthCredentials>;
|
|
1249
1249
|
/** Convert credentials to an API key string for requests. */
|
|
1250
1250
|
getApiKey?(credentials: OAuthCredentials): string;
|
|
1251
1251
|
/** Optional model rewrite hook for credential-aware routing (e.g., enterprise URLs). */
|
|
@@ -17,17 +17,17 @@ export interface BuildInfo {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
export const BUILD_INFO: BuildInfo = {
|
|
20
|
-
"version": "21.21.
|
|
21
|
-
"commit": "
|
|
22
|
-
"shortCommit": "
|
|
20
|
+
"version": "21.21.3",
|
|
21
|
+
"commit": "7e54131642306d980389560cbdf1a0edb9fc9493",
|
|
22
|
+
"shortCommit": "7e54131",
|
|
23
23
|
"branch": "main",
|
|
24
|
-
"tag": "v21.21.
|
|
25
|
-
"commitDate": "2026-09-
|
|
26
|
-
"buildDate": "2026-09-
|
|
24
|
+
"tag": "v21.21.3",
|
|
25
|
+
"commitDate": "2026-09-09T15:46:05+00:00",
|
|
26
|
+
"buildDate": "2026-09-09T16:41:57.008Z",
|
|
27
27
|
"dirty": true,
|
|
28
28
|
"prNumber": "",
|
|
29
29
|
"repoUrl": "https://github.com/f5-sales-demo/xcsh",
|
|
30
30
|
"repoSlug": "f5-sales-demo/xcsh",
|
|
31
|
-
"commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/
|
|
32
|
-
"releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.21.
|
|
31
|
+
"commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/7e54131642306d980389560cbdf1a0edb9fc9493",
|
|
32
|
+
"releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.21.3"
|
|
33
33
|
};
|
|
@@ -28,7 +28,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
|
|
|
28
28
|
"en/automate-extend/skills.mdx": "---\ntitle: \"Create and load skills\"\ndescription: \"Package task-specific instructions in `SKILL.md` files at user or project scope.\"\nsidebar:\n order: 5\n label: \"Create and load skills\"\n---\n\nA skill is a directory centered on `SKILL.md`. It tells an agent when and how to perform a bounded kind of work; it is not executable proof by itself.\n\n## Where do skills live?\n\nUse project scope under `.xcsh/skills/` for repository-specific instructions and user scope under the xcsh data directory for personal skills. Project instructions should be reviewable with the repository.\n\n## How do I test one?\n\nStart xcsh with `--skills <GLOB>` to narrow discovery, invoke a prompt that matches the trigger, and inspect the tools and output. Use `--no-skills` to confirm behavior without it.\n",
|
|
29
29
|
"en/configure-secure/environment-reference.mdx": "---\ntitle: \"Environment variable reference\"\ndescription: \"Look up the environment variables that select models, credentials, tenants, execution behavior, storage roots, and diagnostics.\"\nsidebar:\n order: 2\n label: \"Environment variables\"\n---\n\nEnvironment variables carry credentials and process-scoped overrides. Settings files and command flags keep their documented precedence; a similarly named variable is not automatically supported. Provider adapters read their own vendor key names, which the adapter defines rather than this list.\n\n## Which variables configure models, providers, and search?\n\n| Variable | Controls |\n| --- | --- |\n| `PI_SMOL_MODEL` | Default model for the lightweight role, equivalent to `--smol` |\n| `PI_SLOW_MODEL` | Default model for the reasoning role, equivalent to `--slow` |\n| `PI_PLAN_MODEL` | Default model for the planning role, equivalent to `--plan` |\n| `XCSH_LOCALE` | Interface locale, ahead of `PI_LOCALE` and `LANG` |\n\nA flag beats the variable: `--smol` overrides `PI_SMOL_MODEL` for that invocation. Model selection stays a model-registry decision, so a name these variables set must still resolve through `xcsh --list-models <PROVIDER>`.\n\n## Which variables address an F5 Distributed Cloud tenant?\n\n| Variable | Controls |\n| --- | --- |\n| `XCSH_API_URL` | Tenant application programming interface (API) endpoint when no named context is active |\n| `XCSH_API_TOKEN` | Tenant API credential for that endpoint |\n| `XCSH_TENANT` | Tenant identifier reported in context status |\n| `XCSH_CONTEXT_NAME` | Name of the context the session binds to |\n| `XCSH_NAMESPACE` | Namespace applied when a command does not pass `-n` |\n| `F5XC_NAMESPACE` | Namespace source recorded in resource operation records |\n\nTreat every value in this group as a secret. Supply them through the runtime environment or a named context, never through a committed file or a command argument that reaches shell history.\n\n## Which variables configure Python, shell, and tool execution?\n\n| Variable | Controls |\n| --- | --- |\n| `PI_PYTHON_GATEWAY_URL` | Endpoint the Python tool sends code to |\n| `PI_PYTHON_GATEWAY_TOKEN` | Credential for that gateway |\n| `PI_PYTHON_SKIP_CHECK` | Skips the gateway warm-up probe |\n| `PI_SHELL_PREFIX` | Command prefix wrapped around shell tool invocations |\n| `PI_BASH_NO_LOGIN` | Runs the shell without `-l` |\n| `PI_NO_PTY` | Disables pseudo-terminal (PTY) execution, equivalent to `--no-pty` |\n| `PI_EDIT_VARIANT` | Selects the edit tool implementation and rejects an unknown value |\n\nShell execution inherits the launched process environment, subject to the sandbox and command policy. Restrict dependencies, working directory, and credentials at the process boundary rather than in the prompt.\n\n## Which variables configure storage, runtime, and diagnostics?\n\n| Variable | Controls |\n| --- | --- |\n| `PI_CODING_AGENT_DIR` | Primary agent data root, including session storage |\n| `PI_CONFIG_DIR` | Configuration root directory name, `.xcsh` by default |\n| `PI_PACKAGE_DIR` | Packaged asset directory the runtime resolves against |\n| `PI_SESSION_FILE` | Session file a child process attaches to |\n| `PI_NATIVE_VARIANT` | Hardware variant the native addon loader prefers |\n| `PI_CACHE_RETENTION` | Cache retention policy, `short` by default |\n| `PI_NO_TITLE` | Disables title auto-generation, equivalent to `--no-title` |\n| `PI_NOTIFICATIONS` | Desktop notification behavior |\n| `PI_DEBUG_STARTUP` | Startup phase diagnostics |\n| `PI_TIMING` | Phase timing output |\n| `PI_TUI_DEBUG` | Terminal user interface (TUI) rendering diagnostics |\n\nProject configuration stays under `.xcsh/` even when `PI_CODING_AGENT_DIR` moves the user root. Never print a credential-bearing variable into a diagnostic receipt; name the variable and state whether it was set.\n",
|
|
30
30
|
"en/configure-secure/index.mdx": "---\ntitle: \"Configure and secure\"\ndescription: \"Control settings, providers, credentials, networking, secrets, sandboxing, and runtime boundaries.\"\nsidebar:\n order: 0\n label: \"Overview\"\n---\n\nConfiguration controls provider routing, settings precedence, filesystem access, and credential handling.\n\n## What should I configure first?\n\n1. Inspect [settings precedence and file locations](./settings-files/).\n2. Look up any [environment variable](./environment-reference/) the deployment sets.\n3. Choose a [provider and model route](./providers-routing/).\n4. Apply [secret handling and the filesystem boundary](./secrets-obfuscation/).\n5. Set the [sandbox boundaries](./sandbox-boundaries/) that enforce those decisions.\n\nStart with defaults; add project configuration only when collaborators need the same behavior.\n",
|
|
31
|
-
"en/configure-secure/providers-routing.mdx": "---\ntitle: \"Configure providers and model routing\"\ndescription: \"Select models directly or map default, smol, slow, and plan roles.\"\nsidebar:\n order: 3\n label: \"Configure providers and model routing\"\n---\n\nxcsh resolves a requested model against available providers and credentials. A provider-qualified model name is the most explicit route.\n\n## How do I confirm a route?\n\nRun `xcsh --list-models <PROVIDER>`, then pass one returned name to `--model`. Environment keys and supported subscription sessions authenticate providers; never store tokens in committed settings.\n\n## How do I select a model in a conversation?\n\nOpen `/model`. Tab and Shift+Tab browse providers; typing searches across them. The active conversation model and saved role badges are shown separately. Configured providers remain visible when discovery is empty, unavailable, or requires authentication. Use Ctrl+R to refresh the current provider or Ctrl+L to open login.\n\nChoose a model with Enter, then choose its scope:\n\n- **Use in this conversation** is preselected. It changes this session, including resume, without changing saved role assignments.\n- **Save as default** changes the current conversation and the default for future sessions.\n- **Assign to role** saves Default, Fast/SMOL, Thorough/SLOW, Plan, or another existing role. Roles other than Default leave the current conversation unchanged.\n\nChoose a reasoning level supported by that exact model and press Enter to confirm. Inherit displays the provider default; an existing supported reasoning selection is preselected. Escape backs out without applying an unfinished choice. Failed writes are reported before badges show success.\n\nA manual conversation choice remains in effect under automatic routing. Entering planning mode uses the Plan assignment; exiting restores the prior conversation model and reasoning. Explicit `--models` scopes still limit the picker.\n\n## Where does LiteLLM fit?\n\nLiteLLM is an optional provider proxy installed or checked with `xcsh setup litellm`. Its base uniform resource locator (URL) and credential belong in the runtime environment. Successful text Responses support does not imply Realtime or audio support; test the exact endpoint your workflow uses.\n\n## How do I test licensed Vertex locally?\n\n`bun run dev` and local coding-agent binary builds load the licensed Vertex OAuth client pair automatically. Explicit `XCSH_VERTEX_OAUTH_CLIENT_ID` and `XCSH_VERTEX_OAUTH_CLIENT_SECRET` build inputs take precedence; supply both together.\n\nFor local UAT, the first launch can recover the embedded client pair from an installed official xcsh binary\nand retain it in `$XDG_CONFIG_HOME/xcsh/vertex-build.json` (default `~/.config/xcsh/vertex-build.json`). The\nfile is outside the checkout, shared by local sessions and worktrees for the same operating-system user, and\ncreated with owner-only permissions. Each worktree needs this development/build launcher to load it\nautomatically. Later launches reuse it even if the installed binary changes.\n`XCSH_VERTEX_OAUTH_CREDENTIALS_FILE` selects another private local file containing `clientId` and\n`clientSecret` fields.\n\nThe source-runtime preload keeps the pair in process memory; local compiled candidates embed it. Do not copy\nthis file or its values into source control, logs, or UAT reports. CI does not read or recover workstation\ncredentials: official release builds continue to receive the pair through GitHub secrets. Unit tests use\nfixture credentials; the live provider smoke script uses the same local preload as development UAT.\n",
|
|
31
|
+
"en/configure-secure/providers-routing.mdx": "---\ntitle: \"Configure providers and model routing\"\ndescription: \"Select models directly or map default, smol, slow, and plan roles.\"\nsidebar:\n order: 3\n label: \"Configure providers and model routing\"\n---\n\nxcsh resolves a requested model against available providers and credentials. A provider-qualified model name is the most explicit route.\n\n## How do I confirm a route?\n\nRun `xcsh --list-models <PROVIDER>`, then pass one returned name to `--model`. Environment keys and supported subscription sessions authenticate providers; never store tokens in committed settings.\n\n## How do I select a model in a conversation?\n\nOpen `/model`. Tab and Shift+Tab browse providers; typing searches across them. The active conversation model and saved role badges are shown separately. Configured providers remain visible when discovery is empty, unavailable, or requires authentication. Use Ctrl+R to refresh the current provider or Ctrl+L to open login.\n\nChoose a model with Enter, then choose its scope:\n\n- **Use in this conversation** is preselected. It changes this session, including resume, without changing saved role assignments.\n- **Save as default** changes the current conversation and the default for future sessions.\n- **Assign to role** saves Default, Fast/SMOL, Thorough/SLOW, Plan, or another existing role. Roles other than Default leave the current conversation unchanged.\n\nChoose a reasoning level supported by that exact model and press Enter to confirm. Inherit displays the provider default; an existing supported reasoning selection is preselected. Escape backs out without applying an unfinished choice. Failed writes are reported before badges show success.\n\nA manual conversation choice remains in effect under automatic routing. Entering planning mode uses the Plan assignment; exiting restores the prior conversation model and reasoning. Explicit `--models` scopes still limit the picker.\n\nOpen `/login` to see providers that are configured, credential-backed, allowlisted, active, or freshly detected. Optional local runtimes do not appear merely because xcsh attempted an automatic probe. Choose `Add provider…` to search the complete built-in catalog.\n\nProvider rows use human status labels. Press Right on a row to inspect its credential source, last verification, sanitized failure reason, model visibility, and any grouped routes. `/logout` lists only providers with stored credentials that xcsh can remove; environment and configuration credentials are not presented as removable.\n\nProvider grouping in `models.yml` is also used by the management view:\n\n```yaml\nproviders:\n litellm:\n picker:\n groupId: litellm\n groupLabel: LiteLLM\n sectionLabel: OpenAI\n modelAllowlist:\n - gpt-5.6-sol\n - gpt-5.6-terra\n - gpt-5.6-luna\n anthropic:\n picker:\n groupId: litellm\n groupLabel: LiteLLM\n sectionLabel: Anthropic\n modelAllowlist:\n - claude-opus-5\n - claude-sonnet-5\n - claude-haiku-4-5\n```\n\n`modelProviderAllowlist` is a settings key that limits normal `/model` visibility. An empty list means no picker restriction; it does not make every built-in provider relevant in `/login`. Explicit provider-qualified command-line selection and direct `/login <provider>` remain available.\n\n```bash\nxcsh config set modelProviderAllowlist '[\"litellm\", \"anthropic\"]'\nxcsh config set modelProviderOrder '[\"litellm\", \"anthropic\", \"google-vertex\"]'\n```\n\nFor command-line selection, qualify the provider whenever several usable providers expose the same model ID. A bare `--model` value succeeds only when one usable provider matches; otherwise xcsh prints the qualified choices and exits nonzero in noninteractive mode.\n\n## Where does LiteLLM fit?\n\nLiteLLM is an optional provider proxy installed or checked with `xcsh setup litellm`. Its base uniform resource locator (URL) and credential belong in the runtime environment. Successful text Responses support does not imply Realtime or audio support; test the exact endpoint your workflow uses.\n\n## How do I test licensed Vertex locally?\n\n`bun run dev` and local coding-agent binary builds load the licensed Vertex OAuth client pair automatically. Explicit `XCSH_VERTEX_OAUTH_CLIENT_ID` and `XCSH_VERTEX_OAUTH_CLIENT_SECRET` build inputs take precedence; supply both together.\n\nFor local UAT, the first launch can recover the embedded client pair from an installed official xcsh binary\nand retain it in `$XDG_CONFIG_HOME/xcsh/vertex-build.json` (default `~/.config/xcsh/vertex-build.json`). The\nfile is outside the checkout, shared by local sessions and worktrees for the same operating-system user, and\ncreated with owner-only permissions. Each worktree needs this development/build launcher to load it\nautomatically. Later launches reuse it even if the installed binary changes.\n`XCSH_VERTEX_OAUTH_CREDENTIALS_FILE` selects another private local file containing `clientId` and\n`clientSecret` fields.\n\nThe source-runtime preload keeps the pair in process memory; local compiled candidates embed it. Do not copy\nthis file or its values into source control, logs, or UAT reports. CI does not read or recover workstation\ncredentials: official release builds continue to receive the pair through GitHub secrets. Unit tests use\nfixture credentials; the live provider smoke script uses the same local preload as development UAT.\n",
|
|
32
32
|
"en/configure-secure/sandbox-boundaries.mdx": "---\ntitle: \"Set sandbox boundaries\"\ndescription: \"Constrain filesystem, shell, native, browser, and extension effects at the layer that enforces them.\"\nsidebar:\n order: 5\n label: \"Sandbox boundaries\"\n---\n\nA model instruction is not a sandbox. Enforcement belongs to the tool, host process, container, operating system, or remote service that performs the action.\n\n## How do I restrict the exposed tool set?\n\nStart with `--no-tools` or an explicit `--tools` allow-list when a run needs only conversation. Disable Model Context Protocol (MCP) and extensions separately because they can register additional capabilities. Review custom tool and hook code with the same care as any locally executed module.\n\n## How do I constrain files and processes?\n\nFilesystem-aware tools resolve paths against their configured workspace boundary. The Bash runtime applies its sandbox and output limits before returning a result; large output may spill to an artifact instead of remaining inline. Containers add process and filesystem isolation, but mounted credentials and sockets still cross that boundary.\n\n## Where does remote authority differ from local authority?\n\nBrowser, editor, Office, and remote-service integrations enforce different permission models. Confirm the active host, account, context, namespace, and target immediately before a mutation. A successful read proves connectivity, not authorization for a write.\n",
|
|
33
33
|
"en/configure-secure/secrets-obfuscation.mdx": "---\ntitle: \"Resolve secrets safely\"\ndescription: \"Reference sensitive values without placing plaintext credentials in prompts, manifests, logs, or commits.\"\nsidebar:\n order: 4\n label: \"Resolve secrets safely\"\n---\n\nKeep provider keys and F5 Distributed Cloud contexts outside prompts, session exports, logs, and committed files. Pass secrets through supported environment or protected runtime files.\n\n## How does obfuscation work?\n\nWhen secret obfuscation is enabled, values declared in the protected `secrets.yml` source are resolved at runtime and replaced in observable text before it is retained or rendered. Environment values take their documented precedence over file-backed values.\n\nObfuscation reduces accidental disclosure in supported paths; it is not encryption for a compromised process or an excuse to place secrets in prompts.\n\n## How does the filesystem boundary work?\n\nxcsh discovers a task root and guards access outside it. Add an explicit path with `--allow-path`; use `--allow-home` only when the home directory is intentionally the task root. `--no-sandbox` removes that guard and should be reserved for a controlled diagnostic.\n\n## How do I inspect the boundary?\n\nRun `xcsh sandbox check`, then start a read-only session with the smallest required `--allow-path` set. A sandbox boundary limits file discovery; it does not replace operating-system permissions or tool review.\n",
|
|
34
34
|
"en/configure-secure/settings-files.mdx": "---\ntitle: \"Understand settings precedence\"\ndescription: \"Predict which user, project, environment, and command-line value xcsh resolves.\"\nsidebar:\n order: 1\n label: \"Understand settings precedence\"\n---\n\nProject settings apply to one repository; user settings apply across projects; command flags override both for one invocation. Use `xcsh config list --json` to inspect effective values.\n\n## How is configuration resolved?\n\nDiscovery collects fixed user, project, environment, and command-line sources, normalizes each through the schema-backed configuration wrapper, then resolves values by explicit priority. Capability-specific discovery uses the same roots but owns its own merge and deduplication rules. Native `.xcsh` providers participate through the documented provider interface, not an implicit recursive scan.\n\n## Where are settings stored?\n\nRun `xcsh config path` instead of assuming a platform path. Project data uses `.xcsh/`, including `settings.json`, `mcp.json`, contexts, skills, agents, extensions, tools, hooks, commands, and `XCSH.md`. Primary user data lives under the xcsh agent directory; `PI_CODING_AGENT_DIR` can override that location.\n\n## How do I change one value?\n\n```bash\nxcsh config get <KEY>\nxcsh config set <KEY> <VALUE>\nxcsh config reset <KEY>\n```\n\nUse environment variables for credentials and ephemeral process configuration. Do not copy an entire old settings file when only one key is needed.\n",
|
package/src/main.ts
CHANGED
|
@@ -446,7 +446,7 @@ async function buildSessionOptions(
|
|
|
446
446
|
process.stderr.write(`${chalk.yellow(`Warning: ${resolved.warning}`)}\n`);
|
|
447
447
|
}
|
|
448
448
|
if (resolved.error) {
|
|
449
|
-
if (
|
|
449
|
+
if (resolved.deferToExtensions) {
|
|
450
450
|
// Model not found in built-in registry — defer resolution to after extensions load
|
|
451
451
|
// (extensions may register additional providers/models via registerProvider)
|
|
452
452
|
options.modelPattern = parsed.model;
|
package/src/mcp/manager.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import * as path from "node:path";
|
|
8
8
|
import * as url from "node:url";
|
|
9
|
+
import { isDefinitiveOAuthFailure } from "@f5-sales-demo/pi-ai";
|
|
9
10
|
import { logger } from "@f5-sales-demo/pi-utils";
|
|
10
11
|
import type { TSchema } from "@sinclair/typebox";
|
|
11
12
|
import type { SourceMeta } from "../capability/types";
|
|
@@ -593,8 +594,8 @@ export class MCPManager {
|
|
|
593
594
|
/**
|
|
594
595
|
* Resolve auth and shell-command substitutions in config before connecting.
|
|
595
596
|
*/
|
|
596
|
-
async prepareConfig(config: MCPServerConfig): Promise<MCPServerConfig> {
|
|
597
|
-
return this.#resolveAuthConfig(config);
|
|
597
|
+
async prepareConfig(config: MCPServerConfig, forceRefresh = false): Promise<MCPServerConfig> {
|
|
598
|
+
return this.#resolveAuthConfig(config, forceRefresh);
|
|
598
599
|
}
|
|
599
600
|
|
|
600
601
|
/**
|
|
@@ -1071,15 +1072,32 @@ export class MCPManager {
|
|
|
1071
1072
|
forceRefresh || (credential.expires && Date.now() >= credential.expires - REFRESH_BUFFER_MS);
|
|
1072
1073
|
if (shouldRefresh && credential.refresh && auth.tokenUrl) {
|
|
1073
1074
|
try {
|
|
1074
|
-
const
|
|
1075
|
-
|
|
1076
|
-
credential.
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1075
|
+
const row = this.#authStorage
|
|
1076
|
+
.listStoredCredentials(credentialId)
|
|
1077
|
+
.find(entry => entry.credential.type === "oauth");
|
|
1078
|
+
if (row?.credential.type === "oauth") {
|
|
1079
|
+
const outcome = await this.#authStorage.refreshStoredOAuthCredential(credentialId, {
|
|
1080
|
+
credentialId: row.id,
|
|
1081
|
+
observedCredential: credential,
|
|
1082
|
+
credentialFromRow: current => current,
|
|
1083
|
+
forceRefresh,
|
|
1084
|
+
refreshSkewMs: REFRESH_BUFFER_MS,
|
|
1085
|
+
canRefresh: current => Boolean(current.refresh && auth.tokenUrl),
|
|
1086
|
+
refresh: (current, signal) =>
|
|
1087
|
+
refreshMCPOAuthToken(
|
|
1088
|
+
auth.tokenUrl!,
|
|
1089
|
+
current.refresh,
|
|
1090
|
+
auth.clientId,
|
|
1091
|
+
auth.clientSecret,
|
|
1092
|
+
signal,
|
|
1093
|
+
),
|
|
1094
|
+
isDefinitiveFailure: isDefinitiveOAuthFailure,
|
|
1095
|
+
disabledCause: error =>
|
|
1096
|
+
`oauth refresh failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1097
|
+
keepCredentialOnRefreshFailure: true,
|
|
1098
|
+
});
|
|
1099
|
+
credential = outcome.credential;
|
|
1100
|
+
}
|
|
1083
1101
|
} catch (refreshError) {
|
|
1084
1102
|
logger.warn("MCP OAuth refresh failed, using existing token", {
|
|
1085
1103
|
credentialId,
|
|
@@ -1088,22 +1106,24 @@ export class MCPManager {
|
|
|
1088
1106
|
}
|
|
1089
1107
|
}
|
|
1090
1108
|
|
|
1091
|
-
if (
|
|
1092
|
-
resolved
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1109
|
+
if (credential) {
|
|
1110
|
+
if (resolved.type === "http" || resolved.type === "sse") {
|
|
1111
|
+
resolved = {
|
|
1112
|
+
...resolved,
|
|
1113
|
+
headers: {
|
|
1114
|
+
...resolved.headers,
|
|
1115
|
+
Authorization: `Bearer ${credential.access}`,
|
|
1116
|
+
},
|
|
1117
|
+
};
|
|
1118
|
+
} else {
|
|
1119
|
+
resolved = {
|
|
1120
|
+
...resolved,
|
|
1121
|
+
env: {
|
|
1122
|
+
...resolved.env,
|
|
1123
|
+
OAUTH_ACCESS_TOKEN: credential.access,
|
|
1124
|
+
},
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1107
1127
|
}
|
|
1108
1128
|
}
|
|
1109
1129
|
} catch (error) {
|
package/src/mcp/oauth-flow.ts
CHANGED
|
@@ -352,8 +352,9 @@ export class MCPOAuthFlow extends OAuthCallbackFlow {
|
|
|
352
352
|
export async function refreshMCPOAuthToken(
|
|
353
353
|
tokenUrl: string,
|
|
354
354
|
refreshToken: string,
|
|
355
|
-
clientId
|
|
356
|
-
clientSecret
|
|
355
|
+
clientId: string | undefined,
|
|
356
|
+
clientSecret: string | undefined,
|
|
357
|
+
signal: AbortSignal,
|
|
357
358
|
): Promise<OAuthCredentials> {
|
|
358
359
|
const params = new URLSearchParams({
|
|
359
360
|
grant_type: "refresh_token",
|
|
@@ -366,11 +367,21 @@ export async function refreshMCPOAuthToken(
|
|
|
366
367
|
method: "POST",
|
|
367
368
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
368
369
|
body: params.toString(),
|
|
370
|
+
signal,
|
|
369
371
|
});
|
|
370
372
|
|
|
371
373
|
if (!response.ok) {
|
|
372
|
-
|
|
373
|
-
|
|
374
|
+
let payload: unknown;
|
|
375
|
+
try {
|
|
376
|
+
payload = await response.json();
|
|
377
|
+
} catch {
|
|
378
|
+
payload = undefined;
|
|
379
|
+
}
|
|
380
|
+
const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : undefined;
|
|
381
|
+
const rawCode = (record as { error?: unknown } | undefined)?.error;
|
|
382
|
+
const code =
|
|
383
|
+
typeof rawCode === "string" && /^[a-z][a-z0-9_.-]{0,63}$/i.test(rawCode.trim()) ? rawCode.trim() : undefined;
|
|
384
|
+
throw new Error(`MCP OAuth refresh failed (HTTP ${response.status}${code ? `; error=${code}` : ""})`);
|
|
374
385
|
}
|
|
375
386
|
|
|
376
387
|
const data = (await response.json()) as {
|