sliccy 2.48.0 → 2.49.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 (144) hide show
  1. package/README.md +1 -1
  2. package/dist/ui/assets/{adobe-f1RkQ2LG.js → adobe-DgFQQrOg.js} +1 -1
  3. package/dist/ui/assets/{adobe-B5JX3vSF.js → adobe-Dreg1wVK.js} +2 -2
  4. package/dist/ui/assets/{agent-bridge-KerdP1oi.js → agent-bridge-DQExUBtZ.js} +1 -1
  5. package/dist/ui/assets/{agent-message-to-chat-rNxH0eRL.js → agent-message-to-chat-CHszPkfe.js} +1 -1
  6. package/dist/ui/assets/anthropic-8dSWvEaO.js +39 -0
  7. package/dist/ui/assets/{anthropic-DXIx8WQZ.js → anthropic-CQXRZrKe.js} +2 -2
  8. package/dist/ui/assets/{azure-openai-Bbb6cKeV.js → azure-openai-DljwQRpg.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-jVgW-OuR.js → azure-openai-Z75yrg_y.js} +1 -1
  10. package/dist/ui/assets/azure-openai-responses-B6VpI3fU.js +1 -0
  11. package/dist/ui/assets/azure-openai-responses-BruPNuxz.js +1 -0
  12. package/dist/ui/assets/backend-local-P05Hg6Af.js +9 -0
  13. package/dist/ui/assets/backend-local-mju0Ps5U.js +9 -0
  14. package/dist/ui/assets/bedrock-camp-9aDiXDk5.js +5 -0
  15. package/dist/ui/assets/bedrock-camp-CqXHYC67.js +4 -0
  16. package/dist/ui/assets/{cdp-C1_c8-E0.js → cdp-D-xyOaeF.js} +2 -2
  17. package/dist/ui/assets/cost-command-BOnG0NY3.js +1 -0
  18. package/dist/ui/assets/{dist-CxsgJFgV.js → dist-6maigE1F.js} +1 -1
  19. package/dist/ui/assets/{dist-BqCqxkrA.js → dist-8qo5XTx8.js} +1 -1
  20. package/dist/ui/assets/{dist-Sngeewv4.js → dist-DGI-KRHb.js} +1 -1
  21. package/dist/ui/assets/{dist-DPNMKo07.js → dist-DTOmXa93.js} +1 -1
  22. package/dist/ui/assets/{dist-USoe4ZIh.js → dist-Nvn9jT7s.js} +1 -1
  23. package/dist/ui/assets/env-api-keys-CH1OdZie.js +1 -0
  24. package/dist/ui/assets/env-api-keys-DxKb6C4Q.js +1 -0
  25. package/dist/ui/assets/{es-CbuIWQjf.js → es-DYpNCglL.js} +1 -1
  26. package/dist/ui/assets/{fs-Ch4z-7e8.js → fs-J4meBUCH.js} +3 -3
  27. package/dist/ui/assets/{fs-C8QxzFK_.js → fs-_TOckX3i.js} +2 -2
  28. package/dist/ui/assets/{github-DnfkA3fV.js → github-Cyp5HOCt.js} +1 -1
  29. package/dist/ui/assets/github-DIojNo8-.js +2 -0
  30. package/dist/ui/assets/google-BszFYcuS.js +1 -0
  31. package/dist/ui/assets/google-CYM-5k2z.js +1 -0
  32. package/dist/ui/assets/{google-shared-b8limp-0.js → google-shared-D_QrelB6.js} +1 -1
  33. package/dist/ui/assets/{google-shared-CEbAcMay.js → google-shared-XoadLsBb.js} +1 -1
  34. package/dist/ui/assets/{google-vertex-nFbLM1jr.js → google-vertex-ByJZJUMR.js} +1 -1
  35. package/dist/ui/assets/{google-vertex-DhlxvV6o.js → google-vertex-qkuMo_cz.js} +1 -1
  36. package/dist/ui/assets/{index-BxaasNW5.js → index-BqTqpjeH.js} +153 -163
  37. package/dist/ui/assets/json-parse-C5jSA6JB.js +3 -0
  38. package/dist/ui/assets/json-parse-Or9qhSeP.js +3 -0
  39. package/dist/ui/assets/{kernel-worker-BTAvhT7r.js → kernel-worker-CQw5MMmq.js} +883 -899
  40. package/dist/ui/assets/{local-llm-DQQUPDay.js → local-llm-CPVFxdug.js} +1 -1
  41. package/dist/ui/assets/{local-llm-BQQV1eUs.js → local-llm-g0wnxbDi.js} +1 -1
  42. package/dist/ui/assets/{magick-wasm-DwA3cs4T.js → magick-wasm-CTqVspRN.js} +1 -1
  43. package/dist/ui/assets/{magick-wasm-Dek2V-_y.js → magick-wasm-VuSQ-PNC.js} +1 -1
  44. package/dist/ui/assets/{mistral-BvJc11au.js → mistral-7vMFlwyv.js} +2 -2
  45. package/dist/ui/assets/{mistral-D_QxZUo3.js → mistral-BZdZwhYA.js} +2 -2
  46. package/dist/ui/assets/mount-B1Yosetn.js +2 -0
  47. package/dist/ui/assets/mount-rVcltyQp.js +1 -0
  48. package/dist/ui/assets/mount-table-store-BDnU4NqG.js +1 -0
  49. package/dist/ui/assets/{nuke-command-CKv7dPLq.js → nuke-command-6I6vn_OB.js} +1 -1
  50. package/dist/ui/assets/{oauth-bootstrap-iOQY9ywE.js → oauth-bootstrap-BhTDTASJ.js} +1 -1
  51. package/dist/ui/assets/{oauth-service-DTHr_ILl.js → oauth-service-BgJZh8oA.js} +1 -1
  52. package/dist/ui/assets/{oauth-service-BynE1niO.js → oauth-service-s6wxPNhT.js} +1 -1
  53. package/dist/ui/assets/offscreen-client-D_yQhOLu.js +1 -0
  54. package/dist/ui/assets/{onboarding-orchestrator-BTbcOsYi.js → onboarding-orchestrator-0jBXpPO0.js} +1 -1
  55. package/dist/ui/assets/{openai-codex-responses-ZTcDLOww.js → openai-codex-responses-BOuesx1c.js} +4 -4
  56. package/dist/ui/assets/{openai-codex-responses-jw3eMyAW.js → openai-codex-responses-DW3ZYFcb.js} +3 -3
  57. package/dist/ui/assets/openai-completions-D5rB4vsV.js +5 -0
  58. package/dist/ui/assets/openai-completions-ytvpg3gQ.js +5 -0
  59. package/dist/ui/assets/openai-responses-8f3sjZ0n.js +1 -0
  60. package/dist/ui/assets/openai-responses-CF3yEStf.js +1 -0
  61. package/dist/ui/assets/openai-responses-shared-DJ_O7os_.js +12 -0
  62. package/dist/ui/assets/{openai-responses-shared-Cb6xPI3z.js → openai-responses-shared-vokXRwgV.js} +1 -1
  63. package/dist/ui/assets/provider-settings-Ug5jEGjw.js +28 -0
  64. package/dist/ui/assets/provider-settings-rnwJD-hi.js +63 -0
  65. package/dist/ui/assets/{providers-DyuaLPXN.js → providers-CM4udL4d.js} +1 -1
  66. package/dist/ui/assets/{py-realm-worker-CiPbLFx2.js → py-realm-worker-Cg-6whKO.js} +1 -1
  67. package/dist/ui/assets/{pyodide-C2X7foBW.js → pyodide-DhfjhWo1.js} +1 -1
  68. package/dist/ui/assets/{pyodide-DM3gAwss.js → pyodide-DwCMl2Ja.js} +1 -1
  69. package/dist/ui/assets/{remote-terminal-view-B3w1XsI8.js → remote-terminal-view-BjoQOWNM.js} +3 -3
  70. package/dist/ui/assets/{slicc-editor-DAgxp34c.js → slicc-editor-DlLebxYv.js} +2 -2
  71. package/dist/ui/assets/{spawn-X9L04o6Q.js → spawn-C0I0kFhe.js} +1 -1
  72. package/dist/ui/assets/{sql-wasm-CqUynK8y.js → sql-wasm-eXBRXMXY.js} +1 -1
  73. package/dist/ui/assets/telemetry-B7l3TtVP.js +1 -0
  74. package/dist/ui/assets/tool-ui-B3Bihlxa.js +1 -0
  75. package/dist/ui/assets/tool-ui-D9h6SJkp.js +1 -0
  76. package/dist/ui/assets/{upgrade-detection-Bllbwwis.js → upgrade-detection-D1m3U6nl.js} +1 -1
  77. package/dist/ui/electron-overlay-entry.js +7 -7
  78. package/dist/ui/index.html +14 -10
  79. package/dist/ui/packages/webapp/index.html +14 -10
  80. package/package.json +3 -3
  81. package/dist/ui/assets/anthropic-DqN-XhOb.js +0 -39
  82. package/dist/ui/assets/azure-openai-responses-BLClomsm.js +0 -1
  83. package/dist/ui/assets/azure-openai-responses-DucvnACK.js +0 -1
  84. package/dist/ui/assets/bedrock-camp-BNzU3faS.js +0 -5
  85. package/dist/ui/assets/bedrock-camp-DAEKkMwP.js +0 -4
  86. package/dist/ui/assets/cost-command-DszplwaG.js +0 -1
  87. package/dist/ui/assets/github-Bm46hrl1.js +0 -2
  88. package/dist/ui/assets/google-D6ha3Lvd.js +0 -1
  89. package/dist/ui/assets/google-DmmMEYi-.js +0 -1
  90. package/dist/ui/assets/mount-CBj4Y0uY.js +0 -1
  91. package/dist/ui/assets/mount-XM0MMGbg.js +0 -2
  92. package/dist/ui/assets/offscreen-client-Bm3MzxIR.js +0 -1
  93. package/dist/ui/assets/openai-completions-DeKhvKno.js +0 -5
  94. package/dist/ui/assets/openai-completions-rPhCMQf6.js +0 -5
  95. package/dist/ui/assets/openai-responses-09Y9u2o-.js +0 -1
  96. package/dist/ui/assets/openai-responses-BYVIjcrN.js +0 -1
  97. package/dist/ui/assets/openai-responses-shared-BSdTPGXk.js +0 -12
  98. package/dist/ui/assets/provider-settings-B88plz7u.js +0 -63
  99. package/dist/ui/assets/provider-settings-YeoYrehC.js +0 -28
  100. /package/dist/ui/assets/{__vite-browser-external-BvI1wG2f.js → __vite-browser-external-ChUuVKj-.js} +0 -0
  101. /package/dist/ui/assets/{addon-fit-DYt1qsAX.js → addon-fit-BCjyTVK7.js} +0 -0
  102. /package/dist/ui/assets/{addon-fit-B0aHsvmX.js → addon-fit-CVV7fTw9.js} +0 -0
  103. /package/dist/ui/assets/{azure-ai-foundry-CaxHzIfg.js → azure-ai-foundry-BS3xCper.js} +0 -0
  104. /package/dist/ui/assets/{azure-ai-foundry-Bcv3AvZm.js → azure-ai-foundry-rmhg6ipI.js} +0 -0
  105. /package/dist/ui/assets/{bsh-watchdog-DEvn8Q9x.js → bsh-watchdog-D59Tbl5E.js} +0 -0
  106. /package/dist/ui/assets/{chat-fixture-5h_JuUYl.js → chat-fixture-CZVZdKyJ.js} +0 -0
  107. /package/dist/ui/assets/{diagnostics-5umns3WY.js → diagnostics-COTIkqqc.js} +0 -0
  108. /package/dist/ui/assets/{diagnostics-BowEoTPl.js → diagnostics-DEZCW87A.js} +0 -0
  109. /package/dist/ui/assets/{dist-Ct5XR8EU.js → dist-BzFg7Vf5.js} +0 -0
  110. /package/dist/ui/assets/{dist-zlAHCcD1.js → dist-DNQ3u_NS.js} +0 -0
  111. /package/dist/ui/assets/{git-config-BMEHAjvp.js → git-config-Bl-XsMb6.js} +0 -0
  112. /package/dist/ui/assets/{git-config-DZUguBxI.js → git-config-CxvDN7N3.js} +0 -0
  113. /package/dist/ui/assets/{github-copilot-headers-C8KSO_i5.js → github-copilot-headers-B6Fvsk-Y.js} +0 -0
  114. /package/dist/ui/assets/{github-copilot-headers-DLK82thn.js → github-copilot-headers-DFUtSIuj.js} +0 -0
  115. /package/dist/ui/assets/{hash-B7CztTb_.js → hash-CQjDwcjR.js} +0 -0
  116. /package/dist/ui/assets/{hash-BwzabXYv.js → hash-CsofV07h.js} +0 -0
  117. /package/dist/ui/assets/{headers-CRXCny-K.js → headers-BCPSYYop.js} +0 -0
  118. /package/dist/ui/assets/{headers-CeeP1wvy.js → headers-DkHU-pcw.js} +0 -0
  119. /package/dist/ui/assets/{lick-manager-proxy-DwmV23nZ.js → lick-manager-proxy-B0RDZsAR.js} +0 -0
  120. /package/dist/ui/assets/{mime-types-CtECiBq5.js → mime-types-DVkB7Eq7.js} +0 -0
  121. /package/dist/ui/assets/{mount-id-BBl3dJu8.js → mount-id-Ccy4_G8i.js} +0 -0
  122. /package/dist/ui/assets/{mount-picker-popup-BLHoVG3y.js → mount-picker-popup-DJJfRF_c.js} +0 -0
  123. /package/dist/ui/assets/{openai-NzrumIkM.js → openai-CRGaNv9i.js} +0 -0
  124. /package/dist/ui/assets/{openai-Cya-48mD.js → openai-D6Fs9zDM.js} +0 -0
  125. /package/dist/ui/assets/{page-storage-sync-DEhI1xEB.js → page-storage-sync-BawH6Tr4.js} +0 -0
  126. /package/dist/ui/assets/{panel-rpc-g85bMVnq.js → panel-rpc-CgCAJfWO.js} +0 -0
  127. /package/dist/ui/assets/{panel-rpc-handlers-Cd0NeWGr.js → panel-rpc-handlers-DQC5qat8.js} +0 -0
  128. /package/dist/ui/assets/{path-utils-B73K5PBp.js → path-utils-CgbXfwyO.js} +0 -0
  129. /package/dist/ui/assets/{path-utils-CNNVZ3-O.js → path-utils-d3qOVZOu.js} +0 -0
  130. /package/dist/ui/assets/{pdfjs-BdNq0_-j.js → pdfjs-jzfXBGiL.js} +0 -0
  131. /package/dist/ui/assets/{remote-cache-BdYCICnT.js → remote-cache-DdfqyJ2A.js} +0 -0
  132. /package/dist/ui/assets/{rum-_zaGz-D7.js → rum-CMSkYNP8.js} +0 -0
  133. /package/dist/ui/assets/{sanitize-unicode-DANurEy1.js → sanitize-unicode-BD2XKRoV.js} +0 -0
  134. /package/dist/ui/assets/{sanitize-unicode-MlE1hQqG.js → sanitize-unicode-ncMKN_SD.js} +0 -0
  135. /package/dist/ui/assets/{secret-env-DES2XPkD.js → secret-env-VITP8dzh.js} +0 -0
  136. /package/dist/ui/assets/{simple-options-B0cR4giT.js → simple-options-imi_RHvn.js} +0 -0
  137. /package/dist/ui/assets/{sprinkle-bridge-channel-DJuNr3kv.js → sprinkle-bridge-channel-C5ki0FNk.js} +0 -0
  138. /package/dist/ui/assets/{sprinkle-bridge-channel-DhKQ_srk.js → sprinkle-bridge-channel-CHgv5aYx.js} +0 -0
  139. /package/dist/ui/assets/{sprinkle-proxy-Ci8JPwa_.js → sprinkle-proxy-8PgiiiqE.js} +0 -0
  140. /package/dist/ui/assets/{src-oRxlT3fT.js → src-BcpYRmFj.js} +0 -0
  141. /package/dist/ui/assets/{transform-messages-DlZklr1h.js → transform-messages-uhk4b6os.js} +0 -0
  142. /package/dist/ui/assets/{tray-follower-status-DmK3Afse.js → tray-follower-status-Bjjx7UWt.js} +0 -0
  143. /package/dist/ui/assets/{xterm-CeGiW_7a.js → xterm-B7kAlFoJ.js} +0 -0
  144. /package/dist/ui/assets/{xterm-D5M9QCcR.js → xterm-ucbPh68r.js} +0 -0
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-settings-Ug5jEGjw.js","assets/chunk-jRWAZmH_.js","assets/preload-helper-ca-nBW7U.js","assets/bedrock-camp-CqXHYC67.js","assets/env-api-keys-DxKb6C4Q.js","assets/simple-options-imi_RHvn.js","assets/json-parse-C5jSA6JB.js","assets/tray-follower-status-Bjjx7UWt.js","assets/logger-B-No_qN_.js","assets/tool-ui-B3Bihlxa.js","assets/telemetry-B7l3TtVP.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./mime-types-DL940yDZ.js";import{t as n}from"./preload-helper-ca-nBW7U.js";import{r}from"./backend-local-mju0Ps5U.js";var i=`slicc-mount-cache`,a=`listings`,o=`bodies`,s=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??i}isStale(e,t){return Date.now()-e>=(t??this.ttlMs)}async openDb(){return this.dbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(a)||e.createObjectStore(a),e.objectStoreNames.contains(o)||e.createObjectStore(o)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),this.dbPromise}key(e){return`${this.mountId}::${e}`}async getListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(a,`readonly`).objectStore(a).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putListing(e,t){let n=await this.openDb();return new Promise((r,i)=>{let o=n.transaction(a,`readwrite`),s={entries:t,cachedAt:Date.now()};o.objectStore(a).put(s,this.key(e)),o.oncomplete=()=>r(),o.onerror=()=>i(o.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(a,`readwrite`);i.objectStore(a).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async getBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(o,`readonly`).objectStore(o).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putBody(e,t,n){let r=await this.openDb(),i={body:t,etag:n,size:t.byteLength,cachedAt:Date.now()};try{await this.txPut(r,o,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,o,this.key(e),i)}catch{}return}throw t}}async invalidateBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(o,`readwrite`);i.objectStore(o).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async clearMount(){let e=await this.openDb(),t=`${this.mountId}::`,n=n=>new Promise((r,i)=>{let a=e.transaction(n,`readwrite`),o=a.objectStore(n),s=o.getAllKeys();s.onsuccess=()=>{for(let e of s.result)typeof e==`string`&&e.startsWith(t)&&o.delete(e)},a.oncomplete=()=>r(),a.onerror=()=>i(a.error)});await Promise.all([n(a),n(o)])}txPut(e,t,n,r){return new Promise((i,a)=>{let o=e.transaction(t,`readwrite`);o.objectStore(t).put(r,n),o.oncomplete=()=>i(),o.onerror=()=>a(o.error)})}async evictLru(e){let t=await this.openDb(),n=`${this.mountId}::`,r=await new Promise((e,r)=>{let i=t.transaction(o,`readonly`).objectStore(o),a=[],s=i.openCursor();s.onsuccess=()=>{let t=s.result;if(!t){e(a);return}if(typeof t.key==`string`&&t.key.startsWith(n)){let e=t.value;a.push({key:t.key,cachedAt:e.cachedAt})}t.continue()},s.onerror=()=>r(s.error)});r.sort((e,t)=>e.cachedAt-t.cachedAt);let i=Math.max(1,Math.ceil(r.length*e)),a=r.slice(0,i);await new Promise((e,n)=>{let r=t.transaction(o,`readwrite`),i=r.objectStore(o);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}},c=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function l(){let{getAccounts:e}=await n(async()=>{let{getAccounts:e}=await import(`./provider-settings-Ug5jEGjw.js`).then(e=>e.m);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])),t=e().find(e=>e.providerId===`adobe`);if(!t||!t.accessToken)throw new c(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}function u(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var d=25*1024*1024,f=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=u(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??d,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new r(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let i={};n&&(i[`if-none-match`]=n.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:i});if(a.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(a.status===404)throw await this.cache.invalidateBody(t),new r(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new r(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new r(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=await this.cache.getBody(n),a={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};i?a[`if-match`]=i.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:a,body:t}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let i=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(i.status>=400)throw new r(`EIO`,`s3 reconcile HEAD failed: ${i.status}`,e);let a=i.headers.get(`etag`)??``;await this.cache.putBody(n,t,a);let o=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new r(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new r(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new r(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(i.status>=400)throw new r(`EIO`,`s3 list failed: ${i.status}`,`/`);let a=await i.text(),o=this.parseListingXml(a);e.push(...o.contents),t=o.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let i=t.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===a);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new r(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new r(`ENOENT`,`no such file or directory`,e)}throw new r(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new r(`EINVAL`,`recursive remove not yet supported on S3`,e);let i=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(i.status===404)throw new r(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new r(`EACCES`,`s3 delete denied`,e);if(i.status>=400)throw new r(`EIO`,`s3 delete failed: ${i.status}`,e);await this.cache.invalidateBody(n);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function p(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function m(e){return e.split(`/`).pop()||`data`}function h(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=5*1024*1024,_=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??g,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new r(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let i={};n&&(i[`if-none-match`]=n.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:i});if(a.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(a.status===404)throw await this.cache.invalidateBody(t),new r(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new r(`EACCES`,`da access denied`,e);if(a.status>=400)throw new r(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=this.toMountRelative(e),a=await this.cache.getBody(i),o=p(m(e),t(e),n),s={"content-type":o.contentType,"content-length":String(o.body.byteLength)};a&&a.etag?s[`if-match`]=a.etag:a||(s[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(i),headers:s,body:o.body}),l,u=1;try{l=await c()}catch{u=2,l=await c()}if(l.status===412){if(u===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(i)});if(t.status>=400)throw new r(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let a=t.headers.get(`etag`)??``;await this.cache.putBody(i,n,a);let o=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(i);try{await this.readFile(e)}catch{}throw new r(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new r(`EACCES`,`da write denied`,e);if(l.status>=400)throw new r(`EIO`,`da writeFile failed: ${l.status}`,e);let d=l.headers.get(`etag`)??``;await this.cache.putBody(i,n,d);let f=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(f)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let i=await this.transport({method:`GET`,path:this.toListPath(t)});if(i.status===404)throw new r(`ENOENT`,`no such directory`,e);if(i.status>=400)throw new r(`EIO`,`da list failed: ${i.status}`,e);let a=(await i.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,a),a}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let i=t.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===a);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new r(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new r(`ENOENT`,`no such file or directory`,e)}throw new r(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new r(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new r(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new r(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let i=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});continue}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified});let i=await this.cache.getBody(n);i?r.etag&&i.etag!==r.etag?(await this.cache.invalidateBody(n),t.changed.push(n)):t.unchanged++:t.added.push(n)}else{a.push({name:r.name,kind:`directory`});let t=e?`${e}/${r.name}`:r.name;n.push(t)}await this.cache.putListing(e,a)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}if(e?.bodies)for(let e of t.changed)try{await this.readFile(e)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}return t}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function v(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function y(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function b(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}var x=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),S=new Set([101,103,204,205,304]);function C(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new r(`EACCES`,e.error):e.errorCode===`invalid_request`?new r(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||x.has(String(e.errorCode))?new r(`EIO`,e.error):new r(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=y(e.bodyBase64)}catch(e){throw new r(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=S.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function w(e,t){let n;try{n=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}catch(e){throw new r(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new r(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function T(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new r(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}function E(e){return async t=>{let n={profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?b(t.body):void 0};return C(v()?await T(`mount.s3-sign-and-forward`,n):await w(`/api/s3-sign-and-forward`,n))}}function D(e){let t=e?.getImsToken??(async()=>(await l()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new r(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}let i={imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?b(e.body):void 0};return C(v()?await T(`mount.da-sign-and-forward`,i):await w(`/api/da-sign-and-forward`,i))}}var O=e({DaMountBackend:()=>_,RemoteMountCache:()=>s,S3MountBackend:()=>f,makeSignedFetchDa:()=>D,makeSignedFetchS3:()=>E});export{f as a,_ as i,D as n,s as o,E as r,O as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-jRWAZmH_.js";import{i as t}from"./backend-local-P05Hg6Af.js";import{t as n}from"./mime-types-DVkB7Eq7.js";import{t as r}from"./remote-cache-DdfqyJ2A.js";function i(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var a=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=i(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new t(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=await this.cache.getBody(r),a={"content-type":`application/octet-stream`,"content-length":String(n.byteLength)};i?a[`if-match`]=i.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(r),headers:a,body:n}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let i=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status>=400)throw new t(`EIO`,`s3 reconcile HEAD failed: ${i.status}`,e);let a=i.headers.get(`etag`)??``;await this.cache.putBody(r,n,a);let o=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new t(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new t(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(r,n,l);let u=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],n;do{let r={"list-type":`2`};this.parsed.prefix&&(r.prefix=`${this.parsed.prefix}/`),n&&(r[`continuation-token`]=n);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:r});if(i.status>=400)throw new t(`EIO`,`s3 list failed: ${i.status}`,`/`);let a=await i.text(),o=this.parseListingXml(a);e.push(...o.contents),n=o.nextContinuationToken}while(n);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.body.byteLength,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n?.recursive)throw new t(`EINVAL`,`recursive remove not yet supported on S3`,e);let i=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status===404)throw new t(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new t(`EACCES`,`s3 delete denied`,e);if(i.status>=400)throw new t(`EIO`,`s3 delete failed: ${i.status}`,e);await this.cache.invalidateBody(r);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function o(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function s(e){return e.split(`/`).pop()||`data`}function c(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var l=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=c(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`da access denied`,e);if(a.status>=400)throw new t(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,r){if(this.assertOpen(e),r.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=this.toMountRelative(e),a=await this.cache.getBody(i),c=o(s(e),n(e),r),l={"content-type":c.contentType,"content-length":String(c.body.byteLength)};a&&a.etag?l[`if-match`]=a.etag:a||(l[`if-none-match`]=`*`);let u=()=>this.transport({method:`POST`,path:this.toSourcePath(i),headers:l,body:c.body}),d,f=1;try{d=await u()}catch{f=2,d=await u()}if(d.status===412){if(f===2){let n=await this.transport({method:`HEAD`,path:this.toSourcePath(i)});if(n.status>=400)throw new t(`EIO`,`da reconcile HEAD failed: ${n.status}`,e);let a=n.headers.get(`etag`)??``;await this.cache.putBody(i,r,a);let o=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(i);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(d.status===401||d.status===403)throw new t(`EACCES`,`da write denied`,e);if(d.status>=400)throw new t(`EIO`,`da writeFile failed: ${d.status}`,e);let p=d.headers.get(`etag`)??``;await this.cache.putBody(i,r,p);let m=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let n=this.toMountRelative(e).replace(/\/+$/,``),r=await this.cache.getListing(n);if(r&&!this.cache.isStale(r.cachedAt))return r.entries;let i=await this.transport({method:`GET`,path:this.toListPath(n)});if(i.status===404)throw new t(`ENOENT`,`no such directory`,e);if(i.status>=400)throw new t(`EIO`,`da list failed: ${i.status}`,e);let a=(await i.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(n,a),a}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.size,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.transport({method:`DELETE`,path:this.toSourcePath(n)});if(r.status===404)throw new t(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new t(`EACCES`,`da delete denied`,e);if(r.status>=400)throw new t(`EIO`,`da delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});continue}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified});let i=await this.cache.getBody(n);i?r.etag&&i.etag!==r.etag?(await this.cache.invalidateBody(n),t.changed.push(n)):t.unchanged++:t.added.push(n)}else{a.push({name:r.name,kind:`directory`});let t=e?`${e}/${r.name}`:r.name;n.push(t)}await this.cache.putListing(e,a)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}if(e?.bodies)for(let e of t.changed)try{await this.readFile(e)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}return t}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},u=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function d(){let{getAccounts:e}=await import(`./provider-settings-rnwJD-hi.js`).then(e=>e.l),t=e().find(e=>e.providerId===`adobe`);if(!t||!t.accessToken)throw new u(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}function f(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function p(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function m(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const h=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),g=new Set([101,103,204,205,304]);function _(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new t(`EACCES`,e.error):e.errorCode===`invalid_request`?new t(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||h.has(String(e.errorCode))?new t(`EIO`,e.error):new t(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let n;try{n=p(e.bodyBase64)}catch(e){throw new t(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let r=g.has(e.status)?null:n;return new Response(r,{status:e.status,headers:new Headers(e.headers)})}async function v(e,n){let r;try{r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new t(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function y(e,n){try{return await chrome.runtime.sendMessage({type:e,envelope:n})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}function b(e){return async t=>{let n={profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?m(t.body):void 0};return _(f()?await y(`mount.s3-sign-and-forward`,n):await v(`/api/s3-sign-and-forward`,n))}}function x(e){let n=e?.getImsToken??(async()=>(await d()).getBearerToken());return async e=>{let r;try{r=await n()}catch(e){throw new t(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}let i={imsToken:r,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?m(e.body):void 0};return _(f()?await y(`mount.da-sign-and-forward`,i):await v(`/api/da-sign-and-forward`,i))}}var S=e({DaMountBackend:()=>l,RemoteMountCache:()=>r,S3MountBackend:()=>a,makeSignedFetchDa:()=>x,makeSignedFetchS3:()=>b});export{a,l as i,x as n,b as r,S as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./mount-id-Ccy4_G8i.js";var n=e({clearMountEntries:()=>u,getAllMountEntries:()=>c,loadMountHandle:()=>l,removeMountEntry:()=>s,saveMountEntry:()=>o});const r=`mounts`,i=`mount-entries`;function a(){return new Promise((e,n)=>{let a=indexedDB.open(`slicc-mount-table`,2);a.onupgradeneeded=e=>{let n=a.result,o=e.oldVersion;if(n.objectStoreNames.contains(r)||n.createObjectStore(r),n.objectStoreNames.contains(i)||n.createObjectStore(i),o<2){let e=a.transaction,n=e.objectStore(r),o=e.objectStore(i),s=n.getAllKeys();s.onsuccess=()=>{for(let e of s.result){if(typeof e!=`string`)continue;let n={targetPath:e,descriptor:{kind:`local`,mountId:t(),idbHandleKey:e},createdAt:Date.now()};o.put(n,e)}}}},a.onsuccess=()=>e(a.result),a.onerror=()=>n(a.error)})}async function o(e,t){let n=await a();try{let a=e.descriptor.kind===`local`&&t?[r,i]:[i],o=n.transaction(a,`readwrite`);o.objectStore(i).put(e,e.targetPath),e.descriptor.kind===`local`&&t&&o.objectStore(r).put(t,e.descriptor.idbHandleKey),await new Promise((e,t)=>{o.oncomplete=()=>e(),o.onerror=()=>t(o.error),o.onabort=()=>t(o.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{n.close()}}async function s(e){let t=await a();try{let n=t.transaction([r,i],`readwrite`);n.objectStore(i).delete(e),n.objectStore(r).delete(e),await new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{t.close()}}async function c(){let e=await a();try{return await new Promise((t,n)=>{let r=e.transaction(i,`readonly`),a=r.objectStore(i).getAll();a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error),r.onabort=()=>n(r.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{e.close()}}async function l(e){let t=await a();try{return await new Promise((n,i)=>{let a=t.transaction(r,`readonly`).objectStore(r).get(e);a.onsuccess=()=>n(a.result??null),a.onerror=()=>i(a.error)})}finally{t.close()}}async function u(){let e=await a();try{let t=e.transaction([r,i],`readwrite`);t.objectStore(r).clear(),t.objectStore(i).clear(),await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error),t.onabort=()=>n(t.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{e.close()}}export{o as a,s as i,l as n,n as r,u as t};
@@ -1 +1 @@
1
- import"./index-BxaasNW5.js";var e=`slicc-nuke-control`;function t(t=()=>location.reload()){if(typeof BroadcastChannel!=`function`)return()=>{};let n=new BroadcastChannel(e),r=e=>{let n=e.data;if(n?.type===`nuke-reload`){if(Array.isArray(n.keysToRemove)){for(let e of n.keysToRemove)if(typeof e==`string`)try{localStorage.removeItem(e)}catch{}}t()}};return n.addEventListener(`message`,r),()=>{n.removeEventListener(`message`,r),n.close()}}export{t as installNukeReloadListener};
1
+ import"./index-BqTqpjeH.js";var e=`slicc-nuke-control`;function t(t=()=>location.reload()){if(typeof BroadcastChannel!=`function`)return()=>{};let n=new BroadcastChannel(e),r=e=>{let n=e.data;if(n?.type===`nuke-reload`){if(Array.isArray(n.keysToRemove)){for(let e of n.keysToRemove)if(typeof e==`string`)try{localStorage.removeItem(e)}catch{}}t()}};return n.addEventListener(`message`,r),()=>{n.removeEventListener(`message`,r),n.close()}}export{t as installNukeReloadListener};
@@ -1 +1 @@
1
- import{t as e}from"./logger-B-No_qN_.js";import{r as t,v as n,x as r}from"./provider-settings-YeoYrehC.js";var i=e(`oauth-bootstrap`),a=6e4;async function o(){let e=t();i.info(`Bootstrap OAuth replicas`,{count:e.length});for(let t of e){if(!t.accessToken){i.debug(`Skipping account without token`,{providerId:t.providerId});continue}if((t.tokenExpiresAt??1/0)-Date.now()<=a){let e=r(t.providerId);if(e?.onSilentRenew)try{if(await e.onSilentRenew()){i.info(`Silently renewed OAuth token`,{providerId:t.providerId});continue}i.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:t.providerId});continue}catch(e){i.warn(`Silent renewal failed`,{providerId:t.providerId,error:e instanceof Error?e.message:String(e)});continue}i.debug(`Skipping expired account (no silent-renew hook)`,{providerId:t.providerId});continue}try{await n({providerId:t.providerId,accessToken:t.accessToken,refreshToken:t.refreshToken,tokenExpiresAt:t.tokenExpiresAt,userName:t.userName,userAvatar:t.userAvatar}),i.debug(`Bootstrapped OAuth replica`,{providerId:t.providerId})}catch(e){i.error(`OAuth bootstrap failed`,{providerId:t.providerId,error:e instanceof Error?e.message:String(e)})}}}export{o as bootstrapOAuthReplicas};
1
+ import{t as e}from"./logger-B-No_qN_.js";import{r as t,v as n,x as r}from"./provider-settings-Ug5jEGjw.js";var i=e(`oauth-bootstrap`),a=6e4;async function o(){let e=t();i.info(`Bootstrap OAuth replicas`,{count:e.length});for(let t of e){if(!t.accessToken){i.debug(`Skipping account without token`,{providerId:t.providerId});continue}if((t.tokenExpiresAt??1/0)-Date.now()<=a){let e=r(t.providerId);if(e?.onSilentRenew)try{if(await e.onSilentRenew()){i.info(`Silently renewed OAuth token`,{providerId:t.providerId});continue}i.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:t.providerId});continue}catch(e){i.warn(`Silent renewal failed`,{providerId:t.providerId,error:e instanceof Error?e.message:String(e)});continue}i.debug(`Skipping expired account (no silent-renew hook)`,{providerId:t.providerId});continue}try{await n({providerId:t.providerId,accessToken:t.accessToken,refreshToken:t.refreshToken,tokenExpiresAt:t.tokenExpiresAt,userName:t.userName,userAvatar:t.userAvatar}),i.debug(`Bootstrapped OAuth replica`,{providerId:t.providerId})}catch(e){i.error(`OAuth bootstrap failed`,{providerId:t.providerId,error:e instanceof Error?e.message:String(e)})}}}export{o as bootstrapOAuthReplicas};
@@ -1 +1 @@
1
- import{getPanelRpcClient as e}from"./panel-rpc-g85bMVnq.js";var t=typeof chrome<`u`&&!!chrome?.runtime?.id;function n(){return t?a:typeof window>`u`?r:i}async function r(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 i(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(`[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`,o),(location.pathname.startsWith(`/electron`)||new URLSearchParams(location.search).get(`runtime`)===`electron-overlay`)&&(i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204)return;let n=await e.json();if(r)return;if(a(),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));let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}async function a(e){return new Promise(t=>{let n=!1,r=()=>{n||(n=!0,chrome.runtime.onMessage.removeListener(i),clearTimeout(a))},i=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(r(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),t(null);return}t(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(i),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let a=setTimeout(()=>{r(),t(null)},12e4)})}export{n as createOAuthLauncher};
1
+ import{getPanelRpcClient as e}from"./panel-rpc-CgCAJfWO.js";var t=typeof chrome<`u`&&!!chrome?.runtime?.id;function n(){return t?a:typeof window>`u`?r:i}async function r(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 i(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(`[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`,o),(location.pathname.startsWith(`/electron`)||new URLSearchParams(location.search).get(`runtime`)===`electron-overlay`)&&(i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204)return;let n=await e.json();if(r)return;if(a(),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));let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}async function a(e){return new Promise(t=>{let n=!1,r=()=>{n||(n=!0,chrome.runtime.onMessage.removeListener(i),clearTimeout(a))},i=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(r(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),t(null);return}t(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(i),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let a=setTimeout(()=>{r(),t(null)},12e4)})}export{n as createOAuthLauncher};
@@ -1 +1 @@
1
- import{i as e}from"./kernel-worker-BTAvhT7r.js";const t=typeof chrome<`u`&&!!chrome?.runtime?.id;function n(){return t?a:typeof window>`u`?r:i}async function r(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 i(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(`[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`,o),(location.pathname.startsWith(`/electron`)||new URLSearchParams(location.search).get(`runtime`)===`electron-overlay`)&&(i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204)return;let n=await e.json();if(r)return;if(a(),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));let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}async function a(e){return new Promise(t=>{let n=!1,r=()=>{n||(n=!0,chrome.runtime.onMessage.removeListener(i),clearTimeout(a))},i=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(r(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),t(null);return}t(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(i),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let a=setTimeout(()=>{r(),t(null)},12e4)})}export{n as createOAuthLauncher};
1
+ import{t as e}from"./kernel-worker-CQw5MMmq.js";const t=typeof chrome<`u`&&!!chrome?.runtime?.id;function n(){return t?a:typeof window>`u`?r:i}async function r(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 i(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(`[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`,o),(location.pathname.startsWith(`/electron`)||new URLSearchParams(location.search).get(`runtime`)===`electron-overlay`)&&(i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204)return;let n=await e.json();if(r)return;if(a(),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));let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}async function a(e){return new Promise(t=>{let n=!1,r=()=>{n||(n=!0,chrome.runtime.onMessage.removeListener(i),clearTimeout(a))},i=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(r(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),t(null);return}t(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(i),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let a=setTimeout(()=>{r(),t(null)},12e4)})}export{n as createOAuthLauncher};
@@ -0,0 +1 @@
1
+ import{t as e}from"./logger-B-No_qN_.js";import{n as t}from"./tray-follower-status-Bjjx7UWt.js";import{r as n}from"./index-BqTqpjeH.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;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;sendSprinkleLick(e,t,n){this.send({type:`sprinkle-lick`,sprinkleName:e,body:t,targetScoop: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`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{t as e}from"./logger-B-No_qN_.js";import{t}from"./index-BxaasNW5.js";var n=[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.`],r=[`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.`],i={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.`]},a={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.`]},o=[`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.`],s=[`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 c(e,t){return e[Math.floor(t()*e.length)%e.length]}function l(e){return e.replace(/-/g,` `)}function u(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 d(e,t=Math.random){let a=(e.name||``).trim(),o=e.purpose?i[e.purpose]:void 0;return a?`${c(n,t)(a)}${o?` ${c(o,t)}`:``}`:`${c(r,t)}${o?` ${c(o,t)}`:``}`}function f(e,t=Math.random){let n=e.role&&a[e.role]?e.role:``,r=c(n?a[n]:o,t),i=(e.tasks??[]).slice(0,3).map(l);return`I'm sliccy. ${r}${i.length>0?` Especially handy for ${u(i)}.`:``} I'm an AI agent.`}function p(e,t=Math.random){return c(s,t)}function m(e,t=Math.random){return[d(e,t),f(e,t),p(e,t)]}var h={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 g(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 _(e){let{provider:t,apiKey:n,baseUrl:r,signal:i}=e,a=e.fetchImpl??fetch,o=n.trim();if(!o)return{kind:`failed`,status:null,message:`API key is empty.`};let s=h[t];if(!s)return{kind:`skipped`,reason:`No live validation available for "${t}" — saving without testing.`};let c=s.url(r);if(t===`google`){let e=c.includes(`?`)?`&`:`?`;c=`${c}${e}key=${encodeURIComponent(o)}`}try{let e=await a(c,{method:`GET`,headers:s.headers(o),signal:i});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:g(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 v=e(`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(e){if(this.stage!==`idle`)return v.debug(`Ignoring duplicate onboarding-complete`,{stage:this.stage}),!0;this.profile=e??{},this.stage=`awaiting-connect`,t(this.deps.fs).catch(e=>v.warn(`recordWelcomed failed`,e)),this.persistProfile(this.profile).catch(e=>v.warn(`persistProfile failed`,e));let n=m(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:i,apiVersion:a,model:o}=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 s=(()=>{try{return this.deps.getProviderCatalogue().providers.find(e=>e.id===t)}catch{return}})();if(s?.requiresDeployment&&!i?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${s.name} requires a deployment name.`}),this.stage=`awaiting-connect`;return}if(s?.requiresBaseUrl&&!r?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${s.name} requires a base URL.`}),this.stage=`awaiting-connect`;return}let c;try{c=await _({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(c.kind===`failed`){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:c.message}),this.stage=`awaiting-connect`;return}let l=o||null;if(!l)try{let e=this.deps.getProviderCatalogue().models?.[t]?.[0]?.id;e&&(l=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,i?.trim()||void 0,a?.trim()||void 0),l&&this.deps.setSelectedModel(l)}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 u=c.kind===`skipped`?`Saved — ${c.reason}`:`Validated against the provider. Ready when you are.`;this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:c.kind,note:u});let d=l&&this.deps.resolveModelLabel?.(t,l)?this.deps.resolveModelLabel?.(t,l):l||null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:t,model:l??null,modelLabel:d,validation:c.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{t as e}from"./logger-B-No_qN_.js";import{t}from"./index-BqTqpjeH.js";var n=[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.`],r=[`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.`],i={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.`]},a={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.`]},o=[`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.`],s=[`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 c(e,t){return e[Math.floor(t()*e.length)%e.length]}function l(e){return e.replace(/-/g,` `)}function u(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 d(e,t=Math.random){let a=(e.name||``).trim(),o=e.purpose?i[e.purpose]:void 0;return a?`${c(n,t)(a)}${o?` ${c(o,t)}`:``}`:`${c(r,t)}${o?` ${c(o,t)}`:``}`}function f(e,t=Math.random){let n=e.role&&a[e.role]?e.role:``,r=c(n?a[n]:o,t),i=(e.tasks??[]).slice(0,3).map(l);return`I'm sliccy. ${r}${i.length>0?` Especially handy for ${u(i)}.`:``} I'm an AI agent.`}function p(e,t=Math.random){return c(s,t)}function m(e,t=Math.random){return[d(e,t),f(e,t),p(e,t)]}var h={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 g(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 _(e){let{provider:t,apiKey:n,baseUrl:r,signal:i}=e,a=e.fetchImpl??fetch,o=n.trim();if(!o)return{kind:`failed`,status:null,message:`API key is empty.`};let s=h[t];if(!s)return{kind:`skipped`,reason:`No live validation available for "${t}" — saving without testing.`};let c=s.url(r);if(t===`google`){let e=c.includes(`?`)?`&`:`?`;c=`${c}${e}key=${encodeURIComponent(o)}`}try{let e=await a(c,{method:`GET`,headers:s.headers(o),signal:i});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:g(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 v=e(`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(e){if(this.stage!==`idle`)return v.debug(`Ignoring duplicate onboarding-complete`,{stage:this.stage}),!0;this.profile=e??{},this.stage=`awaiting-connect`,t(this.deps.fs).catch(e=>v.warn(`recordWelcomed failed`,e)),this.persistProfile(this.profile).catch(e=>v.warn(`persistProfile failed`,e));let n=m(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:i,apiVersion:a,model:o}=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 s=(()=>{try{return this.deps.getProviderCatalogue().providers.find(e=>e.id===t)}catch{return}})();if(s?.requiresDeployment&&!i?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${s.name} requires a deployment name.`}),this.stage=`awaiting-connect`;return}if(s?.requiresBaseUrl&&!r?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${s.name} requires a base URL.`}),this.stage=`awaiting-connect`;return}let c;try{c=await _({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(c.kind===`failed`){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:c.message}),this.stage=`awaiting-connect`;return}let l=o||null;if(!l)try{let e=this.deps.getProviderCatalogue().models?.[t]?.[0]?.id;e&&(l=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,i?.trim()||void 0,a?.trim()||void 0),l&&this.deps.setSelectedModel(l)}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 u=c.kind===`skipped`?`Saved — ${c.reason}`:`Validated against the provider. Ready when you are.`;this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:c.kind,note:u});let d=l&&this.deps.resolveModelLabel?.(t,l)?this.deps.resolveModelLabel?.(t,l):l||null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:t,model:l??null,modelLabel:d,validation:c.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,7 +1,7 @@
1
- import{a as e,c as t,r as n}from"./transform-messages-DlZklr1h.js";import{i as r,n as i,r as a,t as o}from"./diagnostics-5umns3WY.js";import{t as s}from"./headers-CRXCny-K.js";import{r as c}from"./kernel-worker-BTAvhT7r.js";import{n as l,r as u,t as d}from"./openai-responses-shared-BSdTPGXk.js";let f=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(e=>import(e))(`node:os`).then(e=>{f=e});const p=1e3,m=new Set([`openai`,`openai-codex`,`opencode`]),h=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function g(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 _(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 v=(t,n,r)=>{let a=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,provider:t.provider,model:t.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||c(t.provider)||``;if(!l)throw Error(`No API key for provider: ${t.provider}`);let u=ue(l),d=b(t,n,r),f=await r?.onPayload?.(d,t);f!==void 0&&(d=f);let m=r?.sessionId||de(),h=fe(t.headers,r?.headers,u,l,r?.sessionId),v=pe(t.headers,r?.headers,u,l,m),y=JSON.stringify(d),x=r?.transport||`auto`,S=x!==`sse`&&B(r?.sessionId);if(S&&V(r?.sessionId),x!==`sse`&&!S){let n=!1;try{if(await ce(T(t.baseUrl),d,v,e,a,t,()=>{n=!0},r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end();return}catch(t){if(r?.signal?.aborted||k(t)||(o(e,i(`provider_transport_failure`,t,{configuredTransport:x,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(y).byteLength})),ee(r?.sessionId,t),n))throw t;V(r?.sessionId)}}let C,D;for(let e=0;e<=3;e++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{if(C=await fetch(w(t.baseUrl),{method:`POST`,headers:h,body:y,signal:r?.signal}),await r?.onResponse?.({status:C.status,headers:s(C.headers)},t),C.ok)break;let n=await C.text();if(e<3&&g(C.status,n)){await _(p*2**e,r?.signal);continue}let i=await le(new Response(n,{status:C.status,statusText:C.statusText}));throw Error(i.friendlyMessage||i.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(D=t instanceof Error?t:Error(String(t)),e<3&&!D.message.includes(`usage limit`)){await _(p*2**e,r?.signal);continue}throw D}}if(!C?.ok)throw D??Error(`Failed after retries`);if(!C.body)throw Error(`No response body`);if(a.push({type:`start`,partial:e}),await E(C,e,a,t,r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.partialJson;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:String(t),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},y=(e,r,i)=>{let a=i?.apiKey||c(e.provider);if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=n(e,i,a),s=i?.reasoning?t(e,i.reasoning):void 0,l=s===`off`?void 0:s;return v(e,r,{...o,reasoningEffort:l})};function b(e,t,n){let r=d(e,t,m,{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 T(e){let t=new URL(w(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function E(e,t,n,r,i){await u(A(M(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,r)})}var D=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}},O=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function k(e){return e instanceof D||e instanceof O}async function*A(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 D(`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 D(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:j(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function j(e){if(typeof e==`string`)return h.has(e)?e:void 0}async function*M(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let o=r.indexOf(`
1
+ import{t as e}from"./env-api-keys-CH1OdZie.js";import{a as t,c as n,r}from"./transform-messages-uhk4b6os.js";import{i,n as a,r as o,t as s}from"./diagnostics-COTIkqqc.js";import{t as c}from"./headers-BCPSYYop.js";import{n as l,r as u,t as d}from"./openai-responses-shared-DJ_O7os_.js";let f=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(e=>import(e))(`node:os`).then(e=>{f=e});const p=1e3,m=new Set([`openai`,`openai-codex`,`opencode`]),h=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function g(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 _(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 v=(n,r,i)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:`openai-codex-responses`,provider:n.provider,model:n.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=i?.apiKey||e(n.provider)||``;if(!l)throw Error(`No API key for provider: ${n.provider}`);let u=ue(l),d=b(n,r,i),f=await i?.onPayload?.(d,n);f!==void 0&&(d=f);let m=i?.sessionId||de(),h=fe(n.headers,i?.headers,u,l,i?.sessionId),v=pe(n.headers,i?.headers,u,l,m),y=JSON.stringify(d),x=i?.transport||`auto`,S=x!==`sse`&&B(i?.sessionId);if(S&&V(i?.sessionId),x!==`sse`&&!S){let e=!1;try{if(await ce(T(n.baseUrl),d,v,t,o,n,()=>{e=!0},i),i?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end();return}catch(n){if(i?.signal?.aborted||k(n)||(s(t,a(`provider_transport_failure`,n,{configuredTransport:x,fallbackTransport:e?void 0:`sse`,eventsEmitted:e,phase:e?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(y).byteLength})),ee(i?.sessionId,n),e))throw n;V(i?.sessionId)}}let C,D;for(let e=0;e<=3;e++){if(i?.signal?.aborted)throw Error(`Request was aborted`);try{if(C=await fetch(w(n.baseUrl),{method:`POST`,headers:h,body:y,signal:i?.signal}),await i?.onResponse?.({status:C.status,headers:c(C.headers)},n),C.ok)break;let t=await C.text();if(e<3&&g(C.status,t)){await _(p*2**e,i?.signal);continue}let r=await le(new Response(t,{status:C.status,statusText:C.statusText}));throw Error(r.friendlyMessage||r.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(D=t instanceof Error?t:Error(String(t)),e<3&&!D.message.includes(`usage limit`)){await _(p*2**e,i?.signal);continue}throw D}}if(!C?.ok)throw D??Error(`Failed after retries`);if(!C.body)throw Error(`No response body`);if(o.push({type:`start`,partial:t}),await E(C,t,o,n,i),i?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end()}catch(e){for(let e of t.content)delete e.partialJson;t.stopReason=i?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:String(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},y=(t,i,a)=>{let o=a?.apiKey||e(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,a,o),c=a?.reasoning?n(t,a.reasoning):void 0,l=c===`off`?void 0:c;return v(t,i,{...s,reasoningEffort:l})};function b(e,t,n){let r=d(e,t,m,{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 T(e){let t=new URL(w(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function E(e,t,n,r,i){await u(A(M(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,r)})}var D=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}},O=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function k(e){return e instanceof D||e instanceof O}async function*A(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 D(`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 D(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:j(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function j(e){if(typeof e==`string`)return h.has(e)?e:void 0}async function*M(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
2
 
3
- `);for(;o!==-1;){let e=r.slice(0,o);r=r.slice(o+2);let t=e.split(`
3
+ `);for(;a!==-1;){let e=r.slice(0,a);r=r.slice(a+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(`
5
- `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new O(`Invalid Codex SSE JSON: ${a(t)}`,{cause:t,payload:e})}}o=r.indexOf(`
5
+ `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new O(`Invalid Codex SSE JSON: ${o(t)}`,{cause:t,payload:e})}}a=r.indexOf(`
6
6
 
7
- `)}}}finally{try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}const N=new Map,P=new Map,F=new Set;function I(e){let t=P.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},P.set(e,t)),t}function L(e){let t=P.get(e);return t?{...t}:void 0}function R(e){if(e){P.delete(e),F.delete(e);return}P.clear(),F.clear()}function z(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),G(e.socket,1e3,`debug_close`)};if(e){let n=N.get(e);n&&t(n),N.delete(e);return}for(let e of N.values())t(e);N.clear()}r(z);function B(e){return e?F.has(e):!1}function V(e){if(!e)return;let t=I(e);t.sseFallbacks++,t.websocketFallbackActive=B(e)}function ee(e,t){if(!e)return;F.add(e);let n=I(e);n.websocketFailures++,n.lastWebSocketError=a(t),n.websocketFallbackActive=!0}function te(){let e=globalThis.WebSocket;return typeof e==`function`?e:null}var H=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function U(e){let t=e.readyState;return typeof t==`number`?t:void 0}function W(e){let t=U(e);return t===void 0||t===1}function G(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function K(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(G(t.socket,1e3,`idle_timeout`),N.delete(e))},3e5)}async function q(e,t,n){let r=te();if(!r)throw Error(`WebSocket transport is not available in this runtime`);let i=s(t);return delete i[`OpenAI-Beta`],new Promise((t,a)=>{let o=!1,s;try{s=new r(e,{headers:i})}catch(e){a(e instanceof Error?e:Error(String(e)));return}let c=()=>{o||(o=!0,f(),t(s))},l=e=>{let t=Y(e);o||(o=!0,f(),a(t))},u=e=>{let t=X(e);o||(o=!0,f(),a(t))},d=()=>{o||(o=!0,f(),s.close(1e3,`aborted`),a(Error(`Request was aborted`)))},f=()=>{s.removeEventListener(`open`,c),s.removeEventListener(`error`,l),s.removeEventListener(`close`,u),n?.removeEventListener(`abort`,d)};s.addEventListener(`open`,c),s.addEventListener(`error`,l),s.addEventListener(`close`,u),n?.addEventListener(`abort`,d)})}async function J(e,t,n,r){if(!n){let n=await q(e,t,r);return{socket:n,reused:!1,release:({keep:e}={})=>{if(e===!1){G(n);return}G(n)}}}let i=N.get(n);if(i){if(i.idleTimer&&=(clearTimeout(i.idleTimer),void 0),!i.busy&&W(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:e}={})=>{if(!e||!W(i.socket)){G(i.socket),N.delete(n);return}i.busy=!1,K(n,i)}};if(i.busy){let n=await q(e,t,r);return{socket:n,reused:!1,release:()=>{G(n)}}}W(i.socket)||(G(i.socket),N.delete(n))}let a=await q(e,t,r),o={socket:a,busy:!0};return N.set(n,o),{socket:a,entry:o,reused:!1,release:({keep:e}={})=>{if(!e||!W(o.socket)){G(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),N.get(n)===o&&N.delete(n);return}o.busy=!1,K(n,o)}}}function Y(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function X(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===1009&&(a=` message too big`),new H(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function Z(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*ne(e,t){let n=[],r=null,i=!1,o=null,s=!1,c=()=>{if(!r)return;let e=r;r=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Z(e.data),!t))return;let r=JSON.parse(t),a=typeof r.type==`string`?r.type:``;(a===`response.completed`||a===`response.done`||a===`response.incomplete`)&&(s=!0,i=!0),n.push(r),c()}catch(e){o=new O(`Invalid Codex WebSocket JSON: ${a(e)}`,{cause:e,payload:t}),i=!0,c()}})()},u=e=>{o=Y(e),i=!0,c()},d=e=>{if(s){i=!0,c();return}o||=X(e),i=!0,c()},f=()=>{o=Error(`Request was aborted`),i=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,d),t?.addEventListener(`abort`,f);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(n.length>0){yield n.shift();continue}if(i)break;await new Promise(e=>{r=e})}if(o)throw o;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,d),t?.removeEventListener(`abort`,f)}}function Q(e){let{input:t,previous_response_id:n,...r}=e;return r}function re(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function ie(e,t){return JSON.stringify(Q(e))===JSON.stringify(Q(t))}function ae(e,t){if(!ie(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&re(n.slice(0,r.length),r))return n.slice(r.length)}function oe(e,t){let n=e.continuation;if(!n)return t;let r=ae(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*se(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function ce(e,t,n,r,i,a,o,s){let{socket:c,entry:l,reused:f,release:p}=await J(e,n,s?.sessionId,s?.signal),h=!0,g=s?.transport===`websocket-cached`||s?.transport===`auto`,_=t,v=g&&l?oe(l,_):_,y=s?.sessionId?I(s.sessionId):void 0;y&&(y.requests++,f?y.connectionsReused++:y.connectionsCreated++,g&&y.cachedContextRequests++,v.store===!0&&y.storeTrueRequests++,y.lastInputItems=v.input?.length??0,v.previous_response_id?(y.deltaRequests++,y.lastDeltaInputItems=v.input?.length??0,y.lastPreviousResponseId=v.previous_response_id):(y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0));try{if(c.send(JSON.stringify({type:`response.create`,...v})),await u(se(A(ne(c,s?.signal)),r,i,o),r,i,a,{serviceTier:s?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,a)}),s?.signal?.aborted)h=!1;else if(g&&l&&r.responseId){let e=d(a,{messages:[r]},m,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);l.continuation={lastRequestBody:_,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw l&&(l.continuation=void 0),h=!1,e}finally{p({keep:h})}}async function le(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function ue(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function de(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=f?`pi (${f.platform()} ${f.release()}; ${f.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function fe(e,t,n,r,i){let a=$(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session_id`,i),a.set(`x-client-request-id`,i)),a}function pe(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,`responses_websockets=2026-02-06`),a.set(`x-client-request-id`,i),a.set(`session_id`,i),a}export{z as closeOpenAICodexWebSocketSessions,L as getOpenAICodexWebSocketDebugStats,R as resetOpenAICodexWebSocketDebugStats,v as streamOpenAICodexResponses,y as streamSimpleOpenAICodexResponses};
7
+ `)}}}finally{try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}const N=new Map,P=new Map,F=new Set;function I(e){let t=P.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},P.set(e,t)),t}function L(e){let t=P.get(e);return t?{...t}:void 0}function R(e){if(e){P.delete(e),F.delete(e);return}P.clear(),F.clear()}function z(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),G(e.socket,1e3,`debug_close`)};if(e){let n=N.get(e);n&&t(n),N.delete(e);return}for(let e of N.values())t(e);N.clear()}i(z);function B(e){return e?F.has(e):!1}function V(e){if(!e)return;let t=I(e);t.sseFallbacks++,t.websocketFallbackActive=B(e)}function ee(e,t){if(!e)return;F.add(e);let n=I(e);n.websocketFailures++,n.lastWebSocketError=o(t),n.websocketFallbackActive=!0}function te(){let e=globalThis.WebSocket;return typeof e==`function`?e:null}var H=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function U(e){let t=e.readyState;return typeof t==`number`?t:void 0}function W(e){let t=U(e);return t===void 0||t===1}function G(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function K(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(G(t.socket,1e3,`idle_timeout`),N.delete(e))},3e5)}async function q(e,t,n){let r=te();if(!r)throw Error(`WebSocket transport is not available in this runtime`);let i=c(t);return delete i[`OpenAI-Beta`],new Promise((t,a)=>{let o=!1,s;try{s=new r(e,{headers:i})}catch(e){a(e instanceof Error?e:Error(String(e)));return}let c=()=>{o||(o=!0,f(),t(s))},l=e=>{let t=Y(e);o||(o=!0,f(),a(t))},u=e=>{let t=X(e);o||(o=!0,f(),a(t))},d=()=>{o||(o=!0,f(),s.close(1e3,`aborted`),a(Error(`Request was aborted`)))},f=()=>{s.removeEventListener(`open`,c),s.removeEventListener(`error`,l),s.removeEventListener(`close`,u),n?.removeEventListener(`abort`,d)};s.addEventListener(`open`,c),s.addEventListener(`error`,l),s.addEventListener(`close`,u),n?.addEventListener(`abort`,d)})}async function J(e,t,n,r){if(!n){let n=await q(e,t,r);return{socket:n,reused:!1,release:({keep:e}={})=>{if(e===!1){G(n);return}G(n)}}}let i=N.get(n);if(i){if(i.idleTimer&&=(clearTimeout(i.idleTimer),void 0),!i.busy&&W(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:e}={})=>{if(!e||!W(i.socket)){G(i.socket),N.delete(n);return}i.busy=!1,K(n,i)}};if(i.busy){let n=await q(e,t,r);return{socket:n,reused:!1,release:()=>{G(n)}}}W(i.socket)||(G(i.socket),N.delete(n))}let a=await q(e,t,r),o={socket:a,busy:!0};return N.set(n,o),{socket:a,entry:o,reused:!1,release:({keep:e}={})=>{if(!e||!W(o.socket)){G(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),N.get(n)===o&&N.delete(n);return}o.busy=!1,K(n,o)}}}function Y(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function X(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===1009&&(a=` message too big`),new H(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function Z(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*ne(e,t){let n=[],r=null,i=!1,a=null,s=!1,c=()=>{if(!r)return;let e=r;r=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Z(e.data),!t))return;let r=JSON.parse(t),a=typeof r.type==`string`?r.type:``;(a===`response.completed`||a===`response.done`||a===`response.incomplete`)&&(s=!0,i=!0),n.push(r),c()}catch(e){a=new O(`Invalid Codex WebSocket JSON: ${o(e)}`,{cause:e,payload:t}),i=!0,c()}})()},u=e=>{a=Y(e),i=!0,c()},d=e=>{if(s){i=!0,c();return}a||=X(e),i=!0,c()},f=()=>{a=Error(`Request was aborted`),i=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,d),t?.addEventListener(`abort`,f);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(n.length>0){yield n.shift();continue}if(i)break;await new Promise(e=>{r=e})}if(a)throw a;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,d),t?.removeEventListener(`abort`,f)}}function Q(e){let{input:t,previous_response_id:n,...r}=e;return r}function re(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function ie(e,t){return JSON.stringify(Q(e))===JSON.stringify(Q(t))}function ae(e,t){if(!ie(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&re(n.slice(0,r.length),r))return n.slice(r.length)}function oe(e,t){let n=e.continuation;if(!n)return t;let r=ae(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*se(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function ce(e,t,n,r,i,a,o,s){let{socket:c,entry:l,reused:f,release:p}=await J(e,n,s?.sessionId,s?.signal),h=!0,g=s?.transport===`websocket-cached`||s?.transport===`auto`,_=t,v=g&&l?oe(l,_):_,y=s?.sessionId?I(s.sessionId):void 0;y&&(y.requests++,f?y.connectionsReused++:y.connectionsCreated++,g&&y.cachedContextRequests++,v.store===!0&&y.storeTrueRequests++,y.lastInputItems=v.input?.length??0,v.previous_response_id?(y.deltaRequests++,y.lastDeltaInputItems=v.input?.length??0,y.lastPreviousResponseId=v.previous_response_id):(y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0));try{if(c.send(JSON.stringify({type:`response.create`,...v})),await u(se(A(ne(c,s?.signal)),r,i,o),r,i,a,{serviceTier:s?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,a)}),s?.signal?.aborted)h=!1;else if(g&&l&&r.responseId){let e=d(a,{messages:[r]},m,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);l.continuation={lastRequestBody:_,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw l&&(l.continuation=void 0),h=!1,e}finally{p({keep:h})}}async function le(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function ue(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function de(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=f?`pi (${f.platform()} ${f.release()}; ${f.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function fe(e,t,n,r,i){let a=$(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session_id`,i),a.set(`x-client-request-id`,i)),a}function pe(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,`responses_websockets=2026-02-06`),a.set(`x-client-request-id`,i),a.set(`session_id`,i),a}export{z as closeOpenAICodexWebSocketSessions,L as getOpenAICodexWebSocketDebugStats,R as resetOpenAICodexWebSocketDebugStats,v as streamOpenAICodexResponses,y as streamSimpleOpenAICodexResponses};
@@ -1,7 +1,7 @@
1
- import{t as e}from"./preload-helper-ca-nBW7U.js";import{a as t,c as n,n as r}from"./simple-options-B0cR4giT.js";import{i,n as a,r as o,t as s}from"./diagnostics-BowEoTPl.js";import{u as c}from"./index-BxaasNW5.js";import{t as l}from"./headers-CeeP1wvy.js";import{n as u,r as d,t as f}from"./openai-responses-shared-Cb6xPI3z.js";var p=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(t=>e(()=>import(t),[]))(`node:os`).then(e=>{p=e});var m=`https://chatgpt.com/backend-api`,h=`https://api.openai.com/auth`,g=3,_=1e3,v=new Set([`openai`,`openai-codex`,`opencode`]),y=1009,b=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 x(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 S=(e,n,r)=>{let i=new t;return(async()=>{let t={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 o=r?.apiKey||c(e.provider)||``;if(!o)throw Error(`No API key for provider: ${e.provider}`);let u=_e(o),d=te(e,n,r),f=await r?.onPayload?.(d,e);f!==void 0&&(d=f);let p=r?.sessionId||ve(),m=ye(e.headers,r?.headers,u,o,r?.sessionId),h=be(e.headers,r?.headers,u,o,p),v=JSON.stringify(d),y=r?.transport||`auto`,b=y!==`sse`&&z(r?.sessionId);if(b&&B(r?.sessionId),y!==`sse`&&!b){let n=!1;try{if(await Q(ne(e.baseUrl),d,h,t,i,e,()=>{n=!0},r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:t.stopReason,message:t}),i.end();return}catch(e){if(r?.signal?.aborted||A(e)||(s(t,a(`provider_transport_failure`,e,{configuredTransport:y,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(v).byteLength})),V(r?.sessionId,e),n))throw e;B(r?.sessionId)}}let S,C;for(let t=0;t<=g;t++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{if(S=await fetch(D(e.baseUrl),{method:`POST`,headers:m,body:v,signal:r?.signal}),await r?.onResponse?.({status:S.status,headers:l(S.headers)},e),S.ok)break;let n=await S.text();if(t<g&&ee(S.status,n)){await x(_*2**t,r?.signal);continue}let i=await ge(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<g&&!C.message.includes(`usage limit`)){await x(_*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:t}),await re(S,t,i,e,r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:t.stopReason,message:t}),i.end()}catch(e){for(let e of t.content)delete e.partialJson;t.stopReason=r?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:String(e),i.push({type:`error`,reason:t.stopReason,error:t}),i.end()}})(),i},C=(e,t,i)=>{let a=i?.apiKey||c(e.provider);if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=r(e,i,a),s=i?.reasoning?n(e,i.reasoning):void 0,l=s===`off`?void 0:s;return S(e,t,{...o,reasoningEffort:l})};function te(e,t,n){let r=f(e,t,v,{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 w(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=w(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:m).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function ne(e){let t=new URL(D(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function re(e,t,n,r,i){await d(j(ae(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:ie(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function ie(e){if(typeof e==`string`)return b.has(e)?e:void 0}async function*ae(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
1
+ import{t as e}from"./preload-helper-ca-nBW7U.js";import{t}from"./env-api-keys-DxKb6C4Q.js";import{a as n,c as r,n as i}from"./simple-options-imi_RHvn.js";import{i as a,n as o,r as s,t as c}from"./diagnostics-DEZCW87A.js";import{t as l}from"./headers-DkHU-pcw.js";import{n as u,r as d,t as f}from"./openai-responses-shared-vokXRwgV.js";var p=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(t=>e(()=>import(t),[]))(`node:os`).then(e=>{p=e});var m=`https://chatgpt.com/backend-api`,h=`https://api.openai.com/auth`,g=3,_=1e3,v=new Set([`openai`,`openai-codex`,`opencode`]),y=1009,b=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 x(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 S=(e,r,i)=>{let a=new n;return(async()=>{let n={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=i?.apiKey||t(e.provider)||``;if(!s)throw Error(`No API key for provider: ${e.provider}`);let u=_e(s),d=te(e,r,i),f=await i?.onPayload?.(d,e);f!==void 0&&(d=f);let p=i?.sessionId||ve(),m=ye(e.headers,i?.headers,u,s,i?.sessionId),h=be(e.headers,i?.headers,u,s,p),v=JSON.stringify(d),y=i?.transport||`auto`,b=y!==`sse`&&z(i?.sessionId);if(b&&B(i?.sessionId),y!==`sse`&&!b){let t=!1;try{if(await Q(ne(e.baseUrl),d,h,n,a,e,()=>{t=!0},i),i?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:n.stopReason,message:n}),a.end();return}catch(e){if(i?.signal?.aborted||A(e)||(c(n,o(`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(v).byteLength})),V(i?.sessionId,e),t))throw e;B(i?.sessionId)}}let S,C;for(let t=0;t<=g;t++){if(i?.signal?.aborted)throw Error(`Request was aborted`);try{if(S=await fetch(D(e.baseUrl),{method:`POST`,headers:m,body:v,signal:i?.signal}),await i?.onResponse?.({status:S.status,headers:l(S.headers)},e),S.ok)break;let n=await S.text();if(t<g&&ee(S.status,n)){await x(_*2**t,i?.signal);continue}let r=await ge(new Response(n,{status:S.status,statusText:S.statusText}));throw Error(r.friendlyMessage||r.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<g&&!C.message.includes(`usage limit`)){await x(_*2**t,i?.signal);continue}throw C}}if(!S?.ok)throw C??Error(`Failed after retries`);if(!S.body)throw Error(`No response body`);if(a.push({type:`start`,partial:n}),await re(S,n,a,e,i),i?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:n.stopReason,message:n}),a.end()}catch(e){for(let e of n.content)delete e.partialJson;n.stopReason=i?.signal?.aborted?`aborted`:`error`,n.errorMessage=e instanceof Error?e.message:String(e),a.push({type:`error`,reason:n.stopReason,error:n}),a.end()}})(),a},C=(e,n,a)=>{let o=a?.apiKey||t(e.provider);if(!o)throw Error(`No API key for provider: ${e.provider}`);let s=i(e,a,o),c=a?.reasoning?r(e,a.reasoning):void 0,l=c===`off`?void 0:c;return S(e,n,{...s,reasoningEffort:l})};function te(e,t,n){let r=f(e,t,v,{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 w(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=w(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:m).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function ne(e){let t=new URL(D(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function re(e,t,n,r,i){await d(j(ae(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:ie(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function ie(e){if(typeof e==`string`)return b.has(e)?e:void 0}async function*ae(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
2
 
3
3
  `);for(;a!==-1;){let e=r.slice(0,a);r=r.slice(a+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(`
5
- `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new k(`Invalid Codex SSE JSON: ${o(t)}`,{cause:t,payload:e})}}a=r.indexOf(`
5
+ `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new k(`Invalid Codex SSE JSON: ${s(t)}`,{cause:t,payload:e})}}a=r.indexOf(`
6
6
 
7
- `)}}}finally{try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var M=`responses_websockets=2026-02-06`,N=300*1e3,P=new Map,F=new Map,I=new Set;function L(e){let t=F.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},F.set(e,t)),t}function oe(e){let t=F.get(e);return t?{...t}:void 0}function se(e){if(e){F.delete(e),I.delete(e);return}F.clear(),I.clear()}function R(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),K(e.socket,1e3,`debug_close`)};if(e){let n=P.get(e);n&&t(n),P.delete(e);return}for(let e of P.values())t(e);P.clear()}i(R);function z(e){return e?I.has(e):!1}function B(e){if(!e)return;let t=L(e);t.sseFallbacks++,t.websocketFallbackActive=z(e)}function V(e,t){if(!e)return;I.add(e);let n=L(e);n.websocketFailures++,n.lastWebSocketError=o(t),n.websocketFallbackActive=!0}function H(){let e=globalThis.WebSocket;return typeof e==`function`?e:null}var U=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function W(e){let t=e.readyState;return typeof t==`number`?t:void 0}function G(e){let t=W(e);return t===void 0||t===1}function K(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function q(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(K(t.socket,1e3,`idle_timeout`),P.delete(e))},N)}async function J(e,t,n){let r=H();if(!r)throw Error(`WebSocket transport is not available in this runtime`);let i=l(t);return delete i[`OpenAI-Beta`],new Promise((t,a)=>{let o=!1,s;try{s=new r(e,{headers:i})}catch(e){a(e instanceof Error?e:Error(String(e)));return}let c=()=>{o||(o=!0,f(),t(s))},l=e=>{let t=Y(e);o||(o=!0,f(),a(t))},u=e=>{let t=X(e);o||(o=!0,f(),a(t))},d=()=>{o||(o=!0,f(),s.close(1e3,`aborted`),a(Error(`Request was aborted`)))},f=()=>{s.removeEventListener(`open`,c),s.removeEventListener(`error`,l),s.removeEventListener(`close`,u),n?.removeEventListener(`abort`,d)};s.addEventListener(`open`,c),s.addEventListener(`error`,l),s.addEventListener(`close`,u),n?.addEventListener(`abort`,d)})}async function ce(e,t,n,r){if(!n){let n=await J(e,t,r);return{socket:n,reused:!1,release:({keep:e}={})=>{if(e===!1){K(n);return}K(n)}}}let i=P.get(n);if(i){if(i.idleTimer&&=(clearTimeout(i.idleTimer),void 0),!i.busy&&G(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:e}={})=>{if(!e||!G(i.socket)){K(i.socket),P.delete(n);return}i.busy=!1,q(n,i)}};if(i.busy){let n=await J(e,t,r);return{socket:n,reused:!1,release:()=>{K(n)}}}G(i.socket)||(K(i.socket),P.delete(n))}let a=await J(e,t,r),o={socket:a,busy:!0};return P.set(n,o),{socket:a,entry:o,reused:!1,release:({keep:e}={})=>{if(!e||!G(o.socket)){K(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),P.get(n)===o&&P.delete(n);return}o.busy=!1,q(n,o)}}}function Y(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function X(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===y&&(a=` message too big`),new U(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function le(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*ue(e,t){let n=[],r=null,i=!1,a=null,s=!1,c=()=>{if(!r)return;let e=r;r=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await le(e.data),!t))return;let r=JSON.parse(t),a=typeof r.type==`string`?r.type:``;(a===`response.completed`||a===`response.done`||a===`response.incomplete`)&&(s=!0,i=!0),n.push(r),c()}catch(e){a=new k(`Invalid Codex WebSocket JSON: ${o(e)}`,{cause:e,payload:t}),i=!0,c()}})()},u=e=>{a=Y(e),i=!0,c()},d=e=>{if(s){i=!0,c();return}a||=X(e),i=!0,c()},f=()=>{a=Error(`Request was aborted`),i=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,d),t?.addEventListener(`abort`,f);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(n.length>0){yield n.shift();continue}if(i)break;await new Promise(e=>{r=e})}if(a)throw a;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,d),t?.removeEventListener(`abort`,f)}}function Z(e){let{input:t,previous_response_id:n,...r}=e;return r}function de(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function fe(e,t){return JSON.stringify(Z(e))===JSON.stringify(Z(t))}function pe(e,t){if(!fe(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&de(n.slice(0,r.length),r))return n.slice(r.length)}function me(e,t){let n=e.continuation;if(!n)return t;let r=pe(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*he(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function Q(e,t,n,r,i,a,o,s){let{socket:c,entry:l,reused:u,release:p}=await ce(e,n,s?.sessionId,s?.signal),m=!0,h=s?.transport===`websocket-cached`||s?.transport===`auto`,g=t,_=h&&l?me(l,g):g,y=s?.sessionId?L(s.sessionId):void 0;y&&(y.requests++,u?y.connectionsReused++:y.connectionsCreated++,h&&y.cachedContextRequests++,_.store===!0&&y.storeTrueRequests++,y.lastInputItems=_.input?.length??0,_.previous_response_id?(y.deltaRequests++,y.lastDeltaInputItems=_.input?.length??0,y.lastPreviousResponseId=_.previous_response_id):(y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0));try{if(c.send(JSON.stringify({type:`response.create`,..._})),await d(he(j(ue(c,s?.signal)),r,i,o),r,i,a,{serviceTier:s?.serviceTier,resolveServiceTier:E,applyServiceTierPricing:(e,t)=>T(e,t,a)}),s?.signal?.aborted)m=!1;else if(h&&l&&r.responseId){let e=f(a,{messages:[r]},v,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);l.continuation={lastRequestBody:g,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw l&&(l.continuation=void 0),m=!1,e}finally{p({keep:m})}}async function ge(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function _e(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[h]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function ve(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=p?`pi (${p.platform()} ${p.release()}; ${p.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function ye(e,t,n,r,i){let a=$(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session_id`,i),a.set(`x-client-request-id`,i)),a}function be(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,M),a.set(`x-client-request-id`,i),a.set(`session_id`,i),a}export{R as closeOpenAICodexWebSocketSessions,oe as getOpenAICodexWebSocketDebugStats,se as resetOpenAICodexWebSocketDebugStats,S as streamOpenAICodexResponses,C as streamSimpleOpenAICodexResponses};
7
+ `)}}}finally{try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var M=`responses_websockets=2026-02-06`,N=300*1e3,P=new Map,F=new Map,I=new Set;function L(e){let t=F.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},F.set(e,t)),t}function oe(e){let t=F.get(e);return t?{...t}:void 0}function se(e){if(e){F.delete(e),I.delete(e);return}F.clear(),I.clear()}function R(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),K(e.socket,1e3,`debug_close`)};if(e){let n=P.get(e);n&&t(n),P.delete(e);return}for(let e of P.values())t(e);P.clear()}a(R);function z(e){return e?I.has(e):!1}function B(e){if(!e)return;let t=L(e);t.sseFallbacks++,t.websocketFallbackActive=z(e)}function V(e,t){if(!e)return;I.add(e);let n=L(e);n.websocketFailures++,n.lastWebSocketError=s(t),n.websocketFallbackActive=!0}function H(){let e=globalThis.WebSocket;return typeof e==`function`?e:null}var U=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function W(e){let t=e.readyState;return typeof t==`number`?t:void 0}function G(e){let t=W(e);return t===void 0||t===1}function K(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function q(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(K(t.socket,1e3,`idle_timeout`),P.delete(e))},N)}async function J(e,t,n){let r=H();if(!r)throw Error(`WebSocket transport is not available in this runtime`);let i=l(t);return delete i[`OpenAI-Beta`],new Promise((t,a)=>{let o=!1,s;try{s=new r(e,{headers:i})}catch(e){a(e instanceof Error?e:Error(String(e)));return}let c=()=>{o||(o=!0,f(),t(s))},l=e=>{let t=Y(e);o||(o=!0,f(),a(t))},u=e=>{let t=X(e);o||(o=!0,f(),a(t))},d=()=>{o||(o=!0,f(),s.close(1e3,`aborted`),a(Error(`Request was aborted`)))},f=()=>{s.removeEventListener(`open`,c),s.removeEventListener(`error`,l),s.removeEventListener(`close`,u),n?.removeEventListener(`abort`,d)};s.addEventListener(`open`,c),s.addEventListener(`error`,l),s.addEventListener(`close`,u),n?.addEventListener(`abort`,d)})}async function ce(e,t,n,r){if(!n){let n=await J(e,t,r);return{socket:n,reused:!1,release:({keep:e}={})=>{if(e===!1){K(n);return}K(n)}}}let i=P.get(n);if(i){if(i.idleTimer&&=(clearTimeout(i.idleTimer),void 0),!i.busy&&G(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:e}={})=>{if(!e||!G(i.socket)){K(i.socket),P.delete(n);return}i.busy=!1,q(n,i)}};if(i.busy){let n=await J(e,t,r);return{socket:n,reused:!1,release:()=>{K(n)}}}G(i.socket)||(K(i.socket),P.delete(n))}let a=await J(e,t,r),o={socket:a,busy:!0};return P.set(n,o),{socket:a,entry:o,reused:!1,release:({keep:e}={})=>{if(!e||!G(o.socket)){K(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),P.get(n)===o&&P.delete(n);return}o.busy=!1,q(n,o)}}}function Y(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function X(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===y&&(a=` message too big`),new U(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function le(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*ue(e,t){let n=[],r=null,i=!1,a=null,o=!1,c=()=>{if(!r)return;let e=r;r=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await le(e.data),!t))return;let r=JSON.parse(t),a=typeof r.type==`string`?r.type:``;(a===`response.completed`||a===`response.done`||a===`response.incomplete`)&&(o=!0,i=!0),n.push(r),c()}catch(e){a=new k(`Invalid Codex WebSocket JSON: ${s(e)}`,{cause:e,payload:t}),i=!0,c()}})()},u=e=>{a=Y(e),i=!0,c()},d=e=>{if(o){i=!0,c();return}a||=X(e),i=!0,c()},f=()=>{a=Error(`Request was aborted`),i=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,d),t?.addEventListener(`abort`,f);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(n.length>0){yield n.shift();continue}if(i)break;await new Promise(e=>{r=e})}if(a)throw a;if(!o)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,d),t?.removeEventListener(`abort`,f)}}function Z(e){let{input:t,previous_response_id:n,...r}=e;return r}function de(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function fe(e,t){return JSON.stringify(Z(e))===JSON.stringify(Z(t))}function pe(e,t){if(!fe(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&de(n.slice(0,r.length),r))return n.slice(r.length)}function me(e,t){let n=e.continuation;if(!n)return t;let r=pe(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*he(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function Q(e,t,n,r,i,a,o,s){let{socket:c,entry:l,reused:u,release:p}=await ce(e,n,s?.sessionId,s?.signal),m=!0,h=s?.transport===`websocket-cached`||s?.transport===`auto`,g=t,_=h&&l?me(l,g):g,y=s?.sessionId?L(s.sessionId):void 0;y&&(y.requests++,u?y.connectionsReused++:y.connectionsCreated++,h&&y.cachedContextRequests++,_.store===!0&&y.storeTrueRequests++,y.lastInputItems=_.input?.length??0,_.previous_response_id?(y.deltaRequests++,y.lastDeltaInputItems=_.input?.length??0,y.lastPreviousResponseId=_.previous_response_id):(y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0));try{if(c.send(JSON.stringify({type:`response.create`,..._})),await d(he(j(ue(c,s?.signal)),r,i,o),r,i,a,{serviceTier:s?.serviceTier,resolveServiceTier:E,applyServiceTierPricing:(e,t)=>T(e,t,a)}),s?.signal?.aborted)m=!1;else if(h&&l&&r.responseId){let e=f(a,{messages:[r]},v,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);l.continuation={lastRequestBody:g,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw l&&(l.continuation=void 0),m=!1,e}finally{p({keep:m})}}async function ge(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function _e(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[h]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function ve(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=p?`pi (${p.platform()} ${p.release()}; ${p.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function ye(e,t,n,r,i){let a=$(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session_id`,i),a.set(`x-client-request-id`,i)),a}function be(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,M),a.set(`x-client-request-id`,i),a.set(`session_id`,i),a}export{R as closeOpenAICodexWebSocketSessions,oe as getOpenAICodexWebSocketDebugStats,se as resetOpenAICodexWebSocketDebugStats,S as streamOpenAICodexResponses,C as streamSimpleOpenAICodexResponses};
@@ -0,0 +1,5 @@
1
+ import{t as e}from"./env-api-keys-DxKb6C4Q.js";import{a as t,c as n,i as r,n as i,s as a}from"./simple-options-imi_RHvn.js";import{n as o}from"./json-parse-C5jSA6JB.js";import{t as s}from"./headers-DkHU-pcw.js";import{t as c}from"./sanitize-unicode-BD2XKRoV.js";import{i as l,n as u,r as d,t as f}from"./github-copilot-headers-B6Fvsk-Y.js";import{n as p}from"./openai-CRGaNv9i.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=(n,r,i)=>{let a=new t;return(async()=>{let t={role:`assistant`,content:[],api:n.api,provider:n.provider,model:n.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||e(n.provider)||``,l=L(n),u=y(i?.cacheRetention),d=u===`none`?void 0:i?.sessionId,f=S(n,r,c,i?.headers,d,l),p=C(n,r,i,l,u),m=await i?.onPayload?.(p,n);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)},n),a.push({type:`start`,partial:t});let v=null,b=null,x=new Map,w=new Map,T=t.content,E=e=>T.indexOf(e),D=e=>{let n=E(e);n!==-1&&(e.type===`text`?a.push({type:`text_end`,contentIndex:n,content:e.text,partial:t}):e.type===`thinking`?a.push({type:`thinking_end`,contentIndex:n,content:e.thinking,partial:t}):e.type===`toolCall`&&(e.arguments=o(e.partialArgs),delete e.partialArgs,delete e.streamIndex,a.push({type:`toolcall_end`,contentIndex:n,toolCall:e,partial:t})))},O=()=>(v||(v={type:`text`,text:``},T.push(v),a.push({type:`text_start`,contentIndex:E(v),partial:t})),v),k=e=>(b||(b={type:`thinking`,thinking:``,thinkingSignature:e},T.push(b),a.push({type:`thinking_start`,contentIndex:E(b),partial:t})),b),A=e=>{let n=typeof e.index==`number`?e.index:void 0,r=n===void 0?void 0:x.get(n);return!r&&e.id&&(r=w.get(e.id)),r||(r={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``,streamIndex:n},n!==void 0&&x.set(n,r),e.id&&w.set(e.id,r),T.push(r),a.push({type:`toolcall_start`,contentIndex:E(r),partial:t})),n!==void 0&&r.streamIndex===void 0&&(r.streamIndex=n,x.set(n,r)),e.id&&w.set(e.id,r),r};for await(let e of g){if(!e||typeof e!=`object`)continue;t.responseId||=e.id,typeof e.model==`string`&&e.model.length>0&&e.model!==n.id&&(t.responseModel||=e.model),e.usage&&(t.usage=P(e.usage,n));let r=Array.isArray(e.choices)?e.choices[0]:void 0;if(r){if(!e.usage&&r.usage&&(t.usage=P(r.usage,n)),r.finish_reason){let e=F(r.finish_reason);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage)}if(r.delta){if(r.delta.content!==null&&r.delta.content!==void 0&&r.delta.content.length>0){let e=O();e.text+=r.delta.content,a.push({type:`text_delta`,contentIndex:E(e),delta:r.delta.content,partial:t})}let e=[`reasoning_content`,`reasoning`,`reasoning_text`],n=r.delta,i=null;for(let t of e){let e=n[t];if(typeof e==`string`&&e.length>0){i=t;break}}if(i){let e=n[i];if(typeof e==`string`&&e.length>0){let n=k(i);n.thinking+=e,a.push({type:`thinking_delta`,contentIndex:E(n),delta:e,partial:t})}}if(r?.delta?.tool_calls)for(let e of r.delta.tool_calls){let n=A(e);!n.id&&e.id&&(n.id=e.id,w.set(e.id,n)),!n.name&&e.function?.name&&(n.name=e.function.name);let r=``;e.function?.arguments&&(r=e.function.arguments,n.partialArgs=(n.partialArgs??``)+e.function.arguments,n.arguments=o(n.partialArgs)),a.push({type:`toolcall_delta`,contentIndex:E(n),delta:r,partial:t})}let s=r.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let n=t.content.find(t=>t.type===`toolCall`&&t.id===e.id);n&&(n.thoughtSignature=JSON.stringify(e))}}}}}for(let e of T)D(e);if(i?.signal?.aborted||t.stopReason===`aborted`)throw Error(`Request was aborted`);if(t.stopReason===`error`)throw Error(t.errorMessage||`Provider returned an error stop reason`);a.push({type:`done`,reason:t.stopReason,message:t}),a.end()}catch(e){for(let e of t.content)delete e.index,delete e.partialArgs,delete e.streamIndex;t.stopReason=i?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let n=e?.error?.metadata?.raw;n&&(t.errorMessage+=`\n${n}`),a.push({type:`error`,reason:t.stopReason,error:t}),a.end()}})(),a},x=(t,r,a)=>{let o=a?.apiKey||e(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=i(t,a,o),c=a?.reasoning?n(t,a.reasoning):void 0,l=c===`off`?void 0:c,u=a?.toolChoice;return b(t,r,{...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(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 i=[],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=r(t.messages,e,e=>a(e));if(t.systemPrompt){let r=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;i.push({role:r,content:c(t.systemPrompt)})}let s=null;for(let t=0;t<o.length;t++){let r=o[t];if(n.requiresAssistantAfterToolResult&&s===`toolResult`&&r.role===`user`&&i.push({role:`assistant`,content:`I have processed the tool results.`}),r.role===`user`)if(typeof r.content==`string`)i.push({role:`user`,content:c(r.content)});else{let e=r.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;i.push({role:`user`,content:e})}else if(r.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=r.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=r.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
+
3
+ `)},...a];else{o.length>0&&(t.content=o);let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
4
+ `))}else o.length>0&&(t.content=o);let l=r.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;i.push(t)}else if(r.role===`toolResult`){let r=[],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(`
5
+ `),l=t.content.some(e=>e.type===`image`),u={role:`tool`,content:c(s.length>0?s:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(u.name=t.toolName),i.push(u),l&&e.input.includes(`image`))for(let e of t.content)v(e)&&r.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=a-1,r.length>0?(n.requiresAssistantAfterToolResult&&i.push({role:`assistant`,content:`I have processed the tool results.`}),i.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...r]}),s=`user`):s=`toolResult`;continue}s=r.role}return i}function N(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function P(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,i=e.prompt_tokens_details?.cache_write_tokens||0,o=i>0?Math.max(0,r-i):r,s=Math.max(0,n-o-i),c=e.completion_tokens||0,l={input:s,output:c,cacheRead:o,cacheWrite:i,totalTokens:s+c+o+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return a(t,l),l}function F(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function I(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),a=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),o=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),s=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||i||t===`opencode`||n.includes(`opencode.ai`)||a||o,c=n.includes(`chutes.ai`)||i||o,l=t===`xai`||n.includes(`api.x.ai`),u=t===`deepseek`||n.includes(`deepseek.com`),d=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!s,supportsDeveloperRole:!s,supportsReasoningEffort:!l&&!r&&!i&&!o,supportsUsageInStreaming:!0,maxTokensField:c?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:u,thinkingFormat:u?`deepseek`:r?`zai`:t===`openrouter`||n.includes(`openrouter.ai`)?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!i&&!o,cacheControlFormat:d,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!(a||o)}}function L(e){let t=I(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{M as convertMessages,b as streamOpenAICompletions,x as streamSimpleOpenAICompletions};
@@ -0,0 +1,5 @@
1
+ import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./env-api-keys-CH1OdZie.js";import{a as n,c as r,r as i,s as a,t as o}from"./transform-messages-uhk4b6os.js";import{n as s}from"./json-parse-Or9qhSeP.js";import{n as c}from"./openai-D6Fs9zDM.js";import{t as l}from"./headers-BCPSYYop.js";import{t as u}from"./sanitize-unicode-ncMKN_SD.js";import{i as d,n as f,r as p,t as m}from"./github-copilot-headers-DFUtSIuj.js";var h=e({convertMessages:()=>P,streamOpenAICompletions:()=>S,streamSimpleOpenAICompletions:()=>C});function g(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 _(e){return e.type===`text`}function v(e){return e.type===`thinking`}function y(e){return e.type===`toolCall`}function b(e){return e.type===`image`}function x(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}const S=(e,r,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||t(e.provider)||``,c=z(e),u=x(i?.cacheRetention),d=u===`none`?void 0:i?.sessionId,f=w(e,r,o,i?.headers,d,c),p=T(e,r,i,c,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:l(_.headers)},e),a.push({type:`start`,partial:n});let v=null,y=null,b=new Map,S=new Map,C=n.content,E=e=>C.indexOf(e),D=e=>{let t=E(e);t!==-1&&(e.type===`text`?a.push({type:`text_end`,contentIndex:t,content:e.text,partial:n}):e.type===`thinking`?a.push({type:`thinking_end`,contentIndex:t,content:e.thinking,partial:n}):e.type===`toolCall`&&(e.arguments=s(e.partialArgs),delete e.partialArgs,delete e.streamIndex,a.push({type:`toolcall_end`,contentIndex:t,toolCall:e,partial:n})))},O=()=>(v||(v={type:`text`,text:``},C.push(v),a.push({type:`text_start`,contentIndex:E(v),partial:n})),v),k=e=>(y||(y={type:`thinking`,thinking:``,thinkingSignature:e},C.push(y),a.push({type:`thinking_start`,contentIndex:E(y),partial:n})),y),A=e=>{let t=typeof e.index==`number`?e.index:void 0,r=t===void 0?void 0:b.get(t);return!r&&e.id&&(r=S.get(e.id)),r||(r={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``,streamIndex:t},t!==void 0&&b.set(t,r),e.id&&S.set(e.id,r),C.push(r),a.push({type:`toolcall_start`,contentIndex:E(r),partial:n})),t!==void 0&&r.streamIndex===void 0&&(r.streamIndex=t,b.set(t,r)),e.id&&S.set(e.id,r),r};for await(let t of g){if(!t||typeof t!=`object`)continue;n.responseId||=t.id,typeof t.model==`string`&&t.model.length>0&&t.model!==e.id&&(n.responseModel||=t.model),t.usage&&(n.usage=I(t.usage,e));let r=Array.isArray(t.choices)?t.choices[0]:void 0;if(r){if(!t.usage&&r.usage&&(n.usage=I(r.usage,e)),r.finish_reason){let e=L(r.finish_reason);n.stopReason=e.stopReason,e.errorMessage&&(n.errorMessage=e.errorMessage)}if(r.delta){if(r.delta.content!==null&&r.delta.content!==void 0&&r.delta.content.length>0){let e=O();e.text+=r.delta.content,a.push({type:`text_delta`,contentIndex:E(e),delta:r.delta.content,partial:n})}let e=[`reasoning_content`,`reasoning`,`reasoning_text`],t=r.delta,i=null;for(let n of e){let e=t[n];if(typeof e==`string`&&e.length>0){i=n;break}}if(i){let e=t[i];if(typeof e==`string`&&e.length>0){let t=k(i);t.thinking+=e,a.push({type:`thinking_delta`,contentIndex:E(t),delta:e,partial:n})}}if(r?.delta?.tool_calls)for(let e of r.delta.tool_calls){let t=A(e);!t.id&&e.id&&(t.id=e.id,S.set(e.id,t)),!t.name&&e.function?.name&&(t.name=e.function.name);let r=``;e.function?.arguments&&(r=e.function.arguments,t.partialArgs=(t.partialArgs??``)+e.function.arguments,t.arguments=s(t.partialArgs)),a.push({type:`toolcall_delta`,contentIndex:E(t),delta:r,partial:n})}let o=r.delta.reasoning_details;if(o&&Array.isArray(o)){for(let e of o)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=n.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}}}for(let e of C)D(e);if(i?.signal?.aborted||n.stopReason===`aborted`)throw Error(`Request was aborted`);if(n.stopReason===`error`)throw Error(n.errorMessage||`Provider returned an error stop reason`);a.push({type:`done`,reason:n.stopReason,message:n}),a.end()}catch(e){for(let e of n.content)delete e.index,delete e.partialArgs,delete e.streamIndex;n.stopReason=i?.signal?.aborted?`aborted`:`error`,n.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let t=e?.error?.metadata?.raw;t&&(n.errorMessage+=`\n${t}`),a.push({type:`error`,reason:n.stopReason,error:n}),a.end()}})(),a},C=(e,n,a)=>{let o=a?.apiKey||t(e.provider);if(!o)throw Error(`No API key for provider: ${e.provider}`);let s=i(e,a,o),c=a?.reasoning?r(e,a.reasoning):void 0,l=c===`off`?void 0:c,u=a?.toolChoice;return S(e,n,{...s,reasoningEffort:l,toolChoice:u})};function w(e,t,n,r,i,a=z(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=f(t.messages),n=m({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 c({apiKey:n,baseURL:p(e.provider)?d(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:s})}function T(e,t,n,r=z(e),i=x(n?.cacheRetention)){let a=P(e,t,r),o=E(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=F(t.tools,r),r.zaiToolStream&&(s.tool_stream=!0)):g(t.messages)&&(s.tools=[]),o&&D(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(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 E(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 D(e,t,n){O(e,n),A(t,n),k(e,n)}function O(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){j(n,t);return}}function k(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`)&&M(r,t))return}}function A(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function j(e,t){return N(e,t)}function M(e,t){return e.role===`user`||e.role===`assistant`?N(e,t):!1}function N(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 P(e,t,n){let r=[],i=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},a=o(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:u(t.systemPrompt)})}let s=null;for(let t=0;t<a.length;t++){let i=a[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:u(i.content)});else{let e=i.content.map(e=>e.type===`text`?{type:`text`,text:u(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(_).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:u(e.text)})),o=a.map(e=>e.text).join(``),s=i.content.filter(v).filter(e=>e.thinking.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:s.map(e=>u(e.thinking)).join(`
2
+
3
+ `)},...a];else{o.length>0&&(t.content=o);let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
4
+ `))}else o.length>0&&(t.content=o);let c=i.content.filter(y);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.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 l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t)}else if(i.role===`toolResult`){let i=[],o=t;for(;o<a.length&&a[o].role===`toolResult`;o++){let t=a[o],s=t.content.filter(_).map(e=>e.text).join(`
5
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:u(s.length>0?s:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)b(e)&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=o-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),s=`user`):s=`toolResult`;continue}s=i.role}return r}function F(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function I(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,i=e.prompt_tokens_details?.cache_write_tokens||0,o=i>0?Math.max(0,r-i):r,s=Math.max(0,n-o-i),c=e.completion_tokens||0,l={input:s,output:c,cacheRead:o,cacheWrite:i,totalTokens:s+c+o+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return a(t,l),l}function L(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function R(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),a=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),o=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),s=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||i||t===`opencode`||n.includes(`opencode.ai`)||a||o,c=n.includes(`chutes.ai`)||i||o,l=t===`xai`||n.includes(`api.x.ai`),u=t===`deepseek`||n.includes(`deepseek.com`),d=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!s,supportsDeveloperRole:!s,supportsReasoningEffort:!l&&!r&&!i&&!o,supportsUsageInStreaming:!0,maxTokensField:c?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:u,thinkingFormat:u?`deepseek`:r?`zai`:t===`openrouter`||n.includes(`openrouter.ai`)?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!i&&!o,cacheControlFormat:d,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!(a||o)}}function z(e){let t=R(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{S as n,C as r,h as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./env-api-keys-CH1OdZie.js";import{a as t,c as n,r}from"./transform-messages-uhk4b6os.js";import{n as i}from"./openai-D6Fs9zDM.js";import{t as a}from"./headers-BCPSYYop.js";import{i as o,n as s,r as c,t as l}from"./github-copilot-headers-DFUtSIuj.js";import{n as u,r as d,t as f}from"./openai-responses-shared-DJ_O7os_.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}const _=(n,r,i)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:n.api,provider:n.provider,model:n.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=i?.apiKey||e(n.provider)||``,c=m(i?.cacheRetention)===`none`?void 0:i?.sessionId,l=y(n,r,s,i?.headers,c),u=b(n,r,i),f=await i?.onPayload?.(u,n);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 l.responses.create(u,p).withResponse();if(await i?.onResponse?.({status:g.status,headers:a(g.headers)},n),o.push({type:`start`,partial:t}),await d(h,t,o,n,{serviceTier:i?.serviceTier,applyServiceTierPricing:(e,t)=>S(e,t,n)}),i?.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=i?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},v=(t,i,a)=>{let o=a?.apiKey||e(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,a,o),c=a?.reasoning?n(t,a.reasoning):void 0,l=c===`off`?void 0:c;return _(t,i,{...s,reasoningEffort:l})};function y(e,t,n,r,a){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=l({messages:t.messages,hasImages:e});Object.assign(d,n)}a&&(u.sendSessionIdHeader&&(d.session_id=a),d[`x-client-request-id`]=a),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 i({apiKey:n,baseURL:c(e.provider)?o(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function b(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 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)}export{_ as streamOpenAIResponses,v as streamSimpleOpenAIResponses};
@@ -0,0 +1 @@
1
+ import{t as e}from"./env-api-keys-DxKb6C4Q.js";import{a as t,c as n,n as r}from"./simple-options-imi_RHvn.js";import{t as i}from"./headers-DkHU-pcw.js";import{i as a,n as o,r as s,t as c}from"./github-copilot-headers-B6Fvsk-Y.js";import{n as l}from"./openai-CRGaNv9i.js";import{n as u,r as d,t as f}from"./openai-responses-shared-vokXRwgV.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}var _=(n,r,a)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:n.api,provider:n.provider,model:n.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||e(n.provider)||``,c=m(a?.cacheRetention)===`none`?void 0:a?.sessionId,l=y(n,r,s,a?.headers,c),u=b(n,r,a),f=await a?.onPayload?.(u,n);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)},n),o.push({type:`start`,partial:t}),await d(h,t,o,n,{serviceTier:a?.serviceTier,applyServiceTierPricing:(e,t)=>S(e,t,n)}),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 instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},v=(t,i,a)=>{let o=a?.apiKey||e(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,a,o),c=a?.reasoning?n(t,a.reasoning):void 0,l=c===`off`?void 0:c;return _(t,i,{...s,reasoningEffort:l})};function y(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 b(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 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)}export{_ as streamOpenAIResponses,v as streamSimpleOpenAIResponses};
@@ -0,0 +1,12 @@
1
+ import{s as e,t}from"./transform-messages-uhk4b6os.js";import{n}from"./json-parse-Or9qhSeP.js";import{t as r}from"./sanitize-unicode-ncMKN_SD.js";import{t as i}from"./hash-CsofV07h.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
+ `),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
+
4
+ `,e.text+=`
5
+
6
+ `,i.push({type:`thinking_delta`,contentIndex:f(),delta:`
7
+
8
+ `,partial:r}))}}else if(d.type===`response.reasoning_text.delta`)c?.type===`reasoning`&&l?.type===`thinking`&&(l.thinking+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(d.part.type===`output_text`||d.part.type===`refusal`)&&c.content.push(d.part));else if(d.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`output_text`&&(l.text+=d.delta,e.text+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`refusal`&&(l.text+=d.delta,e.refusal+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=d.delta,l.arguments=n(l.partialJson),i.push({type:`toolcall_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.function_call_arguments.done`){if(c?.type===`function_call`&&l?.type===`toolCall`){let e=l.partialJson;if(l.partialJson=d.arguments,l.arguments=n(l.partialJson),d.arguments.startsWith(e)){let t=d.arguments.slice(e.length);t.length>0&&i.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:r})}}}else if(d.type===`response.output_item.done`){let e=d.item;if(e.type===`reasoning`&&l?.type===`thinking`){let t=e.summary?.map(e=>e.text).join(`
9
+
10
+ `)||``,n=e.content?.map(e=>e.text).join(`
11
+
12
+ `)||``;l.thinking=t||n||l.thinking,l.thinkingSignature=JSON.stringify(e),i.push({type:`thinking_end`,contentIndex:f(),content:l.thinking,partial:r}),l=null}else if(e.type===`message`&&l?.type===`text`)l.text=e.content.map(e=>e.type===`output_text`?e.text:e.refusal).join(``),l.textSignature=a(e.id,e.phase??void 0),i.push({type:`text_end`,contentIndex:f(),content:l.text,partial:r}),l=null;else if(e.type===`function_call`){let t=l?.type===`toolCall`&&l.partialJson?n(l.partialJson):n(e.arguments||`{}`),a;l?.type===`toolCall`?(l.arguments=t,delete l.partialJson,a=l):a={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:t},l=null,i.push({type:`toolcall_end`,contentIndex:f(),toolCall:a,partial:r})}}else if(d.type===`response.completed`){let t=d.response;if(t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details?.cached_tokens||0;r.usage={input:(t.usage.input_tokens||0)-e,output:t.usage.output_tokens||0,cacheRead:e,cacheWrite:0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(o,r.usage),s?.applyServiceTierPricing){let e=s.resolveServiceTier?s.resolveServiceTier(t?.service_tier,s.serviceTier):t?.service_tier??s.serviceTier;s.applyServiceTierPricing(r.usage,e)}r.stopReason=u(t?.status),r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)}else if(d.type===`error`)throw Error(`Error Code ${d.code}: ${d.message}`||`Unknown error`);else if(d.type===`response.failed`){let e=d.response?.error,t=d.response?.incomplete_details,n=e?`${e.code||`unknown`}: ${e.message||`no message`}`:t?.reason?`incomplete: ${t.reason}`:`Unknown error (no error details in response)`;throw Error(n)}}function u(e){if(!e)return`stop`;switch(e){case`completed`:return`stop`;case`incomplete`:return`length`;case`failed`:case`cancelled`:return`error`;case`in_progress`:case`queued`:return`stop`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{c as n,l as r,s as t};
@@ -1,4 +1,4 @@
1
- import{i as e,s as t}from"./simple-options-B0cR4giT.js";import{l as n}from"./index-BxaasNW5.js";import{t as r}from"./sanitize-unicode-DANurEy1.js";import{t as i}from"./hash-BwzabXYv.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(t,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=e(n.messages,t,(e,n,r)=>{if(!a.has(t.provider)||!e.includes(`|`))return l(e);let[i,o]=e.split(`|`),s=l(i),c=r.provider!==t.provider||r.api!==t.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&n.systemPrompt){let e=t.reasoning?`developer`:`system`;c.push({role:e,content:r(n.systemPrompt)})}let f=0;for(let e of d){if(e.role===`user`)if(typeof e.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(e.content)}]});else{let t=e.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(t.length===0)continue;c.push({role:`user`,content:t})}else if(e.role===`assistant`){let n=[],a=e,s=a.model!==t.id&&a.provider===t.provider&&a.api===t.api;for(let t of e.content)if(t.type===`thinking`){if(t.thinkingSignature){let e=JSON.parse(t.thinkingSignature);n.push(e)}}else if(t.type===`text`){let e=t,a=o(e.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(e.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(t.type===`toolCall`){let e=t,[r,i]=e.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:e.name,arguments:JSON.stringify(e.arguments)})}if(n.length===0)continue;c.push(...n)}else if(e.role===`toolResult`){let n=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
1
+ import{i as e,s as t}from"./simple-options-imi_RHvn.js";import{n}from"./json-parse-C5jSA6JB.js";import{t as r}from"./sanitize-unicode-BD2XKRoV.js";import{t as i}from"./hash-CQjDwcjR.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(t,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=e(n.messages,t,(e,n,r)=>{if(!a.has(t.provider)||!e.includes(`|`))return l(e);let[i,o]=e.split(`|`),s=l(i),c=r.provider!==t.provider||r.api!==t.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&n.systemPrompt){let e=t.reasoning?`developer`:`system`;c.push({role:e,content:r(n.systemPrompt)})}let f=0;for(let e of d){if(e.role===`user`)if(typeof e.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(e.content)}]});else{let t=e.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(t.length===0)continue;c.push({role:`user`,content:t})}else if(e.role===`assistant`){let n=[],a=e,s=a.model!==t.id&&a.provider===t.provider&&a.api===t.api;for(let t of e.content)if(t.type===`thinking`){if(t.thinkingSignature){let e=JSON.parse(t.thinkingSignature);n.push(e)}}else if(t.type===`text`){let e=t,a=o(e.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(e.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(t.type===`toolCall`){let e=t,[r,i]=e.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:e.name,arguments:JSON.stringify(e.arguments)})}if(n.length===0)continue;c.push(...n)}else if(e.role===`toolResult`){let n=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
2
  `),i=e.content.some(e=>e.type===`image`),a=n.length>0,[o]=e.toolCallId.split(`|`),s;if(i&&t.input.includes(`image`)){let t=[];a&&t.push({type:`input_text`,text:r(n)});for(let n of e.content)n.type===`image`&&t.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=t}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(e,r,i,o,s){let c=null,l=null,d=r.content,f=()=>d.length-1;for await(let d of e)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+=`