UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines • 14.1 kB
import{h as resolveDefaultSecretProviderAlias}from"../../ref-contract-CdpCUlb6.mjs";import{a as coerceSecretRef}from"../../types.secrets-UWdyCdE6.mjs";import{t as normalizeOptionalSecretInput}from"../../normalize-secret-input-CEFJUjQX.mjs";import{s as resolveAgentModelPrimaryValue}from"../../model-input-CJnF-FEy.mjs";import{f as listProfilesForProvider}from"../../order-B8e_5ABM.mjs";import{i as ensureAuthProfileStoreAsync}from"../../store-runtime-GNz-2GjY.mjs";import{t as applyAuthProfileConfig}from"../../provider-auth-helpers-5o5rkp5c.mjs";import"../../provider-onboard-hrWz6i98.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import"../../provider-auth-Czspvb3-.mjs";import{r as upsertAuthProfileWithLockCompat}from"../../provider-auth-write-compat-iCHCUMSb.mjs";import{i as resolveRequiredConfiguredSecretRefInputString}from"../../secret-input-runtime-BSybHjM3.mjs";import{a as resolveGithubCopilotDomain,r as normalizeGithubCopilotDomain,t as PUBLIC_GITHUB_COPILOT_DOMAIN}from"../../domain-Bn9uiqna.mjs";import{t as DEFAULT_COPILOT_MODEL}from"../../model-metadata-CIDVwYlG.mjs";import{n as PROVIDER_ID}from"../../models-hnw5ORFF.mjs";import{a as refreshGithubCopilotOAuth,i as parseGithubCopilotApiKey,n as formatGithubCopilotApiKey,r as loginGithubCopilotOAuth,t as buildGithubCopilotAuthDoctorHint}from"../../oauth-BWqU5YzB.mjs";import{t as resolveFirstGithubToken}from"../../auth-B_iKeJvV.mjs";import{t as createGithubCopilotDynamicModelHooks}from"../../dynamic-models-Boy48IU2.mjs";import{t as githubCopilotMemoryEmbeddingProviderAdapter}from"../../embeddings-CcjSpp3I.mjs";import{t as resolveThinkingProfile}from"../../provider-policy-api-DTj4Koi0.mjs";import{n as stripCopilotAssistantThinkingMessages,t as buildGithubCopilotReplayPolicy}from"../../replay-policy--v7G7PmK.mjs";import{n as wrapCopilotSimpleCompletionStream,t as wrapCopilotProviderStream}from"../../stream-D6THibiY.mjs"; //!extensions/github-copilot/index.ts const COPILOT_ENV_VAR=`COPILOT_GITHUB_TOKEN`;const DEFAULT_COPILOT_PROFILE_ID=`github-copilot:github`;const COPILOT_SECRET_STORE_NAME_PREFIX=`GITHUB_COPILOT_TOKEN`;function buildCopilotTokenProfile(e,t){return{profileId:DEFAULT_COPILOT_PROFILE_ID,credential:{type:`token`,provider:PROVIDER_ID,token:t},...e.secretInputMode===`plaintext`?{}:{secretStorage:{kind:`store`,namePrefix:COPILOT_SECRET_STORE_NAME_PREFIX}}}}async function loadGithubCopilotRuntime(){return await import(`./register.runtime.js`)}function resolveExistingCopilotAuthProfile(e){for(const t of e??[]){const{credential:e}=t;if(e.type===`token`&&e.provider===`github-copilot`&&(normalizeOptionalSecretInput(e.token)||coerceSecretRef(e.tokenRef)?.id.trim()))return{...t,credential:e}}return null}async function resolveInteractiveCopilotStarterModel(e){if(e.ctx.credentialOnly)return{};try{const{resolveCopilotStarterModel:t}=await loadGithubCopilotRuntime();return{defaultModel:await t({githubToken:e.githubToken,env:e.ctx.env??process.env,githubDomain:e.githubDomain,config:e.ctx.config})}}catch{return{notes:[`GitHub Copilot authentication succeeded, but no eligible live model could be selected. Choose a model after checking your Copilot plan and organization policy.`]}}}function buildGithubCopilotDomainConfigPatch(e){return{models:{providers:{[PROVIDER_ID]:{params:{githubDomain:e===void 0?void 0:normalizeGithubCopilotDomain(e)}}}}}}function applyGithubCopilotDomainToConfig(e,t,n){const r=t!==PUBLIC_GITHUB_COPILOT_DOMAIN;if(!r&&!(!r&&n!==`github.com`))return e;const i=e.models??{};const a=i.providers??{};const o=a[PROVIDER_ID];const s={};if(o?.params)Object.assign(s,o.params);if(r)s.githubDomain=t;else delete s.githubDomain;const c={...a};if(o)c[PROVIDER_ID]={...o,params:s};else Object.assign(c,{[PROVIDER_ID]:{params:s}});return{...e,models:{...i,providers:c}}}async function runGitHubCopilotNonInteractiveAuth(e){const t=e.opts;const n=normalizeOptionalSecretInput(t?.githubCopilotToken);const r=e.opts.secretInputMode===`ref`;const i=await e.resolveApiKey({provider:PROVIDER_ID,...r?{}:{flagValue:n},flagName:`--github-copilot-token`,envVar:COPILOT_ENV_VAR,envVarName:COPILOT_ENV_VAR,allowProfile:false,required:false});if(!i&&r&&n)throw new Error(`--github-copilot-token cannot be used with --secret-input-mode ref unless COPILOT_GITHUB_TOKEN is set in env. Set COPILOT_GITHUB_TOKEN and omit --github-copilot-token, or use --secret-input-mode plaintext.`);let a=DEFAULT_COPILOT_PROFILE_ID;let o=i?.key??``;if(i){if(e.opts.secretInputMode===`ref`&&i.source===`env`&&!i.envVarName)throw new Error([`--secret-input-mode ref requires an explicit environment variable for provider "github-copilot".`,`Set COPILOT_GITHUB_TOKEN in env and retry, or use --secret-input-mode plaintext.`].join(` `))}else{const t=await ensureAuthProfileStoreAsync(e.agentDir,{allowKeychainPrompt:false});const n=listProfilesForProvider(t,PROVIDER_ID).find(e=>{const n=t.profiles[e];if(n?.type!==`token`)return false;return Boolean(normalizeOptionalSecretInput(n.token)||coerceSecretRef(n.tokenRef)?.id.trim())});if(!n)throw new Error(`Missing --github-copilot-token (or COPILOT_GITHUB_TOKEN env var) for --auth-choice github-copilot.`);a=n;o=(await resolveFirstGithubToken({agentDir:e.agentDir,config:e.config,env:process.env,profileId:a})).githubToken}const s=resolveGithubCopilotDomain({config:e.config});const c=resolveGithubCopilotDomain({env:{},config:e.config});const l=applyGithubCopilotDomainToConfig(e.config,s,c);let u;if(!resolveAgentModelPrimaryValue(l.agents?.defaults?.model)){const{resolveCopilotStarterModel:e}=await loadGithubCopilotRuntime();u=await e({githubToken:o,env:process.env,githubDomain:s,config:l})}else if(i){const{resolveCopilotRuntimeAuth:e}=await loadGithubCopilotRuntime();await e({githubToken:o,env:process.env,githubDomain:s,config:l})}if(i){const t=e.opts.secretInputMode===`ref`&&i.source===`env`;await upsertAuthProfileWithLockCompat({profileId:a,credential:{type:`token`,provider:PROVIDER_ID,...t?{tokenRef:{source:`env`,provider:resolveDefaultSecretProviderAlias(e.baseConfig,`env`,{preferFirstProviderForSource:true}),id:i.envVarName}}:{token:i.key}},agentDir:e.agentDir})}const d=applyAuthProfileConfig(l,{profileId:a,provider:PROVIDER_ID,mode:`token`});if(!u)return d;if(resolveAgentModelPrimaryValue(d.agents?.defaults?.model))return d;const f=d.agents?.defaults;const p=f?.model;const m=typeof p===`object`&&p!==null&&`fallbacks`in p?p.fallbacks:void 0;return{...d,agents:{...d.agents,defaults:{...f,model:{...m?{fallbacks:m}:void 0,primary:u},models:{...f?.models,[u]:f?.models?.[u]??{}}}}}}var github_copilot_default=definePluginEntry({id:`github-copilot`,name:`GitHub Copilot Provider`,description:`Bundled GitHub Copilot provider plugin`,register(e){const t=createGithubCopilotDynamicModelHooks();async function promptForEnterpriseDomain(e){const t=e.env?.COPILOT_GITHUB_DOMAIN?.trim();if(t){const n=normalizeGithubCopilotDomain(t);await e.prompter.note(`Using the GitHub Enterprise domain from COPILOT_GITHUB_DOMAIN (${n}). Unset it to enter a different domain interactively.`,`GitHub Copilot`);return n}const n=resolveGithubCopilotDomain({env:e.env,config:e.config});const r=await e.prompter.text({message:`GitHub Enterprise domain (data residency)`,placeholder:`your-org.ghe.com`,initialValue:n===`github.com`?``:n,validate:e=>{const t=e.trim();if(!t)return`Enter your GitHub Enterprise domain (for example your-org.ghe.com).`;if(normalizeGithubCopilotDomain(t)===`github.com`&&t.toLowerCase()!==`github.com`){if(t.toLowerCase().endsWith(`.ghe.com`))return`Enter your tenant root (for example your-org.ghe.com), not a service host like api.your-org.ghe.com — service endpoints are derived automatically.`;return`Enter a github.com or *.ghe.com hostname without scheme or path (for example your-org.ghe.com).`}}});return normalizeGithubCopilotDomain(r)}async function runGitHubCopilotDeviceAuth(e,t){const n=normalizeGithubCopilotDomain(t);const r=n!==PUBLIC_GITHUB_COPILOT_DOMAIN;const i=resolveGithubCopilotDomain({env:{},config:e.config});const a=i!==n;const o=r?buildGithubCopilotDomainConfigPatch(n):i!==`github.com`?buildGithubCopilotDomainConfigPatch():void 0;const s=e.opts?.tokenProvider===`github-copilot`?normalizeOptionalSecretInput(e.opts.token):void 0;if(s)return{profiles:[buildCopilotTokenProfile(e,s)],...!e.credentialOnly?{defaultModel:DEFAULT_COPILOT_MODEL}:{},...o?{configPatch:o}:{}};const c=e.credentialOnly?null:resolveExistingCopilotAuthProfile(e.existingProfiles);if(c&&!a){if(!await e.prompter.confirm({message:`GitHub Copilot auth already exists. Re-run login?`,initialValue:false})){e.signal?.throwIfAborted();e.assertCurrent?.();const{profileId:t,credential:r}=c;const i=await resolveRequiredConfiguredSecretRefInputString({config:e.config,env:e.env??process.env,value:r.tokenRef,path:`providers.github-copilot.authProfiles.${t}.tokenRef`});e.signal?.throwIfAborted();e.assertCurrent?.();const a=await resolveInteractiveCopilotStarterModel({ctx:e,githubToken:(i??r.token??``).trim(),githubDomain:n});return{profiles:[c],...a,...o?{configPatch:o}:{}}}}else if(c&&a)await e.prompter.note(r?`Switching to ${n} requires a new tenant login to authorize Copilot for that domain.`:`Switching back to github.com requires a new login to authorize Copilot for the public domain.`,`GitHub Copilot`);await e.prompter.note([r?`This will open a GitHub Enterprise device login (${n}) to authorize Copilot.`:`This will open a GitHub device login to authorize Copilot.`,`Requires an active GitHub Copilot subscription.`].join(` `),`GitHub Copilot`);const{runGitHubCopilotDeviceFlow:l}=await import(`./login.js`);const u=await l({showCode:async({verificationUrl:t,userCode:n,expiresInMs:r})=>{const i=Math.max(1,Math.round(r/6e4));if(e.isRemote)await e.openUrl(t);if(e.prompter.deviceCode){await e.prompter.deviceCode({title:`Authorize GitHub Copilot`,code:n,expiresInMinutes:i,message:`Enter this one-time code to authorize Copilot.`});return}await e.prompter.note([`Open this URL in your browser and enter the code below.`,`URL: <${t}>`,`Code: ${n}`,`Code expires in ${i} minutes. Never share it.`,``,`If a browser does not open automatically after you continue, copy the URL manually.`].join(` `),`Authorize GitHub Copilot`)},...e.isRemote?{}:{openUrl:async t=>{await e.openUrl(t)}},...e.signal?{signal:e.signal}:{},...e.assertCurrent?{assertCurrent:e.assertCurrent}:{}},n);if(u.status===`access_denied`){await e.prompter.note(`GitHub Copilot login was cancelled.`,`GitHub Copilot`);return{profiles:[]}}if(u.status===`expired`){await e.prompter.note(`The GitHub device code expired. Retry login to get a new code.`,`GitHub Copilot`);return{profiles:[]}}const d=await resolveInteractiveCopilotStarterModel({ctx:e,githubToken:u.accessToken,githubDomain:n});const f=e.secretInputMode===`plaintext`;const p=[...d.notes??[],...f?[`Plaintext secret input mode was selected, so the GitHub Copilot token will remain inline in the auth profile and openclaw secrets audit --check will report it.`]:[]];return{profiles:[buildCopilotTokenProfile(e,u.accessToken)],...d.defaultModel?{defaultModel:d.defaultModel}:{},...p.length>0?{notes:p}:{},...o?{configPatch:o}:{}}}async function runGitHubCopilotEnterpriseAuth(e){const t=await promptForEnterpriseDomain(e);if(t===`github.com`){await e.prompter.note(`github.com is the default — use the standard GitHub Copilot login instead of the enterprise (data residency) option.`,`GitHub Copilot`);return{profiles:[]}}return await runGitHubCopilotDeviceAuth(e,t)}e.registerEmbeddingProvider(githubCopilotMemoryEmbeddingProviderAdapter);e.registerProvider({id:PROVIDER_ID,label:`GitHub Copilot`,docsPath:`/providers/models`,envVars:[COPILOT_ENV_VAR],auth:[{id:`device`,label:`GitHub device login`,hint:`Browser device-code flow`,kind:`device_code`,starterModel:DEFAULT_COPILOT_MODEL,run:e=>runGitHubCopilotDeviceAuth(e,PUBLIC_GITHUB_COPILOT_DOMAIN),runNonInteractive:runGitHubCopilotNonInteractiveAuth},{id:`device-enterprise`,label:`GitHub Enterprise device login (data residency)`,hint:`Device-code flow against your *.ghe.com tenant`,kind:`device_code`,run:runGitHubCopilotEnterpriseAuth,wizard:{choiceId:`github-copilot-enterprise`,choiceLabel:`GitHub Copilot (Enterprise / data residency)`,choiceHint:`Device login against your GitHub Enterprise (*.ghe.com) tenant`,methodId:`device-enterprise`,assistantPriority:2,modelSelection:{promptWhenAuthChoiceProvided:true}}}],wizard:{setup:{choiceId:`github-copilot`,choiceLabel:`GitHub Copilot`,choiceHint:`Device login with your GitHub account`,methodId:`device`,assistantPriority:1,modelSelection:{promptWhenAuthChoiceProvided:true}}},catalog:{order:`late`,run:t.runCatalog},prepareDynamicModel:t.prepareDynamicModel,resolveDynamicModel:t.resolveDynamicModel,preferRuntimeResolvedModel:t.preferRuntimeResolvedModel,formatApiKey:formatGithubCopilotApiKey,loginOAuth:loginGithubCopilotOAuth,refreshOAuth:async e=>refreshGithubCopilotOAuth(e),buildAuthDoctorHint:buildGithubCopilotAuthDoctorHint,wrapStreamFn:wrapCopilotProviderStream,wrapSimpleCompletionStreamFn:wrapCopilotSimpleCompletionStream,buildReplayPolicy:buildGithubCopilotReplayPolicy,sanitizeReplayHistoryAsync:e=>e.modelApi===`openai-responses`||e.modelApi===`anthropic-messages`?stripCopilotAssistantThinkingMessages(e.messages):e.messages,resolveThinkingProfile,prepareRuntimeAuthV2:async e=>{const t=parseGithubCopilotApiKey(e.apiKey);const{resolveCopilotRuntimeAuth:n}=await loadGithubCopilotRuntime();const r=await n({githubToken:t.githubToken,env:e.env,githubDomain:resolveGithubCopilotDomain({env:e.env,explicit:t.githubDomain,config:e.config})});return{apiKey:r.apiKey,baseUrl:r.baseUrl,...e.model.headers?{request:{headers:e.model.headers}}:{}}},resolveUsageAuth:async e=>await e.resolveOAuthToken(),fetchUsageSnapshot:async e=>{const t=parseGithubCopilotApiKey(e.token);const{fetchCopilotUsage:n}=await loadGithubCopilotRuntime();return await n(t.githubToken,e.timeoutMs,e.fetchFn,resolveGithubCopilotDomain({env:e.env,explicit:t.githubDomain,config:e.config}))}})}});export{github_copilot_default as default};