sliccy 3.30.0 → 3.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/ui/assets/adobe-CNsjY_V1.js +2 -0
  2. package/dist/ui/assets/adobe-q1ynSkgJ.js +1 -0
  3. package/dist/ui/assets/{agent-bridge-B47ORnu8.js → agent-bridge-DaY3lEr8.js} +1 -1
  4. package/dist/ui/assets/{agent-message-to-chat-CivM5iVI.js → agent-message-to-chat-QxmVsZHN.js} +1 -1
  5. package/dist/ui/assets/{anthropic-B8x_-x-6.js → anthropic-BcxNFOMf.js} +1 -1
  6. package/dist/ui/assets/{anthropic-BIPAKMlm.js → anthropic-C29fNa0p.js} +1 -1
  7. package/dist/ui/assets/{apps-BIbLhrlo.js → apps-DEr5_QVi.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-CxXU2gBi.js → azure-openai-BOAQMret.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-NCIJ99-Z.js → azure-openai-BgjK3tAI.js} +1 -1
  10. package/dist/ui/assets/{azure-openai-responses-Cl168K30.js → azure-openai-responses-B_ZHPZQ_.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-responses-Dsb2dVcl.js → azure-openai-responses-D9aG5ZZZ.js} +1 -1
  12. package/dist/ui/assets/{biome_wasm-CDybUpcY.js → biome_wasm-DFR1VZSE.js} +1 -1
  13. package/dist/ui/assets/{bsh-watchdog-Ct8X8nj0.js → bsh-watchdog-DOvowpMJ.js} +1 -1
  14. package/dist/ui/assets/{cdp-CQNRG1L7.js → cdp-DLzkpHPR.js} +3 -3
  15. package/dist/ui/assets/{cdp-ws-page-bridge-TbT2oOFP.js → cdp-ws-page-bridge-DbNf5VhA.js} +1 -1
  16. package/dist/ui/assets/{common-Dp2LMvPs.js → common-Ce3nKdPG.js} +1 -1
  17. package/dist/ui/assets/{connect-surface-6Xdk8gty.js → connect-surface-BfntsfUz.js} +1 -1
  18. package/dist/ui/assets/cost-command-CfSpaR6u.js +1 -0
  19. package/dist/ui/assets/{es-BZcvk2vu.js → es-Gkir_CGN.js} +1 -1
  20. package/dist/ui/assets/{follower-sprinkle-bridge-BZOJjwi5.js → follower-sprinkle-bridge-Bsb9Um7I.js} +1 -1
  21. package/dist/ui/assets/{github-T4vTwz6j.js → github-C2uMRSdr.js} +1 -1
  22. package/dist/ui/assets/{github-copilot-DJhJjjGT.js → github-copilot-BdAJesOB.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-DCNfM6__.js → github-copilot-DsrWwQfK.js} +2 -2
  24. package/dist/ui/assets/{github-CB-1cuiS.js → github-tMItzRHe.js} +2 -2
  25. package/dist/ui/assets/{google-CjogI3dp.js → google-BCVpl33Q.js} +1 -1
  26. package/dist/ui/assets/{google-Zk-hhREr.js → google-BJtxAJct.js} +1 -1
  27. package/dist/ui/assets/{google-shared-CjuxcHRG.js → google-shared-BEVjYKj2.js} +1 -1
  28. package/dist/ui/assets/{google-shared-D4TYGikU.js → google-shared-CaucmB5i.js} +1 -1
  29. package/dist/ui/assets/{google-vertex-DbzvO7wH.js → google-vertex-BrfIL2f8.js} +1 -1
  30. package/dist/ui/assets/{google-vertex-D_IdMTe5.js → google-vertex-Di3B-unZ.js} +1 -1
  31. package/dist/ui/assets/{intercepted-oauth-B7FJFo6o.js → intercepted-oauth-Ap0NXgFY.js} +1 -1
  32. package/dist/ui/assets/{kernel-worker-CwwcfcWb.js → kernel-worker-aL7clsM2.js} +21 -21
  33. package/dist/ui/assets/{lick-ws-bridge-CCyIzWKp.js → lick-ws-bridge-2FLXq2tY.js} +1 -1
  34. package/dist/ui/assets/{local-llm-liuOe0zO.js → local-llm-CABjY-eT.js} +1 -1
  35. package/dist/ui/assets/{magick-wasm-DNjpr8Jr.js → magick-wasm-DojPv_bG.js} +1 -1
  36. package/dist/ui/assets/{main-DMvYmz_A.js → main-BtoNCPyQ.js} +9 -9
  37. package/dist/ui/assets/main-D683Koa8.css +1 -0
  38. package/dist/ui/assets/{main-cherry-D_banPZS.js → main-cherry-BtqehQbg.js} +1 -1
  39. package/dist/ui/assets/{mistral-RYfQO4J8.js → mistral-D13sQ4B4.js} +1 -1
  40. package/dist/ui/assets/{mistral-BD2ee9tA.js → mistral-DmQtCAV6.js} +1 -1
  41. package/dist/ui/assets/{nodejs-ChSC5wtq.js → nodejs-CqTAsRQj.js} +1 -1
  42. package/dist/ui/assets/{nuke-command-rYpivCHk.js → nuke-command-WSharcWR.js} +1 -1
  43. package/dist/ui/assets/{oauth-cX4Ramn1.js → oauth-C6A6yZED.js} +1 -1
  44. package/dist/ui/assets/{oauth-bootstrap-C7RP8P8x.js → oauth-bootstrap-ac4aWs2_.js} +2 -2
  45. package/dist/ui/assets/{oauth-service-sz6K_MqP.js → oauth-service-0c_TknIC.js} +1 -1
  46. package/dist/ui/assets/{oauth-service-C2C92amm.js → oauth-service-7-jMR6uA.js} +1 -1
  47. package/dist/ui/assets/{offscreen-client-kZ_-M9GL.js → offscreen-client-ltzgalb5.js} +1 -1
  48. package/dist/ui/assets/{onboarding-orchestrator-5vX8kVLy.js → onboarding-orchestrator-BOYZUUXo.js} +1 -1
  49. package/dist/ui/assets/{openai-codex-DpKepxN6.js → openai-codex-BvRU1nKe.js} +1 -1
  50. package/dist/ui/assets/{openai-codex-IvPx6ZBR.js → openai-codex-CfooJWr6.js} +1 -1
  51. package/dist/ui/assets/{openai-codex-responses-BLeLjsUM.js → openai-codex-responses-Cb4wO_aM.js} +1 -1
  52. package/dist/ui/assets/{openai-codex-responses-D_-qBZSC.js → openai-codex-responses-DxuvnQBg.js} +1 -1
  53. package/dist/ui/assets/{openai-completions-BcTP1T3o.js → openai-completions-DkS2zVD3.js} +1 -1
  54. package/dist/ui/assets/{openai-responses-Dapme5mJ.js → openai-responses-C4PfIrGV.js} +1 -1
  55. package/dist/ui/assets/{openai-responses-BccakAos.js → openai-responses-FJRVWCAN.js} +1 -1
  56. package/dist/ui/assets/{openai-responses-shared-DQ2Zhc3v.js → openai-responses-shared-BYmbH8Nn.js} +1 -1
  57. package/dist/ui/assets/{openai-responses-shared-CDgUSOrg.js → openai-responses-shared-C3n9ip32.js} +1 -1
  58. package/dist/ui/assets/{openrouter-CC-WqU96.js → openrouter-B7t4AFIg.js} +1 -1
  59. package/dist/ui/assets/{openrouter-B2q2ipL6.js → openrouter-D_bhNbxi.js} +1 -1
  60. package/dist/ui/assets/{panel-rpc-handlers-GJ90xyvC.js → panel-rpc-handlers-B5pMQ8y2.js} +1 -1
  61. package/dist/ui/assets/{provider-DVHbmHE-.js → provider-D86wGnIQ.js} +2 -2
  62. package/dist/ui/assets/{provider-DQLLbpL2.js → provider-Dy70twsR.js} +1 -1
  63. package/dist/ui/assets/provider-store-access-D_YGmkw4.js +1 -0
  64. package/dist/ui/assets/provider-store-access-iZ8Jszhq.js +1 -0
  65. package/dist/ui/assets/{proxied-fetch-CQfWbSFy.js → proxied-fetch-CAbygDUy.js} +1 -1
  66. package/dist/ui/assets/{pyodide-DbbP0Z2Z.js → pyodide-Cj1nQzdj.js} +2 -2
  67. package/dist/ui/assets/{remote-terminal-view-DCOs0LA6.js → remote-terminal-view-Di-2iBd0.js} +1 -1
  68. package/dist/ui/assets/{secret-env-BltiZf1i.js → secret-env-Kl69LC-B.js} +1 -1
  69. package/dist/ui/assets/{slicc-editor-BmgJU73Z.js → slicc-editor-BpfdHOM4.js} +1 -1
  70. package/dist/ui/assets/{spawn-SKmFRfBn.js → spawn-D7jaToJ9.js} +1 -1
  71. package/dist/ui/assets/{sql-wasm-7mGRTB92.js → sql-wasm-rW6OuYUy.js} +1 -1
  72. package/dist/ui/assets/{store-BL9yDBxi.js → store-BYZoB9Pz.js} +1 -1
  73. package/dist/ui/assets/{tray-leave-runtime-Bbl_QlKA.js → tray-leave-runtime-Bl06YhqQ.js} +1 -1
  74. package/dist/ui/assets/{typescript-lrBWKZhg.js → typescript-BGABsOjF.js} +1 -1
  75. package/dist/ui/assets/{upgrade-detection-vmj6wvLl.js → upgrade-detection-D6N4MRCp.js} +1 -1
  76. package/dist/ui/assets/{web-BGNRUVyk.js → web-DUSjmrph.js} +1 -1
  77. package/dist/ui/assets/{ws-subscribers-BVEk6KlP.js → ws-subscribers-Ctp0G6_t.js} +1 -1
  78. package/dist/ui/assets/{xai-grok-DCg21mqz.js → xai-grok-COpIZ456.js} +1 -1
  79. package/dist/ui/assets/{xai-grok-CfV2xtIC.js → xai-grok-DIrGQApI.js} +1 -1
  80. package/dist/ui/index.html +2 -2
  81. package/dist/ui/packages/webapp/index.html +2 -2
  82. package/package.json +1 -1
  83. package/dist/ui/assets/adobe-BY1zH2zg.js +0 -1
  84. package/dist/ui/assets/adobe-DWr7bwoG.js +0 -2
  85. package/dist/ui/assets/cost-command-BBWgCx9X.js +0 -1
  86. package/dist/ui/assets/main-BxXY3xQw.css +0 -1
  87. package/dist/ui/assets/provider-store-access-8En9BwpM.js +0 -1
  88. package/dist/ui/assets/provider-store-access-pZUdvcTQ.js +0 -1
