@code-yeongyu/senpi 2026.10.21-1 → 2026.10.21-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 +33 -0
- package/dist/bundle/chunks/{anthropic-messages-S5BTP7U2.js → anthropic-messages-2IQD75YN.js} +1 -1
- package/dist/bundle/chunks/args-SV2KM4KA.js +2 -0
- package/dist/bundle/chunks/azure-openai-responses-HFI6SDH5.js +2 -0
- package/dist/bundle/chunks/{chunk-WQLMQGOW.js → chunk-2AJB5S4C.js} +1 -1
- package/dist/bundle/chunks/{chunk-XSRM367N.js → chunk-3AK3WUN4.js} +2 -2
- package/dist/bundle/chunks/{chunk-6TL72TUD.js → chunk-4HJTPWZY.js} +1 -1
- package/dist/bundle/chunks/chunk-4NPBDGC4.js +26 -0
- package/dist/bundle/chunks/{chunk-E4WOCULF.js → chunk-4XR5HDWC.js} +72 -69
- package/dist/bundle/chunks/{chunk-6IWSMXBA.js → chunk-5GC4IQ3A.js} +1 -1
- package/dist/bundle/chunks/{chunk-7I7ZMSBF.js → chunk-A4B4CMOR.js} +1 -1
- package/dist/bundle/chunks/chunk-B4N4N7BR.js +8 -0
- package/dist/bundle/chunks/{chunk-X23XXKMH.js → chunk-BVFJAXWO.js} +1 -1
- package/dist/bundle/chunks/{chunk-25B6JQC4.js → chunk-C3BJRXEV.js} +1 -1
- package/dist/bundle/chunks/{chunk-DKBJM22C.js → chunk-CQDU6S6C.js} +2 -2
- package/dist/bundle/chunks/{chunk-MF57DS3V.js → chunk-EV4TWAJI.js} +1 -1
- package/dist/bundle/chunks/{chunk-JJXDWX46.js → chunk-F3JGTOLH.js} +1 -1
- package/dist/bundle/chunks/{chunk-CRY5CP3B.js → chunk-G42JHX5Q.js} +3 -3
- package/dist/bundle/chunks/{chunk-5VRI3CME.js → chunk-G7VYQRE7.js} +2 -2
- package/dist/bundle/chunks/chunk-GVSBCJFI.js +2 -0
- package/dist/bundle/chunks/{chunk-KUZPBZUK.js → chunk-HKDGQE6D.js} +2 -2
- package/dist/bundle/chunks/{chunk-HD67U37N.js → chunk-HRV7NEOJ.js} +1 -1
- package/dist/bundle/chunks/chunk-JDETIKL7.js +7 -0
- package/dist/bundle/chunks/{chunk-MVNVDGYF.js → chunk-JGMG227A.js} +1 -1
- package/dist/bundle/chunks/chunk-MHD7SSHF.js +2 -0
- package/dist/bundle/chunks/{chunk-CEQMTVYS.js → chunk-MXLEWTWC.js} +2 -2
- package/dist/bundle/chunks/{chunk-C5W3D56I.js → chunk-N6UN2SDS.js} +3 -3
- package/dist/bundle/chunks/chunk-NTK2MHJ5.js +2 -0
- package/dist/bundle/chunks/chunk-OMN4QWFA.js +3 -0
- package/dist/bundle/chunks/chunk-PLQ5WRXN.js +2 -0
- package/dist/bundle/chunks/{chunk-2MOGCBPT.js → chunk-PUMCQ5HS.js} +1 -1
- package/dist/bundle/chunks/{chunk-55YTTFNY.js → chunk-PUQFKAB4.js} +1 -1
- package/dist/bundle/chunks/{chunk-IJT3GSB2.js → chunk-SN7PTZTC.js} +1 -1
- package/dist/bundle/chunks/{chunk-FWHSGCWR.js → chunk-T2IIUI3J.js} +3 -3
- package/dist/bundle/chunks/{chunk-5AOKDC6G.js → chunk-TSETMVJP.js} +1 -1
- package/dist/bundle/chunks/{chunk-SR7DBNWN.js → chunk-V6AYNGMX.js} +1 -1
- package/dist/bundle/chunks/chunk-VDPJ7W52.js +11 -0
- package/dist/bundle/chunks/{chunk-EPQK674G.js → chunk-VLKULV6F.js} +1 -1
- package/dist/bundle/chunks/{chunk-SL7TSFR5.js → chunk-VXACHCLB.js} +1 -1
- package/dist/bundle/chunks/{chunk-FM7NDZR5.js → chunk-VYSRUDEU.js} +1 -1
- package/dist/bundle/chunks/chunk-YMFGBSO3.js +2 -0
- package/dist/bundle/chunks/cli-main-RA6EBOOU.js +3 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-4QEQ7MGK.js → cloudflare-workers-ai-system-one-BVENEDT6.js} +1 -1
- package/dist/bundle/chunks/cursor-agent.js +3 -3
- package/dist/bundle/chunks/google-generative-ai-ONS2KSGN.js +2 -0
- package/dist/bundle/chunks/google-vertex-5VS7ZESH.js +2 -0
- package/dist/bundle/chunks/help-fast-path-FZY53UXB.js +2 -0
- package/dist/bundle/chunks/host-command-TNUIHEFP.js +2 -0
- package/dist/bundle/chunks/{host-lifecycle-EZQ5VCQV.js → host-lifecycle-LDOHAYLK.js} +1 -1
- package/dist/bundle/chunks/host-session-command-OKASUQPA.js +20 -0
- package/dist/bundle/chunks/interactive-mode-PSGTSURY.js +2 -0
- package/dist/bundle/chunks/{mistral-conversations-5EHLE7PZ.js → mistral-conversations-RLDMF2BI.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-OMJZ5VXM.js → multi-session-host-J5BVVUG3.js} +7 -6
- package/dist/bundle/chunks/openai-codex-responses-VRIJIZJG.js +10 -0
- package/dist/bundle/chunks/{openai-completions-NHDMDAS7.js → openai-completions-EZBOIXHP.js} +2 -2
- package/dist/bundle/chunks/{openai-images-PNXQDBSP.js → openai-images-KKM343F2.js} +1 -1
- package/dist/bundle/chunks/openai-responses-CMBH3DCY.js +3 -0
- package/dist/bundle/chunks/{package-manager-cli-7GQDB5DX.js → package-manager-cli-JHVRG35I.js} +1 -1
- package/dist/bundle/chunks/{role-WQWYL4ZD.js → role-LNF5MFGC.js} +1 -1
- package/dist/bundle/chunks/rotation-stream-JK3Q4IWI.js +2 -0
- package/dist/bundle/chunks/rpc-mode-HVSPPRTT.js +2 -0
- package/dist/bundle/chunks/{rpc-monitor-source-FI7H7LGY.js → rpc-monitor-source-2DQZLFFJ.js} +1 -1
- package/dist/bundle/chunks/{runtime-session-IQAKNRTV.js → runtime-session-CLNODAYE.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-XXJC4QQN.js → schedule-command-OMI4VWUV.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-UPYF4OFP.js +3 -0
- package/dist/bundle/chunks/session-picker-NR7CRVNQ.js +2 -0
- package/dist/bundle/chunks/session-worker.js +143 -139
- package/dist/bundle/chunks/{typesafe-system-one-W2ZTYF7X.js → typesafe-system-one-PJIWA5SP.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/cli/host-command.d.ts +2 -0
- package/dist/cli/host-command.js +14 -19
- package/dist/cli/host-handover-args.d.ts +4 -0
- package/dist/cli/host-handover-args.js +20 -0
- package/dist/core/agent-session.d.ts +29 -1
- package/dist/core/agent-session.js +74 -19
- package/dist/core/auth-storage.d.ts +44 -1
- package/dist/core/auth-storage.js +120 -3
- package/dist/core/client-message-identity.d.ts +3 -0
- package/dist/core/credential-accounts.d.ts +2 -0
- package/dist/core/credential-accounts.js +8 -1
- package/dist/core/credential-pool/rotation-slots.js +3 -2
- package/dist/core/extensions/builtin/account/index.js +6 -1
- package/dist/core/extensions/builtin/compaction/openai-remote.d.ts +2 -1
- package/dist/core/extensions/builtin/compaction/openai-remote.js +6 -5
- package/dist/core/extensions/builtin/goal/provider-retry.d.ts +2 -2
- package/dist/core/extensions/builtin/goal/provider-retry.js +18 -6
- package/dist/core/extensions/builtin/terminal/command-monitor-source.d.ts +17 -4
- package/dist/core/extensions/builtin/terminal/command-monitor-source.js +33 -6
- package/dist/core/extensions/builtin/terminal/durable-command.js +1 -0
- package/dist/core/extensions/builtin/terminal/extension.js +28 -0
- package/dist/core/extensions/builtin/terminal/monitor-notify-details.d.ts +6 -0
- package/dist/core/extensions/builtin/terminal/monitor-notify-details.js +19 -0
- package/dist/core/extensions/builtin/terminal/monitor-notify-format.d.ts +18 -0
- package/dist/core/extensions/builtin/terminal/monitor-notify-format.js +52 -0
- package/dist/core/extensions/builtin/terminal/monitor-notify.d.ts +8 -1
- package/dist/core/extensions/builtin/terminal/monitor-notify.js +65 -119
- package/dist/core/extensions/builtin/terminal/monitor-overflow-file.d.ts +7 -0
- package/dist/core/extensions/builtin/terminal/monitor-overflow-file.js +67 -0
- package/dist/core/extensions/builtin/terminal/monitor-overflow.d.ts +37 -0
- package/dist/core/extensions/builtin/terminal/monitor-overflow.js +75 -0
- package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts +10 -0
- package/dist/core/extensions/builtin/terminal/monitor-registry.js +24 -1
- package/dist/core/extensions/builtin/terminal/monitor-types.d.ts +5 -0
- package/dist/core/extensions/builtin/terminal/monitor-wake-fit.d.ts +9 -0
- package/dist/core/extensions/builtin/terminal/monitor-wake-fit.js +34 -0
- package/dist/core/extensions/builtin/terminal/monitor-wake-pacing.d.ts +10 -0
- package/dist/core/extensions/builtin/terminal/monitor-wake-pacing.js +41 -0
- package/dist/core/extensions/builtin/terminal/restore-session.js +2 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.js +5 -1
- package/dist/core/extensions/builtin/terminal/settings.d.ts +10 -0
- package/dist/core/extensions/builtin/terminal/settings.js +13 -1
- package/dist/core/extensions/builtin/terminal/shared.d.ts +17 -10
- package/dist/core/extensions/builtin/terminal/shared.js +19 -10
- package/dist/core/extensions/builtin/terminal/terminal-manifest-model.d.ts +3 -0
- package/dist/core/extensions/builtin/terminal/terminal-manifest-parse.js +7 -0
- package/dist/core/extensions/builtin/terminal/terminal-manifest.js +1 -0
- package/dist/core/extensions/builtin/terminal/tools/monitor-schema.d.ts +1 -0
- package/dist/core/extensions/builtin/terminal/tools/monitor-schema.js +6 -1
- package/dist/core/extensions/builtin/terminal/tools/monitor.d.ts +1 -0
- package/dist/core/extensions/builtin/terminal/tools/monitor.js +9 -1
- package/dist/core/extensions/builtin/tps.js +1 -8
- package/dist/core/extensions/loader.js +3 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.js +12 -1
- package/dist/core/extensions/types.d.ts +3 -1
- package/dist/core/session-manager.d.ts +10 -1
- package/dist/core/session-manager.js +4 -3
- package/dist/core/terminal-settings.d.ts +3 -0
- package/dist/index.d.ts +1 -1
- package/dist/main.d.ts +14 -0
- package/dist/main.js +25 -8
- package/dist/modes/index.d.ts +1 -0
- package/dist/modes/index.js +1 -0
- package/dist/modes/interactive/components/footer.js +4 -2
- package/dist/modes/interactive/interactive-mode.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode.js +13 -1
- package/dist/modes/rpc/client-admission-record.d.ts +5 -0
- package/dist/modes/rpc/client-admission-record.js +2 -0
- package/dist/modes/rpc/connection-handler.d.ts +3 -0
- package/dist/modes/rpc/connection-handler.js +33 -5
- package/dist/modes/rpc/connection-roles.d.ts +30 -0
- package/dist/modes/rpc/connection-roles.js +53 -0
- package/dist/modes/rpc/custom-capability.d.ts +6 -0
- package/dist/modes/rpc/custom-capability.js +6 -0
- package/dist/modes/rpc/host-capabilities.js +2 -1
- package/dist/modes/rpc/host-decision.d.ts +4 -1
- package/dist/modes/rpc/host-decision.js +6 -3
- package/dist/modes/rpc/host-ensure-liveness.d.ts +11 -0
- package/dist/modes/rpc/host-ensure-liveness.js +26 -0
- package/dist/modes/rpc/host-ensure.js +2 -3
- package/dist/modes/rpc/host-holder.d.ts +27 -0
- package/dist/modes/rpc/host-holder.js +18 -0
- package/dist/modes/rpc/host-runner.d.ts +2 -0
- package/dist/modes/rpc/host-runner.js +8 -1
- package/dist/modes/rpc/host-status-all.js +1 -0
- package/dist/modes/rpc/host-status.d.ts +1 -0
- package/dist/modes/rpc/host-status.js +5 -0
- package/dist/modes/rpc/host-stop-generation.d.ts +22 -0
- package/dist/modes/rpc/host-stop-generation.js +36 -0
- package/dist/modes/rpc/host-stop-start-time.d.ts +15 -0
- package/dist/modes/rpc/host-stop-start-time.js +30 -0
- package/dist/modes/rpc/host-stop.d.ts +13 -1
- package/dist/modes/rpc/host-stop.js +78 -9
- package/dist/modes/rpc/rpc-client.d.ts +9 -0
- package/dist/modes/rpc/rpc-client.js +15 -0
- package/dist/modes/rpc/rpc-types.d.ts +18 -0
- package/dist/modes/rpc/rpc-types.js +2 -0
- package/dist/modes/rpc/session-binding.d.ts +1 -1
- package/dist/modes/rpc/session-command-router.d.ts +1 -0
- package/dist/modes/rpc/session-command-router.js +13 -0
- package/dist/modes/rpc/session-worker-client.d.ts +1 -1
- package/dist/modes/rpc/session-worker-client.js +12 -1
- package/dist/modes/rpc/session-worker-protocol.d.ts +3 -0
- package/dist/modes/rpc/session-worker.js +9 -0
- package/docs/rpc.md +54 -2
- package/docs/session-format.md +5 -0
- package/package.json +6 -6
- package/dist/bundle/chunks/args-CRXNC7IS.js +0 -2
- package/dist/bundle/chunks/azure-openai-responses-2DCY6QKO.js +0 -2
- package/dist/bundle/chunks/chunk-5ZBDN3LB.js +0 -26
- package/dist/bundle/chunks/chunk-AEJUOQ7U.js +0 -2
- package/dist/bundle/chunks/chunk-LAWS3FYQ.js +0 -11
- package/dist/bundle/chunks/chunk-LM76EMEJ.js +0 -7
- package/dist/bundle/chunks/chunk-M237EDHB.js +0 -2
- package/dist/bundle/chunks/chunk-V6RY5A6T.js +0 -2
- package/dist/bundle/chunks/chunk-WIAXG52U.js +0 -2
- package/dist/bundle/chunks/chunk-WTFD4TII.js +0 -8
- package/dist/bundle/chunks/chunk-Z33PKFXM.js +0 -3
- package/dist/bundle/chunks/cli-main-RKC5Z25H.js +0 -3
- package/dist/bundle/chunks/google-generative-ai-3SKUSCIL.js +0 -2
- package/dist/bundle/chunks/google-vertex-YHSIIE4G.js +0 -2
- package/dist/bundle/chunks/help-fast-path-FWS5ARO5.js +0 -2
- package/dist/bundle/chunks/host-command-L66Y7ZL5.js +0 -2
- package/dist/bundle/chunks/host-session-command-2YNQNTEH.js +0 -20
- package/dist/bundle/chunks/interactive-mode-XOKTNBLA.js +0 -2
- package/dist/bundle/chunks/openai-codex-responses-4BIPACKV.js +0 -10
- package/dist/bundle/chunks/openai-responses-2UOPEJLP.js +0 -3
- package/dist/bundle/chunks/rotation-stream-J2NUPRMG.js +0 -2
- package/dist/bundle/chunks/rpc-mode-WM5WH7TH.js +0 -2
- package/dist/bundle/chunks/session-control-endpoint-MTOAYRRY.js +0 -3
- package/dist/bundle/chunks/session-picker-LU7BPLNI.js +0 -2
|
@@ -0,0 +1,10 @@
|
|
|
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{createWebSocketTransportFailure,startWebSocketLiveness}from"./chunk-YT2ZSZOY.js";import{combineAbortSignals}from"./chunk-SJ5DSOBX.js";import{transportProviderDiagnosticFromError}from"./chunk-MHD7SSHF.js";import{OPENAI_RESPONSES_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI}from"./chunk-JGMG227A.js";import{applyChatGptSubscriptionCacheAffinityHeaders,clampOpenAIPromptCacheKey,deriveOpenAIPromptCacheKey}from"./chunk-PLQ5WRXN.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import{appendRetryAfterMsMarker,extract429RetryAfterMs}from"./chunk-PELNNWGO.js";import{extractChatGptSubscriptionAccountId,getWireIdentity,uuidv7}from"./chunk-2VZJTDUX.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream,resolveResponsesDeferredToolsMode,resolveResponsesToolPlacement}from"./chunk-3AK3WUN4.js";import"./chunk-GVSBCJFI.js";import{registerSessionResourceCleanup}from"./chunk-WHPDEDCC.js";import{buildProviderDiagnostic,categoryForProviderCode,classifyProviderFailure,isOpaqueProviderCode,isProviderDiagnosticResetsAt,isProviderDiagnosticStatus,readProviderDiagnostic}from"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import{createGrammarToolInputProperties}from"./chunk-2AJB5S4C.js";import"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import{ACCOUNT_LIMIT_NEXT_STEP_LEAD,clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,supportsMax,supportsXhigh}from"./chunk-VDPJ7W52.js";import{attachProviderDiagnostic}from"./chunk-45SZOLCU.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env){let noProxy=getProxyEnv("no_proxy",env).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var CHATGPT_USAGE_LIMIT_PREFIX="You have hit your ChatGPT usage limit",OTHER_ROUTES=`${ACCOUNT_LIMIT_NEXT_STEP_LEAD}add an OpenAI API key, sign in with another ChatGPT account, or switch providers.`,USAGE_PAGE="https://chatgpt.com/settings/usage",REACHED_TYPE_ADVICE={workspace_owner_credits_depleted:`Your workspace is out of credits: add credits at ${USAGE_PAGE}.`,workspace_member_credits_depleted:"Your workspace is out of credits: ask your workspace owner to add more.",workspace_owner_usage_limit_reached:"You hit the spend cap set for your workspace: raise it to continue.",workspace_member_usage_limit_reached:"You hit the spend cap your workspace owner set: ask an owner to raise it to continue."},PLAN_ADVICE={plus:`Upgrade to Pro, or buy credits at ${USAGE_PAGE}.`,pro:`Buy credits at ${USAGE_PAGE}.`,prolite:`Buy credits at ${USAGE_PAGE}.`,promax:`Buy credits at ${USAGE_PAGE}.`,free:"Upgrade to ChatGPT Plus to continue.",go:"Upgrade to ChatGPT Plus to continue.",team:"Ask your workspace admin for more access.",business:"Ask your workspace admin for more access.",self_serve_business_usage_based:"Ask your workspace admin for more access.",enterprise_cbp_usage_based:"Ask your workspace admin for more access."};function headerBool(value){let raw=value?.trim().toLowerCase();if(raw==="true"||raw==="1")return!0;if(raw==="false"||raw==="0")return!1}function limitAdvice(input,plan){let reachedType=input.header("x-codex-rate-limit-reached-type")?.trim().toLowerCase(),reached=reachedType?REACHED_TYPE_ADVICE[reachedType]:void 0;return reached||(headerBool(input.header("x-codex-credits-has-credits"))===!0?"This account has ChatGPT credits, but ChatGPT did not apply them to this request.":plan?PLAN_ADVICE[plan]:void 0)}var USAGE_LIMIT_CODE=/usage_limit_reached|usage_not_included/i,HTTP_LIMIT_CODE=/usage_limit_reached|usage_not_included|rate_limit_exceeded/i;function asUsageLimitError(value){return value!==null&&typeof value=="object"?value:void 0}function fromError(error,header){return describeChatGptUsageLimit({...typeof error.plan_type=="string"?{planType:error.plan_type}:{},...typeof error.resets_at=="number"?{resetsAt:error.resets_at}:{},header})}function hasCode(error,pattern){let code=typeof error.code=="string"&&error.code?error.code:error.type;return typeof code=="string"&&pattern.test(code)}function describeChatGptUsageLimitResponse(status,body,headers){let container=asUsageLimitError(body),error=container?asUsageLimitError(Reflect.get(container,"error")):void 0;if(!(!error||!(hasCode(error,HTTP_LIMIT_CODE)||status===429)))return fromError(error,name=>headers.get(name)??void 0)}function describeChatGptUsageLimitEvent(event){let error=asUsageLimitError(event.error);if(!error||!hasCode(error,USAGE_LIMIT_CODE))return;let headers=asUsageLimitError(event.headers);return fromError(error,name=>{if(!headers)return;let entry=Object.entries(headers).find(([key])=>key.toLowerCase()===name);return typeof entry?.[1]=="string"?entry[1]:void 0})}function describeChatGptUsageLimit(input){let plan=input.planType?.trim().toLowerCase()||void 0,sentences=[`${CHATGPT_USAGE_LIMIT_PREFIX}${plan?` (${plan} plan)`:""}.`],advice=limitAdvice(input,plan);if(advice&&sentences.push(advice),sentences.push(OTHER_ROUTES),input.resetsAt!==void 0&&Number.isFinite(input.resetsAt)){let mins=Math.max(0,Math.round((input.resetsAt*1e3-(input.nowMs??Date.now()))/6e4));sentences.push(`Try again in ~${mins} min.`)}return sentences.join(" ")}var CODEX_WEBSOCKET_FALLBACK_COOLDOWN_MS=6e4,CODEX_WEBSOCKET_MID_STREAM_FAILURES_BEFORE_FALLBACK=2,websocketDebugStats=new Map,websocketSseFallbackUntil=new Map,consecutiveMidStreamFailures=new Map;function getOrCreateWebSocketDebugStats(sessionId){let stats=websocketDebugStats.get(sessionId);return stats||(stats={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},websocketDebugStats.set(sessionId,stats)),stats}function getWebSocketDebugStats(sessionId){let stats=websocketDebugStats.get(sessionId);return stats?{...stats}:void 0}function clearWebSocketFallbackState(sessionId){if(sessionId){websocketDebugStats.delete(sessionId),websocketSseFallbackUntil.delete(sessionId),consecutiveMidStreamFailures.delete(sessionId);return}websocketDebugStats.clear(),websocketSseFallbackUntil.clear(),consecutiveMidStreamFailures.clear()}function isWebSocketSseFallbackActive(sessionId){if(!sessionId)return!1;let fallbackUntil=websocketSseFallbackUntil.get(sessionId);if(fallbackUntil===void 0)return!1;let stats=websocketDebugStats.get(sessionId);return fallbackUntil>Date.now()?(stats&&(stats.websocketFallbackActive=!0),!0):(websocketSseFallbackUntil.delete(sessionId),stats&&(stats.websocketFallbackActive=!1),!1)}function recordWebSocketSseFallback(sessionId){if(!sessionId)return;let stats=getOrCreateWebSocketDebugStats(sessionId);stats.sseFallbacks++,stats.websocketFallbackActive=!0}function recordWebSocketFailure(sessionId,error,phase){if(!sessionId)return;let stats=getOrCreateWebSocketDebugStats(sessionId);if(stats.websocketFailures++,stats.lastWebSocketError=formatThrownValue(error),phase==="after_message_stream_start"){let failures=(consecutiveMidStreamFailures.get(sessionId)??0)+1;if(failures<CODEX_WEBSOCKET_MID_STREAM_FAILURES_BEFORE_FALLBACK){consecutiveMidStreamFailures.set(sessionId,failures);return}}consecutiveMidStreamFailures.delete(sessionId),websocketSseFallbackUntil.set(sessionId,Date.now()+CODEX_WEBSOCKET_FALLBACK_COOLDOWN_MS),stats.websocketFallbackActive=!0}function recordWebSocketSuccess(sessionId){sessionId&&consecutiveMidStreamFailures.delete(sessionId)}function asRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function nonEmptyString(value){return typeof value=="string"&&value.length>0?value:void 0}function errorCode(error){return nonEmptyString(error?.code)??nonEmptyString(error?.type)}function resetsAtMs(error,nowMs){let absolute=error?.resets_at;if(typeof absolute=="number"&&Number.isFinite(absolute)&&absolute>0){let ms=Math.round(absolute<1e12?absolute*1e3:absolute);return isProviderDiagnosticResetsAt(ms)?ms:void 0}let relative=error?.resets_in_seconds;if(typeof relative=="number"&&Number.isFinite(relative)&&relative>=0){let ms=Math.round(nowMs+relative*1e3);return isProviderDiagnosticResetsAt(ms)?ms:void 0}}function classifyCodexFailure(facts){let status=isProviderDiagnosticStatus(facts.status)?facts.status:void 0,reset=facts.resetsAt===void 0?{}:{resetsAt:facts.resetsAt};if(facts.code!==void 0&&categoryForProviderCode(facts.code)!==void 0){let classified=classifyProviderFailure({status,code:facts.code})??classifyProviderFailure({status:void 0,code:facts.code});return classified===void 0?void 0:buildProviderDiagnostic({...classified,...reset})}let byStatus=status===void 0?void 0:classifyProviderFailure({status,code:void 0});if(byStatus!==void 0&&byStatus.category!=="unknown")return byStatus;let opaque=[facts.code,facts.fallbackCode].find(code=>code!==void 0&&isOpaqueProviderCode(code));return opaque!==void 0?buildProviderDiagnostic({category:"unknown",code:opaque,evidence:"structured_code"}):byStatus}function codexHttpProviderDiagnostic(status,bodyText,nowMs=Date.now()){let error;try{error=asRecord(asRecord(JSON.parse(bodyText))?.error)}catch{error=void 0}return classifyCodexFailure({status,code:errorCode(error),resetsAt:resetsAtMs(error,nowMs)})}function codexEventProviderDiagnostic(event,nowMs=Date.now()){let response=asRecord(event.response),error=asRecord(event.error)??asRecord(response?.error),status=typeof event.status=="number"?event.status:void 0,eventType=nonEmptyString(event.type);return classifyCodexFailure({status,code:errorCode(error)??nonEmptyString(event.code),...eventType===void 0?{}:{fallbackCode:eventType},resetsAt:resetsAtMs(error,nowMs)})}function normalizeCodexReasoningSummary(reasoningSummary){switch(reasoningSummary){case null:case"off":return;case void 0:case"on":return"auto";default:return reasoningSummary}}function buildCodexReasoning(reasoningEffort,reasoningSummary,modelSupportsReasoning,thinkingOff){let effort;if(reasoningEffort!=null)effort=reasoningEffort;else if(reasoningEffort===void 0&&modelSupportsReasoning&&thinkingOff!==null)effort=thinkingOff??"none";else return;let summary=normalizeCodexReasoningSummary(reasoningSummary);return{effort,...summary===void 0?{}:{summary}}}function loadNodeOs(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:os")??null}var _os=loadNodeOs(),DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","chatgpt-subscription","opencode"]),CODEX_PREVIOUS_RESPONSE_STALE_CODES=new Set(["codex_previous_response_stale"]),WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return new Uint8Array(compressed.buffer,compressed.byteOffset,compressed.byteLength)}catch{return null}}function copyBytesToArrayBuffer(bytes){let copy=new Uint8Array(bytes.byteLength);return copy.set(bytes),copy.buffer}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,normalizedContext,options,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),routingHint=buildCodexRoutingHint(body.model,body.service_tier),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,routingHint,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,routingHint,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId??apiKey,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),recordWebSocketSuccess(cacheSessionId),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart)throw error;let phase=websocketStarted?"after_message_stream_start":"before_message_stream_start";if(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,...websocketStarted?{}:{fallbackTransport:"sse"},eventsEmitted:websocketStarted,phase,requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error,phase),websocketStarted)throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody?copyBytesToArrayBuffer(compressedBody):bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=extract429RetryAfterMs({status:429,headers:response.headers,bodyText:""}),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse,response.headers),errorMessage=info.friendlyMessage||info.message;if(response.status===429){let hintMs=extract429RetryAfterMs({status:response.status,headers:response.headers,bodyText:errorText});hintMs!==void 0&&(errorMessage=appendRetryAfterMsMarker(errorMessage,hintMs))}throw attachProviderDiagnostic(new Error(errorMessage),codexHttpProviderDiagnostic(response.status,errorText))}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let providerDiagnostic=output.stopReason==="error"?readProviderDiagnostic(error)??transportProviderDiagnosticFromError(error):void 0;providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice,serviceTier:options?.serviceTier},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoningEffort=clampedReasoning==="off"?void 0:clampedReasoning==="max"&&supportsMax(model)?"max":clampMaxForOpenAI(clampedReasoning,supportsXhigh(model));return stream(model,context,{...base,reasoningEffort})};function buildRequestBody(model,context,options,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let requestedReasoningEffort=options?.reasoningEffort,mappedReasoningEffort=requestedReasoningEffort===void 0?void 0:requestedReasoningEffort==="none"?model.thinkingLevelMap?.off:model.thinkingLevelMap?.[requestedReasoningEffort],reasoningEffort=mappedReasoningEffort===void 0?requestedReasoningEffort:mappedReasoningEffort,reasoningRequested=requestedReasoningEffort!==void 0&&requestedReasoningEffort!=="none"&&reasoningEffort!==null,supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,toolPlacement=resolveResponsesToolPlacement(context.messages,resolveResponsesDeferredToolsMode(model.compat)!==void 0),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,preserveThinking:reasoningRequested,preserveTextSignatures:!0,grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),initialSystemMessage=getInitialSystemMessage(context.messages),instructions=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",body={model:model.id,store:!1,stream:!0,instructions:instructions||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:options?.cacheRetention==="none"?void 0:deriveOpenAIPromptCacheKey(model.id,context),tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),toolPlacement.requestTools.length>0&&(body.tools=convertResponsesTools(toolPlacement.requestTools,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}));let reasoning=buildCodexReasoning(reasoningEffort,options?.reasoningSummary,model.reasoning,model.thinkingLevelMap?.off);return reasoning&&(body.reasoning=reasoning),applyExtraBody(body,options?.extraBody,OPENAI_RESPONSES_RESERVED_BODY_KEYS),body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"ultrafast":return["gpt-6-astra","gpt-6.1-sol"].includes(model.upstreamModelId??model.id)?8:1;case"flex":return .5;case"priority":case"fast":return 2.5;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority"||requestServiceTier==="fast"||requestServiceTier==="ultrafast")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output,model,options?.onProviderStreamEvent),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}},ProviderStreamEventCallbackError=class extends Error{constructor(cause){super(formatThrownValue(cause)),this.name="ProviderStreamEventCallbackError",this.cause=cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError||error instanceof ProviderStreamEventCallbackError}function asRecord2(value){return value&&typeof value=="object"?value:null}function getString(value){return typeof value=="string"?value:void 0}function getCodexEventError(event){let response=asRecord2(event.response);return asRecord2(event.error)??(response?asRecord2(response.error):null)}function getCodexEventErrorCode(event){let error=getCodexEventError(event);return getString(error?.code)??getString(error?.type)??getString(event.code)??""}function getCodexEventErrorMessage(event){let response=asRecord2(event.response),error=getCodexEventError(event);return getString(error?.message)??getString(event.message)??getString(response?.message)??""}function isCodexPreviousResponseStale(error){return error instanceof CodexApiError&&typeof error.code=="string"&&CODEX_PREVIOUS_RESPONSE_STALE_CODES.has(error.code)}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}async function*mapCodexEvents(events,output,model,onProviderStreamEvent){for await(let event of events){try{await onProviderStreamEvent?.(event,model)}catch(error){throw new ProviderStreamEventCallbackError(error)}let type=typeof event.type=="string"?event.type:void 0;if(!type)continue;if(type==="error"){let code=getCodexEventErrorCode(event),message=getCodexEventErrorMessage(event),errorText=describeChatGptUsageLimitEvent(event)??`Codex error: ${message||code||JSON.stringify(event)}`,hintMs=extract429RetryAfterMs({bodyText:JSON.stringify(event)});throw hintMs!==void 0&&(errorText=appendRetryAfterMsMarker(errorText,hintMs)),attachProviderDiagnostic(new CodexApiError(errorText,{code:code||void 0,payload:event}),codexEventProviderDiagnostic(event))}if(type==="response.failed"){let code=getCodexEventErrorCode(event),message=getCodexEventErrorMessage(event),errorText=describeChatGptUsageLimitEvent({...event,error:getCodexEventError(event)})??(message||"Codex response failed"),hintMs=extract429RetryAfterMs({bodyText:JSON.stringify(event)});throw hintMs!==void 0&&(errorText=appendRetryAfterMsMarker(errorText,hintMs)),attachProviderDiagnostic(new CodexApiError(errorText,{code,payload:event}),codexEventProviderDiagnostic(event))}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield JSON.parse(JSON.stringify(event))}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
|
|
3
|
+
|
|
4
|
+
`);let idx=buffer.indexOf(`
|
|
5
|
+
|
|
6
|
+
`);for(;idx!==-1;){let chunk=buffer.slice(0,idx);buffer=buffer.slice(idx+2);let dataLines=chunk.split(`
|
|
7
|
+
`).filter(l=>l.startsWith("data:")).map(l=>l.slice(5).trim());if(dataLines.length>0){let data=dataLines.join(`
|
|
8
|
+
`).trim();if(data&&data!=="[DONE]")try{yield JSON.parse(data)}catch(cause){throw new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`,{cause,payload:data})}}idx=buffer.indexOf(`
|
|
9
|
+
|
|
10
|
+
`)}if(done)break}}finally{signal?.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}var OPENAI_BETA_RESPONSES_WEBSOCKETS="responses_websockets=2026-02-06",SESSION_WEBSOCKET_CACHE_TTL_MS=300*1e3,SESSION_WEBSOCKET_MAX_AGE_MS=3300*1e3,websocketSessionCache=new Map;function getChatGptSubscriptionWebSocketDebugStats(sessionId){return getWebSocketDebugStats(sessionId)}function resetChatGptSubscriptionWebSocketDebugStats(sessionId){clearWebSocketFallbackState(sessionId)}function closeChatGptSubscriptionWebSocketSessions(sessionId){let closeEntry=entry=>{unparkSessionWebSocket(entry),closeWebSocketSilently(entry.socket,1e3,"debug_close")};if(sessionId){for(let entry of websocketSessionCache.get(sessionId)?.values()??[])closeEntry(entry);websocketSessionCache.delete(sessionId),clearWebSocketFallbackState(sessionId);return}for(let accountEntries of websocketSessionCache.values())for(let entry of accountEntries.values())closeEntry(entry);websocketSessionCache.clear(),clearWebSocketFallbackState()}registerSessionResourceCleanup(closeChatGptSubscriptionWebSocketSessions);var _cachedWebsocket=null;async function getWebSocketConstructor(env){if(!env&&_cachedWebsocket)return _cachedWebsocket;if(typeof process<"u"&&process.versions?.bun){let WebSocketWithProxy=class{constructor(url,options){let _opts={};Array.isArray(options)||typeof options=="string"?_opts={protocols:options}:_opts={...options};let proxyUrl=resolveHttpProxyUrlForTarget(url.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),env);this.socket=Reflect.construct(WebSocket,[url,{..._opts,...proxyUrl?{proxy:proxyUrl.toString()}:{}}]);let innerPing=this.socket.ping;typeof innerPing=="function"&&(this.ping=data=>innerPing.call(this.socket,data))}get readyState(){return getWebSocketReadyState(this.socket)}close(code,reason){this.socket.close(code,reason)}send(data){this.socket.send(data)}addEventListener(type,listener){this.socket.addEventListener(type,listener)}removeEventListener(type,listener){this.socket.removeEventListener(type,listener)}};return env||(_cachedWebsocket=WebSocketWithProxy),WebSocketWithProxy}let ctor=globalThis.WebSocket;return isWebSocketConstructor(ctor)?ctor:null}function isWebSocketConstructor(value){return typeof value=="function"}function getWebSocketReadyState(socket){let readyState=socket.readyState;return typeof readyState=="number"?readyState:void 0}function isWebSocketReusable(socket){let readyState=getWebSocketReadyState(socket);return readyState===void 0||readyState===1}function isWebSocketSessionExpired(entry){return Date.now()-entry.createdAt>=SESSION_WEBSOCKET_MAX_AGE_MS}function closeWebSocketSilently(socket,code=1e3,reason="done"){try{socket.close(code,reason)}catch{}}function evictSessionWebSocket(sessionId,accountId,entry,reason){unparkSessionWebSocket(entry),closeWebSocketSilently(entry.socket,1e3,reason);let accountEntries=websocketSessionCache.get(sessionId);accountEntries?.get(accountId)===entry&&accountEntries.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId)}function unparkSessionWebSocket(entry){entry.idleTimer&&(clearTimeout(entry.idleTimer),entry.idleTimer=void 0),entry.parkedCloseListener&&(entry.socket.removeEventListener("close",entry.parkedCloseListener),entry.socket.removeEventListener("error",entry.parkedCloseListener),entry.parkedCloseListener=void 0)}function parkSessionWebSocket(sessionId,accountId,entry){unparkSessionWebSocket(entry),entry.busy=!1,entry.idleTimer=setTimeout(()=>{entry.busy||evictSessionWebSocket(sessionId,accountId,entry,"idle_timeout")},SESSION_WEBSOCKET_CACHE_TTL_MS);let onParkedClose=()=>{entry.busy||evictSessionWebSocket(sessionId,accountId,entry,"parked_close")};entry.parkedCloseListener=onParkedClose,entry.socket.addEventListener("close",onParkedClose),entry.socket.addEventListener("error",onParkedClose)}async function connectWebSocket(url,headers,signal,connectTimeoutMs=DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS,env){let WebSocketCtor=await getWebSocketConstructor(env);if(!WebSocketCtor)throw new Error("WebSocket transport is not available in this runtime");let wsHeaders=headersToRecord(headers);return delete wsHeaders["OpenAI-Beta"],new Promise((resolve,reject)=>{let settled=!1,timeout,socket;try{socket=new WebSocketCtor(url,{headers:wsHeaders})}catch(error){reject(error instanceof Error?error:new Error(String(error)));return}let cleanup=()=>{timeout&&(clearTimeout(timeout),timeout=void 0),transportFailure.dispose(),socket.removeEventListener("open",onOpen),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)},fail=(error,closeReason)=>{settled||(settled=!0,cleanup(),closeReason&&closeWebSocketSilently(socket,1e3,closeReason),reject(error))},transportFailure=createWebSocketTransportFailure(error=>fail(error)),onOpen=()=>{settled||(settled=!0,cleanup(),resolve(socket))},onError=event=>{transportFailure.onError(event)},onClose=event=>{transportFailure.onClose(event)},onAbort=()=>{fail(new Error("Request was aborted"),"aborted")};socket.addEventListener("open",onOpen),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort),connectTimeoutMs>0&&(timeout=setTimeout(()=>{fail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`),"connect_timeout")},connectTimeoutMs)),signal?.aborted&&onAbort()})}async function acquireWebSocket(url,headers,sessionId,accountId,signal,connectTimeoutMs,env){if(!sessionId){let socket2=await connectWebSocket(url,headers,signal,connectTimeoutMs,env);return{socket:socket2,reused:!1,release:()=>closeWebSocketSilently(socket2)}}let accountEntries=websocketSessionCache.get(sessionId),cached=accountEntries?.get(accountId),routingHint=headers.get("x-codex-routing-hint");if(cached&&cached.routingHint!==routingHint&&(closeWebSocketSilently(cached.socket,1e3,"routing_hint_changed"),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId),cached=void 0),cached){if(unparkSessionWebSocket(cached),!cached.busy&&isWebSocketSessionExpired(cached))closeWebSocketSilently(cached.socket,1e3,"connection_age_limit"),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId);else if(!cached.busy&&isWebSocketReusable(cached.socket))return cached.busy=!0,{socket:cached.socket,entry:cached,reused:!0,release:({keep}={})=>{if(!keep||!isWebSocketReusable(cached.socket)){closeWebSocketSilently(cached.socket);let currentEntries=websocketSessionCache.get(sessionId);currentEntries?.get(accountId)===cached&¤tEntries.delete(accountId),currentEntries?.size===0&&websocketSessionCache.delete(sessionId);return}parkSessionWebSocket(sessionId,accountId,cached)}};if(cached.busy){let socket2=await connectWebSocket(url,headers,signal,connectTimeoutMs,env);return{socket:socket2,reused:!1,release:()=>{closeWebSocketSilently(socket2)}}}isWebSocketReusable(cached.socket)||(closeWebSocketSilently(cached.socket),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId))}let socket=await connectWebSocket(url,headers,signal,connectTimeoutMs,env),entry={socket,busy:!0,createdAt:Date.now(),routingHint};return accountEntries=websocketSessionCache.get(sessionId),accountEntries||(accountEntries=new Map,websocketSessionCache.set(sessionId,accountEntries)),accountEntries.set(accountId,entry),{socket,entry,reused:!1,release:({keep}={})=>{if(!keep||!isWebSocketReusable(entry.socket)){closeWebSocketSilently(entry.socket),entry.idleTimer&&clearTimeout(entry.idleTimer);let currentEntries=websocketSessionCache.get(sessionId);currentEntries?.get(accountId)===entry&¤tEntries.delete(accountId),currentEntries?.size===0&&websocketSessionCache.delete(sessionId);return}parkSessionWebSocket(sessionId,accountId,entry)}}}async function decodeWebSocketData(data){if(typeof data=="string")return data;if(data instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(data));if(ArrayBuffer.isView(data)){let view=data;return new TextDecoder().decode(new Uint8Array(view.buffer,view.byteOffset,view.byteLength))}if(data&&typeof data=="object"&&"arrayBuffer"in data){let arrayBuffer=await data.arrayBuffer();return new TextDecoder().decode(new Uint8Array(arrayBuffer))}return null}async function*parseWebSocket(socket,signal,idleTimeoutMs){let queue=[],pending=null,done=!1,failed=null,sawCompletion=!1,wake=()=>{if(!pending)return;let resolve=pending;pending=null,resolve()},liveness=startWebSocketLiveness(socket,error=>{failed=error,done=!0,closeWebSocketSilently(socket,1e3,"liveness_timeout"),wake()}),onMessage=event=>{liveness.noteActivity(),(async()=>{let text=null;try{if(!event||typeof event!="object"||!("data"in event)||(text=await decodeWebSocketData(event.data),!text))return;let parsed=JSON.parse(text),type=typeof parsed.type=="string"?parsed.type:"";(type==="response.completed"||type==="response.done"||type==="response.incomplete")&&(sawCompletion=!0,done=!0),queue.push(parsed),wake()}catch(cause){failed=new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`,{cause,payload:text}),done=!0,wake()}})()},transportFailure=createWebSocketTransportFailure(error=>{failed||(failed=error),done=!0,wake()}),onError=event=>{transportFailure.onError(event)},onClose=event=>{if(sawCompletion){transportFailure.dispose(),done=!0,wake();return}transportFailure.onClose(event)},onAbort=()=>{failed=new Error("Request was aborted"),done=!0,wake()};socket.addEventListener("message",onMessage),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort);try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");if(queue.length>0){yield queue.shift();continue}if(done)break;let timeout;await new Promise((resolve,reject)=>{pending=resolve,idleTimeoutMs!==void 0&&idleTimeoutMs>0&&(timeout=setTimeout(()=>{let error=new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);failed=error,done=!0,pending=null,closeWebSocketSilently(socket,1e3,"idle_timeout"),reject(error)},idleTimeoutMs))}).finally(()=>{timeout&&clearTimeout(timeout)})}if(failed)throw failed;if(!sawCompletion)throw new Error("WebSocket stream closed before response.completed")}finally{liveness.stop(),transportFailure.dispose(),socket.removeEventListener("message",onMessage),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)}}function requestBodyWithoutInput(body){let{input:_input,previous_response_id:_previousResponseId,...rest}=body;return rest}function responseInputsEqual(a,b){return JSON.stringify(a??[])===JSON.stringify(b??[])}function requestBodiesMatchExceptInput(a,b){return JSON.stringify(requestBodyWithoutInput(a))===JSON.stringify(requestBodyWithoutInput(b))}function getCachedWebSocketInputDelta(body,continuation){if(!requestBodiesMatchExceptInput(body,continuation.lastRequestBody))return;let currentInput=body.input??[],baseline=[...continuation.lastRequestBody.input??[],...continuation.lastResponseItems];if(currentInput.length<baseline.length)return;let prefix=currentInput.slice(0,baseline.length);if(responseInputsEqual(prefix,baseline))return currentInput.slice(baseline.length)}function buildCachedWebSocketRequestBody(entry,body){let continuation=entry.continuation;if(!continuation)return body;let delta=getCachedWebSocketInputDelta(body,continuation);return!delta||!continuation.lastResponseId?(entry.continuation=void 0,body):{...body,previous_response_id:continuation.lastResponseId,input:delta}}function recordWebSocketRequestStats(stats,requestBody,reused,useCachedContext){stats&&(stats.requests++,reused?stats.connectionsReused++:stats.connectionsCreated++,useCachedContext&&stats.cachedContextRequests++,requestBody.store===!0&&stats.storeTrueRequests++,stats.lastInputItems=requestBody.input?.length??0,requestBody.previous_response_id?(stats.deltaRequests++,stats.lastDeltaInputItems=requestBody.input?.length??0,stats.lastPreviousResponseId=requestBody.previous_response_id):(stats.fullContextRequests++,stats.lastDeltaInputItems=void 0,stats.lastPreviousResponseId=void 0))}async function*startWebSocketOutputOnFirstEvent(events,onStart){let started=!1;for await(let event of events)started||(started=!0,onStart()),yield event}async function processWebSocketStream(url,body,headers,output,stream2,model,onStart,idleTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options){let{socket,entry,reused,release}=await acquireWebSocket(url,headers,cacheSessionId,accountId,options?.signal,websocketConnectTimeoutMs,options?.env),keepConnection=!0,useCachedContext=options?.transport==="websocket-cached"||options?.transport==="auto",fullBody=body,requestBody=useCachedContext&&entry?buildCachedWebSocketRequestBody(entry,fullBody):fullBody,stats=cacheSessionId?getOrCreateWebSocketDebugStats(cacheSessionId):void 0,recoveredStalePreviousResponse=!1;try{for(;;){recordWebSocketRequestStats(stats,requestBody,reused&&!recoveredStalePreviousResponse,useCachedContext);try{socket.send(JSON.stringify({type:"response.create",...requestBody})),await processResponsesStream(startWebSocketOutputOnFirstEvent(mapCodexEvents(parseWebSocket(socket,options?.signal,idleTimeoutMs),output,model,options?.onProviderStreamEvent),onStart),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)});break}catch(error){if(!recoveredStalePreviousResponse&&entry&&requestBody.previous_response_id&&isCodexPreviousResponseStale(error)&&!options?.signal?.aborted){entry.continuation=void 0,requestBody=fullBody,recoveredStalePreviousResponse=!0;continue}throw error}}if(options?.signal?.aborted)keepConnection=!1;else if(useCachedContext&&entry&&output.responseId){let responseItems=convertResponsesMessages(model,normalizeContext({messages:[output]}),CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties}).filter(item=>item.type!=="function_call_output"&&item.type!=="custom_tool_call_output");entry.continuation={lastRequestBody:fullBody,lastResponseId:output.responseId,lastResponseItems:responseItems}}}catch(error){throw entry&&(entry.continuation=void 0),keepConnection=!1,error}finally{release({keep:keepConnection})}}async function parseErrorResponse(response,headers){let raw=await response.text(),message=raw||response.statusText||"Request failed",friendlyMessage;try{let parsed=JSON.parse(raw);friendlyMessage=describeChatGptUsageLimitResponse(response.status,parsed,headers);let err=parsed?.error;err&&(message=err.message||friendlyMessage||message)}catch{}return{message,friendlyMessage}}function extractAccountId(token){return extractChatGptSubscriptionAccountId(token)}function buildCodexRoutingHint(modelId,serviceTier){return serviceTier?`model=${modelId};tier=${serviceTier}`:`model=${modelId}`}function buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token,routingHint){let headers=new Headers(initHeaders);for(let[key,value]of Object.entries(additionalHeaders||{}))value===null?headers.delete(key):headers.set(key,value);headers.set("Authorization",`Bearer ${token}`),accountId?headers.set("chatgpt-account-id",accountId):headers.delete("chatgpt-account-id");let identity=getWireIdentity();headers.set("originator",identity);let userAgent=_os?`${identity} (${_os.platform()} ${_os.release()}; ${_os.arch()})`:`${identity} (browser)`;return headers.set("User-Agent",userAgent),headers.set("x-codex-routing-hint",routingHint),headers}function buildSSEHeaders(initHeaders,additionalHeaders,accountId,token,routingHint,sessionId){let headers=buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token,routingHint);return headers.set("OpenAI-Beta","responses=experimental"),headers.set("accept","text/event-stream"),headers.set("content-type","application/json"),applyChatGptSubscriptionCacheAffinityHeaders(headers,sessionId),headers}function buildWebSocketHeaders(initHeaders,additionalHeaders,accountId,token,routingHint,requestId){let headers=buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token,routingHint);return headers.delete("accept"),headers.delete("content-type"),headers.delete("OpenAI-Beta"),headers.delete("openai-beta"),headers.set("OpenAI-Beta",OPENAI_BETA_RESPONSES_WEBSOCKETS),applyChatGptSubscriptionCacheAffinityHeaders(headers,requestId),headers}export{closeChatGptSubscriptionWebSocketSessions,getChatGptSubscriptionWebSocketDebugStats,resetChatGptSubscriptionWebSocketDebugStats,stream,streamSimple};
|
package/dist/bundle/chunks/{openai-completions-NHDMDAS7.js → openai-completions-EZBOIXHP.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
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{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{clampOpenAIPromptCacheKey}from"./chunk-AEJUOQ7U.js";import{formatGitHubCopilotToolLimitError,limitGitHubCopilotTools,recordGitHubCopilotToolLimit,withGitHubCopilotFailureNote}from"./chunk-Z33PKFXM.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{awaitProviderTransport,iterateProviderTransport,openAICompatibleProviderDiagnosticFromError}from"./chunk-V6RY5A6T.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-MVNVDGYF.js";import{retryProviderStreamRequest}from"./chunk-EDOW5W5H.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-RUGYFYH7.js";import{primeStreamUntilContent,sendWithForcedToolChoiceFallback}from"./chunk-OEFCY46F.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-RFB5CBW7.js";import{getOpenAICompletionsCompat}from"./chunk-QGJLZ6BI.js";import{readProviderDiagnostic}from"./chunk-AA2L2RHH.js";import{appendGrammarToolInputJsonDelta,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-WQLMQGOW.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getDeclaredTools,getSystemMessageText,inferOpenAIThinkingLevelMap,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,supportsMax,supportsXhigh}from"./chunk-LAWS3FYQ.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var KIMI_K3_THINKING_LEVEL_MAP={off:null,minimal:null,low:"low",medium:null,high:"high",xhigh:null,max:"max"},DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"max",max:"max"},OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},MIMO_THINKING_LEVEL_MAP={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:null},OLLAMA_THINKING_LEVEL_MAP={off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:"high"};function getThinkingLevelMap(model,compat){let inferred=inferOpenAIThinkingLevelMap(model);if(inferred!==void 0)return inferred;let id=model.id.toLowerCase(),isKimiK3=id==="k3"||id.startsWith("k3-")||/(?:^|[/:-])kimi-k3(?:$|[/.:_-])/.test(id),isDeepSeek=id.includes("deepseek"),isMiMo=/\bmimo\b/.test(id),isGlm5x=/(?:^|[/:-])glm-5\.[23](?:$|[/.:_-])/.test(id);if(model.provider==="ollama")return OLLAMA_THINKING_LEVEL_MAP;if(isKimiK3)return KIMI_K3_THINKING_LEVEL_MAP;if(compat.thinkingFormat==="openrouter"&&isDeepSeek)return OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP;if((compat.thinkingFormat==="openai"||compat.thinkingFormat==="openrouter")&&isMiMo)return MIMO_THINKING_LEVEL_MAP;if(isDeepSeek)return DEEPSEEK_THINKING_LEVEL_MAP;if(isGlm5x)return compat.thinkingFormat==="zai"?DEEPSEEK_THINKING_LEVEL_MAP:compat.thinkingFormat==="openrouter"?{xhigh:"xhigh"}:{max:"max"}}function resolveReasoningEffort(thinkingLevelMap,effort){let mapped=thinkingLevelMap?.[effort];return mapped===void 0?effort:typeof mapped=="string"?mapped:void 0}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function resolveKimiDeferredTools(messages,compat){let deferred=new Map;if(compat.deferredToolsMode!=="kimi")return deferred;let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);for(let tool of getCurrentTools(messages))names.has(tool.name)&&deferred.set(tool.name,tool);return deferred}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isRecord(value){return typeof value=="object"&&value!==null}function getOpenRouterRawMetadata(error){if(!isRecord(error)||!isRecord(error.error)||!isRecord(error.error.metadata))return;let rawMetadata=error.error.metadata.raw;return typeof rawMetadata=="string"?rawMetadata:void 0}function isForcedOpenAICompletionsToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function chatChunkHasContent(chunk){return!isRecord(chunk)||!Array.isArray(chunk.choices)?!1:chunk.choices.some(choice=>{if(!isRecord(choice))return!1;if(typeof choice.finish_reason=="string"&&choice.finish_reason.length>0)return!0;let delta=choice.delta;return isRecord(delta)?Array.isArray(delta.tool_calls)&&delta.tool_calls.length>0?!0:["content","reasoning_content","reasoning","reasoning_text"].some(field=>typeof delta[field]=="string"&&delta[field].length>0):!1})}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}function toReplayableReasoningDetail(detail){let common={};switch(detail.id!==void 0&&(common.id=detail.id),detail.format!==void 0&&(common.format=detail.format),detail.type){case"reasoning.text":{let replayable={...common,type:"reasoning.text",text:detail.text};return detail.signature!==void 0&&(replayable.signature=detail.signature),replayable}case"reasoning.summary":return{...common,type:"reasoning.summary",summary:detail.summary};case"reasoning.encrypted":return{...common,type:"reasoning.encrypted",data:detail.data}}}function toReplayableReasoningDetails(details){return details.map(toReplayableReasoningDetail)}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(value){return OPENAI_COMPLETIONS_REASONING_FIELDS.some(field=>field===value)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getOpenAICompletionsCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),compat=getOpenAICompletionsCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=normalizeRequestToolSchemas(params,compat);let limitedTools=limitGitHubCopilotTools(model.provider,params.tools,params.tool_choice);limitedTools.omittedCount>0&&(params={...params,tools:limitedTools.tools},recordGitHubCopilotToolLimit(output,limitedTools.omittedCount));let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},createChatCompletion=client.chat.completions.create.bind(client.chat.completions),createStream=async body=>{let{data,response}=await awaitProviderTransport(()=>createChatCompletion(body,requestOptions).withResponse(),openAICompatibleProviderDiagnosticFromError);return{data:iterateProviderTransport(data,openAICompatibleProviderDiagnosticFromError),response}},createRequest=async()=>{let sent=await sendWithForcedToolChoiceFallback({target:model,params,acceptsForcedToolChoice:compat.supportsForcedToolChoice!==!1,isForced:isForcedOpenAICompletionsToolChoice,send:async sentParams=>{let created=await createStream(sentParams);return isForcedOpenAICompletionsToolChoice(sentParams.tool_choice)?{...created,data:await primeStreamUntilContent(created.data,chatChunkHasContent)}:created}});return params=sent.params,sent.result},{stream:openaiStream}=await retryProviderStreamRequest(async()=>{let{data,response}=await createRequest();return await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),{stream:data,metadata:response}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,activeBlock=null,deferMixedEvents=!1,hasFinishReason=!1,deferredTextDeltas=[],deferredThinkingDeltas=[],deferredToolCallDeltas=new Map,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},finishActiveBlock=()=>{activeBlock&&(finishBlock(activeBlock),activeBlock=null)},ensureTextBlock=()=>(textBlock||(deferMixedEvents||(finishActiveBlock(),thinkingBlock=null),textBlock={type:"text",text:""},blocks.push(textBlock),deferMixedEvents||(activeBlock=textBlock,stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output}))),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(deferMixedEvents||(finishActiveBlock(),textBlock=null),thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),deferMixedEvents||(activeBlock=thinkingBlock,stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output}))),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){deferMixedEvents||(finishActiveBlock(),textBlock=null,thinkingBlock=null);let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),deferMixedEvents||(activeBlock=block,stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output}))}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block},flushDeferredBlocks=()=>{for(let block of blocks){let contentIndex=getContentIndex(block);if(block.type==="text"){stream2.push({type:"text_start",contentIndex,partial:output});for(let delta of deferredTextDeltas)stream2.push({type:"text_delta",contentIndex,delta,partial:output})}else if(block.type==="thinking"){stream2.push({type:"thinking_start",contentIndex,partial:output});for(let delta of deferredThinkingDeltas)stream2.push({type:"thinking_delta",contentIndex,delta,partial:output})}else{stream2.push({type:"toolcall_start",contentIndex,partial:output});for(let delta of deferredToolCallDeltas.get(block)??[])stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}finishBlock(block)}};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(!choice)continue;let choiceUsage=choice.usage;if(!chunk.usage&&choiceUsage&&(output.usage=parseChunkUsage(choiceUsage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let contentDelta=typeof choice.delta.content=="string"&&choice.delta.content.length>0?choice.delta.content:null,reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(blocks.length===0&&contentDelta&&foundReasoningField&&(deferMixedEvents=!0),contentDelta){let block=ensureTextBlock();block.text+=contentDelta,deferMixedEvents?deferredTextDeltas.push(contentDelta):stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:contentDelta,partial:output})}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,deferMixedEvents?deferredThinkingDeltas.push(delta):stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}if(deferMixedEvents){let deltas=deferredToolCallDeltas.get(block)??[];deltas.push(delta),deferredToolCallDeltas.set(block,deltas)}else stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];appendOpenAIReasoningDetail(preservedDetails,detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}if(deferMixedEvents?flushDeferredBlocks():finishActiveBlock(),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error";let providerDiagnostic=output.stopReason==="error"?readProviderDiagnostic(error):void 0;providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),output.errorMessage=withGitHubCopilotFailureNote(formatGitHubCopilotToolLimitError(output,formatProviderError(normalizeProviderError(error))),model.provider,error);let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
2
|
+
import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{formatGitHubCopilotToolLimitError,limitGitHubCopilotTools,recordGitHubCopilotToolLimit,withGitHubCopilotFailureNote}from"./chunk-OMN4QWFA.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{awaitProviderTransport,iterateProviderTransport,openAICompatibleProviderDiagnosticFromError}from"./chunk-MHD7SSHF.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-JGMG227A.js";import{retryProviderStreamRequest}from"./chunk-EDOW5W5H.js";import{clampOpenAIPromptCacheKey}from"./chunk-PLQ5WRXN.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-RUGYFYH7.js";import{primeStreamUntilContent,sendWithForcedToolChoiceFallback}from"./chunk-OEFCY46F.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-RFB5CBW7.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import{getOpenAICompletionsCompat}from"./chunk-QGJLZ6BI.js";import{readProviderDiagnostic}from"./chunk-AA2L2RHH.js";import{appendGrammarToolInputJsonDelta,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-2AJB5S4C.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getDeclaredTools,getSystemMessageText,inferOpenAIThinkingLevelMap,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,supportsMax,supportsXhigh}from"./chunk-VDPJ7W52.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var KIMI_K3_THINKING_LEVEL_MAP={off:null,minimal:null,low:"low",medium:null,high:"high",xhigh:null,max:"max"},DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"max",max:"max"},OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},MIMO_THINKING_LEVEL_MAP={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:null},OLLAMA_THINKING_LEVEL_MAP={off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:"high"};function getThinkingLevelMap(model,compat){let inferred=inferOpenAIThinkingLevelMap(model);if(inferred!==void 0)return inferred;let id=model.id.toLowerCase(),isKimiK3=id==="k3"||id.startsWith("k3-")||/(?:^|[/:-])kimi-k3(?:$|[/.:_-])/.test(id),isDeepSeek=id.includes("deepseek"),isMiMo=/\bmimo\b/.test(id),isGlm5x=/(?:^|[/:-])glm-5\.[23](?:$|[/.:_-])/.test(id);if(model.provider==="ollama")return OLLAMA_THINKING_LEVEL_MAP;if(isKimiK3)return KIMI_K3_THINKING_LEVEL_MAP;if(compat.thinkingFormat==="openrouter"&&isDeepSeek)return OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP;if((compat.thinkingFormat==="openai"||compat.thinkingFormat==="openrouter")&&isMiMo)return MIMO_THINKING_LEVEL_MAP;if(isDeepSeek)return DEEPSEEK_THINKING_LEVEL_MAP;if(isGlm5x)return compat.thinkingFormat==="zai"?DEEPSEEK_THINKING_LEVEL_MAP:compat.thinkingFormat==="openrouter"?{xhigh:"xhigh"}:{max:"max"}}function resolveReasoningEffort(thinkingLevelMap,effort){let mapped=thinkingLevelMap?.[effort];return mapped===void 0?effort:typeof mapped=="string"?mapped:void 0}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function resolveKimiDeferredTools(messages,compat){let deferred=new Map;if(compat.deferredToolsMode!=="kimi")return deferred;let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);for(let tool of getCurrentTools(messages))names.has(tool.name)&&deferred.set(tool.name,tool);return deferred}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isRecord(value){return typeof value=="object"&&value!==null}function getOpenRouterRawMetadata(error){if(!isRecord(error)||!isRecord(error.error)||!isRecord(error.error.metadata))return;let rawMetadata=error.error.metadata.raw;return typeof rawMetadata=="string"?rawMetadata:void 0}function isForcedOpenAICompletionsToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function chatChunkHasContent(chunk){return!isRecord(chunk)||!Array.isArray(chunk.choices)?!1:chunk.choices.some(choice=>{if(!isRecord(choice))return!1;if(typeof choice.finish_reason=="string"&&choice.finish_reason.length>0)return!0;let delta=choice.delta;return isRecord(delta)?Array.isArray(delta.tool_calls)&&delta.tool_calls.length>0?!0:["content","reasoning_content","reasoning","reasoning_text"].some(field=>typeof delta[field]=="string"&&delta[field].length>0):!1})}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}function toReplayableReasoningDetail(detail){let common={};switch(detail.id!==void 0&&(common.id=detail.id),detail.format!==void 0&&(common.format=detail.format),detail.type){case"reasoning.text":{let replayable={...common,type:"reasoning.text",text:detail.text};return detail.signature!==void 0&&(replayable.signature=detail.signature),replayable}case"reasoning.summary":return{...common,type:"reasoning.summary",summary:detail.summary};case"reasoning.encrypted":return{...common,type:"reasoning.encrypted",data:detail.data}}}function toReplayableReasoningDetails(details){return details.map(toReplayableReasoningDetail)}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(value){return OPENAI_COMPLETIONS_REASONING_FIELDS.some(field=>field===value)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getOpenAICompletionsCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),compat=getOpenAICompletionsCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=normalizeRequestToolSchemas(params,compat);let limitedTools=limitGitHubCopilotTools(model.provider,params.tools,params.tool_choice);limitedTools.omittedCount>0&&(params={...params,tools:limitedTools.tools},recordGitHubCopilotToolLimit(output,limitedTools.omittedCount));let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},createChatCompletion=client.chat.completions.create.bind(client.chat.completions),createStream=async body=>{let{data,response}=await awaitProviderTransport(()=>createChatCompletion(body,requestOptions).withResponse(),openAICompatibleProviderDiagnosticFromError);return{data:iterateProviderTransport(data,openAICompatibleProviderDiagnosticFromError),response}},createRequest=async()=>{let sent=await sendWithForcedToolChoiceFallback({target:model,params,acceptsForcedToolChoice:compat.supportsForcedToolChoice!==!1,isForced:isForcedOpenAICompletionsToolChoice,send:async sentParams=>{let created=await createStream(sentParams);return isForcedOpenAICompletionsToolChoice(sentParams.tool_choice)?{...created,data:await primeStreamUntilContent(created.data,chatChunkHasContent)}:created}});return params=sent.params,sent.result},{stream:openaiStream}=await retryProviderStreamRequest(async()=>{let{data,response}=await createRequest();return await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),{stream:data,metadata:response}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,activeBlock=null,deferMixedEvents=!1,hasFinishReason=!1,deferredTextDeltas=[],deferredThinkingDeltas=[],deferredToolCallDeltas=new Map,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},finishActiveBlock=()=>{activeBlock&&(finishBlock(activeBlock),activeBlock=null)},ensureTextBlock=()=>(textBlock||(deferMixedEvents||(finishActiveBlock(),thinkingBlock=null),textBlock={type:"text",text:""},blocks.push(textBlock),deferMixedEvents||(activeBlock=textBlock,stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output}))),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(deferMixedEvents||(finishActiveBlock(),textBlock=null),thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),deferMixedEvents||(activeBlock=thinkingBlock,stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output}))),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){deferMixedEvents||(finishActiveBlock(),textBlock=null,thinkingBlock=null);let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),deferMixedEvents||(activeBlock=block,stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output}))}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block},flushDeferredBlocks=()=>{for(let block of blocks){let contentIndex=getContentIndex(block);if(block.type==="text"){stream2.push({type:"text_start",contentIndex,partial:output});for(let delta of deferredTextDeltas)stream2.push({type:"text_delta",contentIndex,delta,partial:output})}else if(block.type==="thinking"){stream2.push({type:"thinking_start",contentIndex,partial:output});for(let delta of deferredThinkingDeltas)stream2.push({type:"thinking_delta",contentIndex,delta,partial:output})}else{stream2.push({type:"toolcall_start",contentIndex,partial:output});for(let delta of deferredToolCallDeltas.get(block)??[])stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}finishBlock(block)}};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(!choice)continue;let choiceUsage=choice.usage;if(!chunk.usage&&choiceUsage&&(output.usage=parseChunkUsage(choiceUsage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let contentDelta=typeof choice.delta.content=="string"&&choice.delta.content.length>0?choice.delta.content:null,reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(blocks.length===0&&contentDelta&&foundReasoningField&&(deferMixedEvents=!0),contentDelta){let block=ensureTextBlock();block.text+=contentDelta,deferMixedEvents?deferredTextDeltas.push(contentDelta):stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:contentDelta,partial:output})}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,deferMixedEvents?deferredThinkingDeltas.push(delta):stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}if(deferMixedEvents){let deltas=deferredToolCallDeltas.get(block)??[];deltas.push(delta),deferredToolCallDeltas.set(block,deltas)}else stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];appendOpenAIReasoningDetail(preservedDetails,detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}if(deferMixedEvents?flushDeferredBlocks():finishActiveBlock(),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error";let providerDiagnostic=output.stopReason==="error"?readProviderDiagnostic(error):void 0;providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),output.errorMessage=withGitHubCopilotFailureNote(formatGitHubCopilotToolLimitError(output,formatProviderError(normalizeProviderError(error))),model.provider,error);let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
3
|
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice??options?.toolChoice},compat=getOpenAICompletionsCompat(model),thinkingLevelMap=getThinkingLevelMap(model,compat),thinkingModel=thinkingLevelMap===model.thinkingLevelMap?model:{...model,thinkingLevelMap},clampedReasoning=options?.reasoning?clampThinkingLevel(thinkingModel,options.reasoning):model.id.includes("gpt-6-astra")?"off":void 0,hasMappedOff=typeof thinkingLevelMap?.off=="string",normalizedReasoning=clampedReasoning==="off"&&model.id.includes("gpt-6-astra")&&!hasMappedOff?"low":clampedReasoning,reasoningEffort=normalizedReasoning==="off"?void 0:normalizedReasoning==="max"&&supportsMax(thinkingModel)?"max":clampMaxForOpenAI(normalizedReasoning,supportsXhigh(thinkingModel));return stream(model,context,{...base,reasoningEffort,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getOpenAICompletionsCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getOpenAICompletionsCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),compat.supportsOpenAIGrammarTools)){let transcriptTools=resolveTranscriptTools(context.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),kimiDeferredTools=resolveKimiDeferredTools(context.messages,compat),requestTools=transcriptTools.requestTools.filter(tool=>!kimiDeferredTools.has(tool.name)),messages=convertMessages(model,context,compat,{preserveThinking:options?.reasoningEffort!==void 0,grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),thinkingLevelMap=getThinkingLevelMap(model,compat),params={model:model.id,messages,stream:!0,prompt_cache_key:cacheRetention!=="none"&&!(model.baseUrl.includes("api.openai.com")&&model.cost.cacheWrite>0)&&(model.baseUrl.includes("api.openai.com")||cacheRetention==="long"&&compat.supportsLongCacheRetention||compat.supportsPromptCacheKey)?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0,session_id:compat.sendSessionAffinityHeaders&&compat.sessionAffinityFormat==="openrouter"&&cacheRetention!=="none"?options?.sessionId:void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature),requestTools.length>0?(params.tools=convertTools(requestTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice),compat.vllmPriority!==void 0&&(params.priority=compat.vllmPriority);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let isGlm53=/(?:^|[/:-])glm-5\.3(?:-(?:flash|highspeed))?(?:$|[/.:_])/.test(model.id.toLowerCase()),zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort||isGlm53?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat,compat.chatTemplateArgs??{},thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?thinkingLevelMap?.[requestedEffort]:thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)if(options?.reasoningEffort){if(params.thinking={type:"enabled"},compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}}else compat.supportsDisabledThinking!==!1&&thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"});else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;if(options?.reasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(openRouterParams.reasoning={effort})}else thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;if(togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(togetherParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning)if(options?.reasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.thinking=effort)}else thinkingLevelMap?.off!==null&&(params.thinking=thinkingLevelMap?.off??"none");else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.veniceParameters&&(params.venice_parameters=model.compat.veniceParameters),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}return applyExtraBody(params,options?.extraBody,OPENAI_COMPLETIONS_RESERVED_BODY_KEYS),Object.assign(params,model.samplingParams,options?.samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,compat,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,compat,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,compat,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let thinkingLevelMap=getThinkingLevelMap(model,compat),mappedValue=reasoningEffort?thinkingLevelMap?.[reasoningEffort]:thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function appendUserMessage(params,content,mergeAdjacentUserMessages){let previous=params[params.length-1];if(!mergeAdjacentUserMessages||previous?.role!=="user"){params.push({role:"user",content});return}let previousContent=typeof previous.content=="string"?[{type:"text",text:previous.content}]:previous.content,currentContent=typeof content=="string"?[{type:"text",text:content}]:content;previous.content=[...previousContent,...currentContent]}function convertMessages(model,context,compat,options={}){let normalizedContext=resolveTranscript(context,compat.supportsMidConvoSystemMessages),params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash2=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash2.length-1))}_${hash2}`}let sanitizedId=id.replace(/[^a-zA-Z0-9_-]/g,"_")||"tool_call";if(sanitizedId===id&&sanitizedId.length<=40)return id;let hash=shortHash(id).slice(0,8);return`${sanitizedId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`},transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeToolCallId(id),{preserveThinking:options.preserveThinking,normalizeSameModelToolCallIds:!0}),mergeAdjacentUserMessages=!model.baseUrl.includes("api.openai.com"),transcriptTools=resolveTranscriptTools(normalizedContext.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),kimiDeferredTools=resolveKimiDeferredTools(normalizedContext.messages,compat),loadedToolNames=new Set,instructionRole=model.reasoning&&compat.supportsDeveloperRole?"developer":"system",lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&¶ms.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="system"){let addedTools=i>0&&transcriptTools.anchorsAdditions?(msg.toolsAdded??[]).filter(tool=>!loadedToolNames.has(tool.name)):[];for(let tool of addedTools)loadedToolNames.add(tool.name);if(addedTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(addedTools,compat)};params.push(kimiToolMessage)}let text=i===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&¶ms.push({role:instructionRole,content:sanitizeSurrogates(text)})}else if(msg.role==="user")if(typeof msg.content=="string")appendUserMessage(params,sanitizeSurrogates(msg.content),mergeAdjacentUserMessages);else{let content=msg.content.filter(item=>item.type!=="text"||item.text.length>0).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;appendUserMessage(params,content,mergeAdjacentUserMessages)}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0)if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else{assistantText.length>0&&(assistantMsg.content=assistantText);let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature!==void 0&&isOpenAICompletionsReasoningField(signature)&&Object.assign(assistantMsg,{[signature]:nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|
|
6
6
|
`)})}else assistantText.length>0&&(assistantMsg.content=assistantText);toolCalls.length>0&&(assistantMsg.tool_calls=toolCalls.map(tc=>{let customInputProperty=options?.grammarToolInputProperties?.get(tc.name);return customInputProperty!==void 0?{id:tc.id,type:"custom",custom:{name:tc.name,input:sanitizeSurrogates(getGrammarToolInput(tc.name,tc.arguments,customInputProperty))}}:{id:tc.id,type:"function",function:{name:tc.name,arguments:JSON.stringify(tc.arguments)}}})),preservedReasoningDetails&&(assistantMsg.reasoning_details=toReplayableReasoningDetails(preservedReasoningDetails)),compat.requiresReasoningContentOnAssistantMessages&&model.reasoning&&assistantMsg.reasoning_content===void 0&&(assistantMsg.reasoning_content="");let content=assistantMsg.content;if(!(content!=null&&content.length>0)&&!assistantMsg.tool_calls)continue;params.push(assistantMsg)}else if(msg.role==="toolResult"){let imageBlocks=[],deferredTools=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";j++){let toolMsg=transformedMessages[j],textResult=toolMsg.content.filter(isTextContentBlock).map(block=>block.text).join(`
|
|
7
|
-
`),hasImages=toolMsg.content.some(c=>c.type==="image"),toolResultText=textResult.length>0?textResult:hasImages?"(see attached image)":"(no tool output)",toolResultMsg={role:"tool",content:sanitizeSurrogates(toolResultText),tool_call_id:toolMsg.toolCallId};compat.requiresToolResultName&&toolMsg.toolName&&Object.assign(toolResultMsg,{name:toolMsg.toolName}),params.push(toolResultMsg);for(let name of toolMsg.addedToolNames??[]){let tool=kimiDeferredTools.get(name);!tool||loadedToolNames.has(name)||(loadedToolNames.add(name),deferredTools.push(tool))}if(hasImages&&model.input.includes("image"))for(let block of toolMsg.content)isImageContentBlock(block)&&imageBlocks.push({type:"image_url",image_url:{url:`data:${block.mimeType};base64,${block.data}`}})}if(i=j-1,imageBlocks.length>0?(compat.requiresAssistantAfterToolResult&¶ms.push({role:"assistant",content:"I have processed the tool results."}),params.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...imageBlocks]}),lastRole="user"):lastRole="toolResult",deferredTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(deferredTools,compat)};params.push(kimiToolMessage)}continue}lastRole=msg.role}return params}function convertTools(tools,compat){return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,compat.supportsOpenAIGrammarTools);if(grammar)return{type:"custom",custom:{name:tool.name,description:tool.description,format:{type:"grammar",grammar:{syntax:grammar.format,definition:grammar.definition}}}};if(tool.freeform)throw new Error("Freeform tools cannot be sent to OpenAI Chat Completions; use Responses API");let strict=resolveJsonSchemaStrictSampling(tool,compat.supportsStrictMode!==!1),schemaParameters=getJsonSchemaToolParameters(tool,strict),normalizedParameters=compat.toolSchemaFlavor==="moonshot-mfjs"?normalizeToolParametersForMoonshot(schemaParameters):normalizeToolParametersForOpenAICompat(schemaParameters);return{type:"function",function:{name:tool.name,description:tool.description,parameters:normalizedParameters,...compat.supportsStrictMode!==!1&&{strict:strict??!1}}}})}function normalizeRequestToolSchemas(params,compat){return params.tools?{...params,tools:params.tools.map(tool=>{if(tool.type!=="function"||!tool.function.parameters)return tool;let parameters=compat.toolSchemaFlavor==="moonshot-mfjs"?normalizeToolParametersForMoonshot(tool.function.parameters):normalizeToolParametersForOpenAICompat(tool.function.parameters);return{...tool,function:{...tool.function,parameters}}})}:params}function parseChunkUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,cacheReadTokens=rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.prompt_cache_hit_tokens??rawUsage.cached_tokens??0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens??rawUsage.prompt_tokens_details?.cache_creation_tokens??0,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),outputTokens=rawUsage.completion_tokens||0,usage={input,output:outputTokens,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens
|
|
7
|
+
`),hasImages=toolMsg.content.some(c=>c.type==="image"),toolResultText=textResult.length>0?textResult:hasImages?"(see attached image)":"(no tool output)",toolResultMsg={role:"tool",content:sanitizeSurrogates(toolResultText),tool_call_id:toolMsg.toolCallId};compat.requiresToolResultName&&toolMsg.toolName&&Object.assign(toolResultMsg,{name:toolMsg.toolName}),params.push(toolResultMsg);for(let name of toolMsg.addedToolNames??[]){let tool=kimiDeferredTools.get(name);!tool||loadedToolNames.has(name)||(loadedToolNames.add(name),deferredTools.push(tool))}if(hasImages&&model.input.includes("image"))for(let block of toolMsg.content)isImageContentBlock(block)&&imageBlocks.push({type:"image_url",image_url:{url:`data:${block.mimeType};base64,${block.data}`}})}if(i=j-1,imageBlocks.length>0?(compat.requiresAssistantAfterToolResult&¶ms.push({role:"assistant",content:"I have processed the tool results."}),params.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...imageBlocks]}),lastRole="user"):lastRole="toolResult",deferredTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(deferredTools,compat)};params.push(kimiToolMessage)}continue}lastRole=msg.role}return params}function convertTools(tools,compat){return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,compat.supportsOpenAIGrammarTools);if(grammar)return{type:"custom",custom:{name:tool.name,description:tool.description,format:{type:"grammar",grammar:{syntax:grammar.format,definition:grammar.definition}}}};if(tool.freeform)throw new Error("Freeform tools cannot be sent to OpenAI Chat Completions; use Responses API");let strict=resolveJsonSchemaStrictSampling(tool,compat.supportsStrictMode!==!1),schemaParameters=getJsonSchemaToolParameters(tool,strict),normalizedParameters=compat.toolSchemaFlavor==="moonshot-mfjs"?normalizeToolParametersForMoonshot(schemaParameters):normalizeToolParametersForOpenAICompat(schemaParameters);return{type:"function",function:{name:tool.name,description:tool.description,parameters:normalizedParameters,...compat.supportsStrictMode!==!1&&{strict:strict??!1}}}})}function normalizeRequestToolSchemas(params,compat){return params.tools?{...params,tools:params.tools.map(tool=>{if(tool.type!=="function"||!tool.function.parameters)return tool;let parameters=compat.toolSchemaFlavor==="moonshot-mfjs"?normalizeToolParametersForMoonshot(tool.function.parameters):normalizeToolParametersForOpenAICompat(tool.function.parameters);return{...tool,function:{...tool.function,parameters}}})}:params}function parseChunkUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,cacheReadTokens=rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.prompt_cache_hit_tokens??rawUsage.cached_tokens??0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens??rawUsage.prompt_tokens_details?.cache_creation_tokens??0,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),outputTokens=rawUsage.completion_tokens||0,reasoning=reportedCount(rawUsage.completion_tokens_details?.reasoning_tokens),usage={input,output:outputTokens,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens,...reasoning===void 0?{}:{reasoning},totalTokens:input+outputTokens+cacheReadTokens+cacheWriteTokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}function mapStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${reason}`}}}export{convertMessages,getOpenAICompletionsCompat as getCompat,stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
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{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI,toFile}from"./chunk-CD2HJK4C.js";import{awaitProviderTransport,openAICompatibleProviderDiagnosticFromError}from"./chunk-
|
|
2
|
+
import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI,toFile}from"./chunk-CD2HJK4C.js";import{awaitProviderTransport,openAICompatibleProviderDiagnosticFromError}from"./chunk-MHD7SSHF.js";import{retryProviderRequest}from"./chunk-EDOW5W5H.js";import{buildParams,isImageParams,parseOpenAIImageOutputOptions,parseOpenAIImageSize}from"./chunk-HB35RBP4.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-RFB5CBW7.js";import{readProviderDiagnostic}from"./chunk-AA2L2RHH.js";import"./chunk-WDTJ6JKE.js";import"./chunk-45SZOLCU.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";function upload(image,name){return toFile(Buffer.from(image.data,"base64"),`${name}.${image.mimeType.split("/")[1]}`,{type:image.mimeType})}async function buildEditParams(params,images,mask){if(images.length>16)throw new Error("OpenAI image edits accept at most 16 reference images");let image=await Promise.all(images.map((reference,i)=>upload(reference,`reference-${i}`)));return mask===void 0?{...params,image}:{...params,image,mask:await upload(mask,"mask")}}var PNG_MAGIC=[137,80,78,71],JPEG_MAGIC=[255,216,255],WEBP_MAGIC=[82,73,70,70,87,69,66,80];function requestedOutputFormat(value){return value==="jpeg"||value==="webp"?value:"png"}async function resolveImage(datum,outputFormat,options){let b64=datum.b64_json?.trim();if(b64)return{type:"image",mimeType:detectMime(Buffer.from(b64.slice(0,24),"base64"))??`image/${outputFormat}`,data:b64};let url=datum.url?.trim();if(!url)throw new Error("OpenAI images response datum contained no image data");return url.startsWith("data:")?parseDataUrl(url):hydrateImageUrl(url,options)}function parseDataUrl(url){let match=/^data:([^;,]+);base64,(.+)$/i.exec(url);if(!match?.[1]||!match[2])throw new Error("OpenAI images response contained an invalid data URL");let mimeType=supportedMime(match[1]);if(!mimeType)throw new Error(`OpenAI images response used unsupported MIME type: ${match[1]}`);return{type:"image",mimeType,data:match[2]}}async function hydrateImageUrl(url,options){let parsed;try{parsed=new URL(url)}catch{throw new Error("OpenAI images response URL must be absolute")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new Error("OpenAI images response URL must use HTTP or HTTPS");let response=await(options?.fetch??globalThis.fetch)(url,options?.signal?{signal:options.signal}:{});if(!response.ok)throw new Error(`OpenAI image hydration failed with HTTP ${response.status}`);let declaredLength=response.headers.get("content-length");if(declaredLength&&Number(declaredLength)>25165824)throw oversizedImageError();let bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength===0)throw new Error("OpenAI image hydration returned an empty body");if(bytes.byteLength>25165824)throw oversizedImageError();let declaredMime=supportedMime(response.headers.get("content-type")?.split(";",1)[0]),detectedMime=detectMime(bytes);if(declaredMime&&detectedMime&&declaredMime!==detectedMime)throw new Error(`OpenAI image MIME mismatch: declared ${declaredMime}, detected ${detectedMime}`);let mimeType=detectedMime??declaredMime;if(!mimeType)throw new Error("OpenAI image hydration returned unsupported image content");return{type:"image",mimeType,data:bytesToBase64(bytes)}}function supportedMime(value){let normalized=value?.trim().toLowerCase();if(normalized==="image/png"||normalized==="image/jpeg"||normalized==="image/webp")return normalized}function detectMime(bytes){if(hasMagic(bytes,PNG_MAGIC))return"image/png";if(hasMagic(bytes,JPEG_MAGIC))return"image/jpeg";if(hasMagic(bytes,WEBP_MAGIC.slice(0,4))&&hasMagic(bytes,WEBP_MAGIC.slice(4),8))return"image/webp"}function hasMagic(bytes,magic,offset=0){return magic.every((value,index)=>bytes[offset+index]===value)}function bytesToBase64(bytes){let binary="";for(let offset=0;offset<bytes.length;offset+=32768)binary+=String.fromCharCode(...bytes.subarray(offset,offset+32768));return btoa(binary)}function oversizedImageError(){return new Error("OpenAI image hydration exceeded the 24 MiB limit")}var ENDPOINT_SUFFIXES=["/chat/completions","/responses","/models"],generateImages=async(model,context,options)=>{let output={api:model.api,provider:model.provider,model:model.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let params=buildParams(model,context,options),images=context.input.filter(item=>item.type==="image"),method=images.length>0?"edit":"generate";method==="edit"&&(params=await buildEditParams(params,images,options?.mask));let nextParams=await options?.onPayload?.(params,model);if(nextParams!==void 0){if(!isImageParams(nextParams))throw new Error("onPayload returned an invalid image generation payload");params=nextParams}let headers={...model.headers,...options?.headers},auth=resolveOpenAIClientAuth(model.provider,options?.apiKey,headers),client=new OpenAI({apiKey:auth.apiKey,baseURL:normalizeBaseUrl(model.baseUrl),dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:auth.headers}),requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:response,response:rawResponse}=await retryProviderRequest(()=>{let sdkParams=params;return awaitProviderTransport(()=>(method==="edit"?client.images.edit(sdkParams,requestOptions):client.images.generate(sdkParams,requestOptions)).withResponse(),openAICompatibleProviderDiagnosticFromError)},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:rawResponse.status,headers:headersToRecord(rawResponse.headers)},model),response.usage&&(output.usage=parseUsage(response.usage,model)),(response.background==="transparent"||response.background==="opaque")&&(output.background=response.background),!response.data||response.data.length===0)throw new Error("OpenAI images response contained no image data");let outputFormat=requestedOutputFormat(params.output_format);for(let datum of response.data){let image=await resolveImage(datum,outputFormat,options);datum.revised_prompt?.trim()&&output.output.push({type:"text",text:datum.revised_prompt}),output.output.push(image)}return output}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let providerDiagnostic=output.stopReason==="error"?readProviderDiagnostic(error):void 0;return providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),output}};function normalizeBaseUrl(baseUrl){let url;try{url=new URL(baseUrl)}catch{throw new Error(`Invalid OpenAI images base URL: ${baseUrl}`)}if(url.protocol!=="http:"&&url.protocol!=="https:")throw new Error("OpenAI images base URL must use HTTP or HTTPS");if(url.search||url.hash)throw new Error("OpenAI images base URL must not include a query or fragment");let pathname=url.pathname.replace(/\/+$/,""),normalizedPathname=pathname.toLowerCase();if(normalizedPathname.includes("/images"))throw new Error("OpenAI images base URL must not include an images endpoint");if(ENDPOINT_SUFFIXES.some(suffix=>normalizedPathname.endsWith(suffix)))throw new Error("OpenAI images base URL must not include a known API endpoint");return url.pathname=pathname.endsWith("/v1")?pathname:`${pathname}/v1`,url.toString()}function parseUsage(rawUsage,model){let input=rawUsage.input_tokens??0,output=rawUsage.output_tokens??0,imageTokens=rawUsage.input_tokens_details?.image_tokens??0,textTokens=rawUsage.input_tokens_details?.text_tokens??Math.max(0,input-imageTokens),imageRate=model.cost.imageInput??model.cost.input,usage={input,output,cacheRead:0,cacheWrite:0,totalTokens:rawUsage.total_tokens??input+output,cost:{input:(model.cost.input*textTokens+imageRate*imageTokens)/1e6,output:model.cost.output/1e6*output,cacheRead:0,cacheWrite:0,total:0}};return usage.cost.total=usage.cost.input+usage.cost.output,usage}export{generateImages,parseOpenAIImageOutputOptions,parseOpenAIImageSize};
|
|
@@ -0,0 +1,3 @@
|
|
|
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{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{createWebSocketTransportFailure,startWebSocketLiveness}from"./chunk-YT2ZSZOY.js";import{isCloudflareProvider,resolveCloudflareBaseUrl}from"./chunk-OZNCR6E6.js";import{formatGitHubCopilotToolLimitError,limitGitHubCopilotTools,recordGitHubCopilotToolLimit,withGitHubCopilotFailureNote}from"./chunk-OMN4QWFA.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{awaitProviderTransport,openAICompatibleProviderDiagnosticFromError}from"./chunk-MHD7SSHF.js";import{OPENAI_RESPONSES_RESERVED_BODY_KEYS,buildBaseOptions,clampMaxForOpenAI}from"./chunk-JGMG227A.js";import{retryProviderRequest}from"./chunk-EDOW5W5H.js";import{deriveOpenAIPromptCacheKey}from"./chunk-PLQ5WRXN.js";import{isRequestRefusal,sendWithForcedToolChoiceFallback}from"./chunk-OEFCY46F.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import{supportsAllowedToolChoice}from"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import{convertResponsesMessages,convertResponsesTools,findPromptCacheComparisonResponseId,processResponsesStream,resolveResponsesDeferredToolsMode,resolveResponsesToolPlacement,withPromptCacheComparison}from"./chunk-3AK3WUN4.js";import"./chunk-GVSBCJFI.js";import{readProviderDiagnostic}from"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import{createGrammarToolInputProperties}from"./chunk-2AJB5S4C.js";import"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getDeclaredTools,inferOpenAIThinkingLevelMap,normalizeContext,resolveTranscript,supportsMax,supportsXhigh}from"./chunk-VDPJ7W52.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var allowedToolsRefusals=new Set;function refusalKey(target){return JSON.stringify([target.api,target.provider,target.baseUrl,target.id])}function hasRefusedAllowedToolsChoice(target){return allowedToolsRefusals.has(refusalKey(target))}function rememberAllowedToolsChoiceRefusal(target){allowedToolsRefusals.add(refusalKey(target))}function allowedReference(tool){return tool.type==="function"||tool.type==="custom"?{type:tool.type,name:tool.name}:tool.type==="mcp"?{type:"mcp",server_label:tool.server_label}:{type:tool.type}}function allowedToolsChoice(params){let choice=params.tool_choice;if(typeof choice!="object"||choice===null)return;let{type,tools}=choice;return type==="allowed_tools"&&Array.isArray(tools)?tools:void 0}function errorMessage(error){return error instanceof Error?error.message:String(error)}function isAllowedToolsChoiceRefusal(error,params,options={}){if(allowedToolsChoice(params)===void 0||!options.beforeContent&&!isRequestRefusal(error))return!1;let message=errorMessage(error);return/\ballowed_tools\b/.test(message)&&/invalid|unsupported|not\s+supported/i.test(message)}function restrictToAllowedTools(params){let allowed=allowedToolsChoice(params);if(allowed===void 0)return params;let allowedNames=new Set(allowed.map(tool=>tool.name).filter(name=>typeof name=="string")),tools=(params.tools??[]).filter(tool=>tool.type!=="function"&&tool.type!=="custom"||allowedNames.has(tool.name)),restricted={...params,tools};return delete restricted.tool_choice,restricted}function applyAllowedToolsChoice(params,context,activeToolNames,compat){if(!compat.supportsAllowedTools||activeToolNames===void 0||params.tool_choice!==void 0)return params;let active=new Set(activeToolNames),declaredTools=getCurrentTools(context.messages);if(declaredTools.every(tool=>active.has(tool.name)))return params;let allowed=[],namedInTools=new Set;for(let tool of params.tools??[])(tool.type==="function"||tool.type==="custom")&&(namedInTools.add(tool.name),!active.has(tool.name))||allowed.push(allowedReference(tool));let requestToolNames=new Set(resolveResponsesToolPlacement(context.messages,resolveResponsesDeferredToolsMode(compat)!==void 0).requestTools.map(tool=>tool.name));for(let tool of declaredTools){if(namedInTools.has(tool.name)||!active.has(tool.name)||requestToolNames.has(tool.name))continue;let[converted]=convertResponsesTools([tool],{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools});converted&&allowed.push(allowedReference(converted))}let toolChoice=allowed.length>0?{type:"allowed_tools",mode:"auto",tools:allowed}:"none";return{...params,tool_choice:toolChoice}}var OPENAI_TOOL_CALL_PROVIDERS=new Set(["openai","chatgpt-subscription","opencode"]),OPENAI_BETA_RESPONSES_WEBSOCKETS="responses_websockets=2026-02-06",OPENAI_WEB_SEARCH_SOURCES_INCLUDE="web_search_call.action.sources",SESSION_WEBSOCKET_CACHE_TTL_MS=300*1e3,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16,PROMPT_CACHE_PREWARM_TIMEOUT_MS=3e4,CHATGPT_USAGE_URL="https://chatgpt.com/settings/usage",websocketSessionCache=new Map;function isForcedOpenAIResponsesToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function detectSessionAffinityFormat(model){return model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCompat(model,env){let isNativeEndpoint=isOpenAIResponsesNativeEndpoint(model,env);return{supportsDeveloperRole:model.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:model.compat?.sessionAffinityFormat??detectSessionAffinityFormat(model),supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,supportsWebSocket:model.compat?.supportsWebSocket??isNativeEndpoint,supportsRemoteCompactionV2:model.compat?.supportsRemoteCompactionV2??isNativeEndpoint,supportsWebSearchPreview:model.compat?.supportsWebSearchPreview??isNativeEndpoint,webSearchToolType:model.compat?.webSearchToolType??"web_search_preview",supportsImageGeneration:model.compat?.supportsImageGeneration??isNativeEndpoint,supportsStrictMode:model.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:model.compat?.supportsAdditionalTools??!1,supportsToolSearch:model.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:model.compat?.supportsExplicitPromptCacheMode??!1,supportsConfigurationUpdate:model.compat?.supportsConfigurationUpdate??!1,supportsMaxOutputTokens:model.compat?.supportsMaxOutputTokens??!0,supportsForcedToolChoice:model.compat?.supportsForcedToolChoice??!0,supportsAllowedTools:supportsAllowedToolChoice(model)}}function isOpenAIResponsesNativeEndpoint(model,env){let baseUrl=isCloudflareProvider(model.provider)?resolveCloudflareBaseUrl(model,env):model.baseUrl;try{return new URL(baseUrl||"https://api.openai.com/v1").hostname==="api.openai.com"}catch{return!1}}function getPromptCacheRetention(compat,cacheRetention){return cacheRetention==="long"&&compat.supportsLongCacheRetention&&!compat.supportsExplicitPromptCacheMode?"24h":void 0}function getPromptCacheOptions(compat,cacheRetention){if(compat.supportsExplicitPromptCacheMode){if(cacheRetention==="none")return{mode:"explicit"};if(cacheRetention==="long"&&compat.supportsLongCacheRetention)return{ttl:"30m"}}}function isRecord(value){return typeof value=="object"&&value!==null}function isOpenAiWebSearchPreviewTool(value){return isRecord(value)&&(value.type==="web_search"||value.type==="web_search_preview"||value.type==="web_search_preview_2025_03_11")}function sanitizeUnsupportedNativeTools(params,compat){if(compat.supportsWebSearchPreview)return params;let payload=params,sanitized,nextPayload=()=>(sanitized??={...payload},sanitized);if(Array.isArray(payload.tools)){let tools=payload.tools.filter(tool=>!isOpenAiWebSearchPreviewTool(tool));if(tools.length!==payload.tools.length){let next=nextPayload();tools.length>0?next.tools=tools:delete next.tools}}if(Array.isArray(payload.include)){let include=payload.include.filter(value=>value!==OPENAI_WEB_SEARCH_SOURCES_INCLUDE);if(include.length!==payload.include.length){let next=nextPayload();include.length>0?next.include=include:delete next.include}}return isOpenAiWebSearchPreviewTool(payload.tool_choice)&&delete nextPayload().tool_choice,sanitized||params}function formatOpenAIResponsesError(error,provider){let errorMessage2=formatProviderError(normalizeProviderError(error),`${provider==="openai"?"OpenAI":provider} API error`);return errorMessage2.includes("subscription_sharing_usage_limit_exceeded")?`${errorMessage2}
|
|
3
|
+
Check your ChatGPT usage: ${CHATGPT_USAGE_URL}`:errorMessage2}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,compat=getCompat(model,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),client=createClient(model,normalizedContext,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,options?.env),params=buildParams(model,normalizedContext,options,compat,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=sanitizeUnsupportedNativeTools(params,compat),params=applyAllowedToolsChoice(params,normalizedContext,context.activeToolNames,compat),hasRefusedAllowedToolsChoice(model)&&(params=restrictToAllowedTools(params));let limitedTools=limitGitHubCopilotTools(model.provider,params.tools,params.tool_choice,getDeclaredTools(normalizedContext.messages).map(tool=>tool.name));limitedTools.omittedCount>0&&(params={...params,tools:limitedTools.tools},recordGitHubCopilotToolLimit(output,limitedTools.omittedCount));let transport=options?.transport??"sse",refusedAllowedToolsOverWebSocket=!1;if(transport!=="sse"&&compat.supportsWebSocket){let websocketStarted=!1;try{if(await processWebSocketStream(resolveOpenAIResponsesWebSocketUrl(model,options?.env),params,buildWebSocketHeaders(model,normalizedContext,clientAuth.apiKey,clientAuth.headers,cacheSessionId,options?.env),output,stream2,model,()=>{websocketStarted=!0},cacheSessionId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");stream2.push({type:"done",reason:getDoneReason(output.stopReason),message:output}),stream2.end();return}catch(error){let refusedAllowedTools=output.content.length===0&&isAllowedToolsChoiceRefusal(error,params,{beforeContent:!0});if(!refusedAllowedTools&&(transport==="websocket"||websocketStarted))throw error;refusedAllowedTools&&(params=restrictToAllowedTools(params),refusedAllowedToolsOverWebSocket=!0,output.stopReason="pending",delete output.errorMessage)}}let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},sendOnce=async body=>{let sent=await sendWithForcedToolChoiceFallback({target:model,params:body,acceptsForcedToolChoice:compat.supportsForcedToolChoice,isForced:isForcedOpenAIResponsesToolChoice,send:request=>model.provider==="github-copilot"?awaitProviderTransport(()=>client.responses.create(request,requestOptions).withResponse(),openAICompatibleProviderDiagnosticFromError):client.responses.create(request,requestOptions).withResponse()});return params=sent.params,sent.result},createRequest=async()=>{try{let result=await sendOnce(params);return refusedAllowedToolsOverWebSocket&&rememberAllowedToolsChoiceRefusal(model),result}catch(error){if(!isAllowedToolsChoiceRefusal(error,params))throw error;params=restrictToAllowedTools(params);let result=await sendOnce(params);return rememberAllowedToolsChoiceRefusal(model),result}},{data:openaiStream,response}=await retryProviderRequest(()=>createRequest(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),refusedAllowedToolsOverWebSocket||stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,serviceTier:options?.serviceTier,grammarToolInputProperties,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error";let providerDiagnostic=model.provider==="github-copilot"&&output.stopReason==="error"?readProviderDiagnostic(error)??openAICompatibleProviderDiagnosticFromError(error):void 0;providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),output.errorMessage=withGitHubCopilotFailureNote(formatGitHubCopilotToolLimitError(output,formatOpenAIResponsesError(error,model.provider)),model.provider,error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>(resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),stream(model,context,resolveSimpleOptions(model,context,options)));function resolveSimpleOptions(model,context,options){let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice,serviceTier:options?.serviceTier},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoningEffort=clampedReasoning==="off"?void 0:clampedReasoning==="max"&&supportsMax(model)?"max":clampMaxForOpenAI(clampedReasoning,supportsXhigh(model));return{...base,reasoningEffort}}async function warmOpenAIResponsesPromptCache(model,context,options){let prefix=normalizeContext({...context,messages:[]}),resolved=resolveSimpleOptions(model,prefix,options),clientAuth=resolveOpenAIClientAuth(model.provider,resolved.apiKey,resolved.headers),cacheRetention=resolveCacheRetention(resolved.cacheRetention,resolved.env),compat=getCompat(model,resolved.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(prefix.messages),compat.supportsOpenAIGrammarTools),client=createClient(model,prefix,clientAuth.apiKey,clientAuth.headers,resolved.fetch,cacheRetention==="none"?void 0:resolved.sessionId,resolved.env),params=buildParams(model,prefix,resolved,compat,grammarToolInputProperties),nextParams=await resolved.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=sanitizeUnsupportedNativeTools(params,compat);let limitedTools=limitGitHubCopilotTools(model.provider,params.tools,params.tool_choice,getDeclaredTools(prefix.messages).map(tool=>tool.name));limitedTools.omittedCount>0&&(params={...params,tools:limitedTools.tools});let body={...params,stream:!1,prompt_cache_options:{...params.prompt_cache_options,prewarm:!0}},response=await client.responses.create(body,{maxRetries:0,timeout:resolved.timeoutMs??PROMPT_CACHE_PREWARM_TIMEOUT_MS,...resolved.signal?{signal:resolved.signal}:{}}),usageRaw=response.usage,inputDetails=usageRaw?.input_tokens_details,cacheRead=inputDetails?.cached_tokens||0,cacheWrite=inputDetails?.cache_write_tokens??inputDetails?.cache_creation_tokens??0,usage={input:Math.max(0,(usageRaw?.input_tokens||0)-cacheRead-cacheWrite),output:usageRaw?.output_tokens||0,cacheRead,cacheWrite,totalTokens:usageRaw?.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),applyServiceTierPricing(usage,response.service_tier??resolved.serviceTier,model),{usage,usageRaw}}function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,env){let compat=getCompat(model,env),headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:isCloudflareProvider(model.provider)?resolveCloudflareBaseUrl(model,env):model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),compat.supportsOpenAIGrammarTools)){let toolPlacement=resolveResponsesToolPlacement(context.messages,resolveResponsesDeferredToolsMode(compat)!==void 0),requestedReasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0),thinkingLevelMap=inferOpenAIThinkingLevelMap(model),mappedReasoningEffort=requestedReasoningEffort===void 0?void 0:thinkingLevelMap?.[requestedReasoningEffort],reasoningEffort=mappedReasoningEffort===void 0?requestedReasoningEffort:mappedReasoningEffort,reasoningRequested=reasoningEffort!=null,reasoningUnavailable=reasoningEffort===null,cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),messages=convertResponsesMessages(model,context,OPENAI_TOOL_CALL_PROVIDERS,{preserveThinking:reasoningRequested,systemPromptCacheBreakpoint:compat.supportsExplicitPromptCacheMode&&cacheRetention!=="none",grammarToolInputProperties,supportsMidConvoSystemMessages:compat.supportsMidConvoSystemMessages,supportsAdditionalTools:compat.supportsAdditionalTools,supportsToolSearch:compat.supportsToolSearch,toolOptions:{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools}}),isNativeEndpoint=isOpenAIResponsesNativeEndpoint(model,options?.env),comparisonResponseId=cacheRetention!=="none"&&compat.supportsExplicitPromptCacheMode&&isNativeEndpoint?findPromptCacheComparisonResponseId(model,context.messages):void 0,params={model:model.id,input:messages,stream:!0,prompt_cache_key:cacheRetention==="none"?void 0:deriveOpenAIPromptCacheKey(model.id,context),prompt_cache_retention:getPromptCacheRetention(compat,cacheRetention),prompt_cache_options:withPromptCacheComparison(getPromptCacheOptions(compat,cacheRetention),comparisonResponseId),store:!1};return options?.maxTokens&&compat.supportsMaxOutputTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),options?.serviceTier!==void 0&&(params.service_tier=options.serviceTier),toolPlacement.requestTools.length>0&&(params.tools=convertResponsesTools(toolPlacement.requestTools,{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice),model.reasoning&&(reasoningRequested?(params.reasoning={effort:reasoningEffort,...options?.reasoningSummary===null?{}:{summary:options?.reasoningSummary||"auto"}},params.include=["reasoning.encrypted_content"]):!reasoningUnavailable&&model.provider!=="github-copilot"&&thinkingLevelMap?.off!==null&&(params.reasoning={effort:thinkingLevelMap?.off??"none"}),model.provider==="xai"&&(params.include=["reasoning.encrypted_content"])),applyExtraBodyToResponsesParams(params,options?.extraBody),Object.assign(params,model.samplingParams,options?.samplingParams),params}function applyExtraBodyToResponsesParams(params,extraBody){if(extraBody)for(let[key,value]of Object.entries(extraBody))OPENAI_RESPONSES_RESERVED_BODY_KEYS.has(key)||Object.defineProperty(params,key,{value,writable:!0,enumerable:!0,configurable:!0})}function getDoneReason(stopReason){return stopReason==="length"||stopReason==="toolUse"?stopReason:"stop"}function getWebSocketConstructor(){let wsConstructor=globalThis.WebSocket;return typeof wsConstructor=="function"?wsConstructor:null}function getWebSocketReadyState(socket){let readyState=socket.readyState;return typeof readyState=="number"?readyState:void 0}function isWebSocketReusable(socket){let readyState=getWebSocketReadyState(socket);return readyState===void 0||readyState===1}function closeWebSocketSilently(socket,code=1e3,reason="done"){try{socket.close(code,reason)}catch{}}function scheduleSessionWebSocketExpiry(sessionId,entry){entry.idleTimer&&clearTimeout(entry.idleTimer),entry.idleTimer=setTimeout(()=>{if(entry.busy){if(!isWebSocketReusable(entry.socket)){closeWebSocketSilently(entry.socket,1e3,"idle_timeout_dead"),websocketSessionCache.delete(sessionId);return}scheduleSessionWebSocketExpiry(sessionId,entry);return}closeWebSocketSilently(entry.socket,1e3,"idle_timeout"),websocketSessionCache.delete(sessionId)},SESSION_WEBSOCKET_CACHE_TTL_MS);let unref=entry.idleTimer.unref;unref&&unref.call(entry.idleTimer)}function getOpenAIResponsesWebSocketCacheSize(){return websocketSessionCache.size}async function connectWebSocket(url,headers,signal){let WebSocketConstructorValue=getWebSocketConstructor();if(!WebSocketConstructorValue)throw new Error("WebSocket transport is not available in this runtime");let websocketHeaders=headersToRecord(headers);return new Promise((resolve,reject)=>{let settled=!1,socket,cleanup=()=>{transportFailure.dispose(),socket.removeEventListener("open",onOpen),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)},transportFailure=createWebSocketTransportFailure(error=>{settled||(settled=!0,cleanup(),reject(error))}),onOpen=()=>{settled||(settled=!0,cleanup(),resolve(socket))},onError=event=>{transportFailure.onError(event)},onClose=event=>{transportFailure.onClose(event)},onAbort=()=>{settled||(settled=!0,cleanup(),closeWebSocketSilently(socket,1e3,"aborted"),reject(new Error("Request was aborted")))};try{socket=new WebSocketConstructorValue(url,{headers:websocketHeaders})}catch(error){reject(error instanceof Error?error:new Error(String(error)));return}socket.addEventListener("open",onOpen),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort)})}async function acquireWebSocket(url,headers,sessionId,signal){if(!sessionId){let socket2=await connectWebSocket(url,headers,signal);return{socket:socket2,release:()=>closeWebSocketSilently(socket2)}}let cached=websocketSessionCache.get(sessionId);if(cached){if(cached.idleTimer&&(clearTimeout(cached.idleTimer),cached.idleTimer=void 0),!cached.busy&&isWebSocketReusable(cached.socket))return cached.busy=!0,{socket:cached.socket,release:({keep}={})=>{if(!keep||!isWebSocketReusable(cached.socket)){closeWebSocketSilently(cached.socket),websocketSessionCache.delete(sessionId);return}cached.busy=!1,scheduleSessionWebSocketExpiry(sessionId,cached)}};cached.busy||(closeWebSocketSilently(cached.socket),websocketSessionCache.delete(sessionId))}let socket=await connectWebSocket(url,headers,signal),entry={socket,busy:!0};return websocketSessionCache.set(sessionId,entry),{socket,release:({keep}={})=>{if(!keep||!isWebSocketReusable(entry.socket)){closeWebSocketSilently(entry.socket),entry.idleTimer&&clearTimeout(entry.idleTimer),websocketSessionCache.get(sessionId)===entry&&websocketSessionCache.delete(sessionId);return}entry.busy=!1,scheduleSessionWebSocketExpiry(sessionId,entry)}}}async function decodeWebSocketData(data){if(typeof data=="string")return data;if(data instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(data));if(ArrayBuffer.isView(data))return new TextDecoder().decode(new Uint8Array(data.buffer,data.byteOffset,data.byteLength));if(data&&typeof data=="object"&&"arrayBuffer"in data){let arrayBuffer=await data.arrayBuffer();return new TextDecoder().decode(new Uint8Array(arrayBuffer))}return null}async function*parseWebSocket(socket,signal){let queue=[],pending=null,done=!1,failed=null,sawCompletion=!1,wake=()=>{if(!pending)return;let resolve=pending;pending=null,resolve()},liveness=startWebSocketLiveness(socket,error=>{failed=error,done=!0,closeWebSocketSilently(socket,1e3,"liveness_timeout"),wake()}),onMessage=event=>{liveness.noteActivity(),(async()=>{if(!event||typeof event!="object"||!("data"in event))return;let text=await decodeWebSocketData(event.data);if(text)try{let parsed=JSON.parse(text);(parsed.type==="response.completed"||parsed.type==="response.incomplete")&&(sawCompletion=!0,done=!0),queue.push(parsed),wake()}catch{}})()},transportFailure=createWebSocketTransportFailure(error=>{failed||(failed=error),done=!0,wake()}),onError=event=>{transportFailure.onError(event)},onClose=event=>{if(sawCompletion){transportFailure.dispose(),done=!0,wake();return}transportFailure.onClose(event)},onAbort=()=>{failed=new Error("Request was aborted"),done=!0,wake()};socket.addEventListener("message",onMessage),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort);try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");if(queue.length>0){let event=queue.shift();event&&(yield event);continue}if(done)break;await new Promise(resolve=>{pending=resolve})}if(failed)throw failed;if(!sawCompletion)throw new Error("WebSocket stream closed before response.completed")}finally{liveness.stop(),transportFailure.dispose(),socket.removeEventListener("message",onMessage),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)}}async function processWebSocketStream(url,params,headers,output,stream2,model,onStart,cacheSessionId,grammarToolInputProperties,options){let{socket,release}=await acquireWebSocket(url,headers,cacheSessionId,options?.signal);try{socket.send(JSON.stringify({type:"response.create",...params})),onStart(),await options?.onResponse?.({status:101,headers:{}},model),stream2.push({type:"start",partial:output}),await processResponsesStream(parseWebSocket(socket,options?.signal),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}finally{release({keep:!1})}}function resolveOpenAIResponsesWebSocketUrl(model,env){let baseUrl=isCloudflareProvider(model.provider)?resolveCloudflareBaseUrl(model,env):model.baseUrl||"https://api.openai.com/v1",url=new URL(baseUrl);return url.pathname.endsWith("/responses")||(url.pathname=`${url.pathname.replace(/\/$/,"")}/responses`),url.protocol==="https:"?url.protocol="wss:":url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}function buildWebSocketHeaders(model,context,apiKey,optionsHeaders,sessionId,env){let headers=new Headers(model.headers),suppressDefaultAuthorization=!1;if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});for(let[key,value]of Object.entries(copilotHeaders))headers.set(key,value)}for(let[key,value]of Object.entries(optionsHeaders||{}))value===null?(key.toLowerCase()==="authorization"&&(suppressDefaultAuthorization=!0),headers.delete(key)):headers.set(key,value);if(!suppressDefaultAuthorization&&!headers.has("Authorization")&&headers.set("Authorization",`Bearer ${apiKey}`),sessionId){let compat=getCompat(model,env);compat.sessionAffinityFormat==="openai"&&headers.set("session_id",sessionId),compat.sessionAffinityFormat==="openai"||compat.sessionAffinityFormat==="openai-nosession"?headers.set("x-client-request-id",sessionId):compat.sessionAffinityFormat==="openrouter"&&headers.set("x-session-id",sessionId)}return headers.delete("accept"),headers.delete("content-type"),headers.delete("OpenAI-Beta"),headers.delete("openai-beta"),headers.set("OpenAI-Beta",OPENAI_BETA_RESPONSES_WEBSOCKETS),headers}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"ultrafast":return["gpt-6-astra","gpt-6.1-sol"].includes(model.upstreamModelId??model.id)?6:1;case"flex":return .5;case"priority":case"fast":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}export{getOpenAIResponsesWebSocketCacheSize,scheduleSessionWebSocketExpiry,stream,streamSimple,warmOpenAIResponsesPromptCache};
|
package/dist/bundle/chunks/{package-manager-cli-7GQDB5DX.js → package-manager-cli-JHVRG35I.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
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{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-
|
|
2
|
+
import{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-4XR5HDWC.js";import"./chunk-B4N4N7BR.js";import"./chunk-FC2YWHEC.js";import{DefaultPackageManager,DynamicBorder,SettingsManager,keyHint,rawKeyHint}from"./chunk-VXACHCLB.js";import"./chunk-25FRFTSP.js";import"./chunk-EFJKVUID.js";import"./chunk-G42JHX5Q.js";import"./chunk-EV4TWAJI.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-SN7PTZTC.js";import"./chunk-MXLEWTWC.js";import"./chunk-ZMS6YEAO.js";import"./chunk-RPAHOJ6F.js";import"./chunk-V6AYNGMX.js";import"./chunk-PUMCQ5HS.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-HMK6F3RG.js";import"./chunk-YMFGBSO3.js";import{appendHiddenTuiStdout}from"./chunk-QZBH7PDO.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-4NPBDGC4.js";import"./chunk-JDETIKL7.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-5GC4IQ3A.js";import"./chunk-VYSRUDEU.js";import"./chunk-VLKULV6F.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import{runtimeExecArgv}from"./chunk-HRV7NEOJ.js";import"./chunk-CQDU6S6C.js";import"./chunk-HKDGQE6D.js";import"./chunk-IQWPR35S.js";import"./chunk-H4QOEVS5.js";import"./chunk-KLAX467B.js";import"./chunk-HB35RBP4.js";import"./chunk-QXJVKVA2.js";import"./chunk-7X72IACK.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-PLQ5WRXN.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-G7VYQRE7.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-JKNUKBS3.js";import{killProcessTree}from"./chunk-N6UN2SDS.js";import"./chunk-YU4AYH4C.js";import"./chunk-T2IIUI3J.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-3AK3WUN4.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-2AJB5S4C.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-VDPJ7W52.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-PUQFKAB4.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import{APP_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-4J4ABCCL.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
|
|
3
3
|
`)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...runtimeExecArgv(),cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
|
|
4
4
|
`,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
|
|
5
5
|
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
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{MODULE_JOB_KIND,NOTICE_TAIL_MAX_CHARS,TERMINAL_CHILD_JOB_KINDS,TerminalManager,ToolChildJobError,childTerminalIdScope,controlFd,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createModuleJobHandler,createPtyBashTool,goShimScript,runToolChild,sanitizeTerminalOutput,withControlPipe}from"./chunk-
|
|
2
|
+
import{MODULE_JOB_KIND,NOTICE_TAIL_MAX_CHARS,TERMINAL_CHILD_JOB_KINDS,TerminalManager,ToolChildJobError,childTerminalIdScope,controlFd,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createModuleJobHandler,createPtyBashTool,goShimScript,runToolChild,sanitizeTerminalOutput,withControlPipe}from"./chunk-G7VYQRE7.js";import"./chunk-JKNUKBS3.js";import{getShellConfig}from"./chunk-N6UN2SDS.js";import"./chunk-YU4AYH4C.js";import"./chunk-T2IIUI3J.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-3AK3WUN4.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-2AJB5S4C.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-VDPJ7W52.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-4J4ABCCL.js";import"./chunk-ATQFN5HI.js";import{value_exports}from"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";var PTY_GO_SHIM='stty -echo 2>/dev/null; IFS= read -r _go || exit 127; stty echo 2>/dev/null; exec "$0" "$@"';function parseArgs(value){let field=name=>typeof value=="object"&&value!==null?Reflect.get(value,name):void 0,cwd=field("cwd"),toolCallId=field("toolCallId"),env=field("env");if(typeof cwd!="string"||typeof toolCallId!="string"||typeof env!="object"||env===null)throw new ToolChildJobError("terminal_job_bad_args","a terminal job needs cwd, toolCallId and env");let shellPath=field("shellPath"),timeoutAction=field("timeoutAction");return{params:field("params"),toolCallId,cwd,env:Object.fromEntries(Object.entries(env).filter(entry=>typeof entry[1]=="string")),...typeof shellPath=="string"?{shellPath}:{},defaultCols:Number(field("defaultCols"))||0,defaultRows:Number(field("defaultRows"))||0,...timeoutAction==="background"||timeoutAction==="kill"?{timeoutAction}:{}}}function barrierFor(job){return{wrap:(command,args)=>({command:"/bin/sh",args:["-c",PTY_GO_SHIM,command,...args]}),async release(session){if(session.pid===void 0)throw new ToolChildJobError("terminal_spawn_failed","the PTY reported no pid");let gated=job.gate.request({jobId:job.jobId,origin:"terminal",api:"pty.spawn",containment:"own-group",lifetime:"owned",pid:session.pid,pgid:session.pid});session.onExit(exitCode=>job.gate.done(gated.launchId,exitCode===null?{}:{exitCode})),job.gate.skipsAckWait||await gated.acked,job.gate.invokeNow(gated.launchId),session.write(`go
|
|
3
3
|
`)}}}function exitSummary(id,runtime){let output=sanitizeTerminalOutput(runtime.fullOutput()).trimEnd(),exit=runtime.exitResult;return{event:"background_exit",id,exit:exit===null?null:{exitCode:exit.exitCode,signal:exit.signal,cancelled:exit.cancelled,timedOut:exit.timedOut},output:output.length>NOTICE_TAIL_MAX_CHARS?output.slice(output.length-NOTICE_TAIL_MAX_CHARS-1):output}}function createTerminalJobHandlers(injected){let manager=injected,managerFor=generation=>(manager??=new TerminalManager({idScope:childTerminalIdScope(generation)}),manager),tell=(job,wake)=>{job.wake(TERMINAL_CHILD_JOB_KINDS.bash,wake).catch(error=>{process.stderr.write(`tool-child: terminal ${wake.event} for ${wake.id} not delivered: ${error instanceof Error?error.message:String(error)}
|
|
4
4
|
`)})},contextFor=(args,job)=>({manager:managerFor(job.generation),...args.timeoutAction===void 0?{}:{timeoutAction:args.timeoutAction},onBackgroundStart:(id,description,startedAtMs)=>tell(job,{event:"background_start",id,description,startedAtMs}),onBackgroundExit:(id,runtime)=>tell(job,exitSummary(id,runtime)),cwd:args.cwd,...args.shellPath===void 0?{}:{shellPath:args.shellPath},defaultCols:args.defaultCols,defaultRows:args.defaultRows,getEnv:()=>({...args.env}),launchBarrier:barrierFor(job)}),run=create=>async(value,job)=>{let args=parseArgs(value),tool=create(contextFor(args,job));if(!value_exports.Check(tool.parameters,args.params))throw new ToolChildJobError("terminal_job_bad_args","the tool's parameters do not match its schema");let onUpdate=update=>{job.update(update).catch(error=>{process.stderr.write(`tool-child: ${args.toolCallId} update not sent: ${error instanceof Error?error.message:String(error)}
|
|
5
5
|
`)})};return tool.execute(args.toolCallId,args.params,job.signal,onUpdate,{cwd:args.cwd})};return{[TERMINAL_CHILD_JOB_KINDS.bash]:run(createPtyBashTool),[TERMINAL_CHILD_JOB_KINDS.output]:run(createBashOutputTool),[TERMINAL_CHILD_JOB_KINDS.input]:run(createBashInputTool),[TERMINAL_CHILD_JOB_KINDS.resize]:run(createBashResizeTool),[TERMINAL_CHILD_JOB_KINDS.kill]:run(createKillBashTool)}}import{access}from"node:fs/promises";import{constants as osConstants}from"node:os";import{spawn}from"node:child_process";import{once}from"node:events";import{Socket}from"node:net";async function launchOwnGroup(launch){if(process.platform==="win32")throw new Error("launchOwnGroup is POSIX-only; Windows launches are contained by the job");let callerStdio=[...launch.options?.stdio??["ignore","pipe","pipe"]],fd=controlFd(callerStdio),shim=spawn("/bin/sh",["-c",goShimScript(fd),launch.program,...launch.args],{...launch.options,detached:!0,stdio:withControlPipe(callerStdio,fd,"ignore","pipe")}),pid=shim.pid,exited=once(shim,"exit").then(([exitCode,signal])=>({exitCode,signal}));if(pid===void 0)throw new Error(`could not start ${launch.program}`);let gated=launch.gate.request({jobId:launch.jobId,origin:launch.origin,api:launch.api,containment:"own-group",lifetime:launch.lifetime??"owned",pid,pgid:pid});if(exited.then(({exitCode,signal})=>launch.gate.done(gated.launchId,{...exitCode===null?{}:{exitCode},...signal===null?{}:{signal}})),launch.gate.skipsAckWait||await Promise.race([gated.acked,exited]),shim.exitCode===null&&shim.signalCode===null){launch.gate.invokeNow(gated.launchId);let control=shim.stdio[fd];control instanceof Socket&&(control.on("error",()=>{}),exited.then(()=>control.destroy()),control.unref(),control.write(`go
|
|
@@ -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{applyAccountOrder,classifyCredentialFailure,isCommittedRotationOutput,isRotationStreamStart,rendezvousOrder,resolveConfigValue,rotationErrorFromEvent,runCredentialFailover,slotsOfOwnKind}from"./chunk-YMFGBSO3.js";import{activeModelBlockUntil,appendDebugLogEntry,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-QZBH7PDO.js";import{discoverEnvSlots}from"./chunk-VYSRUDEU.js";import"./chunk-KLAX467B.js";import{acquireHalfOpenLease}from"./chunk-QXJVKVA2.js";import{CredentialStoreBusyError}from"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-N6UN2SDS.js";import"./chunk-YU4AYH4C.js";import"./chunk-T2IIUI3J.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-3AK3WUN4.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-2AJB5S4C.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-VDPJ7W52.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-4J4ABCCL.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";async function writeHealthUnlessStoreBusy(what,write){try{return await write()}catch(error){if(!(error instanceof CredentialStoreBusyError))throw error;return appendDebugLogEntry("credential pool: skipped a health write, state file busy",`${what}: lock ${error.path} still held after ${error.waitedMs}ms`),STORE_BUSY}}var STORE_BUSY=Symbol("credential-pool-store-busy");async function releaseLeaseIfModelBlocked(repository,providerId,lane,slotName,leaseId,until){until!==void 0&&await writeHealthUnlessStoreBusy(`lease release on ${slotName}`,()=>repository.mutateSlotState(providerId,lane,slotName,current=>{if(current?.lease?.id!==leaseId)return current;let{lease:_released,...rest}=current;return rest}))}function probeLease(repository,providerId,lane,slotName,now){return writeHealthUnlessStoreBusy(`probe lease on ${slotName}`,()=>acquireHalfOpenLease(repository,providerId,lane,slotName,{now}))}function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}function overlayModelBlock(slot,until){return until===void 0||slot.blockedUntil!==void 0&&slot.blockedUntil>=until?slot:{...slot,blockedUntil:until,blockReason:slot.blockReason??"rate_limit"}}async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,modelId=options.modelId,now=sources.now??Date.now,{providerId,credential,env,repository}=sources,policySlots=[];for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,{}):void 0;key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of slotsOfOwnKind(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),lease;if(!(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()&&(lease=await probeLease(repository,providerId,"stored",slot.name,now()),lease===void 0))){if(lease!==void 0&&lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name],leasedApplicable=leasedState?.credentialRevision===storedRevision?leasedState:void 0,leasedModelUntil=activeModelBlockUntil(leasedApplicable?.modelBlocks,modelId,now());await releaseLeaseIfModelBlocked(repository,providerId,"stored",slot.name,lease.leaseId,leasedModelUntil),slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedApplicable),leasedModelUntil));continue}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable),modelUntil))}}if(policySlots.length===0)return slots;let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases,modelId);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];return listEnvRotationSlots(sources,envSlots,acquireLeases,modelId)}async function listEnvRotationSlots(sources,envSlots,acquireLeases,modelId){if(envSlots.length===0)return[];let{providerId,repository}=sources,now=sources.now??Date.now,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now());if(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()){let lease=await probeLease(repository,providerId,"env",slot.name,now());if(lease===void 0)continue;if(lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"env"))[slot.name];applicable=leasedState?.credentialRevision===revision?leasedState:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),await releaseLeaseIfModelBlocked(repository,providerId,"env",slot.name,lease.leaseId,modelUntil)}}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable),modelUntil))}return slots}var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function modelBlockPatch(family,modelId,blockedUntil,current,now,credentialRevision){let sameMaterial=current!==void 0&¤t.credentialRevision===credentialRevision,{stateVersion:_stateVersion,...kept}=sameMaterial?current:{stateVersion:0};return{...kept,lease:void 0,...credentialRevision===void 0?{}:{credentialRevision},modelBlocks:withModelBlock(sameMaterial?current.modelBlocks:void 0,modelBlockKey(family,modelId),blockedUntil,now)}}function blockPatch(block,current,now,credentialRevision,policy,modelId){if(block.reason==="rate_limit"&&block.modelFamily!==void 0&&modelId!==void 0){let blockedUntil=now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs);return modelBlockPatch(block.modelFamily,modelId,blockedUntil,current,now,credentialRevision)}let failureCount=(current?.failureCount??0)+1,liveModelBlocks=current?.credentialRevision===credentialRevision?pruneModelBlocks(current?.modelBlocks,now):void 0,base={failureCount,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt},...liveModelBlocks===void 0?{}:{modelBlocks:liveModelBlocks}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:block.reason==="auth_error"?{...base,blockedUntil:now+9e5,blockReason:"auth_error"}:{...base,blockReason:block.reason}}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,pooled=sources.credential,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources,options.modelId===void 0?{}:{modelId:options.modelId}),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ranked=useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates,winner=applyAccountOrder(pooled?.order,ranked)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:isCommittedRotationOutput,isStreamStart:isRotationStreamStart,errorFromEvent:rotationErrorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,nowMs:now(),cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await writeHealthUnlessStoreBusy(`success on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0,failureCount:void 0,modelBlocks:pruneModelBlocks(current.modelBlocks,now(),options.modelId)}:void 0))},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await writeHealthUnlessStoreBusy(`${block.reason} block on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy,options.modelId)))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
|
|
@@ -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{runRpcMode}from"./chunk-4XR5HDWC.js";import"./chunk-B4N4N7BR.js";import"./chunk-FC2YWHEC.js";import"./chunk-VXACHCLB.js";import"./chunk-25FRFTSP.js";import"./chunk-EFJKVUID.js";import"./chunk-G42JHX5Q.js";import"./chunk-EV4TWAJI.js";import"./chunk-SN7PTZTC.js";import"./chunk-MXLEWTWC.js";import"./chunk-ZMS6YEAO.js";import"./chunk-RPAHOJ6F.js";import"./chunk-V6AYNGMX.js";import"./chunk-PUMCQ5HS.js";import"./chunk-HMK6F3RG.js";import"./chunk-YMFGBSO3.js";import"./chunk-QZBH7PDO.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-4NPBDGC4.js";import"./chunk-JDETIKL7.js";import"./chunk-QMRJYMNH.js";import"./chunk-5GC4IQ3A.js";import"./chunk-VYSRUDEU.js";import"./chunk-VLKULV6F.js";import"./chunk-26UBFF6N.js";import"./chunk-IBDADH5Z.js";import"./chunk-3474DPZK.js";import"./chunk-HRV7NEOJ.js";import"./chunk-CQDU6S6C.js";import"./chunk-HKDGQE6D.js";import"./chunk-IQWPR35S.js";import"./chunk-H4QOEVS5.js";import"./chunk-KLAX467B.js";import"./chunk-HB35RBP4.js";import"./chunk-QXJVKVA2.js";import"./chunk-7X72IACK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-PLQ5WRXN.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-G7VYQRE7.js";import"./chunk-JKNUKBS3.js";import"./chunk-N6UN2SDS.js";import"./chunk-YU4AYH4C.js";import"./chunk-T2IIUI3J.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-3AK3WUN4.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-2AJB5S4C.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-VDPJ7W52.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-PUQFKAB4.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-RAIZG6HA.js";import"./chunk-HRPMLI7O.js";import"./chunk-QEQG42HL.js";import"./chunk-4J4ABCCL.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-7ASLQ243.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
|