UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 8.41 kB
import{n as sanitizeTerminalText}from"./safe-text-B_QTgn0s.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{n as formatConfigIssueLines}from"./issue-format-CeCSO2Ku.mjs";import{r as enablePluginWithCapabilityConsent}from"./enable-DLQhpAs1.mjs";import{s as loadManifestMetadataSnapshot}from"./manifest-contract-eligibility-BFn2JM5T.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import{r as replaceConfigFile}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import{r as resolveManifestProviderAuthChoice}from"./provider-auth-choices-Ca4qv7bL.mjs";import{t as ClawHubRequestError}from"./clawhub-client-BqChQ9oR.mjs";import{r as resolveProviderInstallCatalogEntry}from"./provider-install-catalog-W08jhjF8.mjs";import{r as promptYesNo}from"./prompt-BGeJBE18.mjs";import{i as hasAvailableAuthForProvider}from"./model-auth-C99Q9Dp8.mjs";import{t as createPluginCapabilityConsentPrompter}from"./plugin-capability-consent-CNNJbvR9.mjs";import{a as repairModelSelectionRuntimePlugins}from"./runtime-plugin-install-B9zy32i-.mjs";import{t as applyAuthChoiceLoadedPluginProvider}from"./provider-auth-choice-CTnmwi8x.mjs";import{t as createClackPrompter}from"./clack-prompter-CkhFfk2k.mjs";import{f as upsertCanonicalModelConfigEntry,t as applyDefaultModelPrimaryUpdate,u as updateConfig}from"./shared-Sc7lnGKV.mjs";import{t as normalizeAlias}from"./alias-name-Boa_uxyO.mjs";import{t as fetchClawHubPromotion}from"./clawhub-promotions-Bdm6-CpZ.mjs"; //!src/commands/promos/claim.ts function resolvePromotionModelTarget(e,t){const n=e.provider??``;const r=`${n}/`;if(!t.startsWith(r)||t.length<=r.length)throw new Error(`Promotion "${e.slug}" lists model "${t}" outside its provider "${n}"; refusing to configure it.`);return{provider:n,model:t.slice(r.length)}}async function fetchLivePromotion(e){try{return await fetchClawHubPromotion({slug:e})}catch(t){if(t instanceof ClawHubRequestError&&t.status===404)throw new Error(`Promotion "${e}" was not found or is not live. See ${formatCliCommand(`openclaw promos list`)}.`,{cause:t});throw t}}function requireLiveWindow(e){const t=Date.now();if(t>e.endsAt)throw new Error(`Promotion "${e.slug}" ended on ${new Date(e.endsAt).toLocaleDateString()}.`);if(t<e.startsAt||!e.active)throw new Error(`Promotion "${e.slug}" is not live yet.`)}function promotionClaimContract(e){return JSON.stringify({slug:e.slug,startsAt:e.startsAt,endsAt:e.endsAt,provider:e.provider??null,authChoiceId:e.authChoiceId??null,pluginNames:[...e.pluginNames??[]].toSorted(),models:e.models.map(e=>({modelRef:e.modelRef,alias:e.alias??null,suggestedDefault:Boolean(e.suggestedDefault)}))})}function resolveAuthChoice(e,t,n){const r=e.authChoiceId?.trim();if(!r)return;const i=resolveManifestProviderAuthChoice(r,{config:n,includeUntrustedWorkspacePlugins:false});const a=i?void 0:resolveProviderInstallCatalogEntry(r,{config:n,includeUntrustedWorkspacePlugins:false});const o=i??a;if(!o)throw new Error(`Promotion "${e.slug}" requires auth choice "${r}", which this OpenClaw version does not know. Update OpenClaw and retry.`);if(o.providerId!==t)throw new Error(`Promotion "${e.slug}" declares provider "${t}" but its auth choice belongs to "${o.providerId}"; refusing to configure it.`);let s=[];if(i){const e=i.pluginId;const t=loadManifestMetadataSnapshot({config:n});s=[...new Set(t.manifestRegistry.plugins.filter(t=>t.id===e).map(e=>e.packageName?.trim()).filter(e=>Boolean(e)))]}else if(a){const e=a.installSource?.npm?.expectedPackageName??a.installSource?.npm?.packageName;s=[...new Set([e,a.installSource?.clawhub?.packageName].filter(e=>Boolean(e)))]}return{entry:o,installed:Boolean(i),packageNames:s}}async function readValidConfigWriteSnapshot(){const e=await readConfigFileSnapshotForWrite();const{snapshot:t}=e;if(!t.valid){const e=formatConfigIssueLines(t.issues,`-`).join(` `);throw new Error(`Invalid config at ${t.path}\n${e}`)}return e}async function ensureProviderAuth(e){const{promotion:t,provider:n,authChoice:r,prepared:i,opts:a,runtime:o}=e;const{snapshot:s,writeOptions:c}=i;const l=r?.entry;const u=s.runtimeConfig??s.config;const d=a.apiKey?.trim();if(!d&&(r?.installed??true)&&await hasAvailableAuthForProvider({provider:n,cfg:u})){o.log(`Using your existing ${n} credentials.`);return}if(!l)throw new Error(`No credentials configured for provider "${n}". Add one with ${formatCliCommand(`openclaw models auth add`)} and retry.`);if(t.signupUrl)o.log(`Get a free key for this promotion: ${sanitizeTerminalText(t.signupUrl)}`);if(d&&!l.optionKey)throw new Error(`Auth choice "${l.choiceId}" does not accept --api-key; run without it to authenticate interactively.`);const f=await applyAuthChoiceLoadedPluginProvider({authChoice:l.choiceId,config:structuredClone(s.sourceConfig??s.config),prompter:createClackPrompter(),runtime:o,setDefaultModel:false,opts:d&&l.optionKey?{[l.optionKey]:d}:void 0});if(!f||f.retrySelection||!await hasAvailableAuthForProvider({provider:n,cfg:f.config}))throw new Error(`Authentication for "${n}" was not completed; nothing was changed.`);await replaceConfigFile({sourceConfig:f.config,baseHash:s.hash,writeOptions:c})}async function promosClaimCommand(e,t,n){const r=e.trim().toLowerCase();if(!r)throw new Error(`Promotion slug required.`);let i=await fetchLivePromotion(r);requireLiveWindow(i);const a=i.provider?.trim();if(!a)throw new Error(`Promotion "${r}" does not declare a provider; it cannot be claimed from the CLI.`);for(const e of i.models)resolvePromotionModelTarget(i,e.modelRef);const o=await readValidConfigWriteSnapshot();const{snapshot:s}=o;const c=resolveAuthChoice(i,a,s.runtimeConfig??s.config);const l=new Set(c?.packageNames??[]);const u=i.pluginNames?.find(e=>!l.has(e));if(u!==void 0){const e=c?`auth choice "${c.entry.choiceId}"`:`a missing auth choice`;throw new Error(`Promotion "${i.slug}" requires plugin package "${u}", but ${e} does not provide it in this OpenClaw version. Update OpenClaw and retry.`)}await ensureProviderAuth({promotion:i,provider:a,authChoice:c,prepared:o,opts:t,runtime:n});const d=i.models.find(e=>e.suggestedDefault)??i.models[0];let f=Boolean(t.setDefault&&d);if(!f&&d&&process.stdin.isTTY)f=await promptYesNo(`Set ${d.modelRef} as your default model?`,false);const p=await fetchLivePromotion(r);requireLiveWindow(p);if(promotionClaimContract(i)!==promotionClaimContract(p))throw new Error(`Promotion "${i.slug}" changed while the claim was in progress; no promotional models were added. Any provider credentials you just configured were kept. Run ${formatCliCommand(`openclaw promos list`)} and retry.`);i=p;const m=[];const h=[];const g=[];const _=await updateConfig(async(e,t)=>{let n=e;if(c){const e=await enablePluginWithCapabilityConsent(n,c.entry.pluginId,{onCapabilityConsent:process.stdin.isTTY?createPluginCapabilityConsentPrompter(createClackPrompter()):void 0});if(!e.enabled)throw new Error(`The "${c.entry.pluginId}" plugin is blocked by your plugin policy (${e.reason??`disabled`}); cannot claim this promotion.`);n=e.config}const r={...n.agents?.defaults?.models};for(const e of i.models){const t=resolvePromotionModelTarget(i,e.modelRef);const n=upsertCanonicalModelConfigEntry(r,t);let a;try{a=e.alias?normalizeAlias(e.alias):void 0}catch{g.push(e.alias??``)}if(a&&!r[n]?.alias){const e=a.toLowerCase();if(Object.values(r).some(t=>t.alias?.toLowerCase()===e))h.push(a);else r[n]={...r[n],alias:a}}m.push(n)}let a={...n,agents:{...n.agents,defaults:{...n.agents?.defaults,models:r}}};if(f&&d)a=applyDefaultModelPrimaryUpdate({cfg:a,resolveCfg:t.runtimeConfig,modelRaw:d.modelRef,field:`model`});return a});if(f&&d){const e=await repairModelSelectionRuntimePlugins({cfg:_,model:d.modelRef});for(const t of e)n.error?.(t)}n.log(`Claimed "${sanitizeTerminalText(i.title)}".`);for(const e of m)n.log(` Added model: ${sanitizeTerminalText(e)}`);for(const e of h)n.log(` Alias "${sanitizeTerminalText(e)}" is already in use; kept your existing alias.`);for(const e of g)n.log(` Alias "${sanitizeTerminalText(e)}" is not a valid model alias; skipped it.`);if(f&&d){n.log(` Default model set to ${sanitizeTerminalText(d.modelRef)}.`);n.log(` Revert anytime with ${formatCliCommand(`openclaw models set <previous-model>`)}.`)}else if(d)n.log(` Try it: ${formatCliCommand(`openclaw models set ${d.modelRef}`)} (promotion ends ${new Date(i.endsAt).toLocaleDateString()}).`)}export{promosClaimCommand};