dsh-siwc 0.1.3 → 0.1.4

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 CHANGED
@@ -25,19 +25,19 @@ If another plugin uses the `openai` route, disable that route first to avoid a c
25
25
 
26
26
  ### From source
27
27
 
28
- Clone the repository and install dependencies:
28
+ Clone the repository and install dependencies from its root:
29
29
 
30
30
  ```sh
31
- git clone https://github.com/ph0ryn/dsh-siwc.git
32
- cd dsh-siwc
31
+ git clone https://github.com/ph0ryn/dsh-plugins.git
32
+ cd dsh-plugins
33
33
  pnpm install --frozen-lockfile
34
34
  ```
35
35
 
36
- Build a package and install it into your Web profile:
36
+ Build this plugin and install it into your Web profile:
37
37
 
38
38
  ```sh
39
- pnpm pack
40
- dsh plugin --profile web add ./dsh-siwc-0.1.3.tgz --ignore-scripts
39
+ pnpm --filter dsh-siwc pack --pack-destination ./artifacts
40
+ dsh plugin --profile web add ./artifacts/dsh-siwc-0.1.4.tgz --ignore-scripts
41
41
  ```
42
42
 
43
43
  ## Use
@@ -14,4 +14,4 @@ function I(e,t){return new lt({type:`object`,shape:e,catchall:/* @__PURE__ */ ot
14
14
  function dt(e,t){return new ut({type:`literal`,values:Array.isArray(e)?e:[e],...D(t)})}const ft=/*@__PURE__*/ C(`ZodMiniOptional`,(e,t)=>{qe.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
15
15
  function L(e){return new ft({type:`optional`,innerType:e})}const pt=new TextEncoder,mt=new TextDecoder,ht=new TextDecoder(`utf-8`,{fatal:!0});function gt(...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 _t=/[^\x00-\x7f]/;function R(e){if(typeof e==`string`&&e.length>=128){if(_t.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return pt.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 vt(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}},yt=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}},bt=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`},xt=class extends z{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},St=class extends z{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},Ct=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)}},wt=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)}},Tt=class extends z{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Et=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 Dt(e){try{return vt(typeof e==`string`?e:mt.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 Ot(e){return U(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(U)}function kt(...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 At(e,t,n){try{return Dt(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function jt(e,t,n){try{return R(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Mt(e,t,n){let r;try{r=JSON.parse(ht.decode(Dt(e)))}catch{throw new t(n)}if(!U(r))throw new t(n);return r}const Nt={__proto__:null,b64:!0};function Pt(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 Ft(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 It(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 Lt=e=>e[Symbol.toStringTag],Rt=(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 zt(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=Zt(t),typeof o.kty!=`string`)throw Kt(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(Rt(e,o,n),o.kty===`oct`)return Dt(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Wt(t))throw Kt(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Lt(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Ht(t))return t;if(s=t,s.type===`secret`)return s.export()}Bt||=/* @__PURE__ */ new WeakMap;let c=t,l=Bt.get(c);if(l?.[r])return l[r];if(l||Bt.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Vt[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 Qt(e,o)}let Bt;const Vt={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},Ht=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Ut=e=>e?.[Symbol.toStringTag]===`KeyObject`,Wt=e=>Ht(e)||Ut(e);function Gt(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 Kt(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Gt(`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 qt(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Jt(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 Yt(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`);qt(e,n)}function Xt(e){return{__proto__:null,...e}}function Zt(e){let t=Xt(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 Qt(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 $t(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Yt(e,t,n),e}function en(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const G=[[`verify`],[`sign`]];function tn(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 nn(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:G}}function rn(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:G}}function an(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:G}}const on=en({HS256:tn(256),HS384:tn(384),HS512:tn(512),RS256:K(256),RS384:K(384),RS512:K(512),PS256:K(256,32),PS384:K(384,48),PS512:K(512,64),ES256:nn(`P-256`,256),ES384:nn(`P-384`,384),ES512:nn(`P-521`,512),EdDSA:rn(),Ed25519:rn(),"ML-DSA-44":an(44),"ML-DSA-65":an(65),"ML-DSA-87":an(87)});function sn(e){let t=typeof e==`string`?on[e]:void 0;if(!t)throw new V(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function cn(e){return[e&&Pt(`algorithms`,e.algorithms),e?.crit]}function ln(e){return e===void 0?{}:Mt(e,H,`JWS Protected Header is invalid`)}function un(e){try{return R(e)}catch{throw new H(`JWS Compact Serialization payload must use only ASCII characters`)}}async function dn(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??ln(a);if(!kt(c,o))throw new H(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=It(c,Ft(H,Nt,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 bt(`"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=sn(d),h=gt(a===void 0?/* @__PURE__ */ new Uint8Array:R(a),R(`.`),typeof f==`string`?t[2]??=jt(f,`payload`,H):f),g=At(e.signature,`signature`,H),_=await zt(m,n,`verify`),ee=await $t(_,m.subtle,`verify`);m.minRsaBits&&Jt(m.alg,ee);let v=!1;try{v=await crypto.subtle.verify(m.signing,ee,g,h)}catch{}if(!v)throw new Et;let y={payload:typeof f==`string`?At(f,`payload`,H):f};return a!==void 0&&(y.protectedHeader=c),o!==void 0&&(y.unprotectedHeader=o),p?[{...y,key:_},u]:[y,u]}async function fn(e,t,n){if(e instanceof Uint8Array&&(e=mt.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 dn({payload:i,protected:r,signature:a},t,n,un)}const pn=e=>Math.floor(e.getTime()/1e3),mn={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},hn=/^(\+|\-)? ?(\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 gn(){throw TypeError(`Invalid time period format`)}function _n(e){typeof e!=`string`&&gn();let t=hn.exec(e);(!t||t[4]&&t[1])&&gn();let n=parseFloat(t[2]),r=Math.round(n*mn[t[3][0].toLowerCase()]);return Number.isFinite(r)||gn(),t[1]===`-`||t[4]===`ago`?-r:r}function vn(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const yn=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},bn=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function xn(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 Sn(e,t){throw new B(`unexpected "${t}" claim value`,e,t,q)}function Cn(e,t,n={}){let r;try{r=JSON.parse(ht.decode(t))}catch{}if(!U(r))throw new xt(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||yn(e.typ)!==yn(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)&&Sn(r,`iss`),s!==void 0&&r.sub!==s&&Sn(r,`sub`),c!==void 0&&!bn(r.aud,typeof c==`string`?[c]:c)&&Sn(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=_n(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}vn(`clockTolerance option`,f);let{currentDate:p}=n,m=vn(`currentDate option`,pn(p===void 0?/* @__PURE__ */ new Date:p)),h=xn(r,`iat`,l!==void 0),g=xn(r,`nbf`);if(g!==void 0&&g>m+f)throw new B(`"nbf" claim timestamp check failed`,r,`nbf`,q);let _=xn(r,`exp`);if(_!==void 0&&_<=m-f)throw new yt(`"exp" claim timestamp check failed`,r,`exp`,q);if(l!==void 0){let e=m-h,t=vn(`maxTokenAge option`,typeof l==`number`?l:_n(l));if(e-f>t)throw new yt(`"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 wn(e,t,n){let[r,i]=await fn(e,cn(n),t);if(!i)throw new xt(`JWTs MUST NOT use unencoded payload`);let a=Cn(r.protectedHeader,r.payload,n);return{...r,payload:a}}function Tn(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 En(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=Qt(n,t,!0).then(e=>{if(e.type!==`public`)throw new St(`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 Dn(e){let t;try{t=structuredClone(e)}catch{}if(!Ot(t))throw new St(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=Xt(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`?on[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)=>Tn(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new Ct;if(u!==1){let e=new wt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await En(r,e,s)}catch{}},e}return En(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function On(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let kn;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(kn=`jose/v6.2.12`);const An=/* @__PURE__ */ Symbol();async function jn(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 Tt: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 Mn=/* @__PURE__ */ Symbol();function J(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Nn(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function Pn(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=Nn(r.cooldownDuration,3e4,`cooldownDuration`),s=Nn(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);kn&&!c.has(`User-Agent`)&&c.set(`User-Agent`,kn),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[An],u=r[Mn],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;J(e,s)&&Ot(t)&&(d=e,h=Dn(t))}let g=async()=>{if(f&&On()&&(f=void 0),!f){let e=++p,t=f=jn(n,c,AbortSignal.timeout(a),l).then(t=>{let n=Dn(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 Ct&&!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`,Fn=`https://api.openai.com/v1`,X=`https://chatgpt.com/settings/usage`;var In=class extends Error{},Ln=class extends Error{},Rn=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 zn=/* @__PURE__ */ new Set([`invalid_grant`,`invalid_refresh_token`,`token_expired`,`refresh_token_expired`,`refresh_token_invalidated`,`refresh_token_reused`]);function Bn(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 Vn(e,t={}){let n=await fetch(e,{...t,signal:AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]])}).catch(e=>{throw new Ln(`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();Bn(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 Rn(n.status,e,n.headers.get(`x-request-id`))}let r=await n.json();return Bn(r),r}async function Hn(t){let n=await Vn(`${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 Un(t,n,r,i,a){let o=await Hn(a).catch(()=>{throw new In(`OpenAI identity service is unavailable. Try again.`)}),s=Pn(new URL(o.jwks_uri)),{payload:c}=await wn(t,async(e,t)=>{try{return await s(e,t)}catch(e){throw e instanceof Ct?e:new In(`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 Wn(t,n){let r=await Vn((await Hn(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 Gn(t,n){return e.ok(t.tokens,`Sign in with /chatgpt login first`),Wn(new URLSearchParams({grant_type:`refresh_token`,client_id:t.clientId,refresh_token:t.tokens.refresh,resource:Fn}),n)}async function Kn(t){let n=AbortSignal.timeout(1e4),r=await Hn(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 qn(t,n){let r=await Vn(`${Fn}/models`,{headers:{authorization:`Bearer ${t}`},signal:n});return e.ok(Array.isArray(r.models),`Invalid ChatGPT model catalog`),r.models.filter(e=>(Bn(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 Jn(r,i,o,s){let c=await Hn(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=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:_}).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}))}),b=new AbortController;try{f.throwIfAborted(),y.listen(0,`127.0.0.1`),await ee(y,`listening`);let n=y.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:Fn,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(),_=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,b.signal])}).then(()=>{throw new a}),v=await Promise.race([h,g]);b.abort(),f.throwIfAborted(),await s(v.clientId);let x=await Wn(new URLSearchParams({grant_type:`authorization_code`,client_id:v.clientId,code:v.code,code_verifier:d,redirect_uri:p,resource:Fn}),f);Z(x.idToken,`id_token`);let te=await Un(x.idToken,v.clientId,u,void 0,f);return o.subject&&e.equal(te.subject,o.subject,`ChatGPT account changed during reauthorization`),f.throwIfAborted(),{...te,tokens:x.tokens,idToken:x.idToken}}finally{b.abort(),f.removeEventListener(`abort`,g),y.close(),y.closeAllConnections()}}T(Ye());const Q=p(`siwc`,`chatgpt`),Yn=/* @__PURE__ */ I({access:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),refresh:(/* @__PURE__ */ F()).check(/* @__PURE__ */ N(1)),expires:/* @__PURE__ */ nt(),scopes:/* @__PURE__ */ ct(/* @__PURE__ */ F()),refreshAfter:/* @__PURE__ */ L(/* @__PURE__ */ nt())}),Xn=/* @__PURE__ */ I({version:/* @__PURE__ */ dt(1),activeId:/* @__PURE__ */ L(/* @__PURE__ */ F()),welcomed:/* @__PURE__ */ L(/* @__PURE__ */ it()),accounts:/* @__PURE__ */ ct(/* @__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(Yn),pending:/* @__PURE__ */ L(/* @__PURE__ */ I({tokens:Yn,idToken:/* @__PURE__ */ L(/* @__PURE__ */ F()),receivedAt:/* @__PURE__ */ nt()})),models:/* @__PURE__ */ L(/* @__PURE__ */ ct(/* @__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`),Xn.parse(t.payload))}async function Zn(){let t=m(`siwc`,`host-id`);return await c(u(t),{recursive:!0,mode:448}),d(t,async()=>{let n;try{n=(await l(t,`utf8`)).trim()}catch(e){if(e.code!==`ENOENT`)throw e;n=`urn:uuid:${r()}`,await f(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 Qn=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 h(`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 Gn(s,i),l.idToken){let t=await Un(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 In&&l)s.pending=l;else if(l||e instanceof Rn&&e.code!==void 0&&zn.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 $n(e,t){let n=ne(),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:_(void 0,`siwc`),modelErrors:/* @__PURE__ */ new Map,configuredMaxTokens:/* @__PURE__ */ new Map}]])}var er=class extends b{ctx;accounts;currentProfiles;options;constructor(e,t){let n={value:$n(e),stamp:``},r={profiles:()=>n.value,resolveApiKey:(e,n)=>t.accessToken(n.accountId),auth:{credentials:new x,authContext:te()},resolveAttachments:()=>e.get(`attachments`),resolveImageAccess:(t,n)=>g(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=$n(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)}};function tr(e){try{let t=new URL(e);if((t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password)return t.href}catch{}}function nr(e){return e.replace(/[\\[\]]/g,`\\$&`)}function rr(e){return e.replace(/</g,`%3C`).replace(/>/g,`%3E`)}function ir(e){let t=e.filter(e=>e.type===`web_search_call`);if(!t.some(e=>e.status===`completed`&&e.action.type===`search`))throw new S(`ChatGPT did not complete a web search.`,`SIWC_SEARCH_NOT_EXECUTED`);let n=/* @__PURE__ */ new Map,r=(e,t)=>{let r=tr(e);if(!r)return;let i=n.get(r);return n.set(r,{url:r,...i?.title||t?{title:i?.title||t}:{}}),r};for(let e of t)if(e.status===`completed`&&e.action.type===`search`)for(let t of e.action.sources??[])r(t.url);let i=[];for(let t of e)if(t.type===`message`)for(let e of t.content){if(e.type!==`output_text`)continue;let t=e.annotations.filter(e=>e.type===`url_citation`),n=``,a=0;for(let i of t.toSorted((e,t)=>e.start_index-t.start_index)){let t=r(i.url,i.title),{start_index:o,end_index:s}=i;if(!t||!Number.isInteger(o)||!Number.isInteger(s)||o<a||s<=o||s>e.text.length)continue;n+=e.text.slice(a,o);let c=e.text.slice(o,s),l=i.title&&/^(\[\d+\]|.*)$/u.test(c)?i.title:c;n+=`[${nr(l)}](<${rr(t)}>)`,a=s}i.push(n+e.text.slice(a))}return{...i.length?{content:i.join(`
16
16
 
17
- `)}:{},sources:[...n.values()],truncated:!1}}function ar(e,t,n={}){return{id:`siwc`,available:()=>t().trim().length>0,async search(r,i){let a=AbortSignal.timeout(n.timeoutMs??6e4),o=i?AbortSignal.any([i,a]):a,s,c,l,u=(e,t)=>typeof e==`string`&&t.test(e)&&(!l||!e.includes(l))?e:void 0,d=(e,t=c,n=`ChatGPT web search failed.`)=>{let r=u(e,/^[A-Za-z][A-Za-z0-9_]{0,99}$/)??`WEB_PROVIDER_ERROR`;return new S(n,r,{cause:{...t===void 0?{}:{status:t},code:r,...s?{requestId:s}:{}}})};try{o.throwIfAborted();let i=t();if(!i.trim())throw new S(`Select a ChatGPT search model.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);let a=await e.read();o.throwIfAborted();let f=a.accounts.find(e=>e.id===a.activeId);if(!f?.tokens)throw new S(`Continue with ChatGPT using /chatgpt login.`,`MISSING_CREDENTIAL`);if(!f.models?.some(e=>e.id===i))throw new S(`The selected search model is not available for this ChatGPT account.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);l=await e.accessToken(f.id),o.throwIfAborted();let{data:p,request_id:m,response:h}=await new re({apiKey:l,baseURL:`https://api.openai.com/v1`,organization:null,project:null,maxRetries:0,fetch:n.fetch}).responses.create({model:i,store:!1,stream:!0,input:[{role:`user`,content:r.query}],tools:[{type:`web_search`}],tool_choice:`required`,include:[`web_search_call.action.sources`]},{signal:o}).withResponse();s=u(m,/^[A-Za-z0-9_-]{1,200}$/),c=h.status;let g,_=/* @__PURE__ */ new Map;for await(let e of p){if(o.throwIfAborted(),e.type===`error`)throw d(e.code);if(e.type===`response.failed`)throw d(e.response.error?.code);if(e.type===`response.incomplete`)throw d(`SIWC_SEARCH_INCOMPLETE`);if(e.type===`response.output_item.done`&&_.set(e.output_index,e.item),e.type===`response.completed`){if(e.response.status!==`completed`)throw d(`SIWC_SEARCH_INCOMPLETE`);g=e.response}}if(o.throwIfAborted(),!g)throw d(`SIWC_SEARCH_INCOMPLETE`);return ir(g.output.length?g.output:[..._].sort(([e],[t])=>e-t).map(([,e])=>e))}catch(e){throw o.aborted?d(i?.aborted?`WEB_ABORTED`:`WEB_TIMEOUT`,c,i?.aborted?`ChatGPT web search was cancelled.`:`ChatGPT web search timed out.`):e instanceof S?e:e instanceof re.APIError?(s=u(e.requestID,/^[A-Za-z0-9_-]{1,200}$/)??s,d(e.code,e.status)):d(e instanceof Error&&`code`in e?e.code:void 0)}}}}function or(e,t){e.connection.fetch.register({path:`/api/siwc/status`,methods:[`POST`],requestBody:`buffered`,async fetch(e){if(e.headers.get(`content-type`)?.split(`;`,1)[0]?.trim()!==`application/json`)return new Response(`Expected application/json`,{status:415});let n;try{n=await e.json()}catch{return new Response(`Invalid JSON`,{status:400})}let r=ie.safeParse(n);if(!r.success||r.data.method!==`siwc/status`)return new Response(`Invalid SIWC request`,{status:400});let{rpcId:i,payload:a}=r.data;if(!a||typeof a!=`object`||Array.isArray(a)||Object.keys(a).length!==0)return Response.json({type:`server-response`,rpcId:i,result:{ok:!1,error:{code:`invalid-input`,message:`SIWC status takes no parameters.`,details:{}}}});e.signal.throwIfAborted();let o=await t.read();e.signal.throwIfAborted();let s=o.accounts.find(e=>e.id===o.activeId&&e.tokens),c={...s?{account:{id:s.id,label:`${s.email??`ChatGPT account`} (${s.id.slice(0,8)})`}}:{},models:s?.models?.map(({id:e,name:t})=>({id:e,name:t}))??[],usageUrl:X};return Response.json({type:`server-response`,rpcId:i,result:{ok:!0,value:c}},{headers:{"cache-control":`no-store`}})}})}const sr=`siwc`,cr=[`credentials`,`authorization`,`llm`],lr=s.object({searchModel:s.string().default(``).volatile()}),ur=[`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`],dr=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;async function fr(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 qn(i)}catch(t){if(!(t instanceof Ln)&&!(t instanceof Rn)&&!(t instanceof In))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 pr(t,n){let s=i();ur.includes(s)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,ur.join(`, `),s);let c=new Qn(t.credentials);await fr(t,c);let l=new er(t,c);t.llm.registerAdapter([`openai`],l),t.inject([`web`],e=>{e.web.registerSearchProvider(ar(c,()=>n.searchModel.get()))}),t.inject([`connection`],e=>or(e,c)),t.inject([`settings`],e=>{e.effect(()=>e.settings.configure({auto:!1},t.fiber))});async function u(t){let n=await c.read(),i=n.accounts.map(e=>({id:e.id,label:dr(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 s=o??{id:r(),clientId:`dynamic_agent_client`};if(t.method===`oauth`){let e=await Jn(t,await Zn(),s,async e=>{t.signal.throwIfAborted(),s.clientId=e,await c.change(t=>{let n=t.accounts.find(e=>e.id===s.id);n?n.clientId=e:t.accounts.push({...s,clientId:e})})});Object.assign(s,e)}e.ok(s.tokens,`This account is signed out. Reconnect with /chatgpt login.`);let u=await qn(t.method===`oauth`?s.tokens.access:await c.accessToken(s.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 c.change(n=>{t.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===s.id);e.ok(r,`ChatGPT registration was removed during sign-in. Please retry.`),t.method===`oauth`&&(Object.assign(r,s),delete r.pending),r.models=u,n.activeId=s.id,n.welcomed=!0}),await l.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:u}),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 c.change(async t=>{let n=t.accounts.find(e=>e.id===t.activeId);if(n?.tokens||n?.pending)try{await Kn(n)}catch{e=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete t.activeId}),await l.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 c.read(),t=e.accounts.find(t=>t.id===e.activeId);return{kind:`success`,text:`${t?.tokens?`Using ChatGPT plan: ${dr(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 s;return(await e.authorization.begin({key:Q,method:i===`login`?`oauth`:`select`,signal:r,interaction:{notify(e){s=e},async prompt(n){if(n.kind!==`select`)throw Error(`Unsupported authorization prompt`);let i=s;s=void 0;let c=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}),l=n.options.find(e=>e.label===c.answers[0]?.selected[0]);if(!l)throw new a;return l.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{lr as Config,pr as apply,cr as inject,sr as name};
17
+ `)}:{},sources:[...n.values()],truncated:!1}}function ar(e,t,n={}){return{id:`siwc`,available:()=>t().trim().length>0,async search(r,i){let a=AbortSignal.timeout(n.timeoutMs??6e4),o=i?AbortSignal.any([i,a]):a,s,c,l,u=(e,t)=>typeof e==`string`&&t.test(e)&&(!l||!e.includes(l))?e:void 0,d=(e,t=c,n=`ChatGPT web search failed.`)=>{let r=u(e,/^[A-Za-z][A-Za-z0-9_]{0,99}$/)??`WEB_PROVIDER_ERROR`;return new S(n,r,{cause:{...t===void 0?{}:{status:t},code:r,...s?{requestId:s}:{}}})};try{o.throwIfAborted();let i=t();if(!i.trim())throw new S(`Select a ChatGPT search model.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);let a=await e.read();o.throwIfAborted();let f=a.accounts.find(e=>e.id===a.activeId);if(!f?.tokens)throw new S(`Continue with ChatGPT using /chatgpt login.`,`MISSING_CREDENTIAL`);if(!f.models?.some(e=>e.id===i))throw new S(`The selected search model is not available for this ChatGPT account.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);l=await e.accessToken(f.id),o.throwIfAborted();let{data:p,request_id:m,response:h}=await new re({apiKey:l,baseURL:`https://api.openai.com/v1`,organization:null,project:null,maxRetries:0,fetch:n.fetch}).responses.create({model:i,store:!1,stream:!0,input:[{role:`user`,content:r.query}],tools:[{type:`web_search`}],tool_choice:`required`,include:[`web_search_call.action.sources`]},{signal:o}).withResponse();s=u(m,/^[A-Za-z0-9_-]{1,200}$/),c=h.status;let g,_=/* @__PURE__ */ new Map;for await(let e of p){if(o.throwIfAborted(),e.type===`error`)throw d(e.code);if(e.type===`response.failed`)throw d(e.response.error?.code);if(e.type===`response.incomplete`)throw d(`SIWC_SEARCH_INCOMPLETE`);if(e.type===`response.output_item.done`&&_.set(e.output_index,e.item),e.type===`response.completed`){if(e.response.status!==`completed`)throw d(`SIWC_SEARCH_INCOMPLETE`);g=e.response}}if(o.throwIfAborted(),!g)throw d(`SIWC_SEARCH_INCOMPLETE`);return ir(g.output.length?g.output:[..._].sort(([e],[t])=>e-t).map(([,e])=>e))}catch(e){throw o.aborted?d(i?.aborted?`WEB_ABORTED`:`WEB_TIMEOUT`,c,i?.aborted?`ChatGPT web search was cancelled.`:`ChatGPT web search timed out.`):e instanceof S?e:e instanceof re.APIError?(s=u(e.requestID,/^[A-Za-z0-9_-]{1,200}$/)??s,d(e.code,e.status)):d(e instanceof Error&&`code`in e?e.code:void 0)}}}}function or(e,t){e.connection.fetch.register({path:`/api/siwc/status`,methods:[`POST`],requestBody:`buffered`,async fetch(e){if(e.headers.get(`content-type`)?.split(`;`,1)[0]?.trim()!==`application/json`)return new Response(`Expected application/json`,{status:415});let n;try{n=await e.json()}catch{return new Response(`Invalid JSON`,{status:400})}let r=ie.safeParse(n);if(!r.success||r.data.method!==`siwc/status`)return new Response(`Invalid SIWC request`,{status:400});let{rpcId:i,payload:a}=r.data;if(!a||typeof a!=`object`||Array.isArray(a)||Object.keys(a).length!==0)return Response.json({type:`server-response`,rpcId:i,result:{ok:!1,error:{code:`invalid-input`,message:`SIWC status takes no parameters.`,details:{}}}});e.signal.throwIfAborted();let o=await t.read();e.signal.throwIfAborted();let s=o.accounts.find(e=>e.id===o.activeId&&e.tokens),c={...s?{account:{id:s.id,label:`${s.email??`ChatGPT account`} (${s.id.slice(0,8)})`}}:{},models:s?.models?.map(({id:e,name:t})=>({id:e,name:t}))??[],usageUrl:X};return Response.json({type:`server-response`,rpcId:i,result:{ok:!0,value:c}},{headers:{"cache-control":`no-store`}})}})}const sr=`siwc`,cr=[`credentials`,`authorization`,`llm`],lr=s.object({searchModel:s.string().default(``).volatile()}),ur=[`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`,`0.2.2-alpha.2`,`0.2.2-alpha.3`],dr=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;async function fr(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 qn(i)}catch(t){if(!(t instanceof Ln)&&!(t instanceof Rn)&&!(t instanceof In))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 pr(t,n){let s=i();ur.includes(s)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,ur.join(`, `),s);let c=new Qn(t.credentials);await fr(t,c);let l=new er(t,c);t.llm.registerAdapter([`openai`],l),t.inject([`web`],e=>{e.web.registerSearchProvider(ar(c,()=>n.searchModel.get()))}),t.inject([`connection`],e=>or(e,c)),t.inject([`settings`],e=>{e.effect(()=>e.settings.configure({auto:!1},t.fiber))});async function u(t){let n=await c.read(),i=n.accounts.map(e=>({id:e.id,label:dr(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 s=o??{id:r(),clientId:`dynamic_agent_client`};if(t.method===`oauth`){let e=await Jn(t,await Zn(),s,async e=>{t.signal.throwIfAborted(),s.clientId=e,await c.change(t=>{let n=t.accounts.find(e=>e.id===s.id);n?n.clientId=e:t.accounts.push({...s,clientId:e})})});Object.assign(s,e)}e.ok(s.tokens,`This account is signed out. Reconnect with /chatgpt login.`);let u=await qn(t.method===`oauth`?s.tokens.access:await c.accessToken(s.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 c.change(n=>{t.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===s.id);e.ok(r,`ChatGPT registration was removed during sign-in. Please retry.`),t.method===`oauth`&&(Object.assign(r,s),delete r.pending),r.models=u,n.activeId=s.id,n.welcomed=!0}),await l.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:u}),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 c.change(async t=>{let n=t.accounts.find(e=>e.id===t.activeId);if(n?.tokens||n?.pending)try{await Kn(n)}catch{e=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete t.activeId}),await l.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 c.read(),t=e.accounts.find(t=>t.id===e.activeId);return{kind:`success`,text:`${t?.tokens?`Using ChatGPT plan: ${dr(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 s;return(await e.authorization.begin({key:Q,method:i===`login`?`oauth`:`select`,signal:r,interaction:{notify(e){s=e},async prompt(n){if(n.kind!==`select`)throw Error(`Unsupported authorization prompt`);let i=s;s=void 0;let c=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}),l=n.options.find(e=>e.label===c.answers[0]?.selected[0]);if(!l)throw new a;return l.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{lr as Config,pr as apply,cr as inject,sr as name};
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "dsh-siwc",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Sign in with ChatGPT for DeepSeek Harness",
5
5
  "keywords": [
6
6
  "dsh",
7
7
  "deepseek-harness"
8
8
  ],
9
- "homepage": "https://github.com/ph0ryn/dsh-siwc#readme",
9
+ "homepage": "https://github.com/ph0ryn/dsh-plugins#readme",
10
10
  "bugs": {
11
- "url": "https://github.com/ph0ryn/dsh-siwc/issues"
11
+ "url": "https://github.com/ph0ryn/dsh-plugins/issues"
12
12
  },
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "git+https://github.com/ph0ryn/dsh-siwc.git"
15
+ "url": "git+https://github.com/ph0ryn/dsh-plugins.git"
16
16
  },
17
17
  "license": "MIT",
18
18
  "author": "ph0ryn",