@@ -1 +1 @@
1
- import{dt as e}from"./kernel-worker-CwwcfcWb.js";const t=e(`mcp-oauth`);async function n(e,n,r){let i=new URL(e).origin,a=n??`${i}/.well-known/oauth-protected-resource`,o=null,s=null;t.debug(`Fetching PRM`,{prmUrl:a});try{let e=await r(a,{headers:{Accept:`application/json`}});if(!e.ok)s=`${e.status} ${e.statusText}`;else{let t=await e.json();!t.authorization_servers||t.authorization_servers.length===0?s=`lists no authorization_servers`:o=t}}catch(e){s=e instanceof Error?e.message:String(e)}let c,l,u;o?.authorization_servers&&o.authorization_servers.length>0?(c=o.authorization_servers[0].replace(/\/+$/,``),l=`${c}/.well-known/oauth-authorization-server`,u=`prm`,t.debug(`Discovery via PRM`,{prmUrl:a,asmUrl:l})):(c=i,l=`${i}/.well-known/oauth-authorization-server`,u=`asm-origin-fallback`,t.debug(`PRM unavailable; falling back to ASM at server origin`,{prmUrl:a,prmReason:s,asmUrl:l}));let d=null,f=null;t.debug(`Fetching ASM`,{asmUrl:l});try{let e=await r(l,{headers:{Accept:`application/json`}});e.ok?d=await e.json():f=`${e.status} ${e.statusText}`}catch(e){f=e instanceof Error?e.message:String(e)}if(!d)throw Error(u===`asm-origin-fallback`?`MCP OAuth discovery failed. PRM (${a}): ${s}. ASM fallback (${l}): ${f}.`:`ASM fetch failed: ${f} (${l})`);if(!d.authorization_endpoint||!d.token_endpoint)throw Error(u===`asm-origin-fallback`?`MCP OAuth discovery failed. PRM (${a}): ${s}. ASM fallback (${l}) is missing required endpoints (authorization_endpoint, token_endpoint).`:`ASM at ${l} is missing required endpoints`);return{issuer:d.issuer||c,authorizationEndpoint:d.authorization_endpoint,tokenEndpoint:d.token_endpoint,registrationEndpoint:d.registration_endpoint,supportedScopes:d.scopes_supported??o?.scopes_supported,codeChallengeMethods:d.code_challenge_methods_supported,grantTypes:d.grant_types_supported,discoveryPath:u}}async function r(e,t,n){if(!e.registrationEndpoint)throw Error(`Authorization server does not advertise a registration_endpoint (RFC 7591)`);let r=e.grantTypes,i=r&&r.length>0&&!r.includes(`refresh_token`)?[`authorization_code`]:[`authorization_code`,`refresh_token`],a=JSON.stringify({client_name:`SLICC`,redirect_uris:[t],token_endpoint_auth_method:`none`,grant_types:i,response_types:[`code`]}),o=await n(e.registrationEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:a});if(!o.ok)throw Error(`DCR failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw Error(`DCR response missing client_id`);return{clientId:s.client_id,registrationClientUri:s.registration_client_uri}}function i(e){return!e||e.length===0||e.includes(`S256`)?`S256`:e.includes(`plain`)?`plain`:`S256`}function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function o(e){let t=new Uint8Array(32);crypto.getRandomValues(t);let n=a(t);if(e===`plain`)return{codeVerifier:n,codeChallenge:n,method:e};let r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return{codeVerifier:n,codeChallenge:a(new Uint8Array(r)),method:e}}function s(e){try{let t=new URL(e);return{code:t.searchParams.get(`code`),state:t.searchParams.get(`state`)}}catch{return{code:null,state:null}}}async function c(e){let t=await o(i(e.asMetadata.codeChallengeMethods)),n=a(crypto.getRandomValues(new Uint8Array(16))),r=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:t.codeChallenge,code_challenge_method:t.method,state:n});e.scope&&r.set(`scope`,e.scope);let c=`${e.asMetadata.authorizationEndpoint}?${r.toString()}`,l=await e.launcher(c);if(!l)throw Error(`MCP OAuth flow cancelled or timed out`);let{code:d,state:f}=s(l);if(!d)throw Error("MCP OAuth redirect missing `code` parameter");if(f!==n)throw Error(`MCP OAuth state mismatch — possible CSRF`);return u({tokenEndpoint:e.asMetadata.tokenEndpoint,clientId:e.clientId,code:d,codeVerifier:t.codeVerifier,redirectUri:e.redirectUri,fetchImpl:e.fetchImpl})}function l(e){if(e.error||!e.access_token)throw Error(`Token endpoint error: ${e.error??`no_access_token`}${e.error_description?` — ${e.error_description}`:``}`);return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:e.expires_in?Date.now()+e.expires_in*1e3:void 0,scope:e.scope,tokenType:e.token_type}}async function u(e){let t=new URLSearchParams({grant_type:`authorization_code`,code:e.code,redirect_uri:e.redirectUri,client_id:e.clientId,code_verifier:e.codeVerifier}).toString(),n=await e.fetchImpl(e.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:t}),r=await n.json();if(!n.ok&&!r.access_token)throw Error(`Token exchange failed: ${n.status} ${n.statusText}${r.error?` (${r.error})`:``}`);return l(r)}async function d(e){let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});e.scope&&t.set(`scope`,e.scope);let n=await e.fetchImpl(e.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:t.toString()}),r=await n.json();if(!n.ok&&!r.access_token)throw Error(`Token refresh failed: ${n.status} ${n.statusText}${r.error?` (${r.error})`:``}`);return l(r)}export{n as discoverAuth,r as dynamicRegister,d as refreshAccessToken,c as runAuthFlow};
1
+ import{dt as e}from"./kernel-worker-aL7clsM2.js";const t=e(`mcp-oauth`);async function n(e,n,r){let i=new URL(e).origin,a=n??`${i}/.well-known/oauth-protected-resource`,o=null,s=null;t.debug(`Fetching PRM`,{prmUrl:a});try{let e=await r(a,{headers:{Accept:`application/json`}});if(!e.ok)s=`${e.status} ${e.statusText}`;else{let t=await e.json();!t.authorization_servers||t.authorization_servers.length===0?s=`lists no authorization_servers`:o=t}}catch(e){s=e instanceof Error?e.message:String(e)}let c,l,u;o?.authorization_servers&&o.authorization_servers.length>0?(c=o.authorization_servers[0].replace(/\/+$/,``),l=`${c}/.well-known/oauth-authorization-server`,u=`prm`,t.debug(`Discovery via PRM`,{prmUrl:a,asmUrl:l})):(c=i,l=`${i}/.well-known/oauth-authorization-server`,u=`asm-origin-fallback`,t.debug(`PRM unavailable; falling back to ASM at server origin`,{prmUrl:a,prmReason:s,asmUrl:l}));let d=null,f=null;t.debug(`Fetching ASM`,{asmUrl:l});try{let e=await r(l,{headers:{Accept:`application/json`}});e.ok?d=await e.json():f=`${e.status} ${e.statusText}`}catch(e){f=e instanceof Error?e.message:String(e)}if(!d)throw Error(u===`asm-origin-fallback`?`MCP OAuth discovery failed. PRM (${a}): ${s}. ASM fallback (${l}): ${f}.`:`ASM fetch failed: ${f} (${l})`);if(!d.authorization_endpoint||!d.token_endpoint)throw Error(u===`asm-origin-fallback`?`MCP OAuth discovery failed. PRM (${a}): ${s}. ASM fallback (${l}) is missing required endpoints (authorization_endpoint, token_endpoint).`:`ASM at ${l} is missing required endpoints`);return{issuer:d.issuer||c,authorizationEndpoint:d.authorization_endpoint,tokenEndpoint:d.token_endpoint,registrationEndpoint:d.registration_endpoint,supportedScopes:d.scopes_supported??o?.scopes_supported,codeChallengeMethods:d.code_challenge_methods_supported,grantTypes:d.grant_types_supported,discoveryPath:u}}async function r(e,t,n){if(!e.registrationEndpoint)throw Error(`Authorization server does not advertise a registration_endpoint (RFC 7591)`);let r=e.grantTypes,i=r&&r.length>0&&!r.includes(`refresh_token`)?[`authorization_code`]:[`authorization_code`,`refresh_token`],a=JSON.stringify({client_name:`SLICC`,redirect_uris:[t],token_endpoint_auth_method:`none`,grant_types:i,response_types:[`code`]}),o=await n(e.registrationEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:a});if(!o.ok)throw Error(`DCR failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw Error(`DCR response missing client_id`);return{clientId:s.client_id,registrationClientUri:s.registration_client_uri}}function i(e){return!e||e.length===0||e.includes(`S256`)?`S256`:e.includes(`plain`)?`plain`:`S256`}function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function o(e){let t=new Uint8Array(32);crypto.getRandomValues(t);let n=a(t);if(e===`plain`)return{codeVerifier:n,codeChallenge:n,method:e};let r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return{codeVerifier:n,codeChallenge:a(new Uint8Array(r)),method:e}}function s(e){try{let t=new URL(e);return{code:t.searchParams.get(`code`),state:t.searchParams.get(`state`)}}catch{return{code:null,state:null}}}async function c(e){let t=await o(i(e.asMetadata.codeChallengeMethods)),n=a(crypto.getRandomValues(new Uint8Array(16))),r=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:t.codeChallenge,code_challenge_method:t.method,state:n});e.scope&&r.set(`scope`,e.scope);let c=`${e.asMetadata.authorizationEndpoint}?${r.toString()}`,l=await e.launcher(c);if(!l)throw Error(`MCP OAuth flow cancelled or timed out`);let{code:d,state:f}=s(l);if(!d)throw Error("MCP OAuth redirect missing `code` parameter");if(f!==n)throw Error(`MCP OAuth state mismatch — possible CSRF`);return u({tokenEndpoint:e.asMetadata.tokenEndpoint,clientId:e.clientId,code:d,codeVerifier:t.codeVerifier,redirectUri:e.redirectUri,fetchImpl:e.fetchImpl})}function l(e){if(e.error||!e.access_token)throw Error(`Token endpoint error: ${e.error??`no_access_token`}${e.error_description?` — ${e.error_description}`:``}`);return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:e.expires_in?Date.now()+e.expires_in*1e3:void 0,scope:e.scope,tokenType:e.token_type}}async function u(e){let t=new URLSearchParams({grant_type:`authorization_code`,code:e.code,redirect_uri:e.redirectUri,client_id:e.clientId,code_verifier:e.codeVerifier}).toString(),n=await e.fetchImpl(e.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:t}),r=await n.json();if(!n.ok&&!r.access_token)throw Error(`Token exchange failed: ${n.status} ${n.statusText}${r.error?` (${r.error})`:``}`);return l(r)}async function d(e){let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});e.scope&&t.set(`scope`,e.scope);let n=await e.fetchImpl(e.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:t.toString()}),r=await n.json();if(!n.ok&&!r.access_token)throw Error(`Token refresh failed: ${n.status} ${n.statusText}${r.error?` (${r.error})`:``}`);return l(r)}export{n as discoverAuth,r as dynamicRegister,d as refreshAccessToken,c as runAuthFlow};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-DVHbmHE-.js","assets/main-DMvYmz_A.js","assets/modulepreload-polyfill-Dezn_h7o.js","assets/main-BxXY3xQw.css","assets/global-db-CbuLl-zx.js"])))=>i.map(i=>d[i]);
2
- import{A as e,F as t,f as n,it as r,r as i}from"./main-DMvYmz_A.js";var a=t(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:e}=await r(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-DVHbmHE-.js`);return{ensureAllMcpProvidersRegistered:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();t.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:t.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let t=i();a.info(`Bootstrap OAuth replicas`,{count:t.length});for(let r of t){if(!r.accessToken){a.debug(`Skipping account without token`,{providerId:r.providerId});continue}if((r.tokenExpiresAt??1/0)-Date.now()<=o){let t=e(r.providerId);if(t?.onSilentRenew)try{if(await t.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:r.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:r.providerId});continue}catch(e){a.warn(`Silent renewal failed`,{providerId:r.providerId,error:e instanceof Error?e.message:String(e)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:r.providerId});continue}try{await n({providerId:r.providerId,accessToken:r.accessToken,refreshToken:r.refreshToken,tokenExpiresAt:r.tokenExpiresAt,userName:r.userName,userAvatar:r.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:r.providerId})}catch(e){a.error(`OAuth bootstrap failed`,{providerId:r.providerId,error:e instanceof Error?e.message:String(e)})}}}export{s as bootstrapOAuthReplicas};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-D86wGnIQ.js","assets/main-BtoNCPyQ.js","assets/modulepreload-polyfill-Dezn_h7o.js","assets/main-D683Koa8.css","assets/global-db-CbuLl-zx.js"])))=>i.map(i=>d[i]);
2
+ import{A as e,F as t,f as n,it as r,r as i}from"./main-BtoNCPyQ.js";var a=t(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:e}=await r(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-D86wGnIQ.js`);return{ensureAllMcpProvidersRegistered:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();t.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:t.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let t=i();a.info(`Bootstrap OAuth replicas`,{count:t.length});for(let r of t){if(!r.accessToken){a.debug(`Skipping account without token`,{providerId:r.providerId});continue}if((r.tokenExpiresAt??1/0)-Date.now()<=o){let t=e(r.providerId);if(t?.onSilentRenew)try{if(await t.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:r.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:r.providerId});continue}catch(e){a.warn(`Silent renewal failed`,{providerId:r.providerId,error:e instanceof Error?e.message:String(e)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:r.providerId});continue}try{await n({providerId:r.providerId,accessToken:r.accessToken,refreshToken:r.refreshToken,tokenExpiresAt:r.tokenExpiresAt,userName:r.userName,userAvatar:r.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:r.providerId})}catch(e){a.error(`OAuth bootstrap failed`,{providerId:r.providerId,error:e instanceof Error?e.message:String(e)})}}}export{s as bootstrapOAuthReplicas};
@@ -1 +1 @@
1
- import{M as e,it as t}from"./main-DMvYmz_A.js";var n=12e4;function r(e,t){return t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}#`)}function i(e){return e.endsWith(`*`)?e:`${e}*`}function a(e,t){if(!t||t.length===0)return e;let n=e;for(let e of t)if(n.includes(e.match)){if(e.replaceUrl){n=e.replaceUrl;continue}if(e.appendParams)try{let t=new URL(n);for(let[n,r]of Object.entries(e.appendParams))t.searchParams.set(n,r);n=t.toString()}catch{}}return n}function o(e){return async t=>{let o=t.timeoutMs??n,s=t.rewrite??[],c=t.onCapture??`close`,l,u,d=!1,f=null,p=async()=>{if(u){try{await e.send(`Fetch.disable`,{},u)}catch{}try{await e.send(`Target.detachFromTarget`,{sessionId:u})}catch{}}if(l&&c===`close`)try{await e.send(`Target.closeTarget`,{targetId:l})}catch{}};return await new Promise(n=>{let c=async t=>{d||(d=!0,clearTimeout(h),e.off(`Fetch.requestPaused`,m),await p(),n(t))},m=n=>{let i=n;if(!i?.request?.url||!u||(typeof n.sessionId==`string`?n.sessionId:void 0)!==u)return;if(r(i.request.url,t.redirectUriPattern)){f=i.request.url,e.send(`Fetch.failRequest`,{requestId:i.requestId,errorReason:`Aborted`},u).catch(()=>{}),c(f);return}let o=a(i.request.url,s);if(o!==i.request.url){e.send(`Fetch.continueRequest`,{requestId:i.requestId,url:o},u).catch(e=>{console.warn(`[intercepted-oauth] continueRequest (rewrite) failed:`,e instanceof Error?e.message:String(e))});return}e.send(`Fetch.continueRequest`,{requestId:i.requestId},u).catch(()=>{})},h=setTimeout(()=>{c(null)},o);(async()=>{try{l=(await e.send(`Target.createTarget`,{url:`about:blank`})).targetId,u=(await e.send(`Target.attachToTarget`,{targetId:l,flatten:!0})).sessionId,e.on(`Fetch.requestPaused`,m),await e.send(`Fetch.enable`,{patterns:[{urlPattern:i(t.redirectUriPattern),requestStage:`Request`},...s.map(e=>({urlPattern:`*${e.match}*`,requestStage:`Request`}))]},u),await e.send(`Page.navigate`,{url:t.authorizeUrl},u)}catch(e){console.error(`[intercepted-oauth] setup failed:`,e instanceof Error?e.message:String(e)),c(null)}})()})}}var s=typeof chrome<`u`&&!!chrome?.runtime?.id;function c(){return s?h:typeof window>`u`?f:p}async function l(){let e=await u();return e?o(e):null}async function u(){try{let{getActiveCdpTransport:e}=await t(async()=>{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return{getActiveCdpTransport:e}},[]);return await e()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function d(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let t=e();if(!t)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await t.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function f(t){let n=e();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.call(`oauth-popup`,{url:t},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function p(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=null,o=()=>{r||(r=!0,window.removeEventListener(`message`,s),clearTimeout(c),i&&clearInterval(i),a&&clearInterval(a))},s=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(o(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,s),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(o(),n.error){console.error(`[oauth-service] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),n&&(a=setInterval(()=>{n.closed&&(clearInterval(a),a=null,setTimeout(()=>{r||(o(),t(null))},1500))},500));let c=setTimeout(()=>{o();try{n?.close()}catch{}t(null)},12e4)})}async function m(e,t=180*1e3){if(typeof window>`u`||s)return;let n=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!n){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let r=setTimeout(()=>{clearInterval(i);try{n.close()}catch{}e()},t),i=setInterval(()=>{n.closed&&(clearTimeout(r),clearInterval(i),e())},500)})}async function h(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{l as createInterceptingOAuthLauncherForCurrentRuntime,c as createOAuthLauncher,d as getOAuthPageOrigin,m as openIdpLogoutUrl};
1
+ import{M as e,it as t}from"./main-BtoNCPyQ.js";var n=12e4;function r(e,t){return t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}#`)}function i(e){return e.endsWith(`*`)?e:`${e}*`}function a(e,t){if(!t||t.length===0)return e;let n=e;for(let e of t)if(n.includes(e.match)){if(e.replaceUrl){n=e.replaceUrl;continue}if(e.appendParams)try{let t=new URL(n);for(let[n,r]of Object.entries(e.appendParams))t.searchParams.set(n,r);n=t.toString()}catch{}}return n}function o(e){return async t=>{let o=t.timeoutMs??n,s=t.rewrite??[],c=t.onCapture??`close`,l,u,d=!1,f=null,p=async()=>{if(u){try{await e.send(`Fetch.disable`,{},u)}catch{}try{await e.send(`Target.detachFromTarget`,{sessionId:u})}catch{}}if(l&&c===`close`)try{await e.send(`Target.closeTarget`,{targetId:l})}catch{}};return await new Promise(n=>{let c=async t=>{d||(d=!0,clearTimeout(h),e.off(`Fetch.requestPaused`,m),await p(),n(t))},m=n=>{let i=n;if(!i?.request?.url||!u||(typeof n.sessionId==`string`?n.sessionId:void 0)!==u)return;if(r(i.request.url,t.redirectUriPattern)){f=i.request.url,e.send(`Fetch.failRequest`,{requestId:i.requestId,errorReason:`Aborted`},u).catch(()=>{}),c(f);return}let o=a(i.request.url,s);if(o!==i.request.url){e.send(`Fetch.continueRequest`,{requestId:i.requestId,url:o},u).catch(e=>{console.warn(`[intercepted-oauth] continueRequest (rewrite) failed:`,e instanceof Error?e.message:String(e))});return}e.send(`Fetch.continueRequest`,{requestId:i.requestId},u).catch(()=>{})},h=setTimeout(()=>{c(null)},o);(async()=>{try{l=(await e.send(`Target.createTarget`,{url:`about:blank`})).targetId,u=(await e.send(`Target.attachToTarget`,{targetId:l,flatten:!0})).sessionId,e.on(`Fetch.requestPaused`,m),await e.send(`Fetch.enable`,{patterns:[{urlPattern:i(t.redirectUriPattern),requestStage:`Request`},...s.map(e=>({urlPattern:`*${e.match}*`,requestStage:`Request`}))]},u),await e.send(`Page.navigate`,{url:t.authorizeUrl},u)}catch(e){console.error(`[intercepted-oauth] setup failed:`,e instanceof Error?e.message:String(e)),c(null)}})()})}}var s=typeof chrome<`u`&&!!chrome?.runtime?.id;function c(){return s?h:typeof window>`u`?f:p}async function l(){let e=await u();return e?o(e):null}async function u(){try{let{getActiveCdpTransport:e}=await t(async()=>{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return{getActiveCdpTransport:e}},[]);return await e()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function d(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let t=e();if(!t)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await t.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function f(t){let n=e();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.call(`oauth-popup`,{url:t},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function p(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=null,o=()=>{r||(r=!0,window.removeEventListener(`message`,s),clearTimeout(c),i&&clearInterval(i),a&&clearInterval(a))},s=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(o(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,s),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(o(),n.error){console.error(`[oauth-service] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),n&&(a=setInterval(()=>{n.closed&&(clearInterval(a),a=null,setTimeout(()=>{r||(o(),t(null))},1500))},500));let c=setTimeout(()=>{o();try{n?.close()}catch{}t(null)},12e4)})}async function m(e,t=180*1e3){if(typeof window>`u`||s)return;let n=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!n){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let r=setTimeout(()=>{clearInterval(i);try{n.close()}catch{}e()},t),i=setInterval(()=>{n.closed&&(clearTimeout(r),clearInterval(i),e())},500)})}async function h(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{l as createInterceptingOAuthLauncherForCurrentRuntime,c as createOAuthLauncher,d as getOAuthPageOrigin,m as openIdpLogoutUrl};
@@ -1 +1 @@
1
- import{rt as e}from"./kernel-worker-CwwcfcWb.js";import{t}from"./intercepted-oauth-B7FJFo6o.js";const n=typeof chrome<`u`&&!!chrome?.runtime?.id;function r(){return n?u:typeof window>`u`?s:c}async function i(){let e=await a();return e?t(e):null}async function a(){try{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return await e()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function o(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let t=e();if(!t)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await t.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function s(t){let n=e();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.call(`oauth-popup`,{url:t},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function c(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=null,o=()=>{r||(r=!0,window.removeEventListener(`message`,s),clearTimeout(c),i&&clearInterval(i),a&&clearInterval(a))},s=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(o(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,s),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(o(),n.error){console.error(`[oauth-service] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),n&&(a=setInterval(()=>{n.closed&&(clearInterval(a),a=null,setTimeout(()=>{r||(o(),t(null))},1500))},500));let c=setTimeout(()=>{o();try{n?.close()}catch{}t(null)},12e4)})}async function l(e,t=180*1e3){if(typeof window>`u`||n)return;let r=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!r){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let n=setTimeout(()=>{clearInterval(i);try{r.close()}catch{}e()},t),i=setInterval(()=>{r.closed&&(clearTimeout(n),clearInterval(i),e())},500)})}async function u(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{i as createInterceptingOAuthLauncherForCurrentRuntime,r as createOAuthLauncher,o as getOAuthPageOrigin,l as openIdpLogoutUrl};
1
+ import{rt as e}from"./kernel-worker-aL7clsM2.js";import{t}from"./intercepted-oauth-Ap0NXgFY.js";const n=typeof chrome<`u`&&!!chrome?.runtime?.id;function r(){return n?u:typeof window>`u`?s:c}async function i(){let e=await a();return e?t(e):null}async function a(){try{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return await e()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function o(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let t=e();if(!t)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await t.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function s(t){let n=e();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.call(`oauth-popup`,{url:t},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function c(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=null,o=()=>{r||(r=!0,window.removeEventListener(`message`,s),clearTimeout(c),i&&clearInterval(i),a&&clearInterval(a))},s=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(o(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,s),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(o(),n.error){console.error(`[oauth-service] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),n&&(a=setInterval(()=>{n.closed&&(clearInterval(a),a=null,setTimeout(()=>{r||(o(),t(null))},1500))},500));let c=setTimeout(()=>{o();try{n?.close()}catch{}t(null)},12e4)})}async function l(e,t=180*1e3){if(typeof window>`u`||n)return;let r=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!r){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let n=setTimeout(()=>{clearInterval(i);try{r.close()}catch{}e()},t),i=setInterval(()=>{r.closed&&(clearTimeout(n),clearInterval(i),e())},500)})}async function u(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{i as createInterceptingOAuthLauncherForCurrentRuntime,r as createOAuthLauncher,o as getOAuthPageOrigin,l as openIdpLogoutUrl};
@@ -1 +1 @@
1
- import{F as e,S as t,w as n}from"./main-DMvYmz_A.js";var r=e(`panel-transport`);function i(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function a(){return{onMessage:e=>{let t=(t,n,r)=>(i(t)&&e(t),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:e=>{chrome.runtime.sendMessage({source:`panel`,payload:e}).catch(e=>{r.error(`failed to send to offscreen`,{error:e instanceof Error?e.message:String(e)})})}}}var o=e(`offscreen-client`),s=class{eventListeners=new Set;callbacks;scoops=[];scoopStatuses=new Map;currentMessageId=new Map;ready=!1;stateRetryTimer=null;localFs=null;pendingClearAcks=new Map;transport;_selectedScoopJid=null;get selectedScoopJid(){return this._selectedScoopJid}scoopSelectedListeners=new Set;onScoopSelected(e){return this.scoopSelectedListeners.add(e),()=>{this.scoopSelectedListeners.delete(e)}}setSelectedScoopJid(e){if(this._selectedScoopJid!==e&&(this._selectedScoopJid=e,e!==null))for(let t of this.scoopSelectedListeners)try{t(e)}catch(e){o.error(`onScoopSelected handler threw`,{error:e instanceof Error?e.message:String(e)})}}locked=!1;constructor(e,t){this.callbacks=e,this.transport=t??a(),this.setupMessageListener()}setLocalFS(e){this.localFs=e}createAgentHandle(){return{sendMessage:(e,t,n)=>{if(!this.selectedScoopJid){this.emitToUI({type:`error`,error:`No scoop selected`});return}this.send({type:`user-message`,scoopJid:this.selectedScoopJid,text:e,attachments:n,messageId:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`})},onEvent:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e)),stop:()=>{this.selectedScoopJid&&this.send({type:`abort`,scoopJid:this.selectedScoopJid})}}}getScoops(){return this.scoops}getScoop(e){return this.scoops.find(t=>t.jid===e)}isProcessing(e){return this.scoopStatuses.get(e)===`processing`}async registerScoop(e){if(!e.isCone)throw Error(`OffscreenClient.registerScoop is cone-only; use scoop_scoop for non-cone scoops`);this.scoops.find(t=>t.name===e.name)||(this.scoops.push(e),this.scoopStatuses.set(e.jid,`initializing`)),this.send({type:`cone-create`,name:e.name})}async unregisterScoop(e){this.send({type:`scoop-drop`,scoopJid:e}),this.scoops=this.scoops.filter(t=>t.jid!==e),this.scoopStatuses.delete(e)}createScoopTab(e){}async getGlobalMemory(){if(!this.localFs)return``;try{let e=await this.localFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});return typeof e==`string`?e:new TextDecoder().decode(e)}catch{return``}}getScoopContext(e){if(this.localFs)return{getFS:()=>this.localFs}}getSharedFS(){return this.localFs}stopScoop(e){this.send({type:`abort`,scoopJid:e})}async clearQueuedMessages(e){}async deleteQueuedMessage(e,t){}updateModel(){this.send({type:`refresh-model`})}setLocked(e){this.locked=e}setScoopThinkingLevel(e,t){this.send({type:`set-thinking-level`,scoopJid:e,level:t})}async clearAllMessages(){let e=`clear-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,t=new Promise(t=>{this.pendingClearAcks.set(e,t)});this.send({type:`clear-chat`,requestId:e}),await Promise.race([t,new Promise(e=>setTimeout(e,5e3))]),this.pendingClearAcks.delete(e)}clearFilesystem(){this.send({type:`clear-filesystem`})}requestScoopMessages(e){this.send({type:`request-scoop-messages`,scoopJid:e})}requestState(){this.send({type:`request-state`});let e=0;this.stateRetryTimer=setInterval(()=>{if(e++,this.ready||e>20){this.stateRetryTimer&&=(clearInterval(this.stateRetryTimer),null);return}o.debug(`Retrying request-state`,{attempt:e}),this.send({type:`request-state`})},500)}isReady(){return this.ready}sprinkleOpHandler=null;forwardLickHandler=null;sendSprinkleLick(e,t,n,r){this.send({type:`sprinkle-lick`,sprinkleName:e,body:t,targetScoop:n,originLabel:r})}sendWebhookEvent(e,t,n){this.send({type:`lick-webhook-event`,webhookId:e,headers:t,body:n})}sendSetFollowerForwarding(e){this.send({type:`set-follower-forwarding`,enabled:e})}sendForwardedLick(e){this.send({type:`inject-forwarded-lick`,event:e})}setForwardLickHandler(e){this.forwardLickHandler=e}sendCherryHostEvent(e,t,n){this.send({type:`lick-cherry-host-event`,cherryRuntimeId:e,name:t,detail:n})}setSprinkleOpHandler(e){this.sprinkleOpHandler=e}sendRaw(e){this.send(e)}setupMessageListener(){this.transport.onMessage(e=>{if(e.source!==`offscreen`)return;let t=e.payload;t?.type===`sprinkle-op`&&this.sprinkleOpHandler?this.sprinkleOpHandler(t):this.handleOffscreenMessage(e.payload)})}handleOffscreenMessage(e){switch(e.type){case`offscreen-ready`:this.ready?(o.warn(`Offscreen restarted — re-requesting state`),this.ready=!1):o.info(`Offscreen engine ready`),this.send({type:`request-state`});break;case`agent-event`:this.handleAgentEvent(e);break;case`scoop-status`:this.handleScoopStatus(e);break;case`compaction-state`:this.callbacks.onCompactionStateChange?.(e.scoopJid,e.state);break;case`clear-chat-ack`:{let t=this.pendingClearAcks.get(e.requestId);t&&(this.pendingClearAcks.delete(e.requestId),t());break}case`scoop-created`:this.handleScoopCreated(e);break;case`scoop-list`:this.handleScoopList(e);break;case`state-snapshot`:this.handleStateSnapshot(e);break;case`error`:this.handleError(e);break;case`incoming-message`:this.handleIncomingMessage(e);break;case`scoop-messages-replaced`:{let t=e;this.callbacks.onScoopMessagesReplaced?.(t.scoopJid,t.messages);break}case`tray-runtime-status`:{let t=e;l(t.leader,t.follower);break}case`forward-lick`:this.forwardLickHandler?.(e.event);break;case`terminal-status`:case`terminal-output`:case`terminal-media-preview`:case`terminal-exit`:case`terminal-cleared`:for(let t of this.terminalEventListeners)try{t(e)}catch(e){o.error(`terminal event listener error`,{error:e instanceof Error?e.message:String(e)})}break}}terminalEventListeners=new Set;onTerminalEvent(e){return this.terminalEventListeners.add(e),()=>this.terminalEventListeners.delete(e)}handleAgentEvent(e){if(e.scoopJid===this.selectedScoopJid)switch(e.eventType){case`text_delta`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let t=this.currentMessageId.get(e.scoopJid);t&&this.emitToUI({type:`tool_result`,messageId:t,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let t=this.currentMessageId.get(e.scoopJid);t&&this.emitToUI({type:`tool_ui_done`,messageId:t,requestId:e.requestId??``});break}case`response_done`:{let t=this.currentMessageId.get(e.scoopJid);t&&(this.emitToUI({type:`content_done`,messageId:t}),this.currentMessageId.delete(e.scoopJid));break}case`turn_end`:{let t=this.currentMessageId.get(e.scoopJid)??`done-${e.scoopJid}-${c()}`;this.currentMessageId.delete(e.scoopJid),this.emitToUI({type:`turn_end`,messageId:t});break}}}handleScoopStatus(e){this.scoopStatuses.set(e.scoopJid,e.status),this.callbacks.onStatusChange(e.scoopJid,e.status)}handleScoopCreated(e){let t=this.msgScoopToRegistered(e.scoop);this.scoops=this.scoops.filter(e=>e.name!==t.name||e.jid===t.jid),this.scoops.find(e=>e.jid===t.jid)||this.scoops.push(t),this.scoopStatuses.set(t.jid,e.scoop.status),this.callbacks.onScoopCreated(t)}handleScoopList(e){this.scoops=e.scoops.map(e=>this.msgScoopToRegistered(e));for(let t of e.scoops)this.scoopStatuses.set(t.jid,t.status);this.callbacks.onScoopListUpdate(e.scoops)}handleStateSnapshot(e){o.info(`Received state snapshot`,{scoopCount:e.scoops.length}),this.scoops=e.scoops.map(e=>this.msgScoopToRegistered(e));for(let t of e.scoops)this.scoopStatuses.set(t.jid,t.status);e.trayRuntimeStatus&&l(e.trayRuntimeStatus.leader,e.trayRuntimeStatus.follower);let t=!this.ready;t&&(this.ready=!0,this.stateRetryTimer&&=(clearInterval(this.stateRetryTimer),null)),this.callbacks.onScoopListUpdate(e.scoops),t&&this.callbacks.onReady?.()}handleError(e){e.scoopJid===this.selectedScoopJid&&this.emitToUI({type:`error`,error:e.error})}handleIncomingMessage(e){this.callbacks.onIncomingMessage(e.scoopJid,e.message)}msgScoopToRegistered(e){return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,type:e.isCone?`cone`:`scoop`,requiresTrigger:!e.isCone,assistantLabel:e.assistantLabel,addedAt:new Date().toISOString(),...e.config?{config:{...e.config}}:{}}}emitToUI(e){for(let t of this.eventListeners)try{t(e)}catch(e){o.error(`Listener error`,{error:e instanceof Error?e.message:String(e)})}}send(e){if(this.locked){this.emitToUI({type:`error`,error:`This window is detached. Close it and use the detached tab.`});return}this.transport.send(e)}};function c(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function l(e,r){n({state:e.state,error:e.error,reconnectAttempts:e.reconnectAttempts,session:e.session?{...e.session}:null}),t({state:r.state,joinUrl:r.joinUrl,trayId:r.trayId,error:r.error,lastError:r.lastError,reconnectAttempts:r.reconnectAttempts,attachAttempts:r.attachAttempts,lastAttachCode:r.lastAttachCode,connectingSince:r.connectingSince,lastPingTime:r.lastPingTime})}export{s as OffscreenClient};
1
+ import{F as e,S as t,w as n}from"./main-BtoNCPyQ.js";var r=e(`panel-transport`);function i(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function a(){return{onMessage:e=>{let t=(t,n,r)=>(i(t)&&e(t),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:e=>{chrome.runtime.sendMessage({source:`panel`,payload:e}).catch(e=>{r.error(`failed to send to offscreen`,{error:e instanceof Error?e.message:String(e)})})}}}var o=e(`offscreen-client`),s=class{eventListeners=new Set;callbacks;scoops=[];scoopStatuses=new Map;currentMessageId=new Map;ready=!1;stateRetryTimer=null;localFs=null;pendingClearAcks=new Map;transport;_selectedScoopJid=null;get selectedScoopJid(){return this._selectedScoopJid}scoopSelectedListeners=new Set;onScoopSelected(e){return this.scoopSelectedListeners.add(e),()=>{this.scoopSelectedListeners.delete(e)}}setSelectedScoopJid(e){if(this._selectedScoopJid!==e&&(this._selectedScoopJid=e,e!==null))for(let t of this.scoopSelectedListeners)try{t(e)}catch(e){o.error(`onScoopSelected handler threw`,{error:e instanceof Error?e.message:String(e)})}}locked=!1;constructor(e,t){this.callbacks=e,this.transport=t??a(),this.setupMessageListener()}setLocalFS(e){this.localFs=e}createAgentHandle(){return{sendMessage:(e,t,n)=>{if(!this.selectedScoopJid){this.emitToUI({type:`error`,error:`No scoop selected`});return}this.send({type:`user-message`,scoopJid:this.selectedScoopJid,text:e,attachments:n,messageId:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`})},onEvent:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e)),stop:()=>{this.selectedScoopJid&&this.send({type:`abort`,scoopJid:this.selectedScoopJid})}}}getScoops(){return this.scoops}getScoop(e){return this.scoops.find(t=>t.jid===e)}isProcessing(e){return this.scoopStatuses.get(e)===`processing`}async registerScoop(e){if(!e.isCone)throw Error(`OffscreenClient.registerScoop is cone-only; use scoop_scoop for non-cone scoops`);this.scoops.find(t=>t.name===e.name)||(this.scoops.push(e),this.scoopStatuses.set(e.jid,`initializing`)),this.send({type:`cone-create`,name:e.name})}async unregisterScoop(e){this.send({type:`scoop-drop`,scoopJid:e}),this.scoops=this.scoops.filter(t=>t.jid!==e),this.scoopStatuses.delete(e)}createScoopTab(e){}async getGlobalMemory(){if(!this.localFs)return``;try{let e=await this.localFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});return typeof e==`string`?e:new TextDecoder().decode(e)}catch{return``}}getScoopContext(e){if(this.localFs)return{getFS:()=>this.localFs}}getSharedFS(){return this.localFs}stopScoop(e){this.send({type:`abort`,scoopJid:e})}async clearQueuedMessages(e){}async deleteQueuedMessage(e,t){}updateModel(){this.send({type:`refresh-model`})}setLocked(e){this.locked=e}setScoopThinkingLevel(e,t){this.send({type:`set-thinking-level`,scoopJid:e,level:t})}async clearAllMessages(){let e=`clear-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,t=new Promise(t=>{this.pendingClearAcks.set(e,t)});this.send({type:`clear-chat`,requestId:e}),await Promise.race([t,new Promise(e=>setTimeout(e,5e3))]),this.pendingClearAcks.delete(e)}clearFilesystem(){this.send({type:`clear-filesystem`})}requestScoopMessages(e){this.send({type:`request-scoop-messages`,scoopJid:e})}requestState(){this.send({type:`request-state`});let e=0;this.stateRetryTimer=setInterval(()=>{if(e++,this.ready||e>20){this.stateRetryTimer&&=(clearInterval(this.stateRetryTimer),null);return}o.debug(`Retrying request-state`,{attempt:e}),this.send({type:`request-state`})},500)}isReady(){return this.ready}sprinkleOpHandler=null;forwardLickHandler=null;sendSprinkleLick(e,t,n,r){this.send({type:`sprinkle-lick`,sprinkleName:e,body:t,targetScoop:n,originLabel:r})}sendWebhookEvent(e,t,n){this.send({type:`lick-webhook-event`,webhookId:e,headers:t,body:n})}sendSetFollowerForwarding(e){this.send({type:`set-follower-forwarding`,enabled:e})}sendForwardedLick(e){this.send({type:`inject-forwarded-lick`,event:e})}setForwardLickHandler(e){this.forwardLickHandler=e}sendCherryHostEvent(e,t,n){this.send({type:`lick-cherry-host-event`,cherryRuntimeId:e,name:t,detail:n})}setSprinkleOpHandler(e){this.sprinkleOpHandler=e}sendRaw(e){this.send(e)}setupMessageListener(){this.transport.onMessage(e=>{if(e.source!==`offscreen`)return;let t=e.payload;t?.type===`sprinkle-op`&&this.sprinkleOpHandler?this.sprinkleOpHandler(t):this.handleOffscreenMessage(e.payload)})}handleOffscreenMessage(e){switch(e.type){case`offscreen-ready`:this.ready?(o.warn(`Offscreen restarted — re-requesting state`),this.ready=!1):o.info(`Offscreen engine ready`),this.send({type:`request-state`});break;case`agent-event`:this.handleAgentEvent(e);break;case`scoop-status`:this.handleScoopStatus(e);break;case`compaction-state`:this.callbacks.onCompactionStateChange?.(e.scoopJid,e.state);break;case`clear-chat-ack`:{let t=this.pendingClearAcks.get(e.requestId);t&&(this.pendingClearAcks.delete(e.requestId),t());break}case`scoop-created`:this.handleScoopCreated(e);break;case`scoop-list`:this.handleScoopList(e);break;case`state-snapshot`:this.handleStateSnapshot(e);break;case`error`:this.handleError(e);break;case`incoming-message`:this.handleIncomingMessage(e);break;case`scoop-messages-replaced`:{let t=e;this.callbacks.onScoopMessagesReplaced?.(t.scoopJid,t.messages);break}case`tray-runtime-status`:{let t=e;l(t.leader,t.follower);break}case`forward-lick`:this.forwardLickHandler?.(e.event);break;case`terminal-status`:case`terminal-output`:case`terminal-media-preview`:case`terminal-exit`:case`terminal-cleared`:for(let t of this.terminalEventListeners)try{t(e)}catch(e){o.error(`terminal event listener error`,{error:e instanceof Error?e.message:String(e)})}break}}terminalEventListeners=new Set;onTerminalEvent(e){return this.terminalEventListeners.add(e),()=>this.terminalEventListeners.delete(e)}handleAgentEvent(e){if(e.scoopJid===this.selectedScoopJid)switch(e.eventType){case`text_delta`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let t=this.currentMessageId.get(e.scoopJid);t&&this.emitToUI({type:`tool_result`,messageId:t,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let t=this.currentMessageId.get(e.scoopJid);t&&this.emitToUI({type:`tool_ui_done`,messageId:t,requestId:e.requestId??``});break}case`response_done`:{let t=this.currentMessageId.get(e.scoopJid);t&&(this.emitToUI({type:`content_done`,messageId:t}),this.currentMessageId.delete(e.scoopJid));break}case`turn_end`:{let t=this.currentMessageId.get(e.scoopJid)??`done-${e.scoopJid}-${c()}`;this.currentMessageId.delete(e.scoopJid),this.emitToUI({type:`turn_end`,messageId:t});break}}}handleScoopStatus(e){this.scoopStatuses.set(e.scoopJid,e.status),this.callbacks.onStatusChange(e.scoopJid,e.status)}handleScoopCreated(e){let t=this.msgScoopToRegistered(e.scoop);this.scoops=this.scoops.filter(e=>e.name!==t.name||e.jid===t.jid),this.scoops.find(e=>e.jid===t.jid)||this.scoops.push(t),this.scoopStatuses.set(t.jid,e.scoop.status),this.callbacks.onScoopCreated(t)}handleScoopList(e){this.scoops=e.scoops.map(e=>this.msgScoopToRegistered(e));for(let t of e.scoops)this.scoopStatuses.set(t.jid,t.status);this.callbacks.onScoopListUpdate(e.scoops)}handleStateSnapshot(e){o.info(`Received state snapshot`,{scoopCount:e.scoops.length}),this.scoops=e.scoops.map(e=>this.msgScoopToRegistered(e));for(let t of e.scoops)this.scoopStatuses.set(t.jid,t.status);e.trayRuntimeStatus&&l(e.trayRuntimeStatus.leader,e.trayRuntimeStatus.follower);let t=!this.ready;t&&(this.ready=!0,this.stateRetryTimer&&=(clearInterval(this.stateRetryTimer),null)),this.callbacks.onScoopListUpdate(e.scoops),t&&this.callbacks.onReady?.()}handleError(e){e.scoopJid===this.selectedScoopJid&&this.emitToUI({type:`error`,error:e.error})}handleIncomingMessage(e){this.callbacks.onIncomingMessage(e.scoopJid,e.message)}msgScoopToRegistered(e){return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,type:e.isCone?`cone`:`scoop`,requiresTrigger:!e.isCone,assistantLabel:e.assistantLabel,addedAt:new Date().toISOString(),...e.config?{config:{...e.config}}:{}}}emitToUI(e){for(let t of this.eventListeners)try{t(e)}catch(e){o.error(`Listener error`,{error:e instanceof Error?e.message:String(e)})}}send(e){if(this.locked){this.emitToUI({type:`error`,error:`This window is detached. Close it and use the detached tab.`});return}this.transport.send(e)}};function c(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function l(e,r){n({state:e.state,error:e.error,reconnectAttempts:e.reconnectAttempts,session:e.session?{...e.session}:null}),t({state:r.state,joinUrl:r.joinUrl,trayId:r.trayId,error:r.error,lastError:r.lastError,reconnectAttempts:r.reconnectAttempts,attachAttempts:r.attachAttempts,lastAttachCode:r.lastAttachCode,connectingSince:r.connectingSince,lastPingTime:r.lastPingTime})}export{s as OffscreenClient};
@@ -1 +1 @@
1
- import{C as e,F as t}from"./main-DMvYmz_A.js";var n={openai:{url:e=>`${(e??`https://api.openai.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},anthropic:{url:e=>`${(e??`https://api.anthropic.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({"x-api-key":e,"anthropic-version":`2023-06-01`})},groq:{url:e=>`${(e??`https://api.groq.com/openai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},cerebras:{url:e=>`${(e??`https://api.cerebras.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},mistral:{url:e=>`${(e??`https://api.mistral.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},"x-ai":{url:e=>`${(e??`https://api.x.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},deepseek:{url:e=>`${(e??`https://api.deepseek.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},openrouter:{url:e=>`${(e??`https://openrouter.ai/api`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},google:{url:e=>`${(e??`https://generativelanguage.googleapis.com`).replace(/\/$/,``)}/v1beta/models`,headers:()=>({})}};function r(e,t){if(e===401||e===403)return`Authentication failed — the key was rejected by the provider.`;if(e===404)return`Endpoint not found — check the base URL.`;if(e===429)return`Rate-limited — try again in a moment.`;if(e>=500)return`Provider returned a server error.`;let n=t.trim();return n?`${e}: ${n.slice(0,160)}`:`Provider responded with HTTP ${e}.`}async function i(e){let{provider:t,apiKey:i,baseUrl:a,signal:o}=e,s=e.fetchImpl??fetch,c=i.trim();if(!c)return{kind:`failed`,status:null,message:`API key is empty.`};let l=n[t];if(!l)return{kind:`skipped`,reason:`No live validation available for "${t}" — saving without testing.`};let u=l.url(a);if(t===`google`){let e=u.includes(`?`)?`&`:`?`;u=`${u}${e}key=${encodeURIComponent(c)}`}try{let e=await s(u,{method:`GET`,headers:l.headers(c),signal:o});if(e.ok)return{kind:`ok`};let t=``;try{t=await e.text()}catch{}return e.status===401||e.status,{kind:`failed`,status:e.status,message:r(e.status,t)}}catch(e){if(e?.name===`AbortError`)throw e;return{kind:`skipped`,reason:`Couldn't reach the provider (${e instanceof Error?e.message:String(e)}). Saving without live test — you can retry from Settings.`}}}var a=[e=>`Nice to meet you, ${e}.`,e=>`Hello ${e} — glad you stopped by.`,e=>`Hey ${e}, welcome aboard.`,e=>`${e}! Pleasure to make your acquaintance.`],o=[`Nice to meet you, mysterious stranger — I'll respect the incognito.`,`Hello, anonymous traveler. You can always tell me your name later if you change your mind.`,`An unnamed visitor — intriguing. Whenever you'd like to introduce yourself, just say the word.`,`Hey there, ghost — happy to keep things first-name-optional. The door's always open if you decide to drop the cloak.`],s={work:[`Work mode — let's make today productive.`,`On the clock? Same. Let's chip away at it.`],school:[`School business — I love a good study session.`,`Hitting the books? Glad to ride along.`],personal:[`Personal project energy is the best kind.`,`Tinkering for yourself is how the good stuff happens.`],"side-project":[`Side projects keep the lights on creatively.`,`Two-job life — respect.`],exploring:[`Just poking around? Excellent. The best discoveries start there.`,`Exploration mode — no agenda, no pressure.`]},c={developer:[`I can write code, run shell commands, drive a real browser, and ship pages.`,`Code, terminals, browsers, repos — I live in all of them.`],designer:[`I can prototype layouts, generate assets, and walk page editors with you.`,`Pixels, components, screenshots — design ops are my jam.`],"content-creator":[`I can draft copy, edit, scrape references, and stitch publish-ready pages.`,`Words, structure, SEO, polish — say the topic and I'll get moving.`],marketer:[`I can audit funnels, scrape competitors, and stand up landing pages quickly.`,`Campaigns, analytics, creatives — plug me in and I'll go.`],"product-pm":[`I can summarise research, draft specs, and crunch competitive intel.`,`Briefs, roadmaps, comparisons — I take the boring half off your plate.`],founder:[`I can prototype landing pages, automate ops, and prep investor decks.`,`Idea → MVP → repeat. I'll do the legwork between coffee refills.`],student:[`I can read papers with you, draft notes, and turn lectures into outlines.`,`Studying together makes it bearable — let me handle the busywork.`],researcher:[`I can scrape sources, summarise findings, and keep a running bibliography.`,`Lit reviews, datasets, write-ups — I'm all in.`],other:[`I'm flexible — give me a task and I'll figure out the right tools.`,`Whatever the role, I can probably help. Tell me what's on the docket.`]},l=[`I can browse the web, run commands, write code, and automate the boring parts.`,`I'm comfortable with terminals, browsers, files, and a long backlog of skills.`],u=[`But to be honest, I'm not really an AI yet — I'm an empty shell. You'll need to help me become intelligent. Pick a model and I'll wake up:`,`Confession time: I can't actually think yet. Wire me up to an LLM and I'll start earning my keep:`,`Plot twist — there's no brain in here. Choose a provider so I can do more than read this script:`,`Truthfully? I'm a very polite placeholder until you give me a model. Help me out:`];function d(e,t){return e[Math.floor(t()*e.length)%e.length]}function f(e){return e.replace(/-/g,` `)}function p(e){if(e.length===0)return``;if(e.length===1)return e[0];if(e.length===2)return`${e[0]} and ${e[1]}`;let t=e[e.length-1];return`${e.slice(0,-1).join(`, `)}, and ${t}`}function m(e,t=Math.random){let n=(e.name||``).trim(),r=e.purpose?s[e.purpose]:void 0;return n?`${d(a,t)(n)}${r?` ${d(r,t)}`:``}`:`${d(o,t)}${r?` ${d(r,t)}`:``}`}function h(e,t=Math.random){let n=e.role&&c[e.role]?e.role:``,r=d(n?c[n]:l,t),i=(e.tasks??[]).slice(0,3).map(f);return`I'm sliccy. ${r}${i.length>0?` Especially handy for ${p(i)}.`:``} I'm an AI agent.`}function g(e,t=Math.random){return d(u,t)}function _(e,t=Math.random){return[m(e,t),h(e,t),g(e,t)]}var v=t(`onboarding-orchestrator`),y=class{deps;stage=`idle`;profile={};constructor(e){this.deps=e}getStage(){return this.stage}getProfile(){return{...this.profile}}handleFirstRun(){this.stage===`idle`&&(this.deps.postDipReference(`Welcome to SLICC — let's get you set up.`),this.deps.postDipReference(`![Welcome](/shared/sprinkles/welcome/welcome.shtml)`))}async handleOnboardingComplete(t){if(this.stage!==`idle`)return v.debug(`Ignoring duplicate onboarding-complete`,{stage:this.stage}),!0;this.profile=t??{},this.stage=`awaiting-connect`,e(this.deps.fs).catch(e=>v.warn(`recordWelcomed failed`,e)),this.persistProfile(this.profile).catch(e=>v.warn(`persistProfile failed`,e));let n=_(this.profile,this.deps.rand);for(let e of n)this.deps.postSystemMessage(e);return this.deps.postDipReference(`![Connect a model](/shared/sprinkles/welcome/connect-llm.shtml)`),!0}handleConnectReady(){if(this.stage===`complete`)return;let e=this.deps.getProviderCatalogue();this.deps.broadcastToDip({type:`slicc-providers`,providers:e.providers,models:e.models})}async handleConnectAttempt(e){if(this.stage===`complete`)return;this.stage=`connecting`;let{provider:t,apiKey:n,baseUrl:r,deployment:a,apiVersion:o,model:s}=e;if(!t||typeof n!=`string`||!n.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Provider and API key are required.`}),this.stage=`awaiting-connect`;return}let c=(()=>{try{return this.deps.getProviderCatalogue().providers.find(e=>e.id===t)}catch{return}})();if(c?.requiresDeployment&&!a?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${c.name} requires a deployment name.`}),this.stage=`awaiting-connect`;return}if(c?.requiresBaseUrl&&!r?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${c.name} requires a base URL.`}),this.stage=`awaiting-connect`;return}let l;try{l=await i({provider:t,apiKey:n.trim(),baseUrl:r??void 0,fetchImpl:this.deps.fetchImpl})}catch(e){v.warn(`validateApiKey threw`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Validation request was aborted.`}),this.stage=`awaiting-connect`;return}if(l.kind===`failed`){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:l.message}),this.stage=`awaiting-connect`;return}let u=s||null;if(!u)try{let e=this.deps.getProviderCatalogue().models?.[t]?.[0]?.id;e&&(u=e)}catch(e){v.warn(`Failed to resolve fallback model for provider`,{provider:t,err:e})}try{this.deps.saveAccount(t,n.trim(),r?.trim()||void 0,a?.trim()||void 0,o?.trim()||void 0),u&&this.deps.setSelectedModel(u)}catch(e){v.warn(`saveAccount failed`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Failed to save credentials locally.`}),this.stage=`awaiting-connect`;return}let d=l.kind===`skipped`?`Saved — ${l.reason}`:`Validated against the provider. Ready when you are.`;this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:l.kind,note:d});let f=u&&this.deps.resolveModelLabel?.(t,u)?this.deps.resolveModelLabel?.(t,u):u||null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:t,model:u??null,modelLabel:f,validation:l.kind}})}async handleOAuthAttempt(e){if(this.stage===`complete`)return;if(!this.deps.launchOAuth){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`OAuth login is not available in this runtime.`});return}this.stage=`connecting`;let t;try{t=await this.deps.launchOAuth(e.provider,e.baseUrl??null)}catch(e){v.warn(`launchOAuth threw`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:e instanceof Error?e.message:`Login was cancelled.`}),this.stage=`awaiting-connect`;return}if(!t.ok){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:t.message||`Login was cancelled.`}),this.stage=`awaiting-connect`;return}if(t.model)try{this.deps.setSelectedModel(t.model)}catch(e){v.warn(`setSelectedModel after OAuth failed`,e)}this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:`ok`,note:t.message||`Logged in.`});let n=t.model&&this.deps.resolveModelLabel?.(e.provider,t.model)?this.deps.resolveModelLabel?.(e.provider,t.model):t.model??null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:e.provider,model:t.model??null,modelLabel:n,validation:`oauth`}})}async persistProfile(e){let t=(e.name||`user`).toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||`user`;await this.deps.fs.writeFile(`/home/${t}/.welcome.json`,JSON.stringify(e,null,2))}};export{y as OnboardingOrchestrator};
1
+ import{C as e,F as t}from"./main-BtoNCPyQ.js";var n={openai:{url:e=>`${(e??`https://api.openai.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},anthropic:{url:e=>`${(e??`https://api.anthropic.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({"x-api-key":e,"anthropic-version":`2023-06-01`})},groq:{url:e=>`${(e??`https://api.groq.com/openai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},cerebras:{url:e=>`${(e??`https://api.cerebras.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},mistral:{url:e=>`${(e??`https://api.mistral.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},"x-ai":{url:e=>`${(e??`https://api.x.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},deepseek:{url:e=>`${(e??`https://api.deepseek.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},openrouter:{url:e=>`${(e??`https://openrouter.ai/api`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},google:{url:e=>`${(e??`https://generativelanguage.googleapis.com`).replace(/\/$/,``)}/v1beta/models`,headers:()=>({})}};function r(e,t){if(e===401||e===403)return`Authentication failed — the key was rejected by the provider.`;if(e===404)return`Endpoint not found — check the base URL.`;if(e===429)return`Rate-limited — try again in a moment.`;if(e>=500)return`Provider returned a server error.`;let n=t.trim();return n?`${e}: ${n.slice(0,160)}`:`Provider responded with HTTP ${e}.`}async function i(e){let{provider:t,apiKey:i,baseUrl:a,signal:o}=e,s=e.fetchImpl??fetch,c=i.trim();if(!c)return{kind:`failed`,status:null,message:`API key is empty.`};let l=n[t];if(!l)return{kind:`skipped`,reason:`No live validation available for "${t}" — saving without testing.`};let u=l.url(a);if(t===`google`){let e=u.includes(`?`)?`&`:`?`;u=`${u}${e}key=${encodeURIComponent(c)}`}try{let e=await s(u,{method:`GET`,headers:l.headers(c),signal:o});if(e.ok)return{kind:`ok`};let t=``;try{t=await e.text()}catch{}return e.status===401||e.status,{kind:`failed`,status:e.status,message:r(e.status,t)}}catch(e){if(e?.name===`AbortError`)throw e;return{kind:`skipped`,reason:`Couldn't reach the provider (${e instanceof Error?e.message:String(e)}). Saving without live test — you can retry from Settings.`}}}var a=[e=>`Nice to meet you, ${e}.`,e=>`Hello ${e} — glad you stopped by.`,e=>`Hey ${e}, welcome aboard.`,e=>`${e}! Pleasure to make your acquaintance.`],o=[`Nice to meet you, mysterious stranger — I'll respect the incognito.`,`Hello, anonymous traveler. You can always tell me your name later if you change your mind.`,`An unnamed visitor — intriguing. Whenever you'd like to introduce yourself, just say the word.`,`Hey there, ghost — happy to keep things first-name-optional. The door's always open if you decide to drop the cloak.`],s={work:[`Work mode — let's make today productive.`,`On the clock? Same. Let's chip away at it.`],school:[`School business — I love a good study session.`,`Hitting the books? Glad to ride along.`],personal:[`Personal project energy is the best kind.`,`Tinkering for yourself is how the good stuff happens.`],"side-project":[`Side projects keep the lights on creatively.`,`Two-job life — respect.`],exploring:[`Just poking around? Excellent. The best discoveries start there.`,`Exploration mode — no agenda, no pressure.`]},c={developer:[`I can write code, run shell commands, drive a real browser, and ship pages.`,`Code, terminals, browsers, repos — I live in all of them.`],designer:[`I can prototype layouts, generate assets, and walk page editors with you.`,`Pixels, components, screenshots — design ops are my jam.`],"content-creator":[`I can draft copy, edit, scrape references, and stitch publish-ready pages.`,`Words, structure, SEO, polish — say the topic and I'll get moving.`],marketer:[`I can audit funnels, scrape competitors, and stand up landing pages quickly.`,`Campaigns, analytics, creatives — plug me in and I'll go.`],"product-pm":[`I can summarise research, draft specs, and crunch competitive intel.`,`Briefs, roadmaps, comparisons — I take the boring half off your plate.`],founder:[`I can prototype landing pages, automate ops, and prep investor decks.`,`Idea → MVP → repeat. I'll do the legwork between coffee refills.`],student:[`I can read papers with you, draft notes, and turn lectures into outlines.`,`Studying together makes it bearable — let me handle the busywork.`],researcher:[`I can scrape sources, summarise findings, and keep a running bibliography.`,`Lit reviews, datasets, write-ups — I'm all in.`],other:[`I'm flexible — give me a task and I'll figure out the right tools.`,`Whatever the role, I can probably help. Tell me what's on the docket.`]},l=[`I can browse the web, run commands, write code, and automate the boring parts.`,`I'm comfortable with terminals, browsers, files, and a long backlog of skills.`],u=[`But to be honest, I'm not really an AI yet — I'm an empty shell. You'll need to help me become intelligent. Pick a model and I'll wake up:`,`Confession time: I can't actually think yet. Wire me up to an LLM and I'll start earning my keep:`,`Plot twist — there's no brain in here. Choose a provider so I can do more than read this script:`,`Truthfully? I'm a very polite placeholder until you give me a model. Help me out:`];function d(e,t){return e[Math.floor(t()*e.length)%e.length]}function f(e){return e.replace(/-/g,` `)}function p(e){if(e.length===0)return``;if(e.length===1)return e[0];if(e.length===2)return`${e[0]} and ${e[1]}`;let t=e[e.length-1];return`${e.slice(0,-1).join(`, `)}, and ${t}`}function m(e,t=Math.random){let n=(e.name||``).trim(),r=e.purpose?s[e.purpose]:void 0;return n?`${d(a,t)(n)}${r?` ${d(r,t)}`:``}`:`${d(o,t)}${r?` ${d(r,t)}`:``}`}function h(e,t=Math.random){let n=e.role&&c[e.role]?e.role:``,r=d(n?c[n]:l,t),i=(e.tasks??[]).slice(0,3).map(f);return`I'm sliccy. ${r}${i.length>0?` Especially handy for ${p(i)}.`:``} I'm an AI agent.`}function g(e,t=Math.random){return d(u,t)}function _(e,t=Math.random){return[m(e,t),h(e,t),g(e,t)]}var v=t(`onboarding-orchestrator`),y=class{deps;stage=`idle`;profile={};constructor(e){this.deps=e}getStage(){return this.stage}getProfile(){return{...this.profile}}handleFirstRun(){this.stage===`idle`&&(this.deps.postDipReference(`Welcome to SLICC — let's get you set up.`),this.deps.postDipReference(`![Welcome](/shared/sprinkles/welcome/welcome.shtml)`))}async handleOnboardingComplete(t){if(this.stage!==`idle`)return v.debug(`Ignoring duplicate onboarding-complete`,{stage:this.stage}),!0;this.profile=t??{},this.stage=`awaiting-connect`,e(this.deps.fs).catch(e=>v.warn(`recordWelcomed failed`,e)),this.persistProfile(this.profile).catch(e=>v.warn(`persistProfile failed`,e));let n=_(this.profile,this.deps.rand);for(let e of n)this.deps.postSystemMessage(e);return this.deps.postDipReference(`![Connect a model](/shared/sprinkles/welcome/connect-llm.shtml)`),!0}handleConnectReady(){if(this.stage===`complete`)return;let e=this.deps.getProviderCatalogue();this.deps.broadcastToDip({type:`slicc-providers`,providers:e.providers,models:e.models})}async handleConnectAttempt(e){if(this.stage===`complete`)return;this.stage=`connecting`;let{provider:t,apiKey:n,baseUrl:r,deployment:a,apiVersion:o,model:s}=e;if(!t||typeof n!=`string`||!n.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Provider and API key are required.`}),this.stage=`awaiting-connect`;return}let c=(()=>{try{return this.deps.getProviderCatalogue().providers.find(e=>e.id===t)}catch{return}})();if(c?.requiresDeployment&&!a?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${c.name} requires a deployment name.`}),this.stage=`awaiting-connect`;return}if(c?.requiresBaseUrl&&!r?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${c.name} requires a base URL.`}),this.stage=`awaiting-connect`;return}let l;try{l=await i({provider:t,apiKey:n.trim(),baseUrl:r??void 0,fetchImpl:this.deps.fetchImpl})}catch(e){v.warn(`validateApiKey threw`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Validation request was aborted.`}),this.stage=`awaiting-connect`;return}if(l.kind===`failed`){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:l.message}),this.stage=`awaiting-connect`;return}let u=s||null;if(!u)try{let e=this.deps.getProviderCatalogue().models?.[t]?.[0]?.id;e&&(u=e)}catch(e){v.warn(`Failed to resolve fallback model for provider`,{provider:t,err:e})}try{this.deps.saveAccount(t,n.trim(),r?.trim()||void 0,a?.trim()||void 0,o?.trim()||void 0),u&&this.deps.setSelectedModel(u)}catch(e){v.warn(`saveAccount failed`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Failed to save credentials locally.`}),this.stage=`awaiting-connect`;return}let d=l.kind===`skipped`?`Saved — ${l.reason}`:`Validated against the provider. Ready when you are.`;this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:l.kind,note:d});let f=u&&this.deps.resolveModelLabel?.(t,u)?this.deps.resolveModelLabel?.(t,u):u||null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:t,model:u??null,modelLabel:f,validation:l.kind}})}async handleOAuthAttempt(e){if(this.stage===`complete`)return;if(!this.deps.launchOAuth){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`OAuth login is not available in this runtime.`});return}this.stage=`connecting`;let t;try{t=await this.deps.launchOAuth(e.provider,e.baseUrl??null)}catch(e){v.warn(`launchOAuth threw`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:e instanceof Error?e.message:`Login was cancelled.`}),this.stage=`awaiting-connect`;return}if(!t.ok){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:t.message||`Login was cancelled.`}),this.stage=`awaiting-connect`;return}if(t.model)try{this.deps.setSelectedModel(t.model)}catch(e){v.warn(`setSelectedModel after OAuth failed`,e)}this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:`ok`,note:t.message||`Logged in.`});let n=t.model&&this.deps.resolveModelLabel?.(e.provider,t.model)?this.deps.resolveModelLabel?.(e.provider,t.model):t.model??null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:e.provider,model:t.model??null,modelLabel:n,validation:`oauth`}})}async persistProfile(e){let t=(e.name||`user`).toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||`user`;await this.deps.fs.writeFile(`/home/${t}/.welcome.json`,JSON.stringify(e,null,2))}};export{y as OnboardingOrchestrator};
@@ -1 +1 @@
1
- import{B as e,I as t,Q as n,W as r,w as i,y as a}from"./kernel-worker-CwwcfcWb.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return a().find(e=>e.providerId===o)}async function D(){let e=E();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await x(e.refreshToken);if(t?.access_token)return await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:u,userName:w(t.access_token),userAvatar:await T(t.access_token)}),t.access_token}return e.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const k=(e,n,i={})=>{let a=r();return(async()=>{try{let r=await D(),o=t({...e,baseUrl:u,api:d},n,{...i,apiKey:r,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(t,n,i)=>{let a=r();return(async()=>{try{let r=await D(),o=e({...t,baseUrl:u,api:d},n,{...i,apiKey:r,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(O(t,e)),a.end()}})(),a},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(e,t,n)=>{let r=_(),a=await v(r),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,n?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await e({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,r);await i({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),t()},onOAuthLogout:async()=>{await i({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=E();if(!e?.refreshToken)return null;let t=await x(e.refreshToken);return t?.access_token?(await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:u,userName:w(t.access_token),userAvatar:await T(t.access_token)}),t.access_token):null}};function M(){n({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
1
+ import{B as e,I as t,Q as n,W as r,w as i,y as a}from"./kernel-worker-aL7clsM2.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return a().find(e=>e.providerId===o)}async function D(){let e=E();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await x(e.refreshToken);if(t?.access_token)return await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:u,userName:w(t.access_token),userAvatar:await T(t.access_token)}),t.access_token}return e.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const k=(e,n,i={})=>{let a=r();return(async()=>{try{let r=await D(),o=t({...e,baseUrl:u,api:d},n,{...i,apiKey:r,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(t,n,i)=>{let a=r();return(async()=>{try{let r=await D(),o=e({...t,baseUrl:u,api:d},n,{...i,apiKey:r,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(O(t,e)),a.end()}})(),a},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(e,t,n)=>{let r=_(),a=await v(r),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,n?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await e({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,r);await i({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),t()},onOAuthLogout:async()=>{await i({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=E();if(!e?.refreshToken)return null;let t=await x(e.refreshToken);return t?.access_token?(await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:u,userName:w(t.access_token),userAvatar:await T(t.access_token)}),t.access_token):null}};function M(){n({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
@@ -1 +1 @@
1
- import{U as e,Z as t,at as n,f as r,q as i,r as a}from"./main-DMvYmz_A.js";var o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/authorize`,l=`https://auth.openai.com/oauth/token`,u=`openid profile email offline_access`,d=`http://localhost:1455/auth/callback`,f=`http://localhost:1455/auth/callback*`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${o}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));function v(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function y(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function b(){return v(y(32))}async function x(e){let t=new TextEncoder().encode(e);return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function S(){return v(y(16))}async function C(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:d}),r=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function w(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function T(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function E(e){let t=T(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function D(e){let t=T(e)?.[`https://api.openai.com/auth`],n=E(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function O(e){let t=E(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function k(){return a().find(e=>e.providerId===o)}async function A(){let e=k();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await w(e.refreshToken);if(t?.access_token)return await r({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token}return e.accessToken}function j(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var M=(n,r,i={})=>{let a=t();return(async()=>{try{let t=await A(),o=e({...n,baseUrl:p,api:m},r,{...i,apiKey:t,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(n,e)),a.end()}})(),a},N=(e,n,r)=>{let a=t();return(async()=>{try{let t=await A(),o=i({...e,baseUrl:p,api:m},n,{...r,apiKey:t,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(j(e,t)),a.end()}})(),a},P={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(e,t,n)=>{let i=b(),a=await x(i),l=S(),m=new URL(c);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,s),m.searchParams.set(`redirect_uri`,d),m.searchParams.set(`scope`,n?.scopes??u),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,l),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await e({authorizeUrl:m.toString(),redirectUriPattern:f,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),v=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(v!==l)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let y=await C(_,i);await r({providerId:o,accessToken:y.access_token,refreshToken:y.refresh_token,tokenExpiresAt:Date.now()+(y.expires_in??3600)*1e3,baseUrl:p,userName:D(y.access_token),userAvatar:await O(y.access_token)}),t()},onOAuthLogout:async()=>{await r({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=k();if(!e?.refreshToken)return null;let t=await w(e.refreshToken);return t?.access_token?(await r({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token):null}};function F(){n({api:h,stream:M,streamSimple:N})}export{P as config,F as register};
1
+ import{U as e,Z as t,at as n,f as r,q as i,r as a}from"./main-BtoNCPyQ.js";var o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/authorize`,l=`https://auth.openai.com/oauth/token`,u=`openid profile email offline_access`,d=`http://localhost:1455/auth/callback`,f=`http://localhost:1455/auth/callback*`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${o}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));function v(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function y(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function b(){return v(y(32))}async function x(e){let t=new TextEncoder().encode(e);return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function S(){return v(y(16))}async function C(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:d}),r=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function w(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function T(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function E(e){let t=T(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function D(e){let t=T(e)?.[`https://api.openai.com/auth`],n=E(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function O(e){let t=E(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function k(){return a().find(e=>e.providerId===o)}async function A(){let e=k();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await w(e.refreshToken);if(t?.access_token)return await r({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token}return e.accessToken}function j(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var M=(n,r,i={})=>{let a=t();return(async()=>{try{let t=await A(),o=e({...n,baseUrl:p,api:m},r,{...i,apiKey:t,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(n,e)),a.end()}})(),a},N=(e,n,r)=>{let a=t();return(async()=>{try{let t=await A(),o=i({...e,baseUrl:p,api:m},n,{...r,apiKey:t,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(j(e,t)),a.end()}})(),a},P={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(e,t,n)=>{let i=b(),a=await x(i),l=S(),m=new URL(c);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,s),m.searchParams.set(`redirect_uri`,d),m.searchParams.set(`scope`,n?.scopes??u),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,l),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await e({authorizeUrl:m.toString(),redirectUriPattern:f,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),v=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(v!==l)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let y=await C(_,i);await r({providerId:o,accessToken:y.access_token,refreshToken:y.refresh_token,tokenExpiresAt:Date.now()+(y.expires_in??3600)*1e3,baseUrl:p,userName:D(y.access_token),userAvatar:await O(y.access_token)}),t()},onOAuthLogout:async()=>{await r({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=k();if(!e?.refreshToken)return null;let t=await w(e.refreshToken);return t?.access_token?(await r({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token):null}};function F(){n({api:h,stream:M,streamSimple:N})}export{P as config,F as register};
@@ -1,4 +1,4 @@
1
- import{K as e,M as t,N as n,O as r,P as i,U as a,X as o,j as s,u as c}from"./kernel-worker-CwwcfcWb.js";import{n as l,r as u,t as d}from"./openai-responses-shared-DQ2Zhc3v.js";let f=null;const p=e=>import(e);typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&p(`node:os`).then(e=>{f=e});const m=1e3,h=new Set([`openai`,`openai-codex`,`opencode`]),g=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function _(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function v(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}const y=(e,n,r)=>{let i=new a;return(async()=>{let a={role:`assistant`,content:[],api:`openai-codex-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l=r?.apiKey||o(e.provider)||``;if(!l)throw Error(`No API key for provider: ${e.provider}`);let u=fe(l),d=ee(e,n,r),f=await r?.onPayload?.(d,e);f!==void 0&&(d=f);let p=r?.sessionId||pe(),h=me(e.headers,r?.headers,u,l,r?.sessionId),g=he(e.headers,r?.headers,u,l,p),y=JSON.stringify(d),b=r?.transport||`auto`,x=b!==`sse`&&R(r?.sessionId);if(x&&z(r?.sessionId),b!==`sse`&&!x){let n=!1;try{if(await ue(te(e.baseUrl),d,g,a,i,e,()=>{n=!0},r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:a.stopReason,message:a}),i.end();return}catch(e){if(r?.signal?.aborted||O(e)||(s(a,t(`provider_transport_failure`,e,{configuredTransport:b,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(y).byteLength})),re(r?.sessionId,e),n))throw e;z(r?.sessionId)}}let S,C;for(let t=0;t<=3;t++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{if(S=await fetch(w(e.baseUrl),{method:`POST`,headers:h,body:y,signal:r?.signal}),await r?.onResponse?.({status:S.status,headers:c(S.headers)},e),S.ok)break;let n=await S.text();if(t<3&&_(S.status,n)){let e=m*2**t,n=S.headers.get(`retry-after-ms`);if(n!==null){let t=Number(n);Number.isFinite(t)&&(e=Math.max(0,t))}else{let t=S.headers.get(`retry-after`);if(t){let n=Number(t);if(Number.isFinite(n))e=Math.max(0,n*1e3);else{let n=Date.parse(t);Number.isNaN(n)||(e=Math.max(0,n-Date.now()))}}}await v(e,r?.signal);continue}let i=await de(new Response(n,{status:S.status,statusText:S.statusText}));throw Error(i.friendlyMessage||i.message)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message===`Request was aborted`))throw Error(`Request was aborted`);if(C=e instanceof Error?e:Error(String(e)),t<3&&!C.message.includes(`usage limit`)){await v(m*2**t,r?.signal);continue}throw C}}if(!S?.ok)throw C??Error(`Failed after retries`);if(!S.body)throw Error(`No response body`);if(i.push({type:`start`,partial:a}),await T(S,a,i,e,r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:a.stopReason,message:a}),i.end()}catch(e){for(let e of a.content)delete e.partialJson;a.stopReason=r?.signal?.aborted?`aborted`:`error`,a.errorMessage=e instanceof Error?e.message:String(e),i.push({type:`error`,reason:a.stopReason,error:a}),i.end()}})(),i},b=(t,n,i)=>{let a=i?.apiKey||o(t.provider);if(!a)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,i,a),c=i?.reasoning?e(t,i.reasoning):void 0,l=c===`off`?void 0:c;return y(t,n,{...s,reasoningEffort:l})};function ee(e,t,n){let r=d(e,t,h,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:n?.sessionId,tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=l(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}function x(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function S(e,t,n){let r=x(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function C(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function w(e){let t=(e&&e.trim().length>0?e:`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function te(e){let t=new URL(w(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function T(e,t,n,r,i){await u(k(ne(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,r)})}var E=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},D=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function O(e){return e instanceof E||e instanceof D}async function*k(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let e=t.code||``;throw new E(`Codex error: ${t.message||e||JSON.stringify(t)}`,{code:e||void 0,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new E(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:A(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function A(e){if(typeof e==`string`)return g.has(e)?e:void 0}async function*ne(e){if(!e.body)return;let t=e.body.getReader(),r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;i+=r.decode(a,{stream:!0});let o=i.indexOf(`
1
+ import{K as e,M as t,N as n,O as r,P as i,U as a,X as o,j as s,u as c}from"./kernel-worker-aL7clsM2.js";import{n as l,r as u,t as d}from"./openai-responses-shared-BYmbH8Nn.js";let f=null;const p=e=>import(e);typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&p(`node:os`).then(e=>{f=e});const m=1e3,h=new Set([`openai`,`openai-codex`,`opencode`]),g=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function _(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function v(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}const y=(e,n,r)=>{let i=new a;return(async()=>{let a={role:`assistant`,content:[],api:`openai-codex-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l=r?.apiKey||o(e.provider)||``;if(!l)throw Error(`No API key for provider: ${e.provider}`);let u=fe(l),d=ee(e,n,r),f=await r?.onPayload?.(d,e);f!==void 0&&(d=f);let p=r?.sessionId||pe(),h=me(e.headers,r?.headers,u,l,r?.sessionId),g=he(e.headers,r?.headers,u,l,p),y=JSON.stringify(d),b=r?.transport||`auto`,x=b!==`sse`&&R(r?.sessionId);if(x&&z(r?.sessionId),b!==`sse`&&!x){let n=!1;try{if(await ue(te(e.baseUrl),d,g,a,i,e,()=>{n=!0},r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:a.stopReason,message:a}),i.end();return}catch(e){if(r?.signal?.aborted||O(e)||(s(a,t(`provider_transport_failure`,e,{configuredTransport:b,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(y).byteLength})),re(r?.sessionId,e),n))throw e;z(r?.sessionId)}}let S,C;for(let t=0;t<=3;t++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{if(S=await fetch(w(e.baseUrl),{method:`POST`,headers:h,body:y,signal:r?.signal}),await r?.onResponse?.({status:S.status,headers:c(S.headers)},e),S.ok)break;let n=await S.text();if(t<3&&_(S.status,n)){let e=m*2**t,n=S.headers.get(`retry-after-ms`);if(n!==null){let t=Number(n);Number.isFinite(t)&&(e=Math.max(0,t))}else{let t=S.headers.get(`retry-after`);if(t){let n=Number(t);if(Number.isFinite(n))e=Math.max(0,n*1e3);else{let n=Date.parse(t);Number.isNaN(n)||(e=Math.max(0,n-Date.now()))}}}await v(e,r?.signal);continue}let i=await de(new Response(n,{status:S.status,statusText:S.statusText}));throw Error(i.friendlyMessage||i.message)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message===`Request was aborted`))throw Error(`Request was aborted`);if(C=e instanceof Error?e:Error(String(e)),t<3&&!C.message.includes(`usage limit`)){await v(m*2**t,r?.signal);continue}throw C}}if(!S?.ok)throw C??Error(`Failed after retries`);if(!S.body)throw Error(`No response body`);if(i.push({type:`start`,partial:a}),await T(S,a,i,e,r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:a.stopReason,message:a}),i.end()}catch(e){for(let e of a.content)delete e.partialJson;a.stopReason=r?.signal?.aborted?`aborted`:`error`,a.errorMessage=e instanceof Error?e.message:String(e),i.push({type:`error`,reason:a.stopReason,error:a}),i.end()}})(),i},b=(t,n,i)=>{let a=i?.apiKey||o(t.provider);if(!a)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,i,a),c=i?.reasoning?e(t,i.reasoning):void 0,l=c===`off`?void 0:c;return y(t,n,{...s,reasoningEffort:l})};function ee(e,t,n){let r=d(e,t,h,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:n?.sessionId,tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=l(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}function x(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function S(e,t,n){let r=x(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function C(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function w(e){let t=(e&&e.trim().length>0?e:`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function te(e){let t=new URL(w(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function T(e,t,n,r,i){await u(k(ne(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,r)})}var E=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},D=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function O(e){return e instanceof E||e instanceof D}async function*k(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let e=t.code||``;throw new E(`Codex error: ${t.message||e||JSON.stringify(t)}`,{code:e||void 0,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new E(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:A(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function A(e){if(typeof e==`string`)return g.has(e)?e:void 0}async function*ne(e){if(!e.body)return;let t=e.body.getReader(),r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;i+=r.decode(a,{stream:!0});let o=i.indexOf(`
2
2
 
3
3
  `);for(;o!==-1;){let e=i.slice(0,o);i=i.slice(o+2);let t=e.split(`
4
4
  `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
@@ -1,4 +1,4 @@
1
- import{$ as e,B as t,R as n,V as r,X as i,it as a,rt as o,v as s,z as c}from"./main-DMvYmz_A.js";import{t as l}from"./headers-DO1UzNKu.js";import{n as u,r as d,t as f}from"./openai-responses-shared-CDgUSOrg.js";var p=null,m=e=>a(()=>import(e),[]);typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&m(`node:os`).then(e=>{p=e});var h=`https://chatgpt.com/backend-api`,g=`https://api.openai.com/auth`,_=3,v=1e3,y=new Set([`openai`,`openai-codex`,`opencode`]),b=1009,x=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function ee(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function S(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}var C=(e,t,r)=>{let a=new i;return(async()=>{let i={role:`assistant`,content:[],api:`openai-codex-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=r?.apiKey||o(e.provider)||``;if(!s)throw Error(`No API key for provider: ${e.provider}`);let u=ye(s),d=w(e,t,r),f=await r?.onPayload?.(d,e);f!==void 0&&(d=f);let p=r?.sessionId||be(),m=xe(e.headers,r?.headers,u,s,r?.sessionId),h=Se(e.headers,r?.headers,u,s,p),g=JSON.stringify(d),y=r?.transport||`auto`,b=y!==`sse`&&z(r?.sessionId);if(b&&B(r?.sessionId),y!==`sse`&&!b){let t=!1;try{if(await _e(re(e.baseUrl),d,h,i,a,e,()=>{t=!0},r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:i.stopReason,message:i}),a.end();return}catch(e){if(r?.signal?.aborted||A(e)||(n(i,c(`provider_transport_failure`,e,{configuredTransport:y,fallbackTransport:t?void 0:`sse`,eventsEmitted:t,phase:t?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(g).byteLength})),V(r?.sessionId,e),t))throw e;B(r?.sessionId)}}let x,C;for(let t=0;t<=_;t++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{if(x=await fetch(D(e.baseUrl),{method:`POST`,headers:m,body:g,signal:r?.signal}),await r?.onResponse?.({status:x.status,headers:l(x.headers)},e),x.ok)break;let n=await x.text();if(t<_&&ee(x.status,n)){let e=v*2**t,n=x.headers.get(`retry-after-ms`);if(n!==null){let t=Number(n);Number.isFinite(t)&&(e=Math.max(0,t))}else{let t=x.headers.get(`retry-after`);if(t){let n=Number(t);if(Number.isFinite(n))e=Math.max(0,n*1e3);else{let n=Date.parse(t);Number.isNaN(n)||(e=Math.max(0,n-Date.now()))}}}await S(e,r?.signal);continue}let i=await ve(new Response(n,{status:x.status,statusText:x.statusText}));throw Error(i.friendlyMessage||i.message)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message===`Request was aborted`))throw Error(`Request was aborted`);if(C=e instanceof Error?e:Error(String(e)),t<_&&!C.message.includes(`usage limit`)){await S(v*2**t,r?.signal);continue}throw C}}if(!x?.ok)throw C??Error(`Failed after retries`);if(!x.body)throw Error(`No response body`);if(a.push({type:`start`,partial:i}),await ie(x,i,a,e,r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:i.stopReason,message:i}),a.end()}catch(e){for(let e of i.content)delete e.partialJson;i.stopReason=r?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:String(e),a.push({type:`error`,reason:i.stopReason,error:i}),a.end()}})(),a},te=(t,n,r)=>{let i=r?.apiKey||o(t.provider);if(!i)throw Error(`No API key for provider: ${t.provider}`);let a=s(t,r,i),c=r?.reasoning?e(t,r.reasoning):void 0,l=c===`off`?void 0:c;return C(t,n,{...a,reasoningEffort:l})};function w(e,t,n){let r=f(e,t,y,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:n?.sessionId,tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=u(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}function ne(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function T(e,t,n){let r=ne(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function E(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function D(e){let t=(e&&e.trim().length>0?e:h).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function re(e){let t=new URL(D(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function ie(e,t,n,r,i){await d(j(oe(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:E,applyServiceTierPricing:(e,t)=>T(e,t,r)})}var O=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},k=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function A(e){return e instanceof O||e instanceof k}async function*j(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let e=t.code||``;throw new O(`Codex error: ${t.message||e||JSON.stringify(t)}`,{code:e||void 0,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new O(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:ae(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function ae(e){if(typeof e==`string`)return x.has(e)?e:void 0}async function*oe(e){if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;i+=r.decode(a,{stream:!0});let o=i.indexOf(`
1
+ import{$ as e,B as t,R as n,V as r,X as i,it as a,rt as o,v as s,z as c}from"./main-BtoNCPyQ.js";import{t as l}from"./headers-DO1UzNKu.js";import{n as u,r as d,t as f}from"./openai-responses-shared-C3n9ip32.js";var p=null,m=e=>a(()=>import(e),[]);typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&m(`node:os`).then(e=>{p=e});var h=`https://chatgpt.com/backend-api`,g=`https://api.openai.com/auth`,_=3,v=1e3,y=new Set([`openai`,`openai-codex`,`opencode`]),b=1009,x=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function ee(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function S(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}var C=(e,t,r)=>{let a=new i;return(async()=>{let i={role:`assistant`,content:[],api:`openai-codex-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=r?.apiKey||o(e.provider)||``;if(!s)throw Error(`No API key for provider: ${e.provider}`);let u=ye(s),d=w(e,t,r),f=await r?.onPayload?.(d,e);f!==void 0&&(d=f);let p=r?.sessionId||be(),m=xe(e.headers,r?.headers,u,s,r?.sessionId),h=Se(e.headers,r?.headers,u,s,p),g=JSON.stringify(d),y=r?.transport||`auto`,b=y!==`sse`&&z(r?.sessionId);if(b&&B(r?.sessionId),y!==`sse`&&!b){let t=!1;try{if(await _e(re(e.baseUrl),d,h,i,a,e,()=>{t=!0},r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:i.stopReason,message:i}),a.end();return}catch(e){if(r?.signal?.aborted||A(e)||(n(i,c(`provider_transport_failure`,e,{configuredTransport:y,fallbackTransport:t?void 0:`sse`,eventsEmitted:t,phase:t?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(g).byteLength})),V(r?.sessionId,e),t))throw e;B(r?.sessionId)}}let x,C;for(let t=0;t<=_;t++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{if(x=await fetch(D(e.baseUrl),{method:`POST`,headers:m,body:g,signal:r?.signal}),await r?.onResponse?.({status:x.status,headers:l(x.headers)},e),x.ok)break;let n=await x.text();if(t<_&&ee(x.status,n)){let e=v*2**t,n=x.headers.get(`retry-after-ms`);if(n!==null){let t=Number(n);Number.isFinite(t)&&(e=Math.max(0,t))}else{let t=x.headers.get(`retry-after`);if(t){let n=Number(t);if(Number.isFinite(n))e=Math.max(0,n*1e3);else{let n=Date.parse(t);Number.isNaN(n)||(e=Math.max(0,n-Date.now()))}}}await S(e,r?.signal);continue}let i=await ve(new Response(n,{status:x.status,statusText:x.statusText}));throw Error(i.friendlyMessage||i.message)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message===`Request was aborted`))throw Error(`Request was aborted`);if(C=e instanceof Error?e:Error(String(e)),t<_&&!C.message.includes(`usage limit`)){await S(v*2**t,r?.signal);continue}throw C}}if(!x?.ok)throw C??Error(`Failed after retries`);if(!x.body)throw Error(`No response body`);if(a.push({type:`start`,partial:i}),await ie(x,i,a,e,r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:i.stopReason,message:i}),a.end()}catch(e){for(let e of i.content)delete e.partialJson;i.stopReason=r?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:String(e),a.push({type:`error`,reason:i.stopReason,error:i}),a.end()}})(),a},te=(t,n,r)=>{let i=r?.apiKey||o(t.provider);if(!i)throw Error(`No API key for provider: ${t.provider}`);let a=s(t,r,i),c=r?.reasoning?e(t,r.reasoning):void 0,l=c===`off`?void 0:c;return C(t,n,{...a,reasoningEffort:l})};function w(e,t,n){let r=f(e,t,y,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:n?.sessionId,tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=u(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}function ne(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function T(e,t,n){let r=ne(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function E(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function D(e){let t=(e&&e.trim().length>0?e:h).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function re(e){let t=new URL(D(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function ie(e,t,n,r,i){await d(j(oe(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:E,applyServiceTierPricing:(e,t)=>T(e,t,r)})}var O=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},k=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function A(e){return e instanceof O||e instanceof k}async function*j(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let e=t.code||``;throw new O(`Codex error: ${t.message||e||JSON.stringify(t)}`,{code:e||void 0,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new O(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:ae(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function ae(e){if(typeof e==`string`)return x.has(e)?e:void 0}async function*oe(e){if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;i+=r.decode(a,{stream:!0});let o=i.indexOf(`
2
2
 
3
3
  `);for(;o!==-1;){let e=i.slice(0,o);i=i.slice(o+2);let n=e.split(`
4
4
  `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(n.length>0){let e=n.join(`
@@ -1,4 +1,4 @@
1
- import{$ as e,L as t,Q as n,X as r,g as i,rt as a,v as o}from"./main-DMvYmz_A.js";import{t as s}from"./headers-DO1UzNKu.js";import{t as c}from"./sanitize-unicode-DmIE6hZJ.js";import{i as l,n as u,r as d,t as f}from"./github-copilot-headers-DZtWWv8W.js";import{n as p}from"./openai-Cn5LRPCm.js";function m(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function h(e){return e.type===`text`}function g(e){return e.type===`thinking`}function _(e){return e.type===`toolCall`}function v(e){return e.type===`image`}function y(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}var b=(e,n,i)=>{let o=new r;return(async()=>{let r={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let c=i?.apiKey||a(e.provider)||``,l=L(e),u=y(i?.cacheRetention),d=u===`none`?void 0:i?.sessionId,f=S(e,n,c,i?.headers,d,l),p=C(e,n,i,l,u),m=await i?.onPayload?.(p,e);m!==void 0&&(p=m);let h={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:g,response:_}=await f.chat.completions.create(p,h).withResponse();await i?.onResponse?.({status:_.status,headers:s(_.headers)},e),o.push({type:`start`,partial:r});let v=null,b=null,x=!1,w=new Map,T=new Map,E=r.content,D=e=>E.indexOf(e),O=e=>{let n=D(e);n!==-1&&(e.type===`text`?o.push({type:`text_end`,contentIndex:n,content:e.text,partial:r}):e.type===`thinking`?o.push({type:`thinking_end`,contentIndex:n,content:e.thinking,partial:r}):e.type===`toolCall`&&(e.arguments=t(e.partialArgs),delete e.partialArgs,delete e.streamIndex,o.push({type:`toolcall_end`,contentIndex:n,toolCall:e,partial:r})))},k=()=>(v||(v={type:`text`,text:``},E.push(v),o.push({type:`text_start`,contentIndex:D(v),partial:r})),v),A=e=>(b||(b={type:`thinking`,thinking:``,thinkingSignature:e},E.push(b),o.push({type:`thinking_start`,contentIndex:D(b),partial:r})),b),j=e=>{let t=typeof e.index==`number`?e.index:void 0,n=t===void 0?void 0:w.get(t);return!n&&e.id&&(n=T.get(e.id)),n||(n={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``,streamIndex:t},t!==void 0&&w.set(t,n),e.id&&T.set(e.id,n),E.push(n),o.push({type:`toolcall_start`,contentIndex:D(n),partial:r})),t!==void 0&&n.streamIndex===void 0&&(n.streamIndex=t,w.set(t,n)),e.id&&T.set(e.id,n),n};for await(let n of g){if(!n||typeof n!=`object`)continue;r.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==e.id&&(r.responseModel||=n.model),n.usage&&(r.usage=P(n.usage,e));let i=Array.isArray(n.choices)?n.choices[0]:void 0;if(i){if(!n.usage&&i.usage&&(r.usage=P(i.usage,e)),i.finish_reason){let e=F(i.finish_reason);r.stopReason=e.stopReason,e.errorMessage&&(r.errorMessage=e.errorMessage),x=!0}if(i.delta){if(i.delta.content!==null&&i.delta.content!==void 0&&i.delta.content.length>0){let e=k();e.text+=i.delta.content,o.push({type:`text_delta`,contentIndex:D(e),delta:i.delta.content,partial:r})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],a=i.delta,s=null;for(let e of n){let t=a[e];if(typeof t==`string`&&t.length>0){s=e;break}}if(s){let t=a[s];if(typeof t==`string`&&t.length>0){let n=A(e.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);n.thinking+=t,o.push({type:`thinking_delta`,contentIndex:D(n),delta:t,partial:r})}}if(i?.delta?.tool_calls)for(let e of i.delta.tool_calls){let n=j(e);!n.id&&e.id&&(n.id=e.id,T.set(e.id,n)),!n.name&&e.function?.name&&(n.name=e.function.name);let i=``;e.function?.arguments&&(i=e.function.arguments,n.partialArgs=(n.partialArgs??``)+e.function.arguments,n.arguments=t(n.partialArgs)),o.push({type:`toolcall_delta`,contentIndex:D(n),delta:i,partial:r})}let c=i.delta.reasoning_details;if(c&&Array.isArray(c)){for(let e of c)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=r.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}}}for(let e of E)O(e);if(i?.signal?.aborted||r.stopReason===`aborted`)throw Error(`Request was aborted`);if(r.stopReason===`error`)throw Error(r.errorMessage||`Provider returned an error stop reason`);if(!x)throw Error(`Stream ended without finish_reason`);o.push({type:`done`,reason:r.stopReason,message:r}),o.end()}catch(e){for(let e of r.content)delete e.index,delete e.partialArgs,delete e.streamIndex;r.stopReason=i?.signal?.aborted?`aborted`:`error`,r.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let t=e?.error?.metadata?.raw;t&&(r.errorMessage+=`\n${t}`),o.push({type:`error`,reason:r.stopReason,error:r}),o.end()}})(),o},x=(t,n,r)=>{let i=r?.apiKey||a(t.provider);if(!i)throw Error(`No API key for provider: ${t.provider}`);let s=o(t,r,i),c=r?.reasoning?e(t,r.reasoning):void 0,l=c===`off`?void 0:c,u=r?.toolChoice;return b(t,n,{...s,reasoningEffort:l,toolChoice:u})};function S(e,t,n,r,i,a=L(e)){if(!n){if(!{}.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n={}.OPENAI_API_KEY}let o={...e.headers};if(e.provider===`github-copilot`){let e=u(t.messages),n=f({messages:t.messages,hasImages:e});Object.assign(o,n)}i&&a.sendSessionAffinityHeaders&&(o.session_id=i,o[`x-client-request-id`]=i,o[`x-session-affinity`]=i),r&&Object.assign(o,r);let s=e.provider===`cloudflare-ai-gateway`?{...o,Authorization:o.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:o;return new p({apiKey:n,baseURL:d(e.provider)?l(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:s})}function C(e,t,n,r=L(e),i=y(n?.cacheRetention)){let a=M(e,t,r),o=w(r,i),s={model:e.id,messages:a,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?n?.sessionId:void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};if(r.supportsUsageInStreaming!==!1&&(s.stream_options={include_usage:!0}),r.supportsStore&&(s.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?s.max_tokens=n.maxTokens:s.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(s.temperature=n.temperature),t.tools&&t.tools.length>0?(s.tools=N(t.tools,r),r.zaiToolStream&&(s.tool_stream=!0)):m(t.messages)&&(s.tools=[]),o&&T(a,s.tools,o),n?.toolChoice&&(s.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen`&&e.reasoning)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)s.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`deepseek`&&e.reasoning)s.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&(s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=s;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=s;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&r.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if(n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort)s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(s.reasoning_effort=t)}if(e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(s.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),s.providerOptions={gateway:e}}}return s}function w(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function T(e,t,n){E(e,n),O(t,n),D(e,n)}function E(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){k(n,t);return}}function D(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`)&&A(r,t))return}}function O(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function k(e,t){return j(e,t)}function A(e,t){return e.role===`user`||e.role===`assistant`?j(e,t):!1}function j(e,t){let n=e.content;if(typeof n==`string`)return n.length===0?!1:(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function M(e,t,n){let r=[],a=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},o=i(t.messages,e,e=>a(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:c(t.systemPrompt)})}let s=null;for(let t=0;t<o.length;t++){let i=o[t];if(n.requiresAssistantAfterToolResult&&s===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`)if(typeof i.content==`string`)r.push({role:`user`,content:c(i.content)});else{let e=i.content.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;r.push({role:`user`,content:e})}else if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(h).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:c(e.text)})),o=a.map(e=>e.text).join(``),s=i.content.filter(g).filter(e=>e.thinking.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:s.map(e=>c(e.thinking)).join(`
1
+ import{$ as e,L as t,Q as n,X as r,g as i,rt as a,v as o}from"./main-BtoNCPyQ.js";import{t as s}from"./headers-DO1UzNKu.js";import{t as c}from"./sanitize-unicode-DmIE6hZJ.js";import{i as l,n as u,r as d,t as f}from"./github-copilot-headers-DZtWWv8W.js";import{n as p}from"./openai-Cn5LRPCm.js";function m(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function h(e){return e.type===`text`}function g(e){return e.type===`thinking`}function _(e){return e.type===`toolCall`}function v(e){return e.type===`image`}function y(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}var b=(e,n,i)=>{let o=new r;return(async()=>{let r={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let c=i?.apiKey||a(e.provider)||``,l=L(e),u=y(i?.cacheRetention),d=u===`none`?void 0:i?.sessionId,f=S(e,n,c,i?.headers,d,l),p=C(e,n,i,l,u),m=await i?.onPayload?.(p,e);m!==void 0&&(p=m);let h={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:g,response:_}=await f.chat.completions.create(p,h).withResponse();await i?.onResponse?.({status:_.status,headers:s(_.headers)},e),o.push({type:`start`,partial:r});let v=null,b=null,x=!1,w=new Map,T=new Map,E=r.content,D=e=>E.indexOf(e),O=e=>{let n=D(e);n!==-1&&(e.type===`text`?o.push({type:`text_end`,contentIndex:n,content:e.text,partial:r}):e.type===`thinking`?o.push({type:`thinking_end`,contentIndex:n,content:e.thinking,partial:r}):e.type===`toolCall`&&(e.arguments=t(e.partialArgs),delete e.partialArgs,delete e.streamIndex,o.push({type:`toolcall_end`,contentIndex:n,toolCall:e,partial:r})))},k=()=>(v||(v={type:`text`,text:``},E.push(v),o.push({type:`text_start`,contentIndex:D(v),partial:r})),v),A=e=>(b||(b={type:`thinking`,thinking:``,thinkingSignature:e},E.push(b),o.push({type:`thinking_start`,contentIndex:D(b),partial:r})),b),j=e=>{let t=typeof e.index==`number`?e.index:void 0,n=t===void 0?void 0:w.get(t);return!n&&e.id&&(n=T.get(e.id)),n||(n={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``,streamIndex:t},t!==void 0&&w.set(t,n),e.id&&T.set(e.id,n),E.push(n),o.push({type:`toolcall_start`,contentIndex:D(n),partial:r})),t!==void 0&&n.streamIndex===void 0&&(n.streamIndex=t,w.set(t,n)),e.id&&T.set(e.id,n),n};for await(let n of g){if(!n||typeof n!=`object`)continue;r.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==e.id&&(r.responseModel||=n.model),n.usage&&(r.usage=P(n.usage,e));let i=Array.isArray(n.choices)?n.choices[0]:void 0;if(i){if(!n.usage&&i.usage&&(r.usage=P(i.usage,e)),i.finish_reason){let e=F(i.finish_reason);r.stopReason=e.stopReason,e.errorMessage&&(r.errorMessage=e.errorMessage),x=!0}if(i.delta){if(i.delta.content!==null&&i.delta.content!==void 0&&i.delta.content.length>0){let e=k();e.text+=i.delta.content,o.push({type:`text_delta`,contentIndex:D(e),delta:i.delta.content,partial:r})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],a=i.delta,s=null;for(let e of n){let t=a[e];if(typeof t==`string`&&t.length>0){s=e;break}}if(s){let t=a[s];if(typeof t==`string`&&t.length>0){let n=A(e.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);n.thinking+=t,o.push({type:`thinking_delta`,contentIndex:D(n),delta:t,partial:r})}}if(i?.delta?.tool_calls)for(let e of i.delta.tool_calls){let n=j(e);!n.id&&e.id&&(n.id=e.id,T.set(e.id,n)),!n.name&&e.function?.name&&(n.name=e.function.name);let i=``;e.function?.arguments&&(i=e.function.arguments,n.partialArgs=(n.partialArgs??``)+e.function.arguments,n.arguments=t(n.partialArgs)),o.push({type:`toolcall_delta`,contentIndex:D(n),delta:i,partial:r})}let c=i.delta.reasoning_details;if(c&&Array.isArray(c)){for(let e of c)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=r.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}}}for(let e of E)O(e);if(i?.signal?.aborted||r.stopReason===`aborted`)throw Error(`Request was aborted`);if(r.stopReason===`error`)throw Error(r.errorMessage||`Provider returned an error stop reason`);if(!x)throw Error(`Stream ended without finish_reason`);o.push({type:`done`,reason:r.stopReason,message:r}),o.end()}catch(e){for(let e of r.content)delete e.index,delete e.partialArgs,delete e.streamIndex;r.stopReason=i?.signal?.aborted?`aborted`:`error`,r.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let t=e?.error?.metadata?.raw;t&&(r.errorMessage+=`\n${t}`),o.push({type:`error`,reason:r.stopReason,error:r}),o.end()}})(),o},x=(t,n,r)=>{let i=r?.apiKey||a(t.provider);if(!i)throw Error(`No API key for provider: ${t.provider}`);let s=o(t,r,i),c=r?.reasoning?e(t,r.reasoning):void 0,l=c===`off`?void 0:c,u=r?.toolChoice;return b(t,n,{...s,reasoningEffort:l,toolChoice:u})};function S(e,t,n,r,i,a=L(e)){if(!n){if(!{}.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n={}.OPENAI_API_KEY}let o={...e.headers};if(e.provider===`github-copilot`){let e=u(t.messages),n=f({messages:t.messages,hasImages:e});Object.assign(o,n)}i&&a.sendSessionAffinityHeaders&&(o.session_id=i,o[`x-client-request-id`]=i,o[`x-session-affinity`]=i),r&&Object.assign(o,r);let s=e.provider===`cloudflare-ai-gateway`?{...o,Authorization:o.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:o;return new p({apiKey:n,baseURL:d(e.provider)?l(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:s})}function C(e,t,n,r=L(e),i=y(n?.cacheRetention)){let a=M(e,t,r),o=w(r,i),s={model:e.id,messages:a,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?n?.sessionId:void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};if(r.supportsUsageInStreaming!==!1&&(s.stream_options={include_usage:!0}),r.supportsStore&&(s.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?s.max_tokens=n.maxTokens:s.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(s.temperature=n.temperature),t.tools&&t.tools.length>0?(s.tools=N(t.tools,r),r.zaiToolStream&&(s.tool_stream=!0)):m(t.messages)&&(s.tools=[]),o&&T(a,s.tools,o),n?.toolChoice&&(s.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen`&&e.reasoning)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)s.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`deepseek`&&e.reasoning)s.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&(s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=s;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=s;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&r.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if(n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort)s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(s.reasoning_effort=t)}if(e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(s.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),s.providerOptions={gateway:e}}}return s}function w(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function T(e,t,n){E(e,n),O(t,n),D(e,n)}function E(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){k(n,t);return}}function D(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`)&&A(r,t))return}}function O(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function k(e,t){return j(e,t)}function A(e,t){return e.role===`user`||e.role===`assistant`?j(e,t):!1}function j(e,t){let n=e.content;if(typeof n==`string`)return n.length===0?!1:(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function M(e,t,n){let r=[],a=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},o=i(t.messages,e,e=>a(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:c(t.systemPrompt)})}let s=null;for(let t=0;t<o.length;t++){let i=o[t];if(n.requiresAssistantAfterToolResult&&s===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`)if(typeof i.content==`string`)r.push({role:`user`,content:c(i.content)});else{let e=i.content.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;r.push({role:`user`,content:e})}else if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(h).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:c(e.text)})),o=a.map(e=>e.text).join(``),s=i.content.filter(g).filter(e=>e.thinking.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:s.map(e=>c(e.thinking)).join(`
2
2
 
3
3
  `)},...a];else{o.length>0&&(t.content=o);let n=s[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&n.length>0&&(t[n]=s.map(e=>e.thinking).join(`
4
4
  `))}else o.length>0&&(t.content=o);let l=i.content.filter(_);if(l.length>0){t.tool_calls=l.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=l.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let u=t.content;if(!(u!=null&&u.length>0)&&!t.tool_calls)continue;r.push(t)}else if(i.role===`toolResult`){let i=[],a=t;for(;a<o.length&&o[a].role===`toolResult`;a++){let t=o[a],s=t.content.filter(h).map(e=>e.text).join(`
@@ -1 +1 @@
1
- import{K as e,O as t,U as n,X as r,a as i,c as a,f as o,o as s,s as c,u as l}from"./kernel-worker-CwwcfcWb.js";import{n as u,r as d,t as f}from"./openai-responses-shared-DQ2Zhc3v.js";const p=new Set([`openai`,`openai-codex`,`opencode`]);function m(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function h(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function g(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function _(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}const v=(e,t,i)=>{let a=new n;return(async()=>{let n={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let o=i?.apiKey||r(e.provider)||``,s=m(i?.cacheRetention)===`none`?void 0:i?.sessionId,c=b(e,t,o,i?.headers,s),u=x(e,t,i),f=await i?.onPayload?.(u,e);f!==void 0&&(u=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:h,response:g}=await c.responses.create(u,p).withResponse();if(await i?.onResponse?.({status:g.status,headers:l(g.headers)},e),a.push({type:`start`,partial:n}),await d(h,n,a,e,{serviceTier:i?.serviceTier,applyServiceTierPricing:(t,n)=>C(t,n,e)}),i?.signal?.aborted)throw Error(`Request was aborted`);if(n.stopReason===`aborted`||n.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:n.stopReason,message:n}),a.end()}catch(e){for(let e of n.content)delete e.index,delete e.partialJson;n.stopReason=i?.signal?.aborted?`aborted`:`error`,n.errorMessage=_(e),a.push({type:`error`,reason:n.stopReason,error:n}),a.end()}})(),a},y=(n,i,a)=>{let o=a?.apiKey||r(n.provider);if(!o)throw Error(`No API key for provider: ${n.provider}`);let s=t(n,a,o),c=a?.reasoning?e(n,a.reasoning):void 0,l=c===`off`?void 0:c;return v(n,i,{...s,reasoningEffort:l})};function b(e,t,n,r,l){if(!n){if(!{}.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n={}.OPENAI_API_KEY}let u=h(e),d={...e.headers};if(e.provider===`github-copilot`){let e=s(t.messages),n=i({messages:t.messages,hasImages:e});Object.assign(d,n)}l&&(u.sendSessionIdHeader&&(d.session_id=l),d[`x-client-request-id`]=l),r&&Object.assign(d,r);let f=e.provider===`cloudflare-ai-gateway`?{...d,Authorization:d.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:d;return new o({apiKey:n,baseURL:c(e.provider)?a(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function x(e,t,n){let r=f(e,t,p),i=m(n?.cacheRetention),a=h(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:n?.sessionId,prompt_cache_retention:g(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=u(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function S(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function C(e,t,n){let r=S(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{v as streamOpenAIResponses,y as streamSimpleOpenAIResponses};
1
+ import{K as e,O as t,U as n,X as r,a as i,c as a,f as o,o as s,s as c,u as l}from"./kernel-worker-aL7clsM2.js";import{n as u,r as d,t as f}from"./openai-responses-shared-BYmbH8Nn.js";const p=new Set([`openai`,`openai-codex`,`opencode`]);function m(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function h(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function g(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function _(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}const v=(e,t,i)=>{let a=new n;return(async()=>{let n={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let o=i?.apiKey||r(e.provider)||``,s=m(i?.cacheRetention)===`none`?void 0:i?.sessionId,c=b(e,t,o,i?.headers,s),u=x(e,t,i),f=await i?.onPayload?.(u,e);f!==void 0&&(u=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:h,response:g}=await c.responses.create(u,p).withResponse();if(await i?.onResponse?.({status:g.status,headers:l(g.headers)},e),a.push({type:`start`,partial:n}),await d(h,n,a,e,{serviceTier:i?.serviceTier,applyServiceTierPricing:(t,n)=>C(t,n,e)}),i?.signal?.aborted)throw Error(`Request was aborted`);if(n.stopReason===`aborted`||n.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:n.stopReason,message:n}),a.end()}catch(e){for(let e of n.content)delete e.index,delete e.partialJson;n.stopReason=i?.signal?.aborted?`aborted`:`error`,n.errorMessage=_(e),a.push({type:`error`,reason:n.stopReason,error:n}),a.end()}})(),a},y=(n,i,a)=>{let o=a?.apiKey||r(n.provider);if(!o)throw Error(`No API key for provider: ${n.provider}`);let s=t(n,a,o),c=a?.reasoning?e(n,a.reasoning):void 0,l=c===`off`?void 0:c;return v(n,i,{...s,reasoningEffort:l})};function b(e,t,n,r,l){if(!n){if(!{}.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n={}.OPENAI_API_KEY}let u=h(e),d={...e.headers};if(e.provider===`github-copilot`){let e=s(t.messages),n=i({messages:t.messages,hasImages:e});Object.assign(d,n)}l&&(u.sendSessionIdHeader&&(d.session_id=l),d[`x-client-request-id`]=l),r&&Object.assign(d,r);let f=e.provider===`cloudflare-ai-gateway`?{...d,Authorization:d.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:d;return new o({apiKey:n,baseURL:c(e.provider)?a(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function x(e,t,n){let r=f(e,t,p),i=m(n?.cacheRetention),a=h(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:n?.sessionId,prompt_cache_retention:g(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=u(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function S(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function C(e,t,n){let r=S(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{v as streamOpenAIResponses,y as streamSimpleOpenAIResponses};
@@ -1 +1 @@
1
- import{$ as e,X as t,rt as n,v as r}from"./main-DMvYmz_A.js";import{t as i}from"./headers-DO1UzNKu.js";import{i as a,n as o,r as s,t as c}from"./github-copilot-headers-DZtWWv8W.js";import{n as l}from"./openai-Cn5LRPCm.js";import{n as u,r as d,t as f}from"./openai-responses-shared-CDgUSOrg.js";var p=new Set([`openai`,`openai-codex`,`opencode`]);function m(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function h(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function g(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function _(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}var v=(e,r,a)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=a?.apiKey||n(e.provider)||``,c=m(a?.cacheRetention)===`none`?void 0:a?.sessionId,l=b(e,r,s,a?.headers,c),u=x(e,r,a),f=await a?.onPayload?.(u,e);f!==void 0&&(u=f);let p={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},...a?.maxRetries===void 0?{}:{maxRetries:a.maxRetries}},{data:h,response:g}=await l.responses.create(u,p).withResponse();if(await a?.onResponse?.({status:g.status,headers:i(g.headers)},e),o.push({type:`start`,partial:t}),await d(h,t,o,e,{serviceTier:a?.serviceTier,applyServiceTierPricing:(t,n)=>C(t,n,e)}),a?.signal?.aborted)throw Error(`Request was aborted`);if(t.stopReason===`aborted`||t.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end()}catch(e){for(let e of t.content)delete e.index,delete e.partialJson;t.stopReason=a?.signal?.aborted?`aborted`:`error`,t.errorMessage=_(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},y=(t,i,a)=>{let o=a?.apiKey||n(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,a,o),c=a?.reasoning?e(t,a.reasoning):void 0,l=c===`off`?void 0:c;return v(t,i,{...s,reasoningEffort:l})};function b(e,t,n,r,i){if(!n){if(!{}.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n={}.OPENAI_API_KEY}let u=h(e),d={...e.headers};if(e.provider===`github-copilot`){let e=o(t.messages),n=c({messages:t.messages,hasImages:e});Object.assign(d,n)}i&&(u.sendSessionIdHeader&&(d.session_id=i),d[`x-client-request-id`]=i),r&&Object.assign(d,r);let f=e.provider===`cloudflare-ai-gateway`?{...d,Authorization:d.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:d;return new l({apiKey:n,baseURL:s(e.provider)?a(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function x(e,t,n){let r=f(e,t,p),i=m(n?.cacheRetention),a=h(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:n?.sessionId,prompt_cache_retention:g(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=u(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function S(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function C(e,t,n){let r=S(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{v as streamOpenAIResponses,y as streamSimpleOpenAIResponses};
1
+ import{$ as e,X as t,rt as n,v as r}from"./main-BtoNCPyQ.js";import{t as i}from"./headers-DO1UzNKu.js";import{i as a,n as o,r as s,t as c}from"./github-copilot-headers-DZtWWv8W.js";import{n as l}from"./openai-Cn5LRPCm.js";import{n as u,r as d,t as f}from"./openai-responses-shared-C3n9ip32.js";var p=new Set([`openai`,`openai-codex`,`opencode`]);function m(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function h(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function g(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function _(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}var v=(e,r,a)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=a?.apiKey||n(e.provider)||``,c=m(a?.cacheRetention)===`none`?void 0:a?.sessionId,l=b(e,r,s,a?.headers,c),u=x(e,r,a),f=await a?.onPayload?.(u,e);f!==void 0&&(u=f);let p={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},...a?.maxRetries===void 0?{}:{maxRetries:a.maxRetries}},{data:h,response:g}=await l.responses.create(u,p).withResponse();if(await a?.onResponse?.({status:g.status,headers:i(g.headers)},e),o.push({type:`start`,partial:t}),await d(h,t,o,e,{serviceTier:a?.serviceTier,applyServiceTierPricing:(t,n)=>C(t,n,e)}),a?.signal?.aborted)throw Error(`Request was aborted`);if(t.stopReason===`aborted`||t.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end()}catch(e){for(let e of t.content)delete e.index,delete e.partialJson;t.stopReason=a?.signal?.aborted?`aborted`:`error`,t.errorMessage=_(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},y=(t,i,a)=>{let o=a?.apiKey||n(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,a,o),c=a?.reasoning?e(t,a.reasoning):void 0,l=c===`off`?void 0:c;return v(t,i,{...s,reasoningEffort:l})};function b(e,t,n,r,i){if(!n){if(!{}.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n={}.OPENAI_API_KEY}let u=h(e),d={...e.headers};if(e.provider===`github-copilot`){let e=o(t.messages),n=c({messages:t.messages,hasImages:e});Object.assign(d,n)}i&&(u.sendSessionIdHeader&&(d.session_id=i),d[`x-client-request-id`]=i),r&&Object.assign(d,r);let f=e.provider===`cloudflare-ai-gateway`?{...d,Authorization:d.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:d;return new l({apiKey:n,baseURL:s(e.provider)?a(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function x(e,t,n){let r=f(e,t,p),i=m(n?.cacheRetention),a=h(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:n?.sessionId,prompt_cache_retention:g(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=u(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function S(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function C(e,t,n){let r=S(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{v as streamOpenAIResponses,y as streamSimpleOpenAIResponses};
@@ -1,4 +1,4 @@
1
- import{A as e,E as t,G as n,l as r}from"./kernel-worker-CwwcfcWb.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,n,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=t(n.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&n.systemPrompt){let t=e.reasoning?`developer`:`system`;c.push({role:t,content:r(n.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=a?.id;s?s.length>64&&(s=`msg_${i(s)}`):s=`msg_${f}`,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
1
+ import{A as e,E as t,G as n,l as r}from"./kernel-worker-aL7clsM2.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,n,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=t(n.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&n.systemPrompt){let t=e.reasoning?`developer`:`system`;c.push({role:t,content:r(n.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=a?.id;s?s.length>64&&(s=`msg_${i(s)}`):s=`msg_${f}`,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
2
  `),i=t.content.some(e=>e.type===`image`),a=n.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:r(n)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=r(a?n:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(t,r,i,o,s){let c=null,l=null,d=r.content,f=()=>d.length-1;for await(let d of t)if(d.type===`response.created`)r.responseId=d.response.id;else if(d.type===`response.output_item.added`){let e=d.item;e.type===`reasoning`?(c=e,l={type:`thinking`,thinking:``},r.content.push(l),i.push({type:`thinking_start`,contentIndex:f(),partial:r})):e.type===`message`?(c=e,l={type:`text`,text:``},r.content.push(l),i.push({type:`text_start`,contentIndex:f(),partial:r})):e.type===`function_call`&&(c=e,l={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||``},r.content.push(l),i.push({type:`toolcall_start`,contentIndex:f(),partial:r}))}else if(d.type===`response.reasoning_summary_part.added`)c&&c.type===`reasoning`&&(c.summary=c.summary||[],c.summary.push(d.part));else if(d.type===`response.reasoning_summary_text.delta`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=d.delta,e.text+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.reasoning_summary_part.done`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=`
3
3
 
4
4
  `,e.text+=`
@@ -1,4 +1,4 @@
1
- import{L as e,Q as t,g as n}from"./main-DMvYmz_A.js";import{t as r}from"./sanitize-unicode-DmIE6hZJ.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,t,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=n(t.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&t.systemPrompt){let n=e.reasoning?`developer`:`system`;c.push({role:n,content:r(t.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=a?.id;s?s.length>64&&(s=`msg_${i(s)}`):s=`msg_${f}`,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
1
+ import{L as e,Q as t,g as n}from"./main-BtoNCPyQ.js";import{t as r}from"./sanitize-unicode-DmIE6hZJ.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,t,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=n(t.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&t.systemPrompt){let n=e.reasoning?`developer`:`system`;c.push({role:n,content:r(t.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=a?.id;s?s.length>64&&(s=`msg_${i(s)}`):s=`msg_${f}`,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
2
  `),i=t.content.some(e=>e.type===`image`),a=n.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:r(n)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=r(a?n:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(n,r,i,o,s){let c=null,l=null,d=r.content,f=()=>d.length-1;for await(let d of n)if(d.type===`response.created`)r.responseId=d.response.id;else if(d.type===`response.output_item.added`){let e=d.item;e.type===`reasoning`?(c=e,l={type:`thinking`,thinking:``},r.content.push(l),i.push({type:`thinking_start`,contentIndex:f(),partial:r})):e.type===`message`?(c=e,l={type:`text`,text:``},r.content.push(l),i.push({type:`text_start`,contentIndex:f(),partial:r})):e.type===`function_call`&&(c=e,l={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||``},r.content.push(l),i.push({type:`toolcall_start`,contentIndex:f(),partial:r}))}else if(d.type===`response.reasoning_summary_part.added`)c&&c.type===`reasoning`&&(c.summary=c.summary||[],c.summary.push(d.part));else if(d.type===`response.reasoning_summary_text.delta`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=d.delta,e.text+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.reasoning_summary_part.done`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=`
3
3
 
4
4
  `,e.text+=`
@@ -1 +1 @@
1
- import{rt as e}from"./main-DMvYmz_A.js";import{t}from"./headers-DO1UzNKu.js";import{t as n}from"./sanitize-unicode-DmIE6hZJ.js";import{n as r}from"./openai-Cn5LRPCm.js";var i=async(n,r,i)=>{let c={api:n.api,provider:n.provider,model:n.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let l=i?.apiKey||e(n.provider);if(!l)throw Error(`No API key available for provider: ${n.provider}`);let u=a(n,l,i?.headers),d=o(n,r),f=await i?.onPayload?.(d,n);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:m,response:h}=await u.chat.completions.create(d,p).withResponse();await i?.onResponse?.({status:h.status,headers:t(h.headers)},n);let g=m;c.responseId=g.id,g.usage&&(c.usage=s(g.usage,n));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&c.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&c.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return c}catch(e){return c.stopReason=i?.signal?.aborted?`aborted`:`error`,c.errorMessage=e instanceof Error?e.message:JSON.stringify(e),c}};function a(e,t,n){return new r({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...e.headers,...n}})}function o(e,t){let r=t.input.map(e=>e.type===`text`?{type:`text`,text:n(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:r}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function s(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{i as generateImagesOpenRouter};
1
+ import{rt as e}from"./main-BtoNCPyQ.js";import{t}from"./headers-DO1UzNKu.js";import{t as n}from"./sanitize-unicode-DmIE6hZJ.js";import{n as r}from"./openai-Cn5LRPCm.js";var i=async(n,r,i)=>{let c={api:n.api,provider:n.provider,model:n.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let l=i?.apiKey||e(n.provider);if(!l)throw Error(`No API key available for provider: ${n.provider}`);let u=a(n,l,i?.headers),d=o(n,r),f=await i?.onPayload?.(d,n);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:m,response:h}=await u.chat.completions.create(d,p).withResponse();await i?.onResponse?.({status:h.status,headers:t(h.headers)},n);let g=m;c.responseId=g.id,g.usage&&(c.usage=s(g.usage,n));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&c.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&c.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return c}catch(e){return c.stopReason=i?.signal?.aborted?`aborted`:`error`,c.errorMessage=e instanceof Error?e.message:JSON.stringify(e),c}};function a(e,t,n){return new r({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...e.headers,...n}})}function o(e,t){let r=t.input.map(e=>e.type===`text`?{type:`text`,text:n(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:r}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function s(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{i as generateImagesOpenRouter};
@@ -1 +1 @@
1
- import{X as e,f as t,l as n,u as r}from"./kernel-worker-CwwcfcWb.js";const i=async(t,n,i)=>{let c={api:t.api,provider:t.provider,model:t.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let l=i?.apiKey||e(t.provider);if(!l)throw Error(`No API key available for provider: ${t.provider}`);let u=a(t,l,i?.headers),d=o(t,n),f=await i?.onPayload?.(d,t);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:m,response:h}=await u.chat.completions.create(d,p).withResponse();await i?.onResponse?.({status:h.status,headers:r(h.headers)},t);let g=m;c.responseId=g.id,g.usage&&(c.usage=s(g.usage,t));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&c.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&c.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return c}catch(e){return c.stopReason=i?.signal?.aborted?`aborted`:`error`,c.errorMessage=e instanceof Error?e.message:JSON.stringify(e),c}};function a(e,n,r){return new t({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...e.headers,...r}})}function o(e,t){let r=t.input.map(e=>e.type===`text`?{type:`text`,text:n(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:r}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function s(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{i as generateImagesOpenRouter};
1
+ import{X as e,f as t,l as n,u as r}from"./kernel-worker-aL7clsM2.js";const i=async(t,n,i)=>{let c={api:t.api,provider:t.provider,model:t.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let l=i?.apiKey||e(t.provider);if(!l)throw Error(`No API key available for provider: ${t.provider}`);let u=a(t,l,i?.headers),d=o(t,n),f=await i?.onPayload?.(d,t);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:m,response:h}=await u.chat.completions.create(d,p).withResponse();await i?.onResponse?.({status:h.status,headers:r(h.headers)},t);let g=m;c.responseId=g.id,g.usage&&(c.usage=s(g.usage,t));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&c.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&c.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return c}catch(e){return c.stopReason=i?.signal?.aborted?`aborted`:`error`,c.errorMessage=e instanceof Error?e.message:JSON.stringify(e),c}};function a(e,n,r){return new t({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...e.headers,...r}})}function o(e,t){let r=t.input.map(e=>e.type===`text`?{type:`text`,text:n(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:r}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function s(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{i as generateImagesOpenRouter};
@@ -1 +1 @@
1
- import{a as e,p as t}from"./main-DMvYmz_A.js";function n(n={}){return{"page-info":()=>({origin:window.location.origin,href:window.location.href,title:document.title||``}),screencapture:async({mimeType:e,quality:t})=>{let n=await l(e,t),r=await n.arrayBuffer(),i=await u(n);return{bytes:r,width:i.width,height:i.height,mimeType:e}},"speak-text":async({text:e,lang:t,voice:n,rate:r,pitch:i,volume:a})=>{if(typeof speechSynthesis>`u`)throw Error(`speechSynthesis is unavailable in this page`);return await new Promise((o,s)=>{let c=new SpeechSynthesisUtterance(e);if(t!==void 0&&(c.lang=t),r!==void 0&&(c.rate=r),i!==void 0&&(c.pitch=i),a!==void 0&&(c.volume=a),n){let e=speechSynthesis.getVoices().find(e=>e.name===n);e&&(c.voice=e)}c.onend=()=>o(),c.onerror=e=>s(Error(`speak: ${e.error||`utterance failed`}`)),speechSynthesis.speak(c)}),{done:!0}},"list-voices":async()=>{if(typeof speechSynthesis>`u`)throw Error(`speechSynthesis is unavailable in this page`);let e=speechSynthesis.getVoices();return e.length>0?{voices:e.map(c)}:{voices:(await new Promise(e=>{let t=()=>{speechSynthesis.removeEventListener(`voiceschanged`,t),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,t),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,t),e(speechSynthesis.getVoices())},1e3)})).map(c)}},"play-audio":async({bytes:e,volume:t})=>{if(typeof AudioContext>`u`)throw Error(`Web Audio API is unavailable in this page`);let n=new AudioContext;try{let r=await n.decodeAudioData(e.slice(0)),i=n.createBufferSource();if(i.buffer=r,t!==void 0){let e=n.createGain();e.gain.value=Math.max(0,Math.min(1,t)),i.connect(e),e.connect(n.destination)}else i.connect(n.destination);await new Promise(e=>{i.onended=()=>e(),i.start()})}finally{try{await n.close()}catch{}}return{done:!0}},"play-chime":async({tone:e})=>{let t={success:[880,1320],error:[440,220],notify:[660,660]},[n,r]=t[e??`notify`]??t.notify;if(typeof AudioContext>`u`)throw Error(`Web Audio API is unavailable in this page`);let i=new AudioContext;try{let e=i.currentTime;for(let[t,a]of[n,r].entries()){let n=i.createOscillator();n.type=`sine`,n.frequency.value=a;let r=i.createGain();r.gain.setValueAtTime(1e-4,e+t*.18),r.gain.exponentialRampToValueAtTime(.2,e+t*.18+.02),r.gain.exponentialRampToValueAtTime(1e-4,e+t*.18+.18),n.connect(r),r.connect(i.destination),n.start(e+t*.18),n.stop(e+t*.18+.2)}await new Promise(e=>setTimeout(e,450))}finally{try{await i.close()}catch{}}return{done:!0}},"clipboard-read-text":async()=>{if(!navigator.clipboard?.readText)throw Error(`clipboard API unavailable`);return{text:await navigator.clipboard.readText()}},"clipboard-write-text":async({text:e})=>{if(!navigator.clipboard?.writeText)throw Error(`clipboard API unavailable`);return await f(),await navigator.clipboard.writeText(e),{done:!0}},"clipboard-write-image":async({bytes:e,mimeType:t})=>{if(!navigator.clipboard?.write||typeof ClipboardItem>`u`)throw Error(`clipboard image API unavailable`);let n,r=new Blob([e],{type:t});return n=t===`image/png`?r:await d(r),await f(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{done:!0}},"window-open":async({url:e,target:t,features:n})=>({opened:window.open(e,t??`_blank`,n??`noopener,noreferrer`)!==null}),"oauth-popup":async({url:e})=>({redirectUrl:await s(e)}),"capture-camera":async e=>await i(e),"enumerate-media-devices":async()=>{if(!navigator.mediaDevices?.enumerateDevices)throw Error(`enumerateDevices is not supported in this browser`);let e=await navigator.mediaDevices.enumerateDevices(),t=e=>({deviceId:e.deviceId,label:e.label||``,...e.groupId?{groupId:e.groupId}:{}});return{videoinputs:e.filter(e=>e.kind===`videoinput`).map(t),audioinputs:e.filter(e=>e.kind===`audioinput`).map(t)}},"tray-reset":async()=>{if(!n.resetTray)throw Error(`host reset: no active tray session to reset`);return await n.resetTray()},"tray-leave":async({workerBaseUrl:e,requestId:t})=>{if(!n.leaveTray)throw Error(`host leave: tray leave is not available in this environment`);return await n.leaveTray({workerBaseUrl:e,requestId:t})},"cherry-emit":async({runtimeId:e,name:t,detail:r})=>{if(!n.emitCherrySliccEvent)throw Error(`cherry-emit: not available in this environment`);return{delivered:n.emitCherrySliccEvent(e,t,r)}},"oauth-extras-set":({providerId:n,domains:r})=>(t(n,r),{storeAfter:e()}),"save-oauth-accounts":({accountsJson:e})=>(localStorage.setItem(`slicc_accounts`,e),{storedJson:localStorage.getItem(`slicc_accounts`)??e}),"list-remote-targets":async()=>n.listRemoteTargets?{targets:(await n.listRemoteTargets()).filter(e=>e.targetId.includes(`:`)).map(e=>({targetId:e.targetId,title:e.title,url:e.url}))}:{targets:[]},"remote-cdp-send":async({runtimeId:e,localTargetId:t,method:r,params:i,sessionId:a,timeout:o})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.send({runtimeId:e,localTargetId:t,method:r,params:i,sessionId:a,timeout:o})},"remote-cdp-subscribe":async({runtimeId:e,localTargetId:t,event:r})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.subscribe({runtimeId:e,localTargetId:t,event:r})},"remote-cdp-unsubscribe":async({runtimeId:e,localTargetId:t,event:r})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.unsubscribe({runtimeId:e,localTargetId:t,event:r})},"remote-cdp-detach":async({runtimeId:e,localTargetId:t})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.detach({runtimeId:e,localTargetId:t})},"remote-open-tab":async({runtimeId:e,url:t})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.openTab({runtimeId:e,url:t})}}}var r=1500;async function i(e){if(!navigator.mediaDevices?.getUserMedia)throw Error(`getUserMedia is not supported in this browser`);let t=e.mode===`photo`||e.captureVideo!==!1,n=!!e.captureAudio&&e.mode===`video`;if(!t&&!n)throw Error(`camera capture: at least one of video or audio must be requested`);let i=await o({wantVideo:t,videoDeviceId:t?await a(e.deviceId,`videoinput`):void 0,audioDeviceId:n?await a(e.audioDeviceId,`audioinput`):void 0,wantAudio:n,width:e.width,height:e.height,frameRate:e.frameRate,exact:!!e.exactSize});try{let n=null,a=0,o=0;if(t){n=document.createElement(`video`),n.srcObject=i,n.muted=!0,n.playsInline=!0;let e=n;await new Promise((t,n)=>{e.onloadedmetadata=()=>e.play().then(()=>t()).catch(n),e.onerror=()=>n(Error(`Failed to load camera stream`))}),await new Promise(e=>requestAnimationFrame(()=>e())),await new Promise(e=>requestAnimationFrame(()=>e())),a=e.videoWidth,o=e.videoHeight}if(e.mode===`photo`){if(!n)throw Error(`photo capture requires a video track`);let t=e.warmupMs??r;t>0&&await new Promise(e=>setTimeout(e,t));let i=document.createElement(`canvas`);i.width=a,i.height=o;let s=i.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(n,0,0,a,o);let c=await new Promise((t,n)=>{i.toBlob(e=>e?t(e):n(Error(`Failed to encode photo`)),e.mimeType,e.quality)});return{bytes:await c.arrayBuffer(),mimeType:c.type||e.mimeType,width:a,height:o}}let s=Math.max(100,Math.min(e.durationMs??5e3,6e4)),c=typeof MediaRecorder<`u`&&MediaRecorder.isTypeSupported(e.mimeType)?e.mimeType:`video/webm`,l=new MediaRecorder(i,{mimeType:c}),u=[];l.ondataavailable=e=>{e.data&&e.data.size>0&&u.push(e.data)};let d=new Promise(e=>{l.onstop=()=>e()});l.start(),await new Promise(e=>setTimeout(e,s)),l.stop(),await d;let f=new Blob(u,{type:c});return{bytes:await f.arrayBuffer(),mimeType:f.type||c,width:a,height:o,durationMs:s}}finally{i.getTracks().forEach(e=>{e.stop()})}}async function a(e,t){if(e===void 0||e===``)return;if(!/^\d+$/.test(e))return e;if(!navigator.mediaDevices?.enumerateDevices)return;let n=parseInt(e,10);return(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===t)[n]?.deviceId}async function o(e){let t=t=>{if(!e.wantVideo)return!1;let n={};return e.videoDeviceId&&(n.deviceId={exact:e.videoDeviceId}),e.width&&(n.width=t===`exact`?{exact:e.width}:{ideal:e.width}),e.height&&(n.height=t===`exact`?{exact:e.height}:{ideal:e.height}),e.frameRate&&(n.frameRate=t===`exact`?{exact:e.frameRate}:{ideal:e.frameRate}),Object.keys(n).length>0?n:!0},n=()=>e.wantAudio?e.audioDeviceId?{deviceId:{exact:e.audioDeviceId}}:!0:!1;try{return await navigator.mediaDevices.getUserMedia({video:t(e.exact?`exact`:`ideal`),audio:n()})}catch(r){let i=r?.name;if(!e.exact||i!==`OverconstrainedError`&&i!==`NotReadableError`)throw r;return console.warn(`panel-rpc:capture-camera: exact ${e.width??`?`}x${e.height??`?`}@${e.frameRate??`?`} unmet, falling back to ideal`),await navigator.mediaDevices.getUserMedia({video:t(`ideal`),audio:n()})}}function s(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=()=>{r||(r=!0,window.removeEventListener(`message`,o),clearTimeout(s),i&&clearInterval(i))},o=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(a(),e.data.error){console.error(`[panel-rpc:oauth-popup] OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,o),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(a(),n.error){console.error(`[panel-rpc:oauth-popup] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[panel-rpc:oauth-popup] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3);let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}function c(e){return{name:e.name,lang:e.lang,default:e.default}}async function l(e,t){if(!navigator.mediaDevices?.getDisplayMedia)throw Error(`screen capture is not supported in this browser`);let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)})}finally{n.getTracks().forEach(e=>{e.stop()})}}async function u(e){let t=URL.createObjectURL(e);try{let e=new Image;return await new Promise((n,r)=>{e.onload=()=>n(),e.onerror=()=>r(Error(`Failed to decode capture`)),e.src=t}),{width:e.naturalWidth,height:e.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function d(e){let t=URL.createObjectURL(e);try{let e=new Image;await new Promise((n,r)=>{e.onload=()=>n(),e.onerror=()=>r(Error(`Failed to load image for clipboard conversion`)),e.src=t});let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);return r.drawImage(e,0,0),await new Promise((e,t)=>{n.toBlob(n=>n?e(n):t(Error(`PNG re-encode failed`)),`image/png`)})}finally{URL.revokeObjectURL(t)}}async function f(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}export{n as createStandalonePanelRpcHandlers};
1
+ import{a as e,p as t}from"./main-BtoNCPyQ.js";function n(n={}){return{"page-info":()=>({origin:window.location.origin,href:window.location.href,title:document.title||``}),screencapture:async({mimeType:e,quality:t})=>{let n=await l(e,t),r=await n.arrayBuffer(),i=await u(n);return{bytes:r,width:i.width,height:i.height,mimeType:e}},"speak-text":async({text:e,lang:t,voice:n,rate:r,pitch:i,volume:a})=>{if(typeof speechSynthesis>`u`)throw Error(`speechSynthesis is unavailable in this page`);return await new Promise((o,s)=>{let c=new SpeechSynthesisUtterance(e);if(t!==void 0&&(c.lang=t),r!==void 0&&(c.rate=r),i!==void 0&&(c.pitch=i),a!==void 0&&(c.volume=a),n){let e=speechSynthesis.getVoices().find(e=>e.name===n);e&&(c.voice=e)}c.onend=()=>o(),c.onerror=e=>s(Error(`speak: ${e.error||`utterance failed`}`)),speechSynthesis.speak(c)}),{done:!0}},"list-voices":async()=>{if(typeof speechSynthesis>`u`)throw Error(`speechSynthesis is unavailable in this page`);let e=speechSynthesis.getVoices();return e.length>0?{voices:e.map(c)}:{voices:(await new Promise(e=>{let t=()=>{speechSynthesis.removeEventListener(`voiceschanged`,t),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,t),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,t),e(speechSynthesis.getVoices())},1e3)})).map(c)}},"play-audio":async({bytes:e,volume:t})=>{if(typeof AudioContext>`u`)throw Error(`Web Audio API is unavailable in this page`);let n=new AudioContext;try{let r=await n.decodeAudioData(e.slice(0)),i=n.createBufferSource();if(i.buffer=r,t!==void 0){let e=n.createGain();e.gain.value=Math.max(0,Math.min(1,t)),i.connect(e),e.connect(n.destination)}else i.connect(n.destination);await new Promise(e=>{i.onended=()=>e(),i.start()})}finally{try{await n.close()}catch{}}return{done:!0}},"play-chime":async({tone:e})=>{let t={success:[880,1320],error:[440,220],notify:[660,660]},[n,r]=t[e??`notify`]??t.notify;if(typeof AudioContext>`u`)throw Error(`Web Audio API is unavailable in this page`);let i=new AudioContext;try{let e=i.currentTime;for(let[t,a]of[n,r].entries()){let n=i.createOscillator();n.type=`sine`,n.frequency.value=a;let r=i.createGain();r.gain.setValueAtTime(1e-4,e+t*.18),r.gain.exponentialRampToValueAtTime(.2,e+t*.18+.02),r.gain.exponentialRampToValueAtTime(1e-4,e+t*.18+.18),n.connect(r),r.connect(i.destination),n.start(e+t*.18),n.stop(e+t*.18+.2)}await new Promise(e=>setTimeout(e,450))}finally{try{await i.close()}catch{}}return{done:!0}},"clipboard-read-text":async()=>{if(!navigator.clipboard?.readText)throw Error(`clipboard API unavailable`);return{text:await navigator.clipboard.readText()}},"clipboard-write-text":async({text:e})=>{if(!navigator.clipboard?.writeText)throw Error(`clipboard API unavailable`);return await f(),await navigator.clipboard.writeText(e),{done:!0}},"clipboard-write-image":async({bytes:e,mimeType:t})=>{if(!navigator.clipboard?.write||typeof ClipboardItem>`u`)throw Error(`clipboard image API unavailable`);let n,r=new Blob([e],{type:t});return n=t===`image/png`?r:await d(r),await f(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{done:!0}},"window-open":async({url:e,target:t,features:n})=>({opened:window.open(e,t??`_blank`,n??`noopener,noreferrer`)!==null}),"oauth-popup":async({url:e})=>({redirectUrl:await s(e)}),"capture-camera":async e=>await i(e),"enumerate-media-devices":async()=>{if(!navigator.mediaDevices?.enumerateDevices)throw Error(`enumerateDevices is not supported in this browser`);let e=await navigator.mediaDevices.enumerateDevices(),t=e=>({deviceId:e.deviceId,label:e.label||``,...e.groupId?{groupId:e.groupId}:{}});return{videoinputs:e.filter(e=>e.kind===`videoinput`).map(t),audioinputs:e.filter(e=>e.kind===`audioinput`).map(t)}},"tray-reset":async()=>{if(!n.resetTray)throw Error(`host reset: no active tray session to reset`);return await n.resetTray()},"tray-leave":async({workerBaseUrl:e,requestId:t})=>{if(!n.leaveTray)throw Error(`host leave: tray leave is not available in this environment`);return await n.leaveTray({workerBaseUrl:e,requestId:t})},"cherry-emit":async({runtimeId:e,name:t,detail:r})=>{if(!n.emitCherrySliccEvent)throw Error(`cherry-emit: not available in this environment`);return{delivered:n.emitCherrySliccEvent(e,t,r)}},"oauth-extras-set":({providerId:n,domains:r})=>(t(n,r),{storeAfter:e()}),"save-oauth-accounts":({accountsJson:e})=>(localStorage.setItem(`slicc_accounts`,e),{storedJson:localStorage.getItem(`slicc_accounts`)??e}),"list-remote-targets":async()=>n.listRemoteTargets?{targets:(await n.listRemoteTargets()).filter(e=>e.targetId.includes(`:`)).map(e=>({targetId:e.targetId,title:e.title,url:e.url}))}:{targets:[]},"remote-cdp-send":async({runtimeId:e,localTargetId:t,method:r,params:i,sessionId:a,timeout:o})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.send({runtimeId:e,localTargetId:t,method:r,params:i,sessionId:a,timeout:o})},"remote-cdp-subscribe":async({runtimeId:e,localTargetId:t,event:r})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.subscribe({runtimeId:e,localTargetId:t,event:r})},"remote-cdp-unsubscribe":async({runtimeId:e,localTargetId:t,event:r})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.unsubscribe({runtimeId:e,localTargetId:t,event:r})},"remote-cdp-detach":async({runtimeId:e,localTargetId:t})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.detach({runtimeId:e,localTargetId:t})},"remote-open-tab":async({runtimeId:e,url:t})=>{if(!n.remoteCdp)throw Error(`remote-cdp bridge not available`);return n.remoteCdp.openTab({runtimeId:e,url:t})}}}var r=1500;async function i(e){if(!navigator.mediaDevices?.getUserMedia)throw Error(`getUserMedia is not supported in this browser`);let t=e.mode===`photo`||e.captureVideo!==!1,n=!!e.captureAudio&&e.mode===`video`;if(!t&&!n)throw Error(`camera capture: at least one of video or audio must be requested`);let i=await o({wantVideo:t,videoDeviceId:t?await a(e.deviceId,`videoinput`):void 0,audioDeviceId:n?await a(e.audioDeviceId,`audioinput`):void 0,wantAudio:n,width:e.width,height:e.height,frameRate:e.frameRate,exact:!!e.exactSize});try{let n=null,a=0,o=0;if(t){n=document.createElement(`video`),n.srcObject=i,n.muted=!0,n.playsInline=!0;let e=n;await new Promise((t,n)=>{e.onloadedmetadata=()=>e.play().then(()=>t()).catch(n),e.onerror=()=>n(Error(`Failed to load camera stream`))}),await new Promise(e=>requestAnimationFrame(()=>e())),await new Promise(e=>requestAnimationFrame(()=>e())),a=e.videoWidth,o=e.videoHeight}if(e.mode===`photo`){if(!n)throw Error(`photo capture requires a video track`);let t=e.warmupMs??r;t>0&&await new Promise(e=>setTimeout(e,t));let i=document.createElement(`canvas`);i.width=a,i.height=o;let s=i.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(n,0,0,a,o);let c=await new Promise((t,n)=>{i.toBlob(e=>e?t(e):n(Error(`Failed to encode photo`)),e.mimeType,e.quality)});return{bytes:await c.arrayBuffer(),mimeType:c.type||e.mimeType,width:a,height:o}}let s=Math.max(100,Math.min(e.durationMs??5e3,6e4)),c=typeof MediaRecorder<`u`&&MediaRecorder.isTypeSupported(e.mimeType)?e.mimeType:`video/webm`,l=new MediaRecorder(i,{mimeType:c}),u=[];l.ondataavailable=e=>{e.data&&e.data.size>0&&u.push(e.data)};let d=new Promise(e=>{l.onstop=()=>e()});l.start(),await new Promise(e=>setTimeout(e,s)),l.stop(),await d;let f=new Blob(u,{type:c});return{bytes:await f.arrayBuffer(),mimeType:f.type||c,width:a,height:o,durationMs:s}}finally{i.getTracks().forEach(e=>{e.stop()})}}async function a(e,t){if(e===void 0||e===``)return;if(!/^\d+$/.test(e))return e;if(!navigator.mediaDevices?.enumerateDevices)return;let n=parseInt(e,10);return(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===t)[n]?.deviceId}async function o(e){let t=t=>{if(!e.wantVideo)return!1;let n={};return e.videoDeviceId&&(n.deviceId={exact:e.videoDeviceId}),e.width&&(n.width=t===`exact`?{exact:e.width}:{ideal:e.width}),e.height&&(n.height=t===`exact`?{exact:e.height}:{ideal:e.height}),e.frameRate&&(n.frameRate=t===`exact`?{exact:e.frameRate}:{ideal:e.frameRate}),Object.keys(n).length>0?n:!0},n=()=>e.wantAudio?e.audioDeviceId?{deviceId:{exact:e.audioDeviceId}}:!0:!1;try{return await navigator.mediaDevices.getUserMedia({video:t(e.exact?`exact`:`ideal`),audio:n()})}catch(r){let i=r?.name;if(!e.exact||i!==`OverconstrainedError`&&i!==`NotReadableError`)throw r;return console.warn(`panel-rpc:capture-camera: exact ${e.width??`?`}x${e.height??`?`}@${e.frameRate??`?`} unmet, falling back to ideal`),await navigator.mediaDevices.getUserMedia({video:t(`ideal`),audio:n()})}}function s(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=()=>{r||(r=!0,window.removeEventListener(`message`,o),clearTimeout(s),i&&clearInterval(i))},o=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(a(),e.data.error){console.error(`[panel-rpc:oauth-popup] OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,o),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(a(),n.error){console.error(`[panel-rpc:oauth-popup] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[panel-rpc:oauth-popup] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3);let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}function c(e){return{name:e.name,lang:e.lang,default:e.default}}async function l(e,t){if(!navigator.mediaDevices?.getDisplayMedia)throw Error(`screen capture is not supported in this browser`);let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)})}finally{n.getTracks().forEach(e=>{e.stop()})}}async function u(e){let t=URL.createObjectURL(e);try{let e=new Image;return await new Promise((n,r)=>{e.onload=()=>n(),e.onerror=()=>r(Error(`Failed to decode capture`)),e.src=t}),{width:e.naturalWidth,height:e.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function d(e){let t=URL.createObjectURL(e);try{let e=new Image;await new Promise((n,r)=>{e.onload=()=>n(),e.onerror=()=>r(Error(`Failed to load image for clipboard conversion`)),e.src=t});let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);return r.drawImage(e,0,0),await new Promise((e,t)=>{n.toBlob(n=>n?e(n):t(Error(`PNG re-encode failed`)),`image/png`)})}finally{URL.revokeObjectURL(t)}}async function f(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}export{n as createStandalonePanelRpcHandlers};