@code-yeongyu/senpi 2026.11.13 → 2026.11.15-2
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 +45 -0
- package/dist/bundle/chunks/{args-H56W53X6.js → args-JWBI5LNO.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-MNN2TINI.js → azure-openai-responses-PEMLRPJ5.js} +1 -1
- package/dist/bundle/chunks/{chunk-HZQHA4PA.js → chunk-3RILB2OD.js} +1 -1
- package/dist/bundle/chunks/{chunk-BKDXY6EM.js → chunk-5NECOJNK.js} +1 -1
- package/dist/bundle/chunks/{chunk-Y4PFEXFN.js → chunk-64FJ4QQJ.js} +1 -1
- package/dist/bundle/chunks/chunk-6QQL3SKM.js +2 -0
- package/dist/bundle/chunks/{chunk-7T2LAWZ4.js → chunk-73HGQTJN.js} +1 -1
- package/dist/bundle/chunks/{chunk-U4FAWC6C.js → chunk-74HCKLRH.js} +1 -1
- package/dist/bundle/chunks/chunk-75O3CWR5.js +2 -0
- package/dist/bundle/chunks/{chunk-AZ27TE3H.js → chunk-7BX3JQ7F.js} +1 -1
- package/dist/bundle/chunks/{chunk-NDI6N4NJ.js → chunk-7CXLNKEH.js} +1 -1
- package/dist/bundle/chunks/{chunk-E6ZBTSC6.js → chunk-A3LGSX7Z.js} +1 -1
- package/dist/bundle/chunks/chunk-AH2YAO7R.js +2 -0
- package/dist/bundle/chunks/{chunk-6FE42M54.js → chunk-BMADOJHZ.js} +2 -2
- package/dist/bundle/chunks/{chunk-7GD2EO6T.js → chunk-FYVQEZYN.js} +1 -1
- package/dist/bundle/chunks/{chunk-EQT4WNCW.js → chunk-HTWWKJJI.js} +2 -2
- package/dist/bundle/chunks/{chunk-SFACYIB6.js → chunk-IK3S2NDB.js} +1 -1
- package/dist/bundle/chunks/{chunk-V4VDIV3U.js → chunk-PWA75RQU.js} +1 -1
- package/dist/bundle/chunks/{chunk-IREUIMFE.js → chunk-PWTXZXHH.js} +1 -1
- package/dist/bundle/chunks/{chunk-KKB3K5CV.js → chunk-Q4RJ4WLE.js} +1 -1
- package/dist/bundle/chunks/{chunk-NXGSYUMV.js → chunk-QSU2456D.js} +2 -2
- package/dist/bundle/chunks/chunk-QVG5SUSV.js +2 -0
- package/dist/bundle/chunks/chunk-RLIY3AUC.js +2 -0
- package/dist/bundle/chunks/{chunk-I4N2OIY4.js → chunk-RRFDLGX6.js} +26 -26
- package/dist/bundle/chunks/{chunk-JLCZIEBC.js → chunk-THYIV26N.js} +1 -1
- package/dist/bundle/chunks/{chunk-NI2AOYP6.js → chunk-TPLEPLEB.js} +3 -2
- package/dist/bundle/chunks/{chunk-CU6HUYL7.js → chunk-WAGFTIT4.js} +1 -1
- package/dist/bundle/chunks/{chunk-UYPH6RHY.js → chunk-Z4PN2MDA.js} +2 -2
- package/dist/bundle/chunks/{chunk-JJYN347Z.js → chunk-ZJUL5ODW.js} +1 -1
- package/dist/bundle/chunks/{cli-main-MY53RXU3.js → cli-main-GNQY2LTU.js} +1 -1
- package/dist/bundle/chunks/credential-accounts-RXZIUKFM.js +2 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{hand-entry-AXTVMVJK.js → hand-entry-D3DNH6XL.js} +1 -1
- package/dist/bundle/chunks/{headless-host-SU5O2KZ2.js → headless-host-OEK6W65T.js} +1 -1
- package/dist/bundle/chunks/{health-write-TN7EXGLI.js → health-write-44JERGEJ.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-TFQ4HJNO.js → help-fast-path-JWHUCE4E.js} +1 -1
- package/dist/bundle/chunks/{host-command-FG56Y53E.js → host-command-O2K2WIPO.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-UFEOW7EP.js → host-session-command-K3MR6RJY.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-ATBPY4M5.js +2 -0
- package/dist/bundle/chunks/{login-health-XBTIORM4.js → login-health-V4B6LSCP.js} +1 -1
- package/dist/bundle/chunks/main-OMFVSMUR.js +2 -0
- package/dist/bundle/chunks/{multi-session-host-Q6SHI22A.js → multi-session-host-ACQ5N4UB.js} +6 -6
- package/dist/bundle/chunks/openai-codex-responses-G7ZXJBU6.js +10 -0
- package/dist/bundle/chunks/openai-responses-3TAF7WQF.js +5 -0
- package/dist/bundle/chunks/{package-manager-cli-LILAWI3Q.js → package-manager-cli-2VMRV4HL.js} +3 -3
- package/dist/bundle/chunks/{role-KODRTWH5.js → role-BTH5PVME.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-2KNROTYB.js → rotation-stream-ZGPXLY62.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-XUK5SYKH.js +2 -0
- package/dist/bundle/chunks/{run-attached-tui-OEFHV5CZ.js → run-attached-tui-RVVYEINN.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-VO4RP2KX.js → schedule-command-6TAAG2KU.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-CCVRJHSC.js → session-control-endpoint-Y5EIFFPY.js} +1 -1
- package/dist/bundle/chunks/{session-picker-VN5I2ZDI.js → session-picker-PRSZJYY4.js} +1 -1
- package/dist/bundle/chunks/session-slot-N4E4OSCX.js +2 -0
- package/dist/bundle/chunks/session-worker.js +74 -72
- package/dist/bundle/chunks/{state-store-7RVODZJU.js → state-store-I6MUHET3.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session-runtime.js +3 -3
- package/dist/core/agent-session.d.ts +5 -3
- package/dist/core/agent-session.js +20 -8
- package/dist/core/credential-accounts.d.ts +5 -3
- package/dist/core/credential-accounts.js +8 -6
- package/dist/core/credential-pool/classify.js +5 -1
- package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.d.ts +6 -0
- package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.js +14 -0
- package/dist/core/extensions/builtin/anthropic-subscription/prompt-bridge.js +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +4 -1
- package/dist/core/extensions/builtin/permission-system/index.js +6 -1
- package/dist/core/extensions/loader.js +17 -1
- package/dist/core/extensions/runner.js +16 -2
- package/dist/core/extensions/tool-call-signal.d.ts +8 -0
- package/dist/core/extensions/tool-call-signal.js +14 -0
- package/dist/core/extensions/two-sided-forwarding.d.ts +6 -0
- package/dist/core/extensions/types.d.ts +26 -1
- package/dist/core/extensions/types.js +10 -0
- package/dist/core/reasoning-baseline.d.ts +8 -1
- package/dist/core/reasoning-baseline.js +24 -0
- package/dist/core/retry-fallback/chains.js +5 -1
- package/dist/core/retry-fallback/controller.d.ts +6 -1
- package/dist/core/retry-fallback/controller.js +11 -3
- package/dist/core/retry-fallback/expansion.js +18 -4
- package/dist/core/retry-fallback/settings.d.ts +7 -6
- package/dist/core/retry-fallback/settings.js +9 -8
- package/dist/core/runtime/bootstrap.d.ts +3 -0
- package/dist/core/runtime/bootstrap.js +1 -0
- package/dist/core/session-cwd.d.ts +15 -1
- package/dist/core/session-cwd.js +22 -1
- package/dist/core/tools/bash.d.ts +12 -0
- package/dist/core/tools/bash.js +30 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/modes/rpc/connection-handler.js +4 -0
- package/dist/modes/rpc/method-classes-schema-session.d.ts +3 -0
- package/dist/modes/rpc/method-classes-schema-session.js +6 -2
- package/dist/modes/rpc/method-classes-schema.d.ts +3 -0
- package/dist/modes/rpc/project-expected-cwd.d.ts +29 -0
- package/dist/modes/rpc/project-expected-cwd.js +45 -0
- package/dist/modes/rpc/rpc-error-types.d.ts +7 -1
- package/dist/modes/rpc/rpc-error-types.js +6 -0
- package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
- package/dist/modes/rpc/session-router-close.js +6 -1
- package/dist/modes/rpc/session-router-open.js +5 -0
- package/dist/modes/rpc/session-status.d.ts +1 -1
- package/dist/modes/rpc/session-status.js +2 -0
- package/dist/package-manager-cli.d.ts +14 -0
- package/dist/package-manager-cli.js +20 -4
- package/dist/utils/version-check.d.ts +10 -7
- package/dist/utils/version-check.js +24 -5
- package/docs/extensions.md +12 -0
- package/docs/rpc.md +28 -13
- package/docs/settings.md +1 -1
- package/package.json +7 -7
- package/dist/bundle/chunks/chunk-GLTOBXZY.js +0 -2
- package/dist/bundle/chunks/chunk-PBUV2Z3R.js +0 -2
- package/dist/bundle/chunks/chunk-WRBOKYPS.js +0 -2
- package/dist/bundle/chunks/chunk-YT2ZSZOY.js +0 -2
- package/dist/bundle/chunks/credential-accounts-ZB5IXHIG.js +0 -2
- package/dist/bundle/chunks/interactive-mode-PHES47E3.js +0 -2
- package/dist/bundle/chunks/main-PR4FI6HQ.js +0 -2
- package/dist/bundle/chunks/openai-codex-responses-VRGOAFEG.js +0 -10
- package/dist/bundle/chunks/openai-responses-I7PXRWCM.js +0 -4
- package/dist/bundle/chunks/rpc-mode-CGVK4SSA.js +0 -2
- package/dist/bundle/chunks/session-slot-GHJVOSG7.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{require_semver}from"./chunk-ZOFZRJSL.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{APP_NAME,BRAND,DISPLAY_VERSION,PACKAGE_NAME,brandProfile,detectInstallMethod,envValue}from"./chunk-SODMQEHO.js";import{__toESM}from"./chunk-IKOFCODM.js";import{spawnSync}from"node:child_process";import{homedir as osHomedir}from"node:os";import{posix,win32}from"node:path";var RUNTIME_ENV_VAR="SENPI_RUNTIME",MIN_BUN_VERSION="1.4.0";function normalize(path){return path.replaceAll("\\","/")}function paths(options){return options.platform==="win32"?win32:posix}function bunRoot(options){let configured=options.env.BUN_INSTALL;return configured!==void 0&&configured.trim()!==""?configured:paths(options).join(options.homedir,".bun")}function resolveOrSelf(path,options){try{return options.realpath(path)}catch{return path}}function isUnderBunGlobalTree(scriptRealPath,options){let globalRoot=paths(options).join(bunRoot(options),"install","global"),script=normalize(scriptRealPath);for(let candidate of new Set([globalRoot,resolveOrSelf(globalRoot,options)]))if(script.startsWith(`${normalize(candidate)}/`))return!0;return!1}function isInstalledPackageScript(scriptRealPath){return normalize(scriptRealPath).includes("/node_modules/")}function bunVersionSatisfies(version){let actual=/^v?(\d+)\.(\d+)\.(\d+)/.exec(version?.trim()??""),minimum=/^(\d+)\.(\d+)\.(\d+)/.exec(MIN_BUN_VERSION);if(!actual||!minimum)return!1;for(let index=1;index<=3;index++){let difference=Number(actual[index])-Number(minimum[index]);if(difference!==0)return difference>0}return!0}function bunExecutableName(options){return options.platform==="win32"?"bun.exe":"bun"}function pathCandidateNames(options){if(options.platform!=="win32")return["bun"];let extensions=(options.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(extension=>extension.trim()).filter(extension=>extension.length>0);return extensions.length>0?extensions.map(extension=>`bun${extension}`):["bun.exe"]}function findBunBinary(options){let path=paths(options),executable=bunExecutableName(options),rootCandidates=[path.join(bunRoot(options),"bin",executable),path.join(options.homedir,".bun","bin",executable)];for(let candidate of rootCandidates)if(options.exists(candidate))return candidate;let pathValue=options.env.PATH??options.env.Path;if(pathValue===void 0||pathValue==="")return;let names=pathCandidateNames(options);for(let directory of pathValue.split(path.delimiter))if(directory!=="")for(let name of names){let candidate=path.join(directory,name);if(options.exists(candidate))return candidate}}function readRuntimePin(options){let value=options.env[RUNTIME_ENV_VAR];if(value==="node"||value==="bun")return value}function resolveBunReexec(input){if(input.versions.bun!==void 0)return{action:"stay",reason:"already-bun"};let pinned=readRuntimePin(input.options);if(pinned==="node")return{action:"stay",reason:"runtime-pinned-node"};if(input.hasInheritedInspectorOption)return{action:"stay",reason:"inspector"};let trustsInstalledBun=pinned==="bun"||isUnderBunGlobalTree(input.scriptRealPath,input.options);if(!trustsInstalledBun&&!isInstalledPackageScript(input.scriptRealPath))return{action:"stay",reason:"not-bun-install"};let bunPath=findBunBinary(input.options);return bunPath===void 0?{action:"stay",reason:"bun-not-found"}:!trustsInstalledBun&&!bunVersionSatisfies(input.options.bunVersion(bunPath))?{action:"stay",reason:"bun-too-old"}:{action:"reexec",bunPath}}function readBunVersion(bunPath){try{let result=spawnSync(bunPath,["--version"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(result.status!==0)return;let version=result.stdout.trim();return version===""?void 0:version}catch{return}}function processBunRuntimeOptions(exists,realpath){return{env:process.env,homedir:osHomedir(),platform:process.platform,exists,realpath,bunVersion:readBunVersion}}function getPiUserAgent(version=DISPLAY_VERSION){let runtime=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`${BRAND?.userAgent??APP_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`}var import_semver=__toESM(require_semver(),1);var REGISTRY_BASE_URL="https://registry.npmjs.org",LATEST_VERSION_URL=`${REGISTRY_BASE_URL}/${encodeURIComponent(PACKAGE_NAME)}/latest`;function latestVersionUrl(channel){return channel?`${REGISTRY_BASE_URL}/-/package/${encodeURIComponent(channel.packageName)}/dist-tags`:LATEST_VERSION_URL}var LATEST_RELEASE_URL="https://api.github.com/repos/code-yeongyu/senpi/releases/latest";function readLatestReleaseVersion(payload){if(typeof payload!="object"||payload===null)return;let release=payload;if(release.draft===!0||release.prerelease===!0)return;let tag=typeof release.tag_name=="string"?release.tag_name.trim():"";return(tag.startsWith("v")?tag.slice(1):tag)||void 0}function readAvailableVersion(payload,channel){if(typeof payload!="object"||payload===null)return;let source=payload,raw=channel?source[channel.distTag]:source.version;return typeof raw=="string"&&raw.trim()?raw.trim():void 0}var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4,RELEASE_CHANGELOG_BASE_URL="https://github.com/code-yeongyu/senpi/blob",RELEASE_CHANGELOG_PATH="packages/coding-agent/CHANGELOG.md",SENPI_CALVER_PATTERN=/^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-([1-9]\d*))?$/;function parseSenpiCalVer(version){let match=SENPI_CALVER_PATTERN.exec(version);if(match)return[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??1)]}function canonicalCalVer([year,month,day,revision]){return revision>1?`${year}.${month}.${day}-${revision}`:`${year}.${month}.${day}`}function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let leftTrimmed=leftVersion.trim(),rightTrimmed=rightVersion.trim(),leftCalVer=parseSenpiCalVer(leftTrimmed),rightCalVer=parseSenpiCalVer(rightTrimmed);if(leftCalVer&&rightCalVer){for(let index=0;index<leftCalVer.length;index++)if(leftCalVer[index]!==rightCalVer[index])return leftCalVer[index]<rightCalVer[index]?-1:1;return 0}let left=(0,import_semver.valid)(leftCalVer?canonicalCalVer(leftCalVer):leftTrimmed),right=(0,import_semver.valid)(rightCalVer?canonicalCalVer(rightCalVer):rightTrimmed);if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0&&comparison>0}function getReleaseChangelogUrl(version){let trimmedVersion=version.trim(),channel=brandProfile()?.update;if(channel?.changelogUrl)return channel.changelogUrl.replace("{version}",trimmedVersion);let tag=trimmedVersion.startsWith("v")?trimmedVersion:`v${trimmedVersion}`;return`${RELEASE_CHANGELOG_BASE_URL}/${tag}/${RELEASE_CHANGELOG_PATH}`}async function getLatestPiRelease(currentVersion,options={}){if(envValue("OFFLINE"))return;let brand=brandProfile(),channel=brand?.update;if(brand&&!channel)return;let fromRelease=!channel&&(options.installMethod??detectInstallMethod())==="bun-binary",response=await fetchWithRetry(fromRelease?LATEST_RELEASE_URL:latestVersionUrl(channel),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:fromRelease?"application/vnd.github+json":"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;if(fromRelease){let releaseVersion=readLatestReleaseVersion(await response.json());return releaseVersion?{version:releaseVersion}:void 0}let data=await response.json(),availableVersion=readAvailableVersion(data,channel);if(!availableVersion)return;if(channel)return{version:availableVersion,packageName:channel.packageName};let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:availableVersion,packageName,note}}async function checkForNewPiVersion(currentVersion,options={}){if(!envValue("SKIP_VERSION_CHECK"))try{let latestRelease=await getLatestPiRelease(currentVersion,options);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}export{RUNTIME_ENV_VAR,MIN_BUN_VERSION,bunVersionSatisfies,findBunBinary,resolveBunReexec,processBunRuntimeOptions,getPiUserAgent,formatVersionCheckError,isNewerPackageVersion,getReleaseChangelogUrl,getLatestPiRelease,checkForNewPiVersion};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{usageLimitResetMs}from"./chunk-WB4BUHOH.js";import{rateLimitModelFamily}from"./chunk-NJ43NBSP.js";import{isSiwcMissingResponsesScope}from"./chunk-6QQL3SKM.js";import{normalizeProviderError}from"./chunk-AC72EWI5.js";import{extract429RetryAfterMs,parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{getOverflowPatterns}from"./chunk-IK3S2NDB.js";import{ModelsError,OAuthTokenEndpointError,PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError}from"./chunk-OH5TKHW7.js";import{credentialPoolBlockedDiagnostic,readProviderDiagnostic}from"./chunk-JGKH3D6W.js";import{attachProviderDiagnostic,siwcRecoveryFromDiagnostic}from"./chunk-3SASTB6Y.js";function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}function applyAccountOrder(order,ranked){if(order===void 0||order.length===0)return[...ranked];let byName=new Map(ranked.map(slot=>[slot.name,slot])),front=[];for(let name of order){let slot=byName.get(name);slot!==void 0&&!front.includes(slot)&&front.push(slot)}return[...front,...ranked.filter(slot=>!front.includes(slot))]}function withoutOrderedAccount(credential,name){if(credential.order===void 0||!credential.order.includes(name))return credential;let order=credential.order.filter(entry=>entry!==name),next={...credential};return order.length===0?delete next.order:next.order=order,next}function isSlotBlocked(slot,now){return slot.blockReason==="auth_error"||slot.blockedUntil!==void 0&&slot.blockedUntil>now}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,GUESSED_BACKOFF_CAP_MS=1800*1e3,RETRY_SAME_MAX_ATTEMPTS=2,ACCOUNT_POOL_REFUSAL_NOTE="No request was sent: the account pool refused it locally.";function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,GUESSED_BACKOFF_CAP_MS,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}function usageLimitCooldown(resetMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS;return{cooldownMs:Math.min(cap,resetMs),retryAfterWasCapped:resetMs>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,REVOKED_TOKEN_TEXT=/invalidated (?:oauth )?token|(?<!\b(?:session|csrf|xsrf|page|pagination|continuation|cursor|sync|stream|upload|idempotency|request|nonce|state)[ _-])token(?:[ _-](?:invalidated|revoked)|\s(?:has been|was) (?:invalidated|revoked))/i,REFUSED_GRANT_CODES=new Set(["invalid_grant","refresh_token_expired","refresh_token_invalidated","refresh_token_reused","token_revoked"]),REFUSED_GRANT_TOKEN=/(?<![a-z_])(invalid_grant|refresh_token_(?:expired|invalidated|reused)|token_revoked)(?![a-z_])/,CLIENT_FAULT_CODES=new Set(["invalid_client","invalid_request","invalid_scope","unauthorized_client","unsupported_grant_type"]),NETWORK_FAULT_CODES=new Set(["ECONNRESET","ECONNREFUSED","ECONNABORTED","ETIMEDOUT","EHOSTUNREACH","EHOSTDOWN","ENETUNREACH","ENETDOWN","ENETRESET","ENOTFOUND","EAI_AGAIN","EPIPE","EADDRNOTAVAIL","ERR_SOCKET_CONNECTION_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CLOSED","ConnectionRefused","ConnectionClosed","FailedToOpenSocket"]),AUTH_ERROR_CODES=new Set(["authentication_error","invalid_api_key","token_invalidated",...REFUSED_GRANT_CODES]),MAX_CAUSE_LINKS=16,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,MODEL_SCOPED_REFUSAL_TEXT=[/(?:does not include(?: access to)?|not entitled to(?: use)?|no access to)[^.]{0,60}?\bmodel\b/i,/\bmodel\b.{0,80}?\b(?:is not|not|no)\b.{0,40}?\b(?:available|included|entitled|enabled|accessible)\b.{0,40}?\b(?:plan|subscription)\b/i,/(?:plan|subscription)[^.]{0,30}?\bdoes not\b[^.]{0,20}?\binclude access to\b/i],RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i,TEMPORARY_FAULT_TEXT=/time[ds]?[ _-]?out|timed out|disconnect|reset before|connection reset|gateway|temporarily|unavailable/i;function limitFromProviderCode(error){let diagnostic=readProviderDiagnostic(error);if(diagnostic?.evidence==="structured_code")switch(diagnostic.code){case"rate_limit_exceeded":return{kind:"throttle"};case"usage_limit_reached":case"usage_not_included":return diagnostic.resetsAt===void 0?{kind:"spent"}:{kind:"spent",resetsAt:diagnostic.resetsAt};default:return}}function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function failedRefresh(error){let seen=new Set;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof ModelsError)return error.code==="oauth"?error:void 0;error=Reflect.get(error,"cause")}}function oauthBodyErrorCode(message){let start=message.indexOf("{"),end=message.lastIndexOf("}");if(!(start<0||end<=start))try{let body=JSON.parse(message.slice(start,end+1));if(typeof body!="object"||body===null)return;let field=Reflect.get(body,"error");if(typeof field=="string")return field;if(typeof field=="object"&&field!==null){let code=Reflect.get(field,"code");return typeof code=="string"?code:void 0}return}catch{return}}function isRefusedGrant(refresh){let cause=refresh.cause;if(!(cause instanceof OAuthTokenEndpointError))return!1;let code=cause.oauthError??oauthBodyErrorCode(cause.message);return code!==void 0&&CLIENT_FAULT_CODES.has(code)?!1:cause.credentialRefused||cause.status===401?!0:code!==void 0&&REFUSED_GRANT_CODES.has(code)?[400,403,404].includes(cause.status):cause.status===400&&REFUSED_GRANT_TOKEN.test(cause.message)}function isRefreshNetworkFault(refresh,text){let seen=new Set,error=refresh.cause;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof OAuthTokenEndpointError)return!1;let code=Reflect.get(error,"code");if(typeof code=="string")return NETWORK_FAULT_CODES.has(code);error=Reflect.get(error,"cause")}return NETWORK_TEXT.test(text)}function hasAuthDiagnostic(error){let diagnostic=readProviderDiagnostic(error);return diagnostic===void 0?!1:diagnostic.category==="auth"||diagnostic.code!==void 0&&AUTH_ERROR_CODES.has(diagnostic.code)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}var JSON_BODY=/\{\s*"[^"]+"\s*:/;function rateLimitHint(codedThrottle,codedReset,text,status,usageLimit,diagnosticRetryAfterMs,nowMs){let sourced=(hint,source)=>hint===void 0?{hint,resetSource:"default_backoff"}:{hint,resetSource:source};if(codedThrottle)return sourced(parseRetryAfterMsMarker(text),"retry_after");if(codedReset!==void 0)return sourced(codedReset,"reset_field");let retryAfter=extract429RetryAfterMs({status:status??429,bodyText:text},nowMs);return retryAfter!==void 0?parseRetryAfterMsMarker(text)!==void 0?sourced(retryAfter,"retry_after"):sourced(retryAfter,JSON_BODY.test(text)?"reset_field":"reset_prose"):usageLimit?diagnosticRetryAfterMs!==void 0?sourced(diagnosticRetryAfterMs,"reset_field"):sourced(usageLimitResetMs(text,nowMs),JSON_BODY.test(text)?"reset_field":"reset_prose"):sourced(void 0,"default_backoff")}function credentialFailureText(error){let normalized=normalizeProviderError(error);return normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(error instanceof Error&&error.name==="AbortError")return{kind:"fail_request"};switch(siwcRecoveryFromDiagnostic(readProviderDiagnostic(error))){case"usage_limit":return{kind:"failover",block:{reason:"rate_limit",usageLimit:!0,...rateLimitCooldown(failureCount,void 0,{baseMs:context.cooldownBaseMs,capMs:Math.min(context.cooldownCapMs??COOLDOWN_CAP_MS,30*6e4)})}};case"account_disabled":return{kind:"failover",block:{reason:"account_disabled"}};case"auth":return isSiwcMissingResponsesScope(text)?{kind:"fail_request"}:{kind:"failover",block:{reason:"auth_error"}};case"request":return{kind:"fail_request"};case"transient":return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};case void 0:break}if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(ACCOUNT_POOL_REFUSAL_NOTE))return{kind:"fail_request"};let providerFault=status===408||status!==void 0&&status>=500&&status<600||status===void 0&&(TEMPORARY_FAULT_TEXT.test(text)||NETWORK_TEXT.test(text)||OVERLOAD_TEXT.test(text)),codedLimit=limitFromProviderCode(error),usageLimit=codedLimit!==void 0?codedLimit.kind==="spent":isAccountUsageLimitText(text)&&!isOverflowText(text),limitText=codedLimit!==void 0||RATE_LIMIT_TEXT.test(text)||usageLimit;if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};let statusFault=status===408||status===429||status!==void 0&&status>=500&&status<600,refresh=failedRefresh(error);if(refresh!==void 0)return!statusFault&&isRefusedGrant(refresh)?{kind:"failover",block:{reason:"auth_error"}}:isRefreshNetworkFault(refresh,text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"};if(!providerFault&&status!==429&&hasAuthDiagnostic(error))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||!providerFault&&status!==429&&(INVALID_KEY_TEXT.test(text)||REVOKED_TOKEN_TEXT.test(text)))return{kind:"failover",block:{reason:"auth_error"}};if(status===403&&!limitText)return MODEL_SCOPED_REFUSAL_TEXT.some(pattern=>pattern.test(text))?{kind:"fail_request"}:ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||!providerFault&&BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||limitText){if(codedLimit===void 0&&MODEL_SCOPED_REFUSAL_TEXT.some(pattern=>pattern.test(text)))return{kind:"fail_request"};let nowMs=context.nowMs??Date.now(),codedResetMs=codedLimit?.kind==="spent"&&codedLimit.resetsAt!==void 0?codedLimit.resetsAt-nowMs:void 0,codedReset=codedResetMs!==void 0&&codedResetMs>0?codedResetMs:void 0,{hint,resetSource}=rateLimitHint(codedLimit?.kind==="throttle",codedReset,text,status,usageLimit,normalized.retryAfterMs,nowMs),modelFamily=rateLimitModelFamily(text),policy={baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs};return{kind:"failover",block:{reason:"rate_limit",...usageLimit&&hint!==void 0&&hint>0?usageLimitCooldown(hint,policy):rateLimitCooldown(failureCount,hint,policy),resetSource,...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function coolingProbe(slots,attempted){if(attempted.size>0)return[];let soonest=slots.filter(slot=>slot.blockReason==="rate_limit"&&slot.blockedUntil!==void 0).reduce((best,slot)=>best===void 0||(slot.blockedUntil??0)<(best.blockedUntil??0)?slot:best,void 0);return soonest===void 0?[]:[soonest]}function attemptCandidates(slots,attempted,now){let available=slots.filter(slot=>!attempted.has(slot.name)&&isAvailable(slot,now));return available.length>0?available:coolingProbe(slots,attempted)}function noSlotsError(slots,now){let retryAt=soonestRetryAt(slots,now);return new CredentialFailoverError({kind:"fail_request"},new Error(noSlotsMessage(slots,now)),retryAt===void 0?{}:{retryAt})}function dueBack(epochMs){return`${localTime(epochMs)} (${new Date(epochMs).toISOString()})`}function localTime(epochMs){return new Date(epochMs).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function noSlotsMessage(slots,now){let blocked=slots.map(slot=>{let reason=slot.blockReason??"blocked";return slot.blockedUntil!==void 0&&slot.blockedUntil>now?`${slot.name} (${reason} until ${dueBack(slot.blockedUntil)})`:reason==="account_disabled"?`${slot.name} (account_disabled until re-login)`:`${slot.name} (${reason})`}),firstBack=soonestRetryAt(slots,now),step=firstBack===void 0?"Sign in again or add a new API key for this provider, or choose another model.":`Wait until ${localTime(firstBack)}, or choose another model.`;return blocked.length===0?`No credential slots available. ${step}`:`No credential slots available: ${blocked.join(", ")}. ${step}`}function isRateLimitBlock(action){return action.kind==="failover"&&action.block.reason==="rate_limit"}var OUT_OF_POOL_REASONS=new Set(["auth_error","account_disabled"]);function limitedUntil(slots,now){let resets=[];for(let slot of slots)if(!OUT_OF_POOL_REASONS.has(slot.blockReason??"")){if(slot.blockReason!=="rate_limit"||slot.blockedUntil===void 0||slot.blockedUntil<=now)return;resets.push(slot.blockedUntil)}return resets.length===0?void 0:Math.min(...resets)}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1,unsettled;try{for(;;){let slots=await options.listSlots(),candidates=attemptCandidates(slots,attempted,now());if(candidates.length===0){let limitedRetryAt=lastError===void 0||isRateLimitBlock(lastError.action)?limitedUntil(slots,now()):void 0;if(lastTerminalEvent!==void 0){yield limitedRetryAt===void 0||options.withPoolRetryAt===void 0?lastTerminalEvent:options.withPoolRetryAt(lastTerminalEvent,limitedRetryAt);return}let retryAt=soonestRetryAt(slots,now()),refusal=lastError===void 0||lastOriginal===void 0?noSlotsError(slots,now()):new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt});throw limitedRetryAt===void 0?refusal:attachProviderDiagnostic(refusal,credentialPoolBlockedDiagnostic(limitedRetryAt))}let slot=options.select(candidates);unsettled=slot;let committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}unsettled=void 0,await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts){unsettled=void 0,await options.releaseSlot?.(slot);continue}if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}unsettled=void 0,await options.persistBlock(slot,action.block,error),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}finally{unsettled!==void 0&&await options.releaseSlot?.(unsettled)}}function parseAccountStrategy(value,field){switch(value){case void 0:case"cache-affine":case"fill-first":case"round-robin":return value;default:throw new Error(`${field} must be "cache-affine", "fill-first", or "round-robin"`)}}function orderAccounts(accounts,ranked,accountOrder,strategy="cache-affine",offset=0){switch(strategy){case"cache-affine":return applyAccountOrder(accountOrder,ranked);case"fill-first":return applyAccountOrder(accountOrder,accounts);case"round-robin":{let ordered=applyAccountOrder(accountOrder,accounts);if(ordered.length===0)return ordered;let start=offset%ordered.length;return[...ordered.slice(start),...ordered.slice(0,start)]}default:{let unsupported=strategy;throw new Error(`Unknown account strategy: ${unsupported}`)}}}function preferHeadroom(ordered,provider,limits,now,preferredAccount){let preferred=ordered.find(account=>account.name===preferredAccount),normal=preferred===void 0?ordered:[preferred,...ordered.filter(account=>account!==preferred)],nearLimit=new Set(limits.filter(limit=>limit.provider===provider&&limit.windows.some(window=>window.usedPercent>=95&&(window.resetsAt===void 0||!(Date.parse(window.resetsAt)<=now)))).map(limit=>limit.account)),withHeadroom=normal.filter(account=>!nearLimit.has(account.name));return withHeadroom.length>0?withHeadroom:normal}export{rendezvousOrder,applyAccountOrder,withoutOrderedAccount,isSlotBlocked,MAX_SLOT_BLOCK_MS,ACCOUNT_POOL_REFUSAL_NOTE,credentialFailureText,classifyCredentialFailure,CredentialFailoverError,isAvailable,attemptCandidates,noSlotsError,runCredentialFailover,parseAccountStrategy,orderAccounts,preferHeadroom};
|