dsh-siwc 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,15 +2,15 @@
2
2
 
3
3
  Use your ChatGPT plan in [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness).
4
4
 
5
- | Supported DSH versions | Verification |
6
- | ---------------------- | ------------------ |
7
- | 0.2.2-alpha.3 | Verified |
8
- | 0.2.2-alpha.2 | Verified |
9
- | 0.2.1-rc.2 | Verified |
10
- | 0.2.1-rc.1 | Source review only |
11
- | 0.2.1-alpha.2–alpha.5 | Source review only |
5
+ | Supported DSH versions | Verification |
6
+ | ---------------------- | ------------ |
7
+ | 0.2.2-rc.5 | Verified |
8
+ | 0.2.2-alpha.3 | Verified |
9
+ | 0.2.2-alpha.2 | Verified |
10
+ | 0.2.1-rc.2 | Verified |
12
11
 
13
- Use a browser on the same machine as DSH. Unlisted versions are unverified.
12
+ Use a browser on the same machine as DSH. The install check requires DSH 0.2.1-rc.2 or later;
13
+ unlisted versions are unverified.
14
14
 
15
15
  ## Install
16
16
 
@@ -37,37 +37,34 @@ Build this plugin and install it into your Web profile:
37
37
 
38
38
  ```sh
39
39
  pnpm --filter dsh-siwc pack --pack-destination ./artifacts
40
- dsh plugin --profile web add ./artifacts/dsh-siwc-0.1.4.tgz --ignore-scripts
40
+ dsh plugin --profile web add ./artifacts/dsh-siwc-0.1.6.tgz --ignore-scripts
41
41
  ```
42
42
 
43
43
  ## Use
44
44
 
45
- Run `/chatgpt login` in a chat, open **Continue with ChatGPT**, and finish signing in.
46
- Then select a model under **ChatGPT Subscription Plan**.
45
+ Open **Settings → SIWC**, choose **Add account…** in the account dropdown, and finish signing in
46
+ in your browser. Then choose a model under **ChatGPT Subscription Plan**.
47
47
 
48
- On startup, the plugin refreshes the signed-in account's model list automatically.
48
+ The SIWC settings page is the only account management surface. Use it to sign in, add or reconnect
49
+ an account, switch saved accounts, and sign out. Signing out removes local tokens but keeps saved
50
+ registrations so you can reconnect later.
49
51
 
50
- | Command | Action |
51
- | ------------------- | ----------------------------------------------------------------- |
52
- | `/chatgpt login` | Sign in again or add an account or workspace. |
53
- | `/chatgpt accounts` | Switch accounts and refresh available models. |
54
- | `/chatgpt status` | Show your connection and usage link. |
55
- | `/chatgpt logout` | Sign out and delete local tokens, keeping the saved registration. |
52
+ On startup, the plugin refreshes the signed-in account's model list automatically.
56
53
 
57
54
  Tokens use DSH's credential store; the default local store is not encrypted by an OS keychain.
