dsh-siwc 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -4
- package/dist/client/client.cjs +11 -0
- package/dist/server/index.js +17 -0
- package/package.json +22 -6
- package/dist/index.js +0 -15
package/README.md
CHANGED
|
@@ -4,6 +4,8 @@ Use your ChatGPT plan in [DeepSeek Harness](https://github.com/deepseek-ai/deeps
|
|
|
4
4
|
|
|
5
5
|
| Supported DSH versions | Verification |
|
|
6
6
|
| ---------------------- | ------------------ |
|
|
7
|
+
| 0.2.2-alpha.3 | Verified |
|
|
8
|
+
| 0.2.2-alpha.2 | Verified |
|
|
7
9
|
| 0.2.1-rc.2 | Verified |
|
|
8
10
|
| 0.2.1-rc.1 | Source review only |
|
|
9
11
|
| 0.2.1-alpha.2–alpha.5 | Source review only |
|
|
@@ -35,7 +37,7 @@ Build a package and install it into your Web profile:
|
|
|
35
37
|
|
|
36
38
|
```sh
|
|
37
39
|
pnpm pack
|
|
38
|
-
dsh plugin --profile web add ./dsh-siwc-0.1.
|
|
40
|
+
dsh plugin --profile web add ./dsh-siwc-0.1.3.tgz --ignore-scripts
|
|
39
41
|
```
|
|
40
42
|
|
|
41
43
|
## Use
|
|
@@ -54,7 +56,18 @@ On startup, the plugin refreshes the signed-in account's model list automaticall
|
|
|
54
56
|
|
|
55
57
|
Tokens use DSH's credential store; the default local store is not encrypted by an OS keychain.
|
|
56
58
|
Manage usage and app access in [ChatGPT settings](https://chatgpt.com/settings/usage).
|
|
57
|
-
|
|
59
|
+
|
|
60
|
+
## Web search
|
|
61
|
+
|
|
62
|
+
1. Sign in with `/chatgpt login`.
|
|
63
|
+
2. Open **Settings → SIWC**, refresh the account status, and choose a **Search model**.
|
|
64
|
+
3. Select **Use SIWC for web search**.
|
|
65
|
+
|
|
66
|
+
Search uses your ChatGPT plan through the public Responses API, including for conversations with other models. `web_fetch` is unchanged.
|
|
67
|
+
|
|
68
|
+
The search model is separate from the conversation model and must support web search under your account's policy. After switching accounts, reselect it if unavailable. Errors do not trigger automatic retries or a switch to API-key billing.
|
|
69
|
+
|
|
70
|
+
**Restore deployment default** clears the search-provider override; DSH may then select a provider automatically.
|
|
58
71
|
|
|
59
72
|
## Development
|
|
60
73
|
|
|
@@ -65,7 +78,6 @@ pnpm format
|
|
|
65
78
|
pnpm lint
|
|
66
79
|
pnpm typecheck
|
|
67
80
|
pnpm test
|
|
68
|
-
pnpm build
|
|
69
81
|
```
|
|
70
82
|
|
|
71
|
-
Formatting, linting, and library builds use Vite+.
|
|
83
|
+
Formatting, linting, and library builds use Vite+. Behavioral tests live beside the source files.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({id:"dsh-siwc",factory:(require)=>{var module={exports:{}};var exports=module.exports;
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react");function t({form:t,web:n,loadStatus:r,subscribeReset:i}){let a=(0,e.useSyncExternalStore)(t.subscribe.bind(t),t.getSnapshot.bind(t)),o=(0,e.useSyncExternalStore)(n.subscribe.bind(n),n.getSnapshot.bind(n)),[s,c]=(0,e.useState)(),[l,u]=(0,e.useState)(0),[d,f]=(0,e.useState)(!0),[p,m]=(0,e.useState)(!1),[h,g]=(0,e.useState)(``),_=(0,e.useId)();(0,e.useEffect)(()=>{let e=new AbortController;return f(!0),c(void 0),g(``),r(e.signal).then(t=>{e.signal.aborted||c(t)}).catch(()=>{e.signal.aborted||g(`Could not load your ChatGPT account. Refresh to try again.`)}).finally(()=>{e.signal.aborted||f(!1)}),()=>e.abort()},[r,l]),(0,e.useEffect)(()=>i?.(()=>u(e=>e+1)),[i]);let v=a.value?.searchModel??``,y=s?.models.some(e=>e.id===v)??!1,b=o.value?.searchProvider===`siwc`,x=a.status===`ready`&&a.writable&&!p&&!d,S=o.status===`ready`&&o.writable&&x&&y&&!!s?.account;async function C(e){g(``),m(!0);try{await e()||g(`Settings changed or could not be saved. Review the current values and try again.`)}catch{g(`Could not confirm the save. Refresh to check the current settings before trying again.`)}finally{m(!1)}}return(0,e.createElement)(`section`,{className:`siwc-settings`,"aria-labelledby":`${_}-title`,"aria-busy":d||p},(0,e.createElement)(`h2`,{id:`${_}-title`},`SIWC`),p&&(0,e.createElement)(`p`,{role:`status`},`Saving…`),h&&(0,e.createElement)(`p`,{role:`alert`},h),(0,e.createElement)(`div`,{className:`siwc-group`},(0,e.createElement)(`h3`,null,`ChatGPT account`),!d&&s&&!s.account&&(0,e.createElement)(`p`,{className:`siwc-hint`},`Sign in with /chatgpt login, or switch with /chatgpt accounts. Then refresh.`),(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},d?`Loading account…`:s?s.account?.label??`Not signed in`:`Account status unavailable`),(0,e.createElement)(`div`,{className:`siwc-actions`},(0,e.createElement)(`button`,{type:`button`,disabled:d||p,onClick:()=>u(e=>e+1)},`Refresh account`),s&&(0,e.createElement)(`a`,{href:s.usageUrl,target:`_blank`,rel:`noopener noreferrer`},`Manage ChatGPT usage`))),(0,e.createElement)(`div`,{className:`siwc-group`},(0,e.createElement)(`label`,{htmlFor:`${_}-model`},`Search model`),(0,e.createElement)(`p`,{id:`${_}-model-hint`,className:`siwc-hint`},`Separate from the conversation model.`),v&&!y&&s?.account&&(0,e.createElement)(`p`,{id:`${_}-model-status`,className:`siwc-state`,role:`status`},`The saved model is unavailable for this account. Select a search model to continue.`),!a.writable&&a.status===`ready`&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},`Settings are read-only.`),(0,e.createElement)(`select`,{id:`${_}-model`,value:y?v:``,disabled:!x||!s?.models.length,"aria-describedby":v&&!y&&s?.account?`${_}-model-hint ${_}-model-status`:`${_}-model-hint`,onChange:e=>{let n=e.currentTarget.value;return C(()=>n?t.set(`searchModel`,n):t.unset(`searchModel`))}},(0,e.createElement)(`option`,{value:``},`Select a search model`),...(s?.models??[]).map(t=>(0,e.createElement)(`option`,{key:t.id,value:t.id},t.name)))),(0,e.createElement)(`div`,{className:`siwc-group`},(0,e.createElement)(`h3`,null,`Web search provider`),o.status===`ready`&&o.value?.searchProvider===void 0&&(0,e.createElement)(`p`,{className:`siwc-hint`},`The default may select SIWC automatically. Choose a provider to pin it.`),o.status!==`ready`&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},`Web search settings are unavailable.`),o.status===`ready`&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},b?`ChatGPT plan`:o.value?.searchProvider??`Deployment default`),(0,e.createElement)(`div`,{className:`siwc-actions`},!b&&(0,e.createElement)(`button`,{type:`button`,"data-action":`use-siwc`,disabled:!S,onClick:()=>C(()=>n.set(`searchProvider`,`siwc`))},`Use SIWC for web search`),b&&(0,e.createElement)(`button`,{type:`button`,disabled:p||!o.writable,onClick:()=>C(()=>n.unset(`searchProvider`))},`Restore deployment default`))))}const n=[`slots`,`configForms`,`connection`];function r(e){if(!e||typeof e!=`object`)throw Error(`Invalid SIWC status`);let t=e;if(t.usageUrl!==`https://chatgpt.com/settings/usage`||!Array.isArray(t.models)||t.models.some(e=>!e||typeof e.id!=`string`||typeof e.name!=`string`)||t.account!==void 0&&(!t.account||typeof t.account.id!=`string`||typeof t.account.label!=`string`))throw Error(`Invalid SIWC status`);return t}function i(n){let i=n.get(`connection`).rpc,a=n.configForms.get(`siwc`),o=n.configForms.get(`web`),s=async e=>{let t=await i.call(`/api`,`siwc/status`,{},e);if(!t.ok)throw Error(`Could not load SIWC status`);return r(t.value)},c=e=>n.on(`connection/reset`,e);n.effect(()=>{let e=document.createElement(`style`);return e.dataset.plugin=`dsh-siwc`,e.textContent=`
|
|
3
|
+
.siwc-settings{display:grid;min-width:0;max-width:640px;color:var(--dsw-alias-label-primary);font-size:13px;line-height:1.5}
|
|
4
|
+
.siwc-settings h2{font-size:18px;margin:0 0 4px}.siwc-settings h3,.siwc-settings p{margin:0}.siwc-settings h3,.siwc-settings label{font-size:13px;font-weight:600}
|
|
5
|
+
.siwc-settings .siwc-group{display:grid;gap:10px;min-width:0;padding-block:20px}.siwc-settings .siwc-group+.siwc-group{border-block-start:1px solid var(--dsw-alias-border-l4)}
|
|
6
|
+
.siwc-settings .siwc-hint{color:var(--dsw-alias-label-tertiary);font-size:12px}.siwc-settings .siwc-state{overflow-wrap:anywhere}.siwc-settings>.siwc-group:last-child{padding-block-end:0}
|
|
7
|
+
.siwc-settings select,.siwc-settings button{font:inherit;color:inherit;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l4);border-radius:8px;padding:8px 12px;min-height:36px}
|
|
8
|
+
.siwc-settings select{width:100%;min-width:0}.siwc-settings button{width:fit-content;max-width:100%;cursor:pointer}.siwc-settings button:disabled,.siwc-settings select:disabled{opacity:.5;cursor:default}
|
|
9
|
+
.siwc-settings :is(button,select,a):focus-visible{outline:2px solid var(--dsw-alias-link);outline-offset:3px}.siwc-settings a{color:var(--dsw-alias-link);overflow-wrap:anywhere}.siwc-settings .siwc-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.siwc-settings [role=alert]{color:var(--dsw-alias-label-primary)}
|
|
10
|
+
`,document.head.appendChild(e),()=>e.remove()}),n.effect(()=>n.configForms.whileServed([`siwc`],()=>n.slots.inject(`settings.section`,()=>n.slots.register({name:`settings.section`,id:`siwc`,order:35,label:()=>`SIWC`},()=>(0,e.createElement)(t,{form:a,web:o,loadStatus:s,subscribeReset:c})))))}exports.apply=i,exports.inject=n;
|
|
11
|
+
return module.exports;}});
|
|
@@ -0,0 +1,17 @@
|
|
|
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 s from"@deepseek-ai/schemastery";import{mkdir as c,readFile as l}from"node:fs/promises";import{dirname as u}from"node:path";import{withFileLock as d,writeFileAtomic as f}from"@deepseek-ai/dsh-atomic-write";import{credentialKey as p}from"@deepseek-ai/dsh-credentials";import{dshHomePath as m}from"@deepseek-ai/dsh-home-paths";import{LlmError as h,resolveImageAttachmentAccess as g,resolveRetryPolicy as _}from"@deepseek-ai/dsh-llm";import{once as ee}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 te}from"@earendil-works/pi-ai";import{openaiProvider as ne}from"@earendil-works/pi-ai/providers/openai";import{WebError as S}from"@deepseek-ai/dsh-web";import re from"openai";import{clientRequestSchema as ie}from"@deepseek-ai/dsh-client-connection";var ae;/* @__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.`)}};(ae=globalThis).__zod_globalConfig??(ae.__zod_globalConfig={});const oe=globalThis.__zod_globalConfig;function T(e){return e&&Object.assign(oe,e),oe}function se(e,t=`|`){return e.map(e=>_e(e)).join(t)}function ce(e,t){return typeof t==`bigint`?t.toString():t}function le(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ue(e){return e==null}function de(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}const fe=/* @__PURE__*/ Symbol(`evaluating`);function E(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==fe)return r===void 0&&(r=fe,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const pe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function he(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ge(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 _e(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function ve(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 ye(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 be(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 xe(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Se(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 Ce=(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,ce,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},we=/* @__PURE__ */ C(`$ZodError`,Ce),j=/* @__PURE__ */ C(`$ZodError`,Ce,{Parent:Error}),Te=/* @__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 pe(t,i?.callee),t}return o.value})(j),Ee=/* @__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 pe(t,i?.callee),t}return o.value})(j),De=/* @__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??we)(a.issues.map(e=>A(e,i,T())))}:{success:!0,data:a.value}})(j),Oe=/* @__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),ke=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ae=/^-?\d+(?:\.\d+)?$/,je=/^(?:true|false)$/i,Me=/*@__PURE__*/ C(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ne=/*@__PURE__*/ C(`$ZodCheckMinLength`,(e,t)=>{var n;Me.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ue(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=xe(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Pe={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=Pe;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(ye(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=De(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Oe(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Fe=/*@__PURE__*/ C(`$ZodString`,(e,t)=>{M.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ke(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}}),Ie=/*@__PURE__*/ C(`$ZodNumber`,(e,t)=>{M.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ae,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}}),Le=/*@__PURE__*/ C(`$ZodBoolean`,(e,t)=>{M.init(e,t),e._zod.pattern=je,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}}),Re=/*@__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 ze(e,t,n){e.issues.length&&t.issues.push(...be(n,e.issues)),t.value[n]=e.value}const Be=/*@__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=>ze(t,n,e))):ze(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Ve(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...be(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 He(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=ve(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ue(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=>Ve(e,n,i,t,u,d))):Ve(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 We=/*@__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=le(()=>He(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=me,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=>Ve(n,t,e,s,r,i))):Ve(a,t,e,s,r,i)}return i?Ue(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ge=/*@__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`?he(e):e?he(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 Ke(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const qe=/*@__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(`^(${de(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=>Ke(e,r)):Ke(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Je=()=>{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=Se(e.input);return`Invalid input: expected ${t}, received ${r[n]??n}`}case`invalid_value`:return e.values.length===1?`Invalid input: expected ${_e(e.values[0])}`:`Invalid option: expected one of ${se(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`:``}: ${se(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 Ye(){return{localeError:Je()}}// @__NO_SIDE_EFFECTS__
|
|
3
|
+
function Xe(e,t){return new e({type:`string`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
4
|
+
function Ze(e,t){return new e({type:`number`,checks:[],...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
5
|
+
function Qe(e,t){return new e({type:`boolean`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
6
|
+
function $e(e,t){return new e({type:`never`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
7
|
+
function N(e,t){return new Ne({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)=>Te(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>De(e,t,n),e.parseAsync=async(t,n)=>Ee(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Oe(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)=>ge(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),et=/*@__PURE__*/ C(`ZodMiniString`,(e,t)=>{Fe.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
8
|
+
function F(e){return/* @__PURE__ */ Xe(et,e)}const tt=/*@__PURE__*/ C(`ZodMiniNumber`,(e,t)=>{Ie.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
9
|
+
function nt(e){return/* @__PURE__ */ Ze(tt,e)}const rt=/*@__PURE__*/ C(`ZodMiniBoolean`,(e,t)=>{Le.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
10
|
+
function it(e){return/* @__PURE__ */ Qe(rt,e)}const at=/*@__PURE__*/ C(`ZodMiniNever`,(e,t)=>{Re.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
11
|
+
function ot(e){return/* @__PURE__ */ $e(at,e)}const st=/*@__PURE__*/ C(`ZodMiniArray`,(e,t)=>{Be.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
12
|
+
function ct(e,t){return new st({type:`array`,element:e,...D(t)})}const lt=/*@__PURE__*/ C(`ZodMiniObject`,(e,t)=>{We.init(e,t),P.init(e,t),E(e,`shape`,()=>t.shape)});// @__NO_SIDE_EFFECTS__
|
|
13
|
+
function I(e,t){return new lt({type:`object`,shape:e,catchall:/* @__PURE__ */ ot(),...D(t)})}const ut=/*@__PURE__*/ C(`ZodMiniLiteral`,(e,t)=>{Ge.init(e,t),P.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
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
|
+
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
|
+
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-siwc",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Sign in with ChatGPT for DeepSeek Harness",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -19,16 +19,21 @@
|
|
|
19
19
|
"type": "module",
|
|
20
20
|
"exports": {
|
|
21
21
|
".": {
|
|
22
|
-
"import": "./dist/index.js"
|
|
22
|
+
"import": "./dist/server/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./client": {
|
|
25
|
+
"default": "./dist/client/client.cjs"
|
|
23
26
|
}
|
|
24
27
|
},
|
|
25
|
-
"main": "./dist/index.js",
|
|
28
|
+
"main": "./dist/server/index.js",
|
|
26
29
|
"files": [
|
|
27
|
-
"dist",
|
|
30
|
+
"dist/client",
|
|
31
|
+
"dist/server",
|
|
28
32
|
"cordis.patch.yml"
|
|
29
33
|
],
|
|
30
34
|
"dependencies": {
|
|
31
|
-
"@earendil-works/pi-ai": "^1.1.0"
|
|
35
|
+
"@earendil-works/pi-ai": "^1.1.0",
|
|
36
|
+
"openai": "^7.19.0"
|
|
32
37
|
},
|
|
33
38
|
"peerDependencies": {
|
|
34
39
|
"@deepseek-ai/cordis": "^4.0.5-alpha.1",
|
|
@@ -36,18 +41,29 @@
|
|
|
36
41
|
"@deepseek-ai/dsh-atomic-write": "^0.2.1-alpha.2",
|
|
37
42
|
"@deepseek-ai/dsh-attachment": "^0.2.1-alpha.2",
|
|
38
43
|
"@deepseek-ai/dsh-authorization": "^0.2.1-alpha.2",
|
|
44
|
+
"@deepseek-ai/dsh-client-connection": "^0.2.1-alpha.2",
|
|
39
45
|
"@deepseek-ai/dsh-commands": "^0.2.1-alpha.2",
|
|
40
46
|
"@deepseek-ai/dsh-credentials": "^0.2.1-alpha.2",
|
|
41
47
|
"@deepseek-ai/dsh-fs": "^0.2.1-alpha.2",
|
|
42
48
|
"@deepseek-ai/dsh-home-paths": "^0.2.1-alpha.2",
|
|
43
49
|
"@deepseek-ai/dsh-llm": "^0.2.1-alpha.2",
|
|
44
50
|
"@deepseek-ai/dsh-llm-pi-ai": "^0.2.1-alpha.2",
|
|
45
|
-
"@deepseek-ai/dsh-
|
|
51
|
+
"@deepseek-ai/dsh-settings": "^0.2.1-alpha.2",
|
|
52
|
+
"@deepseek-ai/dsh-user-questions": "^0.2.1-alpha.2",
|
|
53
|
+
"@deepseek-ai/dsh-web": "^0.2.1-alpha.2",
|
|
54
|
+
"@deepseek-ai/schemastery": "^3.18.5"
|
|
46
55
|
},
|
|
47
56
|
"engines": {
|
|
48
57
|
"node": ">=22.19.0"
|
|
49
58
|
},
|
|
50
59
|
"dsh": {
|
|
60
|
+
"client": {
|
|
61
|
+
"platform": "web",
|
|
62
|
+
"inject": [
|
|
63
|
+
"@deepseek-ai/dsh-client-ui-settings",
|
|
64
|
+
"@deepseek-ai/dsh-client-connection"
|
|
65
|
+
]
|
|
66
|
+
},
|
|
51
67
|
"bundle": {
|
|
52
68
|
"patch": "./cordis.patch.yml"
|
|
53
69
|
}
|
package/dist/index.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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 ee,defaultProviderAuthContext as x}from"@earendil-works/pi-ai";import{openaiProvider as S}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),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 qe(e,t){return new e({type:`string`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
4
|
-
function Je(e,t){return new e({type:`number`,checks:[],...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
5
|
-
function Ye(e,t){return new e({type:`boolean`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
6
|
-
function Xe(e,t){return new e({type:`never`,...D(t)})}// @__NO_SIDE_EFFECTS__
|
|
7
|
-
function M(e,t){return new Ae({check:`min_length`,...D(t),minimum:e})}const N=/*@__PURE__*/ C(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);j.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Se(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>we(e,t,n),e.parseAsync=async(t,n)=>Ce(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Te(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)}),Ze=/*@__PURE__*/ C(`ZodMiniString`,(e,t)=>{Me.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
8
|
-
function P(e){return/* @__PURE__ */ qe(Ze,e)}const Qe=/*@__PURE__*/ C(`ZodMiniNumber`,(e,t)=>{Ne.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
9
|
-
function $e(e){return/* @__PURE__ */ Je(Qe,e)}const et=/*@__PURE__*/ C(`ZodMiniBoolean`,(e,t)=>{Pe.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
10
|
-
function tt(e){return/* @__PURE__ */ Ye(et,e)}const nt=/*@__PURE__*/ C(`ZodMiniNever`,(e,t)=>{Fe.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
11
|
-
function rt(e){return/* @__PURE__ */ Xe(nt,e)}const it=/*@__PURE__*/ C(`ZodMiniArray`,(e,t)=>{Le.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
12
|
-
function at(e,t){return new it({type:`array`,element:e,...D(t)})}const ot=/*@__PURE__*/ C(`ZodMiniObject`,(e,t)=>{Ve.init(e,t),N.init(e,t),E(e,`shape`,()=>t.shape)});// @__NO_SIDE_EFFECTS__
|
|
13
|
-
function F(e,t){return new ot({type:`object`,shape:e,catchall:/* @__PURE__ */ rt(),...D(t)})}const st=/*@__PURE__*/ C(`ZodMiniLiteral`,(e,t)=>{He.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
14
|
-
function ct(e,t){return new st({type:`literal`,values:Array.isArray(e)?e:[e],...D(t)})}const lt=/*@__PURE__*/ C(`ZodMiniOptional`,(e,t)=>{We.init(e,t),N.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
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};
|