@humain/humain-code 0.8.2 → 0.8.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 +11 -0
- package/dist/bundle/chunks/{chunk-EFY2QPVP.js → chunk-2XD7TLKB.js} +4 -4
- package/dist/bundle/chunks/{chunk-U4EAJPMO.js → chunk-4GB7A76U.js} +39 -35
- package/dist/bundle/chunks/{chunk-PJXBU6CR.js → chunk-7LSTTCSC.js} +111 -89
- package/dist/bundle/chunks/{chunk-H2B3WLIM.js → chunk-AW24RHGJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-3PJ7NPWN.js → chunk-B3ZLWVDA.js} +1 -1
- package/dist/bundle/chunks/{chunk-H7UPU2SH.js → chunk-MUN4ZZZP.js} +706 -703
- package/dist/bundle/chunks/chunk-S2US54IU.js +37 -0
- package/dist/bundle/chunks/{chunk-G2QMON4O.js → chunk-VSXVZVBE.js} +3 -3
- package/dist/bundle/chunks/{chunk-JQBZUFH7.js → chunk-ZAHVC5V2.js} +175 -164
- package/dist/bundle/chunks/{compat-ELBUCH6U.js → compat-4ILE5BEC.js} +1 -1
- package/dist/bundle/chunks/{dist-QSYDYE3Y.js → dist-I6CI3CG5.js} +6 -6
- package/dist/bundle/chunks/{dist-NERIS6SW.js → dist-NXHRL2KY.js} +1 -1
- package/dist/bundle/chunks/{entry-SRYLSS5P.js → entry-6XDR2IDE.js} +1 -1
- package/dist/bundle/chunks/{flow-implementer-3P3BHQ7E.js → flow-implementer-XOP4MG5X.js} +3 -3
- package/dist/bundle/chunks/{inprocess-3PDJKE5F.js → inprocess-MBKFGDM2.js} +4 -4
- package/dist/bundle/chunks/{interactive-mode-SDUO5OLD.js → interactive-mode-3322RQEH.js} +2 -2
- package/dist/bundle/chunks/{virtual-modules-IU5KWB2C.js → virtual-modules-47MGUPYN.js} +3 -3
- package/dist/bundle/cli-runtime.js +3 -3
- package/dist/bundle/index.js +6 -6
- package/dist/bundle/rpc-entry.js +3 -3
- package/dist/coordination/adapter/delivery.d.ts +27 -0
- package/dist/coordination/adapter/delivery.d.ts.map +1 -1
- package/dist/coordination/adapter/delivery.js +164 -4
- package/dist/coordination/adapter/delivery.js.map +1 -1
- package/dist/coordination/adapter/index.d.ts.map +1 -1
- package/dist/coordination/adapter/index.js +31 -5
- package/dist/coordination/adapter/index.js.map +1 -1
- package/dist/coordination/adapter/presence.d.ts +5 -0
- package/dist/coordination/adapter/presence.d.ts.map +1 -1
- package/dist/coordination/adapter/presence.js +25 -3
- package/dist/coordination/adapter/presence.js.map +1 -1
- package/dist/coordination/adapter/question-routing.d.ts +7 -0
- package/dist/coordination/adapter/question-routing.d.ts.map +1 -0
- package/dist/coordination/adapter/question-routing.js +40 -0
- package/dist/coordination/adapter/question-routing.js.map +1 -0
- package/dist/coordination/adapter/receipts.d.ts +7 -0
- package/dist/coordination/adapter/receipts.d.ts.map +1 -1
- package/dist/coordination/adapter/receipts.js +25 -2
- package/dist/coordination/adapter/receipts.js.map +1 -1
- package/dist/coordination/adapter/tool.d.ts +19 -3
- package/dist/coordination/adapter/tool.d.ts.map +1 -1
- package/dist/coordination/adapter/tool.js +93 -19
- package/dist/coordination/adapter/tool.js.map +1 -1
- package/dist/coordination/client/client.d.ts +2 -2
- package/dist/coordination/client/client.d.ts.map +1 -1
- package/dist/coordination/client/client.js +4 -0
- package/dist/coordination/client/client.js.map +1 -1
- package/dist/coordination/transport/protocol.d.ts.map +1 -1
- package/dist/coordination/transport/protocol.js +23 -0
- package/dist/coordination/transport/protocol.js.map +1 -1
- package/dist/coordination/transport/types.d.ts +11 -1
- package/dist/coordination/transport/types.d.ts.map +1 -1
- package/dist/coordination/transport/types.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +14 -8
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +14 -0
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +166 -14
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/run-outcome.d.ts +1 -1
- package/dist/core/run-outcome.d.ts.map +1 -1
- package/dist/core/run-outcome.js +2 -2
- package/dist/core/run-outcome.js.map +1 -1
- package/dist/core/run-preflight.d.ts.map +1 -1
- package/dist/core/run-preflight.js +15 -8
- package/dist/core/run-preflight.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -0
- package/dist/main.js.map +1 -1
- package/docs/cli.md +6 -0
- package/docs/coordination.md +16 -4
- package/docs/environment-variables.md +2 -1
- package/docs/providers.md +5 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/chunk-UEW6TUSP.js +0 -36
|
@@ -2,7 +2,7 @@ import { createRequire as __piCreateRequire } from "node:module"; const require
|
|
|
2
2
|
import{CURRENT_SESSION_VERSION,SessionManager,applyExifOrientation,buildSessionProjection,convertToLlm,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,formatDimensionNote,getControlDeniedEntryIds,getDefaultSessionDir,getLatestCompactionEntry,includeSummaryUsageEntries,loadPhoton,projectContextEntry,resizeImage,sessionEntryToContextMessages}from"./chunk-GPLWWO5Q.js";import{VisualLinePreview,addUsageToTotals,combineUsage,createOutputFileStream,createToolDefinitionFromAgentTool,
|
|
3
3
|
createUsageTotals,formatReadLineRange,getSessionUsage,getSummaryUsage,getTextOutput,invalidArgText,normalizeDisplayText,renderToolPath,replaceTabs,shortenPath,splitIncompleteAnsiSuffix,startToolTimer,str as str2,stripAnsi,toolTimerText,wrapToolDefinition}from"./chunk-3E37CJCE.js";import{AccountSourceReplacementError,AuthStorage,FileAuthStorageBackend,InMemoryAuthStorageBackend,McpServerRegistry,ReadOnlyAuthStorage,createToolNameMatcher,getAccountCredentialStore,getConfigValueEnvVarNames,isCommandConfigValue,
|
|
4
4
|
isConfigValueConfigured,isMcpToolName,mcpNamespace,operationSignal,raceWithAbortSignal,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,validateMcpServerConfig}from"./chunk-JWOPWHVH.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,sliceHead,truncateHead,truncateLine,truncateTail}from"./chunk-3HVHETMU.js";import{ANTHROPIC_MODEL_CATALOG,MODEL_CATALOGS,anthropicMessagesApi,builtinProviders,completeSimple,getApiProvider,getBuiltinModelDataGeneratedAt,getModelListing,
|
|
5
|
-
openAICompletionsApi,openAIResponsesApi,personalizeOpenRouterCatalog,piMessagesApi,radiusProvider,resetApiProviders,setModelListing,streamSimple}from"./chunk-
|
|
5
|
+
openAICompletionsApi,openAIResponsesApi,personalizeOpenRouterCatalog,piMessagesApi,radiusProvider,resetApiProviders,setModelListing,streamSimple}from"./chunk-MUN4ZZZP.js";import{BUILTIN_PATH_PREFIX,DEFAULT_TOOL_NAMES,DefaultPackageManager,Minimatch,SettingsManager,applyToolModifiers,createSourceInfo,createSyntheticSourceInfo,getResourcePathKey,getSyntheticPathSource,getToolListError,hcodeDisplayName,isSyntheticPath,isToolModifier,minimatch,readPiManifest,require_ignore,require_semver,resolveHcodeEnvironment}from"./chunk-T2ZGMEMV.js";
|
|
6
6
|
import{require_proper_lockfile}from"./chunk-F6ZAYLU2.js";import{CodeHighlighter,FS_WATCH_RETRY_DELAY_MS,closeWatcher,getLanguageFromPath,getMarkdownTheme,getResolvedThemeColors,getThemeByName,getThemeExportColors,getThemeInstance,highlightCode,keyHint,keyText,loadThemeFromPath,theme,watchWithErrorHandler}from"./chunk-E4VUW4RI.js";import{source_default}from"./chunk-XQRYOCHA.js";import{Box,Container,Markdown,Spacer,Text,detectCapabilities,getCapabilities,getImageDimensions,getTerminalColorMode,
|
|
7
7
|
ne,sanitizeTerminalText,setImageTranscoder,startsWithText,visibleWidth}from"./chunk-M5TVWJ5T.js";import{HttpTraceIngestTransport,QuarantineGateError,TRACE_ENV,acquireTraceSpoolLock,buildChildTraceEnv,createTraceRedactor,ensureTraceSpoolDirs,fsyncDir,isSpoolQuarantinedInProcess,isTraceId,lazyValidator,mintTraceId,parseTraceSpoolBinding,readTraceProducerConfig,readTraceStateFile,readTraceStream,readTraceStreamBinding,sanitizeForTerminal,spawnCommand,systemTraceCredentialProbes,takeTraceIngestCredentials,
|
|
8
8
|
traceCaptureDisabledReason,traceCursorPath,traceStreamPrefixChain,verifyTraceStreamOffset,withQuarantineGate,writeTraceFileAtomic,writeTraceStreamBinding}from"./chunk-R2KD2HFT.js";import{DH_MAX_EXTERNAL_IDS,DH_OUTCOMES,DH_PAYLOAD_SCHEMA_IDS,DhContractError,DhExternalIdSchema,assertDhCapabilityAction,assertDhControlDelivery,assertDhControlStatusEvidence,assertDhOriginDelegation,assertDhProducerAudience,assertDhRetryAdmission,checkDhControlFence,dhCanonicalText,dhControlFrameBytes,dhDigestInput,
|
|
@@ -956,66 +956,77 @@ message.stopReason!=="length"&&message.stopReason!=="toolUse")return;let credits
|
|
|
956
956
|
expires=="number"&&Number.isFinite(value.expires)}function isApiKeyCredential(value){return isRecord2(value)&&value.type==="api_key"&&typeof value.key=="string"&&value.key.trim().length>0&&(value.env===void 0||isRecord2(value.env)&&Object.values(value.env).every(entry=>typeof entry=="string"))}function parsePoolData(content2){if(!content2||content2.trim()==="")return{};let parsed;try{parsed=JSON.parse(stripBom(content2))}catch{throw new Error("not valid JSON")}if(!isRecord2(parsed))throw new Error(
|
|
957
957
|
"expected an object");if(Object.hasOwn(parsed,"version")){if(parsed.version!==2||!isRecord2(parsed.providers))throw new Error("unsupported account document");parsed=parsed.providers}if(!isRecord2(parsed))throw new Error("expected provider pools");for(let pool of Object.values(parsed)){if(!isRecord2(pool)||typeof pool.active!="string"||!isRecord2(pool.accounts)||pool.nextLocalAccountId!==void 0&&(typeof pool.nextLocalAccountId!="number"||!Number.isSafeInteger(pool.nextLocalAccountId)||pool.nextLocalAccountId<
|
|
958
958
|
1))throw new Error("invalid provider pool");if(pool.returnTo!==void 0&&(!isRecord2(pool.returnTo)||typeof pool.returnTo.preferredKey!="string"||typeof pool.returnTo.fromKey!="string"||!Object.hasOwn(pool.accounts,pool.returnTo.preferredKey)||!Object.hasOwn(pool.accounts,pool.returnTo.fromKey)))throw new Error("invalid preferred account state");for(let[key,account]of Object.entries(pool.accounts)){if(!isRecord2(account)||!isOAuthCredential(account.credential)&&!isApiKeyCredential(account.credential)||
|
|
959
|
-
account.quotaFailures!==void 0&&(typeof account.quotaFailures!="number"||!Number.isSafeInteger(account.quotaFailures)||account.quotaFailures<0||account.quotaFailures>31)||account.cooldownRevision!==void 0&&(typeof account.cooldownRevision!="number"||!Number.isSafeInteger(account.cooldownRevision)||account.cooldownRevision<0)||account.exhaustedUntil!==void 0&&(typeof account.exhaustedUntil!="number"||!Number.isFinite(account.exhaustedUntil)))throw new Error("invalid account entry");if(
|
|
960
|
-
key,account.credential))throw new Error("invalid account key");isSafeIdentityValue(account.label,account.credential)||(account.label=key)}}return parsed}function toPoolAccount(pool,key){let stored=pool.accounts[key];return{key,label:stored.label,credential:structuredClone(stored.credential),
|
|
961
|
-
key}}function toAccount(pool,key){let account=toPoolAccount(pool,key);if(account.credential.type!=="oauth")throw new Error("Expected OAuth account");return account}function toPoolAccounts(pool){return Object.
|
|
962
|
-
|
|
963
|
-
map(account=>account.exhaustedUntil).filter(value=>value!==void 0&&value>nowMs);return resetTimes.length>0?Math.min(...resetTimes):void 0}function keysAfterActive(pool){
|
|
964
|
-
aborted?forward():source2.addEventListener("abort",forward,{once:!0}),{options:{...options,signal:controller.signal},detach:()=>source2.removeEventListener("abort",
|
|
965
|
-
getAccountCredentialStore(credentials),this.storage=storage,this.location=location,this.resolvers=new Map(resolvers),this.backupPath=backupPath}static create(credentials,poolPath=join3(
|
|
966
|
-
"oauth-accounts (in-memory)")}async settled(){for(;this.pendingWrites.size>0;)await Promise.all(this.pendingWrites)}registerIdentityResolver(providerId,resolver){this.
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
account.credential
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
expires
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
return this.run(providerId,"
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
if(
|
|
1012
|
-
|
|
1013
|
-
credential)
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
959
|
+
account.quotaFailures!==void 0&&(typeof account.quotaFailures!="number"||!Number.isSafeInteger(account.quotaFailures)||account.quotaFailures<0||account.quotaFailures>31)||account.cooldownRevision!==void 0&&(typeof account.cooldownRevision!="number"||!Number.isSafeInteger(account.cooldownRevision)||account.cooldownRevision<0)||account.exhaustedUntil!==void 0&&(typeof account.exhaustedUntil!="number"||!Number.isFinite(account.exhaustedUntil)))throw new Error("invalid account entry");if(account.quarantine!==
|
|
960
|
+
void 0&&(!isRecord2(account.quarantine)||account.quarantine.identity!==void 0&&!isSafeAccountKey(account.quarantine.identity,account.credential)))throw new Error("invalid account quarantine");if(!isSafeAccountKey(key,account.credential))throw new Error("invalid account key");isSafeIdentityValue(account.label,account.credential)||(account.label=key)}}return parsed}function toPoolAccount(pool,key){let stored=pool.accounts[key];return{key,label:stored.label,credential:structuredClone(stored.credential),
|
|
961
|
+
exhaustedUntil:stored.exhaustedUntil,...stored.quotaFailures!==void 0?{quotaFailures:stored.quotaFailures}:{},...stored.cooldownRevision!==void 0?{cooldownRevision:stored.cooldownRevision}:{},...stored.quarantine?{quarantine:structuredClone(stored.quarantine)}:{},active:pool.active===key&&!stored.quarantine}}function toAccount(pool,key){let account=toPoolAccount(pool,key);if(account.credential.type!=="oauth")throw new Error("Expected OAuth account");return account}function toPoolAccounts(pool){return Object.
|
|
962
|
+
keys(pool.accounts).map(key=>toPoolAccount(pool,key))}function toAccounts(pool){return pool?Object.keys(pool.accounts).filter(key=>pool.accounts[key].credential.type==="oauth").map(key=>toAccount(pool,key)):[]}function isOAuthAccountUsable(account,nowMs){return!account.quarantine&&(account.exhaustedUntil===void 0||account.exhaustedUntil<=nowMs)}function getOAuthAccountRemovalSuccessor(accounts,accountKey,nowMs=Date.now()){let index=accounts.findIndex(account=>account.key===accountKey);return[...accounts.
|
|
963
|
+
slice(index+1),...accounts.slice(0,index)].find(account=>isOAuthAccountUsable(account,nowMs))??accounts.find(account=>account.key!==accountKey&&!account.quarantine)}function earliestResetAt(pool,nowMs,includeApiKeys=!1){let resetTimes=Object.values(pool.accounts).filter(account=>includeApiKeys||account.credential.type==="oauth").map(account=>account.exhaustedUntil).filter(value=>value!==void 0&&value>nowMs);return resetTimes.length>0?Math.min(...resetTimes):void 0}function keysAfterActive(pool){
|
|
964
|
+
let keys=Object.keys(pool.accounts),index=keys.indexOf(pool.active);return index===-1?keys:[...keys.slice(index+1),...keys.slice(0,index)]}function linkAbortSignal(options){let source2=options?.signal;if(!source2)return{options,detach:()=>{}};let controller=new AbortController,forward=()=>controller.abort(source2.reason);return source2.aborted?forward():source2.addEventListener("abort",forward,{once:!0}),{options:{...options,signal:controller.signal},detach:()=>source2.removeEventListener("abort",
|
|
965
|
+
forward)}}function sameCredential(a,b){return JSON.stringify(a)===JSON.stringify(b)}var OAuthAccountPool=class _OAuthAccountPool{credentials;pendingWrites=new Set;storage;location;resolvers;cache=new Map;backupPath;error;constructor(credentials,storage,location,resolvers=DEFAULT_OAUTH_ACCOUNT_IDENTITY_RESOLVERS,backupPath){this.credentials=getAccountCredentialStore(credentials),this.storage=storage,this.location=location,this.resolvers=new Map(resolvers),this.backupPath=backupPath}static create(credentials,poolPath=join3(
|
|
966
|
+
getAgentDir(),"oauth-accounts.json")){let normalized=normalizePath(poolPath);return new _OAuthAccountPool(credentials,new FileAuthStorageBackend(normalized),normalized,DEFAULT_OAUTH_ACCOUNT_IDENTITY_RESOLVERS,`${normalized}.v1.bak`)}static inMemory(credentials){return new _OAuthAccountPool(credentials,new InMemoryAuthStorageBackend,"oauth-accounts (in-memory)")}async settled(){for(;this.pendingWrites.size>0;)await Promise.all(this.pendingWrites)}registerIdentityResolver(providerId,resolver){this.
|
|
967
|
+
resolvers.set(providerId,resolver)}isPooled(_providerId){return!0}getAccountKeyForAccessToken(providerId,accessToken){let credential={type:"oauth",access:accessToken,refresh:"",expires:0},cached=this.cache.get(providerId)?.find(account=>!account.quarantine&&account.credential.type==="oauth"&&account.credential.access===accessToken);if(cached)return cached.key;let key=this.resolvers.get(providerId)?.(credential)?.key;return isSafeAccountKey(key,credential)?key:void 0}getAccountIdentity(providerId,credential){
|
|
968
|
+
let token=providerId==="openai-codex"?resolveOpenAICodexAccountIdentity(credential):void 0,owner=this.cache.get(providerId)?.find(account=>account.key===credential.accountKey);if(token&&owner?.credential.type==="oauth"&&resolveOpenAICodexAccountIdentity(owner.credential)?.key!==token.key){let actual=this.cache.get(providerId)?.find(account=>account.credential.type==="oauth"&&resolveOpenAICodexAccountIdentity(account.credential)?.key===token.key);return actual?{key:actual.key,label:actual.label}:
|
|
969
|
+
this.getAccountIdentity(providerId,{...credential,accountKey:void 0})}if(typeof credential.accountKey=="string"&&/^account-[0-9a-f-]{36}$/.test(credential.accountKey)&&isSafeAccountKey(credential.accountKey,credential))return resolveGenericAccountIdentity(credential);let resolved=this.resolvers.get(providerId)?.(credential);return!resolved||!isSafeAccountKey(resolved.key,credential)?resolveGenericAccountIdentity(credential):{key:resolved.key,label:isSafeIdentityValue(resolved.label,credential)?resolved.
|
|
970
|
+
label:resolved.key}}getAccountDescription(providerId,key){let account=this.cache.get(providerId)?.find(entry=>entry.key===key);if(!account)return;let saved=account.credential,upstream=saved.type==="oauth"?(providerId==="openai-codex"?getOpenAICodexTokenIdentity(saved.access)?.accountId:void 0)??saved.accountId:void 0;return isSafeIdentityValue(upstream,saved)?`${account.label} (${upstream})`:account.label}assertCredentialUsable(providerId,credential){let accounts=this.cache.get(providerId),owner=accounts?.
|
|
971
|
+
find(account=>account.key===credential.accountKey);if(owner?.quarantine||!owner&&accounts?.some(account=>account.quarantine&&sameCredential(account.credential,credential)))throw new Error("Account is quarantined; sign in to the matching account again")}bindRefresh(providerId,issued,refreshed){let before=this.loginIdentity(providerId,issued),after=this.loginIdentity(providerId,refreshed);if(before&&after&&before.key!==after.key)throw new Error("OAuth refresh returned a different account or worksp\
|
|
972
|
+
ace");let bound={...refreshed,accountKey:issued.accountKey};for(let field of OAUTH_ACCOUNT_IDENTITY_FIELDS)issued[field]!==void 0&&(field!=="accountLabel"||bound[field]===void 0)&&(bound[field]=issued[field]);return bound}async loadIntegrity(providerId,options){await this.storage.withLockAsync(async content2=>{let data=parsePoolData(content2),pool=Object.hasOwn(data,providerId)?data[providerId]:{active:"",accounts:{}};return this.quarantineCrosslinks(providerId,pool),this.cache.set(providerId,toPoolAccounts(
|
|
973
|
+
pool)),{result:void 0}},options)}quarantineCrosslinks(providerId,pool){for(let[key,account]of Object.entries(pool.accounts)){let saved=account.credential;if(saved.type!=="oauth"||account.quarantine)continue;let token=providerId==="openai-codex"?getOpenAICodexTokenIdentity(saved.access):void 0,wrongStamp=typeof saved.accountKey=="string"&&saved.accountKey!==key&&Object.hasOwn(pool.accounts,saved.accountKey),wrongIdentity=token&&saved.accountId!==void 0&&saved.accountId!==token.accountId&&(typeof saved.
|
|
974
|
+
accountId=="string"&&saved.accountId!==key&&Object.hasOwn(pool.accounts,saved.accountId)||token.accountId!==key&&Object.hasOwn(pool.accounts,token.accountId)),legacyIdentity=providerId==="openai-codex"&&!/^account-[0-9a-f-]{36}$/.test(key)&&!/^local-\d+$/.test(key),canonical=token&&Object.hasOwn(pool.accounts,token.accountId)?pool.accounts[token.accountId].credential:void 0,canonicalOwner=canonical?.type==="oauth"&&getOpenAICodexTokenIdentity(canonical.access)?.accountId===token?.accountId,wrongLegacyOwner=legacyIdentity&&
|
|
975
|
+
token&&key!==token.accountId&&saved.accountKey===key&&canonicalOwner;if(wrongStamp||wrongIdentity||wrongLegacyOwner){let identity=wrongLegacyOwner?key:wrongIdentity&&isSafeAccountKey(saved.accountId,saved)?saved.accountId:this.loginIdentity(providerId,saved)?.key;account.quarantine=identity?{identity}:{}}}}getError(){return this.error}getCachedAccounts(providerId){let cached=this.cache.get(providerId);return cached?cached.filter(account=>account.credential.type==="oauth").map(account=>({...account,
|
|
976
|
+
credential:structuredClone(account.credential)})):void 0}getCachedPoolAccounts(providerId){return this.cache.get(providerId)?.map(account=>({...account,credential:structuredClone(account.credential)}))}getAccountKeyForApiKey(providerId,apiKey){return this.cache.get(providerId)?.find(account=>account.credential.type==="api_key"&&account.credential.key===apiKey)?.key}async list(providerId,options){return await this.run(providerId,"read",options,pool=>toAccounts(pool))??[]}displayAccounts(providerId,accounts){
|
|
977
|
+
let winners=new Map,identities=accounts.map(account=>{if(account.quarantine||account.credential.type!=="oauth")return;let identity=this.loginIdentity(providerId,account.credential)?.key;if(identity===void 0)return;let incumbent=winners.get(identity);return(!incumbent||!incumbent.active&&(account.active||incumbent.credential.type==="oauth"&&account.credential.expires>incumbent.credential.expires))&&winners.set(identity,account),identity}),visible=accounts.filter((account,index)=>identities[index]===
|
|
978
|
+
void 0||winners.get(identities[index])===account);if(providerId!=="anthropic")return visible;let orgLabels=new Set(visible.flatMap(({label,credential})=>credential.type==="oauth"&&credential.organizationId!==void 0&&label.includes(" \xB7 ")?[label.split(" \xB7 ")[0]]:[]));return visible.map(account=>account.credential.type==="oauth"&&account.credential.organizationId===void 0&&orgLabels.has(account.label)?{...account,label:`${account.label} \xB7 Anthropic`}:account)}loginIdentity(providerId,credential){
|
|
979
|
+
if(credential.organizationId!==void 0&&!isSafeIdentityValue(credential.organizationId,credential))return;let identity=this.getAccountIdentity(providerId,{...credential,accountKey:void 0});return providerId!=="openai-codex"||!identity||!isSafeAccountKey(credential.accountId,credential)||resolveOpenAICodexAccountIdentity(credential)?identity:{...identity,key:credential.accountId}}removeExpiredAliases(providerId,pool,key){let survivor=pool.accounts[key]?.credential,now=Date.now();if(pool.accounts[key]?.
|
|
980
|
+
quarantine||survivor?.type!=="oauth"||survivor.expires<=now||!survivor.refresh)return;let identity=this.loginIdentity(providerId,survivor)?.key;if(identity!==void 0)for(let[alias,{credential}]of Object.entries(pool.accounts))alias===key||pool.accounts[alias].quarantine||alias===pool.active||credential.type!=="oauth"||credential.expires>now||credential.refresh!==survivor.refresh||this.loginIdentity(providerId,credential)?.key!==identity||(delete pool.accounts[alias],(pool.returnTo?.preferredKey===
|
|
981
|
+
alias||pool.returnTo?.fromKey===alias)&&delete pool.returnTo)}async getActive(providerId,options){return this.run(providerId,"read",options,pool=>Object.hasOwn(pool.accounts,pool.active)&&!pool.accounts[pool.active].quarantine&&pool.accounts[pool.active].credential.type==="oauth"?toAccount(pool,pool.active):void 0)}async getCurrent(providerId,options){return this.run(providerId,"read",options,(pool,context)=>context.currentKey!==void 0?toAccount(pool,context.currentKey):void 0)}async adoptCurrent(providerId,options){
|
|
982
|
+
return this.run(providerId,"write",options,(pool,context)=>context.currentKey!==void 0?toAccount(pool,context.currentKey):void 0)}async prepareUsageAccount(providerId,key,refresh,options){return this.run(providerId,"write",options,()=>{},void 0,!1,!1,void 0,void 0,!1,{key,refresh,result:value=>value})}async clearExhaustion(providerId,expected,options){return await this.run(providerId,"write",options,(pool,context)=>{if(!Object.hasOwn(pool.accounts,expected.key))return;let account=pool.accounts[expected.
|
|
983
|
+
key];if(!(expected.exhaustedUntil===void 0||!Number.isFinite(expected.exhaustedUntil)||expected.exhaustedUntil<=Date.now()||account.exhaustedUntil!==expected.exhaustedUntil||account.quotaFailures!==expected.quotaFailures||(account.cooldownRevision??0)!==(expected.cooldownRevision??0)||account.cooldownRevision===Number.MAX_SAFE_INTEGER||!sameCredential(account.credential,expected.credential)||context.currentKey===expected.key&&!sameCredential(context.currentCredential,expected.credential)))return delete account.
|
|
984
|
+
exhaustedUntil,delete account.quotaFailures,!0},void 0,!0,!1,void 0,void 0,!0)??!1}async listAccounts(providerId,options){return await this.run(providerId,"read",options,pool=>toPoolAccounts(pool),void 0,!1,!0)??[]}async getCurrentAccount(providerId,options){return this.run(providerId,"read",options,(pool,context)=>context.currentKey?toPoolAccount(pool,context.currentKey):void 0,void 0,!1,!0)}async adoptCurrentAccount(providerId,options){return this.run(providerId,"write",options,(pool,context)=>{
|
|
985
|
+
if(context.currentKey)return this.removeExpiredAliases(providerId,pool,context.currentKey),toPoolAccount(pool,context.currentKey)},void 0,!0,!0)}async addAccount(providerId,credential,options){if(!isOAuthCredential(credential)&&!isApiKeyCredential(credential))throw new Error("Invalid account credential");if(options?.key!==void 0&&!isSafeAccountKey(options.key,credential))throw new Error("Invalid account key");return this.run(providerId,"write",options,(pool,context)=>{if(options?.label!==void 0&&
|
|
986
|
+
![credential,...Object.values(pool.accounts).map(account=>account.credential)].every(entry=>isSafeIdentityValue(options.label,entry)))throw new Error("Invalid account label");let identity=credential.type==="oauth"?this.loginIdentity(providerId,credential):void 0,matches=Object.keys(pool.accounts).filter(key2=>{let entry=pool.accounts[key2],stored=entry.credential;return entry.quarantine?identity!==void 0&&entry.quarantine.identity===identity.key:credential.type==="api_key"?stored.type==="api_key"&&
|
|
987
|
+
stored.key===credential.key:stored.type==="oauth"&&(sameCredential(stored,credential)||identity!==void 0&&this.loginIdentity(providerId,stored)?.key===identity.key)}),matching=matches.includes(pool.active)?pool.active:matches.reduce((best,candidate)=>{let previous=best===void 0?void 0:pool.accounts[best].credential,next=pool.accounts[candidate].credential;return!previous||next.type==="oauth"&&previous.type==="oauth"&&next.expires>previous.expires?candidate:best},void 0);if(credential.type==="api\
|
|
988
|
+
_key"&&options?.key!==void 0&&matching!==void 0&&matching!==options.key)throw new Error("API key already belongs to another account");let organizationKey=providerId==="anthropic"&&credential.type==="oauth"&&credential.organizationId!==void 0?identity?.key:void 0,key=options?.key??matching??organizationKey??`account-${randomUUID4()}`;if(![credential,...Object.values(pool.accounts).map(account=>account.credential)].every(entry=>isSafeAccountKey(key,entry)))throw new Error("Invalid account key");let existing=Object.
|
|
989
|
+
hasOwn(pool.accounts,key)?pool.accounts[key]:void 0;if(existing&&existing.credential.type!==credential.type)throw new Error("Account credential type cannot change");if(existing?.quarantine&&(!identity||!existing.quarantine.identity))throw new Error("Quarantined account identity is unknown; use Add another account");if(existing?.credential.type==="oauth"&&identity!==void 0){let existingIdentity=existing.quarantine?existing.quarantine.identity?{key:existing.quarantine.identity}:void 0:this.loginIdentity(
|
|
990
|
+
providerId,existing.credential);if(existingIdentity!==void 0&&existingIdentity.key!==identity.key)throw new Error("Sign-in returned a different account or workspace. Sign in to the selected account or use Add another account.")}let label=options?.label??existing?.label??identity?.label??`Account ${pool.nextLocalAccountId??Object.keys(pool.accounts).length+1}`;if(![credential,...Object.values(pool.accounts).map(account=>account.credential)].every(entry=>isSafeIdentityValue(label,entry)))throw new Error(
|
|
991
|
+
"Invalid account label");return pool.nextLocalAccountId=(pool.nextLocalAccountId??Object.keys(pool.accounts).length+1)+(existing?0:1),credential.type==="oauth"&&this.removeExpiredAliases(providerId,pool,key),pool.accounts[key]={credential:credential.type==="oauth"?{...structuredClone(credential),accountKey:key}:structuredClone(credential),label,exhaustedUntil:existing?.exhaustedUntil,quotaFailures:existing?.quotaFailures,cooldownRevision:existing?.cooldownRevision},delete pool.returnTo,pool.active=
|
|
992
|
+
key,credential.type==="oauth"&&this.removeExpiredAliases(providerId,pool,key),context.activate=!0,toPoolAccount(pool,key)},void 0,!0,!0)}async setActiveAccount(providerId,accountKey,options){return this.run(providerId,"write",options,(pool,context)=>{if(Object.hasOwn(pool.accounts,accountKey)){if(pool.accounts[accountKey].quarantine)throw new Error("Account is quarantined; sign in to the matching account again");return context.activate=!0,delete pool.returnTo,pool.active=accountKey,toPoolAccount(
|
|
993
|
+
pool,accountKey)}},void 0,!1,!0)}async renameAccount(providerId,accountKey,label,options){return this.run(providerId,"write",options,pool=>{if(Object.hasOwn(pool.accounts,accountKey)){if(!Object.values(pool.accounts).every(account=>isSafeIdentityValue(label,account.credential)))throw new Error("Invalid account label");return pool.accounts[accountKey].label=label,toPoolAccount(pool,accountKey)}},void 0,!1,!0)}async removeAccount(providerId,accountKey,options){return this.removeStored(providerId,accountKey,
|
|
994
|
+
options,!0)}async add(providerId,credential,options){if(options?.key!==void 0&&!isSafeAccountKey(options.key,credential))throw new Error("Invalid OAuth account key");let identity=this.getAccountIdentity(providerId,credential);if(!(providerId==="openai-codex"&&!identity&&options?.key===void 0))return this.run(providerId,"write",options,(pool,context)=>{context.activate=!0;let local=options?.key===void 0&&!identity?nextLocalAccountIdentity(pool):void 0,key=options?.key??identity?.key??local.key,existing=pool.
|
|
995
|
+
accounts[key];if(existing?.quarantine&&(!existing.quarantine.identity||this.loginIdentity(providerId,credential)?.key!==existing.quarantine.identity))throw new Error("Sign-in returned a different account or workspace");return pool.accounts[key]={credential:providerId==="openai-codex"?structuredClone(credential):{...structuredClone(credential),accountKey:key},label:existing?.label??identity?.label??local?.label??key,exhaustedUntil:existing?.exhaustedUntil,quotaFailures:existing?.quotaFailures,cooldownRevision:existing?.
|
|
996
|
+
cooldownRevision},delete pool.returnTo,pool.active=key,toAccount(pool,key)})}async setActive(providerId,accountKey,options){return this.run(providerId,"write",options,(pool,context)=>{if(!(!Object.hasOwn(pool.accounts,accountKey)||pool.accounts[accountKey].credential.type!=="oauth")){if(pool.accounts[accountKey].quarantine)throw new Error("Account is quarantined; sign in to the matching account again");return context.activate=!0,delete pool.returnTo,pool.active=accountKey,toAccount(pool,accountKey)}})}async remove(providerId,accountKey,options){
|
|
997
|
+
return await this.removeStored(providerId,accountKey,options,!1)}async removeStored(providerId,accountKey,options,includeApiKeys){let matched=!1,target=accountKey;return await this.run(providerId,"write",options,(pool,context)=>{let key=target??context.currentKey;if(key===void 0||!Object.hasOwn(pool.accounts,key)||!includeApiKeys&&pool.accounts[key].credential.type!=="oauth"||accountKey===void 0&&context.currentKey!==key)return;matched=!0,target=key;let removed=toPoolAccount(pool,key),wasActive=pool.
|
|
998
|
+
active===key,successor=wasActive?getOAuthAccountRemovalSuccessor(toPoolAccounts(pool).filter(account=>account.credential.type===removed.credential.type),key)?.key:void 0;return(wasActive||pool.returnTo?.preferredKey===key||pool.returnTo?.fromKey===key)&&delete pool.returnTo,delete pool.accounts[key],wasActive&&(pool.active=successor??""),{status:"removed",removed,active:pool.active&&(includeApiKeys||pool.accounts[pool.active].credential.type==="oauth")?toPoolAccount(pool,pool.active):void 0}},void 0,
|
|
999
|
+
!0,includeApiKeys,options?.ifCurrent?{ifCurrent:options.ifCurrent,changed:{status:"changed"}}:void 0)??{status:matched?"changed":"unmatched"}}async failover(providerId,options){return this.failoverStored(providerId,options,!1)}async failoverAccounts(providerId,options){return this.failoverStored(providerId,{...options,trackPreferred:options.trackPreferred??!0},!0)}async failoverStored(providerId,options,includeApiKeys){let{expectedActiveKey,exhaustedUntil,now=Date.now(),skipKeys,trackPreferred,apiKeyFallback,
|
|
1000
|
+
allowApiKeyRotation,markExhausted=!0,candidateKeys,candidateFilter,canActivate,...operationOptions}=options,accounts=pool=>includeApiKeys?toPoolAccounts(pool):toAccounts(pool),activeChanged=(pool,activeKey)=>({switched:!1,reason:"active_changed",active:activeKey!==void 0&&Object.hasOwn(pool.accounts,activeKey)?toPoolAccount(pool,activeKey):void 0,total:accounts(pool).length,earliestResetAt:earliestResetAt(pool,now,includeApiKeys)}),operation=(pool,context)=>{let total=accounts(pool).length;if(context.
|
|
1001
|
+
currentKey!==expectedActiveKey||pool.active!==expectedActiveKey)return activeChanged(pool,context.currentKey);let source2=pool.accounts[expectedActiveKey];trackPreferred&&markExhausted&&(source2.quotaFailures=Math.min(31,(source2.quotaFailures??0)+1));let reset=exhaustedUntil??(trackPreferred?now+Math.min(ACCOUNT_RETURN_MAX_COOLDOWN_MS,ACCOUNT_RETURN_COOLDOWN_MS*2**((source2.quotaFailures??1)-1)):void 0);reset!==void 0&&markExhausted&&(source2.exhaustedUntil=reset,source2.cooldownRevision=Math.min(
|
|
1002
|
+
Number.MAX_SAFE_INTEGER,(source2.cooldownRevision??0)+1));let usable=key=>key!==expectedActiveKey&&!skipKeys?.has(key)&&isOAuthAccountUsable(pool.accounts[key],now),sameType=source2.credential.type==="oauth"||allowApiKeyRotation===!0,ordered=candidateKeys?candidateKeys.filter(key=>Object.hasOwn(pool.accounts,key)):keysAfterActive(pool),candidate=(sameType?ordered.find(key=>pool.accounts[key].credential.type===source2.credential.type&&usable(key)&&(candidateFilter===void 0||candidateFilter(toPoolAccount(
|
|
1003
|
+
pool,expectedActiveKey),toPoolAccount(pool,key)))):void 0)??(source2.credential.type==="oauth"&&apiKeyFallback!==void 0&&Object.hasOwn(pool.accounts,apiKeyFallback)&&pool.accounts[apiKeyFallback].credential.type==="api_key"&&usable(apiKeyFallback)?apiKeyFallback:void 0);return candidate===void 0?{switched:!1,reason:"exhausted",active:toPoolAccount(pool,expectedActiveKey),total,earliestResetAt:earliestResetAt(pool,now,includeApiKeys)}:(pool.accounts[candidate].exhaustedUntil=void 0,trackPreferred&&
|
|
1004
|
+
(pool.returnTo={preferredKey:pool.returnTo?.preferredKey??expectedActiveKey,fromKey:candidate}),pool.active=candidate,{switched:!0,from:toPoolAccount(pool,expectedActiveKey),to:toPoolAccount(pool,candidate),total})};return this.run(providerId,"write",operationOptions,operation,expectedActiveKey,!1,includeApiKeys,void 0,canActivate)}async returnToPreferred(providerId,options){return await this.run(providerId,"write",options,(pool,context)=>{let pending=pool.returnTo;if(!pending)return;if(context.
|
|
1005
|
+
currentKey!==pending.fromKey)return delete pool.returnTo,!1;let preferred=pool.accounts[pending.preferredKey];return!preferred||options?.skipKeys?.has(pending.preferredKey)||!isOAuthAccountUsable(preferred,Date.now())?!1:(pool.active=pending.preferredKey,delete pool.returnTo,toPoolAccount(pool,pool.active))},void 0,!0,!0,void 0,options?.canActivate)||void 0}async activateCreditFallback(providerId,options){let{expectedActiveKey,targetKey:targetKey2,skipKeys,now=Date.now(),canActivate,...operationOptions}=options,
|
|
1006
|
+
activeChanged=(pool,activeKey)=>({outcome:"active_changed",active:activeKey!==void 0&&Object.hasOwn(pool.accounts,activeKey)?toAccount(pool,activeKey):void 0}),operation=(pool,context)=>{if(context.currentKey!==expectedActiveKey||pool.active!==expectedActiveKey)return activeChanged(pool,context.currentKey);let untried=keysAfterActive(pool).find(key=>pool.accounts[key].credential.type==="oauth"&&!skipKeys?.has(key)&&isOAuthAccountUsable(pool.accounts[key],now));return untried!==void 0?(pool.accounts[untried].
|
|
1007
|
+
exhaustedUntil=void 0,pool.active=untried,pool.returnTo&&(pool.returnTo.fromKey=untried),{outcome:"untried",account:toAccount(pool,untried)}):!Object.hasOwn(pool.accounts,targetKey2)||pool.accounts[targetKey2].quarantine||pool.accounts[targetKey2].credential.type!=="oauth"?{outcome:"missing"}:(pool.active=targetKey2,pool.returnTo&&(pool.returnTo.fromKey=targetKey2),{outcome:"credit",account:toAccount(pool,targetKey2)})};return this.run(providerId,"write",operationOptions,operation,expectedActiveKey,
|
|
1008
|
+
!1,!1,void 0,canActivate)}upsertCredential(pool,credential,providerId,activeKey=pool.active,includeApiKeys=!1){if(credential?.type==="api_key"){if(!includeApiKeys||!isApiKeyCredential(credential))return;let apiKey=credential.key,existingKey=Object.keys(pool.accounts).find(key2=>pool.accounts[key2].credential.type==="api_key"&&pool.accounts[key2].credential.key===apiKey),cachedKey=this.cache.get(providerId)?.find(account=>account.credential.type==="api_key"&&account.credential.key===apiKey)?.key,
|
|
1009
|
+
key=existingKey??cachedKey??`account-${randomUUID4()}`,existing2=pool.accounts[key];return pool.accounts[key]={credential:structuredClone(credential),label:existing2?.label??`Account ${Object.keys(pool.accounts).length+1}`,exhaustedUntil:existing2?.exhaustedUntil,quotaFailures:existing2?.quotaFailures,cooldownRevision:existing2?.cooldownRevision},key}if(credential?.type!=="oauth")return;let owner=isSafeAccountKey(credential.accountKey,credential)&&Object.hasOwn(pool.accounts,credential.accountKey)?
|
|
1010
|
+
pool.accounts[credential.accountKey]:void 0;if(owner?.quarantine||!owner&&Object.values(pool.accounts).some(entry=>entry.quarantine&&sameCredential(credential,entry.credential)))return;let tokenIdentity=providerId==="openai-codex"?getOpenAICodexTokenIdentity(credential.access):void 0;tokenIdentity&&(credential.accountId===void 0||owner?.credential.type==="oauth"&&this.loginIdentity(providerId,owner.credential)?.key!==tokenIdentity.accountId)&&(credential={...credential,accountId:tokenIdentity.accountId});
|
|
1011
|
+
let stamped=credential.accountKey;if(isSafeAccountKey(stamped,credential)&&Object.hasOwn(pool.accounts,stamped)){let owner2=pool.accounts[stamped].credential;(owner2.type!=="oauth"||this.loginIdentity(providerId,owner2)?.key!==this.loginIdentity(providerId,credential)?.key)&&(credential={...credential,accountKey:void 0})}let identity=this.getAccountIdentity(providerId,credential),loginId=this.loginIdentity(providerId,credential)?.key,stampedKey=credential.accountKey,matchesLogin=stored=>stored.type===
|
|
1012
|
+
"oauth"&&loginId!==void 0&&this.loginIdentity(providerId,stored)?.key===loginId;if(identity&&isSafeAccountKey(stampedKey,credential)&&Object.hasOwn(pool.accounts,stampedKey)&&matchesLogin(pool.accounts[stampedKey].credential)&&(identity={...identity,key:stampedKey}),identity&&!Object.hasOwn(pool.accounts,identity.key)&&stampedKey===void 0&&(identity={key:(Object.hasOwn(pool.accounts,activeKey)&&matchesLogin(pool.accounts[activeKey].credential)?activeKey:Object.keys(pool.accounts).find(key=>matchesLogin(
|
|
1013
|
+
pool.accounts[key].credential)))??this.cache.get(providerId)?.find(account=>matchesLogin(account.credential))?.key??(includeApiKeys?`account-${randomUUID4()}`:identity.key),label:identity.label}),!identity){if(providerId==="openai-codex")return;let cached=this.cache.get(providerId)?.find(account=>account.credential.type==="oauth"&&sameCredential({...account.credential,accountKey:void 0},credential));identity=activeKey&&Object.hasOwn(pool.accounts,activeKey)&&pool.accounts[activeKey].credential.type===
|
|
1014
|
+
"oauth"?{key:activeKey,label:pool.accounts[activeKey].label}:cached?{key:cached.key,label:cached.label}:includeApiKeys?{key:`account-${randomUUID4()}`,label:`Account ${pool.nextLocalAccountId??Object.keys(pool.accounts).length+1}`}:nextLocalAccountIdentity(pool)}let existing=pool.accounts[identity.key];if(!existing?.quarantine)return pool.accounts[identity.key]={credential:providerId==="openai-codex"&&!identity.key.startsWith("account-")?structuredClone(credential):{...structuredClone(credential),
|
|
1015
|
+
accountKey:identity.key},label:existing?.label??identity.label,exhaustedUntil:existing?.exhaustedUntil,quotaFailures:existing?.quotaFailures,cooldownRevision:existing?.cooldownRevision},identity.key}async run(providerId,mode,callerOptions,operation,expectedKey,recheckAuth=!1,includeApiKeys=!1,observation,canActivate,poolOnly=!1,usageRefresh){let operationPromise=(async()=>{let observationChanged=!1,credentials=observation?getAccountCredentialStore(this.credentials,current=>{let matches=observation.
|
|
1016
|
+
ifCurrent(current);return matches||(observationChanged=!0),matches}):this.credentials,passthrough={options:callerOptions,detach:()=>{}},outerLink=mode==="write"?linkAbortSignal(callerOptions):passthrough,authLink=mode==="write"?linkAbortSignal(callerOptions):passthrough,options=outerLink.options,commitAuthChange=()=>{callerOptions?.signal?.throwIfAborted(),outerLink.detach()},published={};try{let outcome=await this.storage.withLockAsync(async(content2,save)=>{let data,corrupt=!1;try{data=parsePoolData(
|
|
1017
|
+
content2),this.error=void 0}catch(error){if(this.error=`Invalid ${this.location}: ${error instanceof Error?error.message:String(error)}`,mode==="write")throw new Error(`Refusing to modify corrupt ${this.location}. Fix or delete it first.`);corrupt=!0,data={}}let hasLegacyAccounts=!corrupt&&content2!==void 0&&!Object.hasOwn(JSON.parse(stripBom(content2).trim()||"{}"),"version")&&Object.keys(data).length>0,backedUp=!1,serialize=providers=>{if(hasLegacyAccounts&&this.storage instanceof FileAuthStorageBackend&&
|
|
1018
|
+
!this.backupPath)throw new Error("File-backed account migration requires OAuthAccountPool.create() or a backup path");if(hasLegacyAccounts&&!backedUp&&this.backupPath){if(existsSync4(this.backupPath)){if(readFileSync3(this.backupPath,"utf8")!==content2)throw new Error("Account migration backup already exists; refusing to overwrite it");let fd=openSync2(this.backupPath,"r");try{fchmodSync(fd,384),fsyncSync2(fd)}finally{closeSync2(fd)}}else{let fd=openSync2(this.backupPath,"wx",384);try{writeFileSync2(
|
|
1019
|
+
fd,content2,"utf8"),fsyncSync2(fd)}finally{closeSync2(fd)}}backedUp=!0}return this.storage instanceof FileAuthStorageBackend&&this.storage.makePrivate(),JSON.stringify({version:2,providers},null,2)},stored=Object.hasOwn(data,providerId)?data[providerId]:void 0,before=JSON.stringify(stored),plan=credential=>{let pool2=stored?structuredClone(stored):{active:"",accounts:{}};this.quarantineCrosslinks(providerId,pool2);let currentKey2=this.upsertCredential(pool2,credential,providerId,pool2.active,includeApiKeys);
|
|
1020
|
+
providerId!=="openai-codex"&&reserveLocalAccountKeys(pool2),currentKey2!==void 0&&(pool2.active=currentKey2);let source2=structuredClone(pool2),context={currentKey:currentKey2,currentCredential:currentKey2===void 0?void 0:pool2.accounts[currentKey2].credential};poolOnly&&(pool2=stored?structuredClone(stored):{active:"",accounts:{}});let result2=operation(pool2,context),keys=Object.keys(pool2.accounts);!poolOnly&&!Object.hasOwn(pool2.accounts,pool2.active)&&(pool2.active="");let active3=pool2.accounts[pool2.
|
|
1021
|
+
active];if(!poolOnly&&active3?.credential.type==="api_key"&&(active3.credential.key?.includes("$")||active3.credential.key?.startsWith("!"))){let stamped={...active3.credential,accountKey:pool2.active};active3.credential=stamped}return{pool:pool2,source:source2,context,result:result2,empty:keys.length===0||pool2.active===""}},current=await credentials.read(providerId,options);if(observationChanged)return{result:observation.changed};let next=plan(current);if(options?.signal?.throwIfAborted(),mode===
|
|
1022
|
+
"read"){let view2=structuredClone(next.pool);return includeApiKeys||this.upsertCredential(view2,current,providerId,view2.active,!0),this.cache.set(providerId,toPoolAccounts(view2)),{result:next.result}}if(next.result===void 0&&!usageRefresh)return{result:void 0};!observation&&JSON.stringify(next.pool)!==before&&serialize(data);let planned=current,replan=latest=>((poolOnly||!sameCredential(latest,planned))&&(next=plan(latest),planned=latest),next),persisted=before,{currentKey}=next.context;if(usageRefresh)
|
|
1023
|
+
await credentials.modify(providerId,async latest=>{let{pool:pool2,context}=replan(latest),key=usageRefresh.key??pool2.active,account=Object.hasOwn(pool2.accounts,key)?pool2.accounts[key]:void 0;if(account?.quarantine||account?.credential.type!=="oauth")return;if(account.credential.expires>Date.now()){next.result=usageRefresh.result(toAccount(pool2,key));return}serialize(data),commitAuthChange(),authLink.detach();let refreshed=await usageRefresh.refresh(account.credential);if(typeof refreshed=="s\
|
|
1024
|
+
tring"){next.result=usageRefresh.result(refreshed);return}return account.credential={...this.bindRefresh(providerId,account.credential,refreshed),accountKey:key},next.result=usageRefresh.result(toAccount(pool2,key)),context.currentKey===key?structuredClone(account.credential):void 0},authLink.options);else if(!(expectedKey!==void 0&¤tKey!==expectedKey)){if((poolOnly||!next.empty&&(currentKey!==void 0||next.context.activate)||recheckAuth&¤tKey===void 0)&&(!next.empty&&!sameCredential(
|
|
1025
|
+
next.pool.accounts[next.pool.active].credential,current)||expectedKey!==void 0||recheckAuth)&&(await credentials.modify(providerId,async latest=>{authLink.options?.signal?.throwIfAborted();let{pool:pool2,source:source2,context,result:result2,empty}=replan(latest);if(poolOnly||result2===void 0||expectedKey!==void 0&&context.currentKey!==expectedKey||context.currentKey===void 0&&!context.activate||empty)return;let target=pool2.accounts[pool2.active].credential;if(canActivate&&(context.currentKey===
|
|
1026
|
+
void 0||!canActivate(toPoolAccount(source2,context.currentKey),toPoolAccount(pool2,pool2.active))))throw new Error("Account activation is no longer authorized");if(!pool2.accounts[pool2.active].quarantine&&!sameCredential(target,latest))return latest!==void 0&&pool2.active!==context.currentKey&&JSON.stringify(source2)!==persisted&&(save(serialize({...data,[providerId]:source2})),persisted=JSON.stringify(source2)),serialize(data),commitAuthChange(),structuredClone(target)},authLink.options),observationChanged))
|
|
1027
|
+
return{result:observation.changed}}if(!poolOnly&&next.result!==void 0&&next.empty&&next.context.currentKey!==void 0){let deleteOptions={...authLink.options,ifCurrent:latest=>{let{result:result2,empty,context}=replan(latest);return result2===void 0||!empty||context.currentKey===void 0?!1:(serialize(data),commitAuthChange(),!0)}};if(await credentials.delete(providerId,deleteOptions),observationChanged)return{result:observation.changed}}let{pool,result}=next;Object.keys(pool.accounts).length===0&&pool.
|
|
1028
|
+
nextLocalAccountId===void 0?delete data[providerId]:Object.defineProperty(data,providerId,{value:pool,enumerable:!0,configurable:!0,writable:!0});let view=structuredClone(pool);if(poolOnly){let currentKey2=this.upsertCredential(view,next.context.currentCredential??planned,providerId,view.active,!0);currentKey2!==void 0&&(view.active=currentKey2)}!poolOnly&&!includeApiKeys&&planned?.type==="api_key"&&!next.context.activate&&this.upsertCredential(view,planned,providerId,view.active,!0),published.view=
|
|
1029
|
+
toPoolAccounts(view);let changed=!corrupt&&JSON.stringify(data[providerId])!==persisted;return{result,next:changed?serialize(data):void 0}},options);return published.view&&this.cache.set(providerId,published.view),outcome}finally{outerLink.detach(),authLink.detach()}})();if(mode==="write"){let pending=operationPromise.then(()=>{},()=>{});this.pendingWrites.add(pending),pending.finally(()=>this.pendingWrites.delete(pending))}return operationPromise}};import{existsSync as existsSync5}from"node:fs";import{setTimeout as delay2}from"node:timers/promises";var REASONS=new Set(["invalid-key","revoked-key","rate-limit","weekly-cap","quota"]),AUTH_STATUS=401,LIMIT_STATUS=429,INVALID_KEY_CODES=new Set(["invalid_api_key","missing_api_key"]),LIMIT_CODES=new Map([["rate_limit_exceeded","rate-limit"],["weekly_cap_exceeded","weekly-cap"],["quota_exceeded","quota"],["partner_credit_limit_exceeded","quota"]]),MAX_RETRY_AFTER_MS=366*24*60*60*1e3;function errorCode(body){if(typeof body!="object"||body===null||!("error"in body))return;let error=body.error;if(!(typeof error!=
|
|
1019
1030
|
"object"||error===null))return"code"in error&&typeof error.code=="string"?error.code:"type"in error&&typeof error.type=="string"?error.type:void 0}function retryAfterMs(headers,nowMs){let value=headers.get("retry-after")?.trim();if(!value)return;let delay3=/^\d+(?:\.\d+)?$/u.test(value)?Number(value)*1e3:Date.parse(value)-nowMs;return Number.isFinite(delay3)&&delay3>0&&delay3<=MAX_RETRY_AFTER_MS?Math.round(delay3):void 0}function classifyNodeAccountFailure(status,body,headers){let code=errorCode(
|
|
1020
1031
|
body);if(code===void 0)return;let reason;if(status===AUTH_STATUS&&INVALID_KEY_CODES.has(code)?reason="invalid-key":status===LIMIT_STATUS&&(reason=LIMIT_CODES.get(code)),reason===void 0)return;let delay3=retryAfterMs(headers,Date.now());return delay3===void 0?{reason}:{reason,retryAfterMs:delay3}}function getNodeAccountFailure(diagnostics){let details=diagnostics?.findLast(entry=>entry.type==="provider_http_error")?.details;if(typeof details!="object"||details===null||!("nodeAccountFailure"in details))
|
|
1021
1032
|
return;let value=details.nodeAccountFailure;if(typeof value!="object"||value===null||!("reason"in value)||typeof value.reason!="string"||!REASONS.has(value.reason))return;let reason=value.reason,delay3="retryAfterMs"in value?value.retryAfterMs:void 0;return typeof delay3=="number"&&Number.isFinite(delay3)&&delay3>0&&delay3<=MAX_RETRY_AFTER_MS?{reason,retryAfterMs:delay3}:{reason}}function redactAssistantMessage(message,key){if(!key)return;let redact=value=>value.replaceAll(key,"[redacted]"),redactJson=value=>typeof value=="string"?redact(value):Array.isArray(value)?value.map(redactJson):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([name,value2])=>[redact(name),redactJson(value2)])):value;message.errorMessage&&=redact(message.errorMessage),message.diagnostics&&(message.diagnostics=message.diagnostics.map(diagnostic=>({...diagnostic,type:redact(
|
|
@@ -1415,104 +1426,104 @@ provider=>provider.id):void 0,signal})}catch(error){throw runtime.dispose(),erro
|
|
|
1415
1426
|
HCODE_PROVIDER)continue;let config=this.config.getProvider(providerId);config?.oauth!=="radius"||!config.baseUrl||this.builtins.set(providerId,radiusProvider({id:providerId,name:config.name??providerId,gateway:config.baseUrl.replace(/\/v1\/?$/u,"")}))}}providerIds(){return new Set([...this.builtins.keys(),...this.nativeExtensionProviders.keys(),...this.config.getProviderIds(),...this.extensionProviders.keys(),...this.virtualModels.keys()])}recomposeProvider(providerId){let composed=this.composeProvider(
|
|
1416
1427
|
providerId),provider=composed;if(provider?.auth.apiKey){let apiKey=provider.auth.apiKey,withCredentialEnv=input=>{let env=input.credential?.env,ctx=input.ctx;return env?{...input,ctx:{...ctx,env:async name=>env[name]||await ctx.env(name)}}:input};provider={...provider,auth:{...provider.auth,apiKey:{...apiKey,resolve:async input=>{if(input.purpose!=="catalog"){let result=await apiKey.resolve(withCredentialEnv(input)),key=!this.credentials.hasRuntimeApiKey(providerId)&&input.credential?.key&&input.
|
|
1417
1428
|
credential.key===result?.auth.apiKey?this.oauthAccountPool.getAccountKeyForApiKey(providerId,input.credential.key):void 0;return this.oauthAccountObserver.getStore()?.(providerId,key),result}let credential=await this.credentials.authResolution.run(providerId,()=>this.credentials.read(providerId,{signal:input.signal}));if(credential?.type!=="oauth")return apiKey.resolve(withCredentialEnv({...input,credential}))},check:apiKey.check?input=>apiKey.check(withCredentialEnv(input)):void 0}}}}let oauth=provider?.
|
|
1418
|
-
auth.oauth;if(provider&&oauth&&this.oauthAccountPool.isPooled(providerId)&&(provider={...provider,auth:{...provider.auth,oauth:{...oauth,refresh:async(credential,signal)=>{
|
|
1419
|
-
this.oauthAccountPool.getAccountIdentity(providerId,credential)?.key),auth}}}}),providerId==="openrouter"&&provider?.refreshModels&&!this.nativeExtensionProviders.has(providerId)){let refreshModels=provider.refreshModels.bind(provider);provider={...provider,refreshModels:async context=>{let credential=context.credential;if(!context.allowNetwork&&
|
|
1420
|
-
signal}),command=this.credentials.isExternalCredential(stored)&&stored?.type==="api_key"&&stored.key!==void 0&&isCommandConfigValue(stored.key),configuredKey=this.extensionProviders.get(providerId)?.apiKey??this.config.getProvider(providerId)?.apiKey,key=credential?.key||credential?.env?.OPENROUTER_API_KEY||process.env.OPENROUTER_API_KEY;command?
|
|
1421
|
-
type:"api_key",key}:void 0}await refreshModels({...context,credential})}}}provider&&composed&&provider!==composed&&setModelListing(provider,()=>getModelListing(composed));let virtualModels=[...this.virtualModels.get(providerId)?.values()??[]].map(entry=>entry.model);return virtualModels.length>0?this.models.setProvider(withVirtualModels(
|
|
1422
|
-
nativeExtensionProviders.get(providerId)??this.builtins.get(providerId),extension=this.extensionProviders.get(providerId);if(rejectsConfigOverlays(providerId)&&(this.config.getProvider(providerId)||extension))return this.compositionErrors.set(providerId,`${providerId===HCODE_PROVIDER?"HUMAIN Code account":"HUMAIN Gateway"} does
|
|
1423
|
-
providerId,base,this.config,extension);return this.compositionErrors.delete(providerId),provider}catch(error){return this.compositionErrors.set(providerId,error instanceof Error?error.message:String(error)),base}}rebuildProviders(){this.models.clearProviders(),this.compositionErrors.clear();for(let providerId of this.
|
|
1424
|
-
all,available:all.ofProviders(this.snapshot.configuredProviders)}}async runAvailabilityRefresh(seq,errorSeq,signal){let providers=this.models.getProviders(),[available,checks,credentials]=await Promise.all([this.models.getAvailable(void 0,{signal}),Promise.all(providers.map(async provider=>[provider.id,await this.
|
|
1425
|
-
entry=>entry[1]!==void 0).map(([providerId])=>providerId));this.snapshot={all:new ChatModelsSnapshot(this.models.getProviders()),available:[...available],configuredProviders,storedProviders:new Set(credentials.map(entry=>entry.providerId)),auth},errorSeq===this.availabilityErrorSeq&&(this.availabilityError=void 0)}queueAvailabilityRefresh(signal){
|
|
1426
|
-
1);let errorSeq=++this.availabilityErrorSeq,effectiveSignal=operationSignal(signal);return this.runAvailabilityRefresh(seq,errorSeq,effectiveSignal).catch(error=>{throw errorSeq===this.availabilityErrorSeq&&!effectiveSignal.aborted&&(this.availabilityError=error instanceof Error?error.message:String(error)),error})}async refreshProviderAvailability(providerId,signal){
|
|
1427
|
-
providerId,providerSeq);let errorSeq=++this.availabilityErrorSeq;try{let[available,auth,credential]=await Promise.all([this.models.getAvailable(providerId,{signal}),this.models.checkAuth(providerId,{signal}),this.credentials.read(providerId,{signal})]);if(signal.throwIfAborted(),this.providerAvailabilitySeq.get(providerId)!==providerSeq)return;let configuredProviders=new Set(
|
|
1428
|
-
auth);auth?(configuredProviders.add(providerId),authByProvider.set(providerId,auth)):(configuredProviders.delete(providerId),authByProvider.delete(providerId)),credential?storedProviders.add(providerId):storedProviders.delete(providerId);let all=new ChatModelsSnapshot(this.models.getProviders()),availableById=new Map([...this.snapshot.available.filter(model=>model.provider!==
|
|
1429
|
-
values(),model=>model.provider));this.snapshot={all,available:all.ofProviders(availableProviders).flatMap(model=>availableById.get(`${model.provider}\0${model.id}`)??[]),configuredProviders,storedProviders,auth:authByProvider},errorSeq===this.availabilityErrorSeq&&(this.availabilityError=void 0)}catch(error){throw this.providerAvailabilitySeq.get(providerId)===providerSeq&&
|
|
1430
|
-
error}}getProviders(){return this.models.getProviders()}getProvider(providerId){return this.models.getProvider(providerId)}getModels(providerId){return this.models.getModels(providerId)}getModel(providerId,modelId){return this.models.getModel(providerId,modelId)}getModelChoices(){let models=[],standIns=new Map;for(let provider of this.models.getProviders()){let listing=getModelListing(
|
|
1431
|
-
let standIn=entry;models.push(standIn),standIns.set(standIn,{listing,index})})}return{models,model:choice=>{let standIn=standIns.get(choice);return standIn?standIn.listing.models()[standIn.index]:choice}}}getModelsOfType(type,providerId){return this.models.getModelsOfType(type,providerId)}getModelOfType(type,providerId,modelId){return this.models.getModelOfType(type,providerId,
|
|
1432
|
-
return this.models.getAvailableOfType(type,providerId,options)}getAllAvailable(providerId,options){return this.models.getAllAvailable(providerId,options)}async checkAuth(providerId,options){return this.models.checkAuth(providerId,options)}async getAvailable(providerId,options){if(providerId){let errorSeq=++this.availabilityErrorSeq;try{let available=await this.models.getAvailable(
|
|
1433
|
-
throw errorSeq===this.availabilityErrorSeq&&!options?.signal?.aborted&&(this.availabilityError=error instanceof Error?error.message:String(error)),error}}return await this.queueAvailabilityRefresh(options?.signal),this.snapshot.available}getAvailableSnapshot(){return this.snapshot.available}getError(){let errors=[],configError=this.config.getError();configError&&errors.push(configError);
|
|
1434
|
-
errors.push(`Availability refresh: ${this.availabilityError}`);let poolError=this.oauthAccountPool.getError();return poolError&&errors.push(poolError),errors.length>0?errors.join(`
|
|
1429
|
+
auth.oauth;if(provider&&oauth&&this.oauthAccountPool.isPooled(providerId)&&(provider={...provider,auth:{...provider.auth,oauth:{...oauth,refresh:async(credential,signal)=>{this.oauthAccountPool.assertCredentialUsable(providerId,credential),this.oauthAccountObserver.getStore()?.(providerId,this.oauthAccountPool.getAccountIdentity(providerId,credential)?.key);let refreshed=await oauth.refresh(credential,signal);return this.oauthAccountPool.bindRefresh(providerId,credential,refreshed)},toAuth:async credential=>{
|
|
1430
|
+
this.oauthAccountPool.assertCredentialUsable(providerId,credential);let auth=await oauth.toAuth(credential);return this.oauthAccountObserver.getStore()?.(providerId,this.oauthAccountPool.getAccountIdentity(providerId,credential)?.key),auth}}}}),providerId==="openrouter"&&provider?.refreshModels&&!this.nativeExtensionProviders.has(providerId)){let refreshModels=provider.refreshModels.bind(provider);provider={...provider,refreshModels:async context=>{let credential=context.credential;if(!context.allowNetwork&&
|
|
1431
|
+
credential?.type!=="oauth"){let stored=this.credentials.getRuntimeApiKey(providerId)?void 0:await this.credentials.readStored(providerId,{signal:context.signal}),command=this.credentials.isExternalCredential(stored)&&stored?.type==="api_key"&&stored.key!==void 0&&isCommandConfigValue(stored.key),configuredKey=this.extensionProviders.get(providerId)?.apiKey??this.config.getProvider(providerId)?.apiKey,key=credential?.key||credential?.env?.OPENROUTER_API_KEY||process.env.OPENROUTER_API_KEY;command?
|
|
1432
|
+
key=void 0:!credential&&configuredKey!==void 0&&(key=isCommandConfigValue(configuredKey)?void 0:resolveConfigValue(configuredKey)),credential=key?{...credential,type:"api_key",key}:void 0}await refreshModels({...context,credential})}}}provider&&composed&&provider!==composed&&setModelListing(provider,()=>getModelListing(composed));let virtualModels=[...this.virtualModels.get(providerId)?.values()??[]].map(entry=>entry.model);return virtualModels.length>0?this.models.setProvider(withVirtualModels(
|
|
1433
|
+
providerId,provider,virtualModels)):provider?this.models.setProvider(provider):this.models.deleteProvider(providerId),provider}composeProvider(providerId){let base=this.nativeExtensionProviders.get(providerId)??this.builtins.get(providerId),extension=this.extensionProviders.get(providerId);if(rejectsConfigOverlays(providerId)&&(this.config.getProvider(providerId)||extension))return this.compositionErrors.set(providerId,`${providerId===HCODE_PROVIDER?"HUMAIN Code account":"HUMAIN Gateway"} does n\
|
|
1434
|
+
ot accept models.json overrides.`),base;if(!this.config.getProvider(providerId)&&!extension)return this.compositionErrors.delete(providerId),base;try{let provider=composeModelProvider(providerId,base,this.config,extension);return this.compositionErrors.delete(providerId),provider}catch(error){return this.compositionErrors.set(providerId,error instanceof Error?error.message:String(error)),base}}rebuildProviders(){this.models.clearProviders(),this.compositionErrors.clear();for(let providerId of this.
|
|
1435
|
+
providerIds())this.recomposeProvider(providerId);this.updateModelSnapshot()}updateModelSnapshot(){let all=new ChatModelsSnapshot(this.models.getProviders());this.snapshot={...this.snapshot,all,available:all.ofProviders(this.snapshot.configuredProviders)}}async runAvailabilityRefresh(seq,errorSeq,signal){let providers=this.models.getProviders(),[available,checks,credentials]=await Promise.all([this.models.getAvailable(void 0,{signal}),Promise.all(providers.map(async provider=>[provider.id,await this.
|
|
1436
|
+
models.checkAuth(provider.id,{signal})])),this.credentials.list({signal})]);if(seq!==this.availabilityRefreshSeq)return;let auth=new Map(checks),configuredProviders=new Set(checks.filter(entry=>entry[1]!==void 0).map(([providerId])=>providerId));this.snapshot={all:new ChatModelsSnapshot(this.models.getProviders()),available:[...available],configuredProviders,storedProviders:new Set(credentials.map(entry=>entry.providerId)),auth},errorSeq===this.availabilityErrorSeq&&(this.availabilityError=void 0)}queueAvailabilityRefresh(signal){
|
|
1437
|
+
let seq=++this.availabilityRefreshSeq;for(let[providerId,providerSeq]of this.providerAvailabilitySeq)this.providerAvailabilitySeq.set(providerId,providerSeq+1);let errorSeq=++this.availabilityErrorSeq,effectiveSignal=operationSignal(signal);return this.runAvailabilityRefresh(seq,errorSeq,effectiveSignal).catch(error=>{throw errorSeq===this.availabilityErrorSeq&&!effectiveSignal.aborted&&(this.availabilityError=error instanceof Error?error.message:String(error)),error})}async refreshProviderAvailability(providerId,signal){
|
|
1438
|
+
++this.availabilityRefreshSeq;let providerSeq=(this.providerAvailabilitySeq.get(providerId)??0)+1;this.providerAvailabilitySeq.set(providerId,providerSeq);let errorSeq=++this.availabilityErrorSeq;try{let[available,auth,credential]=await Promise.all([this.models.getAvailable(providerId,{signal}),this.models.checkAuth(providerId,{signal}),this.credentials.read(providerId,{signal})]);if(signal.throwIfAborted(),this.providerAvailabilitySeq.get(providerId)!==providerSeq)return;let configuredProviders=new Set(
|
|
1439
|
+
this.snapshot.configuredProviders),storedProviders=new Set(this.snapshot.storedProviders),authByProvider=new Map(this.snapshot.auth);auth?(configuredProviders.add(providerId),authByProvider.set(providerId,auth)):(configuredProviders.delete(providerId),authByProvider.delete(providerId)),credential?storedProviders.add(providerId):storedProviders.delete(providerId);let all=new ChatModelsSnapshot(this.models.getProviders()),availableById=new Map([...this.snapshot.available.filter(model=>model.provider!==
|
|
1440
|
+
providerId),...available].map(model=>[`${model.provider}\0${model.id}`,model])),availableProviders=new Set(Array.from(availableById.values(),model=>model.provider));this.snapshot={all,available:all.ofProviders(availableProviders).flatMap(model=>availableById.get(`${model.provider}\0${model.id}`)??[]),configuredProviders,storedProviders,auth:authByProvider},errorSeq===this.availabilityErrorSeq&&(this.availabilityError=void 0)}catch(error){throw this.providerAvailabilitySeq.get(providerId)===providerSeq&&
|
|
1441
|
+
errorSeq===this.availabilityErrorSeq&&!signal.aborted&&(this.availabilityError=error instanceof Error?error.message:String(error)),error}}getProviders(){return this.models.getProviders()}getProvider(providerId){return this.models.getProvider(providerId)}getModels(providerId){return this.models.getModels(providerId)}getModel(providerId,modelId){return this.models.getModel(providerId,modelId)}getModelChoices(){let models=[],standIns=new Map;for(let provider of this.models.getProviders()){let listing=getModelListing(
|
|
1442
|
+
provider);if(!listing){try{models.push(...provider.getModels())}catch{}continue}listing.entries.forEach((entry,index)=>{let standIn=entry;models.push(standIn),standIns.set(standIn,{listing,index})})}return{models,model:choice=>{let standIn=standIns.get(choice);return standIn?standIn.listing.models()[standIn.index]:choice}}}getModelsOfType(type,providerId){return this.models.getModelsOfType(type,providerId)}getModelOfType(type,providerId,modelId){return this.models.getModelOfType(type,providerId,
|
|
1443
|
+
modelId)}getAllModels(providerId){return this.models.getAllModels(providerId)}getAvailableOfType(type,providerId,options){return this.models.getAvailableOfType(type,providerId,options)}getAllAvailable(providerId,options){return this.models.getAllAvailable(providerId,options)}async checkAuth(providerId,options){return this.models.checkAuth(providerId,options)}async getAvailable(providerId,options){if(providerId){let errorSeq=++this.availabilityErrorSeq;try{let available=await this.models.getAvailable(
|
|
1444
|
+
providerId,options);return errorSeq===this.availabilityErrorSeq&&(this.availabilityError=void 0),available}catch(error){throw errorSeq===this.availabilityErrorSeq&&!options?.signal?.aborted&&(this.availabilityError=error instanceof Error?error.message:String(error)),error}}return await this.queueAvailabilityRefresh(options?.signal),this.snapshot.available}getAvailableSnapshot(){return this.snapshot.available}getError(){let errors=[],configError=this.config.getError();configError&&errors.push(configError);
|
|
1445
|
+
for(let[providerId,error]of this.compositionErrors)errors.push(`Provider "${providerId}": ${error}`);this.availabilityError&&errors.push(`Availability refresh: ${this.availabilityError}`);let poolError=this.oauthAccountPool.getError();return poolError&&errors.push(poolError),errors.length>0?errors.join(`
|
|
1435
1446
|
|
|
1436
1447
|
`):void 0}getRegisteredProviderConfig(providerId){return this.extensionProviders.get(providerId)}getRegisteredProviderIds(){return[...new Set([...this.extensionProviders.keys(),...this.nativeExtensionProviders.keys()])]}getRegisteredNativeProvider(providerId){return this.nativeExtensionProviders.get(providerId)}getCompatibilityRequestConfig(model){if(model.provider===HCODE_PROVIDER)throw new ModelsError("auth","HUMAIN Code account is unavailable.");return rejectsConfigOverlays(model.provider)?resolveCompatibilityRequestConfig(
|
|
1437
1448
|
model,void 0,void 0):resolveCompatibilityRequestConfig(model,this.config.getProvider(model.provider),this.extensionProviders.get(model.provider))}isUsingOAuth(providerId){return this.snapshot.auth.get(providerId)?.type==="oauth"}isUsingSubscription(providerId){let auth=this.models.getProvider(providerId)?.auth;return this.isUsingOAuth(providerId)?auth?.oauth?.isSubscription===!0:this.hasConfiguredAuth(providerId)&&auth?.apiKey?.isSubscription===!0}hasConfiguredAuth(providerId){return this.snapshot.
|
|
1438
|
-
configuredProviders.has(providerId)}withResolvedAuth(model,resolution,accountKey,run2){return this.resolvedRequestAuth.run({model,resolution,accountKey},run2)}async getAuth(providerOrModel,overrides={}){let providerId=typeof providerOrModel=="string"?providerOrModel:providerOrModel.provider,pinned=this.resolvedRequestAuth.getStore();if(pinned?.model===providerOrModel)return overrides.signal?.throwIfAborted(),overrides.onOAuthAccount?.(providerId,pinned.accountKey),pinned.resolution;
|
|
1439
|
-
credentials.authResolution.run(providerId,()=>this.oauthAccountObserver.run(overrides.onOAuthAccount,()=>typeof providerOrModel=="string"?this.models.getAuth(providerOrModel,overrides):this.models.getAuth(providerOrModel,overrides)));if(typeof providerOrModel=="string")return resolution;if(!resolution)return;if(rejectsConfigOverlays(providerOrModel.provider))return resolution;let configuredHeaders2=resolveConfiguredModelHeaders(
|
|
1440
|
-
extensionProviders.get(providerOrModel.provider),{...resolution.env??{},...overrides.env??{}});return{...resolution,auth:{...resolution.auth,headers:mergeHeaders(resolution.auth.headers,configuredHeaders2)}}}protectCredentialOperation(operation,signal,mutation=!0){return operation.catch(error=>{if(error instanceof CredentialSynchronizationError)throw new CredentialSynchronizationError(error.providerId,error.operation);if(error instanceof
|
|
1441
|
-
if(error instanceof LoginCancellationError)throw new LoginCancellationError;if(error instanceof SafeCredentialError&&!signal?.aborted)throw new SafeCredentialError(error.message);let safe=new ModelsError("auth",mutation?"Credential operation failed. Stored state may have changed. Inspect accounts and refresh local models before retrying.":"Could not read account metadata. Check credential storage and provider configuration.");
|
|
1442
|
-
let previous=this.credentialOperations.get(providerId)??Promise.resolve(),markStarted,started=new Promise(resolve13=>{markStarted=resolve13}),operation=(async()=>(await previous.catch(()=>{}),signal.throwIfAborted(),markStarted?.(),task()))(),tail=operation.catch(()=>{});return this.credentialOperations.set(providerId,tail),tail.then(()=>{this.credentialOperations.get(providerId)===tail&&this.
|
|
1443
|
-
then(()=>operation),signal)}async synchronizeCredentialState(providerId,operation,signal){try{signal.throwIfAborted(),this.recomposeProvider(providerId);let compositionError=this.compositionErrors.get(providerId);if(compositionError&&!rejectsConfigOverlays(providerId))throw new Error(compositionError);let result=await this.models.refresh({allowNetwork:!1,providers:[providerId],signal});result.
|
|
1444
|
-
this.updateModelSnapshot(),await this.refreshProviderAvailability(providerId,signal)}catch{let error=new CredentialSynchronizationError(providerId,operation);throw this.compositionErrors.has(providerId)&&this.compositionErrors.set(providerId,error.message),this.availabilityError&&(this.availabilityError=error.message),error}}async setRuntimeApiKey(providerId,apiKey,options={}){assertCustomProviderId(
|
|
1445
|
-
signal,async()=>{this.credentials.setRuntimeApiKey(providerId,apiKey),await this.synchronizeCredentialState(providerId,"setRuntimeApiKey",signal)})}removeRuntimeApiKey(providerId,options={}){let signal=operationSignal(options.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{this.credentials.removeRuntimeApiKey(providerId),await this.synchronizeCredentialState(providerId,
|
|
1446
|
-
this.credentials.readStored(providerId,options),options?.signal,!1)}async settleCredentialWrites(){for(;this.credentialOperations.size>0;)await Promise.all(this.credentialOperations.values());await this.credentials.settled(),await this.oauthAccountPool.settled()}listCredentials(options){return this.protectCredentialOperation(this.credentials.list(options),options?.signal,!1)}accounts={
|
|
1447
|
-
providerId,options);if(providerId===HCODE_PROVIDER)return[];let accounts=await this.oauthAccountPool.listAccounts(providerId,options),current=await this.oauthAccountPool.getCurrentAccount(providerId,options),visible=options?.distinctForDisplay?this.oauthAccountPool.displayAccounts(providerId,accounts):accounts,labels=new Map(accounts.map(({key,label})=>[key,label]));return visible.
|
|
1448
|
-
{},type:credential.type,exhaustedUntil,active:key===current?.key,effective:key===current?.key&&storedEffective}))})(),options?.signal,!1),sources:(providerId,options)=>this.protectCredentialOperation(this.readAccountSources(providerId,options).then(result=>result.sources),options?.signal,!1),switch:(providerId,accountKey,options={})=>{let signal=operationSignal(options.
|
|
1449
|
-
accountKey,{signal}))return await this.synchronizeCredentialState(providerId,"switchAccount",signal),(await this.accounts.list(providerId,{signal})).find(entry=>entry.key===accountKey)})},rename:(providerId,accountKey,label,options)=>this.protectCredentialOperation((async()=>await this.oauthAccountPool.renameAccount(providerId,accountKey,label,options)?(await this.
|
|
1450
|
-
logoutWithStatus(providerId,{...options,accountKey})};async readAccountSources(providerId,options){let signal=operationSignal(options?.signal),provider=this.models.getProvider(providerId),session=providerId===HCODE_PROVIDER?this.hcodeSession:void 0,stored=session?void 0:await this.credentials.readStored(providerId,{signal});if(providerId===HCODE_PROVIDER){
|
|
1451
|
-
credential:credential?.type==="api_key"?credential:void 0,signal});return{sources:credential?[{source:session?"runtime":"auth_json",label:this.hcodeFacade.provider.name,type:"api_key",readOnly:!0,effective:!!checked}]:[],storedEffective:!session&&!!checked}}let runtimeKey=this.credentials.getRuntimeApiKey(providerId),extensionKey=this.extensionProviders.get(
|
|
1452
|
-
stored),sources=[],add=(source2,label,effective=!1)=>sources.push({source:source2,label,type:"api_key",readOnly:!0,effective});runtimeKey&&add("runtime","runtime API key",provider?.auth.apiKey!==void 0),stored?.type==="api_key"&&(external||!stored.key?.trim())&&add("auth_json",stored.key?isCommandConfigValue(stored.key)?"command in auth.json":
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
oauth!==void 0;else if(provider.auth.apiKey)if(external&&stored?.type==="api_key"&&stored.key!==void 0&&isCommandConfigValue(stored.key))sources.find(entry=>entry.source==="auth_json").effective=!0;else if(!stored&&configKey!==void 0){let configured=isCommandConfigValue(configKey)||resolveConfigValue(configKey)!==void 0;sources.find(entry=>entry.source==="configuration").
|
|
1456
|
-
check=method?.check??(this.nativeExtensionProviders.has(providerId)?void 0:method?.resolve),credential=stored?.type==="api_key"?{...stored,key:external&&stored.key!==void 0?resolveConfigValue(stored.key,stored.env):stored.key}:void 0,ctx=defaultProviderAuthContext(),usedEnvironment=new Set,result=check?await check({ctx:{...ctx,env:async name=>{let value=env?.[name]||await ctx.
|
|
1457
|
-
nativeExtensionProviders.has(providerId),source2=native?void 0:result?.source;if(storedEffective=!!stored&&(native?check?!!result&&usedEnvironment.size===0:!!credential?.key:source2==="stored credential"||source2==="stored"||!check&&!!credential?.key),result&&!storedEffective){let selectedNames=source2&&sources.some(entry=>entry.label===source2)?[source2]:[...usedEnvironment],
|
|
1458
|
-
entry&&(entry.effective=!0,marked=!0)}marked||add("environment","ambient credentials",!0)}}}let storedSource=sources.find(entry=>entry.source==="auth_json");return storedSource&&storedEffective&&(storedSource.effective=!0),signal.throwIfAborted(),{sources,storedEffective}}async prepareAccountRequest(providerId,autoSwitch,skipKeys,signal){if(!autoSwitch()||this.credentials.hasRuntimeApiKey(
|
|
1459
|
-
isExternalCredential(stored))return;await this.oauthAccountPool.returnToPreferred(providerId,{signal,skipKeys,canActivate:()=>autoSwitch()&&!this.credentials.hasRuntimeApiKey(providerId)})&&await this.synchronizeCredentialState(providerId,"switchAccount",operationSignal(signal))}get oauthAccounts(){return this.oauthAccountPool}getProviderAuthStatus(providerId){if(providerId===HCODE_PROVIDER)
|
|
1460
|
-
if(this.credentials.hasRuntimeApiKey(providerId))return{configured:!0,source:"runtime"};if(this.snapshot.storedProviders.has(providerId))return{configured:!0,source:"stored"};let configured=configuredRequestAuthStatus(this.config.getProvider(providerId),this.extensionProviders.get(providerId));if(configured)return configured;let check=this.snapshot.auth.get(providerId);return check?
|
|
1461
|
-
let admission=this.currentAdmission(),currentProvider=this.models.getProvider(model.provider),provider=currentProvider&&(admission||options?.beforeSubmission?{...currentProvider}:currentProvider);if(admission||options?.beforeSubmission){let native=this.nativeExtensionProviders.get(model.provider);if(!intent||!isModelType(model,"chat")||!["anthropic-messages","bedrock-converse-stream",
|
|
1462
|
-
native,provider))||this.extensionProviders.get(model.provider)?.streamSimple)throw new SubmissionAdmissionError("unsupported-route")}if(this.assertHcodeModel(model),model.provider===HCODE_PROVIDER&&options&&"transport"in options&&options.transport==="auto"&&(options={...options,transport:"sse"}),model.provider===HCODE_PROVIDER&&this.currentRequestPurpose()==="cache-warming")
|
|
1463
|
-
AbortSignal.any([this.hcodeFacade.signal,...options?.signal?[options.signal]:[]]):options?.signal;if(!provider)throw new ModelsError("provider",`Unknown provider: ${model.provider}`);let resolvedAccount,observesAnthropicLimits=model.provider===ANTHROPIC_PROVIDER_ID,resolution=await this.getAuth(model,{apiKey:options?.apiKey,env:options?.env,signal,onOAuthAccount:options?.
|
|
1464
|
-
"auth",`Provider is not configured: ${model.provider}`);let{transformHeaders,resolveOnPayload,onPhysicalTarget:_onPhysicalTarget,onOAuthAccount:_onOAuthAccount,...rawProviderOptions}=options??{},providerOptions=rawProviderOptions,requestModel=resolution.
|
|
1465
|
-
sessionId),resolution.auth.headers),providerOptions.headers);transformHeaders&&(headers=await transformHeaders(headers??{})),this.assertHcodeModel(model);let env=resolution.env||providerOptions.env?{...resolution.env??{},...providerOptions.env??{}}:
|
|
1466
|
-
resolution.auth.apiKey?resolvedAccount.key:apiKey?this.oauthAccountPool.getAccountKeyForAccessToken(model.provider,apiKey):void 0,options?.onOAuthAccount?.(model.provider,attributedAccountKey));let callerOnResponse=providerOptions.onResponse,onResponse=observesAnthropicLimits&&
|
|
1467
|
-
response),await callerOnResponse?.(response,responseModel)}:callerOnResponse,scope=this.currentScope(),tracker=scope||admission?new RequestTracker(scope,requestModel,admission):void 0,gate=admission&&intent?submissionAdmission(admission,requestModel,intent,scope?.purpose):void 0,
|
|
1468
|
-
onPayload;return{provider,model:requestModel,options:{...providerOptions,signal,apiKey,headers,env,onPayload:scope&&callerOnPayload?(payload,payloadModel)=>this.requestScope.run(scope,()=>callerOnPayload(payload,payloadModel)):callerOnPayload,...onResponse?{onResponse}:{}
|
|
1469
|
-
now());snapshot2&&this.anthropicRateLimits.record(accountKey,snapshot2)}catch{}}observeRequests(observer,purpose,fn){return this.admissionScope.getStore()?.observers.add(observer),this.requestScope.run({observer,purpose},fn)}async admitRequests(admission,fn){if(this.admissionScope.
|
|
1470
|
-
try{return await this.admissionScope.run(scope,fn)}finally{this.activeAdmissions.delete(scope)}}currentAdmission(){let scope=this.admissionScope.getStore();if(!scope&&this.activeAdmissions.size>0){let observer=this.requestScope.getStore()?.observer;if(!observer||!this.ownerObservers.
|
|
1471
|
-
|
|
1472
|
-
HCODE_PROVIDER,signal,async()=>{if(this.hcodeSession&&this.hcodeFacade.persistence(this.hcodeSession)==="session")return!1;let stored=await this.credentials.readStored(HCODE_PROVIDER,{signal});return this.hcodeFacade.adopt(stored)?(this.hcode.account.status(
|
|
1473
|
-
return this.hcodeFacade.accountEmail(expected)}async shutdownHcodeSession(signal){try{return await this.hcodeFacade.shutdown(signal)}finally{this.credentials.clearHcodeSessionReference()}}shutdownOwnedHcodeSession(signal){return this.sessionOwned?this.shutdownHcodeSession(
|
|
1474
|
-
delete(observer)&&this.sessionOwned&&this.ownerObservers.size===0&&this.dispose()}}currentScope(){let scope=this.requestScope.getStore();if(scope||this.ownerObservers.size===0)return scope;if(this.ownerObservers.size===1){let[observer]=this.ownerObservers;return{observer,
|
|
1475
|
-
return scope?this.observeRequests(scope.observer,purpose,fn):fn()}assertHcodeModel(model){if(model.provider===HCODE_PROVIDER&&this.getPhysicalModel(HCODE_PROVIDER,model.id)!==model)throw new ModelsError("model_validation","HUMAIN Code account approved model
|
|
1476
|
-
event.type==="error"&&actualModel().provider===HCODE_PROVIDER&&event.error.diagnostics?.some(entry=>entry.type==="provider_no_progress_timeout")&&(onTimeout(),event.error.errorMessage="HUMAIN Code request unavailable. Do not automatically resend.",event.error.diagnostics=
|
|
1477
|
-
provider===HCODE_PROVIDER||this.defaultBuiltins.has(model.provider)&&!this.nativeExtensionProviders.has(model.provider)&&!this.extensionProviders.has(model.provider)&&!this.config.getProvider(model.provider)),provider=native?model.provider:"other",id2=native&&model.provider!==
|
|
1478
|
-
0&&value<=2147483647?value:null,outcome=message?.stopReason==="aborted"?"cancelled":message?.stopReason==="stop"||message?.stopReason==="toolUse"?usage?.usageIncomplete?"unknown":"success":"failure",retries=Math.max(0,submissions-1);if(this.metadata.inference(provider,id2,
|
|
1479
|
-
outcome}),outcome!=="success"){let http=message?.diagnostics?.findLast(entry=>entry.type==="provider_http_error"),hcode=http?.details?.hcode,status=hcode&&typeof hcode=="object"&&"status"in hcode?hcode.status:http?.details?.status,code=observedFailure??(message?.diagnostics?.
|
|
1480
|
-
outcome)}}}trackStream(stream,tracker,observe){return stream.result().then(message=>{observe?.(message),tracker()?.settleMessage(message)},()=>{observe?.(void 0),tracker()?.settleFailure(!1)}),stream}stream(model,context,options){let transcript=normalizeContext(context),
|
|
1481
|
-
guardHcodeTimeout(model,streamWithProgressTimeout(model,async signal=>{assertChatModel(model);let intent=admissionIntent(model,options);this.currentAdmission()&&(intent.requiredImageCount=assertAdmittedModelInput(model,context));let prepared=await this.prepareRequest(
|
|
1482
|
-
message=>observe(message,submissions,observedFailure))}complete(model,context,options){return drainStream(this.stream(model,context,options))}streamSimple(model,context,options){let transcript=normalizeContext(context),tracker,requestModel=model,started=performance.
|
|
1483
|
-
this.guardHcodeTimeout(model,streamWithProgressTimeout(model,async signal=>{let requestOptions=options;if(isVirtualModel(model)){let route=await this.resolveModel(model,transcript.messages,{reason:"direct",thinkingLevel:options?.reasoning??"off",signal});signal.throwIfAborted();
|
|
1484
|
-
{},auth=route.model.provider===model.provider?{apiKey,headers,env}:{};requestModel=route.model,requestOptions={...rest,...auth,maxTokens,reasoning}}observe=this.inferenceObservation(requestModel,started),requestOptions?.onPhysicalTarget?.(requestModel),assertChatModel(requestModel);
|
|
1485
|
-
intent);return tracker=prepared.tracker,signal.throwIfAborted(),prepared.provider.streamSimple(prepared.model,transcript,prepared.options)},options),()=>requestModel,()=>{observedFailure="timeout"}),()=>tracker,message=>observe(message,submissions,observedFailure))}completeSimple(model,context,options){
|
|
1486
|
-
prepareRequest(model,options);if(tracker=prepared.tracker,!prepared.provider.fetchDeferred)throw new ModelsError("provider",`Provider ${model.provider} does not support deferred responses`);return prepared.provider.fetchDeferred(prepared.model,handle,prepared.options)},void 0,options?.signal),
|
|
1487
|
-
prepareRequest(model,options);if(!prepared.provider.cancelDeferred)throw new ModelsError("provider",`Provider ${model.provider} does not support deferred responses`);await prepared.provider.cancelDeferred(prepared.model,handle,prepared.options)}async generateImages(model,context,options){let tracker;
|
|
1488
|
-
does not support image generation`);let result=await prepared.provider.generateImages(prepared.model,context,prepared.options);return tracker?.settleResult(result),result}catch(error){return tracker?.settleFailure(options?.signal?.aborted===!0),imageErrorResult(model,error,options?.signal?.aborted)}}async classify(model,context,options){
|
|
1489
|
-
tracker,!prepared.provider.classify)throw new ModelsError("provider",`Provider ${model.provider} does not support classification`);let result=await prepared.provider.classify(prepared.model,context,prepared.options);return tracker?.settleResult(result),result}catch(error){return tracker?.settleFailure(options?.signal?.aborted===!0),classifierErrorResult(
|
|
1490
|
-
now();return this.enqueueCredentialOperation(providerId,signal,async()=>{let provider=this.models.getProvider(providerId);if(!provider)throw new ModelsError("provider",`Unknown provider: ${providerId}`);let method=type==="oauth"?provider.auth.oauth:provider.auth.apiKey;if(!method?.login)throw new ModelsError("auth",`${provider.name} does not support
|
|
1491
|
-
key===options.accountKey);if(!selected||selected.credential.type!==type)throw new ModelsError("auth","Account is no longer available for reauthentication")}providerId===HCODE_PROVIDER&&await this.hcodeFacade.recover(signal);let nativeReference=providerId===HCODE_PROVIDER?await this.credentials.readStored(providerId,{signal}):void 0;providerId!==HCODE_PROVIDER&&
|
|
1492
|
-
try{return await interaction.prompt(prompt)}catch{throw(signal.aborted||!prompt.signal?.aborted)&&(promptCancelled=!0),new LoginCancellationError}}};login=await raceWithAbortSignal(providerId===HCODE_PROVIDER?this.hcodeFacade.login(input,signal,async reference=>{let candidate=hcodeReferenceCredential(reference);try{await this.credentials.modify(
|
|
1493
|
-
{signal})}catch(error){throw nativeReference?await this.credentials.modify(providerId,async current=>sameCredential(current,candidate)?nativeReference:void 0):await this.credentials.deleteStored(providerId,{ifCurrent:current=>sameCredential(current,candidate)}),error}}).then(hcodeReferenceCredential):method.login(input,options),signal)}catch(error){
|
|
1494
|
-
"oauth"||!!login.key?.trim();if(options?.accountKey!==void 0&&!poolable)throw new ModelsError("auth","Reauthentication must return a literal account credential");let account=poolable?await this.oauthAccountPool.addAccount(providerId,login,{signal,key:options?.accountKey}):void 0,credential=account?.credential??login;if(providerId===HCODE_PROVIDER){let reference=this.
|
|
1495
|
-
|
|
1496
|
-
now()-started),"success"),credential),error=>{let outcome=signal.aborted||error instanceof LoginCancellationError?"cancelled":"failure";throw this.metadata.feature("login",Math.round(performance.now()-started),outcome),this.metadata.failure("login",error instanceof CredentialSynchronizationError?"storage":"auth",0,outcome),providerId===HCODE_PROVIDER&&signal.aborted&&!(error instanceof CredentialSynchronizationError)?
|
|
1497
|
-
logoutWithStatus(providerId,options)}async deleteObservedStoredCredential(providerId,observed,signal){providerId===HCODE_PROVIDER&&await this.hcodeFacade.logoutStored(observed,signal);let status="changed";return await this.credentials.deleteStored(providerId,{signal,ifCurrent:latest=>sameCredential(latest,observed)?(status="removed",!0):!1}),status}prepareStoredCredentialRemoval(providerId,options){return this.protectCredentialOperation(
|
|
1498
|
-
readStored(providerId,options));if(!(!observed||await this.oauthAccountPool.getCurrentAccount(providerId,options)))return removalOptions=>{let signal=operationSignal(removalOptions?.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{let status=await this.deleteObservedStoredCredential(providerId,observed,signal);return status==="removed"&&await this.synchronizeCredentialState(providerId,"logout",signal),status})}})(),
|
|
1499
|
-
let signal=operationSignal(options.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{if(providerId===HCODE_PROVIDER&&await this.hcodeFacade.recover(signal),providerId===HCODE_PROVIDER&&this.hcodeSession){let reference=this.hcodeSession,retained=this.hcodeFacade.persistence(reference)==="session";try{retained&&await this.hcode.account.logout(reference,signal)}finally{this.credentials.clearHcodeSessionReference()}
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
delete(p))}refresh(options={}){return this.refreshInternal(options,{fromRegistration:!1})}async refreshInternal(options,{fromRegistration}){!fromRegistration&&this.pendingRegistrationRefreshes.size>0&&await Promise.allSettled([...this.pendingRegistrationRefreshes]);let config=await ModelConfig.load(this.modelsPath);if(this.assertConfiguration(config),this.config=config,this.configureRadiusProviders(),options.providers){for(let providerId of new Set(
|
|
1505
|
-
this.updateModelSnapshot()}else this.rebuildProviders();let refreshOptions={...options,allowNetwork:options.allowNetwork??this.modelNetworkEnabled},result=await this.models.refresh(refreshOptions)??{aborted:refreshOptions.signal?.aborted??!1,errors:new Map},errors=new Map(result.errors);if(this.updateModelSnapshot(),options.providers)await Promise.all([...new Set(options.providers)].map(async providerId=>{try{await this.refreshProviderAvailability(
|
|
1506
|
-
options.signal?.aborted||errors.set(providerId,error instanceof Error?error:new Error(String(error)))}}));else try{await this.queueAvailabilityRefresh(options.signal)}catch{}return{aborted:result.aborted||(options.signal?.aborted??!1),errors}}registerNativeProvider(provider){if(assertCustomProviderId(provider.id),!provider.id.trim())throw new Error("Provider id must not be empty.");this.extensionProviders.delete(provider.id),this.nativeExtensionProviders.
|
|
1507
|
-
provider.id),this.updateModelSnapshot(),this.markProvisionallyConfigured(provider.id,configuredRequestAuthStatus(this.config.getProvider(provider.id),void 0),provider.auth.oauth&&!provider.auth.apiKey?"oauth":"api_key"),this.queueRegistrationRefresh()}markProvisionallyConfigured(providerId,configuredStatus,type){if(!this.snapshot.storedProviders.has(providerId)&&!configuredStatus?.configured)return;let configuredProviders=new Set(this.snapshot.configuredProviders).
|
|
1508
|
-
snapshot.auth);auth.get(providerId)||auth.set(providerId,{type,source:"configured provider"}),this.snapshot={...this.snapshot,auth,configuredProviders,available:this.snapshot.all.ofProviders(configuredProviders)}}registerProvider(providerId,config){assertCustomProviderId(providerId),this.configurationGuard?.({[providerId]:config}),validateExtensionProvider(providerId,this.builtins.get(providerId),this.config.getProvider(providerId),config),this.nativeExtensionProviders.
|
|
1509
|
-
...this.extensionProviders.get(providerId)};for(let[key,value]of Object.entries(config))value!==void 0&&(effective[key]=value);this.extensionProviders.set(providerId,effective),this.recomposeProvider(providerId),this.updateModelSnapshot(),this.markProvisionallyConfigured(providerId,configuredRequestAuthStatus(this.config.getProvider(providerId),effective),effective.oauth&&!effective.apiKey?"oauth":"api_key"),this.queueRegistrationRefresh()}unregisterProvider(providerId){
|
|
1510
|
-
this.extensionProviders.delete(providerId),this.nativeExtensionProviders.delete(providerId),this.recomposeProvider(providerId),this.updateModelSnapshot(),this.queueRegistrationRefresh()}registerVirtualModel(definition){let{provider:providerId,id:id2}=definition;if(assertCustomProviderId(providerId),!providerId.trim()||!id2.trim())throw new Error("Virtual model provider and id must not be empty.");let existing=this.models.getModel(providerId,id2);if(existing&&!isVirtualModel(
|
|
1511
|
-
`Virtual model ${providerId}/${id2} conflicts with a physical model.`);let models=this.virtualModels.get(providerId)??new Map;if(models.set(id2,{model:createVirtualModel(definition),route:request2=>definition.route(request2)}),this.virtualModels.set(providerId,models),!this.recomposeProvider(providerId)&&!this.snapshot.configuredProviders.has(providerId)){let auth=new Map(this.snapshot.auth).set(providerId,{type:"api_key",source:"virtual"}),configuredProviders=new Set(this.
|
|
1512
|
-
add(providerId);this.snapshot={...this.snapshot,auth,configuredProviders}}this.updateModelSnapshot(),this.queueRegistrationRefresh()}unregisterVirtualModel(providerId,id2){assertCustomProviderId(providerId);let models=this.virtualModels.get(providerId);models?.delete(id2)&&(models.size===0&&this.virtualModels.delete(providerId),this.recomposeProvider(providerId),this.updateModelSnapshot(),this.queueRegistrationRefresh())}async resolveModel(model,messages,options){let name
|
|
1513
|
-
provider}/${model.id}`,virtual=this.virtualModels.get(model.provider)?.get(model.id);if(!virtual)throw new Error(`${name} is not registered.`);let{failed,deferThinkingClamp,...request2}=options,latest=findLatestResponse(messages),previousModel=latest&&this.getPhysicalModel(latest.provider,latest.model),failedModel=failed&&this.getPhysicalModel(failed.provider,failed.model),route=await virtual.route({...request2,model,previous:previousModel&&{model:previousModel,thinkingLevel:latest?.
|
|
1514
|
-
failed:failedModel&&failed&&{model:failedModel,thinkingLevel:failed.thinkingLevel,message:failed},messages});this.assertHcodeModel(route.model);let target=this.getPhysicalModel(route.model.provider,route.model.id),routed=`${name} routed to ${route.model.provider}/${route.model.id}`;if(!target)throw new Error(`${routed}, which is not a physical model.`);if(!this.hasConfiguredAuth(target.provider))throw new Error(`${routed}, which has no credentials.`);return deferThinkingClamp?{...route,
|
|
1515
|
-
{model:target,thinkingLevel:clampThinkingLevel(target,route.thinkingLevel),state:route.state}}getPhysicalModel(providerId,modelId){let model=this.models.getModel(providerId,modelId);if(!(model?.provider===HCODE_PROVIDER&&providerId!==HCODE_PROVIDER))return model&&!isVirtualModel(model)?model:void 0}};import{open as open2}from"node:fs/promises";var IMAGE_TYPE_SNIFF_BYTES=4100,PNG_SIGNATURE=[137,80,78,71,13,10,26,10];function detectSupportedImageMimeType(buffer){return startsWith(buffer,[255,216,255])?buffer[3]===247?null:"image/jpeg":startsWith(buffer,PNG_SIGNATURE)?isPng(buffer)&&!isAnimatedPng(buffer)?"image/png":null:startsWithAscii(buffer,0,"GIF87a")||startsWithAscii(buffer,0,"GIF89a")?"image/gif":startsWithAscii(buffer,0,"RIFF")&&startsWithAscii(buffer,8,"WEBP")?"image/webp":startsWithAscii(
|
|
1449
|
+
configuredProviders.has(providerId)}withResolvedAuth(model,resolution,accountKey,run2){return this.resolvedRequestAuth.run({model,resolution,accountKey},run2)}async getAuth(providerOrModel,overrides={}){let providerId=typeof providerOrModel=="string"?providerOrModel:providerOrModel.provider,pinned=this.resolvedRequestAuth.getStore();if(pinned?.model===providerOrModel)return overrides.signal?.throwIfAborted(),overrides.onOAuthAccount?.(providerId,pinned.accountKey),pinned.resolution;await this.oauthAccountPool.
|
|
1450
|
+
loadIntegrity(providerId,{signal:overrides.signal});let resolution=await this.credentials.authResolution.run(providerId,()=>this.oauthAccountObserver.run(overrides.onOAuthAccount,()=>typeof providerOrModel=="string"?this.models.getAuth(providerOrModel,overrides):this.models.getAuth(providerOrModel,overrides)));if(typeof providerOrModel=="string")return resolution;if(!resolution)return;if(rejectsConfigOverlays(providerOrModel.provider))return resolution;let configuredHeaders2=resolveConfiguredModelHeaders(
|
|
1451
|
+
providerOrModel,this.config.getProvider(providerOrModel.provider),this.extensionProviders.get(providerOrModel.provider),{...resolution.env??{},...overrides.env??{}});return{...resolution,auth:{...resolution.auth,headers:mergeHeaders(resolution.auth.headers,configuredHeaders2)}}}protectCredentialOperation(operation,signal,mutation=!0){return operation.catch(error=>{if(error instanceof CredentialSynchronizationError)throw new CredentialSynchronizationError(error.providerId,error.operation);if(error instanceof
|
|
1452
|
+
AccountSourceReplacementError)throw new AccountSourceReplacementError;if(error instanceof LoginCancellationError)throw new LoginCancellationError;if(error instanceof SafeCredentialError&&!signal?.aborted)throw new SafeCredentialError(error.message);let safe=new ModelsError("auth",mutation?"Credential operation failed. Stored state may have changed. Inspect accounts and refresh local models before retrying.":"Could not read account metadata. Check credential storage and provider configuration.");
|
|
1453
|
+
throw signal?.aborted&&(safe.name="AbortError"),safe})}enqueueCredentialOperation(providerId,signal,task){let previous=this.credentialOperations.get(providerId)??Promise.resolve(),markStarted,started=new Promise(resolve13=>{markStarted=resolve13}),operation=(async()=>(await previous.catch(()=>{}),signal.throwIfAborted(),markStarted?.(),task()))(),tail=operation.catch(()=>{});return this.credentialOperations.set(providerId,tail),tail.then(()=>{this.credentialOperations.get(providerId)===tail&&this.
|
|
1454
|
+
credentialOperations.delete(providerId)}),this.protectCredentialOperation(raceWithAbortSignal(started,signal).then(()=>operation),signal)}async synchronizeCredentialState(providerId,operation,signal){try{signal.throwIfAborted(),this.recomposeProvider(providerId);let compositionError=this.compositionErrors.get(providerId);if(compositionError&&!rejectsConfigOverlays(providerId))throw new Error(compositionError);let result=await this.models.refresh({allowNetwork:!1,providers:[providerId],signal});result.
|
|
1455
|
+
aborted&&signal.throwIfAborted();let refreshError=result.errors.get(providerId);if(refreshError)throw refreshError;this.updateModelSnapshot(),await this.refreshProviderAvailability(providerId,signal)}catch{let error=new CredentialSynchronizationError(providerId,operation);throw this.compositionErrors.has(providerId)&&this.compositionErrors.set(providerId,error.message),this.availabilityError&&(this.availabilityError=error.message),error}}async setRuntimeApiKey(providerId,apiKey,options={}){assertCustomProviderId(
|
|
1456
|
+
providerId);let signal=operationSignal(options.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{this.credentials.setRuntimeApiKey(providerId,apiKey),await this.synchronizeCredentialState(providerId,"setRuntimeApiKey",signal)})}removeRuntimeApiKey(providerId,options={}){let signal=operationSignal(options.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{this.credentials.removeRuntimeApiKey(providerId),await this.synchronizeCredentialState(providerId,
|
|
1457
|
+
"removeRuntimeApiKey",signal)})}readStoredCredential(providerId,options){return this.protectCredentialOperation(this.credentials.readStored(providerId,options),options?.signal,!1)}async settleCredentialWrites(){for(;this.credentialOperations.size>0;)await Promise.all(this.credentialOperations.values());await this.credentials.settled(),await this.oauthAccountPool.settled()}listCredentials(options){return this.protectCredentialOperation(this.credentials.list(options),options?.signal,!1)}accounts={
|
|
1458
|
+
list:(providerId,options)=>this.protectCredentialOperation((async()=>{let{storedEffective}=await this.readAccountSources(providerId,options);if(providerId===HCODE_PROVIDER)return[];let accounts=await this.oauthAccountPool.listAccounts(providerId,options),current=await this.oauthAccountPool.getCurrentAccount(providerId,options),visible=options?.distinctForDisplay?this.oauthAccountPool.displayAccounts(providerId,accounts):accounts,labels=new Map(accounts.map(({key,label})=>[key,label]));return visible.
|
|
1459
|
+
map(({key,label,credential,exhaustedUntil})=>({key,label:labels.get(key)??label,...labels.get(key)!==label?{displayLabel:label}:{},type:credential.type,exhaustedUntil,active:key===current?.key,effective:key===current?.key&&storedEffective}))})(),options?.signal,!1),sources:(providerId,options)=>this.protectCredentialOperation(this.readAccountSources(providerId,options).then(result=>result.sources),options?.signal,!1),switch:(providerId,accountKey,options={})=>{let signal=operationSignal(options.
|
|
1460
|
+
signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{if(await this.oauthAccountPool.setActiveAccount(providerId,accountKey,{signal}))return await this.synchronizeCredentialState(providerId,"switchAccount",signal),(await this.accounts.list(providerId,{signal})).find(entry=>entry.key===accountKey)})},rename:(providerId,accountKey,label,options)=>this.protectCredentialOperation((async()=>await this.oauthAccountPool.renameAccount(providerId,accountKey,label,options)?(await this.
|
|
1461
|
+
accounts.list(providerId,options)).find(entry=>entry.key===accountKey):void 0)(),options?.signal),remove:(providerId,accountKey,options)=>this.logoutWithStatus(providerId,{...options,accountKey})};async readAccountSources(providerId,options){let signal=operationSignal(options?.signal),provider=this.models.getProvider(providerId),session=providerId===HCODE_PROVIDER?this.hcodeSession:void 0,stored=session?void 0:await this.credentials.readStored(providerId,{signal});if(providerId===HCODE_PROVIDER){
|
|
1462
|
+
let credential=session?hcodeReferenceCredential(session):stored,checked=await provider?.auth.apiKey?.check?.({ctx:defaultProviderAuthContext(),credential:credential?.type==="api_key"?credential:void 0,signal});return{sources:credential?[{source:session?"runtime":"auth_json",label:this.hcodeFacade.provider.name,type:"api_key",readOnly:!0,effective:!!checked}]:[],storedEffective:!session&&!!checked}}let runtimeKey=this.credentials.getRuntimeApiKey(providerId),extensionKey=this.extensionProviders.get(
|
|
1463
|
+
providerId)?.apiKey,modelsKey=this.config.getProvider(providerId)?.apiKey,configKey=extensionKey??modelsKey,external=this.credentials.isExternalCredential(stored),sources=[],add=(source2,label,effective=!1)=>sources.push({source:source2,label,type:"api_key",readOnly:!0,effective});runtimeKey&&add("runtime","runtime API key",provider?.auth.apiKey!==void 0),stored?.type==="api_key"&&(external||!stored.key?.trim())&&add("auth_json",stored.key?isCommandConfigValue(stored.key)?"command in auth.json":
|
|
1464
|
+
"environment reference in auth.json":(providerId===HUMAIN_GATEWAY_PROVIDER?describeGatewayCredential(stored.env):void 0)??"provider configuration in auth.json"),extensionKey!==void 0&&add("configuration","extension API key"),modelsKey!==void 0&&add("configuration","API key in models.json");let env=stored?.type==="api_key"?stored.env:void 0,ambientNames=providerId==="amazon-bedrock"?["AWS_BEARER_TOKEN_BEDROCK","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_CONT\
|
|
1465
|
+
AINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN","AWS_REGION","AWS_DEFAULT_REGION","AWS_SHARED_CREDENTIALS_FILE","AWS_CONFIG_FILE"]:providerId==="google-vertex"?["GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT","GCLOUD_PROJECT","GOOGLE_CLOUD_LOCATION"]:[],authEnvironmentNames=new Set([...findEnvKeys(providerId)??[],...findEnvKeys(providerId,env)??[],...ambientNames.filter(name=>!!(env?.[name]||process.env[name]))]);for(let name of authEnvironmentNames)
|
|
1466
|
+
add("environment",name);let storedEffective=!1;if(!runtimeKey&&provider){if(stored?.type==="oauth")storedEffective=provider.auth.oauth!==void 0;else if(provider.auth.apiKey)if(external&&stored?.type==="api_key"&&stored.key!==void 0&&isCommandConfigValue(stored.key))sources.find(entry=>entry.source==="auth_json").effective=!0;else if(!stored&&configKey!==void 0){let configured=isCommandConfigValue(configKey)||resolveConfigValue(configKey)!==void 0;sources.find(entry=>entry.source==="configuration").
|
|
1467
|
+
effective=configured}else{let method=(this.nativeExtensionProviders.get(providerId)??this.builtins.get(providerId))?.auth.apiKey,check=method?.check??(this.nativeExtensionProviders.has(providerId)?void 0:method?.resolve),credential=stored?.type==="api_key"?{...stored,key:external&&stored.key!==void 0?resolveConfigValue(stored.key,stored.env):stored.key}:void 0,ctx=defaultProviderAuthContext(),usedEnvironment=new Set,result=check?await check({ctx:{...ctx,env:async name=>{let value=env?.[name]||await ctx.
|
|
1468
|
+
env(name);return value&&authEnvironmentNames.has(name)&&usedEnvironment.add(name),value}},credential,signal}):void 0,native=this.nativeExtensionProviders.has(providerId),source2=native?void 0:result?.source;if(storedEffective=!!stored&&(native?check?!!result&&usedEnvironment.size===0:!!credential?.key:source2==="stored credential"||source2==="stored"||!check&&!!credential?.key),result&&!storedEffective){let selectedNames=source2&&sources.some(entry=>entry.label===source2)?[source2]:[...usedEnvironment],
|
|
1469
|
+
marked=!1;for(let name of selectedNames){let entry=sources.find(entry2=>entry2.source==="environment"&&entry2.label===name);entry&&(entry.effective=!0,marked=!0)}marked||add("environment","ambient credentials",!0)}}}let storedSource=sources.find(entry=>entry.source==="auth_json");return storedSource&&storedEffective&&(storedSource.effective=!0),signal.throwIfAborted(),{sources,storedEffective}}async prepareAccountRequest(providerId,autoSwitch,skipKeys,signal){if(!autoSwitch()||this.credentials.hasRuntimeApiKey(
|
|
1470
|
+
providerId))return;let stored=await this.credentials.readStored(providerId,{signal});if(!stored||this.credentials.isExternalCredential(stored))return;await this.oauthAccountPool.returnToPreferred(providerId,{signal,skipKeys,canActivate:()=>autoSwitch()&&!this.credentials.hasRuntimeApiKey(providerId)})&&await this.synchronizeCredentialState(providerId,"switchAccount",operationSignal(signal))}get oauthAccounts(){return this.oauthAccountPool}getProviderAuthStatus(providerId){if(providerId===HCODE_PROVIDER)
|
|
1471
|
+
return this.hasConfiguredAuth(providerId)?{configured:!0,source:this.hcodeSession?"runtime":"stored"}:{configured:!1};if(this.credentials.hasRuntimeApiKey(providerId))return{configured:!0,source:"runtime"};if(this.snapshot.storedProviders.has(providerId))return{configured:!0,source:"stored"};let configured=configuredRequestAuthStatus(this.config.getProvider(providerId),this.extensionProviders.get(providerId));if(configured)return configured;let check=this.snapshot.auth.get(providerId);return check?
|
|
1472
|
+
{configured:!0,source:"environment",label:check.source}:{configured:!1}}async prepareRequest(model,options,intent){let admission=this.currentAdmission(),currentProvider=this.models.getProvider(model.provider),provider=currentProvider&&(admission||options?.beforeSubmission?{...currentProvider}:currentProvider);if(admission||options?.beforeSubmission){let native=this.nativeExtensionProviders.get(model.provider);if(!intent||!isModelType(model,"chat")||!["anthropic-messages","bedrock-converse-stream",
|
|
1473
|
+
"openai-completions","openai-responses"].includes(model.api)||native!==void 0&&(!provider||!hasHumainNodeAdmissionTransport(native,provider))||this.extensionProviders.get(model.provider)?.streamSimple)throw new SubmissionAdmissionError("unsupported-route")}if(this.assertHcodeModel(model),model.provider===HCODE_PROVIDER&&options&&"transport"in options&&options.transport==="auto"&&(options={...options,transport:"sse"}),model.provider===HCODE_PROVIDER&&this.currentRequestPurpose()==="cache-warming")
|
|
1474
|
+
throw new ModelsError("model_validation","HUMAIN Code account cache warming is disabled.");let signal=model.provider===HCODE_PROVIDER?AbortSignal.any([this.hcodeFacade.signal,...options?.signal?[options.signal]:[]]):options?.signal;if(!provider)throw new ModelsError("provider",`Unknown provider: ${model.provider}`);let resolvedAccount,observesAnthropicLimits=model.provider===ANTHROPIC_PROVIDER_ID,resolution=await this.getAuth(model,{apiKey:options?.apiKey,env:options?.env,signal,onOAuthAccount:options?.
|
|
1475
|
+
onOAuthAccount||observesAnthropicLimits?(provider2,key)=>{resolvedAccount={provider:provider2,key}}:void 0}).catch(error=>{throw resolvedAccount&&options?.onOAuthAccount?.(resolvedAccount.provider,resolvedAccount.key),error});if(!resolution)throw new ModelsError("auth",`Provider is not configured: ${model.provider}`);let{transformHeaders,resolveOnPayload,onPhysicalTarget:_onPhysicalTarget,onOAuthAccount:_onOAuthAccount,...rawProviderOptions}=options??{},providerOptions=rawProviderOptions,requestModel=resolution.
|
|
1476
|
+
auth.baseUrl?{...model,baseUrl:resolution.auth.baseUrl}:model,sessionId="sessionId"in providerOptions&&typeof providerOptions.sessionId=="string"?providerOptions.sessionId:void 0,headers=mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel,sessionId),resolution.auth.headers),providerOptions.headers);transformHeaders&&(headers=await transformHeaders(headers??{})),this.assertHcodeModel(model);let env=resolution.env||providerOptions.env?{...resolution.env??{},...providerOptions.env??{}}:
|
|
1477
|
+
void 0,apiKey=providerOptions.apiKey??resolution.auth.apiKey,attributedAccountKey;(options?.onOAuthAccount||observesAnthropicLimits)&&this.oauthAccountPool.isPooled(model.provider)&&(attributedAccountKey=resolvedAccount?.provider===model.provider&&apiKey===resolution.auth.apiKey?resolvedAccount.key:apiKey?this.oauthAccountPool.getAccountKeyForAccessToken(model.provider,apiKey):void 0,options?.onOAuthAccount?.(model.provider,attributedAccountKey));let callerOnResponse=providerOptions.onResponse,onResponse=observesAnthropicLimits&&
|
|
1478
|
+
attributedAccountKey!==void 0&&!overridesCredentialHeaders(resolution.auth.headers,headers)&&isOfficialAnthropicBaseUrl(requestModel.baseUrl)?async(response,responseModel)=>{this.observeAnthropicLimits(attributedAccountKey,response),await callerOnResponse?.(response,responseModel)}:callerOnResponse,scope=this.currentScope(),tracker=scope||admission?new RequestTracker(scope,requestModel,admission):void 0,gate=admission&&intent?submissionAdmission(admission,requestModel,intent,scope?.purpose):void 0,
|
|
1479
|
+
callerGate=providerOptions.beforeSubmission,beforeSubmission=gate?async observation=>{await callerGate?.(observation),await gate(observation)}:callerGate,callerOnPayload=resolveOnPayload?resolveOnPayload(model):providerOptions.onPayload;return{provider,model:requestModel,options:{...providerOptions,signal,apiKey,headers,env,onPayload:scope&&callerOnPayload?(payload,payloadModel)=>this.requestScope.run(scope,()=>callerOnPayload(payload,payloadModel)):callerOnPayload,...onResponse?{onResponse}:{},
|
|
1480
|
+
...tracker?{onRequest:tracker.hook(providerOptions.onRequest)}:{},...beforeSubmission?{beforeSubmission}:{}},tracker}}observeAnthropicLimits(accountKey,response){try{let snapshot2=parseAnthropicRateLimits(response.headers,Date.now());snapshot2&&this.anthropicRateLimits.record(accountKey,snapshot2)}catch{}}observeRequests(observer,purpose,fn){return this.admissionScope.getStore()?.observers.add(observer),this.requestScope.run({observer,purpose},fn)}async admitRequests(admission,fn){if(this.admissionScope.
|
|
1481
|
+
getStore())throw new SubmissionAdmissionError("unattributed");let scope={admission,observers:new Set},observer=this.requestScope.getStore()?.observer;observer&&scope.observers.add(observer),this.activeAdmissions.add(scope);try{return await this.admissionScope.run(scope,fn)}finally{this.activeAdmissions.delete(scope)}}currentAdmission(){let scope=this.admissionScope.getStore();if(!scope&&this.activeAdmissions.size>0){let observer=this.requestScope.getStore()?.observer;if(!observer||!this.ownerObservers.
|
|
1482
|
+
has(observer))throw new SubmissionAdmissionError("unattributed");for(let active3 of this.activeAdmissions)if(active3.observers.has(observer))throw new SubmissionAdmissionError("unattributed")}return scope?.admission}observeHcodeVersion(version2){this.hcodeFacade.observeVersion(version2)}getHcodeSupportSnapshot(signal){return this.hcodeFacade.supportSnapshot(signal)}hcodeCatalogEmptyReason(){return this.hcodeFacade.provider.catalogEmptyReason()}hcodeCatalogExclusionReason(modelId){return this.hcodeFacade.
|
|
1483
|
+
provider.catalogExclusionReason(modelId)}hcodeCatalogLoaded(){return this.hcodeFacade.provider.catalogLoaded()}probeHcodeLogin(signal){return this.hcodeFacade.probeLogin(signal)}reloadHcodeAccount(signal){return this.enqueueCredentialOperation(HCODE_PROVIDER,signal,async()=>{if(this.hcodeSession&&this.hcodeFacade.persistence(this.hcodeSession)==="session")return!1;let stored=await this.credentials.readStored(HCODE_PROVIDER,{signal});return this.hcodeFacade.adopt(stored)?(this.hcode.account.status(
|
|
1484
|
+
this.hcode.environmentId)&&(this.hcodeSession=void 0),await this.synchronizeCredentialState(HCODE_PROVIDER,stored?"login":"logout",signal),!0):!1})}hcodeSignedInElsewhere(){return this.hcodeFacade.signedInElsewhere()}hcodeAccountEmail(expected){return this.hcodeFacade.accountEmail(expected)}async shutdownHcodeSession(signal){try{return await this.hcodeFacade.shutdown(signal)}finally{this.credentials.clearHcodeSessionReference()}}shutdownOwnedHcodeSession(signal){return this.sessionOwned?this.shutdownHcodeSession(
|
|
1485
|
+
signal):Promise.resolve({remoteRevocation:"not-needed"})}dispose(){this.credentials.clearHcodeSessionReference(),this.hcodeFacade.dispose()}addOwnerObserver(observer){return this.ownerObservers.add(observer),()=>{this.ownerObservers.delete(observer)&&this.sessionOwned&&this.ownerObservers.size===0&&this.dispose()}}currentScope(){let scope=this.requestScope.getStore();if(scope||this.ownerObservers.size===0)return scope;if(this.ownerObservers.size===1){let[observer]=this.ownerObservers;return{observer,
|
|
1486
|
+
purpose:"chat"}}let[first]=this.ownerObservers;first?.onUnattributed&&swallow(()=>first.onUnattributed?.())}currentRequestPurpose(){return this.requestScope.getStore()?.purpose}withRequestPurpose(purpose,fn){let scope=this.currentScope();return scope?this.observeRequests(scope.observer,purpose,fn):fn()}assertHcodeModel(model){if(model.provider===HCODE_PROVIDER&&this.getPhysicalModel(HCODE_PROVIDER,model.id)!==model)throw new ModelsError("model_validation","HUMAIN Code account approved model chan\
|
|
1487
|
+
ged or is unavailable.")}guardHcodeTimeout(model,stream,actualModel,onTimeout){return model.provider!==HCODE_PROVIDER&&!isVirtualModel(model)?stream:lazyStream(model,async()=>({async*[Symbol.asyncIterator](){for await(let event of stream)event.type==="error"&&actualModel().provider===HCODE_PROVIDER&&event.error.diagnostics?.some(entry=>entry.type==="provider_no_progress_timeout")&&(onTimeout(),event.error.errorMessage="HUMAIN Code request unavailable. Do not automatically resend.",event.error.diagnostics=
|
|
1488
|
+
[{type:"provider_http_error",timestamp:Date.now(),details:{retryable:!1}}]),yield event},result:()=>stream.result()}))}inferenceObservation(model,started){let native=this.getPhysicalModel(model.provider,model.id)===model&&(model.provider===HCODE_PROVIDER||this.defaultBuiltins.has(model.provider)&&!this.nativeExtensionProviders.has(model.provider)&&!this.extensionProviders.has(model.provider)&&!this.config.getProvider(model.provider)),provider=native?model.provider:"other",id2=native&&model.provider!==
|
|
1489
|
+
HCODE_PROVIDER?model.id:"other";return(message,submissions,observedFailure)=>{let usage=message?.usage,known=usage&&!usage.usageIncomplete&&usage.totalTokens>0,token=value=>known&&value!==void 0&&Number.isInteger(value)&&value>=0&&value<=2147483647?value:null,outcome=message?.stopReason==="aborted"?"cancelled":message?.stopReason==="stop"||message?.stopReason==="toolUse"?usage?.usageIncomplete?"unknown":"success":"failure",retries=Math.max(0,submissions-1);if(this.metadata.inference(provider,id2,
|
|
1490
|
+
{durationMs:Math.min(2147483647,Math.round(performance.now()-started)),inputTokens:token(usage?.input),outputTokens:token(usage?.output),cacheReadTokens:token(usage?.cacheRead),cacheWriteTokens:token(usage?.cacheWrite),retries,outcome}),outcome!=="success"){let http=message?.diagnostics?.findLast(entry=>entry.type==="provider_http_error"),hcode=http?.details?.hcode,status=hcode&&typeof hcode=="object"&&"status"in hcode?hcode.status:http?.details?.status,code=observedFailure??(message?.diagnostics?.
|
|
1491
|
+
some(entry=>entry.type==="provider_no_progress_timeout")?"timeout":status===401?"auth":status===403?"approval":status===429?"quota":message?.stopReason==="length"?"invalid":"transport");this.metadata.failure("prompt",code,retries,outcome)}}}trackStream(stream,tracker,observe){return stream.result().then(message=>{observe?.(message),tracker()?.settleMessage(message)},()=>{observe?.(void 0),tracker()?.settleFailure(!1)}),stream}stream(model,context,options){let transcript=normalizeContext(context),
|
|
1492
|
+
tracker,observe=this.inferenceObservation(model,performance.now()),observedFailure,submissions=0,callerRequest=options?.onRequest,onRequest=async request2=>{submissions++,await callerRequest?.(request2)};return this.trackStream(this.guardHcodeTimeout(model,streamWithProgressTimeout(model,async signal=>{assertChatModel(model);let intent=admissionIntent(model,options);this.currentAdmission()&&(intent.requiredImageCount=assertAdmittedModelInput(model,context));let prepared=await this.prepareRequest(
|
|
1493
|
+
model,{...options,signal,onRequest},intent);return tracker=prepared.tracker,signal.throwIfAborted(),prepared.provider.stream(prepared.model,transcript,prepared.options)},options),()=>model,()=>{observedFailure="timeout"}),()=>tracker,message=>observe(message,submissions,observedFailure))}complete(model,context,options){return drainStream(this.stream(model,context,options))}streamSimple(model,context,options){let transcript=normalizeContext(context),tracker,requestModel=model,started=performance.
|
|
1494
|
+
now(),observe=this.inferenceObservation(model,started),observedFailure,submissions=0,callerRequest=options?.onRequest;return options={...options,onRequest:async request2=>{submissions++,await callerRequest?.(request2)}},this.trackStream(this.guardHcodeTimeout(model,streamWithProgressTimeout(model,async signal=>{let requestOptions=options;if(isVirtualModel(model)){let route=await this.resolveModel(model,transcript.messages,{reason:"direct",thinkingLevel:options?.reasoning??"off",signal});signal.throwIfAborted();
|
|
1495
|
+
let{maxTokens:limit}=route.model,maxTokens=options?.maxTokens&&limit>0?Math.min(options.maxTokens,limit):options?.maxTokens,reasoning=route.thinkingLevel==="off"?void 0:route.thinkingLevel,{apiKey,headers,env,...rest}=options??{},auth=route.model.provider===model.provider?{apiKey,headers,env}:{};requestModel=route.model,requestOptions={...rest,...auth,maxTokens,reasoning}}observe=this.inferenceObservation(requestModel,started),requestOptions?.onPhysicalTarget?.(requestModel),assertChatModel(requestModel);
|
|
1496
|
+
let intent=admissionIntent(model,options);this.currentAdmission()&&(intent.requiredImageCount=assertAdmittedModelInput(requestModel,context));let prepared=await this.prepareRequest(requestModel,{...requestOptions,signal},intent);return tracker=prepared.tracker,signal.throwIfAborted(),prepared.provider.streamSimple(prepared.model,transcript,prepared.options)},options),()=>requestModel,()=>{observedFailure="timeout"}),()=>tracker,message=>observe(message,submissions,observedFailure))}completeSimple(model,context,options){
|
|
1497
|
+
return drainStream(this.streamSimple(model,context,options))}streamDeferred(model,handle,options){let tracker;return this.trackStream(lazyStream(model,async()=>{assertChatModel(model);let prepared=await this.prepareRequest(model,options);if(tracker=prepared.tracker,!prepared.provider.fetchDeferred)throw new ModelsError("provider",`Provider ${model.provider} does not support deferred responses`);return prepared.provider.fetchDeferred(prepared.model,handle,prepared.options)},void 0,options?.signal),
|
|
1498
|
+
()=>tracker)}async fetchDeferred(model,handle,options){return drainStream(this.streamDeferred(model,handle,options))}async cancelDeferred(model,handle,options){assertChatModel(model);let prepared=await this.prepareRequest(model,options);if(!prepared.provider.cancelDeferred)throw new ModelsError("provider",`Provider ${model.provider} does not support deferred responses`);await prepared.provider.cancelDeferred(prepared.model,handle,prepared.options)}async generateImages(model,context,options){let tracker;
|
|
1499
|
+
try{assertImageModel(model);let prepared=await this.prepareRequest(model,options);if(tracker=prepared.tracker,!prepared.provider.generateImages)throw new ModelsError("provider",`Provider ${model.provider} does not support image generation`);let result=await prepared.provider.generateImages(prepared.model,context,prepared.options);return tracker?.settleResult(result),result}catch(error){return tracker?.settleFailure(options?.signal?.aborted===!0),imageErrorResult(model,error,options?.signal?.aborted)}}async classify(model,context,options){
|
|
1500
|
+
let tracker;try{assertClassifierModel(model),assertClassifierInputSupported(model,context);let prepared=await this.prepareRequest(model,options);if(tracker=prepared.tracker,!prepared.provider.classify)throw new ModelsError("provider",`Provider ${model.provider} does not support classification`);let result=await prepared.provider.classify(prepared.model,context,prepared.options);return tracker?.settleResult(result),result}catch(error){return tracker?.settleFailure(options?.signal?.aborted===!0),classifierErrorResult(
|
|
1501
|
+
model,error,options?.signal?.aborted)}}login(providerId,type,interaction,options){let signal=operationSignal(interaction.signal),started=performance.now();return this.enqueueCredentialOperation(providerId,signal,async()=>{let provider=this.models.getProvider(providerId);if(!provider)throw new ModelsError("provider",`Unknown provider: ${providerId}`);let method=type==="oauth"?provider.auth.oauth:provider.auth.apiKey;if(!method?.login)throw new ModelsError("auth",`${provider.name} does not support\
|
|
1502
|
+
${type} login`);if(options?.accountKey!==void 0){let selected=(await this.oauthAccountPool.listAccounts(providerId,{signal})).find(account2=>account2.key===options.accountKey);if(!selected||selected.credential.type!==type)throw new ModelsError("auth","Account is no longer available for reauthentication")}providerId===HCODE_PROVIDER&&await this.hcodeFacade.recover(signal);let nativeReference=providerId===HCODE_PROVIDER?await this.credentials.readStored(providerId,{signal}):void 0;providerId!==HCODE_PROVIDER&&
|
|
1503
|
+
await this.oauthAccountPool.adoptCurrentAccount(providerId,{signal});let promptCancelled=!1,login;try{let input={...interaction,signal,prompt:async prompt=>{try{return await interaction.prompt(prompt)}catch{throw(signal.aborted||!prompt.signal?.aborted)&&(promptCancelled=!0),new LoginCancellationError}}};login=await raceWithAbortSignal(providerId===HCODE_PROVIDER?this.hcodeFacade.login(input,signal,async reference=>{let candidate=hcodeReferenceCredential(reference);try{await this.credentials.modify(
|
|
1504
|
+
providerId,async current=>{if(!sameCredential(current,nativeReference))throw new SafeCredentialError(HCODE_LOGIN_FAILURES.accountChanged);return candidate},{signal})}catch(error){throw nativeReference?await this.credentials.modify(providerId,async current=>sameCredential(current,candidate)?nativeReference:void 0):await this.credentials.deleteStored(providerId,{ifCurrent:current=>sameCredential(current,candidate)}),error}}).then(hcodeReferenceCredential):method.login(input,options),signal)}catch(error){
|
|
1505
|
+
throw promptCancelled||signal.aborted?new LoginCancellationError:error}if(promptCancelled)throw new LoginCancellationError;let poolable=login.type==="oauth"||!!login.key?.trim();if(options?.accountKey!==void 0&&!poolable)throw new ModelsError("auth","Reauthentication must return a literal account credential");let account=poolable?await this.oauthAccountPool.addAccount(providerId,login,{signal,key:options?.accountKey}):void 0,credential=account?.credential??login;if(providerId===HCODE_PROVIDER){let reference=this.
|
|
1506
|
+
hcode.account.status(this.hcode.environmentId);if(!reference||login.type!=="api_key")throw new ModelsError("auth","HUMAIN Code account changed.");if(this.hcodeFacade.persistence(reference)==="session")return this.hcodeSession=reference,this.credentials.setHcodeSessionReference(login),await this.synchronizeCredentialState(providerId,"login",signal),login;this.hcodeSession=void 0}else account||await commitLoginCredential(this.credentials.accountStore,providerId,login,signal);return await this.synchronizeCredentialState(
|
|
1507
|
+
providerId,"login",signal),credential}).then(credential=>(this.metadata.feature("login",Math.round(performance.now()-started),"success"),credential),error=>{let outcome=signal.aborted||error instanceof LoginCancellationError?"cancelled":"failure";throw this.metadata.feature("login",Math.round(performance.now()-started),outcome),this.metadata.failure("login",error instanceof CredentialSynchronizationError?"storage":"auth",0,outcome),providerId===HCODE_PROVIDER&&signal.aborted&&!(error instanceof CredentialSynchronizationError)?
|
|
1508
|
+
new LoginCancellationError:error})}async logout(providerId,options={}){await this.logoutWithStatus(providerId,options)}async deleteObservedStoredCredential(providerId,observed,signal){providerId===HCODE_PROVIDER&&await this.hcodeFacade.logoutStored(observed,signal);let status="changed";return await this.credentials.deleteStored(providerId,{signal,ifCurrent:latest=>sameCredential(latest,observed)?(status="removed",!0):!1}),status}prepareStoredCredentialRemoval(providerId,options){return this.protectCredentialOperation(
|
|
1509
|
+
(async()=>{let observed=structuredClone(await this.credentials.readStored(providerId,options));if(!(!observed||await this.oauthAccountPool.getCurrentAccount(providerId,options)))return removalOptions=>{let signal=operationSignal(removalOptions?.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{let status=await this.deleteObservedStoredCredential(providerId,observed,signal);return status==="removed"&&await this.synchronizeCredentialState(providerId,"logout",signal),status})}})(),
|
|
1510
|
+
options?.signal,!1)}logoutWithStatus(providerId,options={}){let signal=operationSignal(options.signal);return this.enqueueCredentialOperation(providerId,signal,async()=>{if(providerId===HCODE_PROVIDER&&await this.hcodeFacade.recover(signal),providerId===HCODE_PROVIDER&&this.hcodeSession){let reference=this.hcodeSession,retained=this.hcodeFacade.persistence(reference)==="session";try{retained&&await this.hcode.account.logout(reference,signal)}finally{this.credentials.clearHcodeSessionReference()}
|
|
1511
|
+
return await this.synchronizeCredentialState(providerId,"logout",signal),retained?"removed":"unmatched"}let observed=options.accountKey===void 0?structuredClone(await this.credentials.modify(providerId,async()=>{},{signal})):void 0;if(this.credentials.isExternalCredential(observed)||observed?.type==="api_key"&&!observed.key?.trim()||providerId==="openai-codex"&&observed?.type==="oauth"&&!this.oauthAccountPool.getAccountIdentity(providerId,observed)){let status2=await this.deleteObservedStoredCredential(
|
|
1512
|
+
providerId,observed,signal);return status2==="removed"&&await this.synchronizeCredentialState(providerId,"logout",signal),status2}let stored=options.accountKey===void 0?observed:await this.credentials.readStored(providerId,{signal}),legacyUnmatchedCodex=providerId==="openai-codex"&&stored?.type==="oauth"&&!this.oauthAccountPool.getAccountIdentity(providerId,stored),selectedLegacyCurrent=legacyUnmatchedCodex&&options.accountKey?.startsWith("account-")&&(await this.oauthAccountPool.getCurrentAccount(
|
|
1513
|
+
providerId,{signal}))?.key===options.accountKey,status=(legacyUnmatchedCodex&&!selectedLegacyCurrent?await this.oauthAccountPool.remove(providerId,options.accountKey,{signal}):await this.oauthAccountPool.removeAccount(providerId,options.accountKey,{signal,ifCurrent:options.accountKey===void 0?latest=>sameCredential(latest,observed):void 0})).status;if(status==="unmatched"){if(options.accountKey!==void 0)return status;status=await this.deleteObservedStoredCredential(providerId,observed,signal)}return status===
|
|
1514
|
+
"removed"&&await this.synchronizeCredentialState(providerId,"logout",signal),status})}pendingRegistrationRefreshes=new Set;registeringWithoutRefresh=!1;registerWithoutRefresh(register){let previous=this.registeringWithoutRefresh;this.registeringWithoutRefresh=!0;try{register()}finally{this.registeringWithoutRefresh=previous}}queueRegistrationRefresh(){if(this.registeringWithoutRefresh)return;let p=this.refreshInternal({allowNetwork:!1},{fromRegistration:!0}).then(()=>{},()=>{});this.pendingRegistrationRefreshes.
|
|
1515
|
+
add(p),p.finally(()=>this.pendingRegistrationRefreshes.delete(p))}refresh(options={}){return this.refreshInternal(options,{fromRegistration:!1})}async refreshInternal(options,{fromRegistration}){!fromRegistration&&this.pendingRegistrationRefreshes.size>0&&await Promise.allSettled([...this.pendingRegistrationRefreshes]);let config=await ModelConfig.load(this.modelsPath);if(this.assertConfiguration(config),this.config=config,this.configureRadiusProviders(),options.providers){for(let providerId of new Set(
|
|
1516
|
+
options.providers))this.recomposeProvider(providerId);this.updateModelSnapshot()}else this.rebuildProviders();let refreshOptions={...options,allowNetwork:options.allowNetwork??this.modelNetworkEnabled},result=await this.models.refresh(refreshOptions)??{aborted:refreshOptions.signal?.aborted??!1,errors:new Map},errors=new Map(result.errors);if(this.updateModelSnapshot(),options.providers)await Promise.all([...new Set(options.providers)].map(async providerId=>{try{await this.refreshProviderAvailability(
|
|
1517
|
+
providerId,operationSignal(options.signal))}catch(error){options.signal?.aborted||errors.set(providerId,error instanceof Error?error:new Error(String(error)))}}));else try{await this.queueAvailabilityRefresh(options.signal)}catch{}return{aborted:result.aborted||(options.signal?.aborted??!1),errors}}registerNativeProvider(provider){if(assertCustomProviderId(provider.id),!provider.id.trim())throw new Error("Provider id must not be empty.");this.extensionProviders.delete(provider.id),this.nativeExtensionProviders.
|
|
1518
|
+
set(provider.id,provider),this.recomposeProvider(provider.id),this.updateModelSnapshot(),this.markProvisionallyConfigured(provider.id,configuredRequestAuthStatus(this.config.getProvider(provider.id),void 0),provider.auth.oauth&&!provider.auth.apiKey?"oauth":"api_key"),this.queueRegistrationRefresh()}markProvisionallyConfigured(providerId,configuredStatus,type){if(!this.snapshot.storedProviders.has(providerId)&&!configuredStatus?.configured)return;let configuredProviders=new Set(this.snapshot.configuredProviders).
|
|
1519
|
+
add(providerId),auth=new Map(this.snapshot.auth);auth.get(providerId)||auth.set(providerId,{type,source:"configured provider"}),this.snapshot={...this.snapshot,auth,configuredProviders,available:this.snapshot.all.ofProviders(configuredProviders)}}registerProvider(providerId,config){assertCustomProviderId(providerId),this.configurationGuard?.({[providerId]:config}),validateExtensionProvider(providerId,this.builtins.get(providerId),this.config.getProvider(providerId),config),this.nativeExtensionProviders.
|
|
1520
|
+
delete(providerId);let effective={...this.extensionProviders.get(providerId)};for(let[key,value]of Object.entries(config))value!==void 0&&(effective[key]=value);this.extensionProviders.set(providerId,effective),this.recomposeProvider(providerId),this.updateModelSnapshot(),this.markProvisionallyConfigured(providerId,configuredRequestAuthStatus(this.config.getProvider(providerId),effective),effective.oauth&&!effective.apiKey?"oauth":"api_key"),this.queueRegistrationRefresh()}unregisterProvider(providerId){
|
|
1521
|
+
assertCustomProviderId(providerId),this.extensionProviders.delete(providerId),this.nativeExtensionProviders.delete(providerId),this.recomposeProvider(providerId),this.updateModelSnapshot(),this.queueRegistrationRefresh()}registerVirtualModel(definition){let{provider:providerId,id:id2}=definition;if(assertCustomProviderId(providerId),!providerId.trim()||!id2.trim())throw new Error("Virtual model provider and id must not be empty.");let existing=this.models.getModel(providerId,id2);if(existing&&!isVirtualModel(
|
|
1522
|
+
existing))throw new Error(`Virtual model ${providerId}/${id2} conflicts with a physical model.`);let models=this.virtualModels.get(providerId)??new Map;if(models.set(id2,{model:createVirtualModel(definition),route:request2=>definition.route(request2)}),this.virtualModels.set(providerId,models),!this.recomposeProvider(providerId)&&!this.snapshot.configuredProviders.has(providerId)){let auth=new Map(this.snapshot.auth).set(providerId,{type:"api_key",source:"virtual"}),configuredProviders=new Set(this.
|
|
1523
|
+
snapshot.configuredProviders).add(providerId);this.snapshot={...this.snapshot,auth,configuredProviders}}this.updateModelSnapshot(),this.queueRegistrationRefresh()}unregisterVirtualModel(providerId,id2){assertCustomProviderId(providerId);let models=this.virtualModels.get(providerId);models?.delete(id2)&&(models.size===0&&this.virtualModels.delete(providerId),this.recomposeProvider(providerId),this.updateModelSnapshot(),this.queueRegistrationRefresh())}async resolveModel(model,messages,options){let name=`\
|
|
1524
|
+
Virtual model ${model.provider}/${model.id}`,virtual=this.virtualModels.get(model.provider)?.get(model.id);if(!virtual)throw new Error(`${name} is not registered.`);let{failed,deferThinkingClamp,...request2}=options,latest=findLatestResponse(messages),previousModel=latest&&this.getPhysicalModel(latest.provider,latest.model),failedModel=failed&&this.getPhysicalModel(failed.provider,failed.model),route=await virtual.route({...request2,model,previous:previousModel&&{model:previousModel,thinkingLevel:latest?.
|
|
1525
|
+
thinkingLevel},failed:failedModel&&failed&&{model:failedModel,thinkingLevel:failed.thinkingLevel,message:failed},messages});this.assertHcodeModel(route.model);let target=this.getPhysicalModel(route.model.provider,route.model.id),routed=`${name} routed to ${route.model.provider}/${route.model.id}`;if(!target)throw new Error(`${routed}, which is not a physical model.`);if(!this.hasConfiguredAuth(target.provider))throw new Error(`${routed}, which has no credentials.`);return deferThinkingClamp?{...route,
|
|
1526
|
+
model:target}:{model:target,thinkingLevel:clampThinkingLevel(target,route.thinkingLevel),state:route.state}}getPhysicalModel(providerId,modelId){let model=this.models.getModel(providerId,modelId);if(!(model?.provider===HCODE_PROVIDER&&providerId!==HCODE_PROVIDER))return model&&!isVirtualModel(model)?model:void 0}};import{open as open2}from"node:fs/promises";var IMAGE_TYPE_SNIFF_BYTES=4100,PNG_SIGNATURE=[137,80,78,71,13,10,26,10];function detectSupportedImageMimeType(buffer){return startsWith(buffer,[255,216,255])?buffer[3]===247?null:"image/jpeg":startsWith(buffer,PNG_SIGNATURE)?isPng(buffer)&&!isAnimatedPng(buffer)?"image/png":null:startsWithAscii(buffer,0,"GIF87a")||startsWithAscii(buffer,0,"GIF89a")?"image/gif":startsWithAscii(buffer,0,"RIFF")&&startsWithAscii(buffer,8,"WEBP")?"image/webp":startsWithAscii(
|
|
1516
1527
|
buffer,0,"BM")&&isBmp(buffer)?"image/bmp":null}async function detectSupportedImageMimeTypeFromFile(filePath){let fileHandle=await open2(filePath,"r");try{let buffer=Buffer.alloc(IMAGE_TYPE_SNIFF_BYTES),{bytesRead}=await fileHandle.read(buffer,0,IMAGE_TYPE_SNIFF_BYTES,0);return detectSupportedImageMimeType(buffer.subarray(0,bytesRead))}finally{await fileHandle.close()}}function isPng(buffer){return buffer.length>=16&&readUint32BE(buffer,PNG_SIGNATURE.length)===13&&startsWithAscii(buffer,12,"IHDR")}
|
|
1517
1528
|
function isAnimatedPng(buffer){let offset=PNG_SIGNATURE.length;for(;offset+8<=buffer.length;){let chunkLength=readUint32BE(buffer,offset),chunkTypeOffset=offset+4;if(startsWithAscii(buffer,chunkTypeOffset,"acTL"))return!0;if(startsWithAscii(buffer,chunkTypeOffset,"IDAT"))return!1;let nextOffset=offset+8+chunkLength+4;if(nextOffset<=offset||nextOffset>buffer.length)return!1;offset=nextOffset}return!1}function isBmp(buffer){if(buffer.length<26)return!1;let declaredFileSize=readUint32LE(buffer,2),pixelDataOffset=readUint32LE(
|
|
1518
1529
|
buffer,10),dibHeaderSize=readUint32LE(buffer,14);if(declaredFileSize!==0&&declaredFileSize<26||pixelDataOffset<14+dibHeaderSize||declaredFileSize!==0&&pixelDataOffset>=declaredFileSize)return!1;let colorPlanes,bitsPerPixel;if(dibHeaderSize===12)colorPlanes=readUint16LE(buffer,22),bitsPerPixel=readUint16LE(buffer,24);else if(dibHeaderSize>=40&&dibHeaderSize<=124){if(buffer.length<30)return!1;colorPlanes=readUint16LE(buffer,26),bitsPerPixel=readUint16LE(buffer,28)}else return!1;return colorPlanes===
|
|
@@ -2177,7 +2188,7 @@ exitCode===0?1:exitCode,killed,truncated}}var ENABLED=process.env.PI_TIMING==="1
|
|
|
2177
2188
|
let printableTimings=timings.filter(timing=>timing.ms>=0);if(printableTimings.length!==0){console.error(`
|
|
2178
2189
|
--- ${title} ---`);for(let t of printableTimings)console.error(` ${t.label}: ${t.ms}ms`);console.error(` TOTAL: ${printableTimings.reduce((a,b)=>a+b.ms,0)}ms`),console.error(`${"-".repeat(title.length+8)}
|
|
2179
2190
|
`)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}var loadJitiBunLoader=()=>import("./jiti-bun-loader-VSLLRCSD.js");var require2=createRequire(import.meta.url),isNodeSeaBinary="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,isTypeScriptSourceRuntime=!isBunBinary&&path.extname(fileURLToPath(import.meta.url))===".ts",usesEmbeddedModules=isBunBinary||isNodeSeaBinary||isBundledNode,createJitiPromise;function getCreateJiti(){return createJitiPromise??=(isBunBinary?loadJitiBunLoader():usesEmbeddedModules?import("./jiti-static-loader-7OZNBOCI.js"):import("./jiti-loader-TMJL6S2D.js")).
|
|
2180
|
-
then(module=>module.createJiti),createJitiPromise}var virtualModulesPromise;function getVirtualModules(){return virtualModulesPromise??=import("./virtual-modules-
|
|
2191
|
+
then(module=>module.createJiti),createJitiPromise}var virtualModulesPromise;function getVirtualModules(){return virtualModulesPromise??=import("./virtual-modules-47MGUPYN.js").then(module=>({...module.VIRTUAL_MODULES,"@humain/humain-code":module.VIRTUAL_MODULES["@earendil-works/pi-coding-agent"]})),virtualModulesPromise}var _aliases=null;function getAliases(){if(_aliases)return _aliases;let __dirname=path.dirname(fileURLToPath(import.meta.url)),packageIndex=path.resolve(__dirname,"../..","index.js"),
|
|
2181
2192
|
typeboxEntry=require2.resolve("typebox"),typeboxCompileEntry=require2.resolve("typebox/compile"),typeboxValueEntry=require2.resolve("typebox/value"),packagesRoot=path.resolve(__dirname,"../../../../"),resolveWorkspaceOrImport=(workspaceRelativePath,specifier)=>{let workspacePath=path.join(packagesRoot,workspaceRelativePath);return fs.existsSync(workspacePath)?workspacePath:fileURLToPath(import.meta.resolve(specifier))},piCodingAgentEntry=packageIndex,piAgentCoreEntry=resolveWorkspaceOrImport("ag\
|
|
2182
2193
|
ent/dist/index.js","@earendil-works/pi-agent-core"),piTuiEntry=resolveWorkspaceOrImport("tui/dist/index.js","@earendil-works/pi-tui"),piAiCompatEntry=path.resolve(__dirname,"pi-ai-extension-view.js"),piAiModelsEntry=resolveWorkspaceOrImport("ai/dist/models.js","@earendil-works/pi-ai/models"),piAiOauthEntry=resolveWorkspaceOrImport("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),piAiProvidersEntry=resolveWorkspaceOrImport("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return _aliases=
|
|
2183
2194
|
{"@humain/humain-code":piCodingAgentEntry,"@earendil-works/pi-coding-agent":piCodingAgentEntry,"@earendil-works/pi-agent-core":piAgentCoreEntry,"@earendil-works/pi-tui":piTuiEntry,"@earendil-works/pi-ai/providers/all":piAiProvidersEntry,"@earendil-works/pi-ai/compat":piAiCompatEntry,"@earendil-works/pi-ai/models":piAiModelsEntry,"@earendil-works/pi-ai/oauth":piAiOauthEntry,"@earendil-works/pi-ai":piAiCompatEntry,"@mariozechner/pi-coding-agent":piCodingAgentEntry,"@mariozechner/pi-agent-core":piAgentCoreEntry,
|
|
@@ -2247,13 +2258,13 @@ getCodexResetAccount(options);if(target)return{accountId:target.accountId,detail
|
|
|
2247
2258
|
target.account,{signal:options.signal,fetch:options.fetch,accountPool:this.runtime.oauthAccounts})}catch{}return result}async getAnthropicUsage(options){let oauth=this.runtime.getProvider(ANTHROPIC_USAGE_PROVIDER_ID)?.auth.oauth,account;try{account=await this.runtime.oauthAccounts.prepareUsageAccount(ANTHROPIC_USAGE_PROVIDER_ID,options?.accountKey,async credential=>{if(!oauth||!credential.refresh)return"refresh_failed";try{return await oauth.refresh(credential,AbortSignal.timeout(8e3))}catch(error){
|
|
2248
2259
|
return error instanceof OAuthRefreshRejectedError?"refresh_rejected":"refresh_failed"}},{signal:options?.signal})}catch{return{status:"unavailable",reason:options?.signal?.aborted?"timeout":"refresh_failed"}}return typeof account=="string"?{status:"unavailable",reason:account}:account?fetchAnthropicSubscriptionUsage(account,options):void 0}registerProvider(providerOrName,config){if(typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");
|
|
2249
2260
|
this.runtime.registerProvider(providerOrName,config);return}this.runtime.registerNativeProvider(providerOrName)}unregisterProvider(providerName){this.runtime.unregisterProvider(providerName)}registerVirtualModel(definition){this.runtime.registerVirtualModel(definition)}unregisterVirtualModel(providerName,id2){this.runtime.unregisterVirtualModel(providerName,id2)}getRegisteredProviderConfig(providerName){return this.runtime.getRegisteredProviderConfig(providerName)}getRegisteredNativeProvider(providerName){
|
|
2250
|
-
return this.runtime.getRegisteredNativeProvider(providerName)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}};var intents=new WeakMap;function captureModelSelectionIntent(owner,intent){intents.has(owner)||intents.set(owner,intent)}function getModelSelectionIntent(owner){return intents.get(owner)??{kind:"fresh"}}function markModelSelectionChosen(owner){intents.set(owner,{kind:"chosen",source:"selection"})}var RunFailure=class extends Error{classification;constructor(classification,message){super(message),this.name="RunFailure",this.classification=classification}},ModelPreflightFailure=class extends RunFailure{providerId;accountKey;resetsAt;constructor(providerId,accountKey,resetsAt){super("provider"
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
test(message)||status===void 0&&(/\b(?:unauthorized|unauthenticated)\b/i.test(message)||/\b(?:HTTP(?:\/\d(?:\.\d)?)?|status(?: code)?)[:\s]+(?:401|403)\b/i.test(message))?"auth":/timed?\s*out|timeout|deadline exceeded|ETIMEDOUT/i.test(message)?"timeout":status===void 0&&/(?:oauth|token).*(?:expir|refresh|invalid)|no api key|authentication failed|not configured/i.test(message)?"auth":fallback}function classifyAssistantFailure(message){let details=message.
|
|
2254
|
-
"provider_http_error")?.details,hcode=details?.hcode,status=httpStatus(hcode&&typeof hcode=="object"&&"status"in hcode?hcode.status:void 0)??httpStatus(details?.status);return status===401||status===403?"auth":classifyFailureText(message.errorMessage??"",status,"provider")}function failureOutcome(error,fallback){return outcomeForFailureClass(classifyRunFailure(error,fallback))}function outcomeForFailureClass(failureClass){return{type:"run_end",failureClass,
|
|
2255
|
-
function completionEvidence(event){return event.type==="acceptance_settled"&&event.completion?{completion:event.completion,criteria:event.criteria}:void 0}function settledOutcome(messages,evidence){let assistant=messages.findLast(message=>message.role==="assistant");return assistant?.stopReason==="error"?outcomeForFailureClass(classifyAssistantFailure(assistant)):assistant?.stopReason==="aborted"?failureOutcome(new RunFailure("timeout","Run
|
|
2256
|
-
|
|
2261
|
+
return this.runtime.getRegisteredNativeProvider(providerName)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}};var intents=new WeakMap;function captureModelSelectionIntent(owner,intent){intents.has(owner)||intents.set(owner,intent)}function getModelSelectionIntent(owner){return intents.get(owner)??{kind:"fresh"}}function markModelSelectionChosen(owner){intents.set(owner,{kind:"chosen",source:"selection"})}var RunFailure=class extends Error{classification;constructor(classification,message){super(message),this.name="RunFailure",this.classification=classification}},ModelPreflightFailure=class extends RunFailure{providerId;accountKey;resetsAt;constructor(providerId,accountKey,resetsAt,accountDescription){super("provider",`Model preflight usage limit reached${accountDescription?` for ${accountDescription}`:""}. Check provider quota or billing.`),this.providerId=providerId,this.accountKey=accountKey,this.
|
|
2262
|
+
resetsAt=resetsAt}};function classifyRunFailure(error,fallback="provider"){if(error instanceof RunFailure)return error.classification;let status;if(error!==null&&typeof error=="object"){if("code"in error&&error.code==="auth"||(status=errorStatus(error),status===401||status===403))return"auth";if("name"in error&&error.name==="TimeoutError")return"timeout";if("code"in error&&error.code==="oauth"&&"cause"in error&&error.cause!==null&&typeof error.cause=="object"){let cause=error.cause,causeStatus=errorStatus(
|
|
2263
|
+
cause);if(causeStatus===401||causeStatus===403)return"auth";if("name"in cause&&cause.name==="TimeoutError")return"timeout"}}return classifyFailureText(error instanceof Error?error.message:String(error),status,fallback)}function errorStatus(error){return httpStatus("status"in error?error.status:"statusCode"in error?error.statusCode:void 0)}function httpStatus(value){return typeof value=="number"&&Number.isInteger(value)&&value>=100&&value<=599?value:void 0}function classifyFailureText(message,status,fallback){
|
|
2264
|
+
return/\b(?:invalid_api_key|invalid_grant)\b/i.test(message)||status===void 0&&(/\b(?:unauthorized|unauthenticated)\b/i.test(message)||/\b(?:HTTP(?:\/\d(?:\.\d)?)?|status(?: code)?)[:\s]+(?:401|403)\b/i.test(message))?"auth":/timed?\s*out|timeout|deadline exceeded|ETIMEDOUT/i.test(message)?"timeout":status===void 0&&/(?:oauth|token).*(?:expir|refresh|invalid)|no api key|authentication failed|not configured/i.test(message)?"auth":fallback}function classifyAssistantFailure(message){let details=message.
|
|
2265
|
+
diagnostics?.findLast(entry=>entry.type==="provider_http_error")?.details,hcode=details?.hcode,status=httpStatus(hcode&&typeof hcode=="object"&&"status"in hcode?hcode.status:void 0)??httpStatus(details?.status);return status===401||status===403?"auth":classifyFailureText(message.errorMessage??"",status,"provider")}function failureOutcome(error,fallback){return outcomeForFailureClass(classifyRunFailure(error,fallback))}function outcomeForFailureClass(failureClass){return{type:"run_end",failureClass,
|
|
2266
|
+
exitCode:TERMINAL_FAILURE_EXIT_CODES[failureClass]}}function completionEvidence(event){return event.type==="acceptance_settled"&&event.completion?{completion:event.completion,criteria:event.criteria}:void 0}function settledOutcome(messages,evidence){let assistant=messages.findLast(message=>message.role==="assistant");return assistant?.stopReason==="error"?outcomeForFailureClass(classifyAssistantFailure(assistant)):assistant?.stopReason==="aborted"?failureOutcome(new RunFailure("timeout","Run int\
|
|
2267
|
+
errupted")):!assistant||assistant.stopReason==="length"?completionOutcome():completionOutcome(evidence)}function completionOutcome(evidence){return evidence?.criteria?.some(criterion=>criterion.status==="unmet")?failureOutcome(new RunFailure("completed_wrong","Acceptance criterion unmet")):evidence?.completion==="verified"?{type:"run_end",failureClass:null,exitCode:0}:failureOutcome(new RunFailure("completed_unverified","Completion is not verified"))}import{once}from"node:events";import{open as open4}from"node:fs/promises";import{finished as finished2}from"node:stream/promises";import{constants as constants3}from"node:fs";import{access as fsAccess}from"node:fs/promises";import{constants as osConstants2}from"node:os";import{spawn as spawn4}from"child_process";import{AsyncLocalStorage as AsyncLocalStorage4}from"node:async_hooks";import{spawn as spawn3}from"node:child_process";var scopes=new AsyncLocalStorage4;async function withReadOnlyAcceptanceCommand(id2,command,cwd,signal,run2){let filter=socketFilter();return!filter||!await sandboxAvailable(filter,signal)?run2():scopes.run({id:id2,command,cwd,executions:0,completed:!1},run2)}function acceptanceCommandIsReadOnly(id2){let scope=scopes.getStore();return scope?.id===id2&&scope.executions===1&&scope.completed}function readOnlyAcceptanceSpawn(command,cwd,shell,env){let scope=scopes.getStore();if(!(!scope||scope.command!==
|
|
2257
2268
|
command||scope.cwd!==cwd||hasLoaderOverrides(env)))return scope.executions++,{shell:"/usr/bin/bwrap",args:[...sandboxArgs(),"--",shell.shell,...shell.args],commandTransport:shell.commandTransport,filter:socketFilter(),completed:()=>{scope.completed=!0},retry:run2=>(scope.executions++,scopes.exit(run2))}}function sandboxArgs(){return["--unshare-all","--unshare-user","--disable-userns","--cap-drop","ALL","--ro-bind","/","/","--proc","/proc","--dev","/dev","--die-with-parent","--new-session","--sec\
|
|
2258
2269
|
comp","3"]}function socketFilter(){if(process.platform!=="linux"||!["x64","arm64"].includes(process.arch))return;let arch2=process.arch==="x64"?3221225534:3221225655,denied=process.arch==="x64"?[41,42,44,46,85,248,249,250,303,307]:[198,203,206,211,217,218,219,265,269],opens=process.arch==="x64"?[[2,1],[257,2]]:[[56,2]],instructions=[[32,0,0,4],[21,1,0,arch2],[6,0,0,2147483648],[32,0,0,0],[53,0,1,1073741824],[6,0,0,2147483648],[21,0,4,process.arch==="x64"?16:29],[32,0,0,24],[21,1,0,21537],[6,0,0,
|
|
2259
2270
|
327681],[6,0,0,2147418112],...opens.flatMap(([syscall,flagsArgument])=>[[21,0,4,syscall],[32,0,0,16+flagsArgument*8],[69,0,1,1603],[6,0,0,327681],[32,0,0,0]]),...[...denied,425,426,427,437].flatMap(syscall=>[[21,0,1,syscall],[6,0,0,327681]]),[6,0,0,2147418112]],buffer=Buffer.alloc(instructions.length*8);for(let[index,instruction]of instructions.entries())buffer.writeUInt16LE(instruction[0],index*8),buffer[index*8+2]=instruction[1],buffer[index*8+3]=instruction[2],buffer.writeUInt32LE(instruction[3],
|