58
55
  Manage usage and app access in [ChatGPT settings](https://chatgpt.com/settings/usage).
59
56
 
60
57
  ## Web search
61
58
 
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**.
59
+ 1. Open **Settings → SIWC** and sign in.
60
+ 2. Choose a **Search model**.
61
+ 3. Under **Web search**, select **ChatGPT plan**.
65
62
 
66
63
  Search uses your ChatGPT plan through the public Responses API, including for conversations with other models. `web_fetch` is unchanged.
67
64
 
68
65
  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
66
 
70
- **Restore deployment default** clears the search-provider override; DSH may then select a provider automatically.
67
+ **Deployment default** clears the search-provider override; DSH may then select a provider automatically.
71
68
 
72
69
  ## Development
73
70
 
@@ -1,11 +1,13 @@
1
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=`
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react");function t(){return(0,e.createElement)(`svg`,{viewBox:`0 0 24 24`,width:16,height:16,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0,focusable:!1},(0,e.createElement)(`path`,{d:`M20 11a8 8 0 1 0-2.34 5.66M20 4v7h-7`}))}function n({form:n,web:i,loadStatus:a,authorize:o,answer:s,cancel:c,logout:l,subscribeReset:u}){let d=(0,e.useSyncExternalStore)(n.subscribe.bind(n),n.getSnapshot.bind(n)),f=(0,e.useSyncExternalStore)(i.subscribe.bind(i),i.getSnapshot.bind(i)),[p,m]=(0,e.useState)(),[h,g]=(0,e.useState)(0),[_,v]=(0,e.useState)(!0),[y,b]=(0,e.useState)(!1),[x,S]=(0,e.useState)(``),[C,w]=(0,e.useState)(``),[T,E]=(0,e.useState)(!1),D=(0,e.useId)();(0,e.useEffect)(()=>{let e=new AbortController;return v(!0),S(``),a(e.signal).then(t=>{e.signal.aborted||m(t)}).catch(()=>{e.signal.aborted||S(`Could not load your ChatGPT account. Refresh to try again.`)}).finally(()=>{e.signal.aborted||v(!1)}),()=>e.abort()},[a,h]),(0,e.useEffect)(()=>u?.(()=>g(e=>e+1)),[u]),(0,e.useEffect)(()=>E(!1),[p?.account?.id]);let O=p?.attempt;(0,e.useEffect)(()=>{if(O?.phase!==`running`)return;let e=new AbortController,t,n=async()=>{try{let r=await a(e.signal);if(e.signal.aborted)return;m(r),S(e=>e===`Could not refresh sign-in status. Retrying…`?``:e),t=setTimeout(n,800)}catch{if(e.signal.aborted)return;S(`Could not refresh sign-in status. Retrying…`),t=setTimeout(n,1600)}};return t=setTimeout(n,800),()=>{clearTimeout(t),e.abort()}},[O?.id,O?.phase,a,h]);let k=d.value?.searchModel??``,A=p?.models.some(e=>e.id===k)??!1,j=f.value?.searchProvider===`siwc`,M=O?.phase===`running`,N=d.status===`ready`&&d.writable&&!y&&!_&&!M,P=f.status===`ready`&&f.writable&&N&&A&&!!p?.account,F=_||y||M;async function I(e){S(``),w(``),b(!0);try{let t=await e();m(t.status),t.message&&w(t.message)}catch(e){S(e instanceof Error?e.message:`Could not complete the account action.`)}finally{b(!1)}}async function L(e){S(``),b(!0);try{await e()||S(`Settings changed or could not be saved. Review the current values and try again.`)}catch{S(`Could not confirm the save. Refresh to check the current settings before trying again.`)}finally{b(!1)}}return(0,e.createElement)(`section`,{className:`siwc-settings`,"aria-labelledby":`${D}-title`,"aria-busy":_||y},(0,e.createElement)(`h2`,{id:`${D}-title`},`SIWC`),y&&(0,e.createElement)(`p`,{role:`status`},`Saving…`),x&&(0,e.createElement)(`p`,{role:`alert`},x),C&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},C),(0,e.createElement)(`div`,{className:`siwc-group`},(0,e.createElement)(`h3`,null,`ChatGPT account`),!_&&p&&!p.account&&(0,e.createElement)(`p`,{className:`siwc-hint`},`Choose a saved account to reconnect, or Add account…`),(0,e.createElement)(`div`,{className:`siwc-account-line`},(0,e.createElement)(`select`,{id:`${D}-account`,"aria-label":`ChatGPT account`,value:p?.account?.id??``,disabled:F||!p,onChange:e=>{let t=e.currentTarget.value;if(t===`new`)return I(()=>o(`oauth`,`new`));let n=p?.accounts.find(e=>e.id===t);if(n)return I(()=>o(n.signedIn?`select`:`oauth`,n.id))}},(0,e.createElement)(`option`,{value:``,disabled:!0},_?`Loading account…`:p?`Not signed in`:`Account status unavailable`),...(p?.accounts??[]).map(t=>(0,e.createElement)(`option`,{key:t.id,value:t.id},`${t.label} — ${t.active?`Active`:t.signedIn?`Signed in`:`Signed out`}`)),(0,e.createElement)(`option`,{value:`new`},`Add account…`)),(0,e.createElement)(`button`,{type:`button`,className:`siwc-icon-button`,"aria-label":`Refresh account`,title:`Refresh account`,"data-action":`refresh-account`,disabled:_||y,onClick:()=>g(e=>e+1)},(0,e.createElement)(t))),(0,e.createElement)(`div`,{className:`siwc-actions`},p?.account&&(0,e.createElement)(`button`,{type:`button`,disabled:F,onClick:()=>E(!0)},`Sign out`),(0,e.createElement)(`a`,{href:p?.usageUrl??`https://chatgpt.com/settings/usage`,target:`_blank`,rel:`noopener noreferrer`},`Manage ChatGPT usage`)),T&&(0,e.createElement)(`div`,{className:`siwc-confirm`,role:`group`,"aria-label":`Confirm sign out`},(0,e.createElement)(`p`,null,`Sign out of this ChatGPT account? Saved registrations will be kept.`),(0,e.createElement)(`div`,{className:`siwc-actions`},(0,e.createElement)(`button`,{type:`button`,disabled:y,onClick:()=>(E(!1),I(()=>l()))},`Sign out`),(0,e.createElement)(`button`,{type:`button`,disabled:y,onClick:()=>E(!1)},`Cancel`))),O&&r(O,y,()=>I(()=>c(O.id)),e=>I(()=>s(e,O.id)))),(0,e.createElement)(`div`,{className:`siwc-group`},(0,e.createElement)(`label`,{htmlFor:`${D}-model`},`Search model`),(0,e.createElement)(`p`,{id:`${D}-model-hint`,className:`siwc-hint`},`Separate from the conversation model.`),!p?.account&&(0,e.createElement)(`p`,{className:`siwc-hint`},`Sign in to choose a search model.`),k&&!A&&p?.account&&(0,e.createElement)(`p`,{id:`${D}-model-status`,className:`siwc-state`,role:`status`},`The saved model is unavailable for this account. Select a search model to continue.`),!d.writable&&d.status===`ready`&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},`Settings are read-only.`),(0,e.createElement)(`select`,{id:`${D}-model`,value:A?k:``,disabled:!N||!p?.models.length,"aria-describedby":k&&!A&&p?.account?`${D}-model-hint ${D}-model-status`:`${D}-model-hint`,onChange:e=>{let t=e.currentTarget.value;return L(()=>t?n.set(`searchModel`,t):n.unset(`searchModel`))}},(0,e.createElement)(`option`,{value:``},`Select a search model`),...(p?.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`),f.status===`ready`&&f.value?.searchProvider===void 0&&(0,e.createElement)(`p`,{className:`siwc-hint`},`The default may select SIWC automatically. Choose a provider to pin it.`),f.status!==`ready`&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},`Web search settings are unavailable.`),f.status===`ready`&&j&&!p?.account&&(0,e.createElement)(`p`,{className:`siwc-hint`},`ChatGPT plan is selected. Sign in to use it for web search.`),f.status===`ready`&&(0,e.createElement)(`p`,{className:`siwc-state`,role:`status`},j?`ChatGPT plan`:f.value?.searchProvider??`Deployment default`),(0,e.createElement)(`div`,{className:`siwc-actions`},!j&&(0,e.createElement)(`button`,{type:`button`,"data-action":`use-siwc`,disabled:!P,onClick:()=>L(()=>i.set(`searchProvider`,`siwc`))},`Use SIWC for web search`),j&&(0,e.createElement)(`button`,{type:`button`,disabled:y||!f.writable,onClick:()=>L(()=>i.unset(`searchProvider`))},`Restore deployment default`))))}function r(t,n,r,i){if(t.phase===`running`){let a=t.prompt?.message.startsWith(`Open the sign-in`)&&t.prompt.options.length===1&&t.prompt.options[0]?.id===`cancel`;return(0,e.createElement)(`div`,{className:`siwc-attempt`},(0,e.createElement)(`h4`,null,`Connecting account…`),t.notice&&(0,e.createElement)(`p`,null,t.notice.url?(0,e.createElement)(`a`,{href:t.notice.url,target:`_blank`,rel:`noopener noreferrer`},t.notice.message):t.notice.message),!t.notice&&(0,e.createElement)(`p`,{className:`siwc-hint`},`Preparing secure sign-in…`),t.prompt&&!a&&(0,e.createElement)(`div`,null,(0,e.createElement)(`p`,null,t.prompt.message),(0,e.createElement)(`div`,{className:`siwc-actions`},...t.prompt.options.map(t=>(0,e.createElement)(`button`,{key:t.id,type:`button`,disabled:n,onClick:()=>i(t.id)},t.label)))),a&&(0,e.createElement)(`p`,{className:`siwc-hint`},`Finish signing in in your browser. This page updates automatically.`),(0,e.createElement)(`div`,{className:`siwc-actions`},(0,e.createElement)(`button`,{type:`button`,disabled:n,onClick:r},`Cancel sign-in`)))}return(0,e.createElement)(`p`,{className:`siwc-state`,role:t.phase===`failed`?`alert`:`status`},t.phase===`failed`?t.error:t.phase===`authorized`?`ChatGPT account connected.`:`Sign-in cancelled. Your active account was not changed.`)}const i=[`slots`,`configForms`,`connection`];function a(e){if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.label!=`string`||typeof e.active!=`boolean`||typeof e.signedIn!=`boolean`)throw Error(`Invalid SIWC account`);return e}function o(e){if(!e||typeof e!=`object`)throw Error(`Invalid SIWC attempt`);let t=e;if(typeof t.id!=`string`||t.method!==`oauth`&&t.method!==`select`||![`running`,`authorized`,`cancelled`,`failed`].includes(t.phase??``)||t.notice!==void 0&&(typeof t.notice.message!=`string`||t.notice.url!==void 0&&typeof t.notice.url!=`string`)||t.prompt!==void 0&&(t.prompt.kind!==`select`||typeof t.prompt.message!=`string`||!Array.isArray(t.prompt.options)||t.prompt.options.some(e=>!e||typeof e.id!=`string`||typeof e.label!=`string`))||t.error!==void 0&&typeof t.error!=`string`)throw Error(`Invalid SIWC attempt`);return t}function s(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.accounts)||!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,accounts:t.accounts.map(a),...t.attempt?{attempt:o(t.attempt)}:{}}}function c(t){let r=t.get(`connection`).rpc,i=t.configForms.get(`siwc`),a=t.configForms.get(`web`);async function o(e,t,n){let i=await r.call(`/api`,e,t,n);if(!i.ok)throw Error(i.error.message);return i.value}let c=async e=>s(await o(`siwc/status`,{},e)),u=async(e,t,n)=>l(await o(`siwc/authorize`,{method:e,...t?{accountId:t}:{}},n)),d=async(e,t,n)=>l(await o(`siwc/answer`,{choice:e,attemptId:t},n)),f=async(e,t)=>l(await o(`siwc/cancel`,{attemptId:e},t)),p=async e=>l(await o(`siwc/logout`,{},e)),m=e=>t.on(`connection/reset`,e);t.effect(()=>{let e=document.createElement(`style`);return e.dataset.plugin=`dsh-siwc`,e.textContent=`
3
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}
4
+ .siwc-settings h2{font-size:18px;margin:0 0 4px}.siwc-settings h3,.siwc-settings h4,.siwc-settings p{margin:0}.siwc-settings h3,.siwc-settings h4,.siwc-settings label{font-size:13px;font-weight:600}
5
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
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
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}
8
+ .siwc-settings select{width:100%;min-width:0}.siwc-settings button{width:fit-content;min-width:0;max-width:100%;overflow-wrap:anywhere;cursor:pointer}.siwc-settings button:disabled,.siwc-settings select:disabled{opacity:.5;cursor:default}
9
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;
10
+ .siwc-settings .siwc-account-line{display:flex;align-items:center;gap:8px;min-width:0}.siwc-settings .siwc-account-line select{flex:1;width:auto}.siwc-settings .siwc-icon-button{display:inline-flex;flex:none;align-items:center;justify-content:center;width:36px;padding:0}
11
+ .siwc-settings .siwc-confirm,.siwc-settings .siwc-attempt{display:grid;gap:8px;padding:12px;border:1px solid var(--dsw-alias-border-l4);border-radius:8px}
12
+ `,document.head.appendChild(e),()=>e.remove()}),t.effect(()=>t.configForms.whileServed([`siwc`],()=>t.slots.inject(`settings.section`,()=>t.slots.register({name:`settings.section`,id:`siwc`,order:35,label:()=>`SIWC`},()=>(0,e.createElement)(n,{form:i,web:a,loadStatus:c,authorize:u,answer:d,cancel:f,logout:p,subscribeReset:m})))))}function l(e){if(!e||typeof e!=`object`)throw Error(`Invalid SIWC action result`);let t=e;if(t.message!==void 0&&typeof t.message!=`string`)throw Error(`Invalid SIWC action result`);return{status:s(t.status),...t.message?{message:t.message}:{}}}exports.apply=c,exports.inject=i;
11
13
  return module.exports;}});
@@ -1,17 +1,21 @@
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(`
1
+ import{getDshRuntimeVersion as e}from"@deepseek-ai/dsh-app-boot";import t from"@deepseek-ai/schemastery";import n from"node:assert/strict";import{createHash as r,randomBytes as i,randomUUID as a}from"node:crypto";import{mkdir as o,readFile as s}from"node:fs/promises";import{dirname as c}from"node:path";import{withFileLock as l,writeFileAtomic as u}from"@deepseek-ai/dsh-atomic-write";import{credentialKey as d}from"@deepseek-ai/dsh-credentials";import{dshHomePath as f}from"@deepseek-ai/dsh-home-paths";import{LlmError as p,resolveImageAttachmentAccess as m,resolveRetryPolicy as h}from"@deepseek-ai/dsh-llm";import{once as g}from"node:events";import{createServer as _}from"node:http";import{setTimeout as v}from"node:timers/promises";import{AuthorizationDeclinedError as ee,AuthorizationError as y}from"@deepseek-ai/dsh-authorization";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`)}const ye={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function be(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 xe(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 Se(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function O(e){return typeof e==`string`?e:e?.message}function Ce(e,t,n){let r=e.message?e.message:O(e.inst?._zod.def?.error?.(e))??O(t?.error?.(e))??O(n.customError?.(e))??O(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 we(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Te(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}function Ee(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const De=(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})},Oe=/* @__PURE__ */ C(`$ZodError`,De),ke=/* @__PURE__ */ C(`$ZodError`,De,{Parent:Error}),Ae=/* @__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=>Ce(e,a,T())));throw pe(t,i?.callee),t}return o.value})(ke),je=/* @__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=>Ce(e,a,T())));throw pe(t,i?.callee),t}return o.value})(ke),Me=/* @__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??Oe)(a.issues.map(e=>Ce(e,i,T())))}:{success:!0,data:a.value}})(ke),Ne=/* @__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=>Ce(e,i,T())))}:{success:!0,data:a.value}})(ke),Pe=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Fe=/^-?\d+$/,Ie=/^-?\d+(?:\.\d+)?$/,Le=/^(?:true|false)$/i,Re=/*@__PURE__*/ C(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ze=/*@__PURE__*/ C(`$ZodCheckNumberFormat`,(e,t)=>{Re.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=ye[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Fe)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Be=/*@__PURE__*/ C(`$ZodCheckMinLength`,(e,t)=>{var n;Re.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=we(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ve={major:4,minor:4,patch:3},k=/*@__PURE__*/ C(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ve;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=be(e),i;for(let a of t){if(a._zod.def.when){if(xe(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||=be(e,t))});else{if(e.issues.length===t)continue;r||=be(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(be(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=Me(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ne(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),He=/*@__PURE__*/ C(`$ZodString`,(e,t)=>{k.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Pe(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}}),Ue=/*@__PURE__*/ C(`$ZodNumber`,(e,t)=>{k.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ie,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}}),We=/*@__PURE__*/ C(`$ZodNumberFormat`,(e,t)=>{ze.init(e,t),Ue.init(e,t)}),Ge=/*@__PURE__*/ C(`$ZodBoolean`,(e,t)=>{k.init(e,t),e._zod.pattern=Le,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}}),Ke=/*@__PURE__*/ C(`$ZodNever`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function qe(e,t,n){e.issues.length&&t.issues.push(...Se(n,e.issues)),t.value[n]=e.value}const Je=/*@__PURE__*/ C(`$ZodArray`,(e,t)=>{k.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=>qe(t,n,e))):qe(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Ye(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Se(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 Xe(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 Ze(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Ye(e,n,i,t,u,d))):Ye(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 Qe=/*@__PURE__*/ C(`$ZodObject`,(e,t)=>{if(k.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(()=>Xe(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=>Ye(n,t,e,s,r,i))):Ye(a,t,e,s,r,i)}return i?Ze(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),$e=/*@__PURE__*/ C(`$ZodLiteral`,(e,t)=>{if(k.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 et(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const tt=/*@__PURE__*/ C(`$ZodOptional`,(e,t)=>{k.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=>et(e,r)):et(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),nt=/*@__PURE__*/ C(`$ZodCustom`,(e,t)=>{Re.init(e,t),k.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>rt(t,n,r,e));rt(i,n,r,e)}});function rt(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ee(e))}}const it=()=>{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=Te(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 at(){return{localeError:it()}}// @__NO_SIDE_EFFECTS__
3
+ function ot(e,t){return new e({type:`string`,...D(t)})}// @__NO_SIDE_EFFECTS__
4
+ function st(e,t){return new e({type:`number`,checks:[],...D(t)})}// @__NO_SIDE_EFFECTS__
5
+ function ct(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...D(t)})}// @__NO_SIDE_EFFECTS__
6
+ function lt(e,t){return new e({type:`boolean`,...D(t)})}// @__NO_SIDE_EFFECTS__
7
+ function ut(e,t){return new e({type:`never`,...D(t)})}// @__NO_SIDE_EFFECTS__
8
+ function A(e,t){return new Be({check:`min_length`,...D(t),minimum:e})}// @__NO_SIDE_EFFECTS__
9
+ function dt(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...D(n)})}const j=/*@__PURE__*/ C(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);k.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Ae(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Me(e,t,n),e.parseAsync=async(t,n)=>je(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ne(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)}),ft=/*@__PURE__*/ C(`ZodMiniString`,(e,t)=>{He.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
10
+ function M(e){return/* @__PURE__ */ ot(ft,e)}const pt=/*@__PURE__*/ C(`ZodMiniNumber`,(e,t)=>{Ue.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
11
+ function mt(e){return/* @__PURE__ */ st(pt,e)}const ht=/*@__PURE__*/ C(`ZodMiniNumberFormat`,(e,t)=>{We.init(e,t),pt.init(e,t)});// @__NO_SIDE_EFFECTS__
12
+ function gt(e){return/* @__PURE__ */ ct(ht,e)}const _t=/*@__PURE__*/ C(`ZodMiniBoolean`,(e,t)=>{Ge.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
13
+ function vt(e){return/* @__PURE__ */ lt(_t,e)}const yt=/*@__PURE__*/ C(`ZodMiniNever`,(e,t)=>{Ke.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
14
+ function bt(e){return/* @__PURE__ */ ut(yt,e)}const xt=/*@__PURE__*/ C(`ZodMiniArray`,(e,t)=>{Je.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
15
+ function N(e,t){return new xt({type:`array`,element:e,...D(t)})}const St=/*@__PURE__*/ C(`ZodMiniObject`,(e,t)=>{Qe.init(e,t),j.init(e,t),E(e,`shape`,()=>t.shape)});// @__NO_SIDE_EFFECTS__
16
+ function P(e,t){return new St({type:`object`,shape:e,catchall:/* @__PURE__ */ bt(),...D(t)})}const Ct=/*@__PURE__*/ C(`ZodMiniLiteral`,(e,t)=>{$e.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
17
+ function wt(e,t){return new Ct({type:`literal`,values:Array.isArray(e)?e:[e],...D(t)})}const Tt=/*@__PURE__*/ C(`ZodMiniOptional`,(e,t)=>{tt.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
18
+ function F(e){return new Tt({type:`optional`,innerType:e})}const Et=/*@__PURE__*/ C(`ZodMiniCustom`,(e,t)=>{nt.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
19
+ function Dt(e,t={}){return/* @__PURE__ */ dt(Et,e,t)}const Ot=new TextEncoder,kt=new TextDecoder,At=new TextDecoder(`utf-8`,{fatal:!0});function jt(...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 Nt(e){if(typeof e==`string`&&e.length>=128){if(Mt.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Ot.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 Pt(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 I=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)}},L=class extends I{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}},Ft=class extends I{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}},It=class extends I{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},R=class extends I{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},z=class extends I{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Lt=class extends I{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Rt=class extends I{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},zt=class extends I{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Bt=class extends I{[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)}},Vt=class extends I{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Ht=class extends I{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function Ut(e){try{return Pt(typeof e==`string`?e:kt.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function B(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Wt(e){return B(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(B)}function Gt(...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 Kt(e,t,n){try{return Ut(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function qt(e,t,n){try{return Nt(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Jt(e,t,n){let r;try{r=JSON.parse(At.decode(Ut(e)))}catch{throw new t(n)}if(!B(r))throw new t(n);return r}const Yt={__proto__:null,b64:!0};function Xt(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 Zt(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 R(`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 Qt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new z(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}const $t=e=>e[Symbol.toStringTag],en=(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 tn(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(B(t)){if(o=hn(t),typeof o.kty!=`string`)throw ln(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(en(e,o,n),o.kty===`oct`)return Ut(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!sn(t))throw ln(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${$t(t)} instances must be of type "${e}" for the ${r} algorithm`);if(an(t))return t;if(s=t,s.type===`secret`)return s.export()}nn||=/* @__PURE__ */ new WeakMap;let c=t,l=nn.get(c);if(l?.[r])return l[r];if(l||nn.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=rn[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 gn(e,o)}let nn;const rn={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},an=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},on=e=>e?.[Symbol.toStringTag]===`KeyObject`,sn=e=>an(e)||on(e);function cn(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 ln(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(cn(`Key for the ${e} algorithm must be `,t,...r))}const un=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function dn(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function fn(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 pn(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw un(t.name);if(t.hash&&r.hash?.name!==t.hash)throw un(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw un(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw un(t.length,`algorithm.length`);dn(e,n)}function mn(e){return{__proto__:null,...e}}function hn(e){let t=mn(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 gn(e,t,n){if(!e.kty.includes(t.kty))throw new R(`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 _n(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),pn(e,t,n),e}function vn(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const V=[[`verify`],[`sign`]];function yn(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:V}}function H(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:V,minRsaBits:2048}}function bn(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:V}}function xn(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:V}}function Sn(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:V}}const Cn=vn({HS256:yn(256),HS384:yn(384),HS512:yn(512),RS256:H(256),RS384:H(384),RS512:H(512),PS256:H(256,32),PS384:H(384,48),PS512:H(512,64),ES256:bn(`P-256`,256),ES384:bn(`P-384`,384),ES512:bn(`P-521`,512),EdDSA:xn(),Ed25519:xn(),"ML-DSA-44":Sn(44),"ML-DSA-65":Sn(65),"ML-DSA-87":Sn(87)});function wn(e){let t=typeof e==`string`?Cn[e]:void 0;if(!t)throw new R(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Tn(e){return[e&&Xt(`algorithms`,e.algorithms),e?.crit]}function En(e){return e===void 0?{}:Jt(e,z,`JWS Protected Header is invalid`)}function Dn(e){try{return Nt(e)}catch{throw new z(`JWS Compact Serialization payload must use only ASCII characters`)}}async function On(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??En(a);if(!Gt(c,o))throw new z(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Qt(c,Zt(z,Yt,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new z(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new It(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new z(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new z(`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=wn(d),h=jt(a===void 0?/* @__PURE__ */ new Uint8Array:Nt(a),Nt(`.`),typeof f==`string`?t[2]??=qt(f,`payload`,z):f),g=Kt(e.signature,`signature`,z),_=await tn(m,n,`verify`),v=await _n(_,m.subtle,`verify`);m.minRsaBits&&fn(m.alg,v);let ee=!1;try{ee=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!ee)throw new Ht;let y={payload:typeof f==`string`?Kt(f,`payload`,z):f};return a!==void 0&&(y.protectedHeader=c),o!==void 0&&(y.unprotectedHeader=o),p?[{...y,key:_},u]:[y,u]}async function kn(e,t,n){if(e instanceof Uint8Array&&(e=kt.decode(e)),typeof e!=`string`)throw new z(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new z(`Invalid Compact JWS`);return On({payload:i,protected:r,signature:a},t,n,Dn)}const An=e=>Math.floor(e.getTime()/1e3),jn={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Mn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,U=`check_failed`;function Nn(){throw TypeError(`Invalid time period format`)}function Pn(e){typeof e!=`string`&&Nn();let t=Mn.exec(e);(!t||t[4]&&t[1])&&Nn();let n=parseFloat(t[2]),r=Math.round(n*jn[t[3][0].toLowerCase()]);return Number.isFinite(r)||Nn(),t[1]===`-`||t[4]===`ago`?-r:r}function Fn(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const In=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Ln=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function Rn(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new L(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function zn(e,t){throw new L(`unexpected "${t}" claim value`,e,t,U)}function Bn(e,t,n={}){let r;try{r=JSON.parse(At.decode(t))}catch{}if(!B(r))throw new Lt(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||In(e.typ)!==In(i)))throw new L(`unexpected "typ" JWT header value`,r,`typ`,U);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 L(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&zn(r,`iss`),s!==void 0&&r.sub!==s&&zn(r,`sub`),c!==void 0&&!Ln(r.aud,typeof c==`string`?[c]:c)&&zn(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Pn(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}Fn(`clockTolerance option`,f);let{currentDate:p}=n,m=Fn(`currentDate option`,An(p===void 0?/* @__PURE__ */ new Date:p)),h=Rn(r,`iat`,l!==void 0),g=Rn(r,`nbf`);if(g!==void 0&&g>m+f)throw new L(`"nbf" claim timestamp check failed`,r,`nbf`,U);let _=Rn(r,`exp`);if(_!==void 0&&_<=m-f)throw new Ft(`"exp" claim timestamp check failed`,r,`exp`,U);if(l!==void 0){let e=m-h,t=Fn(`maxTokenAge option`,typeof l==`number`?l:Pn(l));if(e-f>t)throw new Ft(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,U);if(e<-f)throw new L(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,U)}return r}async function Vn(e,t,n){let[r,i]=await kn(e,Tn(n),t);if(!i)throw new Lt(`JWTs MUST NOT use unencoded payload`);let a=Bn(r.protectedHeader,r.payload,n);return{...r,payload:a}}function Hn(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 Un(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=gn(n,t,!0).then(e=>{if(e.type!==`public`)throw new Rt(`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(!Wt(t))throw new Rt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=mn(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`?Cn[a]:void 0;if(!s||s.secret)throw new R(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Hn(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new zt;if(u!==1){let e=new Bt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await Un(r,e,s)}catch{}},e}return Un(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Gn(){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 qn=/* @__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 Vt:e});if(i.status!==200)throw new I(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new I(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Yn=/* @__PURE__ */ Symbol();function W(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Xn(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function Zn(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=Xn(r.cooldownDuration,3e4,`cooldownDuration`),s=Xn(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[qn],u=r[Yn],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;W(e,s)&&Wt(t)&&(d=e,h=Wn(t))}let g=async()=>{if(f&&Gn()&&(f=void 0),!f){let e=++p,t=f=Jn(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||!W(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof zt&&!W(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>W(d,o),enumerable:!0},fresh:{get:()=>W(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}const G=`https://auth.openai.com`,K=`https://api.openai.com/v1`,Qn=`https://chatgpt.com/settings/usage`;var q=class extends Error{},$n=class extends Error{},er=class extends Error{status;code;requestId;constructor(e,t,n){super(`OpenAI request failed (${e}${t?`: ${t}`:``}). Reconnect in Settings → SIWC; manage usage: ${Qn}`),this.status=e,this.code=t,this.requestId=n}};const tr=/* @__PURE__ */ new Set([`invalid_grant`,`invalid_refresh_token`,`token_expired`,`refresh_token_expired`,`refresh_token_invalidated`,`refresh_token_reused`]);function nr(e){n.ok(typeof e==`object`&&!!e&&!Array.isArray(e),`Invalid OpenAI response`)}function J(e,t){n.ok(typeof e==`string`&&e.trim(),`OpenAI returned invalid ${t}`)}async function rr(e,t={}){let n=await fetch(e,{...t,signal:AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]])}).catch(e=>{throw new $n(`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`))try{let t=await n.json();nr(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)}catch{e=void 0}throw new er(n.status,e,n.headers.get(`x-request-id`))}let r;try{r=await n.json()}catch{throw new $n(`OpenAI returned an invalid JSON response.`)}return nr(r),r}async function Y(e){let t=await rr(`${G}/.well-known/openid-configuration`,{signal:e});n.equal(t.issuer,G,`Unexpected OpenAI issuer`);for(let e of[`authorization_endpoint`,`token_endpoint`,`jwks_uri`])J(t[e],e),n.equal(new URL(t[e]).origin,G,`Unexpected OpenAI ${e}`);return t.revocation_endpoint!==void 0&&(J(t.revocation_endpoint,`revocation_endpoint`),n.equal(new URL(t.revocation_endpoint).origin,G,`Unexpected OpenAI revocation endpoint`)),t}async function ir(e,t,r,i,a){let o=await Y(a).catch(()=>{throw new q(`OpenAI identity service is unavailable. Try again.`)}),s=Zn(new URL(o.jwks_uri)),{payload:c}=await Vn(e,async(e,t)=>{try{return await s(e,t)}catch(e){throw e instanceof zt?e:new q(`OpenAI signing keys are unavailable. Try again.`)}},{issuer:G,audience:t,algorithms:[`RS256`],requiredClaims:[`iss`,`sub`,`aud`,`iat`,`exp`],...i===void 0?{}:{currentDate:new Date(i)}});return J(c.sub,`ID token subject`),r!==void 0&&n.equal(c.nonce,r,`OpenAI ID token nonce mismatch`),(c.azp!==void 0||Array.isArray(c.aud)&&c.aud.length>1)&&n.equal(c.azp,t,`OpenAI ID token authorized party mismatch`),{subject:c.sub,...typeof c.email==`string`?{email:c.email}:{}}}async function ar(e,t){let r=await rr((await Y(t)).token_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:e,signal:t});J(r.access_token,`access_token`),J(r.refresh_token,`refresh_token`),J(r.scope,`scope`),n.equal(String(r.token_type).toLowerCase(),`bearer`,`Unexpected OpenAI token type`),n.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+/);n.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)),n.ok(Number.isFinite(a),`Invalid earliest_refresh_at`)),r.id_token!==void 0&&J(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 or(e,t){return n.ok(e.tokens,`Sign in with ChatGPT in Settings first`),ar(new URLSearchParams({grant_type:`refresh_token`,client_id:e.clientId,refresh_token:e.tokens.refresh,resource:K}),t)}async function sr(e){let t=AbortSignal.timeout(1e4),r=await Y(t);n.ok(r.revocation_endpoint,`OpenAI did not publish a revocation endpoint`);let i=e.pending?.tokens.refresh??e.tokens?.refresh;n.ok(i,`No renewable ChatGPT session`);for(let n=0;;n++){try{let n=await fetch(r.revocation_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},signal:t,body:new URLSearchParams({token:i,token_type_hint:`refresh_token`,client_id:e.clientId})});if(n.status===200)return;if(n.status<500)throw Error(`ChatGPT session revocation failed (${n.status})`)}catch(e){if(!(e instanceof TypeError)||t.aborted||n===2)throw e}if(n===2)throw Error(`ChatGPT session revocation is unavailable`);await v(200*2**n,void 0,{signal:t})}}async function cr(e,t){let r=await rr(`${K}/models`,{headers:{authorization:`Bearer ${e}`},signal:t});return n.ok(Array.isArray(r.models),`Invalid ChatGPT model catalog`),r.models.filter(e=>(nr(e),e.visibility===`list`&&(e.supported_in_api!==void 0&&n.equal(typeof e.supported_in_api,`boolean`,`Invalid ChatGPT API support flag`),e.supported_in_api!==!1))).map(e=>{J(e.slug,`model slug`),J(e.display_name,`model display name`);let t={id:e.slug,name:e.display_name};if(e.supported_in_api!==void 0&&(t.supportedInApi=e.supported_in_api),e.context_window!==void 0&&(n.ok(typeof e.context_window==`number`&&Number.isSafeInteger(e.context_window)&&e.context_window>0,`Invalid ChatGPT context window`),t.contextWindow=e.context_window),e.input_modalities!==void 0){n.ok(Array.isArray(e.input_modalities),`Invalid ChatGPT input modalities`);for(let t of e.input_modalities)J(t,`input modality`);t.input=[...e.input_modalities]}return e.supported_reasoning_levels!==void 0&&(n.ok(Array.isArray(e.supported_reasoning_levels),`Invalid ChatGPT reasoning levels`),t.reasoningEfforts=e.supported_reasoning_levels.map(e=>(nr(e),J(e.effort,`reasoning effort`),e.effort))),t})}async function lr(e,t,a,o){let s=await Y(e.signal),c=i(32).toString(`base64url`),l=i(32).toString(`base64url`),u=i(32).toString(`base64url`),d=AbortSignal.any([e.signal,AbortSignal.timeout(3e5)]),f,p,m=new Promise((e,t)=>{f=e,p=t}),h=()=>p(d.reason);d.addEventListener(`abort`,h,{once:!0}),m.catch(()=>{});let v,y=_((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`)===c){t.writeHead(302,{Location:v}).end();return}if(e.method!==`GET`||n.pathname!==`/auth/callback`){t.writeHead(404).end(`Not found`);return}if(n.searchParams.get(`state`)!==c){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.`),p(/* @__PURE__ */ Error(`ChatGPT sign-in was declined`));return}let r=n.searchParams.get(`code`),i=n.searchParams.get(`client_id`)??a.clientId;!r||!i||i===`dynamic_agent_client`||a.clientId!==`dynamic_agent_client`&&a.clientId!==i?(t.writeHead(400).end(`Invalid OAuth registration callback`),p(/* @__PURE__ */ Error(`Invalid OpenAI OAuth registration callback`))):(t.end(`Return to DSH to finish connecting your ChatGPT account.`),f({code:r,clientId:i}))}),b=new AbortController;try{d.throwIfAborted(),y.listen(0,`127.0.0.1`),await g(y,`listening`);let i=y.address();n.ok(i&&typeof i==`object`);let f=`http://127.0.0.1:${i.port}/auth/callback`,p=new URL(s.authorization_endpoint);p.search=new URLSearchParams({client_id:a.clientId,ext_agent_host_id:t,response_type:`code`,redirect_uri:f,resource:K,scope:`openid profile email offline_access resource.invoke chatgpt.tokens.use.direct`,state:c,nonce:l,code_challenge_method:`S256`,code_challenge:r(`sha256`).update(u).digest(`base64url`),...a.clientId===`dynamic_agent_client`?{agent_name_hint:`DSH SIWC`}:{},...a.idToken?{id_token_hint:a.idToken}:{},...a.email?{login_hint:a.email}:{}}).toString(),v=p.toString(),e.notify({message:`Continue with ChatGPT`,url:`http://127.0.0.1:${i.port}/auth/start?state=${c}`});let h=e.prompt({kind:`select`,message:`Open the sign-in link, then finish in your browser.`,options:[{id:`cancel`,label:`Cancel sign-in`}],signal:AbortSignal.any([d,b.signal])}).then(()=>{throw new ee}),_=await Promise.race([m,h]);b.abort(),d.throwIfAborted(),await o(_.clientId);let x=await ar(new URLSearchParams({grant_type:`authorization_code`,client_id:_.clientId,code:_.code,code_verifier:u,redirect_uri:f,resource:K}),d);J(x.idToken,`id_token`);let te=await ir(x.idToken,_.clientId,l,void 0,d);return a.subject&&n.equal(te.subject,a.subject,`ChatGPT account changed during reauthorization`),d.throwIfAborted(),{...te,tokens:x.tokens,idToken:x.idToken}}finally{b.abort(),d.removeEventListener(`abort`,h),y.close(),y.closeAllConnections()}}T(at());const X=d(`siwc`,`chatgpt`),ur=/* @__PURE__ */ P({access:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),refresh:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),expires:/* @__PURE__ */ mt(),scopes:/* @__PURE__ */ N(/* @__PURE__ */ M()),refreshAfter:/* @__PURE__ */ F(/* @__PURE__ */ mt())}),dr=/* @__PURE__ */ P({version:/* @__PURE__ */ wt(1),activeId:/* @__PURE__ */ F(/* @__PURE__ */ M()),welcomed:/* @__PURE__ */ F(/* @__PURE__ */ vt()),accounts:/* @__PURE__ */ N(/* @__PURE__ */ P({id:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),clientId:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),subject:/* @__PURE__ */ F(/* @__PURE__ */ M()),email:/* @__PURE__ */ F(/* @__PURE__ */ M()),idToken:/* @__PURE__ */ F(/* @__PURE__ */ M()),tokens:/* @__PURE__ */ F(ur),pending:/* @__PURE__ */ F(/* @__PURE__ */ P({tokens:ur,idToken:/* @__PURE__ */ F(/* @__PURE__ */ M()),receivedAt:/* @__PURE__ */ mt()})),models:/* @__PURE__ */ F(/* @__PURE__ */ N(/* @__PURE__ */ P({id:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),name:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),supportedInApi:/* @__PURE__ */ F(/* @__PURE__ */ vt()),contextWindow:/* @__PURE__ */ F((/* @__PURE__ */ mt()).check(/* @__PURE__ */ gt(),/* @__PURE__ */ Dt(e=>e>0,`Expected a positive integer`))),input:/* @__PURE__ */ F(/* @__PURE__ */ N((/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)))),reasoningEfforts:/* @__PURE__ */ F(/* @__PURE__ */ N((/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1))))})))}))}),fr=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;function Z(e){return e===void 0?{version:1,accounts:[]}:(n.ok(e.kind===`grant`,`Invalid SIWC credential record`),dr.parse(e.payload))}async function pr(){let e=f(`siwc`,`host-id`);return await o(c(e),{recursive:!0,mode:448}),l(e,async()=>{let t;try{t=(await s(e,`utf8`)).trim()}catch(n){if(n.code!==`ENOENT`)throw n;t=`urn:uuid:${a()}`,await u(e,t,{mode:384,dirMode:448})}return n.match(t,/^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`),t})}var mr=class{credentials;constructor(e){this.credentials=e}async read(){return Z(await this.credentials.readRecord(X))}async change(e){return Z(await this.credentials.modifyRecord(X,async t=>{let n=Z(t);return await e(n),{kind:`grant`,payload:n}}))}async accessToken(e,t){let r,i=AbortSignal.timeout(2e4),a=await this.credentials.modifyRecord(X,async a=>{let o=Z(a),s=o.accounts.find(t=>t.id===(e??o.activeId));if(!s?.tokens)throw new p(`Continue with ChatGPT in Settings → SIWC.`,`MISSING_CREDENTIAL`);let c=Date.now();if(t!==void 0&&s.tokens.access!==t||!s.pending&&(t===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 or(s,i),l.idToken){let e=await ir(l.idToken,s.clientId,void 0,l.receivedAt,i);n.equal(e.subject,s.subject,`Refreshed ChatGPT identity changed`),s.idToken=l.idToken}s.tokens=l.tokens,delete s.pending}catch(e){if(e instanceof q&&l)s.pending=l;else if(l||e instanceof er&&e.code!==void 0&&tr.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=Z(a);return o.accounts.find(t=>t.id===(e??o.activeId)).tokens.access}},Q=class extends Error{name=`SiwcAccountError`};function hr(e){return e instanceof ee||e instanceof y&&e.code===`CANCELLED`?`Sign-in cancelled.`:e instanceof Q||e instanceof $n||e instanceof er||e instanceof q?e.message:`Could not finish the account action. Try again.`}var gr=class{current;preferredAccountId;operations=Promise.resolve();ctx;accounts;syncAdapter;constructor(e,t,n){this.ctx=e,this.accounts=t,this.syncAdapter=n}async status(){let e=await this.accounts.read(),t=e.accounts.find(t=>t.id===e.activeId&&t.tokens),n=e.accounts.map(t=>({id:t.id,label:fr(t),active:t.id===e.activeId,signedIn:t.tokens!==void 0})).sort((e,t)=>Number(t.active)-Number(e.active));return{...t?{account:{id:t.id,label:fr(t)}}:{},accounts:n,models:t?.models?.map(({id:e,name:t})=>({id:e,name:t}))??[],usageUrl:Qn,...this.current?{attempt:this.projectAttempt(this.current)}:{}}}authorize(e,t){return this.enqueue(()=>this.startAuthorize(e,t))}async startAuthorize(e,t){if(this.current?.phase===`running`)return{status:await this.status()};if(t!==void 0){if(!t)throw new Q(`Choose a saved ChatGPT account.`);if(t!==`new`&&!(await this.accounts.read()).accounts.some(e=>e.id===t))throw new Q(`Saved ChatGPT account not found.`)}let n={id:a(),method:e,controller:new AbortController,phase:`running`,done:Promise.resolve()};return this.current=n,this.preferredAccountId=t,n.done=this.ctx.authorization.begin({key:X,method:e,signal:n.controller.signal,interaction:{notify:e=>this.notify(n,e),prompt:e=>this.prompt(n,e)}}).then(e=>{n.phase=e.status===`authorized`?`authorized`:`cancelled`,n.notice={message:n.phase===`authorized`?`ChatGPT account connected.`:`Sign-in cancelled. Your active account was not changed.`},n.pending=void 0}).catch(e=>{n.phase=`failed`,n.error=hr(e),n.pending=void 0,this.ctx.logger.warn(`SIWC Settings authorization failed: %s`,hr(e))}).finally(()=>{this.current===n&&(this.preferredAccountId=void 0)}),{status:await this.status()}}async answer(e,t){let n=this.current;if(n?.id!==t)throw new Q(`This sign-in attempt is no longer active.`);if(n.phase!==`running`||!n.pending)throw new Q(`There is no sign-in question to answer.`);let r=n.pending;if(!r.prompt.options.some(t=>t.id===e))throw new Q(`Choose one of the available sign-in options.`);return r.resolve(e),{status:await this.status()}}async cancel(e){let t=this.current;if(t?.id!==e)throw new Q(`This sign-in attempt is no longer active.`);return t.phase===`running`&&(t.controller.abort(),this.ctx.authorization.cancel(X),await t.done),{status:await this.status()}}logout(){return this.enqueue(()=>this.performLogout())}async performLogout(){let e=this.current;e?.phase===`running`&&await this.cancel(e.id);let t=!0;return await this.accounts.change(async e=>{let n=e.accounts.find(t=>t.id===e.activeId);if(n?.tokens||n?.pending)try{await sr(n)}catch{t=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete e.activeId}),await this.syncAdapter(),this.current===e&&(this.current=void 0),{status:await this.status(),message:t?`Signed out. Saved registrations were kept.`:`Signed out locally. Remote revocation was not confirmed; disconnect this app in ChatGPT settings.`}}async authorizeSession(e){let t=await this.accounts.read(),n=t.accounts.filter(t=>e.method===`oauth`||t.tokens!==void 0),r=n.map(e=>({id:e.id,label:fr(e)}));if(e.method===`oauth`&&r.push({id:`new`,label:`Add ChatGPT account or workspace`}),!r.length)throw new Q(`Sign in with ChatGPT in Settings first.`);let i=this.preferredAccountId,o;if(i===`new`){if(e.method!==`oauth`)throw new Q(`Only sign-in can add a ChatGPT account.`);o=`new`}else if(i!==void 0){if(!n.some(e=>e.id===i))throw new Q(`This saved ChatGPT account cannot be selected.`);o=i}else o=r.length===1?r[0].id:await e.prompt({kind:`select`,message:`Choose your ChatGPT account`,options:r,signal:e.signal});let s=t.accounts.find(e=>e.id===o);if(o!==`new`&&!s)throw new Q(`Unknown ChatGPT account.`);let c=s?.tokens?.access,l=s?.subject,u=s??{id:a(),clientId:`dynamic_agent_client`};if(e.method===`oauth`){let t=await lr(e,await pr(),u,async t=>{e.signal.throwIfAborted(),u.clientId=t,await this.accounts.change(n=>{e.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===u.id);r?r.clientId=t:n.accounts.push({...u,clientId:t}),e.signal.throwIfAborted()})});Object.assign(u,t)}if(!u.tokens)throw new Q(`This account is signed out. Reconnect it in Settings.`);let d=e.method===`oauth`?u.tokens.access:await this.accounts.accessToken(u.id),f=await cr(d,e.signal);t.welcomed||(e.notify({message:`Manage usage`,url:Qn}),await e.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`}],signal:e.signal})),e.signal.throwIfAborted();let p=Z(await this.accounts.credentials.readRecord(X)),m=p.accounts.find(e=>e.id===u.id);if(!m)throw new Q(`ChatGPT registration was removed during sign-in. Please retry.`);if(e.method===`oauth`){if(m.clientId!==u.clientId||s!==void 0&&m.subject!==l||s!==void 0&&m.tokens?.access!==c)throw new Q(`ChatGPT account changed during sign-in. Please retry.`);Object.assign(m,u),delete m.pending}else if(!m.tokens||m.tokens.access!==d)throw new Q(`ChatGPT account changed while switching. Please retry.`);m.models=f,p.activeId=u.id,p.welcomed=!0,await e.commit({kind:`grant`,payload:p}),await this.syncAdapter(),e.notify({message:`Using ChatGPT plan. Manage usage`,url:Qn})}dispose(){this.current?.controller.abort(),this.current?.phase===`running`&&this.ctx.authorization.cancel(X)}enqueue(e){let t=this.operations.then(e,e);return this.operations=t.then(()=>void 0,()=>void 0),t}notify(e,t){e.phase===`running`&&(e.notice={message:t.message,...t.url?{url:t.url}:{}})}prompt(e,t){return t.kind===`select`?e.pending?Promise.reject(new Q(`A sign-in question is already open.`)):new Promise((n,r)=>{let i=()=>{e.pending=void 0,t.signal?.removeEventListener(`abort`,a)},a=()=>{i(),r(new Q(`Sign-in prompt was withdrawn.`))};e.pending={prompt:t,resolve:e=>{i(),n(e)}},t.signal?.addEventListener(`abort`,a,{once:!0}),t.signal?.aborted&&a()}):Promise.reject(new Q(`This sign-in step does not accept typed input.`))}projectAttempt(e){return{id:e.id,method:e.method,phase:e.phase,...e.notice?{notice:e.notice}:{},...e.pending?{prompt:{kind:`select`,message:e.pending.prompt.message,options:e.pending.prompt.options.map(({id:e,label:t})=>({id:e,label:t}))}}:{},...e.error?{error:e.error}:{}}}};const _r=/(?:^|-)(?:image|tts|transcribe|realtime|audio|embedding)(?:-|$)/i,vr=/* @__PURE__ */ new Set([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]);function yr(e){return e.startsWith(`gpt-`)&&!_r.test(e)}function br(e){return e===`text`||e===`image`}function xr(e,t){let n=t.get(e);if(n)return n;let r=[...t.values()].filter(e=>yr(e.id)&&e.api===`openai-responses`&&e.reasoning),i=(e,t)=>t.id.localeCompare(e.id,void 0,{numeric:!0}),a=e.match(/-([a-z]+)$/i)?.[1]?.toLowerCase(),o=a?r.filter(e=>e.id.toLowerCase().endsWith(`-${a}`)):[];if(o.sort(i),o[0])return o[0];let s=e.match(/^gpt-(\d+)/)?.[1],c=s?r.filter(e=>RegExp(`^gpt-${s}(?:[.-]|$)`).test(e.id)):[];return c.sort(i),c[0]?c[0]:r.sort((e,t)=>t.contextWindow-e.contextWindow||i(e,t))[0]}function Sr(e){return yr(e.id)&&e.supportedInApi===!0&&e.contextWindow!==void 0&&e.input?.includes(`text`)===!0}function Cr(e){if(e===void 0||!e.some(e=>vr.has(e)))return;let t=new Set(e);return{off:t.has(`none`)?`none`:null,minimal:t.has(`minimal`)?`minimal`:null,low:t.has(`low`)?`low`:null,medium:t.has(`medium`)?`medium`:null,high:t.has(`high`)?`high`:null,xhigh:t.has(`xhigh`)?`xhigh`:null,max:t.has(`max`)?`max`:null}}function wr(e,t){let n=ne(),r=new Map(n.getModels().map(e=>[e.id,e])),i=(t?.models??[]).flatMap(t=>{if(t.supportedInApi===!1||_r.test(t.id))return[];let n=r.get(t.id);if(!n&&!Sr(t))return e.logger.warn(`Skipping ChatGPT model %s: missing SIWC chat capabilities.`,t.id),[];let i=xr(t.id,r);if(!i)return e.logger.warn(`Skipping ChatGPT model %s: no pi-ai template.`,t.id),[];let a=t.input===void 0?i.input:t.input.filter(br);if(!a.includes(`text`))return e.logger.warn(`Skipping ChatGPT model %s: no supported text input.`,t.id),[];let o=t.contextWindow??(n?i.contextWindow:void 0);return o===void 0?(e.logger.warn(`Skipping ChatGPT model %s: missing SIWC context window.`,t.id),[]):(n||e.logger.info(`Synthesizing ChatGPT model %s from template %s`,t.id,i.id),[{id:t.id,name:t.name,api:`openai-responses`,provider:`openai`,baseUrl:K,input:a,cost:i.cost,reasoning:t.reasoningEfforts===void 0?!!(n&&i.reasoning):t.reasoningEfforts.some(e=>vr.has(e)),thinkingLevelMap:t.reasoningEfforts===void 0&&n?i.thinkingLevelMap:Cr(t.reasoningEfforts),contextWindow:o,maxTokens:i.maxTokens,...i.compat?{compat:i.compat}:{}}])});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:h(void 0,`siwc`),modelErrors:/* @__PURE__ */ new Map,configuredMaxTokens:/* @__PURE__ */ new Map}]])}var Tr=class extends b{ctx;accounts;currentProfiles;options;constructor(e,t){let n={value:wr(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)=>m(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=wr(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 Er(e){try{let t=new URL(e);if((t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password)return t.href}catch{}}function Dr(e){return e.replace(/[\\[\]]/g,`\\$&`)}function Or(e){return e.replace(/</g,`%3C`).replace(/>/g,`%3E`)}function kr(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=Er(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+=`[${Dr(l)}](<${Or(t)}>)`,a=s}i.push(n+e.text.slice(a))}return{...i.length?{content:i.join(`
16
20
 
17
- `)}:{},sources:[...n.values()],truncated:!1}}function ar(e,t,n={}){return{id:`siwc`,available:()=>t().trim().length>0,async search(r,i){let a=AbortSignal.timeout(n.timeoutMs??6e4),o=i?AbortSignal.any([i,a]):a,s,c,l,u=(e,t)=>typeof e==`string`&&t.test(e)&&(!l||!e.includes(l))?e:void 0,d=(e,t=c,n=`ChatGPT web search failed.`)=>{let r=u(e,/^[A-Za-z][A-Za-z0-9_]{0,99}$/)??`WEB_PROVIDER_ERROR`;return new S(n,r,{cause:{...t===void 0?{}:{status:t},code:r,...s?{requestId:s}:{}}})};try{o.throwIfAborted();let i=t();if(!i.trim())throw new S(`Select a ChatGPT search model.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);let a=await e.read();o.throwIfAborted();let f=a.accounts.find(e=>e.id===a.activeId);if(!f?.tokens)throw new S(`Continue with ChatGPT using /chatgpt login.`,`MISSING_CREDENTIAL`);if(!f.models?.some(e=>e.id===i))throw new S(`The selected search model is not available for this ChatGPT account.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);l=await e.accessToken(f.id),o.throwIfAborted();let{data:p,request_id:m,response:h}=await new re({apiKey:l,baseURL:`https://api.openai.com/v1`,organization:null,project:null,maxRetries:0,fetch:n.fetch}).responses.create({model:i,store:!1,stream:!0,input:[{role:`user`,content:r.query}],tools:[{type:`web_search`}],tool_choice:`required`,include:[`web_search_call.action.sources`]},{signal:o}).withResponse();s=u(m,/^[A-Za-z0-9_-]{1,200}$/),c=h.status;let g,_=/* @__PURE__ */ new Map;for await(let e of p){if(o.throwIfAborted(),e.type===`error`)throw d(e.code);if(e.type===`response.failed`)throw d(e.response.error?.code);if(e.type===`response.incomplete`)throw d(`SIWC_SEARCH_INCOMPLETE`);if(e.type===`response.output_item.done`&&_.set(e.output_index,e.item),e.type===`response.completed`){if(e.response.status!==`completed`)throw d(`SIWC_SEARCH_INCOMPLETE`);g=e.response}}if(o.throwIfAborted(),!g)throw d(`SIWC_SEARCH_INCOMPLETE`);return ir(g.output.length?g.output:[..._].sort(([e],[t])=>e-t).map(([,e])=>e))}catch(e){throw o.aborted?d(i?.aborted?`WEB_ABORTED`:`WEB_TIMEOUT`,c,i?.aborted?`ChatGPT web search was cancelled.`:`ChatGPT web search timed out.`):e instanceof S?e:e instanceof re.APIError?(s=u(e.requestID,/^[A-Za-z0-9_-]{1,200}$/)??s,d(e.code,e.status)):d(e instanceof Error&&`code`in e?e.code:void 0)}}}}function or(e,t){e.connection.fetch.register({path:`/api/siwc/status`,methods:[`POST`],requestBody:`buffered`,async fetch(e){if(e.headers.get(`content-type`)?.split(`;`,1)[0]?.trim()!==`application/json`)return new Response(`Expected application/json`,{status:415});let n;try{n=await e.json()}catch{return new Response(`Invalid JSON`,{status:400})}let r=ie.safeParse(n);if(!r.success||r.data.method!==`siwc/status`)return new Response(`Invalid SIWC request`,{status:400});let{rpcId:i,payload:a}=r.data;if(!a||typeof a!=`object`||Array.isArray(a)||Object.keys(a).length!==0)return Response.json({type:`server-response`,rpcId:i,result:{ok:!1,error:{code:`invalid-input`,message:`SIWC status takes no parameters.`,details:{}}}});e.signal.throwIfAborted();let o=await t.read();e.signal.throwIfAborted();let s=o.accounts.find(e=>e.id===o.activeId&&e.tokens),c={...s?{account:{id:s.id,label:`${s.email??`ChatGPT account`} (${s.id.slice(0,8)})`}}:{},models:s?.models?.map(({id:e,name:t})=>({id:e,name:t}))??[],usageUrl:X};return Response.json({type:`server-response`,rpcId:i,result:{ok:!0,value:c}},{headers:{"cache-control":`no-store`}})}})}const sr=`siwc`,cr=[`credentials`,`authorization`,`llm`],lr=s.object({searchModel:s.string().default(``).volatile()}),ur=[`0.2.1-alpha.2`,`0.2.1-alpha.3`,`0.2.1-alpha.4`,`0.2.1-alpha.5`,`0.2.1-rc.1`,`0.2.1-rc.2`,`0.2.2-alpha.2`,`0.2.2-alpha.3`],dr=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;async function fr(e,t){let n=await t.read(),r=n.accounts.find(e=>e.id===n.activeId);if(!r?.tokens)return;let i,a;try{i=await t.accessToken(r.id),a=await qn(i)}catch(t){if(!(t instanceof Ln)&&!(t instanceof Rn)&&!(t instanceof In))throw t;e.logger.warn(`Could not refresh ChatGPT models at startup; keeping the saved catalog: %s`,t.message);return}await t.change(e=>{let t=e.accounts.find(e=>e.id===r.id);t?.tokens?.access===i&&(t.models=a)})}async function pr(t,n){let s=i();ur.includes(s)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,ur.join(`, `),s);let c=new Qn(t.credentials);await fr(t,c);let l=new er(t,c);t.llm.registerAdapter([`openai`],l),t.inject([`web`],e=>{e.web.registerSearchProvider(ar(c,()=>n.searchModel.get()))}),t.inject([`connection`],e=>or(e,c)),t.inject([`settings`],e=>{e.effect(()=>e.settings.configure({auto:!1},t.fiber))});async function u(t){let n=await c.read(),i=n.accounts.map(e=>({id:e.id,label:dr(e)}));t.method===`oauth`&&i.push({id:`new`,label:`Add ChatGPT account or workspace`}),e.ok(i.length,`No saved ChatGPT account. Use /chatgpt login first.`);let a=i.length===1?i[0].id:await t.prompt({kind:`select`,message:`Choose your ChatGPT account`,options:i}),o=n.accounts.find(e=>e.id===a);e.ok(a===`new`||o,`Unknown ChatGPT account`);let s=o??{id:r(),clientId:`dynamic_agent_client`};if(t.method===`oauth`){let e=await Jn(t,await Zn(),s,async e=>{t.signal.throwIfAborted(),s.clientId=e,await c.change(t=>{let n=t.accounts.find(e=>e.id===s.id);n?n.clientId=e:t.accounts.push({...s,clientId:e})})});Object.assign(s,e)}e.ok(s.tokens,`This account is signed out. Reconnect with /chatgpt login.`);let u=await qn(t.method===`oauth`?s.tokens.access:await c.accessToken(s.id),t.signal);n.welcomed||(t.notify({message:`Manage usage`,url:X}),await t.prompt({kind:`select`,message:`You're using your ChatGPT plan. Eligible requests use your plan allowance. Manage usage in ChatGPT settings.`,options:[{id:`ok`,label:`Got it`}]})),t.signal.throwIfAborted(),await c.change(n=>{t.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===s.id);e.ok(r,`ChatGPT registration was removed during sign-in. Please retry.`),t.method===`oauth`&&(Object.assign(r,s),delete r.pending),r.models=u,n.activeId=s.id,n.welcomed=!0}),await l.sync(),t.notify({message:`Using ChatGPT plan. Manage usage`,url:X})}t.authorization.registerFlow({key:Q,label:`ChatGPT plan`,methods:[{id:`oauth`,label:`Continue with ChatGPT`},{id:`select`,label:`Switch saved account`}],run:u}),t.inject([`commands`,`userQuestions`],e=>{e.commands.register({name:`chatgpt`,description:`Connect or manage your ChatGPT plan`,input:{hint:`<login|accounts|logout|status>`},async handler({agent:t,rawInput:n,signal:r}){let i=n.trim()||`status`;if(i===`logout`){let e=!0;return await c.change(async t=>{let n=t.accounts.find(e=>e.id===t.activeId);if(n?.tokens||n?.pending)try{await Kn(n)}catch{e=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete t.activeId}),await l.sync(),{kind:`success`,text:`Signed out. Saved registrations are retained.${e?``:` Remote revocation was not confirmed; disconnect this app in ChatGPT settings.`}\nManage app access: ${X}`}}if(i===`status`){let e=await c.read(),t=e.accounts.find(t=>t.id===e.activeId);return{kind:`success`,text:`${t?.tokens?`Using ChatGPT plan: ${dr(t)}`:`Signed out. Use /chatgpt login.`}\nManage usage: ${X}`}}if(i!==`login`&&i!==`accounts`)return{kind:`error`,text:`Usage: /chatgpt login|accounts|logout|status`};let s;return(await e.authorization.begin({key:Q,method:i===`login`?`oauth`:`select`,signal:r,interaction:{notify(e){s=e},async prompt(n){if(n.kind!==`select`)throw Error(`Unsupported authorization prompt`);let i=s;s=void 0;let c=await e.userQuestions.ask({agent:t,signal:AbortSignal.any([r,...n.signal?[n.signal]:[]]),questions:[{id:`chatgpt`,header:`ChatGPT`,question:n.message,...i?{detail:i.url?`[${i.message}](${i.url})`:i.message}:{},options:n.options.map(({label:e})=>({label:e})),multiSelect:!1}]}).catch(e=>{throw e instanceof o&&e.code===`ASK_ABORTED`&&!n.signal?.aborted&&!r.aborted?new a:e}),l=n.options.find(e=>e.label===c.answers[0]?.selected[0]);if(!l)throw new a;return l.id}}})).status===`authorized`?{kind:`success`,text:`Using ChatGPT plan. Select a model under ChatGPT plan.\nManage usage: ${X}`}:{kind:`error`,text:`ChatGPT sign-in cancelled.`}}})})}export{lr as Config,pr as apply,cr as inject,sr as name};
21
+ `)}:{},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 in Settings → SIWC.`,`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 kr(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 jr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mr(e){return jr(e)&&Object.keys(e).length===0}function $(e){return{ok:!1,error:{code:`invalid-input`,message:e,details:{}}}}async function Nr(e,t,n,r,i){i.throwIfAborted();try{return n===`status`?Mr(r)?{ok:!0,value:await t.status()}:$(`SIWC status takes no parameters.`):n===`authorize`?!jr(r)||r.method!==`oauth`&&r.method!==`select`||r.accountId!==void 0&&(typeof r.accountId!=`string`||!r.accountId)||Object.keys(r).some(e=>e!==`method`&&e!==`accountId`)?$(`Choose a valid SIWC authorization method.`):{ok:!0,value:await t.authorize(r.method,r.accountId)}:n===`answer`?!jr(r)||Object.keys(r).length!==2||typeof r.attemptId!=`string`||!r.attemptId||typeof r.choice!=`string`||!r.choice?$(`Choose one of the available sign-in options.`):{ok:!0,value:await t.answer(r.choice,r.attemptId)}:n===`cancel`?!jr(r)||Object.keys(r).length!==1||typeof r.attemptId!=`string`||!r.attemptId?$(`Choose an active SIWC sign-in attempt.`):{ok:!0,value:await t.cancel(r.attemptId)}:n===`logout`?Mr(r)?{ok:!0,value:await t.logout()}:$(`SIWC logout takes no parameters.`):$(`Unknown SIWC Settings action.`)}catch(t){let r=hr(t);return e.logger.warn(`SIWC Settings action %s failed: %s`,n,r),{ok:!1,error:{code:`siwc/action-failed`,message:r,details:{}}}}}function Pr(e,t){for(let n of[`status`,`authorize`,`answer`,`cancel`,`logout`])e.connection.fetch.register({path:`/api/siwc/${n}`,methods:[`POST`],requestBody:`buffered`,async fetch(r){if(r.headers.get(`content-type`)?.split(`;`,1)[0]?.trim()!==`application/json`)return new Response(`Expected application/json`,{status:415});let i;try{i=await r.json()}catch{return new Response(`Invalid JSON`,{status:400})}let a=ie.safeParse(i);if(!a.success||a.data.method!==`siwc/${n}`)return new Response(`Invalid SIWC request`,{status:400});let{rpcId:o,payload:s}=a.data,c=await Nr(e,t,n,s,r.signal);return Response.json({type:`server-response`,rpcId:o,result:c},{headers:{"cache-control":`no-store`}})}})}const Fr=`siwc`,Ir=[`credentials`,`authorization`,`llm`],Lr=t.object({searchModel:t.string().default(``).volatile()}),Rr=[`0.2.1-rc.2`,`0.2.2-alpha.2`,`0.2.2-alpha.3`,`0.2.2-rc.5`];async function zr(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 cr(i)}catch(t){if(!(t instanceof $n)&&!(t instanceof er)&&!(t instanceof q))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 Br(t,n){let r=e();Rr.includes(r)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,Rr.join(`, `),r);let i=new mr(t.credentials),a=new Tr(t,i);t.llm.registerAdapter([`openai`],a),t.inject([`web`],e=>{e.web.registerSearchProvider(Ar(i,()=>n.searchModel.get()))});let o=new gr(t,i,()=>a.sync());t.effect(()=>()=>o.dispose()),t.inject([`connection`],e=>Pr(e,o)),t.inject([`settings`],e=>{e.effect(()=>e.settings.configure({auto:!1},t.fiber))}),t.effect(()=>t.authorization.registerFlow({key:X,label:`ChatGPT plan`,methods:[{id:`oauth`,label:`Continue with ChatGPT`},{id:`select`,label:`Switch saved account`}],run:e=>o.authorizeSession(e)})),await zr(t,i),await a.sync()}export{Lr as Config,Br as apply,Ir as inject,Fr as name};
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "dsh-siwc",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Sign in with ChatGPT for DeepSeek Harness",
5
5
  "keywords": [
6
6
  "dsh",
7
7
  "deepseek-harness"
8
8
  ],
9
- "homepage": "https://github.com/ph0ryn/dsh-plugins#readme",
9
+ "homepage": "https://github.com/ph0ryn/dsh-plugins/tree/main/packages/siwc#readme",
10
10
  "bugs": {
11
11
  "url": "https://github.com/ph0ryn/dsh-plugins/issues"
12
12
  },
@@ -36,26 +36,27 @@
36
36
  "openai": "^7.19.0"
37
37
  },
38
38
  "peerDependencies": {
39
- "@deepseek-ai/cordis": "^4.0.5-alpha.1",
40
- "@deepseek-ai/dsh-app-boot": "^0.2.1-alpha.2",
41
- "@deepseek-ai/dsh-atomic-write": "^0.2.1-alpha.2",
42
- "@deepseek-ai/dsh-attachment": "^0.2.1-alpha.2",
43
- "@deepseek-ai/dsh-authorization": "^0.2.1-alpha.2",
44
- "@deepseek-ai/dsh-client-connection": "^0.2.1-alpha.2",
45
- "@deepseek-ai/dsh-commands": "^0.2.1-alpha.2",
46
- "@deepseek-ai/dsh-credentials": "^0.2.1-alpha.2",
47
- "@deepseek-ai/dsh-fs": "^0.2.1-alpha.2",
48
- "@deepseek-ai/dsh-home-paths": "^0.2.1-alpha.2",
49
- "@deepseek-ai/dsh-llm": "^0.2.1-alpha.2",
50
- "@deepseek-ai/dsh-llm-pi-ai": "^0.2.1-alpha.2",
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"
39
+ "@deepseek-ai/cordis": "^4.0.5",
40
+ "@deepseek-ai/dsh-app-boot": "^0.2.1-rc.2",
41
+ "@deepseek-ai/dsh-atomic-write": "^0.2.1-rc.2",
42
+ "@deepseek-ai/dsh-attachment": "^0.2.1-rc.2",
43
+ "@deepseek-ai/dsh-authorization": "^0.2.1-rc.2",
44
+ "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.2",
45
+ "@deepseek-ai/dsh-credentials": "^0.2.1-rc.2",
46
+ "@deepseek-ai/dsh-fs": "^0.2.1-rc.2",
47
+ "@deepseek-ai/dsh-home-paths": "^0.2.1-rc.2",
48
+ "@deepseek-ai/dsh-llm": "^0.2.1-rc.2",
49
+ "@deepseek-ai/dsh-llm-pi-ai": "^0.2.1-rc.2",
50
+ "@deepseek-ai/dsh-settings": "^0.2.1-rc.2",
51
+ "@deepseek-ai/dsh-web": "^0.2.1-rc.2",
52
+ "@deepseek-ai/schemastery": "~3.18.5"
55
53
  },
56
54
  "engines": {
57
55
  "node": ">=22.19.0"
58
56
  },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
59
60
  "dsh": {
60
61
  "client": {
61
62
  "platform": "web",