dsh-siwc 0.1.1 → 0.1.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/README.md +1 -1
- package/dist/index.js +15 -15
- package/package.json +1 -1
package/README.md
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import e from"node:assert/strict";import{createHash as t,randomBytes as n,randomUUID as r}from"node:crypto";import{getDshRuntimeVersion as i}from"@deepseek-ai/dsh-app-boot";import{AuthorizationDeclinedError as a}from"@deepseek-ai/dsh-authorization";import{UserQuestionError as o}from"@deepseek-ai/dsh-user-questions";import{mkdir as s,readFile as c}from"node:fs/promises";import{dirname as l}from"node:path";import{withFileLock as u,writeFileAtomic as d}from"@deepseek-ai/dsh-atomic-write";import{credentialKey as f}from"@deepseek-ai/dsh-credentials";import{dshHomePath as p}from"@deepseek-ai/dsh-home-paths";import{LlmError as m,resolveImageAttachmentAccess as h,resolveRetryPolicy as g}from"@deepseek-ai/dsh-llm";import{once as _}from"node:events";import{createServer as v}from"node:http";import{setTimeout as y}from"node:timers/promises";import{PiAiAdapter as b}from"@deepseek-ai/dsh-llm-pi-ai";import{InMemoryCredentialStore as
|
|
2
|
-
function C(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:/* @__PURE__ */ new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var w=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};(te=globalThis).__zod_globalConfig??(te.__zod_globalConfig={});const ne=globalThis.__zod_globalConfig;function T(e){return e&&Object.assign(ne,e),ne}function re(e,t=`|`){return e.map(e=>pe(e)).join(t)}function ie(e,t){return typeof t==`bigint`?t.toString():t}function ae(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function oe(e){return e==null}function se(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}const ce=/* @__PURE__*/ Symbol(`evaluating`);function E(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ce)return r===void 0&&(r=ce,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const le=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function de(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function fe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function D(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function pe(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function me(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function O(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function he(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ge(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function k(e){return typeof e==`string`?e:e?.message}function A(e,t,n){let r=e.message?e.message:k(e.inst?._zod.def?.error?.(e))??k(t?.error?.(e))??k(n.customError?.(e))??k(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function _e(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ve(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}const ye=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ie,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},be=/* @__PURE__ */ C(`$ZodError`,ye),xe=/* @__PURE__ */ C(`$ZodError`,ye,{Parent:Error}),Se=/* @__PURE__*/ (e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new w;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>A(e,a,T())));throw le(t,i?.callee),t}return o.value})(xe),Ce=/* @__PURE__*/ (e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>A(e,a,T())));throw le(t,i?.callee),t}return o.value})(xe),we=/* @__PURE__*/ (e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new w;return a.issues.length?{success:!1,error:new(e??be)(a.issues.map(e=>A(e,i,T())))}:{success:!0,data:a.value}})(xe),Te=/* @__PURE__*/ (e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>A(e,i,T())))}:{success:!0,data:a.value}})(xe),Ee=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},De=/^-?\d+(?:\.\d+)?$/,Oe=/^(?:true|false)$/i,ke=/*@__PURE__*/ C(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ae=/*@__PURE__*/ C(`$ZodCheckMinLength`,(e,t)=>{var n;ke.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=_e(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),je={major:4,minor:4,patch:3},j=/*@__PURE__*/ C(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=je;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=O(e),i;for(let a of t){if(a._zod.def.when){if(he(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new w;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=O(e,t))});else{if(e.issues.length===t)continue;r||=O(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(O(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new w;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new w;return o.then(e=>t(e,r,a))}return t(o,r,a)}}E(e,`~standard`,()=>({validate:t=>{try{let n=we(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Te(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Me=/*@__PURE__*/ C(`$ZodString`,(e,t)=>{j.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ee(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Ne=/*@__PURE__*/ C(`$ZodNumber`,(e,t)=>{j.init(e,t),e._zod.pattern=e._zod.bag.pattern??De,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Pe=/*@__PURE__*/ C(`$ZodBoolean`,(e,t)=>{j.init(e,t),e._zod.pattern=Oe,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Fe=/*@__PURE__*/ C(`$ZodNever`,(e,t)=>{j.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Ie(e,t,n){e.issues.length&&t.issues.push(...ge(n,e.issues)),t.value[n]=e.value}const Le=/*@__PURE__*/ C(`$ZodArray`,(e,t)=>{j.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Ie(t,n,e))):Ie(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Re(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...ge(n,e.issues))}!o&&!i?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function ze(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=me(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Be(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Re(e,n,i,t,u,d))):Re(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const Ve=/*@__PURE__*/ C(`$ZodObject`,(e,t)=>{if(j.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=ae(()=>ze(t));E(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */ new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ue,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>Re(n,t,e,s,r,i))):Re(a,t,e,s,r,i)}return i?Be(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),He=/*@__PURE__*/ C(`$ZodLiteral`,(e,t)=>{if(j.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?de(e):e?de(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}});function Ue(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const We=/*@__PURE__*/ C(`$ZodOptional`,(e,t)=>{j.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,E(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,void 0]):void 0),E(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${se(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Ue(e,r)):Ue(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Ge=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};return e=>{switch(e.code){case`invalid_type`:{let t=r[e.expected]??e.expected,n=ve(e.input);return`Invalid input: expected ${t}, received ${r[n]??n}`}case`invalid_value`:return e.values.length===1?`Invalid input: expected ${pe(e.values[0])}`:`Invalid option: expected one of ${re(e.values,`|`)}`;case`too_big`:{let n=e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${re(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Ke(){return{localeError:Ge()}}// @__NO_SIDE_EFFECTS__
|
|
3
|
-
function
|
|
4
|
-
function
|
|
5
|
-
function
|
|
6
|
-
function
|
|
7
|
-
function
|
|
8
|
-
function
|
|
9
|
-
function
|
|
10
|
-
function
|
|
11
|
-
function
|
|
12
|
-
function
|
|
13
|
-
function
|
|
14
|
-
function
|
|
15
|
-
function I(e){return new lt({type:`optional`,innerType:e})}const ut=new TextEncoder,dt=new TextDecoder,ft=new TextDecoder(`utf-8`,{fatal:!0});function pt(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}const mt=/[^\x00-\x7f]/;function L(e){if(typeof e==`string`&&e.length>=128){if(mt.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return ut.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function ht(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}var R=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},z=class extends R{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},gt=class extends R{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},_t=class extends R{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},B=class extends R{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},V=class extends R{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},vt=class extends R{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},yt=class extends R{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},bt=class extends R{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},xt=class extends R{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},St=class extends R{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Ct=class extends R{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function wt(e){try{return ht(typeof e==`string`?e:dt.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function H(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Tt(e){return H(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(H)}function Et(...e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Dt(e,t,n){try{return wt(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Ot(e,t,n){try{return L(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function kt(e,t,n){let r;try{r=JSON.parse(ft.decode(wt(e)))}catch{throw new t(n)}if(!H(r))throw new t(n);return r}const At={__proto__:null,b64:!0};function jt(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function Mt(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new B(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Nt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new V(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}const Pt=e=>e[Symbol.toStringTag],Ft=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function It(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(H(t)){if(o=Jt(t),typeof o.kty!=`string`)throw Ut(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Ft(e,o,n),o.kty===`oct`)return wt(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Vt(t))throw Ut(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Pt(t)} instances must be of type "${e}" for the ${r} algorithm`);if(zt(t))return t;if(s=t,s.type===`secret`)return s.export()}Lt||=/* @__PURE__ */ new WeakMap;let c=t,l=Lt.get(c);if(l?.[r])return l[r];if(l||Lt.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Rt[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await Yt(e,o)}let Lt;const Rt={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},zt=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Bt=e=>e?.[Symbol.toStringTag]===`KeyObject`,Vt=e=>zt(e)||Bt(e);function Ht(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function Ut(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Ht(`Key for the ${e} algorithm must be `,t,...r))}const U=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Wt(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Gt(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Kt(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw U(t.name);if(t.hash&&r.hash?.name!==t.hash)throw U(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw U(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw U(t.length,`algorithm.length`);Wt(e,n)}function qt(e){return{__proto__:null,...e}}function Jt(e){let t=qt(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function Yt(e,t,n){if(!e.kty.includes(t.kty))throw new B(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function Xt(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Kt(e,t,n),e}function Zt(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const W=[[`verify`],[`sign`]];function Qt(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:W}}function G(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:W,minRsaBits:2048}}function $t(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:W}}function en(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:W}}function tn(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:W}}const nn=Zt({HS256:Qt(256),HS384:Qt(384),HS512:Qt(512),RS256:G(256),RS384:G(384),RS512:G(512),PS256:G(256,32),PS384:G(384,48),PS512:G(512,64),ES256:$t(`P-256`,256),ES384:$t(`P-384`,384),ES512:$t(`P-521`,512),EdDSA:en(),Ed25519:en(),"ML-DSA-44":tn(44),"ML-DSA-65":tn(65),"ML-DSA-87":tn(87)});function rn(e){let t=typeof e==`string`?nn[e]:void 0;if(!t)throw new B(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function an(e){return[e&&jt(`algorithms`,e.algorithms),e?.crit]}function on(e){return e===void 0?{}:kt(e,V,`JWS Protected Header is invalid`)}function sn(e){try{return L(e)}catch{throw new V(`JWS Compact Serialization payload must use only ASCII characters`)}}async function cn(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??on(a);if(!Et(c,o))throw new V(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Nt(c,Mt(V,At,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new V(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new _t(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new V(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new V(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=rn(d),h=pt(a===void 0?/* @__PURE__ */ new Uint8Array:L(a),L(`.`),typeof f==`string`?t[2]??=Ot(f,`payload`,V):f),g=Dt(e.signature,`signature`,V),_=await It(m,n,`verify`),v=await Xt(_,m.subtle,`verify`);m.minRsaBits&&Gt(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new Ct;let b={payload:typeof f==`string`?Dt(f,`payload`,V):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function ln(e,t,n){if(e instanceof Uint8Array&&(e=dt.decode(e)),typeof e!=`string`)throw new V(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new V(`Invalid Compact JWS`);return cn({payload:i,protected:r,signature:a},t,n,sn)}const un=e=>Math.floor(e.getTime()/1e3),dn={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},fn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,K=`check_failed`;function pn(){throw TypeError(`Invalid time period format`)}function mn(e){typeof e!=`string`&&pn();let t=fn.exec(e);(!t||t[4]&&t[1])&&pn();let n=parseFloat(t[2]),r=Math.round(n*dn[t[3][0].toLowerCase()]);return Number.isFinite(r)||pn(),t[1]===`-`||t[4]===`ago`?-r:r}function hn(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const gn=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},_n=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function vn(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new z(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function yn(e,t){throw new z(`unexpected "${t}" claim value`,e,t,K)}function bn(e,t,n={}){let r;try{r=JSON.parse(ft.decode(t))}catch{}if(!H(r))throw new vt(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||gn(e.typ)!==gn(i)))throw new z(`unexpected "typ" JWT header value`,r,`typ`,K);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new z(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&yn(r,`iss`),s!==void 0&&r.sub!==s&&yn(r,`sub`),c!==void 0&&!_n(r.aud,typeof c==`string`?[c]:c)&&yn(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=mn(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}hn(`clockTolerance option`,f);let{currentDate:p}=n,m=hn(`currentDate option`,un(p===void 0?/* @__PURE__ */ new Date:p)),h=vn(r,`iat`,l!==void 0),g=vn(r,`nbf`);if(g!==void 0&&g>m+f)throw new z(`"nbf" claim timestamp check failed`,r,`nbf`,K);let _=vn(r,`exp`);if(_!==void 0&&_<=m-f)throw new gt(`"exp" claim timestamp check failed`,r,`exp`,K);if(l!==void 0){let e=m-h,t=hn(`maxTokenAge option`,typeof l==`number`?l:mn(l));if(e-f>t)throw new gt(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,K);if(e<-f)throw new z(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,K)}return r}async function xn(e,t,n){let[r,i]=await ln(e,an(n),t);if(!i)throw new vt(`JWTs MUST NOT use unencoded payload`);let a=bn(r.protectedHeader,r.payload,n);return{...r,payload:a}}function Sn(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function Cn(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=Yt(n,t,!0).then(e=>{if(e.type!==`public`)throw new yt(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function wn(e){let t;try{t=structuredClone(e)}catch{}if(!Tt(t))throw new yt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=qt(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=/* @__PURE__ */ new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?nn[a]:void 0;if(!s||s.secret)throw new B(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Sn(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new bt;if(u!==1){let e=new xt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await Cn(r,e,s)}catch{}},e}return Cn(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Tn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let En;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(En=`jose/v6.2.12`);const Dn=/* @__PURE__ */ Symbol();async function On(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new St:e});if(i.status!==200)throw new R(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new R(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const kn=/* @__PURE__ */ Symbol();function q(e,t){return Number.isFinite(e)&&Date.now()<e+t}function An(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function jn(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=An(r.cooldownDuration,3e4,`cooldownDuration`),s=An(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);En&&!c.has(`User-Agent`)&&c.set(`User-Agent`,En),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[Dn],u=r[kn],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;q(e,s)&&Tt(t)&&(d=e,h=wn(t))}let g=async()=>{if(f&&Tn()&&(f=void 0),!f){let e=++p,t=f=On(n,c,AbortSignal.timeout(a),l).then(t=>{let n=wn(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!q(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof bt&&!q(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>q(d,o),enumerable:!0},fresh:{get:()=>q(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}const J=`https://auth.openai.com`,Y=`https://api.openai.com/v1`,X=`https://chatgpt.com/settings/usage`;var Mn=class extends Error{},Nn=class extends Error{},Pn=class extends Error{status;code;requestId;constructor(e,t,n){super(`OpenAI request failed (${e}${t?`: ${t}`:``}). Reconnect with /chatgpt login; manage usage: ${X}`),this.status=e,this.code=t,this.requestId=n}};const Fn=/* @__PURE__ */ new Set([`invalid_grant`,`invalid_refresh_token`,`token_expired`,`refresh_token_expired`,`refresh_token_invalidated`,`refresh_token_reused`]);function In(t){e.ok(typeof t==`object`&&!!t&&!Array.isArray(t),`Invalid OpenAI response`)}function Z(t,n){e.ok(typeof t==`string`&&t.trim(),`OpenAI returned invalid ${n}`)}async function Ln(e,t={}){let n=await fetch(e,{...t,signal:AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]])}).catch(e=>{throw new Nn(`Could not reach OpenAI. Check your connection and try again.`,{cause:e})});if(!n.ok){let e;if(n.headers.get(`content-type`)?.includes(`json`)){let t=await n.json();In(t),typeof t.error==`string`?e=t.error:t.error&&typeof t.error==`object`&&`code`in t.error&&typeof t.error.code==`string`&&(e=t.error.code)}throw new Pn(n.status,e,n.headers.get(`x-request-id`))}let r=await n.json();return In(r),r}async function Rn(t){let n=await Ln(`${J}/.well-known/openid-configuration`,{signal:t});e.equal(n.issuer,J,`Unexpected OpenAI issuer`);for(let t of[`authorization_endpoint`,`token_endpoint`,`jwks_uri`])Z(n[t],t),e.equal(new URL(n[t]).origin,J,`Unexpected OpenAI ${t}`);return n.revocation_endpoint!==void 0&&(Z(n.revocation_endpoint,`revocation_endpoint`),e.equal(new URL(n.revocation_endpoint).origin,J,`Unexpected OpenAI revocation endpoint`)),n}async function zn(t,n,r,i,a){let o=await Rn(a).catch(()=>{throw new Mn(`OpenAI identity service is unavailable. Try again.`)}),s=jn(new URL(o.jwks_uri)),{payload:c}=await xn(t,async(e,t)=>{try{return await s(e,t)}catch(e){throw e instanceof bt?e:new Mn(`OpenAI signing keys are unavailable. Try again.`)}},{issuer:J,audience:n,algorithms:[`RS256`],requiredClaims:[`iss`,`sub`,`aud`,`iat`,`exp`],...i===void 0?{}:{currentDate:new Date(i)}});return Z(c.sub,`ID token subject`),r!==void 0&&e.equal(c.nonce,r,`OpenAI ID token nonce mismatch`),(c.azp!==void 0||Array.isArray(c.aud)&&c.aud.length>1)&&e.equal(c.azp,n,`OpenAI ID token authorized party mismatch`),{subject:c.sub,...typeof c.email==`string`?{email:c.email}:{}}}async function Bn(t,n){let r=await Ln((await Rn(n)).token_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:t,signal:n});Z(r.access_token,`access_token`),Z(r.refresh_token,`refresh_token`),Z(r.scope,`scope`),e.equal(String(r.token_type).toLowerCase(),`bearer`,`Unexpected OpenAI token type`),e.ok(typeof r.expires_in==`number`&&Number.isFinite(r.expires_in)&&r.expires_in>0,`Invalid OpenAI token expiry`);let i=r.scope.split(/\s+/);e.ok(i.includes(`chatgpt.tokens.use.direct`),`ChatGPT plan usage was not granted`);let a;return r.earliest_refresh_at!==void 0&&(a=typeof r.earliest_refresh_at==`number`?r.earliest_refresh_at*1e3:Date.parse(String(r.earliest_refresh_at)),e.ok(Number.isFinite(a),`Invalid earliest_refresh_at`)),r.id_token!==void 0&&Z(r.id_token,`id_token`),{tokens:{access:r.access_token,refresh:r.refresh_token,expires:Date.now()+r.expires_in*1e3,scopes:i,...a===void 0?{}:{refreshAfter:a}},receivedAt:Date.now(),...r.id_token===void 0?{}:{idToken:r.id_token}}}function Vn(t,n){return e.ok(t.tokens,`Sign in with /chatgpt login first`),Bn(new URLSearchParams({grant_type:`refresh_token`,client_id:t.clientId,refresh_token:t.tokens.refresh,resource:Y}),n)}async function Hn(t){let n=AbortSignal.timeout(1e4),r=await Rn(n);e.ok(r.revocation_endpoint,`OpenAI did not publish a revocation endpoint`);let i=t.pending?.tokens.refresh??t.tokens?.refresh;e.ok(i,`No renewable ChatGPT session`);for(let e=0;;e++){try{let e=await fetch(r.revocation_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},signal:n,body:new URLSearchParams({token:i,token_type_hint:`refresh_token`,client_id:t.clientId})});if(e.status===200)return;if(e.status<500)throw Error(`ChatGPT session revocation failed (${e.status})`)}catch(t){if(!(t instanceof TypeError)||n.aborted||e===2)throw t}if(e===2)throw Error(`ChatGPT session revocation is unavailable`);await y(200*2**e,void 0,{signal:n})}}async function Un(t,n){let r=await Ln(`${Y}/models`,{headers:{authorization:`Bearer ${t}`},signal:n});return e.ok(Array.isArray(r.models),`Invalid ChatGPT model catalog`),r.models.filter(e=>(In(e),e.visibility===`list`)).map(e=>(Z(e.slug,`model slug`),Z(e.display_name,`model display name`),{id:e.slug,name:e.display_name}))}async function Wn(r,i,o,s){let c=await Rn(r.signal),l=n(32).toString(`base64url`),u=n(32).toString(`base64url`),d=n(32).toString(`base64url`),f=AbortSignal.any([r.signal,AbortSignal.timeout(3e5)]),p,m,h=new Promise((e,t)=>{p=e,m=t}),g=()=>m(f.reason);f.addEventListener(`abort`,g,{once:!0}),h.catch(()=>{});let y,b=v((e,t)=>{t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`Referrer-Policy`,`no-referrer`),t.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let n=new URL(e.url??`/`,`http://127.0.0.1`);if(e.method===`GET`&&n.pathname===`/auth/start`&&n.searchParams.get(`state`)===l){t.writeHead(302,{Location:y}).end();return}if(e.method!==`GET`||n.pathname!==`/auth/callback`){t.writeHead(404).end(`Not found`);return}if(n.searchParams.get(`state`)!==l){t.writeHead(400).end(`OAuth state mismatch`);return}if(n.searchParams.has(`error`)){t.writeHead(400).end(`ChatGPT sign-in was declined. Return to DSH.`),m(/* @__PURE__ */ Error(`ChatGPT sign-in was declined`));return}let r=n.searchParams.get(`code`),i=n.searchParams.get(`client_id`)??o.clientId;!r||!i||i===`dynamic_agent_client`||o.clientId!==`dynamic_agent_client`&&o.clientId!==i?(t.writeHead(400).end(`Invalid OAuth registration callback`),m(/* @__PURE__ */ Error(`Invalid OpenAI OAuth registration callback`))):(t.end(`Return to DSH to finish connecting your ChatGPT account.`),p({code:r,clientId:i}))}),ee=new AbortController;try{f.throwIfAborted(),b.listen(0,`127.0.0.1`),await _(b,`listening`);let n=b.address();e.ok(n&&typeof n==`object`);let p=`http://127.0.0.1:${n.port}/auth/callback`,m=new URL(c.authorization_endpoint);m.search=new URLSearchParams({client_id:o.clientId,ext_agent_host_id:i,response_type:`code`,redirect_uri:p,resource:Y,scope:`openid profile email offline_access resource.invoke chatgpt.tokens.use.direct`,state:l,nonce:u,code_challenge_method:`S256`,code_challenge:t(`sha256`).update(d).digest(`base64url`),...o.clientId===`dynamic_agent_client`?{agent_name_hint:`DSH SIWC`}:{},...o.idToken?{id_token_hint:o.idToken}:{},...o.email?{login_hint:o.email}:{}}).toString(),y=m.toString(),r.notify({message:`Continue with ChatGPT`,url:`http://127.0.0.1:${n.port}/auth/start?state=${l}`});let g=r.prompt({kind:`select`,message:`Open the sign-in link, then finish in your browser.`,options:[{id:`cancel`,label:`Cancel sign-in`}],signal:AbortSignal.any([f,ee.signal])}).then(()=>{throw new a}),v=await Promise.race([h,g]);ee.abort(),f.throwIfAborted(),await s(v.clientId);let x=await Bn(new URLSearchParams({grant_type:`authorization_code`,client_id:v.clientId,code:v.code,code_verifier:d,redirect_uri:p,resource:Y}),f);Z(x.idToken,`id_token`);let S=await zn(x.idToken,v.clientId,u,void 0,f);return o.subject&&e.equal(S.subject,o.subject,`ChatGPT account changed during reauthorization`),f.throwIfAborted(),{...S,tokens:x.tokens,idToken:x.idToken}}finally{ee.abort(),f.removeEventListener(`abort`,g),b.close(),b.closeAllConnections()}}T(Ke());const Q=f(`siwc`,`chatgpt`),Gn=/* @__PURE__ */ F({access:(/* @__PURE__ */ P()).check(/* @__PURE__ */ M(1)),refresh:(/* @__PURE__ */ P()).check(/* @__PURE__ */ M(1)),expires:/* @__PURE__ */ $e(),scopes:/* @__PURE__ */ at(/* @__PURE__ */ P()),refreshAfter:/* @__PURE__ */ I(/* @__PURE__ */ $e())}),Kn=/* @__PURE__ */ F({version:/* @__PURE__ */ ct(1),activeId:/* @__PURE__ */ I(/* @__PURE__ */ P()),welcomed:/* @__PURE__ */ I(/* @__PURE__ */ tt()),accounts:/* @__PURE__ */ at(/* @__PURE__ */ F({id:(/* @__PURE__ */ P()).check(/* @__PURE__ */ M(1)),clientId:(/* @__PURE__ */ P()).check(/* @__PURE__ */ M(1)),subject:/* @__PURE__ */ I(/* @__PURE__ */ P()),email:/* @__PURE__ */ I(/* @__PURE__ */ P()),idToken:/* @__PURE__ */ I(/* @__PURE__ */ P()),tokens:/* @__PURE__ */ I(Gn),pending:/* @__PURE__ */ I(/* @__PURE__ */ F({tokens:Gn,idToken:/* @__PURE__ */ I(/* @__PURE__ */ P()),receivedAt:/* @__PURE__ */ $e()})),models:/* @__PURE__ */ I(/* @__PURE__ */ at(/* @__PURE__ */ F({id:(/* @__PURE__ */ P()).check(/* @__PURE__ */ M(1)),name:(/* @__PURE__ */ P()).check(/* @__PURE__ */ M(1))})))}))});function $(t){return t===void 0?{version:1,accounts:[]}:(e.ok(t.kind===`grant`,`Invalid SIWC credential record`),Kn.parse(t.payload))}async function qn(){let t=p(`siwc`,`host-id`);return await s(l(t),{recursive:!0,mode:448}),u(t,async()=>{let n;try{n=(await c(t,`utf8`)).trim()}catch(e){if(e.code!==`ENOENT`)throw e;n=`urn:uuid:${r()}`,await d(t,n,{mode:384,dirMode:448})}return e.match(n,/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,`Invalid saved SIWC host ID`),n})}var Jn=class{credentials;constructor(e){this.credentials=e}async read(){return $(await this.credentials.readRecord(Q))}async change(e){return $(await this.credentials.modifyRecord(Q,async t=>{let n=$(t);return await e(n),{kind:`grant`,payload:n}}))}async accessToken(t,n){let r,i=AbortSignal.timeout(2e4),a=await this.credentials.modifyRecord(Q,async a=>{let o=$(a),s=o.accounts.find(e=>e.id===(t??o.activeId));if(!s?.tokens)throw new m(`Continue with ChatGPT using /chatgpt login`,`MISSING_CREDENTIAL`);let c=Date.now();if(n!==void 0&&s.tokens.access!==n||!s.pending&&(n===void 0&&c<s.tokens.expires-6e4||s.tokens.refreshAfter!==void 0&&c<s.tokens.refreshAfter&&c<s.tokens.expires))return;if(!s.pending&&s.tokens.refreshAfter!==void 0&&c<s.tokens.refreshAfter)throw Error(`ChatGPT token expired before its refresh window. Try again later or reconnect.`);let l;try{if(l=s.pending??await Vn(s,i),l.idToken){let t=await zn(l.idToken,s.clientId,void 0,l.receivedAt,i);e.equal(t.subject,s.subject,`Refreshed ChatGPT identity changed`),s.idToken=l.idToken}s.tokens=l.tokens,delete s.pending}catch(e){if(e instanceof Mn&&l)s.pending=l;else if(l||e instanceof Pn&&e.code!==void 0&&Fn.has(e.code))delete s.tokens,delete s.pending,o.activeId===s.id&&delete o.activeId;else throw e;r=e}return{kind:`grant`,payload:o}});if(r)throw r;let o=$(a);return o.accounts.find(e=>e.id===(t??o.activeId)).tokens.access}};function Yn(t){let n=S(),r=new Map(n.getModels().map(e=>[e.id,e]));return t.map(({id:t,name:n})=>{let i=r.get(t);return e.ok(i,`ChatGPT model ${t} is missing from pi-ai. Update the plugin's Pi dependency.`),{...i,name:n}})}function Xn(e){let t=S(),n=Yn(e?.models??[]);return/* @__PURE__ */ new Map([[`openai`,{provider:`openai`,displayName:`ChatGPT Subscription Plan`,...e?{accountId:e.id}:{},piProvider:{...t,getModels:()=>n,getAllModels:()=>n},streamIdleTimeoutMs:3e5,maxRequestImageBytes:20971520,requestImagePixelBudget:4194304,requestImageMaxBytes:1048576,retryPolicy:g(void 0,`siwc`),modelErrors:/* @__PURE__ */ new Map,configuredMaxTokens:/* @__PURE__ */ new Map}]])}var Zn=class extends b{accounts;currentProfiles;options;constructor(e,t){let n={value:Xn(),stamp:``},r={profiles:()=>n.value,resolveApiKey:(e,n)=>t.accessToken(n.accountId),auth:{credentials:new ee,authContext:x()},resolveAttachments:()=>e.get(`attachments`),resolveImageAccess:(t,n)=>h(t,t=>e.get(`fs`)?.processPathFromHostPath(t),n)};super(r),this.options=r,this.accounts=t,this.currentProfiles=n}async sync(){let e=await this.accounts.read(),t=e.accounts.find(t=>t.id===e.activeId),n=JSON.stringify([t?.id,t?.email,t?.models]);n!==this.currentProfiles.stamp&&(this.currentProfiles.value=Xn(t),this.currentProfiles.stamp=n)}async listModels(e){return await this.sync(),super.listModels(e)}async resolveModel(e,t,n){return await this.sync(),super.resolveModel(e,t,n)}async prepareCall(e,t,n){await this.sync();let r=this.currentProfiles.value,i=r.get(e)?.accountId,a,o=await new b({...this.options,profiles:()=>r,resolveApiKey:async()=>(a=await this.accounts.accessToken(i),a)}).prepareCall(e,t,n);return{model:o.model,stream:e=>this.recoverAuth(o.stream(e),i,()=>a)}}async*recoverAuth(e,t,n){let r=!1,i=async e=>{let i=n();t&&i&&/\b401\b|subscription_sharing_invalid_user/.test(e)&&(r=!0,await this.accounts.accessToken(t,i))};try{for await(let t of e)t.type===`finish`&&t.reason.kind===`error`&&await i(t.reason.failure.message),yield t}catch(e){throw!r&&e instanceof Error&&await i(e.message),e}}async*stream(e){yield*(await this.prepareCall(e.provider,e.model,e.signal)).stream(e)}};const Qn=`siwc`,$n=[`credentials`,`authorization`,`llm`],er=[`0.2.1-alpha.2`,`0.2.1-alpha.3`,`0.2.1-alpha.4`,`0.2.1-alpha.5`,`0.2.1-rc.1`,`0.2.1-rc.2`],tr=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;async function nr(e,t){let n=await t.read(),r=n.accounts.find(e=>e.id===n.activeId);if(!r?.tokens)return;let i,a;try{i=await t.accessToken(r.id),a=await Un(i)}catch(t){if(!(t instanceof Nn)&&!(t instanceof Pn)&&!(t instanceof Mn))throw t;e.logger.warn(`Could not refresh ChatGPT models at startup; keeping the saved catalog: %s`,t.message);return}Yn(a),await t.change(e=>{let t=e.accounts.find(e=>e.id===r.id);t?.tokens?.access===i&&(t.models=a)})}async function rr(t){let n=i();er.includes(n)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,er.join(`, `),n);let s=new Jn(t.credentials);await nr(t,s);let c=new Zn(t,s);t.llm.registerAdapter([`openai`],c);async function l(t){let n=await s.read(),i=n.accounts.map(e=>({id:e.id,label:tr(e)}));t.method===`oauth`&&i.push({id:`new`,label:`Add ChatGPT account or workspace`}),e.ok(i.length,`No saved ChatGPT account. Use /chatgpt login first.`);let a=i.length===1?i[0].id:await t.prompt({kind:`select`,message:`Choose your ChatGPT account`,options:i}),o=n.accounts.find(e=>e.id===a);e.ok(a===`new`||o,`Unknown ChatGPT account`);let l=o??{id:r(),clientId:`dynamic_agent_client`};if(t.method===`oauth`){let e=await Wn(t,await qn(),l,async e=>{t.signal.throwIfAborted(),l.clientId=e,await s.change(t=>{let n=t.accounts.find(e=>e.id===l.id);n?n.clientId=e:t.accounts.push({...l,clientId:e})})});Object.assign(l,e)}e.ok(l.tokens,`This account is signed out. Reconnect with /chatgpt login.`);let u=await Un(t.method===`oauth`?l.tokens.access:await s.accessToken(l.id),t.signal);Yn(u),n.welcomed||(t.notify({message:`Manage usage`,url:X}),await t.prompt({kind:`select`,message:`You're using your ChatGPT plan. Eligible requests use your plan allowance. Manage usage in ChatGPT settings.`,options:[{id:`ok`,label:`Got it`}]})),t.signal.throwIfAborted(),await s.change(n=>{t.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===l.id);e.ok(r,`ChatGPT registration was removed during sign-in. Please retry.`),t.method===`oauth`&&(Object.assign(r,l),delete r.pending),r.models=u,n.activeId=l.id,n.welcomed=!0}),await c.sync(),t.notify({message:`Using ChatGPT plan. Manage usage`,url:X})}t.authorization.registerFlow({key:Q,label:`ChatGPT plan`,methods:[{id:`oauth`,label:`Continue with ChatGPT`},{id:`select`,label:`Switch saved account`}],run:l}),t.inject([`commands`,`userQuestions`],e=>{e.commands.register({name:`chatgpt`,description:`Connect or manage your ChatGPT plan`,input:{hint:`<login|accounts|logout|status>`},async handler({agent:t,rawInput:n,signal:r}){let i=n.trim()||`status`;if(i===`logout`){let e=!0;return await s.change(async t=>{let n=t.accounts.find(e=>e.id===t.activeId);if(n?.tokens||n?.pending)try{await Hn(n)}catch{e=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete t.activeId}),await c.sync(),{kind:`success`,text:`Signed out. Saved registrations are retained.${e?``:` Remote revocation was not confirmed; disconnect this app in ChatGPT settings.`}\nManage app access: ${X}`}}if(i===`status`){let e=await s.read(),t=e.accounts.find(t=>t.id===e.activeId);return{kind:`success`,text:`${t?.tokens?`Using ChatGPT plan: ${tr(t)}`:`Signed out. Use /chatgpt login.`}\nManage usage: ${X}`}}if(i!==`login`&&i!==`accounts`)return{kind:`error`,text:`Usage: /chatgpt login|accounts|logout|status`};let l;return(await e.authorization.begin({key:Q,method:i===`login`?`oauth`:`select`,signal:r,interaction:{notify(e){l=e},async prompt(n){if(n.kind!==`select`)throw Error(`Unsupported authorization prompt`);let i=l;l=void 0;let s=await e.userQuestions.ask({agent:t,signal:AbortSignal.any([r,...n.signal?[n.signal]:[]]),questions:[{id:`chatgpt`,header:`ChatGPT`,question:n.message,...i?{detail:i.url?`[${i.message}](${i.url})`:i.message}:{},options:n.options.map(({label:e})=>({label:e})),multiSelect:!1}]}).catch(e=>{throw e instanceof o&&e.code===`ASK_ABORTED`&&!n.signal?.aborted&&!r.aborted?new a:e}),c=n.options.find(e=>e.label===s.answers[0]?.selected[0]);if(!c)throw new a;return c.id}}})).status===`authorized`?{kind:`success`,text:`Using ChatGPT plan. Select a model under ChatGPT plan.\nManage usage: ${X}`}:{kind:`error`,text:`ChatGPT sign-in cancelled.`}}})})}export{rr as apply,$n as inject,Qn as name};
|
|
1
|
+
import e from"node:assert/strict";import{createHash as t,randomBytes as n,randomUUID as r}from"node:crypto";import{getDshRuntimeVersion as i}from"@deepseek-ai/dsh-app-boot";import{AuthorizationDeclinedError as a}from"@deepseek-ai/dsh-authorization";import{UserQuestionError as o}from"@deepseek-ai/dsh-user-questions";import{mkdir as s,readFile as c}from"node:fs/promises";import{dirname as l}from"node:path";import{withFileLock as u,writeFileAtomic as d}from"@deepseek-ai/dsh-atomic-write";import{credentialKey as f}from"@deepseek-ai/dsh-credentials";import{dshHomePath as p}from"@deepseek-ai/dsh-home-paths";import{LlmError as m,resolveImageAttachmentAccess as h,resolveRetryPolicy as g}from"@deepseek-ai/dsh-llm";import{once as _}from"node:events";import{createServer as v}from"node:http";import{setTimeout as y}from"node:timers/promises";import{PiAiAdapter as b}from"@deepseek-ai/dsh-llm-pi-ai";import{InMemoryCredentialStore as x,defaultProviderAuthContext as S}from"@earendil-works/pi-ai";import{openaiProvider as ee}from"@earendil-works/pi-ai/providers/openai";var te;/* @__NO_SIDE_EFFECTS__ */
|
|
2
|
+
function C(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:/* @__PURE__ */ new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var w=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};(te=globalThis).__zod_globalConfig??(te.__zod_globalConfig={});const ne=globalThis.__zod_globalConfig;function T(e){return e&&Object.assign(ne,e),ne}function re(e,t=`|`){return e.map(e=>pe(e)).join(t)}function ie(e,t){return typeof t==`bigint`?t.toString():t}function ae(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function oe(e){return e==null}function se(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}const ce=/* @__PURE__*/ Symbol(`evaluating`);function E(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ce)return r===void 0&&(r=ce,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const le=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function de(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function fe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function D(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function pe(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function me(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function O(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function he(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ge(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function k(e){return typeof e==`string`?e:e?.message}function A(e,t,n){let r=e.message?e.message:k(e.inst?._zod.def?.error?.(e))??k(t?.error?.(e))??k(n.customError?.(e))??k(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function _e(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ve(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}const ye=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ie,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},be=/* @__PURE__ */ C(`$ZodError`,ye),j=/* @__PURE__ */ C(`$ZodError`,ye,{Parent:Error}),xe=/* @__PURE__*/ (e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new w;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>A(e,a,T())));throw le(t,i?.callee),t}return o.value})(j),Se=/* @__PURE__*/ (e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>A(e,a,T())));throw le(t,i?.callee),t}return o.value})(j),Ce=/* @__PURE__*/ (e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new w;return a.issues.length?{success:!1,error:new(e??be)(a.issues.map(e=>A(e,i,T())))}:{success:!0,data:a.value}})(j),we=/* @__PURE__*/ (e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>A(e,i,T())))}:{success:!0,data:a.value}})(j),Te=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ee=/^-?\d+(?:\.\d+)?$/,De=/^(?:true|false)$/i,Oe=/*@__PURE__*/ C(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ke=/*@__PURE__*/ C(`$ZodCheckMinLength`,(e,t)=>{var n;Oe.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=_e(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ae={major:4,minor:4,patch:3},M=/*@__PURE__*/ C(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ae;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=O(e),i;for(let a of t){if(a._zod.def.when){if(he(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new w;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=O(e,t))});else{if(e.issues.length===t)continue;r||=O(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(O(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new w;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new w;return o.then(e=>t(e,r,a))}return t(o,r,a)}}E(e,`~standard`,()=>({validate:t=>{try{let n=Ce(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return we(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),je=/*@__PURE__*/ C(`$ZodString`,(e,t)=>{M.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Te(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Me=/*@__PURE__*/ C(`$ZodNumber`,(e,t)=>{M.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ee,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ne=/*@__PURE__*/ C(`$ZodBoolean`,(e,t)=>{M.init(e,t),e._zod.pattern=De,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Pe=/*@__PURE__*/ C(`$ZodNever`,(e,t)=>{M.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Fe(e,t,n){e.issues.length&&t.issues.push(...ge(n,e.issues)),t.value[n]=e.value}const Ie=/*@__PURE__*/ C(`$ZodArray`,(e,t)=>{M.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Fe(t,n,e))):Fe(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Le(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...ge(n,e.issues))}!o&&!i?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Re(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=me(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ze(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Le(e,n,i,t,u,d))):Le(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const Be=/*@__PURE__*/ C(`$ZodObject`,(e,t)=>{if(M.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=ae(()=>Re(t));E(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */ new Set);for(let e of r.values)n[t].add(e)}}return n});let r=ue,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>Le(n,t,e,s,r,i))):Le(a,t,e,s,r,i)}return i?ze(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ve=/*@__PURE__*/ C(`$ZodLiteral`,(e,t)=>{if(M.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?de(e):e?de(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}});function He(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Ue=/*@__PURE__*/ C(`$ZodOptional`,(e,t)=>{M.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,E(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,void 0]):void 0),E(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${se(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>He(e,r)):He(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),We=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};return e=>{switch(e.code){case`invalid_type`:{let t=r[e.expected]??e.expected,n=ve(e.input);return`Invalid input: expected ${t}, received ${r[n]??n}`}case`invalid_value`:return e.values.length===1?`Invalid input: expected ${pe(e.values[0])}`:`Invalid option: expected one of ${re(e.values,`|`)}`;case`too_big`:{let n=e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${re(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Ge(){return{localeError:We()}}// @__NO_SIDE_EFFECTS__
|
|
3
|
+
function Ke(e,t){return new e({type:`string`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
4
|
+
function qe(e,t){return new e({type:`number`,checks:[],...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
5
|
+
function Je(e,t){return new e({type:`boolean`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
6
|
+
function Ye(e,t){return new e({type:`never`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
7
|
+
function N(e,t){return new ke({check:`min_length`,...D(t),minimum:e})}const P=/*@__PURE__*/ C(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);M.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>xe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ce(e,t,n),e.parseAsync=async(t,n)=>Se(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>we(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>fe(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Xe=/*@__PURE__*/ C(`ZodMiniString`,(e,t)=>{je.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
8
|
+
function F(e){return/* @__PURE__ */ Ke(Xe,e)}const Ze=/*@__PURE__*/ C(`ZodMiniNumber`,(e,t)=>{Me.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
9
|
+
function Qe(e){return/* @__PURE__ */ qe(Ze,e)}const $e=/*@__PURE__*/ C(`ZodMiniBoolean`,(e,t)=>{Ne.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
10
|
+
function et(e){return/* @__PURE__ */ Je($e,e)}const tt=/*@__PURE__*/ C(`ZodMiniNever`,(e,t)=>{Pe.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
11
|
+
function nt(e){return/* @__PURE__ */ Ye(tt,e)}const rt=/*@__PURE__*/ C(`ZodMiniArray`,(e,t)=>{Ie.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
12
|
+
function it(e,t){return new rt({type:`array`,element:e,...D(t)})}const at=/*@__PURE__*/ C(`ZodMiniObject`,(e,t)=>{Be.init(e,t),P.init(e,t),E(e,`shape`,()=>t.shape)});// @__NO_SIDE_EFFECTS__
|
|
13
|
+
function I(e,t){return new at({type:`object`,shape:e,catchall:/* @__PURE__ */ nt(),...D(t)})}const ot=/*@__PURE__*/ C(`ZodMiniLiteral`,(e,t)=>{Ve.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
14
|
+
function st(e,t){return new ot({type:`literal`,values:Array.isArray(e)?e:[e],...D(t)})}const ct=/*@__PURE__*/ C(`ZodMiniOptional`,(e,t)=>{Ue.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
15
|
+
function L(e){return new ct({type:`optional`,innerType:e})}const lt=new TextEncoder,ut=new TextDecoder,dt=new TextDecoder(`utf-8`,{fatal:!0});function ft(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}const pt=/[^\x00-\x7f]/;function R(e){if(typeof e==`string`&&e.length>=128){if(pt.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return lt.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function mt(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}var z=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},B=class extends z{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ht=class extends z{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},gt=class extends z{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},V=class extends z{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},H=class extends z{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},_t=class extends z{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},vt=class extends z{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},yt=class extends z{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},bt=class extends z{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},xt=class extends z{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},St=class extends z{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function Ct(e){try{return mt(typeof e==`string`?e:ut.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function U(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function wt(e){return U(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(U)}function Tt(...e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Et(e,t,n){try{return Ct(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Dt(e,t,n){try{return R(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Ot(e,t,n){let r;try{r=JSON.parse(dt.decode(Ct(e)))}catch{throw new t(n)}if(!U(r))throw new t(n);return r}const kt={__proto__:null,b64:!0};function At(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function jt(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new V(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Mt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new H(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}const Nt=e=>e[Symbol.toStringTag],Pt=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function Ft(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(U(t)){if(o=qt(t),typeof o.kty!=`string`)throw Ht(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Pt(e,o,n),o.kty===`oct`)return Ct(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Bt(t))throw Ht(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Nt(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Rt(t))return t;if(s=t,s.type===`secret`)return s.export()}It||=/* @__PURE__ */ new WeakMap;let c=t,l=It.get(c);if(l?.[r])return l[r];if(l||It.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Lt[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await Jt(e,o)}let It;const Lt={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},Rt=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},zt=e=>e?.[Symbol.toStringTag]===`KeyObject`,Bt=e=>Rt(e)||zt(e);function Vt(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function Ht(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Vt(`Key for the ${e} algorithm must be `,t,...r))}const W=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Ut(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Wt(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Gt(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw W(t.name);if(t.hash&&r.hash?.name!==t.hash)throw W(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw W(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw W(t.length,`algorithm.length`);Ut(e,n)}function Kt(e){return{__proto__:null,...e}}function qt(e){let t=Kt(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function Jt(e,t,n){if(!e.kty.includes(t.kty))throw new V(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function Yt(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Gt(e,t,n),e}function Xt(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const G=[[`verify`],[`sign`]];function Zt(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:G}}function K(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:G,minRsaBits:2048}}function Qt(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:G}}function $t(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:G}}function en(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:G}}const tn=Xt({HS256:Zt(256),HS384:Zt(384),HS512:Zt(512),RS256:K(256),RS384:K(384),RS512:K(512),PS256:K(256,32),PS384:K(384,48),PS512:K(512,64),ES256:Qt(`P-256`,256),ES384:Qt(`P-384`,384),ES512:Qt(`P-521`,512),EdDSA:$t(),Ed25519:$t(),"ML-DSA-44":en(44),"ML-DSA-65":en(65),"ML-DSA-87":en(87)});function nn(e){let t=typeof e==`string`?tn[e]:void 0;if(!t)throw new V(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function rn(e){return[e&&At(`algorithms`,e.algorithms),e?.crit]}function an(e){return e===void 0?{}:Ot(e,H,`JWS Protected Header is invalid`)}function on(e){try{return R(e)}catch{throw new H(`JWS Compact Serialization payload must use only ASCII characters`)}}async function sn(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??an(a);if(!Tt(c,o))throw new H(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Mt(c,jt(H,kt,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new H(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new gt(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new H(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new H(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=nn(d),h=ft(a===void 0?/* @__PURE__ */ new Uint8Array:R(a),R(`.`),typeof f==`string`?t[2]??=Dt(f,`payload`,H):f),g=Et(e.signature,`signature`,H),_=await Ft(m,n,`verify`),v=await Yt(_,m.subtle,`verify`);m.minRsaBits&&Wt(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new St;let b={payload:typeof f==`string`?Et(f,`payload`,H):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function cn(e,t,n){if(e instanceof Uint8Array&&(e=ut.decode(e)),typeof e!=`string`)throw new H(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new H(`Invalid Compact JWS`);return sn({payload:i,protected:r,signature:a},t,n,on)}const ln=e=>Math.floor(e.getTime()/1e3),un={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},dn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,q=`check_failed`;function fn(){throw TypeError(`Invalid time period format`)}function pn(e){typeof e!=`string`&&fn();let t=dn.exec(e);(!t||t[4]&&t[1])&&fn();let n=parseFloat(t[2]),r=Math.round(n*un[t[3][0].toLowerCase()]);return Number.isFinite(r)||fn(),t[1]===`-`||t[4]===`ago`?-r:r}function mn(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const hn=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},gn=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function _n(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new B(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function vn(e,t){throw new B(`unexpected "${t}" claim value`,e,t,q)}function yn(e,t,n={}){let r;try{r=JSON.parse(dt.decode(t))}catch{}if(!U(r))throw new _t(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||hn(e.typ)!==hn(i)))throw new B(`unexpected "typ" JWT header value`,r,`typ`,q);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new B(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&vn(r,`iss`),s!==void 0&&r.sub!==s&&vn(r,`sub`),c!==void 0&&!gn(r.aud,typeof c==`string`?[c]:c)&&vn(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=pn(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}mn(`clockTolerance option`,f);let{currentDate:p}=n,m=mn(`currentDate option`,ln(p===void 0?/* @__PURE__ */ new Date:p)),h=_n(r,`iat`,l!==void 0),g=_n(r,`nbf`);if(g!==void 0&&g>m+f)throw new B(`"nbf" claim timestamp check failed`,r,`nbf`,q);let _=_n(r,`exp`);if(_!==void 0&&_<=m-f)throw new ht(`"exp" claim timestamp check failed`,r,`exp`,q);if(l!==void 0){let e=m-h,t=mn(`maxTokenAge option`,typeof l==`number`?l:pn(l));if(e-f>t)throw new ht(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,q);if(e<-f)throw new B(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,q)}return r}async function bn(e,t,n){let[r,i]=await cn(e,rn(n),t);if(!i)throw new _t(`JWTs MUST NOT use unencoded payload`);let a=yn(r.protectedHeader,r.payload,n);return{...r,payload:a}}function xn(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function Sn(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=Jt(n,t,!0).then(e=>{if(e.type!==`public`)throw new vt(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function Cn(e){let t;try{t=structuredClone(e)}catch{}if(!wt(t))throw new vt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=Kt(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=/* @__PURE__ */ new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?tn[a]:void 0;if(!s||s.secret)throw new V(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>xn(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new yt;if(u!==1){let e=new bt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await Sn(r,e,s)}catch{}},e}return Sn(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function wn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Tn;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Tn=`jose/v6.2.12`);const En=/* @__PURE__ */ Symbol();async function Dn(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new xt:e});if(i.status!==200)throw new z(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new z(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const On=/* @__PURE__ */ Symbol();function J(e,t){return Number.isFinite(e)&&Date.now()<e+t}function kn(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function An(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=kn(r.cooldownDuration,3e4,`cooldownDuration`),s=kn(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);Tn&&!c.has(`User-Agent`)&&c.set(`User-Agent`,Tn),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[En],u=r[On],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;J(e,s)&&wt(t)&&(d=e,h=Cn(t))}let g=async()=>{if(f&&wn()&&(f=void 0),!f){let e=++p,t=f=Dn(n,c,AbortSignal.timeout(a),l).then(t=>{let n=Cn(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!J(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof yt&&!J(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>J(d,o),enumerable:!0},fresh:{get:()=>J(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}const Y=`https://auth.openai.com`,jn=`https://api.openai.com/v1`,X=`https://chatgpt.com/settings/usage`;var Mn=class extends Error{},Nn=class extends Error{},Pn=class extends Error{status;code;requestId;constructor(e,t,n){super(`OpenAI request failed (${e}${t?`: ${t}`:``}). Reconnect with /chatgpt login; manage usage: ${X}`),this.status=e,this.code=t,this.requestId=n}};const Fn=/* @__PURE__ */ new Set([`invalid_grant`,`invalid_refresh_token`,`token_expired`,`refresh_token_expired`,`refresh_token_invalidated`,`refresh_token_reused`]);function In(t){e.ok(typeof t==`object`&&!!t&&!Array.isArray(t),`Invalid OpenAI response`)}function Z(t,n){e.ok(typeof t==`string`&&t.trim(),`OpenAI returned invalid ${n}`)}async function Ln(e,t={}){let n=await fetch(e,{...t,signal:AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]])}).catch(e=>{throw new Nn(`Could not reach OpenAI. Check your connection and try again.`,{cause:e})});if(!n.ok){let e;if(n.headers.get(`content-type`)?.includes(`json`)){let t=await n.json();In(t),typeof t.error==`string`?e=t.error:t.error&&typeof t.error==`object`&&`code`in t.error&&typeof t.error.code==`string`&&(e=t.error.code)}throw new Pn(n.status,e,n.headers.get(`x-request-id`))}let r=await n.json();return In(r),r}async function Rn(t){let n=await Ln(`${Y}/.well-known/openid-configuration`,{signal:t});e.equal(n.issuer,Y,`Unexpected OpenAI issuer`);for(let t of[`authorization_endpoint`,`token_endpoint`,`jwks_uri`])Z(n[t],t),e.equal(new URL(n[t]).origin,Y,`Unexpected OpenAI ${t}`);return n.revocation_endpoint!==void 0&&(Z(n.revocation_endpoint,`revocation_endpoint`),e.equal(new URL(n.revocation_endpoint).origin,Y,`Unexpected OpenAI revocation endpoint`)),n}async function zn(t,n,r,i,a){let o=await Rn(a).catch(()=>{throw new Mn(`OpenAI identity service is unavailable. Try again.`)}),s=An(new URL(o.jwks_uri)),{payload:c}=await bn(t,async(e,t)=>{try{return await s(e,t)}catch(e){throw e instanceof yt?e:new Mn(`OpenAI signing keys are unavailable. Try again.`)}},{issuer:Y,audience:n,algorithms:[`RS256`],requiredClaims:[`iss`,`sub`,`aud`,`iat`,`exp`],...i===void 0?{}:{currentDate:new Date(i)}});return Z(c.sub,`ID token subject`),r!==void 0&&e.equal(c.nonce,r,`OpenAI ID token nonce mismatch`),(c.azp!==void 0||Array.isArray(c.aud)&&c.aud.length>1)&&e.equal(c.azp,n,`OpenAI ID token authorized party mismatch`),{subject:c.sub,...typeof c.email==`string`?{email:c.email}:{}}}async function Bn(t,n){let r=await Ln((await Rn(n)).token_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:t,signal:n});Z(r.access_token,`access_token`),Z(r.refresh_token,`refresh_token`),Z(r.scope,`scope`),e.equal(String(r.token_type).toLowerCase(),`bearer`,`Unexpected OpenAI token type`),e.ok(typeof r.expires_in==`number`&&Number.isFinite(r.expires_in)&&r.expires_in>0,`Invalid OpenAI token expiry`);let i=r.scope.split(/\s+/);e.ok(i.includes(`chatgpt.tokens.use.direct`),`ChatGPT plan usage was not granted`);let a;return r.earliest_refresh_at!==void 0&&(a=typeof r.earliest_refresh_at==`number`?r.earliest_refresh_at*1e3:Date.parse(String(r.earliest_refresh_at)),e.ok(Number.isFinite(a),`Invalid earliest_refresh_at`)),r.id_token!==void 0&&Z(r.id_token,`id_token`),{tokens:{access:r.access_token,refresh:r.refresh_token,expires:Date.now()+r.expires_in*1e3,scopes:i,...a===void 0?{}:{refreshAfter:a}},receivedAt:Date.now(),...r.id_token===void 0?{}:{idToken:r.id_token}}}function Vn(t,n){return e.ok(t.tokens,`Sign in with /chatgpt login first`),Bn(new URLSearchParams({grant_type:`refresh_token`,client_id:t.clientId,refresh_token:t.tokens.refresh,resource:jn}),n)}async function Hn(t){let n=AbortSignal.timeout(1e4),r=await Rn(n);e.ok(r.revocation_endpoint,`OpenAI did not publish a revocation endpoint`);let i=t.pending?.tokens.refresh??t.tokens?.refresh;e.ok(i,`No renewable ChatGPT session`);for(let e=0;;e++){try{let e=await fetch(r.revocation_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},signal:n,body:new URLSearchParams({token:i,token_type_hint:`refresh_token`,client_id:t.clientId})});if(e.status===200)return;if(e.status<500)throw Error(`ChatGPT session revocation failed (${e.status})`)}catch(t){if(!(t instanceof TypeError)||n.aborted||e===2)throw t}if(e===2)throw Error(`ChatGPT session revocation is unavailable`);await y(200*2**e,void 0,{signal:n})}}async function Un(t,n){let r=await Ln(`${jn}/models`,{headers:{authorization:`Bearer ${t}`},signal:n});return e.ok(Array.isArray(r.models),`Invalid ChatGPT model catalog`),r.models.filter(e=>(In(e),e.visibility===`list`)).map(e=>(Z(e.slug,`model slug`),Z(e.display_name,`model display name`),{id:e.slug,name:e.display_name}))}async function Wn(r,i,o,s){let c=await Rn(r.signal),l=n(32).toString(`base64url`),u=n(32).toString(`base64url`),d=n(32).toString(`base64url`),f=AbortSignal.any([r.signal,AbortSignal.timeout(3e5)]),p,m,h=new Promise((e,t)=>{p=e,m=t}),g=()=>m(f.reason);f.addEventListener(`abort`,g,{once:!0}),h.catch(()=>{});let y,b=v((e,t)=>{t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`Referrer-Policy`,`no-referrer`),t.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let n=new URL(e.url??`/`,`http://127.0.0.1`);if(e.method===`GET`&&n.pathname===`/auth/start`&&n.searchParams.get(`state`)===l){t.writeHead(302,{Location:y}).end();return}if(e.method!==`GET`||n.pathname!==`/auth/callback`){t.writeHead(404).end(`Not found`);return}if(n.searchParams.get(`state`)!==l){t.writeHead(400).end(`OAuth state mismatch`);return}if(n.searchParams.has(`error`)){t.writeHead(400).end(`ChatGPT sign-in was declined. Return to DSH.`),m(/* @__PURE__ */ Error(`ChatGPT sign-in was declined`));return}let r=n.searchParams.get(`code`),i=n.searchParams.get(`client_id`)??o.clientId;!r||!i||i===`dynamic_agent_client`||o.clientId!==`dynamic_agent_client`&&o.clientId!==i?(t.writeHead(400).end(`Invalid OAuth registration callback`),m(/* @__PURE__ */ Error(`Invalid OpenAI OAuth registration callback`))):(t.end(`Return to DSH to finish connecting your ChatGPT account.`),p({code:r,clientId:i}))}),x=new AbortController;try{f.throwIfAborted(),b.listen(0,`127.0.0.1`),await _(b,`listening`);let n=b.address();e.ok(n&&typeof n==`object`);let p=`http://127.0.0.1:${n.port}/auth/callback`,m=new URL(c.authorization_endpoint);m.search=new URLSearchParams({client_id:o.clientId,ext_agent_host_id:i,response_type:`code`,redirect_uri:p,resource:jn,scope:`openid profile email offline_access resource.invoke chatgpt.tokens.use.direct`,state:l,nonce:u,code_challenge_method:`S256`,code_challenge:t(`sha256`).update(d).digest(`base64url`),...o.clientId===`dynamic_agent_client`?{agent_name_hint:`DSH SIWC`}:{},...o.idToken?{id_token_hint:o.idToken}:{},...o.email?{login_hint:o.email}:{}}).toString(),y=m.toString(),r.notify({message:`Continue with ChatGPT`,url:`http://127.0.0.1:${n.port}/auth/start?state=${l}`});let g=r.prompt({kind:`select`,message:`Open the sign-in link, then finish in your browser.`,options:[{id:`cancel`,label:`Cancel sign-in`}],signal:AbortSignal.any([f,x.signal])}).then(()=>{throw new a}),v=await Promise.race([h,g]);x.abort(),f.throwIfAborted(),await s(v.clientId);let S=await Bn(new URLSearchParams({grant_type:`authorization_code`,client_id:v.clientId,code:v.code,code_verifier:d,redirect_uri:p,resource:jn}),f);Z(S.idToken,`id_token`);let ee=await zn(S.idToken,v.clientId,u,void 0,f);return o.subject&&e.equal(ee.subject,o.subject,`ChatGPT account changed during reauthorization`),f.throwIfAborted(),{...ee,tokens:S.tokens,idToken:S.idToken}}finally{x.abort(),f.removeEventListener(`abort`,g),b.close(),b.closeAllConnections()}}T(Ge());const Q=f(`siwc`,`chatgpt`),Gn=/* @__PURE__ */ I({access:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),refresh:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),expires:/* @__PURE__ */ Qe(),scopes:/* @__PURE__ */ it(/* @__PURE__ */ F()),refreshAfter:/* @__PURE__ */ L(/* @__PURE__ */ Qe())}),Kn=/* @__PURE__ */ I({version:/* @__PURE__ */ st(1),activeId:/* @__PURE__ */ L(/* @__PURE__ */ F()),welcomed:/* @__PURE__ */ L(/* @__PURE__ */ et()),accounts:/* @__PURE__ */ it(/* @__PURE__ */ I({id:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),clientId:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),subject:/* @__PURE__ */ L(/* @__PURE__ */ F()),email:/* @__PURE__ */ L(/* @__PURE__ */ F()),idToken:/* @__PURE__ */ L(/* @__PURE__ */ F()),tokens:/* @__PURE__ */ L(Gn),pending:/* @__PURE__ */ L(/* @__PURE__ */ I({tokens:Gn,idToken:/* @__PURE__ */ L(/* @__PURE__ */ F()),receivedAt:/* @__PURE__ */ Qe()})),models:/* @__PURE__ */ L(/* @__PURE__ */ it(/* @__PURE__ */ I({id:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),name:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1))})))}))});function $(t){return t===void 0?{version:1,accounts:[]}:(e.ok(t.kind===`grant`,`Invalid SIWC credential record`),Kn.parse(t.payload))}async function qn(){let t=p(`siwc`,`host-id`);return await s(l(t),{recursive:!0,mode:448}),u(t,async()=>{let n;try{n=(await c(t,`utf8`)).trim()}catch(e){if(e.code!==`ENOENT`)throw e;n=`urn:uuid:${r()}`,await d(t,n,{mode:384,dirMode:448})}return e.match(n,/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,`Invalid saved SIWC host ID`),n})}var Jn=class{credentials;constructor(e){this.credentials=e}async read(){return $(await this.credentials.readRecord(Q))}async change(e){return $(await this.credentials.modifyRecord(Q,async t=>{let n=$(t);return await e(n),{kind:`grant`,payload:n}}))}async accessToken(t,n){let r,i=AbortSignal.timeout(2e4),a=await this.credentials.modifyRecord(Q,async a=>{let o=$(a),s=o.accounts.find(e=>e.id===(t??o.activeId));if(!s?.tokens)throw new m(`Continue with ChatGPT using /chatgpt login`,`MISSING_CREDENTIAL`);let c=Date.now();if(n!==void 0&&s.tokens.access!==n||!s.pending&&(n===void 0&&c<s.tokens.expires-6e4||s.tokens.refreshAfter!==void 0&&c<s.tokens.refreshAfter&&c<s.tokens.expires))return;if(!s.pending&&s.tokens.refreshAfter!==void 0&&c<s.tokens.refreshAfter)throw Error(`ChatGPT token expired before its refresh window. Try again later or reconnect.`);let l;try{if(l=s.pending??await Vn(s,i),l.idToken){let t=await zn(l.idToken,s.clientId,void 0,l.receivedAt,i);e.equal(t.subject,s.subject,`Refreshed ChatGPT identity changed`),s.idToken=l.idToken}s.tokens=l.tokens,delete s.pending}catch(e){if(e instanceof Mn&&l)s.pending=l;else if(l||e instanceof Pn&&e.code!==void 0&&Fn.has(e.code))delete s.tokens,delete s.pending,o.activeId===s.id&&delete o.activeId;else throw e;r=e}return{kind:`grant`,payload:o}});if(r)throw r;let o=$(a);return o.accounts.find(e=>e.id===(t??o.activeId)).tokens.access}};function Yn(e,t){let n=ee(),r=new Map(n.getModels().map(e=>[e.id,e])),i=(t?.models??[]).flatMap(({id:t,name:n})=>{let i=r.get(t);return i?[{...i,name:n}]:(e.logger.warn(`Skipping ChatGPT model %s: missing from pi-ai.`,t),[])});return/* @__PURE__ */ new Map([[`openai`,{provider:`openai`,displayName:`ChatGPT Subscription Plan`,...t?{accountId:t.id}:{},piProvider:{...n,getModels:()=>i,getAllModels:()=>i},streamIdleTimeoutMs:3e5,maxRequestImageBytes:20971520,requestImagePixelBudget:4194304,requestImageMaxBytes:1048576,retryPolicy:g(void 0,`siwc`),modelErrors:/* @__PURE__ */ new Map,configuredMaxTokens:/* @__PURE__ */ new Map}]])}var Xn=class extends b{ctx;accounts;currentProfiles;options;constructor(e,t){let n={value:Yn(e),stamp:``},r={profiles:()=>n.value,resolveApiKey:(e,n)=>t.accessToken(n.accountId),auth:{credentials:new x,authContext:S()},resolveAttachments:()=>e.get(`attachments`),resolveImageAccess:(t,n)=>h(t,t=>e.get(`fs`)?.processPathFromHostPath(t),n)};super(r),this.ctx=e,this.options=r,this.accounts=t,this.currentProfiles=n}async sync(){let e=await this.accounts.read(),t=e.accounts.find(t=>t.id===e.activeId),n=JSON.stringify([t?.id,t?.email,t?.models]);n!==this.currentProfiles.stamp&&(this.currentProfiles.value=Yn(this.ctx,t),this.currentProfiles.stamp=n)}async listModels(e){return await this.sync(),super.listModels(e)}async resolveModel(e,t,n){return await this.sync(),super.resolveModel(e,t,n)}async prepareCall(e,t,n){await this.sync();let r=this.currentProfiles.value,i=r.get(e)?.accountId,a,o=await new b({...this.options,profiles:()=>r,resolveApiKey:async()=>(a=await this.accounts.accessToken(i),a)}).prepareCall(e,t,n);return{model:o.model,stream:e=>this.recoverAuth(o.stream(e),i,()=>a)}}async*recoverAuth(e,t,n){let r=!1,i=async e=>{let i=n();t&&i&&/\b401\b|subscription_sharing_invalid_user/.test(e)&&(r=!0,await this.accounts.accessToken(t,i))};try{for await(let t of e)t.type===`finish`&&t.reason.kind===`error`&&await i(t.reason.failure.message),yield t}catch(e){throw!r&&e instanceof Error&&await i(e.message),e}}async*stream(e){yield*(await this.prepareCall(e.provider,e.model,e.signal)).stream(e)}};const Zn=`siwc`,Qn=[`credentials`,`authorization`,`llm`],$n=[`0.2.1-alpha.2`,`0.2.1-alpha.3`,`0.2.1-alpha.4`,`0.2.1-alpha.5`,`0.2.1-rc.1`,`0.2.1-rc.2`],er=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;async function tr(e,t){let n=await t.read(),r=n.accounts.find(e=>e.id===n.activeId);if(!r?.tokens)return;let i,a;try{i=await t.accessToken(r.id),a=await Un(i)}catch(t){if(!(t instanceof Nn)&&!(t instanceof Pn)&&!(t instanceof Mn))throw t;e.logger.warn(`Could not refresh ChatGPT models at startup; keeping the saved catalog: %s`,t.message);return}await t.change(e=>{let t=e.accounts.find(e=>e.id===r.id);t?.tokens?.access===i&&(t.models=a)})}async function nr(t){let n=i();$n.includes(n)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,$n.join(`, `),n);let s=new Jn(t.credentials);await tr(t,s);let c=new Xn(t,s);t.llm.registerAdapter([`openai`],c);async function l(t){let n=await s.read(),i=n.accounts.map(e=>({id:e.id,label:er(e)}));t.method===`oauth`&&i.push({id:`new`,label:`Add ChatGPT account or workspace`}),e.ok(i.length,`No saved ChatGPT account. Use /chatgpt login first.`);let a=i.length===1?i[0].id:await t.prompt({kind:`select`,message:`Choose your ChatGPT account`,options:i}),o=n.accounts.find(e=>e.id===a);e.ok(a===`new`||o,`Unknown ChatGPT account`);let l=o??{id:r(),clientId:`dynamic_agent_client`};if(t.method===`oauth`){let e=await Wn(t,await qn(),l,async e=>{t.signal.throwIfAborted(),l.clientId=e,await s.change(t=>{let n=t.accounts.find(e=>e.id===l.id);n?n.clientId=e:t.accounts.push({...l,clientId:e})})});Object.assign(l,e)}e.ok(l.tokens,`This account is signed out. Reconnect with /chatgpt login.`);let u=await Un(t.method===`oauth`?l.tokens.access:await s.accessToken(l.id),t.signal);n.welcomed||(t.notify({message:`Manage usage`,url:X}),await t.prompt({kind:`select`,message:`You're using your ChatGPT plan. Eligible requests use your plan allowance. Manage usage in ChatGPT settings.`,options:[{id:`ok`,label:`Got it`}]})),t.signal.throwIfAborted(),await s.change(n=>{t.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===l.id);e.ok(r,`ChatGPT registration was removed during sign-in. Please retry.`),t.method===`oauth`&&(Object.assign(r,l),delete r.pending),r.models=u,n.activeId=l.id,n.welcomed=!0}),await c.sync(),t.notify({message:`Using ChatGPT plan. Manage usage`,url:X})}t.authorization.registerFlow({key:Q,label:`ChatGPT plan`,methods:[{id:`oauth`,label:`Continue with ChatGPT`},{id:`select`,label:`Switch saved account`}],run:l}),t.inject([`commands`,`userQuestions`],e=>{e.commands.register({name:`chatgpt`,description:`Connect or manage your ChatGPT plan`,input:{hint:`<login|accounts|logout|status>`},async handler({agent:t,rawInput:n,signal:r}){let i=n.trim()||`status`;if(i===`logout`){let e=!0;return await s.change(async t=>{let n=t.accounts.find(e=>e.id===t.activeId);if(n?.tokens||n?.pending)try{await Hn(n)}catch{e=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete t.activeId}),await c.sync(),{kind:`success`,text:`Signed out. Saved registrations are retained.${e?``:` Remote revocation was not confirmed; disconnect this app in ChatGPT settings.`}\nManage app access: ${X}`}}if(i===`status`){let e=await s.read(),t=e.accounts.find(t=>t.id===e.activeId);return{kind:`success`,text:`${t?.tokens?`Using ChatGPT plan: ${er(t)}`:`Signed out. Use /chatgpt login.`}\nManage usage: ${X}`}}if(i!==`login`&&i!==`accounts`)return{kind:`error`,text:`Usage: /chatgpt login|accounts|logout|status`};let l;return(await e.authorization.begin({key:Q,method:i===`login`?`oauth`:`select`,signal:r,interaction:{notify(e){l=e},async prompt(n){if(n.kind!==`select`)throw Error(`Unsupported authorization prompt`);let i=l;l=void 0;let s=await e.userQuestions.ask({agent:t,signal:AbortSignal.any([r,...n.signal?[n.signal]:[]]),questions:[{id:`chatgpt`,header:`ChatGPT`,question:n.message,...i?{detail:i.url?`[${i.message}](${i.url})`:i.message}:{},options:n.options.map(({label:e})=>({label:e})),multiSelect:!1}]}).catch(e=>{throw e instanceof o&&e.code===`ASK_ABORTED`&&!n.signal?.aborted&&!r.aborted?new a:e}),c=n.options.find(e=>e.label===s.answers[0]?.selected[0]);if(!c)throw new a;return c.id}}})).status===`authorized`?{kind:`success`,text:`Using ChatGPT plan. Select a model under ChatGPT plan.\nManage usage: ${X}`}:{kind:`error`,text:`ChatGPT sign-in cancelled.`}}})})}export{nr as apply,Qn as inject,Zn as name};
|