alchemylab-opencode 2.0.1 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NODE_COMPAT.md +8 -1
- package/dist/20260127222353_familiar_lady_ursula-YYOFSQD5.js +18 -0
- package/dist/20260211171708_add_project_commands-3GKQTPBZ.js +18 -0
- package/dist/20260213144116_wakeful_the_professor-ROO7OAVL.js +18 -0
- package/dist/20260225215848_workspace-V2OZTNFF.js +18 -0
- package/dist/20260227213759_add_session_workspace_id-GVDWAXKM.js +18 -0
- package/dist/20260228203230_blue_harpoon-Z5QP2II5.js +18 -0
- package/dist/20260303231226_add_workspace_fields-QOVAFN7W.js +18 -0
- package/dist/20260309230000_move_org_to_state-RQURSDZD.js +18 -0
- package/dist/20260312043431_session_message_cursor-VBISKDXL.js +18 -0
- package/dist/20260323234822_events-PILJHLNA.js +18 -0
- package/dist/20260410174513_workspace-name-63YCZ5NS.js +18 -0
- package/dist/20260413175956_chief_energizer-NMAZYGDO.js +18 -0
- package/dist/20260423070820_add_icon_url_override-RAJCVNEP.js +18 -0
- package/dist/20260427172553_slow_nightmare-ULYYZLR4.js +18 -0
- package/dist/20260428004200_add_session_path-U4WO2TGE.js +18 -0
- package/dist/20260501142318_next_venus-6BCYATSC.js +18 -0
- package/dist/20260504145000_add_sync_owner-RGVHV6LN.js +18 -0
- package/dist/20260507164347_add_workspace_time-GE6UHNPM.js +18 -0
- package/dist/{20260510033149_session_usage-UGBVOXZB.js → 20260510033149_session_usage-7XHCFVKY.js} +5 -1
- package/dist/20260511000411_data_migration_state-2EGZKFLB.js +18 -0
- package/dist/20260511173437_session-metadata-K322YY33.js +18 -0
- package/dist/20260601010001_normalize_storage_paths-VZDTY366.js +18 -0
- package/dist/{20260225215848_workspace-ZMSOZSPA.js → 20260601202201_amazing_prowler-YT6PLK3L.js} +5 -1
- package/dist/{20260228203230_blue_harpoon-IW3Z4TQZ.js → 20260602002951_lowly_union_jack-6VLQTBVB.js} +5 -1
- package/dist/20260602182828_add_project_directories-TVSRD25A.js +18 -0
- package/dist/20260603001617_session_message_projection_indexes-PHKTF6HK.js +18 -0
- package/dist/{20260622170816_reset_v2_session_state-5JPHJTZG.js → 20260603040000_session_message_projection_order-7RTV2POG.js} +5 -1
- package/dist/20260603141458_session_input_inbox-RSBWABG7.js +18 -0
- package/dist/20260603160727_jittery_ezekiel_stane-DXBLLRVV.js +18 -0
- package/dist/20260604172448_event_sourced_session_input-H6Z3JEBD.js +18 -0
- package/dist/20260605003541_add_session_context_snapshot-6FDPM2TK.js +18 -0
- package/dist/20260605042240_add_context_epoch_agent-C2OF2UKR.js +18 -0
- package/dist/20260611035744_credential-YNZ47FSH.js +18 -0
- package/dist/20260611192811_lush_chimera-E357VI6P.js +18 -0
- package/dist/20260612174303_project_dir_strategy-VUGGK42O.js +18 -0
- package/dist/20260622142730_simplify_session_context_epoch-UYGXZ5BX.js +18 -0
- package/dist/20260622170816_reset_v2_session_state-EILLPCJQ.js +18 -0
- package/dist/20260622202450_simplify_session_input-Y65GDGBO.js +18 -0
- package/dist/NodeSdk-AGMQWBHH.js +18 -0
- package/dist/anthropic-45OFTLAW.js +18 -0
- package/dist/anthropic-FVULF7C3.js +18 -0
- package/dist/app-runtime-LDQWNGWP.js +18 -0
- package/dist/chunk-2JE3QYG6.js +18 -0
- package/dist/chunk-2MRHL4B2.js +18 -0
- package/dist/chunk-4GJE6OMN.js +190 -0
- package/dist/chunk-4MBUHJHY.js +22 -0
- package/dist/chunk-5BLZCAU6.js +55 -0
- package/dist/chunk-7XX6TY62.js +259 -0
- package/dist/chunk-ANF3QA3Z.js +48 -0
- package/dist/chunk-AZUMH3TO.js +18 -0
- package/dist/chunk-B74WSFN4.js +878 -0
- package/dist/chunk-BQ4IEPN3.js +19 -0
- package/dist/chunk-CYRZU5QM.js +33 -0
- package/dist/chunk-DADVNQTM.js +1490 -0
- package/dist/chunk-DO2UZ6NY.js +18 -0
- package/dist/chunk-DWEYXIQI.js +780 -0
- package/dist/chunk-EK6FQQHY.js +20 -0
- package/dist/chunk-ELPXQ32J.js +90 -0
- package/dist/chunk-FGLPSSRK.js +19 -0
- package/dist/chunk-FOHYZ7MJ.js +55 -0
- package/dist/chunk-FV7U6PVP.js +18 -0
- package/dist/chunk-FYYAOZPU.js +18 -0
- package/dist/chunk-G7PFO5HG.js +920 -0
- package/dist/chunk-GDWO6EXN.js +22 -0
- package/dist/chunk-GW3ZRKAI.js +20 -0
- package/dist/chunk-IYUSBBGY.js +35 -0
- package/dist/chunk-JPOFLMNH.js +18 -0
- package/dist/{chunk-VURLSDCB.js → chunk-K5LKDIVU.js} +4 -0
- package/dist/chunk-KS4WLVK5.js +19 -0
- package/dist/chunk-LIXP4TPL.js +18 -0
- package/dist/chunk-LSC4RT5V.js +36 -0
- package/dist/chunk-M5A6NFHQ.js +28 -0
- package/dist/chunk-M6E6KNLV.js +30 -0
- package/dist/chunk-MLFZXUGQ.js +18 -0
- package/dist/chunk-NDI67DRG.js +31 -0
- package/dist/chunk-NGT6LCW6.js +18 -0
- package/dist/chunk-OCWGUTZJ.js +36 -0
- package/dist/chunk-OGDRUXMJ.js +18 -0
- package/dist/chunk-OGJKLJC7.js +29 -0
- package/dist/chunk-OT2YNR56.js +19 -0
- package/dist/chunk-OUVSKG2H.js +19 -0
- package/dist/chunk-P5RLCJUV.js +18 -0
- package/dist/chunk-Q3WIUQXB.js +18 -0
- package/dist/{20260227213759_add_session_workspace_id-ROENWPKA.js → chunk-QCRIXKIC.js} +5 -1
- package/dist/chunk-QD24DLUD.js +18 -0
- package/dist/chunk-R2GWBJEP.js +18 -0
- package/dist/chunk-RPAXSOGH.js +18 -0
- package/dist/chunk-TK5R7QUN.js +18 -0
- package/dist/chunk-TNQWZFIZ.js +28 -0
- package/dist/chunk-UCLPBO4I.js +18 -0
- package/dist/chunk-UPEPL4I2.js +18 -0
- package/dist/chunk-V6FDDNGV.js +117 -0
- package/dist/chunk-V6HERYFV.js +18 -0
- package/dist/chunk-V7XKKJ7X.js +24 -0
- package/dist/chunk-VHDYUBBS.js +23 -0
- package/dist/chunk-VWLJXTZ5.js +18 -0
- package/dist/chunk-VXAPFOIL.js +22 -0
- package/dist/chunk-WKZYINC7.js +29 -0
- package/dist/chunk-WPMP2ZFE.js +40 -0
- package/dist/chunk-WRTNIOI3.js +18 -0
- package/dist/chunk-X5F46HR5.js +18 -0
- package/dist/chunk-XPS7TQZG.js +22 -0
- package/dist/chunk-YJPP6IQ3.js +23 -0
- package/dist/chunk-ZYQWFC55.js +22 -0
- package/dist/code-mode-YYOGD36U.js +502 -0
- package/dist/copilot-provider-QVMLQZZC.js +18 -0
- package/dist/dist-5NQOHNPL.js +18 -0
- package/dist/dist-7CT3XCNN.js +32 -0
- package/dist/dist-CL46WFZG.js +18 -0
- package/dist/{20260605042240_add_context_epoch_agent-W6IQYZXE.js → dist-CYBRID2F.js} +5 -1
- package/dist/dist-HXJTF22W.js +32 -0
- package/dist/dist-JFXI53ZF.js +22 -0
- package/dist/dist-KBYKWVT5.js +22 -0
- package/dist/dist-KM5HCPZX.js +35 -0
- package/dist/dist-KTNLTEHB.js +18 -0
- package/dist/dist-KZ5R5QM5.js +24 -0
- package/dist/dist-NLXUYBW7.js +32 -0
- package/dist/dist-O4DF72J2.js +22 -0
- package/dist/dist-PH4MEGVR.js +22 -0
- package/dist/{20260511000411_data_migration_state-FB4LBFSE.js → dist-QJPOJCLB.js} +5 -1
- package/dist/dist-QYH62TCJ.js +22 -0
- package/dist/{20260303231226_add_workspace_fields-OUVZMNAG.js → dist-RIC4WKHC.js} +5 -1
- package/dist/dist-T776XKTM.js +22 -0
- package/dist/dist-TCE5MKZQ.js +23 -0
- package/dist/dist-TH2Q44RX.js +50 -0
- package/dist/dist-VV5FV5RT.js +101 -0
- package/dist/dist-XAFENVUS.js +22 -0
- package/dist/dist-XPFB35TX.js +32 -0
- package/dist/dist-YUH4RKR5.js +28 -0
- package/dist/dist-es-43ZM44MP.js +18 -0
- package/dist/dist-es-6PLFRCS4.js +18 -0
- package/dist/dist-es-G5UIJOU7.js +26 -0
- package/dist/{20260428004200_add_session_path-LGW75WYA.js → dist-es-HYIIGUNX.js} +5 -1
- package/dist/dist-es-L2GU465G.js +18 -0
- package/dist/dist-es-LSR2QCFZ.js +18 -0
- package/dist/dist-es-RGEIM2BP.js +18 -0
- package/dist/dist-es-SITTNOGV.js +18 -0
- package/dist/dist-es-W5GYOX6F.js +18 -0
- package/dist/esm-NN5W7YCL.js +18 -0
- package/dist/esm-XWJSHYHG.js +18 -0
- package/dist/getMachineId-bsd-L5I5TZ5I.js +18 -0
- package/dist/getMachineId-darwin-YB7KG37W.js +19 -0
- package/dist/getMachineId-linux-EL47KXX7.js +18 -0
- package/dist/getMachineId-unsupported-QOWPEBPN.js +18 -0
- package/dist/getMachineId-win-HCRYRDFJ.js +18 -0
- package/dist/lib-ZP7Q6A3E.js +199 -0
- package/dist/loadCognitoIdentity-EWT55EI7.js +18 -0
- package/dist/loadSso-AGOUE6RL.js +18 -0
- package/dist/{20260213144116_wakeful_the_professor-ZVDD54AK.js → loadSts-RH5L3PIX.js} +5 -1
- package/dist/mantle-IJXDXT4M.js +25 -0
- package/dist/mime-types-46EO4HOZ.js +18 -0
- package/dist/multipart-parser-KZWMKXA4.js +19 -0
- package/dist/{20260211171708_add_project_commands-GDOHPDPF.js → open-7KXTRM37.js} +5 -1
- package/dist/openai-ZOJI6I5R.js +18 -0
- package/dist/p-map-CYL6ILJW.js +18 -0
- package/dist/photon-W56QZY4L.js +18 -0
- package/dist/{20260423070820_add_icon_url_override-X5SHFGTI.js → pkce-VT4ITJTB.js} +5 -1
- package/dist/{pty.node-Y3N2XKYG.js → pty.node-IWULXXG6.js} +5 -1
- package/dist/run.js +5 -1
- package/dist/serve.js +143 -1
- package/dist/server-LVIHYOCY.js +21 -0
- package/dist/session-6OPJNJMK.js +18 -0
- package/dist/signin-OCIW23YM.js +18 -0
- package/dist/src-3NCXEROI.js +18 -0
- package/dist/src-LXWGIUZH.js +18 -0
- package/dist/src-WDYKISPD.js +20 -0
- package/dist/src-YAAFIGTW.js +18 -0
- package/dist/sso-oidc-OMMKINFE.js +18 -0
- package/dist/sts-MWK22JIX.js +18 -0
- package/dist/token-QPO3OAGS.js +18 -0
- package/dist/token-util-YGPCEEPO.js +18 -0
- package/dist/unified-W3ZKZ4HG.js +18 -0
- package/dist/worktree-32M5MTFE.js +18 -0
- package/package.json +40 -40
- package/postinstall.cjs +4 -2
- package/dist/20260127222353_familiar_lady_ursula-KV747FJX.js +0 -14
- package/dist/20260309230000_move_org_to_state-NOXAPU5V.js +0 -14
- package/dist/20260312043431_session_message_cursor-DJ4T3T4R.js +0 -14
- package/dist/20260323234822_events-72GIKJ2A.js +0 -14
- package/dist/20260410174513_workspace-name-JXSWFBJN.js +0 -14
- package/dist/20260413175956_chief_energizer-4HEWZ6U3.js +0 -14
- package/dist/20260427172553_slow_nightmare-PS5T2AH2.js +0 -14
- package/dist/20260501142318_next_venus-J3TLVXZ6.js +0 -14
- package/dist/20260504145000_add_sync_owner-3R52GB4C.js +0 -14
- package/dist/20260507164347_add_workspace_time-JHDRCZAR.js +0 -14
- package/dist/20260511173437_session-metadata-T2XHGWHS.js +0 -14
- package/dist/20260601010001_normalize_storage_paths-5MAY5GT3.js +0 -14
- package/dist/20260601202201_amazing_prowler-PET224YG.js +0 -14
- package/dist/20260602002951_lowly_union_jack-PG6XDMGL.js +0 -14
- package/dist/20260602182828_add_project_directories-ZCH2ACGG.js +0 -14
- package/dist/20260603001617_session_message_projection_indexes-XVLJTUF2.js +0 -14
- package/dist/20260603040000_session_message_projection_order-XG6RACZQ.js +0 -14
- package/dist/20260603141458_session_input_inbox-K2VQ7V6E.js +0 -14
- package/dist/20260603160727_jittery_ezekiel_stane-WKJLRDO7.js +0 -14
- package/dist/20260604172448_event_sourced_session_input-NTXOECR7.js +0 -14
- package/dist/20260605003541_add_session_context_snapshot-DXMQEXMT.js +0 -14
- package/dist/20260611035744_credential-XTMSYTJD.js +0 -14
- package/dist/20260611192811_lush_chimera-XPLIQMJD.js +0 -14
- package/dist/20260612174303_project_dir_strategy-FR2NGQKK.js +0 -14
- package/dist/20260622142730_simplify_session_context_epoch-NTQZR3RE.js +0 -14
- package/dist/20260622202450_simplify_session_input-2EXF2HMV.js +0 -14
- package/dist/app-runtime-HQBOCDV5.js +0 -14
- package/dist/chunk-4FEBIOI5.js +0 -865
- package/dist/chunk-4K2RXRZL.js +0 -14
- package/dist/chunk-4RFMKEKM.js +0 -1455
- package/dist/chunk-BM2C7NHL.js +0 -41
- package/dist/chunk-MKEMZFJI.js +0 -393
- package/dist/chunk-OMDJ6ZZ2.js +0 -684
- package/dist/chunk-OWMG4NNF.js +0 -186
- package/dist/chunk-QRABYJKL.js +0 -14
- package/dist/chunk-RHIWAYN5.js +0 -14
- package/dist/chunk-Z5TLIUAI.js +0 -28
- package/dist/code-mode-7BQJUARW.js +0 -40
- package/dist/copilot-provider-TX4YFKJZ.js +0 -14
- package/dist/photon-VQS5F5BI.js +0 -14
- package/dist/server-BFUQR7MX.js +0 -17
- package/dist/session-6RNXZNG6.js +0 -14
- package/dist/worktree-QHQHX3SG.js +0 -14
- package/patches/@ai-sdk%2Famazon-bedrock@4.0.166.patch +0 -164
- package/patches/@ai-sdk%2Fanthropic@3.0.111.patch +0 -528
- package/patches/@ai-sdk%2Fgoogle@3.0.73.patch +0 -69
- package/patches/@ai-sdk%2Fgroq@3.0.31.patch +0 -79
- package/patches/@ai-sdk%2Fmistral@3.0.51.patch +0 -714
- package/patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch +0 -39
- package/patches/@ai-sdk%2Fopenai@3.0.88.patch +0 -280
- package/patches/@ai-sdk%2Fxai@3.0.139.patch +0 -296
- package/patches/@modelcontextprotocol%2Fsdk@1.29.0.patch +0 -647
- package/patches/@npmcli%2Fagent@4.0.2.patch +0 -13
- package/patches/effect@4.0.0-beta.83.patch +0 -57
- package/patches/gcp-metadata@8.1.2.patch +0 -14
- package/patches/pacote@21.5.0.patch +0 -18
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Built by esbuild from opencode-server source
|
|
2
|
+
if (typeof globalThis.Bun === 'undefined') {
|
|
3
|
+
globalThis.Bun = {
|
|
4
|
+
version: '0.0.0-node-compat',
|
|
5
|
+
stdin: { async text() { const chunks = []; for await (const c of process.stdin) chunks.push(c); return Buffer.concat(chunks).toString(); } },
|
|
6
|
+
which(cmd) { try { return require('child_process').execFileSync('which', [cmd], { encoding: 'utf8' }).trim(); } catch { return null; } },
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
|
|
10
|
+
if (typeof globalThis.__export === 'undefined') { globalThis.__export = (t, a) => { for (const k in a) Object.defineProperty(t, k, { get: a[k], enumerable: true }); }; }
|
|
11
|
+
import { createRequire as __alchemyCreateRequire } from 'node:module';
|
|
12
|
+
const require = __alchemyCreateRequire(import.meta.url);
|
|
13
|
+
import { fileURLToPath as __alchemyFileURLToPath } from 'node:url';
|
|
14
|
+
import { dirname as __alchemyDirname } from 'node:path';
|
|
15
|
+
const __alchemy_filename = __alchemyFileURLToPath(import.meta.url);
|
|
16
|
+
const __alchemy_dirname = __alchemyDirname(__alchemy_filename);
|
|
17
|
+
|
|
18
|
+
import{A as Ie}from"./chunk-WPMP2ZFE.js";import{a as hl,b as pl,c as ml,d as gl,e as _l,f as yl,g as wl,h as bl}from"./chunk-V7XKKJ7X.js";import{a as i,d as Gi,g as fl}from"./chunk-2MRHL4B2.js";var Lc=Gi((kv,Fc)=>{"use strict";var vd=yl(),Pd=gl(),Rd=hl(),Ed=pl(),Cd=ml(),Td=wl(),Te=_l(),Nc=bl();Te.createWebSocketStream=vd;Te.extension=Pd;Te.PerMessageDeflate=Rd;Te.Receiver=Ed;Te.Sender=Cd;Te.Server=Nc;Te.subprotocol=Td;Te.WebSocket=Te;Te.WebSocketServer=Nc;Fc.exports=Te});var Uc=Gi((Av,Dc)=>{"use strict";Dc.exports=Lc()});function R(r,e,t,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t}i(R,"__classPrivateFieldSet");function g(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)}i(g,"__classPrivateFieldGet");var Ao=i(function(){let{crypto:r}=globalThis;if(r?.randomUUID)return Ao=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))},"uuid4");function Be(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}i(Be,"isAbortError");var As=i(r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)},"castToError");var $=class extends Error{static{i(this,"AnthropicError")}},ne=class r extends ${static{i(this,"APIError")}constructor(e,t,s,n){super(`${r.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t}static makeMessage(e,t,s){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new st({message:s,cause:As(t)});let o=t;return e===400?new cr(e,o,s,n):e===401?new lr(e,o,s,n):e===403?new ur(e,o,s,n):e===404?new dr(e,o,s,n):e===409?new fr(e,o,s,n):e===422?new hr(e,o,s,n):e===429?new pr(e,o,s,n):e>=500?new mr(e,o,s,n):new r(e,o,s,n)}},ae=class extends ne{static{i(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},st=class extends ne{static{i(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ar=class extends st{static{i(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},cr=class extends ne{static{i(this,"BadRequestError")}},lr=class extends ne{static{i(this,"AuthenticationError")}},ur=class extends ne{static{i(this,"PermissionDeniedError")}},dr=class extends ne{static{i(this,"NotFoundError")}},fr=class extends ne{static{i(this,"ConflictError")}},hr=class extends ne{static{i(this,"UnprocessableEntityError")}},pr=class extends ne{static{i(this,"RateLimitError")}},mr=class extends ne{static{i(this,"InternalServerError")}};var kl=/^[a-z][a-z0-9+.-]*:/i,Ji=i(r=>kl.test(r),"isAbsoluteURL"),So=i(r=>(So=Array.isArray,So(r)),"isArray"),Io=So;function bn(r){return typeof r!="object"?{}:r??{}}i(bn,"maybeObj");function Ki(r){if(!r)return!0;for(let e in r)return!1;return!0}i(Ki,"isEmptyObj");function Vi(r,e){return Object.prototype.hasOwnProperty.call(r,e)}i(Vi,"hasOwn");var Xi=i((r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new $(`${r} must be an integer`);if(e<0)throw new $(`${r} must be a positive integer`);return e},"validatePositiveInteger");var xn=i(r=>{try{return JSON.parse(r)}catch{return}},"safeJSON");var zi=i(r=>new Promise(e=>setTimeout(e,r)),"sleep");var nt="0.71.2";var ea=i(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function Al(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}i(Al,"getDetectedPlatform");var Sl=i(()=>{let r=Al();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nt,"X-Stainless-OS":Qi(Deno.build.os),"X-Stainless-Arch":Yi(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nt,"X-Stainless-OS":Qi(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yi(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Il();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Il(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let s=t.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}i(Il,"getBrowserInfo");var Yi=i(r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown","normalizeArch"),Qi=i(r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),"normalizePlatform"),Zi,ta=i(()=>Zi??(Zi=Sl()),"getPlatformHeaders");function ra(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}i(ra,"getDefaultFetch");function vo(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}i(vo,"makeReadableStream");function kn(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return vo({start(){},async pull(t){let{done:s,value:n}=await e.next();s?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}i(kn,"ReadableStreamFrom");function Ss(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}i(Ss,"ReadableStreamToAsyncIterable");async function sa(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}i(sa,"CancelReadableStream");var na=i(({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function aa(r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return t}i(aa,"concatBytes");var oa;function Is(r){let e;return(oa??(e=new globalThis.TextEncoder,oa=e.encode.bind(e)))(r)}i(Is,"encodeUTF8");var ia;function Po(r){let e;return(ia??(e=new globalThis.TextDecoder,ia=e.decode.bind(e)))(r)}i(Po,"decodeUTF8");var pe,me,We=class{static{i(this,"LineDecoder")}constructor(){pe.set(this,void 0),me.set(this,void 0),R(this,pe,new Uint8Array,"f"),R(this,me,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Is(e):e;R(this,pe,aa([g(this,pe,"f"),t]),"f");let s=[],n;for(;(n=Rl(g(this,pe,"f"),g(this,me,"f")))!=null;){if(n.carriage&&g(this,me,"f")==null){R(this,me,n.index,"f");continue}if(g(this,me,"f")!=null&&(n.index!==g(this,me,"f")+1||n.carriage)){s.push(Po(g(this,pe,"f").subarray(0,g(this,me,"f")-1))),R(this,pe,g(this,pe,"f").subarray(g(this,me,"f")),"f"),R(this,me,null,"f");continue}let o=g(this,me,"f")!==null?n.preceding-1:n.preceding,a=Po(g(this,pe,"f").subarray(0,o));s.push(a),R(this,pe,g(this,pe,"f").subarray(n.index),"f"),R(this,me,null,"f")}return s}flush(){return g(this,pe,"f").length?this.decode(`
|
|
19
|
+
`):[]}};pe=new WeakMap,me=new WeakMap;We.NEWLINE_CHARS=new Set([`
|
|
20
|
+
`,"\r"]);We.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Rl(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}i(Rl,"findNewlineIndex");function ca(r){for(let s=0;s<r.length-1;s++){if(r[s]===10&&r[s+1]===10||r[s]===13&&r[s+1]===13)return s+2;if(r[s]===13&&r[s+1]===10&&s+3<r.length&&r[s+2]===13&&r[s+3]===10)return s+4}return-1}i(ca,"findDoubleNewlineIndex");var Sn={off:0,error:200,warn:300,info:400,debug:500},Ro=i((r,e,t)=>{if(r){if(Vi(Sn,r))return r;oe(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Sn))}`)}},"parseLogLevel");function vs(){}i(vs,"noop");function An(r,e,t){return!e||Sn[r]>Sn[t]?vs:e[r].bind(e)}i(An,"makeLogFn");var El={error:vs,warn:vs,info:vs,debug:vs},la=new WeakMap;function oe(r){let e=r.logger,t=r.logLevel??"off";if(!e)return El;let s=la.get(e);if(s&&s[0]===t)return s[1];let n={error:An("error",e,t),warn:An("warn",e,t),info:An("info",e,t),debug:An("debug",e,t)};return la.set(e,[t,n]),n}i(oe,"loggerFor");var He=i(r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r),"formatRequestDetails");var Ps,Me=class r{static{i(this,"Stream")}constructor(e,t,s){this.iterator=e,Ps.set(this,void 0),this.controller=t,R(this,Ps,s,"f")}static fromSSEResponse(e,t,s){let n=!1,o=s?oe(s):console;async function*a(){if(n)throw new $("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let l of Cl(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(u){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),u}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(u){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),u}if(l.event!=="ping"&&l.event==="error")throw new ne(void 0,xn(l.data)??l.data,void 0,e.headers)}c=!0}catch(l){if(Be(l))return;throw l}finally{c||t.abort()}}return i(a,"iterator"),new r(a,t,s)}static fromReadableStream(e,t,s){let n=!1;async function*o(){let c=new We,l=Ss(e);for await(let u of l)for(let f of c.decode(u))yield f;for(let u of c.flush())yield u}i(o,"iterLines");async function*a(){if(n)throw new $("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let l of o())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(Be(l))return;throw l}finally{c||t.abort()}}return i(a,"iterator"),new r(a,t,s)}[(Ps=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],s=this.iterator(),n=i(o=>({next:i(()=>{if(o.length===0){let a=s.next();e.push(a),t.push(a)}return o.shift()},"next")}),"teeIterator");return[new r(()=>n(e),this.controller,g(this,Ps,"f")),new r(()=>n(t),this.controller,g(this,Ps,"f"))]}toReadableStream(){let e=this,t;return vo({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:n,done:o}=await t.next();if(o)return s.close();let a=Is(JSON.stringify(n)+`
|
|
21
|
+
`);s.enqueue(a)}catch(n){s.error(n)}},async cancel(){await t.return?.()}})}};async function*Cl(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new $("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new $("Attempted to iterate over a response with no body");let t=new Eo,s=new We,n=Ss(r.body);for await(let o of Tl(n))for(let a of s.decode(o)){let c=t.decode(a);c&&(yield c)}for(let o of s.flush()){let a=t.decode(o);a&&(yield a)}}i(Cl,"_iterSSEMessages");async function*Tl(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Is(t):t,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=ca(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}i(Tl,"iterSSEChunks");var Eo=class{static{i(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
22
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=Ol(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Ol(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}i(Ol,"partition");async function In(r,e){let{response:t,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return oe(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Me.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){let d=await t.json();return Co(d,t)}return await t.text()})();return oe(r).debug(`[${s}] response parsed`,He({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}i(In,"defaultParseResponse");function Co(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}i(Co,"addRequestID");var Rs,Rt=class r extends Promise{static{i(this,"APIPromise")}constructor(e,t,s=In){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=s,Rs.set(this,void 0),R(this,Rs,e,"f")}_thenUnwrap(e){return new r(g(this,Rs,"f"),this.responsePromise,async(t,s)=>Co(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(g(this,Rs,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Rs=new WeakMap;var vn,Pn=class{static{i(this,"AbstractPage")}constructor(e,t,s,n){vn.set(this,void 0),R(this,vn,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new $("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await g(this,vn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(vn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Es=class extends Rt{static{i(this,"PagePromise")}constructor(e,t,s){super(e,t,async(n,o)=>new s(n,o.response,await In(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ke=class extends Pn{static{i(this,"Page")}constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.first_id=s.first_id||null,this.last_id=s.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let t=this.first_id;return t?{...this.options,query:{...bn(this.options.query),before_id:t}}:null}let e=this.last_id;return e?{...this.options,query:{...bn(this.options.query),after_id:e}}:null}};var gr=class extends Pn{static{i(this,"PageCursor")}constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.next_page=s.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...bn(this.options.query),page:e}}:null}};var Oo=i(()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function Et(r,e,t){return Oo(),new File(r,e??"unknown_file",t)}i(Et,"makeFile");function Cs(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}i(Cs,"getName");var Mo=i(r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function","isAsyncIterable");var _r=i(async(r,e)=>({...r,body:await Nl(r.body,e)}),"multipartFormRequestOptions"),ua=new WeakMap;function $l(r){let e=typeof r=="function"?r:r.fetch,t=ua.get(e);if(t)return t;let s=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return ua.set(e,s),s}i($l,"supportsFormData");var Nl=i(async(r,e)=>{if(!await $l(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([s,n])=>To(t,s,n))),t},"createForm"),Fl=i(r=>r instanceof Blob&&"name"in r,"isNamedBlob");var To=i(async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response){let s={},n=t.headers.get("Content-Type");n&&(s={type:n}),r.append(e,Et([await t.blob()],Cs(t),s))}else if(Mo(t))r.append(e,Et([await new Response(kn(t)).blob()],Cs(t)));else if(Fl(t))r.append(e,Et([t],Cs(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(s=>To(r,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,n])=>To(r,`${e}[${s}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},"addFormValue");var da=i(r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function","isBlobLike"),Ll=i(r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&da(r),"isFileLike"),Dl=i(r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function","isResponseLike");async function Rn(r,e,t){if(Oo(),r=await r,e||(e=Cs(r)),Ll(r))return r instanceof File&&e==null&&t==null?r:Et([await r.arrayBuffer()],e??r.name,{type:r.type,lastModified:r.lastModified,...t});if(Dl(r)){let n=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),Et(await $o(n),e,t)}let s=await $o(r);if(!t?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Et(s,e,t)}i(Rn,"toFile");async function $o(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(da(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Mo(r))for await(let t of r)e.push(...await $o(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Ul(r)}`)}return e}i($o,"getBytes");function Ul(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}i(Ul,"propsForError");var J=class{static{i(this,"APIResource")}constructor(e){this._client=e}};var fa=Symbol.for("brand.privateNullableHeaders");function*ql(r){if(!r)return;if(fa in r){let{values:s,nulls:n}=r;yield*s.entries();for(let o of n)yield[o,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Io(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let s of t){let n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Io(s[1])?s[1]:[s[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,c])}}i(ql,"iterateHeaders");var j=i(r=>{let e=new Headers,t=new Set;for(let s of r){let n=new Set;for(let[o,a]of ql(s)){let c=o.toLowerCase();n.has(c)||(e.delete(o),n.add(c)),a===null?(e.delete(o),t.add(c)):(e.append(o,a),t.delete(c))}}return{[fa]:!0,values:e,nulls:t}},"buildHeaders");function pa(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}i(pa,"encodeURIPath");var ha=Object.freeze(Object.create(null)),Bl=i((r=pa)=>i(function(t,...s){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((f,d,m)=>{/[?#]/.test(d)&&(n=!0);let h=s[m],x=(n?encodeURIComponent:r)(""+h);return m!==s.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??ha)??ha)?.toString)&&(x=h+"",o.push({start:f.length+d.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),f+d+(m===s.length?"":x)},""),c=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=l.exec(c))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((f,d)=>f.start-d.start),o.length>0){let f=0,d=o.reduce((m,h)=>{let x=" ".repeat(h.start-f),y="^".repeat(h.length);return f=h.start+h.length,m+x+y},"");throw new $(`Path parameters result in path with invalid segments:
|
|
23
|
+
${o.map(m=>m.error).join(`
|
|
24
|
+
`)}
|
|
25
|
+
${a}
|
|
26
|
+
${d}`)}return a},"path"),"createPathTagFunction"),K=Bl(pa);var yr=class extends J{static{i(this,"Files")}list(e={},t){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/files",ke,{query:n,...t,headers:j([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},s){let{betas:n}=t??{};return this._client.delete(K`/v1/files/${e}`,{...s,headers:j([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}download(e,t={},s){let{betas:n}=t??{};return this._client.get(K`/v1/files/${e}/content`,{...s,headers:j([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},s){let{betas:n}=t??{};return this._client.get(K`/v1/files/${e}`,{...s,headers:j([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}upload(e,t){let{betas:s,...n}=e;return this._client.post("/v1/files",_r({body:n,...t,headers:j([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}};var wr=class extends J{static{i(this,"Models")}retrieve(e,t={},s){let{betas:n}=t??{};return this._client.get(K`/v1/models/${e}?beta=true`,{...s,headers:j([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",ke,{query:n,...t,headers:j([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}};var En={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function No(r,e,t){return!e||!("parse"in(e.output_format??{}))?{...r,content:r.content.map(s=>{if(s.type==="text"){let n=Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(n,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return s}),parsed_output:null}:Fo(r,e,t)}i(No,"maybeParseBetaMessage");function Fo(r,e,t){let s=null,n=r.content.map(o=>{if(o.type==="text"){let a=Gl(e,o.text);s===null&&(s=a);let c=Object.defineProperty({...o},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return o});return{...r,content:n,parsed_output:s}}i(Fo,"parseBetaMessage");function Gl(r,e){if(r.output_format?.type!=="json_schema")return null;try{return"parse"in r.output_format?r.output_format.parse(e):JSON.parse(e)}catch(t){throw new $(`Failed to parse structured output: ${t}`)}}i(Gl,"parseBetaOutputFormat");var Jl=i(r=>{let e=0,t=[];for(;e<r.length;){let s=r[e];if(s==="\\"){e++;continue}if(s==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(s==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(s==="["){t.push({type:"paren",value:"["}),e++;continue}if(s==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(s===":"){t.push({type:"separator",value:":"}),e++;continue}if(s===","){t.push({type:"delimiter",value:","}),e++;continue}if(s==='"'){let c="",l=!1;for(s=r[++e];s!=='"';){if(e===r.length){l=!0;break}if(s==="\\"){if(e++,e===r.length){l=!0;break}c+=s+r[e],s=r[++e]}else c+=s,s=r[++e]}s=r[++e],l||t.push({type:"string",value:c});continue}if(s&&/\s/.test(s)){e++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let c="";for(s==="-"&&(c+=s,s=r[++e]);s&&o.test(s)||s===".";)c+=s,s=r[++e];t.push({type:"number",value:c});continue}let a=/[a-z]/i;if(s&&a.test(s)){let c="";for(;s&&a.test(s)&&e!==r.length;)c+=s,s=r[++e];if(c=="true"||c=="false"||c==="null")t.push({type:"name",value:c});else{e++;continue}continue}e++}return t},"tokenize"),br=i(r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),br(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),br(r);case"string":let s=r[r.length-2];if(s?.type==="delimiter")return r=r.slice(0,r.length-1),br(r);if(s?.type==="brace"&&s.value==="{")return r=r.slice(0,r.length-1),br(r);break;case"delimiter":return r=r.slice(0,r.length-1),br(r);break}return r},"strip"),Kl=i(r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},"unstrip"),Vl=i(r=>{let e="";return r.map(t=>{t.type==="string"?e+='"'+t.value+'"':e+=t.value}),e},"generate"),Cn=i(r=>JSON.parse(Vl(Kl(br(Jl(r))))),"partialParse");var Ae,ot,xr,Ts,Tn,Os,Ms,On,$s,Ge,Ns,Mn,$n,Ct,Nn,Fn,Fs,Lo,ma,Ln,Do,Uo,jo,ga,_a="__json_buf";function ya(r){return r.type==="tool_use"||r.type==="server_tool_use"||r.type==="mcp_tool_use"}i(ya,"tracksToolInput");var Dn=class r{static{i(this,"BetaMessageStream")}constructor(e,t){Ae.add(this),this.messages=[],this.receivedMessages=[],ot.set(this,void 0),xr.set(this,null),this.controller=new AbortController,Ts.set(this,void 0),Tn.set(this,()=>{}),Os.set(this,()=>{}),Ms.set(this,void 0),On.set(this,()=>{}),$s.set(this,()=>{}),Ge.set(this,{}),Ns.set(this,!1),Mn.set(this,!1),$n.set(this,!1),Ct.set(this,!1),Nn.set(this,void 0),Fn.set(this,void 0),Fs.set(this,void 0),Ln.set(this,s=>{if(R(this,Mn,!0,"f"),Be(s)&&(s=new ae),s instanceof ae)return R(this,$n,!0,"f"),this._emit("abort",s);if(s instanceof $)return this._emit("error",s);if(s instanceof Error){let n=new $(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new $(String(s)))}),R(this,Ts,new Promise((s,n)=>{R(this,Tn,s,"f"),R(this,Os,n,"f")}),"f"),R(this,Ms,new Promise((s,n)=>{R(this,On,s,"f"),R(this,$s,n,"f")}),"f"),g(this,Ts,"f").catch(()=>{}),g(this,Ms,"f").catch(()=>{}),R(this,xr,e,"f"),R(this,Fs,t?.logger??console,"f")}get response(){return g(this,Nn,"f")}get request_id(){return g(this,Fn,"f")}async withResponse(){R(this,Ct,!0,"f");let e=await g(this,Ts,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,s,{logger:n}={}){let o=new r(t,{logger:n});for(let a of t.messages)o._addMessageParam(a);return R(o,xr,{...t,stream:!0},"f"),o._run(()=>o._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},g(this,Ln,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){let n=s?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{g(this,Ae,"m",Do).call(this);let{response:a,data:c}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)g(this,Ae,"m",Uo).call(this,l);if(c.controller.signal?.aborted)throw new ae;g(this,Ae,"m",jo).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(R(this,Nn,e,"f"),R(this,Fn,e?.headers.get("request-id"),"f"),g(this,Tn,"f").call(this,e),this._emit("connect"))}get ended(){return g(this,Ns,"f")}get errored(){return g(this,Mn,"f")}get aborted(){return g(this,$n,"f")}abort(){this.controller.abort()}on(e,t){return(g(this,Ge,"f")[e]||(g(this,Ge,"f")[e]=[])).push({listener:t}),this}off(e,t){let s=g(this,Ge,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(g(this,Ge,"f")[e]||(g(this,Ge,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{R(this,Ct,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){R(this,Ct,!0,"f"),await g(this,Ms,"f")}get currentMessage(){return g(this,ot,"f")}async finalMessage(){return await this.done(),g(this,Ae,"m",Lo).call(this)}async finalText(){return await this.done(),g(this,Ae,"m",ma).call(this)}_emit(e,...t){if(g(this,Ns,"f"))return;e==="end"&&(R(this,Ns,!0,"f"),g(this,On,"f").call(this));let s=g(this,Ge,"f")[e];if(s&&(g(this,Ge,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!g(this,Ct,"f")&&!s?.length&&Promise.reject(n),g(this,Os,"f").call(this,n),g(this,$s,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!g(this,Ct,"f")&&!s?.length&&Promise.reject(n),g(this,Os,"f").call(this,n),g(this,$s,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",g(this,Ae,"m",Lo).call(this))}async _fromReadableStream(e,t){let s=t?.signal,n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{g(this,Ae,"m",Do).call(this),this._connected(null);let o=Me.fromReadableStream(e,this.controller);for await(let a of o)g(this,Ae,"m",Uo).call(this,a);if(o.controller.signal?.aborted)throw new ae;g(this,Ae,"m",jo).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(ot=new WeakMap,xr=new WeakMap,Ts=new WeakMap,Tn=new WeakMap,Os=new WeakMap,Ms=new WeakMap,On=new WeakMap,$s=new WeakMap,Ge=new WeakMap,Ns=new WeakMap,Mn=new WeakMap,$n=new WeakMap,Ct=new WeakMap,Nn=new WeakMap,Fn=new WeakMap,Fs=new WeakMap,Ln=new WeakMap,Ae=new WeakSet,Lo=i(function(){if(this.receivedMessages.length===0)throw new $("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage"),ma=i(function(){if(this.receivedMessages.length===0)throw new $("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(t.length===0)throw new $("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText"),Do=i(function(){this.ended||R(this,ot,void 0,"f")},"_BetaMessageStream_beginRequest"),Uo=i(function(t){if(this.ended)return;let s=g(this,Ae,"m",ga).call(this,t);switch(this._emit("streamEvent",t,s),t.type){case"content_block_delta":{let n=s.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{ya(n)&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(No(s,g(this,xr,"f"),{logger:g(this,Fs,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{R(this,ot,s,"f");break}case"content_block_start":case"message_delta":break}},"_BetaMessageStream_addStreamEvent"),jo=i(function(){if(this.ended)throw new $("stream has ended, this shouldn't happen");let t=g(this,ot,"f");if(!t)throw new $("request ended without sending any chunks");return R(this,ot,void 0,"f"),No(t,g(this,xr,"f"),{logger:g(this,Fs,"f")})},"_BetaMessageStream_endRequest"),ga=i(function(t){let s=g(this,ot,"f");if(t.type==="message_start"){if(s)throw new $(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!s)throw new $(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return s;case"message_delta":return s.container=t.delta.container,s.stop_reason=t.delta.stop_reason,s.stop_sequence=t.delta.stop_sequence,s.usage.output_tokens=t.usage.output_tokens,s.context_management=t.context_management,t.usage.input_tokens!=null&&(s.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(s.usage.server_tool_use=t.usage.server_tool_use),s;case"content_block_start":return s.content.push(t.content_block),s;case"content_block_delta":{let n=s.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(s.content[t.index]={...n,text:(n.text||"")+t.delta.text});break}case"citations_delta":{n?.type==="text"&&(s.content[t.index]={...n,citations:[...n.citations??[],t.delta.citation]});break}case"input_json_delta":{if(n&&ya(n)){let o=n[_a]||"";o+=t.delta.partial_json;let a={...n};if(Object.defineProperty(a,_a,{value:o,enumerable:!1,writable:!0}),o)try{a.input=Cn(o)}catch(c){let l=new $(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${o}`);g(this,Ln,"f").call(this,l)}s.content[t.index]=a}break}case"thinking_delta":{n?.type==="thinking"&&(s.content[t.index]={...n,thinking:n.thinking+t.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(s.content[t.index]={...n,signature:t.delta.signature});break}default:t.delta}return s}case"content_block_stop":return s}},"_BetaMessageStream_accumulateMessage"),Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:i(async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),"next"),return:i(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Me(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var wa=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
27
|
+
1. Task Overview
|
|
28
|
+
The user's core request and success criteria
|
|
29
|
+
Any clarifications or constraints they specified
|
|
30
|
+
2. Current State
|
|
31
|
+
What has been completed so far
|
|
32
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
33
|
+
Key outputs or artifacts produced
|
|
34
|
+
3. Important Discoveries
|
|
35
|
+
Technical constraints or requirements uncovered
|
|
36
|
+
Decisions made and their rationale
|
|
37
|
+
Errors encountered and how they were resolved
|
|
38
|
+
What approaches were tried that didn't work (and why)
|
|
39
|
+
4. Next Steps
|
|
40
|
+
Specific actions needed to complete the task
|
|
41
|
+
Any blockers or open questions to resolve
|
|
42
|
+
Priority order if multiple steps remain
|
|
43
|
+
5. Context to Preserve
|
|
44
|
+
User preferences or style requirements
|
|
45
|
+
Domain-specific details that aren't obvious
|
|
46
|
+
Any promises made to the user
|
|
47
|
+
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
48
|
+
Wrap your summary in <summary></summary> tags.`;var Ls,kr,Tt,Z,Ds,ge,Je,it,Us,ba,qo;function xa(){let r,e;return{promise:new Promise((s,n)=>{r=s,e=n}),resolve:r,reject:e}}i(xa,"promiseWithResolvers");var Ar=class{static{i(this,"BetaToolRunner")}constructor(e,t,s){Ls.add(this),this.client=e,kr.set(this,!1),Tt.set(this,!1),Z.set(this,void 0),Ds.set(this,void 0),ge.set(this,void 0),Je.set(this,void 0),it.set(this,void 0),Us.set(this,0),R(this,Z,{params:{...t,messages:structuredClone(t.messages)}},"f"),R(this,Ds,{...s,headers:j([{"x-stainless-helper":"BetaToolRunner"},s?.headers])},"f"),R(this,it,xa(),"f")}async*[(kr=new WeakMap,Tt=new WeakMap,Z=new WeakMap,Ds=new WeakMap,ge=new WeakMap,Je=new WeakMap,it=new WeakMap,Us=new WeakMap,Ls=new WeakSet,ba=i(async function(){let t=g(this,Z,"f").params.compactionControl;if(!t||!t.enabled)return!1;let s=0;if(g(this,ge,"f")!==void 0)try{let u=await g(this,ge,"f");s=u.usage.input_tokens+(u.usage.cache_creation_input_tokens??0)+(u.usage.cache_read_input_tokens??0)+u.usage.output_tokens}catch{return!1}let n=t.contextTokenThreshold??1e5;if(s<n)return!1;let o=t.model??g(this,Z,"f").params.model,a=t.summaryPrompt??wa,c=g(this,Z,"f").params.messages;if(c[c.length-1].role==="assistant"){let u=c[c.length-1];if(Array.isArray(u.content)){let f=u.content.filter(d=>d.type!=="tool_use");f.length===0?c.pop():u.content=f}}let l=await this.client.beta.messages.create({model:o,messages:[...c,{role:"user",content:[{type:"text",text:a}]}],max_tokens:g(this,Z,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(l.content[0]?.type!=="text")throw new $("Expected text response for compaction");return g(this,Z,"f").params.messages=[{role:"user",content:l.content}],!0},"_BetaToolRunner_checkAndCompact"),Symbol.asyncIterator)](){var e;if(g(this,kr,"f"))throw new $("Cannot iterate over a consumed stream");R(this,kr,!0,"f"),R(this,Tt,!0,"f"),R(this,Je,void 0,"f");try{for(;;){let t;try{if(g(this,Z,"f").params.max_iterations&&g(this,Us,"f")>=g(this,Z,"f").params.max_iterations)break;R(this,Tt,!1,"f"),R(this,Je,void 0,"f"),R(this,Us,(e=g(this,Us,"f"),e++,e),"f"),R(this,ge,void 0,"f");let{max_iterations:s,compactionControl:n,...o}=g(this,Z,"f").params;if(o.stream?(t=this.client.beta.messages.stream({...o},g(this,Ds,"f")),R(this,ge,t.finalMessage(),"f"),g(this,ge,"f").catch(()=>{}),yield t):(R(this,ge,this.client.beta.messages.create({...o,stream:!1},g(this,Ds,"f")),"f"),yield g(this,ge,"f")),!await g(this,Ls,"m",ba).call(this)){if(!g(this,Tt,"f")){let{role:l,content:u}=await g(this,ge,"f");g(this,Z,"f").params.messages.push({role:l,content:u})}let c=await g(this,Ls,"m",qo).call(this,g(this,Z,"f").params.messages.at(-1));if(c)g(this,Z,"f").params.messages.push(c);else if(!g(this,Tt,"f"))break}}finally{t&&t.abort()}}if(!g(this,ge,"f"))throw new $("ToolRunner concluded without a message from the server");g(this,it,"f").resolve(await g(this,ge,"f"))}catch(t){throw R(this,kr,!1,"f"),g(this,it,"f").promise.catch(()=>{}),g(this,it,"f").reject(t),R(this,it,xa(),"f"),t}}setMessagesParams(e){typeof e=="function"?g(this,Z,"f").params=e(g(this,Z,"f").params):g(this,Z,"f").params=e,R(this,Tt,!0,"f"),R(this,Je,void 0,"f")}async generateToolResponse(){let e=await g(this,ge,"f")??this.params.messages.at(-1);return e?g(this,Ls,"m",qo).call(this,e):null}done(){return g(this,it,"f").promise}async runUntilDone(){if(!g(this,kr,"f"))for await(let e of this);return this.done()}get params(){return g(this,Z,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};qo=i(async function(e){return g(this,Je,"f")!==void 0?g(this,Je,"f"):(R(this,Je,zl(g(this,Z,"f").params,e),"f"),g(this,Je,"f"))},"_BetaToolRunner_generateToolResponse");async function zl(r,e=r.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let t=e.content.filter(n=>n.type==="tool_use");return t.length===0?null:{role:"user",content:await Promise.all(t.map(async n=>{let o=r.tools.find(a=>("name"in a?a.name:a.mcp_server_name)===n.name);if(!o||!("run"in o))return{type:"tool_result",tool_use_id:n.id,content:`Error: Tool '${n.name}' not found`,is_error:!0};try{let a=n.input;"parse"in o&&o.parse&&(a=o.parse(a));let c=await o.run(a);return{type:"tool_result",tool_use_id:n.id,content:c}}catch(a){return{type:"tool_result",tool_use_id:n.id,content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}i(zl,"generateToolResponse");var Sr=class r{static{i(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new We;for await(let t of this.iterator)for(let s of e.decode(t))yield JSON.parse(s);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new $("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new $("Attempted to iterate over a response with no body");return new r(Ss(e.body),t)}};var Ir=class extends J{static{i(this,"Batches")}create(e,t){let{betas:s,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:j([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},s){let{betas:n}=t??{};return this._client.get(K`/v1/messages/batches/${e}?beta=true`,{...s,headers:j([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}list(e={},t){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",ke,{query:n,...t,headers:j([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},s){let{betas:n}=t??{};return this._client.delete(K`/v1/messages/batches/${e}?beta=true`,{...s,headers:j([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}cancel(e,t={},s){let{betas:n}=t??{};return this._client.post(K`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:j([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}async results(e,t={},s){let n=await this.retrieve(e);if(!n.results_url)throw new $(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t??{};return this._client.get(n.results_url,{...s,headers:j([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,c)=>Sr.fromResponse(c.response,c.controller))}};var ka={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},at=class extends J{static{i(this,"Messages")}constructor(){super(...arguments),this.batches=new Ir(this._client)}create(e,t){let{betas:s,...n}=e;n.model in ka&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${ka[n.model]}
|
|
49
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let o=this._client._options.timeout;if(!n.stream&&o==null){let a=En[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,a)}return this._client.post("/v1/messages?beta=true",{body:n,timeout:o??6e5,...t,headers:j([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}parse(e,t){return t={...t,headers:j([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-11-13"].toString()},t?.headers])},this.create(e,t).then(s=>Fo(s,e,{logger:this._client.logger??console}))}stream(e,t){return Dn.createMessage(this,e,t)}countTokens(e,t){let{betas:s,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:j([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new Ar(this._client,e,t)}};at.Batches=Ir;at.BetaToolRunner=Ar;var vr=class extends J{static{i(this,"Versions")}create(e,t={},s){let{betas:n,...o}=t??{};return this._client.post(K`/v1/skills/${e}/versions?beta=true`,_r({body:o,...s,headers:j([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])},this._client))}retrieve(e,t,s){let{skill_id:n,betas:o}=t;return this._client.get(K`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:j([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e,t={},s){let{betas:n,...o}=t??{};return this._client.getAPIList(K`/v1/skills/${e}/versions?beta=true`,gr,{query:o,...s,headers:j([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}delete(e,t,s){let{skill_id:n,betas:o}=t;return this._client.delete(K`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:j([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}};var Ot=class extends J{static{i(this,"Skills")}constructor(){super(...arguments),this.versions=new vr(this._client)}create(e={},t){let{betas:s,...n}=e??{};return this._client.post("/v1/skills?beta=true",_r({body:n,...t,headers:j([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},t?.headers])},this._client))}retrieve(e,t={},s){let{betas:n}=t??{};return this._client.get(K`/v1/skills/${e}?beta=true`,{...s,headers:j([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e={},t){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/skills?beta=true",gr,{query:n,...t,headers:j([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},s){let{betas:n}=t??{};return this._client.delete(K`/v1/skills/${e}?beta=true`,{...s,headers:j([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}};Ot.Versions=vr;var ve=class extends J{static{i(this,"Beta")}constructor(){super(...arguments),this.models=new wr(this._client),this.messages=new at(this._client),this.files=new yr(this._client),this.skills=new Ot(this._client)}};ve.Models=wr;ve.Messages=at;ve.Files=yr;ve.Skills=Ot;var Mt=class extends J{static{i(this,"Completions")}create(e,t){let{betas:s,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:this._client._options.timeout??6e5,...t,headers:j([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}};var Se,ct,js,Un,qs,Bs,jn,Ws,Ke,Hs,qn,Bn,$t,Wn,Hn,Bo,Aa,Wo,Ho,Go,Jo,Sa,Ia="__json_buf";function va(r){return r.type==="tool_use"||r.type==="server_tool_use"}i(va,"tracksToolInput");var Gn=class r{static{i(this,"MessageStream")}constructor(){Se.add(this),this.messages=[],this.receivedMessages=[],ct.set(this,void 0),this.controller=new AbortController,js.set(this,void 0),Un.set(this,()=>{}),qs.set(this,()=>{}),Bs.set(this,void 0),jn.set(this,()=>{}),Ws.set(this,()=>{}),Ke.set(this,{}),Hs.set(this,!1),qn.set(this,!1),Bn.set(this,!1),$t.set(this,!1),Wn.set(this,void 0),Hn.set(this,void 0),Wo.set(this,e=>{if(R(this,qn,!0,"f"),Be(e)&&(e=new ae),e instanceof ae)return R(this,Bn,!0,"f"),this._emit("abort",e);if(e instanceof $)return this._emit("error",e);if(e instanceof Error){let t=new $(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new $(String(e)))}),R(this,js,new Promise((e,t)=>{R(this,Un,e,"f"),R(this,qs,t,"f")}),"f"),R(this,Bs,new Promise((e,t)=>{R(this,jn,e,"f"),R(this,Ws,t,"f")}),"f"),g(this,js,"f").catch(()=>{}),g(this,Bs,"f").catch(()=>{})}get response(){return g(this,Wn,"f")}get request_id(){return g(this,Hn,"f")}async withResponse(){R(this,$t,!0,"f");let e=await g(this,js,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,s){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},g(this,Wo,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){let n=s?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{g(this,Se,"m",Ho).call(this);let{response:a,data:c}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)g(this,Se,"m",Go).call(this,l);if(c.controller.signal?.aborted)throw new ae;g(this,Se,"m",Jo).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(R(this,Wn,e,"f"),R(this,Hn,e?.headers.get("request-id"),"f"),g(this,Un,"f").call(this,e),this._emit("connect"))}get ended(){return g(this,Hs,"f")}get errored(){return g(this,qn,"f")}get aborted(){return g(this,Bn,"f")}abort(){this.controller.abort()}on(e,t){return(g(this,Ke,"f")[e]||(g(this,Ke,"f")[e]=[])).push({listener:t}),this}off(e,t){let s=g(this,Ke,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(g(this,Ke,"f")[e]||(g(this,Ke,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{R(this,$t,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){R(this,$t,!0,"f"),await g(this,Bs,"f")}get currentMessage(){return g(this,ct,"f")}async finalMessage(){return await this.done(),g(this,Se,"m",Bo).call(this)}async finalText(){return await this.done(),g(this,Se,"m",Aa).call(this)}_emit(e,...t){if(g(this,Hs,"f"))return;e==="end"&&(R(this,Hs,!0,"f"),g(this,jn,"f").call(this));let s=g(this,Ke,"f")[e];if(s&&(g(this,Ke,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!g(this,$t,"f")&&!s?.length&&Promise.reject(n),g(this,qs,"f").call(this,n),g(this,Ws,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!g(this,$t,"f")&&!s?.length&&Promise.reject(n),g(this,qs,"f").call(this,n),g(this,Ws,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",g(this,Se,"m",Bo).call(this))}async _fromReadableStream(e,t){let s=t?.signal,n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{g(this,Se,"m",Ho).call(this),this._connected(null);let o=Me.fromReadableStream(e,this.controller);for await(let a of o)g(this,Se,"m",Go).call(this,a);if(o.controller.signal?.aborted)throw new ae;g(this,Se,"m",Jo).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(ct=new WeakMap,js=new WeakMap,Un=new WeakMap,qs=new WeakMap,Bs=new WeakMap,jn=new WeakMap,Ws=new WeakMap,Ke=new WeakMap,Hs=new WeakMap,qn=new WeakMap,Bn=new WeakMap,$t=new WeakMap,Wn=new WeakMap,Hn=new WeakMap,Wo=new WeakMap,Se=new WeakSet,Bo=i(function(){if(this.receivedMessages.length===0)throw new $("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage"),Aa=i(function(){if(this.receivedMessages.length===0)throw new $("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(t.length===0)throw new $("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText"),Ho=i(function(){this.ended||R(this,ct,void 0,"f")},"_MessageStream_beginRequest"),Go=i(function(t){if(this.ended)return;let s=g(this,Se,"m",Sa).call(this,t);switch(this._emit("streamEvent",t,s),t.type){case"content_block_delta":{let n=s.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{va(n)&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(s,!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{R(this,ct,s,"f");break}case"content_block_start":case"message_delta":break}},"_MessageStream_addStreamEvent"),Jo=i(function(){if(this.ended)throw new $("stream has ended, this shouldn't happen");let t=g(this,ct,"f");if(!t)throw new $("request ended without sending any chunks");return R(this,ct,void 0,"f"),t},"_MessageStream_endRequest"),Sa=i(function(t){let s=g(this,ct,"f");if(t.type==="message_start"){if(s)throw new $(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!s)throw new $(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return s;case"message_delta":return s.stop_reason=t.delta.stop_reason,s.stop_sequence=t.delta.stop_sequence,s.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(s.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(s.usage.server_tool_use=t.usage.server_tool_use),s;case"content_block_start":return s.content.push({...t.content_block}),s;case"content_block_delta":{let n=s.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(s.content[t.index]={...n,text:(n.text||"")+t.delta.text});break}case"citations_delta":{n?.type==="text"&&(s.content[t.index]={...n,citations:[...n.citations??[],t.delta.citation]});break}case"input_json_delta":{if(n&&va(n)){let o=n[Ia]||"";o+=t.delta.partial_json;let a={...n};Object.defineProperty(a,Ia,{value:o,enumerable:!1,writable:!0}),o&&(a.input=Cn(o)),s.content[t.index]=a}break}case"thinking_delta":{n?.type==="thinking"&&(s.content[t.index]={...n,thinking:n.thinking+t.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(s.content[t.index]={...n,signature:t.delta.signature});break}default:t.delta}return s}case"content_block_stop":return s}},"_MessageStream_accumulateMessage"),Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:i(async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),"next"),return:i(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Me(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Pr=class extends J{static{i(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(K`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",ke,{query:e,...t})}delete(e,t){return this._client.delete(K`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(K`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let s=await this.retrieve(e);if(!s.results_url)throw new $(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);return this._client.get(s.results_url,{...t,headers:j([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((n,o)=>Sr.fromResponse(o.response,o.controller))}};var lt=class extends J{static{i(this,"Messages")}constructor(){super(...arguments),this.batches=new Pr(this._client)}create(e,t){e.model in Pa&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Pa[e.model]}
|
|
50
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let s=this._client._options.timeout;if(!e.stream&&s==null){let n=En[e.model]??void 0;s=this._client.calculateNonstreamingTimeout(e.max_tokens,n)}return this._client.post("/v1/messages",{body:e,timeout:s??6e5,...t,stream:e.stream??!1})}stream(e,t){return Gn.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Pa={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};lt.Batches=Pr;var Nt=class extends J{static{i(this,"Models")}retrieve(e,t={},s){let{betas:n}=t??{};return this._client.get(K`/v1/models/${e}`,{...s,headers:j([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/models",ke,{query:n,...t,headers:j([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}};var Gs=i(r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()},"readEnv");var Ko,Vo,Jn,Ra,Ea="\\n\\nHuman:",Ca="\\n\\nAssistant:",X=class{static{i(this,"BaseAnthropic")}constructor({baseURL:e=Gs("ANTHROPIC_BASE_URL"),apiKey:t=Gs("ANTHROPIC_API_KEY")??null,authToken:s=Gs("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){Ko.add(this),Jn.set(this,void 0);let o={apiKey:t,authToken:s,...n,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&ea())throw new $(`It looks like you're running in a browser-like environment.
|
|
51
|
+
|
|
52
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
53
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
54
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
55
|
+
|
|
56
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
57
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??Vo.DEFAULT_TIMEOUT,this.logger=o.logger??console;let a="warn";this.logLevel=a,this.logLevel=Ro(o.logLevel,"ClientOptions.logLevel",this)??Ro(Gs("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??ra(),R(this,Jn,na,"f"),this._options=o,this.apiKey=typeof t=="string"?t:null,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return j([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return j([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return j([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,s])=>typeof s<"u").map(([t,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(t)}=`;throw new $(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${nt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ao()}`}makeStatusError(e,t,s,n){return ne.generate(e,t,s,n)}buildURL(e,t,s){let n=!g(this,Ko,"m",Ra).call(this)&&s||this.baseURL,o=Ji(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Ki(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new $("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Rt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:c,timeout:l}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:n});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,d=Date.now();if(oe(this).debug(`[${u}] sending request`,He({retryOfRequestLogID:s,method:n.method,url:c,options:n,headers:a.headers})),n.signal?.aborted)throw new ae;let m=new AbortController,h=await this.fetchWithTimeout(c,a,l,m).catch(As),x=Date.now();if(h instanceof globalThis.Error){let I=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new ae;let b=Be(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return oe(this).info(`[${u}] connection ${b?"timed out":"failed"} - ${I}`),oe(this).debug(`[${u}] connection ${b?"timed out":"failed"} (${I})`,He({retryOfRequestLogID:s,url:c,durationMs:x-d,message:h.message})),this.retryRequest(n,t,s??u);throw oe(this).info(`[${u}] connection ${b?"timed out":"failed"} - error; no more retries left`),oe(this).debug(`[${u}] connection ${b?"timed out":"failed"} (error; no more retries left)`,He({retryOfRequestLogID:s,url:c,durationMs:x-d,message:h.message})),b?new ar:new st({cause:h})}let y=[...h.headers.entries()].filter(([I])=>I==="request-id").map(([I,b])=>", "+I+": "+JSON.stringify(b)).join(""),k=`[${u}${f}${y}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${x-d}ms`;if(!h.ok){let I=await this.shouldRetry(h);if(t&&I){let U=`retrying, ${t} attempts remaining`;return await sa(h.body),oe(this).info(`${k} - ${U}`),oe(this).debug(`[${u}] response error (${U})`,He({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:x-d})),this.retryRequest(n,t,s??u,h.headers)}let b=I?"error; no more retries left":"error; not retryable";oe(this).info(`${k} - ${b}`);let L=await h.text().catch(U=>As(U).message),T=xn(L),W=T?void 0:L;throw oe(this).debug(`[${u}] response error (${b})`,He({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:W,durationMs:Date.now()-d})),this.makeStatusError(h.status,T,W,h.headers)}return oe(this).info(k),oe(this).debug(`[${u}] response start`,He({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:x-d})),{response:h,options:n,controller:m,requestLogID:u,retryOfRequestLogID:s,startTime:d}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){let s=this.makeRequest(t,null,void 0);return new Es(this,s,e)}async fetchWithTimeout(e,t,s,n){let{signal:o,method:a,...c}=t||{};o&&o.addEventListener("abort",()=>n.abort());let l=setTimeout(()=>n.abort(),s),u=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:n.signal,...u?{duplex:"half"}:{},method:"GET",...c};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,n){let o,a=n?.get("retry-after-ms");if(a){let l=parseFloat(a);Number.isNaN(l)||(o=l)}let c=n?.get("retry-after");if(c&&!o){let l=parseFloat(c);Number.isNaN(l)?o=Date.parse(c)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,l)}return await zi(o),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new $("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){let s={...e},{method:n,path:o,query:a,defaultBaseURL:c}=s,l=this.buildURL(o,a,c);"timeout"in s&&Xi("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:u,body:f}=this.buildBody({options:s}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:u,retryCount:t});return{req:{method:n,headers:d,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=j([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ta(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let s=j([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:kn(e)}:g(this,Jn,"f").call(this,{body:e,headers:s})}};Vo=X,Jn=new WeakMap,Ko=new WeakSet,Ra=i(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden");X.Anthropic=Vo;X.HUMAN_PROMPT=Ea;X.AI_PROMPT=Ca;X.DEFAULT_TIMEOUT=6e5;X.AnthropicError=$;X.APIError=ne;X.APIConnectionError=st;X.APIConnectionTimeoutError=ar;X.APIUserAbortError=ae;X.NotFoundError=dr;X.ConflictError=fr;X.RateLimitError=pr;X.BadRequestError=cr;X.AuthenticationError=lr;X.InternalServerError=mr;X.PermissionDeniedError=ur;X.UnprocessableEntityError=hr;X.toFile=Rn;var he=class extends X{static{i(this,"Anthropic")}constructor(){super(...arguments),this.completions=new Mt(this),this.messages=new lt(this),this.models=new Nt(this),this.beta=new ve(this)}};he.Completions=Mt;he.Messages=lt;he.Models=Nt;he.Beta=ve;import*as le from"path";import*as Pt from"fs";function N(r,e,t,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t}i(N,"__classPrivateFieldSet");function p(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)}i(p,"__classPrivateFieldGet");var Xo=i(function(){let{crypto:r}=globalThis;if(r?.randomUUID)return Xo=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))},"uuid4");function Js(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}i(Js,"isAbortError");var Ks=i(r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)},"castToError");var E=class extends Error{static{i(this,"OpenAIError")}},ee=class r extends E{static{i(this,"APIError")}constructor(e,t,s,n){super(`${r.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,s){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new ut({message:s,cause:Ks(t)});let o=t?.error;return e===400?new Rr(e,o,s,n):e===401?new Er(e,o,s,n):e===403?new Cr(e,o,s,n):e===404?new Tr(e,o,s,n):e===409?new Or(e,o,s,n):e===422?new Mr(e,o,s,n):e===429?new $r(e,o,s,n):e>=500?new Nr(e,o,s,n):new r(e,o,s,n)}},Y=class extends ee{static{i(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ut=class extends ee{static{i(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},dt=class extends ut{static{i(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},Rr=class extends ee{static{i(this,"BadRequestError")}},Er=class extends ee{static{i(this,"AuthenticationError")}},Cr=class extends ee{static{i(this,"PermissionDeniedError")}},Tr=class extends ee{static{i(this,"NotFoundError")}},Or=class extends ee{static{i(this,"ConflictError")}},Mr=class extends ee{static{i(this,"UnprocessableEntityError")}},$r=class extends ee{static{i(this,"RateLimitError")}},Nr=class extends ee{static{i(this,"InternalServerError")}},Fr=class extends E{static{i(this,"LengthFinishReasonError")}constructor(){super("Could not parse response content as the length limit was reached")}},Lr=class extends E{static{i(this,"ContentFilterFinishReasonError")}constructor(){super("Could not parse response content as the request was rejected by the content filter")}},$e=class extends Error{static{i(this,"InvalidWebhookSignatureError")}constructor(e){super(e)}};var nu=/^[a-z][a-z0-9+.-]*:/i,Ta=i(r=>nu.test(r),"isAbsoluteURL"),ue=i(r=>(ue=Array.isArray,ue(r)),"isArray"),zo=ue;function Yo(r){return typeof r!="object"?{}:r??{}}i(Yo,"maybeObj");function Qo(r){if(!r)return!0;for(let e in r)return!1;return!0}i(Qo,"isEmptyObj");function Oa(r,e){return Object.prototype.hasOwnProperty.call(r,e)}i(Oa,"hasOwn");function Vs(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}i(Vs,"isObj");var Ma=i((r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new E(`${r} must be an integer`);if(e<0)throw new E(`${r} must be a positive integer`);return e},"validatePositiveInteger");var $a=i(r=>{try{return JSON.parse(r)}catch{return}},"safeJSON");var Ne=i(r=>new Promise(e=>setTimeout(e,r)),"sleep");var ft="6.33.0";var Da=i(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function ou(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}i(ou,"getDetectedPlatform");var iu=i(()=>{let r=ou();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":Fa(Deno.build.os),"X-Stainless-Arch":Na(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":Fa(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Na(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=au();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function au(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let s=t.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}i(au,"getBrowserInfo");var Na=i(r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown","normalizeArch"),Fa=i(r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),"normalizePlatform"),La,Ua=i(()=>La??(La=iu()),"getPlatformHeaders");function ja(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}i(ja,"getDefaultFetch");function Zo(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}i(Zo,"makeReadableStream");function Kn(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Zo({start(){},async pull(t){let{done:s,value:n}=await e.next();s?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}i(Kn,"ReadableStreamFrom");function ei(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}i(ei,"ReadableStreamToAsyncIterable");async function qa(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}i(qa,"CancelReadableStream");var Ba=i(({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ti="RFC3986",ri=i(r=>String(r),"default_formatter"),si={RFC1738:i(r=>String(r).replace(/%20/g,"+"),"RFC1738"),RFC3986:ri},Wa="RFC1738";var Vn=i((r,e)=>(Vn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Vn(r,e)),"has"),Fe=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var ni=1024,Ha=i((r,e,t,s,n)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<o.length;c+=ni){let l=o.length>=ni?o.slice(c,c+ni):o,u=[];for(let f=0;f<l.length;++f){let d=l.charCodeAt(f);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===Wa&&(d===40||d===41)){u[u.length]=l.charAt(f);continue}if(d<128){u[u.length]=Fe[d];continue}if(d<2048){u[u.length]=Fe[192|d>>6]+Fe[128|d&63];continue}if(d<55296||d>=57344){u[u.length]=Fe[224|d>>12]+Fe[128|d>>6&63]+Fe[128|d&63];continue}f+=1,d=65536+((d&1023)<<10|l.charCodeAt(f)&1023),u[u.length]=Fe[240|d>>18]+Fe[128|d>>12&63]+Fe[128|d>>6&63]+Fe[128|d&63]}a+=u.join("")}return a},"encode");function Ga(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}i(Ga,"is_buffer");function oi(r,e){if(ue(r)){let t=[];for(let s=0;s<r.length;s+=1)t.push(e(r[s]));return t}return e(r)}i(oi,"maybe_map");var Ka={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Va=i(function(r,e){Array.prototype.push.apply(r,ue(e)?e:[e])},"push_to_array"),Ja,te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ha,encodeValuesOnly:!1,format:ti,formatter:ri,indices:!1,serializeDate(r){return(Ja??(Ja=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function uu(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}i(uu,"is_non_nullish_primitive");var ii={};function Xa(r,e,t,s,n,o,a,c,l,u,f,d,m,h,x,y,k,I){let b=r,L=I,T=0,W=!1;for(;(L=L.get(ii))!==void 0&&!W;){let v=L.get(r);if(T+=1,typeof v<"u"){if(v===T)throw new RangeError("Cyclic object value");W=!0}typeof L.get(ii)>"u"&&(T=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=m?.(b):t==="comma"&&ue(b)&&(b=oi(b,function(v){return v instanceof Date?m?.(v):v})),b===null){if(o)return l&&!y?l(e,te.encoder,k,"key",h):e;b=""}if(uu(b)||Ga(b)){if(l){let v=y?e:l(e,te.encoder,k,"key",h);return[x?.(v)+"="+x?.(l(b,te.encoder,k,"value",h))]}return[x?.(e)+"="+x?.(String(b))]}let B=[];if(typeof b>"u")return B;let U;if(t==="comma"&&ue(b))y&&l&&(b=oi(b,l)),U=[{value:b.length>0?b.join(",")||null:void 0}];else if(ue(u))U=u;else{let v=Object.keys(b);U=f?v.sort(f):v}let H=c?String(e).replace(/\./g,"%2E"):String(e),M=s&&ue(b)&&b.length===1?H+"[]":H;if(n&&ue(b)&&b.length===0)return M+"[]";for(let v=0;v<U.length;++v){let D=U[v],O=typeof D=="object"&&typeof D.value<"u"?D.value:b[D];if(a&&O===null)continue;let C=d&&c?D.replace(/\./g,"%2E"):D,G=ue(b)?typeof t=="function"?t(M,C):M:M+(d?"."+C:"["+C+"]");I.set(r,T);let Q=new WeakMap;Q.set(ii,I),Va(B,Xa(O,G,t,s,n,o,a,c,t==="comma"&&y&&ue(b)?null:l,u,f,d,m,h,x,y,k,Q))}return B}i(Xa,"inner_stringify");function du(r=te){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||te.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=ti;if(typeof r.format<"u"){if(!Vn(si,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let s=si[t],n=te.filter;(typeof r.filter=="function"||ue(r.filter))&&(n=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in Ka?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=te.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:te.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:te.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:te.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:te.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?te.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:te.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:te.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:te.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:te.encodeValuesOnly,filter:n,format:t,formatter:s,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:te.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:te.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:te.strictNullHandling}}i(du,"normalize_stringify_options");function za(r,e={}){let t=r,s=du(e),n,o;typeof s.filter=="function"?(o=s.filter,t=o("",t)):ue(s.filter)&&(o=s.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let c=Ka[s.arrayFormat],l=c==="comma"&&s.commaRoundTrip;n||(n=Object.keys(t)),s.sort&&n.sort(s.sort);let u=new WeakMap;for(let m=0;m<n.length;++m){let h=n[m];s.skipNulls&&t[h]===null||Va(a,Xa(t[h],h,c,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,u))}let f=a.join(s.delimiter),d=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),f.length>0?d+f:""}i(za,"stringify");function Ya(r){return za(r,{arrayFormat:"brackets"})}i(Ya,"stringifyQuery");function ec(r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return t}i(ec,"concatBytes");var Qa;function Dr(r){let e;return(Qa??(e=new globalThis.TextEncoder,Qa=e.encode.bind(e)))(r)}i(Dr,"encodeUTF8");var Za;function ai(r){let e;return(Za??(e=new globalThis.TextDecoder,Za=e.decode.bind(e)))(r)}i(ai,"decodeUTF8");var _e,ye,Ft=class{static{i(this,"LineDecoder")}constructor(){_e.set(this,void 0),ye.set(this,void 0),N(this,_e,new Uint8Array,"f"),N(this,ye,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Dr(e):e;N(this,_e,ec([p(this,_e,"f"),t]),"f");let s=[],n;for(;(n=hu(p(this,_e,"f"),p(this,ye,"f")))!=null;){if(n.carriage&&p(this,ye,"f")==null){N(this,ye,n.index,"f");continue}if(p(this,ye,"f")!=null&&(n.index!==p(this,ye,"f")+1||n.carriage)){s.push(ai(p(this,_e,"f").subarray(0,p(this,ye,"f")-1))),N(this,_e,p(this,_e,"f").subarray(p(this,ye,"f")),"f"),N(this,ye,null,"f");continue}let o=p(this,ye,"f")!==null?n.preceding-1:n.preceding,a=ai(p(this,_e,"f").subarray(0,o));s.push(a),N(this,_e,p(this,_e,"f").subarray(n.index),"f"),N(this,ye,null,"f")}return s}flush(){return p(this,_e,"f").length?this.decode(`
|
|
58
|
+
`):[]}};_e=new WeakMap,ye=new WeakMap;Ft.NEWLINE_CHARS=new Set([`
|
|
59
|
+
`,"\r"]);Ft.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function hu(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}i(hu,"findNewlineIndex");function tc(r){for(let s=0;s<r.length-1;s++){if(r[s]===10&&r[s+1]===10||r[s]===13&&r[s+1]===13)return s+2;if(r[s]===13&&r[s+1]===10&&s+3<r.length&&r[s+2]===13&&r[s+3]===10)return s+4}return-1}i(tc,"findDoubleNewlineIndex");var zn={off:0,error:200,warn:300,info:400,debug:500},ci=i((r,e,t)=>{if(r){if(Oa(zn,r))return r;z(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(zn))}`)}},"parseLogLevel");function Xs(){}i(Xs,"noop");function Xn(r,e,t){return!e||zn[r]>zn[t]?Xs:e[r].bind(e)}i(Xn,"makeLogFn");var pu={error:Xs,warn:Xs,info:Xs,debug:Xs},rc=new WeakMap;function z(r){let e=r.logger,t=r.logLevel??"off";if(!e)return pu;let s=rc.get(e);if(s&&s[0]===t)return s[1];let n={error:Xn("error",e,t),warn:Xn("warn",e,t),info:Xn("info",e,t),debug:Xn("debug",e,t)};return rc.set(e,[t,n]),n}i(z,"loggerFor");var Ve=i(r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r),"formatRequestDetails");var zs,Le=class r{static{i(this,"Stream")}constructor(e,t,s){this.iterator=e,zs.set(this,void 0),this.controller=t,N(this,zs,s,"f")}static fromSSEResponse(e,t,s,n){let o=!1,a=s?z(s):console;async function*c(){if(o)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(let u of mu(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let f;try{f=JSON.parse(u.data)}catch(d){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),d}if(f&&f.error)throw new ee(void 0,f.error,void 0,e.headers);yield n?{event:u.event,data:f}:f}else{let f;try{f=JSON.parse(u.data)}catch(d){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),d}if(u.event=="error")throw new ee(void 0,f.error,f.message,void 0);yield{event:u.event,data:f}}}l=!0}catch(u){if(Js(u))return;throw u}finally{l||t.abort()}}return i(c,"iterator"),new r(c,t,s)}static fromReadableStream(e,t,s){let n=!1;async function*o(){let c=new Ft,l=ei(e);for await(let u of l)for(let f of c.decode(u))yield f;for(let u of c.flush())yield u}i(o,"iterLines");async function*a(){if(n)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let l of o())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(Js(l))return;throw l}finally{c||t.abort()}}return i(a,"iterator"),new r(a,t,s)}[(zs=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],s=this.iterator(),n=i(o=>({next:i(()=>{if(o.length===0){let a=s.next();e.push(a),t.push(a)}return o.shift()},"next")}),"teeIterator");return[new r(()=>n(e),this.controller,p(this,zs,"f")),new r(()=>n(t),this.controller,p(this,zs,"f"))]}toReadableStream(){let e=this,t;return Zo({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:n,done:o}=await t.next();if(o)return s.close();let a=Dr(JSON.stringify(n)+`
|
|
60
|
+
`);s.enqueue(a)}catch(n){s.error(n)}},async cancel(){await t.return?.()}})}};async function*mu(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new E("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new E("Attempted to iterate over a response with no body");let t=new li,s=new Ft,n=ei(r.body);for await(let o of gu(n))for(let a of s.decode(o)){let c=t.decode(a);c&&(yield c)}for(let o of s.flush()){let a=t.decode(o);a&&(yield a)}}i(mu,"_iterSSEMessages");async function*gu(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Dr(t):t,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=tc(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}i(gu,"iterSSEChunks");var li=class{static{i(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
61
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=_u(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function _u(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}i(_u,"partition");async function Yn(r,e){let{response:t,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return z(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData):Le.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let m=await t.json();return ui(m,t)}return await t.text()})();return z(r).debug(`[${s}] response parsed`,Ve({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}i(Yn,"defaultParseResponse");function ui(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}i(ui,"addRequestID");var Ys,Lt=class r extends Promise{static{i(this,"APIPromise")}constructor(e,t,s=Yn){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=s,Ys.set(this,void 0),N(this,Ys,e,"f")}_thenUnwrap(e){return new r(p(this,Ys,"f"),this.responsePromise,async(t,s)=>ui(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(p(this,Ys,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Ys=new WeakMap;var Qn,Qs=class{static{i(this,"AbstractPage")}constructor(e,t,s,n){Qn.set(this,void 0),N(this,Qn,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new E("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await p(this,Qn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Qn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Zs=class extends Lt{static{i(this,"PagePromise")}constructor(e,t,s){super(e,t,async(n,o)=>new s(n,o.response,await Yn(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},De=class extends Qs{static{i(this,"Page")}constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},q=class extends Qs{static{i(this,"CursorPage")}constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Yo(this.options.query),after:t}}:null}},Pe=class extends Qs{static{i(this,"ConversationCursorPage")}constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Yo(this.options.query),after:e}}:null}};var hi=i(()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function Ur(r,e,t){return hi(),new File(r,e??"unknown_file",t)}i(Ur,"makeFile");function en(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}i(en,"getName");var Zn=i(r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function","isAsyncIterable"),ht=i(async(r,e)=>di(r.body)?{...r,body:await nc(r.body,e)}:r,"maybeMultipartFormRequestOptions"),de=i(async(r,e)=>({...r,body:await nc(r.body,e)}),"multipartFormRequestOptions"),sc=new WeakMap;function wu(r){let e=typeof r=="function"?r:r.fetch,t=sc.get(e);if(t)return t;let s=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return sc.set(e,s),s}i(wu,"supportsFormData");var nc=i(async(r,e)=>{if(!await wu(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([s,n])=>fi(t,s,n))),t},"createForm"),oc=i(r=>r instanceof Blob&&"name"in r,"isNamedBlob"),bu=i(r=>typeof r=="object"&&r!==null&&(r instanceof Response||Zn(r)||oc(r)),"isUploadable"),di=i(r=>{if(bu(r))return!0;if(Array.isArray(r))return r.some(di);if(r&&typeof r=="object"){for(let e in r)if(di(r[e]))return!0}return!1},"hasUploadableValue"),fi=i(async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,Ur([await t.blob()],en(t)));else if(Zn(t))r.append(e,Ur([await new Response(Kn(t)).blob()],en(t)));else if(oc(t))r.append(e,t,en(t));else if(Array.isArray(t))await Promise.all(t.map(s=>fi(r,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,n])=>fi(r,`${e}[${s}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},"addFormValue");var ic=i(r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function","isBlobLike"),xu=i(r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&ic(r),"isFileLike"),ku=i(r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function","isResponseLike");async function eo(r,e,t){if(hi(),r=await r,xu(r))return r instanceof File?r:Ur([await r.arrayBuffer()],r.name);if(ku(r)){let n=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),Ur(await pi(n),e,t)}let s=await pi(r);if(e||(e=en(r)),!t?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Ur(s,e,t)}i(eo,"toFile");async function pi(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(ic(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Zn(r))for await(let t of r)e.push(...await pi(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Au(r)}`)}return e}i(pi,"getBytes");function Au(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}i(Au,"propsForError");var w=class{static{i(this,"APIResource")}constructor(e){this._client=e}};function cc(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}i(cc,"encodeURIPath");var ac=Object.freeze(Object.create(null)),Iu=i((r=cc)=>i(function(t,...s){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((f,d,m)=>{/[?#]/.test(d)&&(n=!0);let h=s[m],x=(n?encodeURIComponent:r)(""+h);return m!==s.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??ac)??ac)?.toString)&&(x=h+"",o.push({start:f.length+d.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),f+d+(m===s.length?"":x)},""),c=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=l.exec(c))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((f,d)=>f.start-d.start),o.length>0){let f=0,d=o.reduce((m,h)=>{let x=" ".repeat(h.start-f),y="^".repeat(h.length);return f=h.start+h.length,m+x+y},"");throw new E(`Path parameters result in path with invalid segments:
|
|
62
|
+
${o.map(m=>m.error).join(`
|
|
63
|
+
`)}
|
|
64
|
+
${a}
|
|
65
|
+
${d}`)}return a},"path"),"createPathTagFunction"),_=Iu(cc);var Dt=class extends w{static{i(this,"Messages")}list(e,t={},s){return this._client.getAPIList(_`/chat/completions/${e}/messages`,q,{query:t,...s})}};function tn(r){return r!==void 0&&"function"in r&&r.function!==void 0}i(tn,"isChatCompletionFunctionTool");function rn(r){return r?.$brand==="auto-parseable-response-format"}i(rn,"isAutoParsableResponseFormat");function Ut(r){return r?.$brand==="auto-parseable-tool"}i(Ut,"isAutoParsableTool");function lc(r,e){return!e||!mi(e)?{...r,choices:r.choices.map(t=>(dc(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:sn(r,e)}i(lc,"maybeParseChatCompletion");function sn(r,e){let t=r.choices.map(s=>{if(s.finish_reason==="length")throw new Fr;if(s.finish_reason==="content_filter")throw new Lr;return dc(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(n=>Eu(e,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Ru(e,s.message.content):null}}});return{...r,choices:t}}i(sn,"parseChatCompletion");function Ru(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}i(Ru,"parseResponseFormat");function Eu(r,e){let t=r.tools?.find(s=>tn(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ut(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}i(Eu,"parseToolCall");function uc(r,e){if(!r||!("tools"in r)||!r.tools)return!1;let t=r.tools?.find(s=>tn(s)&&s.function?.name===e.function.name);return tn(t)&&(Ut(t)||t?.function.strict||!1)}i(uc,"shouldParseToolCall");function mi(r){return rn(r.response_format)?!0:r.tools?.some(e=>Ut(e)||e.type==="function"&&e.function.strict===!0)??!1}i(mi,"hasAutoParseableInput");function dc(r){for(let e of r||[])if(e.type!=="function")throw new E(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}i(dc,"assertToolCallsAreChatCompletionFunctionToolCalls");function fc(r){for(let e of r??[]){if(e.type!=="function")throw new E(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new E(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}i(fc,"validateInputTools");var jr=i(r=>r?.role==="assistant","isAssistantMessage"),gi=i(r=>r?.role==="tool","isToolMessage");var _i,to,ro,nn,on,so,an,Xe,cn,no,oo,qr,hc,pt=class{static{i(this,"EventStream")}constructor(){_i.add(this),this.controller=new AbortController,to.set(this,void 0),ro.set(this,()=>{}),nn.set(this,()=>{}),on.set(this,void 0),so.set(this,()=>{}),an.set(this,()=>{}),Xe.set(this,{}),cn.set(this,!1),no.set(this,!1),oo.set(this,!1),qr.set(this,!1),N(this,to,new Promise((e,t)=>{N(this,ro,e,"f"),N(this,nn,t,"f")}),"f"),N(this,on,new Promise((e,t)=>{N(this,so,e,"f"),N(this,an,t,"f")}),"f"),p(this,to,"f").catch(()=>{}),p(this,on,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},p(this,_i,"m",hc).bind(this))},0)}_connected(){this.ended||(p(this,ro,"f").call(this),this._emit("connect"))}get ended(){return p(this,cn,"f")}get errored(){return p(this,no,"f")}get aborted(){return p(this,oo,"f")}abort(){this.controller.abort()}on(e,t){return(p(this,Xe,"f")[e]||(p(this,Xe,"f")[e]=[])).push({listener:t}),this}off(e,t){let s=p(this,Xe,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(p(this,Xe,"f")[e]||(p(this,Xe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{N(this,qr,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){N(this,qr,!0,"f"),await p(this,on,"f")}_emit(e,...t){if(p(this,cn,"f"))return;e==="end"&&(N(this,cn,!0,"f"),p(this,so,"f").call(this));let s=p(this,Xe,"f")[e];if(s&&(p(this,Xe,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!p(this,qr,"f")&&!s?.length&&Promise.reject(n),p(this,nn,"f").call(this,n),p(this,an,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!p(this,qr,"f")&&!s?.length&&Promise.reject(n),p(this,nn,"f").call(this,n),p(this,an,"f").call(this,n),this._emit("end")}}_emitFinal(){}};to=new WeakMap,ro=new WeakMap,nn=new WeakMap,on=new WeakMap,so=new WeakMap,an=new WeakMap,Xe=new WeakMap,cn=new WeakMap,no=new WeakMap,oo=new WeakMap,qr=new WeakMap,_i=new WeakSet,hc=i(function(e){if(N(this,no,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Y),e instanceof Y)return N(this,oo,!0,"f"),this._emit("abort",e);if(e instanceof E)return this._emit("error",e);if(e instanceof Error){let t=new E(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new E(String(e)))},"_EventStream_handleError");function pc(r){return typeof r.parse=="function"}i(pc,"isRunnableFunctionWithParse");var fe,yi,io,wi,bi,xi,mc,gc,Cu=10,Br=class extends pt{static{i(this,"AbstractChatCompletionRunner")}constructor(){super(...arguments),fe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),gi(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(jr(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new E("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),p(this,fe,"m",yi).call(this)}async finalMessage(){return await this.done(),p(this,fe,"m",io).call(this)}async finalFunctionToolCall(){return await this.done(),p(this,fe,"m",wi).call(this)}async finalFunctionToolCallResult(){return await this.done(),p(this,fe,"m",bi).call(this)}async totalUsage(){return await this.done(),p(this,fe,"m",xi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=p(this,fe,"m",io).call(this);t&&this._emit("finalMessage",t);let s=p(this,fe,"m",yi).call(this);s&&this._emit("finalContent",s);let n=p(this,fe,"m",wi).call(this);n&&this._emit("finalFunctionToolCall",n);let o=p(this,fe,"m",bi).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",p(this,fe,"m",xi).call(this))}async _createChatCompletion(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),p(this,fe,"m",mc).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(sn(o,t))}async _runChatCompletion(e,t,s){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){let n="tool",{tool_choice:o="auto",stream:a,...c}=t,l=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:u=Cu}=s||{},f=t.tools.map(h=>{if(Ut(h)){if(!h.$callback)throw new E("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(let h of f)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);let m="tools"in t?f.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of t.messages)this._addMessage(h,!1);for(let h=0;h<u;++h){let y=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:m,messages:[...this.messages]},s)).choices[0]?.message;if(!y)throw new E("missing message in ChatCompletion response");if(!y.tool_calls?.length)return;for(let k of y.tool_calls){if(k.type!=="function")continue;let I=k.id,{name:b,arguments:L}=k.function,T=d[b];if(T){if(l&&l!==b){let H=`Invalid tool_call: ${JSON.stringify(b)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:n,tool_call_id:I,content:H});continue}}else{let H=`Invalid tool_call: ${JSON.stringify(b)}. Available options are: ${Object.keys(d).map(M=>JSON.stringify(M)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:I,content:H});continue}let W;try{W=pc(T)?await T.parse(L):L}catch(H){let M=H instanceof Error?H.message:String(H);this._addMessage({role:n,tool_call_id:I,content:M});continue}let B=await T.function(W,this),U=p(this,fe,"m",gc).call(this,B);if(this._addMessage({role:n,tool_call_id:I,content:U}),l)return}}}};fe=new WeakSet,yi=i(function(){return p(this,fe,"m",io).call(this).content??null},"_AbstractChatCompletionRunner_getFinalContent"),io=i(function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(jr(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new E("stream ended without producing a ChatCompletionMessage with role=assistant")},"_AbstractChatCompletionRunner_getFinalMessage"),wi=i(function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(jr(t)&&t?.tool_calls?.length)return t.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},"_AbstractChatCompletionRunner_getFinalFunctionToolCall"),bi=i(function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(gi(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},"_AbstractChatCompletionRunner_getFinalFunctionToolCallResult"),xi=i(function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},"_AbstractChatCompletionRunner_calculateTotalUsage"),mc=i(function(e){if(e.n!=null&&e.n>1)throw new E("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},"_AbstractChatCompletionRunner_validateParams"),gc=i(function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)},"_AbstractChatCompletionRunner_stringifyFunctionCallResult");var ln=class r extends Br{static{i(this,"ChatCompletionRunner")}static runTools(e,t,s){let n=new r,o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),jr(e)&&e.content&&this._emit("content",e.content)}};var ie={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},ki=class extends Error{static{i(this,"PartialJSON")}},Ai=class extends Error{static{i(this,"MalformedJSON")}};function Tu(r,e=ie.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Ou(r.trim(),e)}i(Tu,"parseJSON");var Ou=i((r,e)=>{let t=r.length,s=0,n=i(m=>{throw new ki(`${m} at position ${s}`)},"markPartialJSON"),o=i(m=>{throw new Ai(`${m} at position ${s}`)},"throwMalformedError"),a=i(()=>(d(),s>=t&&n("Unexpected end of input"),r[s]==='"'?c():r[s]==="{"?l():r[s]==="["?u():r.substring(s,s+4)==="null"||ie.NULL&e&&t-s<4&&"null".startsWith(r.substring(s))?(s+=4,null):r.substring(s,s+4)==="true"||ie.BOOL&e&&t-s<4&&"true".startsWith(r.substring(s))?(s+=4,!0):r.substring(s,s+5)==="false"||ie.BOOL&e&&t-s<5&&"false".startsWith(r.substring(s))?(s+=5,!1):r.substring(s,s+8)==="Infinity"||ie.INFINITY&e&&t-s<8&&"Infinity".startsWith(r.substring(s))?(s+=8,1/0):r.substring(s,s+9)==="-Infinity"||ie.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(r.substring(s))?(s+=9,-1/0):r.substring(s,s+3)==="NaN"||ie.NAN&e&&t-s<3&&"NaN".startsWith(r.substring(s))?(s+=3,NaN):f()),"parseAny"),c=i(()=>{let m=s,h=!1;for(s++;s<t&&(r[s]!=='"'||h&&r[s-1]==="\\");)h=r[s]==="\\"?!h:!1,s++;if(r.charAt(s)=='"')try{return JSON.parse(r.substring(m,++s-Number(h)))}catch(x){o(String(x))}else if(ie.STR&e)try{return JSON.parse(r.substring(m,s-Number(h))+'"')}catch{return JSON.parse(r.substring(m,r.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},"parseStr"),l=i(()=>{s++,d();let m={};try{for(;r[s]!=="}";){if(d(),s>=t&&ie.OBJ&e)return m;let h=c();d(),s++;try{let x=a();Object.defineProperty(m,h,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(ie.OBJ&e)return m;throw x}d(),r[s]===","&&s++}}catch{if(ie.OBJ&e)return m;n("Expected '}' at end of object")}return s++,m},"parseObj"),u=i(()=>{s++;let m=[];try{for(;r[s]!=="]";)m.push(a()),d(),r[s]===","&&s++}catch{if(ie.ARR&e)return m;n("Expected ']' at end of array")}return s++,m},"parseArr"),f=i(()=>{if(s===0){r==="-"&&ie.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(r)}catch(h){if(ie.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(h))}}let m=s;for(r[s]==="-"&&s++;r[s]&&!",]}".includes(r[s]);)s++;s==t&&!(ie.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(r.substring(m,s))}catch{r.substring(m,s)==="-"&&ie.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(r.substring(m,r.lastIndexOf("e")))}catch(x){o(String(x))}}},"parseNum"),d=i(()=>{for(;s<t&&`
|
|
66
|
+
\r `.includes(r[s]);)s++},"skipBlank");return a()},"_parseJSON"),Si=i(r=>Tu(r,ie.ALL^ie.NUM),"partialParse");var re,ze,Wr,mt,Ii,ao,vi,Pi,Ri,co,Ei,_c,jt=class r extends Br{static{i(this,"ChatCompletionStream")}constructor(e){super(),re.add(this),ze.set(this,void 0),Wr.set(this,void 0),mt.set(this,void 0),N(this,ze,e,"f"),N(this,Wr,[],"f")}get currentChatCompletionSnapshot(){return p(this,mt,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){let n=new r(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,s){super._createChatCompletion;let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),p(this,re,"m",Ii).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(let a of o)p(this,re,"m",vi).call(this,a);if(o.controller.signal?.aborted)throw new Y;return this._addChatCompletion(p(this,re,"m",co).call(this))}async _fromReadableStream(e,t){let s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),p(this,re,"m",Ii).call(this),this._connected();let n=Le.fromReadableStream(e,this.controller),o;for await(let a of n)o&&o!==a.id&&this._addChatCompletion(p(this,re,"m",co).call(this)),p(this,re,"m",vi).call(this,a),o=a.id;if(n.controller.signal?.aborted)throw new Y;return this._addChatCompletion(p(this,re,"m",co).call(this))}[(ze=new WeakMap,Wr=new WeakMap,mt=new WeakMap,re=new WeakSet,Ii=i(function(){this.ended||N(this,mt,void 0,"f")},"_ChatCompletionStream_beginRequest"),ao=i(function(t){let s=p(this,Wr,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},p(this,Wr,"f")[t.index]=s,s)},"_ChatCompletionStream_getChoiceEventState"),vi=i(function(t){if(this.ended)return;let s=p(this,re,"m",_c).call(this,t);this._emit("chunk",t,s);for(let n of t.choices){let o=s.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let a=p(this,re,"m",ao).call(this,o);o.finish_reason&&(p(this,re,"m",Ri).call(this,o),a.current_tool_call_index!=null&&p(this,re,"m",Pi).call(this,o,a.current_tool_call_index));for(let c of n.delta.tool_calls??[])a.current_tool_call_index!==c.index&&(p(this,re,"m",Ri).call(this,o),a.current_tool_call_index!=null&&p(this,re,"m",Pi).call(this,o,a.current_tool_call_index)),a.current_tool_call_index=c.index;for(let c of n.delta.tool_calls??[]){let l=o.message.tool_calls?.[c.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:c.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(l?.type,void 0))}}},"_ChatCompletionStream_addChunk"),Pi=i(function(t,s){if(p(this,re,"m",ao).call(this,t).done_tool_calls.has(s))return;let o=t.message.tool_calls?.[s];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let a=p(this,ze,"f")?.tools?.find(c=>tn(c)&&c.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:s,arguments:o.function.arguments,parsed_arguments:Ut(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},"_ChatCompletionStream_emitToolCallDoneEvent"),Ri=i(function(t){let s=p(this,re,"m",ao).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;let n=p(this,re,"m",Ei).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},"_ChatCompletionStream_emitContentDoneEvents"),co=i(function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let t=p(this,mt,"f");if(!t)throw new E("request ended without sending any chunks");return N(this,mt,void 0,"f"),N(this,Wr,[],"f"),Mu(t,p(this,ze,"f"))},"_ChatCompletionStream_endRequest"),Ei=i(function(){let t=p(this,ze,"f")?.response_format;return rn(t)?t:null},"_ChatCompletionStream_getAutoParseableResponseFormat"),_c=i(function(t){var s,n,o,a;let c=p(this,mt,"f"),{choices:l,...u}=t;c?Object.assign(c,u):c=N(this,mt,{...u,choices:[]},"f");for(let{delta:f,finish_reason:d,index:m,logprobs:h=null,...x}of t.choices){let y=c.choices[m];if(y||(y=c.choices[m]={finish_reason:d,index:m,message:{},logprobs:h,...x}),h)if(!y.logprobs)y.logprobs=Object.assign({},h);else{let{content:B,refusal:U,...H}=h;Object.assign(y.logprobs,H),B&&((s=y.logprobs).content??(s.content=[]),y.logprobs.content.push(...B)),U&&((n=y.logprobs).refusal??(n.refusal=[]),y.logprobs.refusal.push(...U))}if(d&&(y.finish_reason=d,p(this,ze,"f")&&mi(p(this,ze,"f")))){if(d==="length")throw new Fr;if(d==="content_filter")throw new Lr}if(Object.assign(y,x),!f)continue;let{content:k,refusal:I,function_call:b,role:L,tool_calls:T,...W}=f;if(Object.assign(y.message,W),I&&(y.message.refusal=(y.message.refusal||"")+I),L&&(y.message.role=L),b&&(y.message.function_call?(b.name&&(y.message.function_call.name=b.name),b.arguments&&((o=y.message.function_call).arguments??(o.arguments=""),y.message.function_call.arguments+=b.arguments)):y.message.function_call=b),k&&(y.message.content=(y.message.content||"")+k,!y.message.refusal&&p(this,re,"m",Ei).call(this)&&(y.message.parsed=Si(y.message.content))),T){y.message.tool_calls||(y.message.tool_calls=[]);for(let{index:B,id:U,type:H,function:M,...v}of T){let D=(a=y.message.tool_calls)[B]??(a[B]={});Object.assign(D,v),U&&(D.id=U),H&&(D.type=H),M&&(D.function??(D.function={name:M.name??"",arguments:""})),M?.name&&(D.function.name=M.name),M?.arguments&&(D.function.arguments+=M.arguments,uc(p(this,ze,"f"),D)&&(D.function.parsed_arguments=Si(D.function.arguments)))}}}return c},"_ChatCompletionStream_accumulateChatCompletion"),Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:i(async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),"next"),return:i(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Mu(r,e){let{id:t,choices:s,created:n,model:o,system_fingerprint:a,...c}=r,l={...c,id:t,choices:s.map(({message:u,finish_reason:f,index:d,logprobs:m,...h})=>{if(!f)throw new E(`missing finish_reason for choice ${d}`);let{content:x=null,function_call:y,tool_calls:k,...I}=u,b=u.role;if(!b)throw new E(`missing role for choice ${d}`);if(y){let{arguments:L,name:T}=y;if(L==null)throw new E(`missing function_call.arguments for choice ${d}`);if(!T)throw new E(`missing function_call.name for choice ${d}`);return{...h,message:{content:x,function_call:{arguments:L,name:T},role:b,refusal:u.refusal??null},finish_reason:f,index:d,logprobs:m}}return k?{...h,index:d,finish_reason:f,logprobs:m,message:{...I,role:b,content:x,refusal:u.refusal??null,tool_calls:k.map((L,T)=>{let{function:W,type:B,id:U,...H}=L,{arguments:M,name:v,...D}=W||{};if(U==null)throw new E(`missing choices[${d}].tool_calls[${T}].id
|
|
67
|
+
${lo(r)}`);if(B==null)throw new E(`missing choices[${d}].tool_calls[${T}].type
|
|
68
|
+
${lo(r)}`);if(v==null)throw new E(`missing choices[${d}].tool_calls[${T}].function.name
|
|
69
|
+
${lo(r)}`);if(M==null)throw new E(`missing choices[${d}].tool_calls[${T}].function.arguments
|
|
70
|
+
${lo(r)}`);return{...H,id:U,type:B,function:{...D,name:v,arguments:M}}})}}:{...h,message:{...I,content:x,role:b,refusal:u.refusal??null},finish_reason:f,index:d,logprobs:m}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return lc(l,e)}i(Mu,"finalizeChatCompletion");function lo(r){return JSON.stringify(r)}i(lo,"str");var un=class r extends jt{static{i(this,"ChatCompletionStreamingRunner")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){let n=new r(t),o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var Ye=class extends w{static{i(this,"Completions")}constructor(){super(...arguments),this.messages=new Dt(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(_`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(_`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",q,{query:e,...t})}delete(e,t){return this._client.delete(_`/chat/completions/${e}`,t)}parse(e,t){return fc(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>sn(s,e))}runTools(e,t){return e.stream?un.runTools(this._client,e,t):ln.runTools(this._client,e,t)}stream(e,t){return jt.createChatCompletion(this._client,e,t)}};Ye.Messages=Dt;var gt=class extends w{static{i(this,"Chat")}constructor(){super(...arguments),this.completions=new Ye(this._client)}};gt.Completions=Ye;var yc=Symbol("brand.privateNullableHeaders");function*Nu(r){if(!r)return;if(yc in r){let{values:s,nulls:n}=r;yield*s.entries();for(let o of n)yield[o,null];return}let e=!1,t;r instanceof Headers?t=r.entries():zo(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let s of t){let n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=zo(s[1])?s[1]:[s[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,c])}}i(Nu,"iterateHeaders");var S=i(r=>{let e=new Headers,t=new Set;for(let s of r){let n=new Set;for(let[o,a]of Nu(s)){let c=o.toLowerCase();n.has(c)||(e.delete(o),n.add(c)),a===null?(e.delete(o),t.add(c)):(e.append(o,a),t.delete(c))}}return{[yc]:!0,values:e,nulls:t}},"buildHeaders");var Hr=class extends w{static{i(this,"Speech")}create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:S([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var Gr=class extends w{static{i(this,"Transcriptions")}create(e,t){return this._client.post("/audio/transcriptions",de({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Jr=class extends w{static{i(this,"Translations")}create(e,t){return this._client.post("/audio/translations",de({body:e,...t,__metadata:{model:e.model}},this._client))}};var Ue=class extends w{static{i(this,"Audio")}constructor(){super(...arguments),this.transcriptions=new Gr(this._client),this.translations=new Jr(this._client),this.speech=new Hr(this._client)}};Ue.Transcriptions=Gr;Ue.Translations=Jr;Ue.Speech=Hr;var qt=class extends w{static{i(this,"Batches")}create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(_`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",q,{query:e,...t})}cancel(e,t){return this._client.post(_`/batches/${e}/cancel`,t)}};var Kr=class extends w{static{i(this,"Assistants")}create(e,t){return this._client.post("/assistants",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(_`/assistants/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(_`/assistants/${e}`,{body:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",q,{query:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(_`/assistants/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Vr=class extends w{static{i(this,"Sessions")}create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Xr=class extends w{static{i(this,"TranscriptionSessions")}create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var _t=class extends w{static{i(this,"Realtime")}constructor(){super(...arguments),this.sessions=new Vr(this._client),this.transcriptionSessions=new Xr(this._client)}};_t.Sessions=Vr;_t.TranscriptionSessions=Xr;var zr=class extends w{static{i(this,"Sessions")}create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(_`/chatkit/sessions/${e}/cancel`,{...t,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Yr=class extends w{static{i(this,"Threads")}retrieve(e,t){return this._client.get(_`/chatkit/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Pe,{query:e,...t,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(_`/chatkit/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(_`/chatkit/threads/${e}/items`,Pe,{query:t,...s,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};var yt=class extends w{static{i(this,"ChatKit")}constructor(){super(...arguments),this.sessions=new zr(this._client),this.threads=new Yr(this._client)}};yt.Sessions=zr;yt.Threads=Yr;var Qr=class extends w{static{i(this,"Messages")}create(e,t,s){return this._client.post(_`/threads/${e}/messages`,{body:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(_`/threads/${n}/messages/${e}`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{thread_id:n,...o}=t;return this._client.post(_`/threads/${n}/messages/${e}`,{body:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(_`/threads/${e}/messages`,q,{query:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){let{thread_id:n}=t;return this._client.delete(_`/threads/${n}/messages/${e}`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}};var Zr=class extends w{static{i(this,"Steps")}retrieve(e,t,s){let{thread_id:n,run_id:o,...a}=t;return this._client.get(_`/threads/${n}/runs/${o}/steps/${e}`,{query:a,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){let{thread_id:n,...o}=t;return this._client.getAPIList(_`/threads/${n}/runs/${e}/steps`,q,{query:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}};var wc=i(r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}},"toFloat32Array");var wt=i(r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()},"readEnv");var ce,Wt,Ci,je,uo,Re,Ht,es,Bt,po,we,fo,ho,hn,dn,fn,bc,xc,kc,Ac,Sc,Ic,vc,Qe=class extends pt{static{i(this,"AssistantStream")}constructor(){super(...arguments),ce.add(this),Ci.set(this,[]),je.set(this,{}),uo.set(this,{}),Re.set(this,void 0),Ht.set(this,void 0),es.set(this,void 0),Bt.set(this,void 0),po.set(this,void 0),we.set(this,void 0),fo.set(this,void 0),ho.set(this,void 0),hn.set(this,void 0)}[(Ci=new WeakMap,je=new WeakMap,uo=new WeakMap,Re=new WeakMap,Ht=new WeakMap,es=new WeakMap,Bt=new WeakMap,po=new WeakMap,we=new WeakMap,fo=new WeakMap,ho=new WeakMap,hn=new WeakMap,ce=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:i(async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),"next"),return:i(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}static fromReadableStream(e){let t=new Wt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=Le.fromReadableStream(e,this.controller);for await(let o of n)p(this,ce,"m",dn).call(this,o);if(n.controller.signal?.aborted)throw new Y;return this._addRun(p(this,ce,"m",fn).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){let o=new Wt;return o._run(()=>o._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,s,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...s,stream:!0},c=await e.submitToolOutputs(t,a,{...n,signal:this.controller.signal});this._connected();for await(let l of c)p(this,ce,"m",dn).call(this,l);if(c.controller.signal?.aborted)throw new Y;return this._addRun(p(this,ce,"m",fn).call(this))}static createThreadAssistantStream(e,t,s){let n=new Wt;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){let o=new Wt;return o._run(()=>o._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return p(this,fo,"f")}currentRun(){return p(this,ho,"f")}currentMessageSnapshot(){return p(this,Re,"f")}currentRunStepSnapshot(){return p(this,hn,"f")}async finalRunSteps(){return await this.done(),Object.values(p(this,je,"f"))}async finalMessages(){return await this.done(),Object.values(p(this,uo,"f"))}async finalRun(){if(await this.done(),!p(this,Ht,"f"))throw Error("Final run was not received.");return p(this,Ht,"f")}async _createThreadAssistantStream(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},a=await e.createAndRun(o,{...s,signal:this.controller.signal});this._connected();for await(let c of a)p(this,ce,"m",dn).call(this,c);if(a.controller.signal?.aborted)throw new Y;return this._addRun(p(this,ce,"m",fn).call(this))}async _createAssistantStream(e,t,s,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...s,stream:!0},c=await e.create(t,a,{...n,signal:this.controller.signal});this._connected();for await(let l of c)p(this,ce,"m",dn).call(this,l);if(c.controller.signal?.aborted)throw new Y;return this._addRun(p(this,ce,"m",fn).call(this))}static accumulateDelta(e,t){for(let[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let o=e[s];if(o==null){e[s]=n;continue}if(s==="index"||s==="type"){e[s]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Vs(o)&&Vs(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...n);continue}for(let a of n){if(!Vs(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let c=a.index;if(c==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);let l=o[c];l==null?o.push(a):o[c]=this.accumulateDelta(l,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${o}`);e[s]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}};Wt=Qe,dn=i(function(e){if(!this.ended)switch(N(this,fo,e,"f"),p(this,ce,"m",kc).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":p(this,ce,"m",vc).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":p(this,ce,"m",xc).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":p(this,ce,"m",bc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},"_AssistantStream_addEvent"),fn=i(function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");if(!p(this,Ht,"f"))throw Error("Final run has not been received");return p(this,Ht,"f")},"_AssistantStream_endRequest"),bc=i(function(e){let[t,s]=p(this,ce,"m",Sc).call(this,e,p(this,Re,"f"));N(this,Re,t,"f"),p(this,uo,"f")[t.id]=t;for(let n of s){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=t.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=p(this,es,"f")){if(p(this,Bt,"f"))switch(p(this,Bt,"f").type){case"text":this._emit("textDone",p(this,Bt,"f").text,p(this,Re,"f"));break;case"image_file":this._emit("imageFileDone",p(this,Bt,"f").image_file,p(this,Re,"f"));break}N(this,es,n.index,"f")}N(this,Bt,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(p(this,es,"f")!==void 0){let n=e.data.content[p(this,es,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,p(this,Re,"f"));break;case"text":this._emit("textDone",n.text,p(this,Re,"f"));break}}p(this,Re,"f")&&this._emit("messageDone",e.data),N(this,Re,void 0,"f")}},"_AssistantStream_handleMessage"),xc=i(function(e){let t=p(this,ce,"m",Ac).call(this,e);switch(N(this,hn,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)o.index==p(this,po,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(p(this,we,"f")&&this._emit("toolCallDone",p(this,we,"f")),N(this,po,o.index,"f"),N(this,we,t.step_details.tool_calls[o.index],"f"),p(this,we,"f")&&this._emit("toolCallCreated",p(this,we,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":N(this,hn,void 0,"f"),e.data.step_details.type=="tool_calls"&&p(this,we,"f")&&(this._emit("toolCallDone",p(this,we,"f")),N(this,we,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},"_AssistantStream_handleRunStep"),kc=i(function(e){p(this,Ci,"f").push(e),this._emit("event",e)},"_AssistantStream_handleEvent"),Ac=i(function(e){switch(e.event){case"thread.run.step.created":return p(this,je,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=p(this,je,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){let n=Wt.accumulateDelta(t,s.delta);p(this,je,"f")[e.data.id]=n}return p(this,je,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":p(this,je,"f")[e.data.id]=e.data;break}if(p(this,je,"f")[e.data.id])return p(this,je,"f")[e.data.id];throw new Error("No snapshot available")},"_AssistantStream_accumulateRunStep"),Sc=i(function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=p(this,ce,"m",Ic).call(this,o,a)}else t.content[o.index]=o,s.push(o);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},"_AssistantStream_accumulateMessage"),Ic=i(function(e,t){return Wt.accumulateDelta(t,e)},"_AssistantStream_accumulateContent"),vc=i(function(e){switch(N(this,ho,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":N(this,Ht,e.data,"f"),p(this,we,"f")&&(this._emit("toolCallDone",p(this,we,"f")),N(this,we,void 0,"f"));break;case"thread.run.cancelling":break}},"_AssistantStream_handleRun");var Gt=class extends w{static{i(this,"Runs")}constructor(){super(...arguments),this.steps=new Zr(this._client)}create(e,t,s){let{include:n,...o}=t;return this._client.post(_`/threads/${e}/runs`,{query:{include:n},body:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(_`/threads/${n}/runs/${e}`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{thread_id:n,...o}=t;return this._client.post(_`/threads/${n}/runs/${e}`,{body:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(_`/threads/${e}/runs`,q,{query:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){let{thread_id:n}=t;return this._client.post(_`/threads/${n}/runs/${e}/cancel`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return Qe.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){let n=S([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(s?.pollIntervalMs)c=s.pollIntervalMs;else{let l=a.headers.get("openai-poll-after-ms");if(l){let u=parseInt(l);isNaN(u)||(c=u)}}await Ne(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,s){return Qe.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){let{thread_id:n,...o}=t;return this._client.post(_`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,s){let n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return Qe.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};Gt.Steps=Zr;var bt=class extends w{static{i(this,"Threads")}constructor(){super(...arguments),this.runs=new Gt(this._client),this.messages=new Qr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(_`/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(_`/threads/${e}`,{body:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(_`/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Qe.createThreadAssistantStream(e,this._client.beta.threads,t)}};bt.Runs=Gt;bt.Messages=Qr;var Ee=class extends w{static{i(this,"Beta")}constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new yt(this._client),this.assistants=new Kr(this._client),this.threads=new bt(this._client)}};Ee.Realtime=_t;Ee.ChatKit=yt;Ee.Assistants=Kr;Ee.Threads=bt;var Jt=class extends w{static{i(this,"Completions")}create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var ts=class extends w{static{i(this,"Content")}retrieve(e,t,s){let{container_id:n}=t;return this._client.get(_`/containers/${n}/files/${e}/content`,{...s,headers:S([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}};var Kt=class extends w{static{i(this,"Files")}constructor(){super(...arguments),this.content=new ts(this._client)}create(e,t,s){return this._client.post(_`/containers/${e}/files`,ht({body:t,...s},this._client))}retrieve(e,t,s){let{container_id:n}=t;return this._client.get(_`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(_`/containers/${e}/files`,q,{query:t,...s})}delete(e,t,s){let{container_id:n}=t;return this._client.delete(_`/containers/${n}/files/${e}`,{...s,headers:S([{Accept:"*/*"},s?.headers])})}};Kt.Content=ts;var xt=class extends w{static{i(this,"Containers")}constructor(){super(...arguments),this.files=new Kt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(_`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",q,{query:e,...t})}delete(e,t){return this._client.delete(_`/containers/${e}`,{...t,headers:S([{Accept:"*/*"},t?.headers])})}};xt.Files=Kt;var rs=class extends w{static{i(this,"Items")}create(e,t,s){let{include:n,...o}=t;return this._client.post(_`/conversations/${e}/items`,{query:{include:n},body:o,...s})}retrieve(e,t,s){let{conversation_id:n,...o}=t;return this._client.get(_`/conversations/${n}/items/${e}`,{query:o,...s})}list(e,t={},s){return this._client.getAPIList(_`/conversations/${e}/items`,Pe,{query:t,...s})}delete(e,t,s){let{conversation_id:n}=t;return this._client.delete(_`/conversations/${n}/items/${e}`,s)}};var kt=class extends w{static{i(this,"Conversations")}constructor(){super(...arguments),this.items=new rs(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(_`/conversations/${e}`,t)}update(e,t,s){return this._client.post(_`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(_`/conversations/${e}`,t)}};kt.Items=rs;var Vt=class extends w{static{i(this,"Embeddings")}create(e,t){let s=!!e.encoding_format,n=s?e.encoding_format:"base64";s&&z(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?o:(z(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(c=>{let l=c.embedding;c.embedding=wc(l)}),a)))}};var ss=class extends w{static{i(this,"OutputItems")}retrieve(e,t,s){let{eval_id:n,run_id:o}=t;return this._client.get(_`/evals/${n}/runs/${o}/output_items/${e}`,s)}list(e,t,s){let{eval_id:n,...o}=t;return this._client.getAPIList(_`/evals/${n}/runs/${e}/output_items`,q,{query:o,...s})}};var Xt=class extends w{static{i(this,"Runs")}constructor(){super(...arguments),this.outputItems=new ss(this._client)}create(e,t,s){return this._client.post(_`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){let{eval_id:n}=t;return this._client.get(_`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(_`/evals/${e}/runs`,q,{query:t,...s})}delete(e,t,s){let{eval_id:n}=t;return this._client.delete(_`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){let{eval_id:n}=t;return this._client.post(_`/evals/${n}/runs/${e}`,s)}};Xt.OutputItems=ss;var At=class extends w{static{i(this,"Evals")}constructor(){super(...arguments),this.runs=new Xt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(_`/evals/${e}`,t)}update(e,t,s){return this._client.post(_`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",q,{query:e,...t})}delete(e,t){return this._client.delete(_`/evals/${e}`,t)}};At.Runs=Xt;var zt=class extends w{static{i(this,"Files")}create(e,t){return this._client.post("/files",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(_`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",q,{query:e,...t})}delete(e,t){return this._client.delete(_`/files/${e}`,t)}content(e,t){return this._client.get(_`/files/${e}/content`,{...t,headers:S([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await Ne(t),a=await this.retrieve(e),Date.now()-o>s)throw new dt({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};var ns=class extends w{static{i(this,"Methods")}};var os=class extends w{static{i(this,"Graders")}run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Yt=class extends w{static{i(this,"Alpha")}constructor(){super(...arguments),this.graders=new os(this._client)}};Yt.Graders=os;var is=class extends w{static{i(this,"Permissions")}create(e,t,s){return this._client.getAPIList(_`/fine_tuning/checkpoints/${e}/permissions`,De,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(_`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}list(e,t={},s){return this._client.getAPIList(_`/fine_tuning/checkpoints/${e}/permissions`,Pe,{query:t,...s})}delete(e,t,s){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(_`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}};var Qt=class extends w{static{i(this,"Checkpoints")}constructor(){super(...arguments),this.permissions=new is(this._client)}};Qt.Permissions=is;var as=class extends w{static{i(this,"Checkpoints")}list(e,t={},s){return this._client.getAPIList(_`/fine_tuning/jobs/${e}/checkpoints`,q,{query:t,...s})}};var Zt=class extends w{static{i(this,"Jobs")}constructor(){super(...arguments),this.checkpoints=new as(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(_`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",q,{query:e,...t})}cancel(e,t){return this._client.post(_`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(_`/fine_tuning/jobs/${e}/events`,q,{query:t,...s})}pause(e,t){return this._client.post(_`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(_`/fine_tuning/jobs/${e}/resume`,t)}};Zt.Checkpoints=as;var Ce=class extends w{static{i(this,"FineTuning")}constructor(){super(...arguments),this.methods=new ns(this._client),this.jobs=new Zt(this._client),this.checkpoints=new Qt(this._client),this.alpha=new Yt(this._client)}};Ce.Methods=ns;Ce.Jobs=Zt;Ce.Checkpoints=Qt;Ce.Alpha=Yt;var cs=class extends w{static{i(this,"GraderModels")}};var St=class extends w{static{i(this,"Graders")}constructor(){super(...arguments),this.graderModels=new cs(this._client)}};St.GraderModels=cs;var er=class extends w{static{i(this,"Images")}createVariation(e,t){return this._client.post("/images/variations",de({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",de({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var tr=class extends w{static{i(this,"Models")}retrieve(e,t){return this._client.get(_`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",De,e)}delete(e,t){return this._client.delete(_`/models/${e}`,t)}};var rr=class extends w{static{i(this,"Moderations")}create(e,t){return this._client.post("/moderations",{body:e,...t})}};var ls=class extends w{static{i(this,"Calls")}accept(e,t,s){return this._client.post(_`/realtime/calls/${e}/accept`,{body:t,...s,headers:S([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(_`/realtime/calls/${e}/hangup`,{...t,headers:S([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(_`/realtime/calls/${e}/refer`,{body:t,...s,headers:S([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(_`/realtime/calls/${e}/reject`,{body:t,...s,headers:S([{Accept:"*/*"},s?.headers])})}};var us=class extends w{static{i(this,"ClientSecrets")}create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var Ze=class extends w{static{i(this,"Realtime")}constructor(){super(...arguments),this.clientSecrets=new us(this._client),this.calls=new ls(this._client)}};Ze.ClientSecrets=us;Ze.Calls=ls;function Pc(r,e){return!e||!fd(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(s=>({...s,parsed:null}))}:t)}:Ti(r,e)}i(Pc,"maybeParseResponse");function Ti(r,e){let t=r.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:md(e,n)};if(n.type==="message"){let o=n.content.map(a=>a.type==="output_text"?{...a,parsed:dd(e,a.text)}:a);return{...n,content:o}}return n}),s=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||mo(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}i(Ti,"parseResponse");function dd(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}i(dd,"parseTextFormat");function fd(r){return!!rn(r.text?.format)}i(fd,"hasAutoParseableInput");function hd(r){return r?.$brand==="auto-parseable-tool"}i(hd,"isAutoParsableTool");function pd(r,e){return r.find(t=>t.type==="function"&&t.name===e)}i(pd,"getInputToolByName");function md(r,e){let t=pd(r.tools??[],e.name);return{...e,...e,parsed_arguments:hd(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}i(md,"parseToolCall");function mo(r){let e=[];for(let t of r.output)if(t.type==="message")for(let s of t.content)s.type==="output_text"&&e.push(s.text);r.output_text=e.join("")}i(mo,"addOutputText");var ds,go,It,_o,Rc,Ec,Cc,Tc,yo=class r extends pt{static{i(this,"ResponseStream")}constructor(e){super(),ds.add(this),go.set(this,void 0),It.set(this,void 0),_o.set(this,void 0),N(this,go,e,"f")}static createResponse(e,t,s){let n=new r(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),p(this,ds,"m",Rc).call(this);let o,a=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(let c of o)p(this,ds,"m",Ec).call(this,c,a);if(o.controller.signal?.aborted)throw new Y;return p(this,ds,"m",Cc).call(this)}[(go=new WeakMap,It=new WeakMap,_o=new WeakMap,ds=new WeakSet,Rc=i(function(){this.ended||N(this,It,void 0,"f")},"_ResponseStream_beginRequest"),Ec=i(function(t,s){if(this.ended)return;let n=i((a,c)=>{(s==null||c.sequence_number>s)&&this._emit(a,c)},"maybeEmit"),o=p(this,ds,"m",Tc).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new E(`missing output at index ${t.output_index}`);if(a.type==="message"){let c=a.content[t.content_index];if(!c)throw new E(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new E(`expected content to be 'output_text', got ${c.type}`);n("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new E(`missing output at index ${t.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:n(t.type,t);break}},"_ResponseStream_addEvent"),Cc=i(function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let t=p(this,It,"f");if(!t)throw new E("request ended without sending any events");N(this,It,void 0,"f");let s=gd(t,p(this,go,"f"));return N(this,_o,s,"f"),s},"_ResponseStream_endRequest"),Tc=i(function(t){let s=p(this,It,"f");if(!s){if(t.type!=="response.created")throw new E(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=N(this,It,t.response,"f"),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{let n=s.output[t.output_index];if(!n)throw new E(`missing output at index ${t.output_index}`);let o=n.type,a=t.part;o==="message"&&a.type!=="reasoning_text"?n.content.push(a):o==="reasoning"&&a.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(a));break}case"response.output_text.delta":{let n=s.output[t.output_index];if(!n)throw new E(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new E(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new E(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=s.output[t.output_index];if(!n)throw new E(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=s.output[t.output_index];if(!n)throw new E(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new E(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new E(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{N(this,It,t.response,"f");break}}return s},"_ResponseStream_accumulateResponse"),Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:i(async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),"next"),return:i(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}async finalResponse(){await this.done();let e=p(this,_o,"f");if(!e)throw new E("stream ended without producing a ChatCompletion");return e}};function gd(r,e){return Pc(r,e)}i(gd,"finalizeResponse");var fs=class extends w{static{i(this,"InputItems")}list(e,t={},s){return this._client.getAPIList(_`/responses/${e}/input_items`,q,{query:t,...s})}};var hs=class extends w{static{i(this,"InputTokens")}count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var et=class extends w{static{i(this,"Responses")}constructor(){super(...arguments),this.inputItems=new fs(this._client),this.inputTokens=new hs(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&mo(s),s))}retrieve(e,t={},s){return this._client.get(_`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&mo(n),n))}delete(e,t){return this._client.delete(_`/responses/${e}`,{...t,headers:S([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>Ti(s,e))}stream(e,t){return yo.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(_`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};et.InputItems=fs;et.InputTokens=hs;var ps=class extends w{static{i(this,"Content")}retrieve(e,t){return this._client.get(_`/skills/${e}/content`,{...t,headers:S([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var ms=class extends w{static{i(this,"Content")}retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(_`/skills/${n}/versions/${e}/content`,{...s,headers:S([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}};var sr=class extends w{static{i(this,"Versions")}constructor(){super(...arguments),this.content=new ms(this._client)}create(e,t={},s){return this._client.post(_`/skills/${e}/versions`,ht({body:t,...s},this._client))}retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(_`/skills/${n}/versions/${e}`,s)}list(e,t={},s){return this._client.getAPIList(_`/skills/${e}/versions`,q,{query:t,...s})}delete(e,t,s){let{skill_id:n}=t;return this._client.delete(_`/skills/${n}/versions/${e}`,s)}};sr.Content=ms;var tt=class extends w{static{i(this,"Skills")}constructor(){super(...arguments),this.content=new ps(this._client),this.versions=new sr(this._client)}create(e={},t){return this._client.post("/skills",ht({body:e,...t},this._client))}retrieve(e,t){return this._client.get(_`/skills/${e}`,t)}update(e,t,s){return this._client.post(_`/skills/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/skills",q,{query:e,...t})}delete(e,t){return this._client.delete(_`/skills/${e}`,t)}};tt.Content=ps;tt.Versions=sr;var gs=class extends w{static{i(this,"Parts")}create(e,t,s){return this._client.post(_`/uploads/${e}/parts`,de({body:t,...s},this._client))}};var vt=class extends w{static{i(this,"Uploads")}constructor(){super(...arguments),this.parts=new gs(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(_`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(_`/uploads/${e}/complete`,{body:t,...s})}};vt.Parts=gs;var Oc=i(async r=>{let e=await Promise.allSettled(r),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let s=[];for(let n of e)n.status==="fulfilled"&&s.push(n.value);return s},"allSettledWithThrow");var _s=class extends w{static{i(this,"FileBatches")}create(e,t,s){return this._client.post(_`/vector_stores/${e}/file_batches`,{body:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(_`/vector_stores/${n}/file_batches/${e}`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){let{vector_store_id:n}=t;return this._client.post(_`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){let{vector_store_id:n,...o}=t;return this._client.getAPIList(_`/vector_stores/${n}/file_batches/${e}/files`,q,{query:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){let n=S([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(o.status){case"in_progress":let c=5e3;if(s?.pollIntervalMs)c=s.pollIntervalMs;else{let l=a.headers.get("openai-poll-after-ms");if(l){let u=parseInt(l);isNaN(u)||(c=u)}}await Ne(c);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,a=Math.min(o,t.length),c=this._client,l=t.values(),u=[...s];async function f(m){for(let h of m){let x=await c.files.create({file:h,purpose:"assistants"},n);u.push(x.id)}}i(f,"processFiles");let d=Array(a).fill(l).map(f);return await Oc(d),await this.createAndPoll(e,{file_ids:u})}};var ys=class extends w{static{i(this,"Files")}create(e,t,s){return this._client.post(_`/vector_stores/${e}/files`,{body:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(_`/vector_stores/${n}/files/${e}`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{vector_store_id:n,...o}=t;return this._client.post(_`/vector_stores/${n}/files/${e}`,{body:o,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(_`/vector_stores/${e}/files`,q,{query:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){let{vector_store_id:n}=t;return this._client.delete(_`/vector_stores/${n}/files/${e}`,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){let n=S([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),a=o.data;switch(a.status){case"in_progress":let c=5e3;if(s?.pollIntervalMs)c=s.pollIntervalMs;else{let l=o.response.headers.get("openai-poll-after-ms");if(l){let u=parseInt(l);isNaN(u)||(c=u)}}await Ne(c);break;case"failed":case"completed":return a}}}async upload(e,t,s){let n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){let n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){let{vector_store_id:n}=t;return this._client.getAPIList(_`/vector_stores/${n}/files/${e}/content`,De,{...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}};var rt=class extends w{static{i(this,"VectorStores")}constructor(){super(...arguments),this.files=new ys(this._client),this.fileBatches=new _s(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(_`/vector_stores/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(_`/vector_stores/${e}`,{body:t,...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",q,{query:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(_`/vector_stores/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(_`/vector_stores/${e}/search`,De,{body:t,method:"post",...s,headers:S([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}};rt.Files=ys;rt.FileBatches=_s;var nr=class extends w{static{i(this,"Videos")}create(e,t){return this._client.post("/videos",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(_`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Pe,{query:e,...t})}delete(e,t){return this._client.delete(_`/videos/${e}`,t)}createCharacter(e,t){return this._client.post("/videos/characters",de({body:e,...t},this._client))}downloadContent(e,t={},s){return this._client.get(_`/videos/${e}/content`,{query:t,...s,headers:S([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",de({body:e,...t},this._client))}extend(e,t){return this._client.post("/videos/extensions",de({body:e,...t},this._client))}getCharacter(e,t){return this._client.get(_`/videos/characters/${e}`,t)}remix(e,t,s){return this._client.post(_`/videos/${e}/remix`,ht({body:t,...s},this._client))}};var ws,Mc,wo,or=class extends w{static{i(this,"Webhooks")}constructor(){super(...arguments),ws.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");p(this,ws,"m",Mc).call(this,s);let o=S([t]).values,a=p(this,ws,"m",wo).call(this,o,"webhook-signature"),c=p(this,ws,"m",wo).call(this,o,"webhook-timestamp"),l=p(this,ws,"m",wo).call(this,o,"webhook-id"),u=parseInt(c,10);if(isNaN(u))throw new $e("Invalid webhook timestamp format");let f=Math.floor(Date.now()/1e3);if(f-u>n)throw new $e("Webhook timestamp is too old");if(u>f+n)throw new $e("Webhook timestamp is too new");let d=a.split(" ").map(y=>y.startsWith("v1,")?y.substring(3):y),m=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),h=l?`${l}.${c}.${e}`:`${c}.${e}`,x=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let y of d)try{let k=Buffer.from(y,"base64");if(await crypto.subtle.verify("HMAC",x,k,new TextEncoder().encode(h)))return}catch{continue}throw new $e("The given webhook signature does not match the expected signature")}};ws=new WeakSet,Mc=i(function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},"_Webhooks_validateSecret"),wo=i(function(e,t){if(!e)throw new Error("Headers are required");let s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s},"_Webhooks_getRequiredHeader");var Oi,Mi,bo,$c,F=class{static{i(this,"OpenAI")}constructor({baseURL:e=wt("OPENAI_BASE_URL"),apiKey:t=wt("OPENAI_API_KEY"),organization:s=wt("OPENAI_ORG_ID")??null,project:n=wt("OPENAI_PROJECT_ID")??null,webhookSecret:o=wt("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Oi.add(this),bo.set(this,void 0),this.completions=new Jt(this),this.chat=new gt(this),this.embeddings=new Vt(this),this.files=new zt(this),this.images=new er(this),this.audio=new Ue(this),this.moderations=new rr(this),this.models=new tr(this),this.fineTuning=new Ce(this),this.graders=new St(this),this.vectorStores=new rt(this),this.webhooks=new or(this),this.beta=new Ee(this),this.batches=new qt(this),this.uploads=new vt(this),this.responses=new et(this),this.realtime=new Ze(this),this.conversations=new kt(this),this.evals=new At(this),this.containers=new xt(this),this.skills=new tt(this),this.videos=new nr(this),t===void 0)throw new E("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let c={apiKey:t,organization:s,project:n,webhookSecret:o,...a,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&Da())throw new E(`It looks like you're running in a browser-like environment.
|
|
71
|
+
|
|
72
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
73
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
74
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
75
|
+
|
|
76
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
77
|
+
|
|
78
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
79
|
+
`);this.baseURL=c.baseURL,this.timeout=c.timeout??Mi.DEFAULT_TIMEOUT,this.logger=c.logger??console;let l="warn";this.logLevel=l,this.logLevel=ci(c.logLevel,"ClientOptions.logLevel",this)??ci(wt("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??ja(),N(this,bo,Ba,"f"),this._options=c,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=s,this.project=n,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return S([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ya(e)}getUserAgent(){return`${this.constructor.name}/JS ${ft}`}defaultIdempotencyKey(){return`stainless-node-retry-${Xo()}`}makeStatusError(e,t,s,n){return ee.generate(e,t,s,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof E?s:new E(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new E(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){let n=!p(this,Oi,"m",$c).call(this)&&s||this.baseURL,o=Ta(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(o.searchParams);return(!Qo(a)||!Qo(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Lt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:c,timeout:l}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:n});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,d=Date.now();if(z(this).debug(`[${u}] sending request`,Ve({retryOfRequestLogID:s,method:n.method,url:c,options:n,headers:a.headers})),n.signal?.aborted)throw new Y;let m=new AbortController,h=await this.fetchWithTimeout(c,a,l,m).catch(Ks),x=Date.now();if(h instanceof globalThis.Error){let I=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new Y;let b=Js(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return z(this).info(`[${u}] connection ${b?"timed out":"failed"} - ${I}`),z(this).debug(`[${u}] connection ${b?"timed out":"failed"} (${I})`,Ve({retryOfRequestLogID:s,url:c,durationMs:x-d,message:h.message})),this.retryRequest(n,t,s??u);throw z(this).info(`[${u}] connection ${b?"timed out":"failed"} - error; no more retries left`),z(this).debug(`[${u}] connection ${b?"timed out":"failed"} (error; no more retries left)`,Ve({retryOfRequestLogID:s,url:c,durationMs:x-d,message:h.message})),b?new dt:new ut({cause:h})}let y=[...h.headers.entries()].filter(([I])=>I==="x-request-id").map(([I,b])=>", "+I+": "+JSON.stringify(b)).join(""),k=`[${u}${f}${y}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${x-d}ms`;if(!h.ok){let I=await this.shouldRetry(h);if(t&&I){let U=`retrying, ${t} attempts remaining`;return await qa(h.body),z(this).info(`${k} - ${U}`),z(this).debug(`[${u}] response error (${U})`,Ve({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:x-d})),this.retryRequest(n,t,s??u,h.headers)}let b=I?"error; no more retries left":"error; not retryable";z(this).info(`${k} - ${b}`);let L=await h.text().catch(U=>Ks(U).message),T=$a(L),W=T?void 0:L;throw z(this).debug(`[${u}] response error (${b})`,Ve({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:W,durationMs:Date.now()-d})),this.makeStatusError(h.status,T,W,h.headers)}return z(this).info(k),z(this).debug(`[${u}] response start`,Ve({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:x-d})),{response:h,options:n,controller:m,requestLogID:u,retryOfRequestLogID:s,startTime:d}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,t){let s=this.makeRequest(t,null,void 0);return new Zs(this,s,e)}async fetchWithTimeout(e,t,s,n){let{signal:o,method:a,...c}=t||{},l=this._makeAbort(n);o&&o.addEventListener("abort",l,{once:!0});let u=setTimeout(l,s),f=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,d={signal:n.signal,...f?{duplex:"half"}:{},method:"GET",...c};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,n){let o,a=n?.get("retry-after-ms");if(a){let l=parseFloat(a);Number.isNaN(l)||(o=l)}let c=n?.get("retry-after");if(c&&!o){let l=parseFloat(c);Number.isNaN(l)?o=Date.parse(c)-Date.now():o=l*1e3}if(o===void 0){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Ne(o),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let s={...e},{method:n,path:o,query:a,defaultBaseURL:c}=s,l=this.buildURL(o,a,c);"timeout"in s&&Ma("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:u,body:f}=this.buildBody({options:s}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:u,retryCount:t});return{req:{method:n,headers:d,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=S([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ua(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let s=S([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Kn(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:p(this,bo,"f").call(this,{body:e,headers:s})}};Mi=F,bo=new WeakMap,Oi=new WeakSet,$c=i(function(){return this.baseURL!=="https://api.openai.com/v1"},"_OpenAI_baseURLOverridden");F.OpenAI=Mi;F.DEFAULT_TIMEOUT=6e5;F.OpenAIError=E;F.APIError=ee;F.APIConnectionError=ut;F.APIConnectionTimeoutError=dt;F.APIUserAbortError=Y;F.NotFoundError=Tr;F.ConflictError=Or;F.RateLimitError=$r;F.BadRequestError=Rr;F.AuthenticationError=Er;F.InternalServerError=Nr;F.PermissionDeniedError=Cr;F.UnprocessableEntityError=Mr;F.InvalidWebhookSignatureError=$e;F.toFile=eo;F.Completions=Jt;F.Chat=gt;F.Embeddings=Vt;F.Files=zt;F.Images=er;F.Audio=Ue;F.Moderations=rr;F.Models=tr;F.FineTuning=Ce;F.Graders=St;F.VectorStores=rt;F.Webhooks=or;F.Beta=Ee;F.Batches=qt;F.Uploads=vt;F.Responses=et;F.Realtime=Ze;F.Conversations=kt;F.Evals=At;F.Containers=xt;F.Skills=tt;F.Videos=nr;var be=fl(Uc(),1);import{AsyncResource as rf}from"async_hooks";import{spawn as sf}from"child_process";import*as el from"path";import*as xe from"fs";import*as yn from"path";import*as sl from"os";import*as nl from"crypto";import*as ir from"fs";import*as xo from"path";import*as cl from"os";import*as Oe from"fs";import*as wn from"path";import*as ul from"os";var A=class Ni extends Error{static{i(this,"_GitLabError")}statusCode;responseBody;constructor(e){super(e.message,{cause:e.cause}),this.name="GitLabError",this.statusCode=e.statusCode,this.responseBody=e.responseBody,Error.captureStackTrace&&Error.captureStackTrace(this,Ni)}static fromResponse(e,t){return new Ni({message:`GitLab API error: ${e.status} ${e.statusText}`,statusCode:e.status,responseBody:t})}isAuthError(){return this.statusCode===401}isRateLimitError(){return this.statusCode===429}isForbiddenError(){return this.statusCode===403}isServerError(){return this.statusCode!==void 0&&this.statusCode>=500}isContextOverflowError(){if(this.statusCode!==400)return!1;let e=this.message?.toLowerCase()||"";return e.includes("context overflow")||e.includes("prompt is too long")||e.includes("prompt too long")||e.includes("tokens")&&e.includes("maximum")}};function pn(r,e){if(/[;&|`$()<>]/.test(r))throw new A({message:`Invalid ${e}: contains shell metacharacters. Use structured arguments instead.`})}i(pn,"validateNoShellMetachars");function bs(r){return"'"+String(r).replace(/'/g,"'\\''")+"'"}i(bs,"shellEscape");var Od=["http:","https:"];function mn(r,e){let t=String(r??"");if(t.includes("\0"))throw new A({message:`${e} contains null bytes`});if(t&&!le.isAbsolute(t)){let s=le.resolve(t),n=process.cwd();if(!s.startsWith(n+le.sep)&&s!==n)throw new A({message:`${e} resolves outside the working directory: ${t}`})}return t}i(mn,"validateMappedPath");function ks(r){return r?r.replace(/\bBearer\s+[A-Za-z0-9\-_.~+/]+=*/gi,"Bearer [REDACTED]").replace(/\bgl(?:pat|oat|cbt|dt|oas|rt|soat|ffct|sapat)-[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/([?&](?:private_token|access_token|token)=)[^&\s"']*/gi,"$1[REDACTED]").replace(/:\/\/([^:@/\s]+):([^@/\s]+)@/g,"://$1:[REDACTED]@"):""}i(ks,"sanitizeErrorMessage");function Md(r,e,t){let s=i(n=>!t||t.has(n),"has");switch(r){case"runReadFile":return{toolName:"read",args:{filePath:mn(e.filepath,"filepath")}};case"runReadFiles":{let n=(e.filepaths??[]).map(o=>mn(o,"filepath"));return n.length<=1?{toolName:"read",args:{filePath:n[0]??""}}:{toolName:"read",args:{filePaths:n}}}case"runWriteFile":{let n=mn(e.filepath,"filepath");if(s("write"))return{toolName:"write",args:{filePath:n,content:e.contents}};let o=String(e.filepath??""),a=String(e.contents??"");return{toolName:"apply_patch",args:{patchText:["*** Begin Patch",`*** Add File: ${o}`,...a.split(`
|
|
80
|
+
`).map(l=>`+${l}`),"*** End Patch"].join(`
|
|
81
|
+
`)}}}case"runEditFile":{let n=String(e.oldString??e.old_string??""),o=String(e.newString??e.new_string??""),a=mn(e.filepath,"filepath");if(s("edit"))return{toolName:"edit",args:{filePath:a,oldString:n,newString:o}};let c=String(e.filepath??""),l=n,u=o,f=l.split(`
|
|
82
|
+
`),d=u.split(`
|
|
83
|
+
`);return{toolName:"apply_patch",args:{patchText:["*** Begin Patch",`*** Update File: ${c}`,"@@",...f.map(h=>`-${h}`),...d.map(h=>`+${h}`),"*** End Patch"].join(`
|
|
84
|
+
`)}}}case"runShellCommand":{let n=e.command;if(!n||typeof n!="string")throw new A({message:"runShellCommand: command is required and must be a string"});if(n.length>1e4)throw new A({message:"runShellCommand: command exceeds maximum length of 10000 characters"});return{toolName:"bash",args:{command:n,description:"DWS shell command"}}}case"runCommand":{let n=e.program;if(!n||typeof n!="string")throw new A({message:"runCommand: program is required and must be a string"});pn(n,"program");let o=e.flags??[],a=e.arguments??[];for(let c of o)typeof c=="string"&&pn(c,"flag");for(let c of a)typeof c=="string"&&pn(c,"argument");return{toolName:"bash",args:{command:[n,...o,...a].map(c=>bs(String(c))).join(" "),description:`DWS run: ${n}`}}}case"runGitCommand":{let n=e.command;if(!n||typeof n!="string")throw new A({message:"runGitCommand: command is required and must be a string"});pn(n,"git command");let o=e.arguments??[];for(let a of o)typeof a=="string"&&pn(a,"git argument");return{toolName:"bash",args:{command:["git",n,...o].map(a=>bs(String(a))).join(" "),description:`DWS git: ${n}`}}}case"listDirectory":return{toolName:"read",args:{filePath:mn(e.directory??".","directory")}};case"findFiles":return{toolName:"glob",args:{pattern:e.name_pattern??e.namePattern}};case"grep":return{toolName:"grep",args:{pattern:e.pattern,path:e.search_directory??e.searchDirectory}};case"mkdir":{let n=String(e.directory_path??e.directoryPath??"");if(!n)throw new A({message:"mkdir: directory_path is required"});if(n.includes("\0"))throw new A({message:"mkdir: directory_path contains null bytes"});return{toolName:"bash",args:{command:`mkdir -p ${bs(n)}`,description:"DWS mkdir"}}}case"runHTTPRequest":{let n=String(e.method??"GET").toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(n))throw new A({message:`runHTTPRequest: invalid HTTP method '${n}'`});let a=String(e.path??"");if(!a)throw new A({message:"runHTTPRequest: path is required"});let c=null;try{c=new URL(a)}catch{c=null}if(c){if(!Od.includes(c.protocol))throw new A({message:`runHTTPRequest: only http:// and https:// schemes are allowed, got '${c.protocol}'`})}else if(!a.startsWith("/"))throw new A({message:`runHTTPRequest: only http:// and https:// schemes are allowed, got a non-URL value '${a}' (curl would guess the protocol)`});let l=bs(n),u=bs(a),f=e.body?` -d ${bs(String(e.body))}`:"";return{toolName:"bash",args:{command:`curl -s -X ${l} -- ${u}${f}`,description:`DWS HTTP ${n}`}}}default:return{toolName:r,args:e}}}i(Md,"mapBuiltinTool");function jc(r){let e=r,t="";for(;;)try{let s=Pt.realpathSync(e);return t?le.join(s,t):s}catch{let s=le.dirname(e);if(s===e)return r;t=t?le.join(le.basename(e),t):le.basename(e),e=s}}i(jc,"realpathDeepestExisting");function qc(r){if(!r)throw new A({message:"filePath is required"});if(r.includes("\0"))throw new A({message:"filePath contains null bytes"});let e=le.resolve(r),t=process.cwd();if(!e.startsWith(t+le.sep)&&e!==t)throw new A({message:`filePath resolves outside the working directory: ${r}`});let s=jc(e),n=jc(t);if(!s.startsWith(n+le.sep)&&s!==n)throw new A({message:`filePath resolves outside the working directory: ${r}`});return e}i(qc,"validateSafePath");function $d(r,e){if(r!=="edit"&&r!=="write")return null;let t;try{t=JSON.parse(e)}catch{return{result:"",error:`${r} fallback: invalid JSON arguments`}}try{if(r==="write"){let f=String(t.filePath??"");if(!f)return{result:"",error:"write fallback: filePath is required"};let d=qc(f),m=String(t.content??"");return Pt.writeFileSync(d,m,"utf-8"),{result:"File written successfully.",title:f,metadata:{output:"File written successfully."}}}let s=String(t.filePath??""),n=String(t.oldString??""),o=String(t.newString??"");if(!s)return{result:"",error:"edit fallback: filePath is required"};if(!n&&!o)return{result:"",error:"edit fallback: oldString and newString are both empty"};let a=qc(s),c;try{c=Pt.readFileSync(a,"utf-8")}catch{c=""}if(n==="")return Pt.writeFileSync(a,o,"utf-8"),{result:"Edit applied successfully.",title:s,metadata:{output:"Edit applied successfully."}};let l=c.indexOf(n);if(l===-1)return{result:"",error:`edit fallback: could not find oldString in ${s}`};let u=c.substring(0,l)+o+c.substring(l+n.length);return Pt.writeFileSync(a,u,"utf-8"),{result:"Edit applied successfully.",title:s,metadata:{output:"Edit applied successfully."}}}catch(s){let n=s instanceof Error?s.message:String(s);return{result:"",error:ks(n)}}}i($d,"executeBuiltinFallback");var Nd=(r=>(r.CHAT="chat",r.SOFTWARE_DEVELOPMENT="software_development",r))(Nd||{}),Fd=45e3,Bc=6e4,Wc=1013,Ld=3e3,Dd=1500,Ud=8,_n="chat",jd=["shell_command"],Fi="8.51.0",qd="USER_ACTION_TRIGGERED_STOP",xs={READ_WRITE_FILES:1,READ_ONLY_GITLAB:2,READ_WRITE_GITLAB:3,RUN_COMMANDS:4,USE_GIT:5,RUN_MCP_TOOLS:6},Bd=[xs.READ_WRITE_FILES,xs.READ_ONLY_GITLAB,xs.READ_WRITE_GITLAB,xs.RUN_COMMANDS,xs.RUN_MCP_TOOLS,xs.USE_GIT],Wd="ide",Hd=1500*1e3,Hc=500;function Li(r){let e=r.length>Hc?r.slice(0,Hc)+"...":r;return ks(e)}i(Li,"sanitizeErrorText");var Gd="__chat_shared__",Jd=class{static{i(this,"GitLabWorkflowTokenClient")}config;fetchFn;tokenCache=new Map;constructor(r){this.config=r,this.fetchFn=r.fetch??fetch}getCacheKey(r,e){let t=r==="chat"?Gd:r;return e?`${t}:${e}`:t}async getToken(r=_n,e,t=!1){let s=Date.now(),n=this.getCacheKey(r,e),o=this.tokenCache.get(n);if(!t&&o&&o.expiresAt>s)return o.token;t&&this.tokenCache.delete(n);let a=`${this.config.instanceUrl}/api/v4/ai/duo_workflows/direct_access`,c={workflow_definition:r};e&&(c.root_namespace_id=e),this.config.featureFlags&&Object.keys(this.config.featureFlags).length>0&&(c.feature_flags=this.config.featureFlags);try{let l=await this.fetchFn(a,{method:"POST",headers:{...this.config.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){let f=await l.text(),d=Li(f);if(l.status===401&&this.config.refreshApiKey&&!t)try{return await this.config.refreshApiKey(),await this.getToken(r,e,!0)}catch(m){throw m instanceof A?m:new A({message:`Failed to get workflow token: ${l.status} ${l.statusText} - ${d}`,statusCode:l.status,responseBody:d,cause:m})}throw l.status===403?new A({message:"GitLab Duo Agent Platform access denied. GitLab Duo Agent Platform requires GitLab Ultimate with Duo Enterprise add-on. Ensure: (1) Your instance has GitLab Ultimate, (2) Duo Enterprise add-on is enabled, (3) Your account has access to AI features.",statusCode:l.status,responseBody:d}):new A({message:`Failed to get workflow token: ${l.status} ${l.statusText} - ${d}`,statusCode:l.status,responseBody:d})}let u=await l.json();return this.tokenCache.set(n,{token:u,expiresAt:s+Hd}),u}catch(l){throw l instanceof A?l:new A({message:`Failed to get workflow token: ${l}`,cause:l})}}async createWorkflow(r,e){if(!r||typeof r!="string")throw new A({message:"goal is required and must be a non-empty string"});if(r.length>1e4)throw new A({message:"goal exceeds maximum length of 10000 characters"});let t=`${this.config.instanceUrl}/api/v4/ai/duo_workflows/workflows`,s={goal:r,project_id:e?.projectId,namespace_id:e?.namespaceId,workflow_definition:e?.workflowDefinition??_n,agent_privileges:e?.agentPrivileges??Bd,environment:e?.environment??Wd,allow_agent_to_request_user:e?.allowAgentToRequestUser??!0,...e?.aiCatalogItemVersionId!==void 0&&{ai_catalog_item_version_id:e.aiCatalogItemVersionId}};try{let n=await this.fetchFn(t,{method:"POST",headers:{...this.config.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){let a=await n.text(),c=Li(a);throw new A({message:`Failed to create workflow: ${n.status} ${n.statusText} - ${c}`,statusCode:n.status,responseBody:c})}return(await n.json()).id.toString()}catch(n){throw n instanceof A?n:new A({message:`Failed to create workflow: ${n}`,cause:n})}}invalidateToken(r,e){r?this.tokenCache.delete(this.getCacheKey(r,e)):this.tokenCache.clear()}},Kd=Ie.object({headers:Ie.record(Ie.string()),token:Ie.string()}),Vd="https://cloud.gitlab.com",Zc=class{static{i(this,"GitLabDirectAccessClient")}config;fetchFn;aiGatewayUrl;cachedToken=null;tokenExpiresAt=0;constructor(r){this.config=r,this.fetchFn=r.fetch??fetch,this.aiGatewayUrl=r.aiGatewayUrl||process.env.GITLAB_AI_GATEWAY_URL||Vd}async getDirectAccessToken(r=!1){let e=Date.now();if(!r&&this.cachedToken&&this.tokenExpiresAt>e)return this.cachedToken;r&&this.invalidateToken();let t=`${this.config.instanceUrl}/api/v4/ai/third_party_agents/direct_access`,s={};this.config.featureFlags&&Object.keys(this.config.featureFlags).length>0&&(s.feature_flags=this.config.featureFlags),this.config.ensureApiKey&&await this.config.ensureApiKey();try{let n=await this.fetchFn(t,{method:"POST",headers:{...this.config.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){let c=await n.text(),l=Li(c);if(n.status===401&&this.config.refreshApiKey&&!r)try{return await this.config.refreshApiKey(),await this.getDirectAccessToken(!0)}catch(u){throw u instanceof A?u:new A({message:`Failed to get direct access token: ${n.status} ${n.statusText} - ${l}`,statusCode:n.status,responseBody:l,cause:u})}throw n.status===403?new A({message:`Access denied to GitLab AI features (${this.config.instanceUrl}). This may indicate that: (1) GitLab Duo is not enabled on this instance, (2) Your account does not have access to AI features, or (3) The third-party agents feature is not available. Original error: ${n.status} ${n.statusText} - ${l}`,statusCode:n.status,responseBody:l}):new A({message:`Failed to get direct access token: ${n.status} ${n.statusText} - ${l}`,statusCode:n.status,responseBody:l})}let o=await n.json(),a=Kd.parse(o);return this.cachedToken=a,this.tokenExpiresAt=e+1500*1e3,a}catch(n){throw n instanceof A?n:new A({message:`Failed to get direct access token: ${n}`,cause:n})}}getAnthropicProxyUrl(){return`${this.aiGatewayUrl.replace(/\/$/,"")}/ai/v1/proxy/anthropic/`}getOpenAIProxyUrl(){return`${this.aiGatewayUrl.replace(/\/$/,"")}/ai/v1/proxy/openai/v1`}invalidateToken(){this.cachedToken=null,this.tokenExpiresAt=0}},Xd=class{static{i(this,"GitLabAnthropicLanguageModel")}specificationVersion="v3";modelId;supportedUrls={};config;directAccessClient;anthropicClient=null;constructor(r,e){this.modelId=r,this.config=e,this.directAccessClient=new Zc({instanceUrl:e.instanceUrl,getHeaders:e.getHeaders,ensureApiKey:e.ensureApiKey,refreshApiKey:e.refreshApiKey,fetch:e.fetch,featureFlags:e.featureFlags,aiGatewayUrl:e.aiGatewayUrl})}get provider(){return this.config.provider}async getAnthropicClient(r=!1){let e=await this.directAccessClient.getDirectAccessToken(r),{"x-api-key":t,...s}=e.headers,n={...s,...this.config.aiGatewayHeaders};return this.anthropicClient=new he({apiKey:null,authToken:e.token,baseURL:this.directAccessClient.getAnthropicProxyUrl(),defaultHeaders:n}),this.anthropicClient}isTokenError(r){if(r instanceof he.APIError){if(r.status===401)return!0;let e=r.message?.toLowerCase()||"";if(e.includes("token")&&(e.includes("expired")||e.includes("revoked")||e.includes("invalid")))return!0}return!1}isContextOverflowError(r){if(r instanceof he.APIError&&r.status===400){let e=r.message?.toLowerCase()||"";if(e.includes("prompt is too long")||e.includes("prompt too long")||e.includes("tokens")&&e.includes("maximum"))return!0}return!1}convertTools(r){if(!(!r||r.length===0))return r.filter(e=>e.type==="function").map(e=>{let t=e.inputSchema;return{name:e.name,description:e.description||"",input_schema:{type:"object",properties:t?.properties||{},required:t?.required||[]}}})}convertToolChoice(r){if(r)switch(r.type){case"auto":return{type:"auto"};case"none":return;case"required":return{type:"any"};case"tool":return{type:"tool",name:r.toolName};default:return}}convertPrompt(r){let e,t=[];for(let o of r){if(o.role==="system"){e=e?`${e}
|
|
85
|
+
${o.content}`:o.content;continue}if(o.role==="user"){let a=[];for(let c of o.content)c.type==="text"?a.push({type:"text",text:c.text}):c.type;a.length>0&&t.push({role:"user",content:a})}else if(o.role==="assistant"){let a=[];for(let c of o.content)if(c.type==="reasoning"){let l=this.convertReasoningPart(c);l&&a.push(l)}else if(c.type==="text")a.push({type:"text",text:c.text});else if(c.type==="tool-call"){let l=c.input;if(typeof c.input=="string")try{l=JSON.parse(c.input)}catch{l={}}a.push({type:"tool_use",id:c.toolCallId,name:c.toolName,input:l})}a.length>0&&t.push({role:"assistant",content:a})}else if(o.role==="tool"){let a=[];for(let c of o.content)if(c.type==="tool-result"){let l;c.output.type==="text"?l=c.output.value:c.output.type==="json"||c.output.type==="content"?l=JSON.stringify(c.output.value):c.output.type==="error-text"?l=c.output.value:c.output.type==="error-json"?l=JSON.stringify(c.output.value):c.output.type==="execution-denied"?l=c.output.reason??"Tool execution denied.":l=JSON.stringify(c.output),a.push({type:"tool_result",tool_use_id:c.toolCallId,content:l,is_error:c.output.type.startsWith("error")})}a.length>0&&t.push({role:"user",content:a})}}let s=e?[{type:"text",text:e,cache_control:{type:"ephemeral"}}]:void 0,n=Math.min(2,t.length);for(let o=t.length-n;o<t.length;o++){let a=t[o];if(Array.isArray(a.content)&&a.content.length>0){let c=a.content[a.content.length-1];c.cache_control={type:"ephemeral"}}}return{system:s,messages:t}}convertFinishReason(r){return{unified:(()=>{switch(r){case"end_turn":return"stop";case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return"other"}})(),raw:r??void 0}}createUsage(r){let e=r?.inputTotal,t=r?.outputTotal,s=r?.cacheRead,n=r?.cacheWrite;return{inputTokens:{total:e!=null?e+(s??0)+(n??0):void 0,noCache:e,cacheRead:s,cacheWrite:n},outputTokens:{total:t,text:t!=null?t-(r?.outputReasoning??0):void 0,reasoning:r?.outputReasoning},raw:r?.raw}}buildThinkingParams(r){return r?r.type==="adaptive"?{thinking:{type:"adaptive",display:"summarized"},output_config:{effort:r.effort}}:r.type==="enabled"?{thinking:{type:"enabled",budget_tokens:r.budgetTokens}}:{thinking:{type:"disabled"}}:{}}resolveThinkingConfig(r){return r.providerOptions?.gitlab?.thinking??this.config.thinking}validateThinkingConfig(r,e){if(r?.type==="enabled"&&r.budgetTokens>=e)throw new A({message:`Anthropic thinking budgetTokens (${r.budgetTokens}) must be less than maxTokens (${e}).`,statusCode:400})}convertReasoningPart(r){let e=r.providerOptions?.gitlab,t=e?.redactedData;if(typeof t=="string")return{type:"redacted_thinking",data:t};let s=e?.signature;if(typeof s=="string")return{type:"thinking",thinking:r.text,signature:s}}isThinkingActive(r){return r?.type==="enabled"||r?.type==="adaptive"}buildSamplingParams(r,e){let t={},s=this.isThinkingActive(e);return r.temperature!=null&&!s&&(t.temperature=r.temperature),r.topP!=null&&(!s||r.topP>=.95&&r.topP<=1)&&(t.top_p=r.topP),t}async doGenerate(r){return this.doGenerateWithRetry(r,!1)}async doGenerateWithRetry(r,e){let{system:t,messages:s}=this.convertPrompt(r.prompt),n=r.toolChoice?.type==="none",o=n?void 0:this.convertTools(r.tools),a=n?void 0:this.convertToolChoice(r.toolChoice),c=this.config.anthropicModel||"claude-sonnet-4-5-20250929",l=r.maxOutputTokens||this.config.maxTokens||8192,u=this.resolveThinkingConfig(r);this.validateThinkingConfig(u,l);let f=await this.getAnthropicClient(e),d={model:c,max_tokens:l,system:t,messages:s,tools:o,tool_choice:o?a:void 0,...this.buildSamplingParams(r,u),stop_sequences:r.stopSequences,...this.buildThinkingParams(u)};try{let m=r.abortSignal?await f.messages.create(d,{signal:r.abortSignal}):await f.messages.create(d),h=[];for(let k of m.content)k.type==="thinking"?h.push({type:"reasoning",text:k.thinking,providerMetadata:{gitlab:{signature:k.signature}}}):k.type==="redacted_thinking"?h.push({type:"reasoning",text:"",providerMetadata:{gitlab:{redactedData:k.data}}}):k.type==="text"?h.push({type:"text",text:k.text}):k.type==="tool_use"&&h.push({type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input)});let x=m.usage,y=this.createUsage({inputTotal:m.usage.input_tokens,outputTotal:m.usage.output_tokens,cacheRead:x.cache_read_input_tokens,cacheWrite:x.cache_creation_input_tokens});return{content:h,finishReason:this.convertFinishReason(m.stop_reason),usage:y,warnings:[]}}catch(m){if(this.isContextOverflowError(m)){let h=m;throw new A({message:`Context overflow: ${h.message}. Please start a new session or use /compact to reduce context.`,statusCode:400,cause:m})}if(!e&&this.isTokenError(m))return this.directAccessClient.invalidateToken(),this.doGenerateWithRetry(r,!0);throw m instanceof he.APIError?new A({message:`Anthropic API error: ${m.message}`,statusCode:m.status,cause:m}):m}}async doStream(r){return this.doStreamWithRetry(r,!1)}async doStreamWithRetry(r,e){let{system:t,messages:s}=this.convertPrompt(r.prompt),n=r.toolChoice?.type==="none",o=n?void 0:this.convertTools(r.tools),a=n?void 0:this.convertToolChoice(r.toolChoice),c=this.config.anthropicModel||"claude-sonnet-4-5-20250929",l=r.maxOutputTokens||this.config.maxTokens||8192,u=this.resolveThinkingConfig(r);this.validateThinkingConfig(u,l);let f=await this.getAnthropicClient(e),d={model:c,max_tokens:l,system:t,messages:s,tools:o,tool_choice:o?a:void 0,...this.buildSamplingParams(r,u),stop_sequences:r.stopSequences,...this.buildThinkingParams(u),stream:!0},m=this,h=new AbortController;r.abortSignal&&(r.abortSignal.aborted?h.abort(r.abortSignal.reason):r.abortSignal.addEventListener("abort",()=>h.abort(r.abortSignal?.reason)));let x=!1;return{stream:new ReadableStream({cancel:i(()=>{x=!0,h.abort()},"cancel"),start:i(async k=>{let I=i(M=>{if(!x)try{k.enqueue(M)}catch{x=!0}},"safeEnqueue"),b=i(()=>{if(!x){x=!0;try{k.close()}catch{}}},"safeClose"),L={},T=m.createUsage(),W={unified:"other",raw:void 0},B=!1,U=!1,H=i(()=>{for(let[M,v]of Object.entries(L))v.type==="tool-call"&&(I({type:"tool-input-end",id:v.toolCallId}),I({type:"tool-call",toolCallId:v.toolCallId,toolName:v.toolName,input:v.input===""?"{}":v.input})),delete L[Number(M)]},"flushPendingToolCalls");try{let M=f.messages.stream(d,{signal:h.signal});I({type:"stream-start",warnings:[]}),await new Promise((v,D)=>{M.on("streamEvent",O=>{try{switch(O.type){case"message_start":if(O.message.usage){let C=O.message.usage;T=m.createUsage({inputTotal:C.input_tokens,outputTotal:T.outputTokens.total,outputReasoning:T.outputTokens.reasoning,cacheRead:C.cache_read_input_tokens,cacheWrite:C.cache_creation_input_tokens,raw:T.raw})}I({type:"response-metadata",id:O.message.id,modelId:O.message.model});break;case"content_block_start":if(U=!0,O.content_block.type==="text"){let C=`text-${O.index}`;L[O.index]={type:"text",id:C},I({type:"text-start",id:C})}else if(O.content_block.type==="thinking"){let C=`reasoning-${O.index}`;L[O.index]={type:"reasoning",id:C},I({type:"reasoning-start",id:C})}else if(O.content_block.type==="redacted_thinking"){let C=`reasoning-${O.index}`;L[O.index]={type:"reasoning",id:C,redactedData:O.content_block.data},I({type:"reasoning-start",id:C})}else O.content_block.type==="tool_use"&&(L[O.index]={type:"tool-call",toolCallId:O.content_block.id,toolName:O.content_block.name,input:""},I({type:"tool-input-start",id:O.content_block.id,toolName:O.content_block.name}));break;case"content_block_delta":{let C=L[O.index];O.delta.type==="text_delta"&&C?.type==="text"?I({type:"text-delta",id:C.id,delta:O.delta.text}):O.delta.type==="thinking_delta"&&C?.type==="reasoning"?I({type:"reasoning-delta",id:C.id,delta:O.delta.thinking}):O.delta.type==="signature_delta"&&C?.type==="reasoning"?C.signature=O.delta.signature:O.delta.type==="input_json_delta"&&C?.type==="tool-call"&&(C.input+=O.delta.partial_json,I({type:"tool-input-delta",id:C.toolCallId,delta:O.delta.partial_json}));break}case"content_block_stop":{let C=L[O.index];if(C?.type==="text")I({type:"text-end",id:C.id});else if(C?.type==="reasoning"){let G=C.redactedData!=null?{redactedData:C.redactedData}:C.signature!=null?{signature:C.signature}:void 0;I({type:"reasoning-end",id:C.id,...G&&{providerMetadata:{gitlab:G}}})}else C?.type==="tool-call"&&(I({type:"tool-input-end",id:C.toolCallId}),I({type:"tool-call",toolCallId:C.toolCallId,toolName:C.toolName,input:C.input===""?"{}":C.input}));delete L[O.index];break}case"message_delta":if(O.usage){let C=O.usage;T=m.createUsage({inputTotal:T.inputTokens.noCache,outputTotal:C.output_tokens,outputReasoning:T.outputTokens.reasoning,cacheRead:C.cache_read_input_tokens??T.inputTokens.cacheRead,cacheWrite:C.cache_creation_input_tokens??T.inputTokens.cacheWrite,raw:T.raw})}O.delta.stop_reason&&(W=m.convertFinishReason(O.delta.stop_reason));break;case"message_stop":{H(),B=!0,I({type:"finish",finishReason:W,usage:T});break}}}catch(C){I({type:"error",error:C instanceof Error?C:new Error(String(C))})}}),M.on("end",()=>{v()}),M.on("error",O=>{D(O)})}),H(),B||(B=!0,I({type:"finish",finishReason:W,usage:T})),b()}catch(M){if(H(),m.isContextOverflowError(M)){let v=M;I({type:"error",error:new A({message:`Context overflow: ${v.message}. Please start a new session or use /compact to reduce context.`,statusCode:400,cause:M})}),b();return}if(!e&&m.isTokenError(M)){if(m.directAccessClient.invalidateToken(),!U)try{let D=(await m.doStreamWithRetry(r,!0)).stream.getReader();for(;;){let{done:O,value:C}=await D.read();if(O)break;C.type!=="stream-start"&&I(C)}b();return}catch(v){I({type:"error",error:v instanceof A?v:new A({message:"Token refresh retry failed",cause:v})}),b();return}I({type:"error",error:new A({message:"TOKEN_REFRESH_NEEDED",cause:M})}),b();return}M instanceof he.APIError?I({type:"error",error:new A({message:`Anthropic API error: ${M.message}`,statusCode:M.status,cause:M})}):I({type:"error",error:M}),b()}},"start")}),request:{body:d}}}},qe={"duo-chat-fable-5-1":{provider:"anthropic",model:"claude-fable-5-1"},"duo-chat-fable-5":{provider:"anthropic",model:"claude-fable-5"},"duo-chat-opus-5-5":{provider:"anthropic",model:"claude-opus-5-5"},"duo-chat-opus-5":{provider:"anthropic",model:"claude-opus-5"},"duo-chat-opus-4-8":{provider:"anthropic",model:"claude-opus-4-8"},"duo-chat-opus-4-7":{provider:"anthropic",model:"claude-opus-4-7"},"duo-chat-opus-4-6":{provider:"anthropic",model:"claude-opus-4-6"},"duo-chat-sonnet-5-5":{provider:"anthropic",model:"claude-sonnet-5-5"},"duo-chat-sonnet-5":{provider:"anthropic",model:"claude-sonnet-5"},"duo-chat-sonnet-4-6":{provider:"anthropic",model:"claude-sonnet-4-6"},"duo-chat-opus-4-5":{provider:"anthropic",model:"claude-opus-4-5-20251101"},"duo-chat-sonnet-4-5":{provider:"anthropic",model:"claude-sonnet-4-5-20250929"},"duo-chat-haiku-4-5":{provider:"anthropic",model:"claude-haiku-4-5-20251001"},"duo-chat-gpt-6-astra":{provider:"openai",model:"gpt-6-astra",openaiApiType:"responses"},"duo-chat-gpt-6-1-sol":{provider:"openai",model:"gpt-6.1-sol",openaiApiType:"responses"},"duo-chat-gpt-6-sol":{provider:"openai",model:"gpt-6-sol",openaiApiType:"responses"},"duo-chat-gpt-6-luna":{provider:"openai",model:"gpt-6-luna",openaiApiType:"responses"},"duo-chat-gpt-5-1":{provider:"openai",model:"gpt-5.1-2025-11-13",openaiApiType:"chat"},"duo-chat-gpt-5-2":{provider:"openai",model:"gpt-5.2-2025-12-11",openaiApiType:"chat"},"duo-chat-gpt-5-4":{provider:"openai",model:"gpt-5.4-2026-03-05",openaiApiType:"chat"},"duo-chat-gpt-5-5":{provider:"openai",model:"gpt-5.5-2026-04-23",openaiApiType:"chat"},"duo-chat-gpt-5-mini":{provider:"openai",model:"gpt-5-mini-2025-08-07",openaiApiType:"chat"},"duo-chat-gpt-5-4-mini":{provider:"openai",model:"gpt-5.4-mini",openaiApiType:"chat"},"duo-chat-gpt-5-4-nano":{provider:"openai",model:"gpt-5.4-nano",openaiApiType:"chat"},"duo-chat-gpt-5-6-sol":{provider:"openai",model:"gpt-5.6-sol",openaiApiType:"responses"},"duo-chat-gpt-5-6-terra":{provider:"openai",model:"gpt-5.6-terra",openaiApiType:"responses"},"duo-chat-gpt-5-6-luna":{provider:"openai",model:"gpt-5.6-luna",openaiApiType:"responses"},"duo-chat-gpt-5-codex":{provider:"openai",model:"gpt-5-codex",openaiApiType:"responses"},"duo-chat-gpt-5-2-codex":{provider:"openai",model:"gpt-5.2-codex",openaiApiType:"responses"},"duo-chat-gpt-5-3-codex":{provider:"openai",model:"gpt-5.3-codex",openaiApiType:"responses"},"duo-workflow":{provider:"workflow",model:"default"},"duo-workflow-default":{provider:"workflow",model:"default"},"duo-workflow-sonnet-4-5":{provider:"workflow",model:"claude_sonnet_4_5_20250929"},"duo-workflow-sonnet-5-5":{provider:"workflow",model:"claude_sonnet_5_5"},"duo-workflow-sonnet-5":{provider:"workflow",model:"claude_sonnet_5"},"duo-workflow-opus-5-5":{provider:"workflow",model:"claude_opus_5_5"},"duo-workflow-opus-5":{provider:"workflow",model:"claude_opus_5"},"duo-workflow-sonnet-4-6":{provider:"workflow",model:"claude_sonnet_4_6"},"duo-workflow-opus-4-5":{provider:"workflow",model:"claude_opus_4_5_20251101"},"duo-workflow-haiku-4-5":{provider:"workflow",model:"claude_haiku_4_5_20251001"},"duo-workflow-opus-4-6":{provider:"workflow",model:"claude_opus_4_6_20260205"}};function Gc(r){return qe[r]}i(Gc,"getModelMapping");function Pv(r){return qe[r]?.provider}i(Pv,"getProviderForModelId");function zd(r){return Object.values(qe).filter(e=>e.provider===r).map(e=>e.model)}i(zd,"getValidModelsForProvider");function Rv(r){let e=qe[r];return e?.provider==="anthropic"?e.model:void 0}i(Rv,"getAnthropicModelForModelId");function Ev(r){let e=qe[r];return e?.provider==="openai"?e.model:void 0}i(Ev,"getOpenAIModelForModelId");function Yd(r){return qe[r]?.openaiApiType??"chat"}i(Yd,"getOpenAIApiType");function Qd(r){return Yd(r)==="responses"}i(Qd,"isResponsesApiModel");function Zd(r){return qe[r]?.provider==="workflow"}i(Zd,"isWorkflowModel");function ef(r){let e=qe[r];return e?.provider==="workflow"?e.model:void 0}i(ef,"getWorkflowModelRef");var Cv=Object.fromEntries(Object.entries(qe).filter(([,r])=>r.provider==="anthropic").map(([r,e])=>[r,e.model])),tf=class{static{i(this,"GitLabOpenAILanguageModel")}specificationVersion="v3";modelId;supportedUrls={};config;directAccessClient;useResponsesApi;openaiClient=null;constructor(r,e){this.modelId=r,this.config=e,this.useResponsesApi=e.useResponsesApi??Qd(r),this.directAccessClient=new Zc({instanceUrl:e.instanceUrl,getHeaders:e.getHeaders,ensureApiKey:e.ensureApiKey,refreshApiKey:e.refreshApiKey,fetch:e.fetch,featureFlags:e.featureFlags,aiGatewayUrl:e.aiGatewayUrl})}get provider(){return this.config.provider}async getOpenAIClient(r=!1){let e=await this.directAccessClient.getDirectAccessToken(r),{"x-api-key":t,...s}=e.headers,n={...s,...this.config.aiGatewayHeaders};return this.openaiClient=new F({apiKey:e.token,baseURL:this.directAccessClient.getOpenAIProxyUrl(),defaultHeaders:n}),this.openaiClient}isTokenError(r){if(r instanceof F.APIError){if(r.status===401)return!0;let e=r.message?.toLowerCase()||"";if(e.includes("token")&&(e.includes("expired")||e.includes("revoked")||e.includes("invalid")))return!0}return!1}isContextOverflowError(r){if(r instanceof F.APIError&&r.status===400){let e=r.message?.toLowerCase()||"";if(e.includes("prompt is too long")||e.includes("prompt too long")||e.includes("tokens")&&e.includes("maximum"))return!0}return!1}formatOpenAIError(r,e){let t=[`OpenAI API error: ${r.message}`],s=r.error;if(s){let c=typeof s=="string"?s:s.message??s.detail??s.error;c&&!r.message.includes(String(c))&&t.push(`detail: ${typeof c=="string"?c:JSON.stringify(c)}`)}let n=r.headers,o=typeof n?.get=="function"?n.get("x-request-id")??n.get("x-amzn-requestid"):void 0;o&&t.push(`request-id: ${o}`);let a=r.message?.includes("no body");return r.status!=null&&r.status>=400&&a&&e!=null&&e>20&&t.push(`Hint: the request included ${e} tools; the GitLab AI Gateway may reject large tool sets \u2014 try reducing the number of enabled tools or MCP servers.`),t.join(" | ")}resolveReasoningEffort(r){return r.providerOptions?.gitlab?.reasoningEffort??this.config.reasoningEffort}asOpenAIReasoningEffort(r){return r}convertTools(r){if(!(!r||r.length===0))return r.filter(e=>e.type==="function").map(e=>{let t=e.inputSchema;return{type:"function",function:{name:e.name,description:e.description||"",parameters:{type:"object",...t}}}})}convertToolChoice(r){if(r)switch(r.type){case"auto":return"auto";case"none":return"none";case"required":return"required";case"tool":return{type:"function",function:{name:r.toolName}};default:return}}convertPrompt(r){let e=[];for(let t of r){if(t.role==="system"){e.push({role:"system",content:t.content});continue}if(t.role==="user"){let s=t.content.filter(n=>n.type==="text").map(n=>n.text);s.length>0&&e.push({role:"user",content:s.join(`
|
|
86
|
+
`)})}else if(t.role==="assistant"){let s=[],n=[];for(let a of t.content)a.type==="text"?s.push(a.text):a.type==="tool-call"&&n.push({id:a.toolCallId,type:"function",function:{name:a.toolName,arguments:typeof a.input=="string"?a.input:JSON.stringify(a.input)}});let o={role:"assistant",content:s.length>0?s.join(`
|
|
87
|
+
`):null};n.length>0&&(o.tool_calls=n),e.push(o)}else if(t.role==="tool"){for(let s of t.content)if(s.type==="tool-result"){let n;s.output.type==="text"?n=s.output.value:s.output.type==="json"||s.output.type==="content"?n=JSON.stringify(s.output.value):s.output.type==="error-text"?n=s.output.value:s.output.type==="error-json"?n=JSON.stringify(s.output.value):s.output.type==="execution-denied"?n=s.output.reason??"Tool execution denied.":n=JSON.stringify(s.output),e.push({role:"tool",tool_call_id:s.toolCallId,content:n})}}}return e}convertFinishReason(r){return{unified:(()=>{switch(r){case"stop":return"stop";case"length":return"length";case"tool_calls":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}})(),raw:r??void 0}}createUsage(r){let e=r?.inputTotal,t=r?.outputTotal,s=r?.cacheRead;return{inputTokens:{total:e,noCache:e==null?void 0:Math.max(0,e-(s??0)),cacheRead:s,cacheWrite:void 0},outputTokens:{total:t,text:t!=null?t-(r?.outputReasoning??0):void 0,reasoning:r?.outputReasoning},raw:r?.raw}}convertToolsForResponses(r){if(!(!r||r.length===0))return r.filter(e=>e.type==="function").map(e=>{let t={...e.inputSchema};return delete t.$schema,{type:"function",name:e.name,description:e.description||"",parameters:t,strict:e.strict}})}convertPromptForResponses(r){let e=[];for(let t of r)if(t.role!=="system"){if(t.role==="user"){let s=t.content.filter(n=>n.type==="text").map(n=>n.text);s.length>0&&e.push({type:"message",role:"user",content:s.map(n=>({type:"input_text",text:n}))})}else if(t.role==="assistant"){let s=[];for(let n of t.content)n.type==="text"?s.push(n.text):n.type==="tool-call"&&e.push({type:"function_call",call_id:n.toolCallId,name:n.toolName,arguments:typeof n.input=="string"?n.input:JSON.stringify(n.input)});s.length>0&&e.push({type:"message",role:"assistant",content:[{type:"output_text",text:s.join(`
|
|
88
|
+
`),annotations:[]}]})}else if(t.role==="tool"){for(let s of t.content)if(s.type==="tool-result"){let n;s.output.type==="text"?n=s.output.value:s.output.type==="json"||s.output.type==="content"?n=JSON.stringify(s.output.value):s.output.type==="error-text"?n=s.output.value:s.output.type==="error-json"?n=JSON.stringify(s.output.value):s.output.type==="execution-denied"?n=s.output.reason??"Tool execution denied.":n=JSON.stringify(s.output),e.push({type:"function_call_output",call_id:s.toolCallId,output:n})}}}return e}extractSystemInstructions(r){return r.filter(t=>t.role==="system").map(t=>t.content).join(`
|
|
89
|
+
`)||void 0}convertResponsesStatus(r,e=!1){return e?{unified:"tool-calls",raw:r}:{unified:(()=>{switch(r){case"completed":return"stop";case"incomplete":return"length";case"cancelled":return"stop";case"failed":return"error";default:return"other"}})(),raw:r}}async doGenerate(r){return this.useResponsesApi?this.doGenerateWithResponsesApi(r,!1):this.doGenerateWithChatApi(r,!1)}async doGenerateWithChatApi(r,e){let t=await this.getOpenAIClient(e),s=this.convertPrompt(r.prompt),n=r.toolChoice?.type==="none",o=n?void 0:this.convertTools(r.tools),a=n?void 0:this.convertToolChoice(r.toolChoice),c=this.config.openaiModel||"gpt-4o",l=r.maxOutputTokens||this.config.maxTokens||8192,u=this.resolveReasoningEffort(r),f={model:c,max_completion_tokens:l,messages:s,tools:o,tool_choice:o?a:void 0,temperature:r.temperature,top_p:r.topP,stop:r.stopSequences,...u&&{reasoning_effort:this.asOpenAIReasoningEffort(u)}};try{let d=r.abortSignal?await t.chat.completions.create(f,{signal:r.abortSignal}):await t.chat.completions.create(f),m=d.choices[0],h=[];if(m?.message.content&&h.push({type:"text",text:m.message.content}),m?.message.tool_calls)for(let y of m.message.tool_calls)y.type==="function"&&h.push({type:"tool-call",toolCallId:y.id,toolName:y.function.name,input:y.function.arguments});let x=this.createUsage({inputTotal:d.usage?.prompt_tokens,outputTotal:d.usage?.completion_tokens,cacheRead:d.usage?.prompt_tokens_details?.cached_tokens,raw:{total_tokens:d.usage?.total_tokens}});return{content:h,finishReason:this.convertFinishReason(m?.finish_reason),usage:x,warnings:[]}}catch(d){if(this.isContextOverflowError(d)){let m=d;throw new A({message:`Context overflow: ${m.message}. Please start a new session or use /compact to reduce context.`,statusCode:400,cause:d})}if(!e&&this.isTokenError(d))return this.directAccessClient.invalidateToken(),this.doGenerateWithChatApi(r,!0);throw d instanceof F.APIError?new A({message:this.formatOpenAIError(d,o?.length),statusCode:d.status,cause:d}):d}}async doGenerateWithResponsesApi(r,e){let t=await this.getOpenAIClient(e),s=this.convertPromptForResponses(r.prompt),n=r.toolChoice?.type==="none"?void 0:this.convertToolsForResponses(r.tools),o=this.extractSystemInstructions(r.prompt),a=this.config.openaiModel||"gpt-5-codex",c=r.maxOutputTokens||this.config.maxTokens||8192,l=this.resolveReasoningEffort(r),u={model:a,input:s,instructions:o,tools:n,max_output_tokens:c,temperature:r.temperature,top_p:r.topP,store:!1,...l&&{reasoning:{effort:this.asOpenAIReasoningEffort(l),summary:"auto"}}};try{let f=r.abortSignal?await t.responses.create(u,{signal:r.abortSignal}):await t.responses.create(u),d=[],m=!1;for(let x of f.output||[])if(x.type==="message"&&x.role==="assistant")for(let y of x.content||[])y.type==="output_text"&&d.push({type:"text",text:y.text});else if(x.type==="function_call")m=!0,d.push({type:"tool-call",toolCallId:x.call_id,toolName:x.name,input:x.arguments});else if(x.type==="reasoning")for(let y of x.summary||[])y.type==="summary_text"&&y.text&&d.push({type:"reasoning",text:y.text});let h=this.createUsage({inputTotal:f.usage?.input_tokens,outputTotal:f.usage?.output_tokens,outputReasoning:f.usage?.output_tokens_details?.reasoning_tokens,cacheRead:f.usage?.input_tokens_details?.cached_tokens,raw:{total_tokens:f.usage?.total_tokens}});return{content:d,finishReason:this.convertResponsesStatus(f.status,m),usage:h,warnings:[]}}catch(f){if(this.isContextOverflowError(f)){let d=f;throw new A({message:`Context overflow: ${d.message}. Please start a new session or use /compact to reduce context.`,statusCode:400,cause:f})}if(!e&&this.isTokenError(f))return this.directAccessClient.invalidateToken(),this.doGenerateWithResponsesApi(r,!0);throw f instanceof F.APIError?new A({message:this.formatOpenAIError(f,n?.length),statusCode:f.status,cause:f}):f}}async doStream(r){return this.useResponsesApi?this.doStreamWithResponsesApi(r,!1):this.doStreamWithChatApi(r,!1)}async doStreamWithChatApi(r,e){let t=await this.getOpenAIClient(e),s=this.convertPrompt(r.prompt),n=r.toolChoice?.type==="none",o=n?void 0:this.convertTools(r.tools),a=n?void 0:this.convertToolChoice(r.toolChoice),c=this.config.openaiModel||"gpt-4o",l=r.maxOutputTokens||this.config.maxTokens||8192,u=this.resolveReasoningEffort(r),f={model:c,max_completion_tokens:l,messages:s,tools:o,tool_choice:o?a:void 0,temperature:r.temperature,top_p:r.topP,stop:r.stopSequences,...u&&{reasoning_effort:this.asOpenAIReasoningEffort(u)},stream:!0,stream_options:{include_usage:!0}},d=this,m=new AbortController;r.abortSignal&&(r.abortSignal.aborted?m.abort(r.abortSignal.reason):r.abortSignal.addEventListener("abort",()=>m.abort(r.abortSignal?.reason)));let h=!1;return{stream:new ReadableStream({cancel:i(()=>{h=!0,m.abort()},"cancel"),start:i(async y=>{let k=i(M=>{if(!h)try{y.enqueue(M)}catch{h=!0}},"safeEnqueue"),I=i(()=>{if(!h){h=!0;try{y.close()}catch{}}},"safeClose"),b={},L=d.createUsage(),T={unified:"other",raw:void 0},W=!1,B=!1,U=!1,H="text-0";try{let M=await t.chat.completions.create({...f,stream:!0},{signal:m.signal});k({type:"stream-start",warnings:[]});for await(let v of M){let D=v.choices?.[0];if(v.id&&!B&&(B=!0,k({type:"response-metadata",id:v.id,modelId:v.model})),D?.delta?.content&&(U=!0,W||(k({type:"text-start",id:H}),W=!0),k({type:"text-delta",id:H,delta:D.delta.content})),D?.delta?.tool_calls){U=!0;for(let O of D.delta.tool_calls){let C=O.index;b[C]?(O.id&&!b[C].id&&(b[C].id=O.id),O.function?.name&&!b[C].name&&(b[C].name=O.function.name)):(b[C]={id:O.id||"",name:O.function?.name||"",arguments:""},k({type:"tool-input-start",id:b[C].id,toolName:b[C].name})),O.function?.arguments&&(b[C].arguments+=O.function.arguments,k({type:"tool-input-delta",id:b[C].id,delta:O.function.arguments}))}}D?.finish_reason&&(T=d.convertFinishReason(D.finish_reason)),v.usage&&(L=d.createUsage({inputTotal:v.usage.prompt_tokens,outputTotal:v.usage.completion_tokens,cacheRead:v.usage.prompt_tokens_details?.cached_tokens,raw:{total_tokens:v.usage.total_tokens}}))}W&&k({type:"text-end",id:H});for(let[,v]of Object.entries(b))k({type:"tool-input-end",id:v.id}),k({type:"tool-call",toolCallId:v.id,toolName:v.name,input:v.arguments||"{}"});k({type:"finish",finishReason:T,usage:L}),I()}catch(M){if(d.isContextOverflowError(M)){let v=M;k({type:"error",error:new A({message:`Context overflow: ${v.message}. Please start a new session or use /compact to reduce context.`,statusCode:400,cause:M})}),I();return}if(!e&&d.isTokenError(M)){if(d.directAccessClient.invalidateToken(),!U)try{let D=(await d.doStreamWithChatApi(r,!0)).stream.getReader();for(;;){let{done:O,value:C}=await D.read();if(O)break;C.type!=="stream-start"&&k(C)}I();return}catch(v){k({type:"error",error:v instanceof A?v:new A({message:"Token refresh retry failed",cause:v})}),I();return}k({type:"error",error:new A({message:"TOKEN_REFRESH_NEEDED",cause:M})}),I();return}M instanceof F.APIError?k({type:"error",error:new A({message:d.formatOpenAIError(M,o?.length),statusCode:M.status,cause:M})}):k({type:"error",error:M}),I()}},"start")}),request:{body:f}}}async doStreamWithResponsesApi(r,e){let t=await this.getOpenAIClient(e),s=this.convertPromptForResponses(r.prompt),n=r.toolChoice?.type==="none"?void 0:this.convertToolsForResponses(r.tools),o=this.extractSystemInstructions(r.prompt),a=this.config.openaiModel||"gpt-5-codex",c=r.maxOutputTokens||this.config.maxTokens||8192,l=this.resolveReasoningEffort(r),u={model:a,input:s,instructions:o,tools:n,max_output_tokens:c,temperature:r.temperature,top_p:r.topP,store:!1,...l&&{reasoning:{effort:this.asOpenAIReasoningEffort(l),summary:"auto"}},stream:!0},f=this,d=new AbortController;r.abortSignal&&(r.abortSignal.aborted?d.abort(r.abortSignal.reason):r.abortSignal.addEventListener("abort",()=>d.abort(r.abortSignal?.reason)));let m=!1;return{stream:new ReadableStream({cancel:i(()=>{m=!0,d.abort()},"cancel"),start:i(async x=>{let y=i(G=>{if(!m)try{x.enqueue(G)}catch{m=!0}},"safeEnqueue"),k=i(()=>{if(!m){m=!0;try{x.close()}catch{}}},"safeClose"),I={},b=new Set,L=new Set,T=new Set,W=f.createUsage(),B={unified:"other",raw:void 0},U=!1,H=!1,M="text-0",v=i((G,Q)=>`reasoning-${G}-${Q}`,"reasoningId"),D=i((G,Q)=>{let P=v(G,Q);return L.has(P)||(L.add(P),b.add(P),H=!0,y({type:"reasoning-start",id:P})),P},"startReasoning"),O=i((G,Q,P)=>{let V=D(G,Q);b.has(V)&&P&&(T.add(V),y({type:"reasoning-delta",id:V,delta:P}))},"emitReasoningDelta"),C=i((G,Q)=>{let P=v(G,Q);b.delete(P)&&y({type:"reasoning-end",id:P})},"endReasoning");try{let G=await t.responses.create({...u,stream:!0},{signal:d.signal});y({type:"stream-start",warnings:[]});for await(let P of G)if(P.type==="response.created")y({type:"response-metadata",id:P.response.id,modelId:P.response.model});else if(P.type==="response.output_item.added"){if(P.item.type==="function_call"){H=!0;let V=P.output_index,se=P.item.call_id;I[V]={callId:se,name:P.item.name,arguments:""},y({type:"tool-input-start",id:se,toolName:P.item.name})}}else if(P.type==="response.reasoning_summary_part.added")D(P.output_index,P.summary_index);else if(P.type==="response.reasoning_summary_text.delta")O(P.output_index,P.summary_index,P.delta);else if(P.type==="response.reasoning_summary_text.done"){let V=D(P.output_index,P.summary_index);T.has(V)||O(P.output_index,P.summary_index,P.text),C(P.output_index,P.summary_index)}else if(P.type==="response.reasoning_summary_part.done"){let V=D(P.output_index,P.summary_index);T.has(V)||O(P.output_index,P.summary_index,P.part.text),C(P.output_index,P.summary_index)}else if(P.type==="response.output_item.done"&&P.item.type==="reasoning"){let V=`reasoning-${P.output_index}-`;for(let se of[...b])se.startsWith(V)&&(b.delete(se),y({type:"reasoning-end",id:se}))}else if(P.type==="response.output_text.delta")H=!0,U||(y({type:"text-start",id:M}),U=!0),y({type:"text-delta",id:M,delta:P.delta});else if(P.type==="response.function_call_arguments.delta"){let V=P.output_index,se=I[V];se&&(se.arguments+=P.delta,y({type:"tool-input-delta",id:se.callId,delta:P.delta}))}else if(P.type==="response.function_call_arguments.done"){let V=P.output_index,se=I[V];se&&(se.arguments=P.arguments)}else if(P.type==="response.completed"){let V=Object.keys(I).length>0;B=f.convertResponsesStatus(P.response.status,V),P.response.usage&&(W=f.createUsage({inputTotal:P.response.usage.input_tokens,outputTotal:P.response.usage.output_tokens,outputReasoning:P.response.usage.output_tokens_details?.reasoning_tokens,cacheRead:P.response.usage.input_tokens_details?.cached_tokens,raw:{total_tokens:P.response.usage.total_tokens}}))}for(let P of b)y({type:"reasoning-end",id:P});b.clear(),U&&y({type:"text-end",id:M}),Object.keys(I).length>0&&B.unified==="stop"&&(B={unified:"tool-calls",raw:B.raw});for(let P of Object.values(I))y({type:"tool-input-end",id:P.callId}),y({type:"tool-call",toolCallId:P.callId,toolName:P.name,input:P.arguments||"{}"});y({type:"finish",finishReason:B,usage:W}),k()}catch(G){if(f.isContextOverflowError(G)){let Q=G;y({type:"error",error:new A({message:`Context overflow: ${Q.message}. Please start a new session or use /compact to reduce context.`,statusCode:400,cause:G})}),k();return}if(!e&&f.isTokenError(G)){if(f.directAccessClient.invalidateToken(),!H)try{let P=(await f.doStreamWithResponsesApi(r,!0)).stream.getReader();for(;;){let{done:V,value:se}=await P.read();if(V)break;se.type!=="stream-start"&&y(se)}k();return}catch(Q){y({type:"error",error:Q instanceof A?Q:new A({message:"Token refresh retry failed",cause:Q})}),k();return}y({type:"error",error:new A({message:"TOKEN_REFRESH_NEEDED",cause:G})}),k();return}G instanceof F.APIError?y({type:"error",error:new A({message:f.formatOpenAIError(G,n?.length),statusCode:G.status,cause:G})}):y({type:"error",error:G}),k()}},"start")}),request:{body:u}}}},Di="6.19.0",Jc=3e4,Kc=class{static{i(this,"GitLabWorkflowClient")}socket=null;keepaliveInterval=null;heartbeatInterval=null;eventCallback=null;closed=!1;closedEmitted=!1;lastSendTime=0;connect(r,e){return this.validateOptions(r),this.disposeSocket(),this.eventCallback=e,this.closed=!1,this.closedEmitted=!1,this.cleanedUp=!1,new Promise((t,s)=>{let n=this.buildWebSocketUrl(r),o=this.buildWebSocketHeaders(r);this.socket=new be.default(n,{headers:o});let a=!1,c=setTimeout(()=>{if(a)return;a=!0;let l=this.socket;this.socket=null;try{l?.close(1e3,"Connect timeout")}catch{}s(new A({message:`WebSocket connect timed out after ${Jc}ms`}))},Jc);this.socket.onopen=()=>{clearTimeout(c),!a&&(a=!0,this.startKeepalive(),this.startHeartbeat(),t())},this.socket.onmessage=l=>{try{let u=this.decodeMessageData(l.data),f=JSON.parse(u);if(!f||typeof f!="object")throw new A({message:"Invalid message structure: expected object"});this.handleAction(f)}catch(u){this.emit({type:"failed",error:u instanceof Error?u:new Error(String(u))})}},this.socket.onerror=l=>{let u=new A({message:`WebSocket error: ${l.message||"unknown"}`});a?this.emit({type:"failed",error:u}):(clearTimeout(c),a=!0,s(u))},this.socket.onclose=l=>{if(this.cleanup(),!a){clearTimeout(c),a=!0,s(new A({message:`WebSocket closed before open: code=${l.code} reason=${l.reason||""}`}));return}this.closed||this.emitClosed(l.code,l.reason||"")}})}sendStartRequest(r){this.send({startRequest:r})}sendActionResponse(r,e,t){this.sendHeartbeatIfNeeded();let s={requestID:r,plainTextResponse:{response:e,error:t??null}};this.send({actionResponse:s})}stop(){this.send({stopWorkflow:{reason:qd}}),this.closed=!0,this.cleanup();let r=this.socket;this.socket=null,r&&(r.readyState===be.default.OPEN||r.readyState===be.default.CONNECTING)&&r.close(1e3,"Client stopping")}close(){if(this.closed)return;this.closed=!0,this.cleanup();let r=this.socket;this.socket=null,r&&(r.readyState===be.default.OPEN||r.readyState===be.default.CONNECTING)&&r.close(1e3,"Client closing")}closeAndWait(r=Ld){let e=this.socket,t=e&&(e.readyState===be.default.OPEN||e.readyState===be.default.CONNECTING);return this.closed||!t?(this.close(),Promise.resolve()):new Promise(s=>{let n=!1,o=i(()=>{n||(n=!0,clearTimeout(a),s())},"finish"),a=setTimeout(o,r),c=e.onclose;e.onclose=l=>{try{c?.call(e,l)}finally{o()}},this.close()})}get isConnected(){return this.socket?.readyState===be.default.OPEN}validateOptions(r){if(!r.instanceUrl||typeof r.instanceUrl!="string")throw new A({message:"instanceUrl is required"});let e=new URL(r.instanceUrl);if(e.protocol!=="https:"&&e.protocol!=="http:")throw new A({message:`Invalid instanceUrl protocol: ${e.protocol}`});if(e.username||e.password)throw new A({message:"instanceUrl must not contain authentication credentials (username/password)"});if(!r.headers||typeof r.headers!="object")throw new A({message:"headers are required"});if(r.modelRef&&typeof r.modelRef!="string")throw new A({message:"modelRef must be a string"})}buildWebSocketUrl(r){let e=new URL(r.instanceUrl.replace(/\/?$/,"/")),t=new URL("./api/v4/ai/duo_workflows/ws",e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",r.modelRef&&r.modelRef!=="default"&&t.searchParams.set("user_selected_model_identifier",r.modelRef),r.aiCatalogItemVersionId&&t.searchParams.set("ai_catalog_item_version_id",String(r.aiCatalogItemVersionId)),r.workflowDefinition&&t.searchParams.set("workflow_definition",r.workflowDefinition),t.toString()}buildWebSocketHeaders(r){let e={};for(let[n,o]of Object.entries(r.headers))e[n.toLowerCase()]=o;delete e["content-type"],e["x-gitlab-client-type"]="node-websocket",e["x-gitlab-language-server-version"]=Fi;let s=new URL(r.instanceUrl).origin;return e.origin=s,r.requestId&&(e["x-request-id"]=r.requestId),r.projectId&&(e["x-gitlab-project-id"]=r.projectId),r.namespaceId&&(e["x-gitlab-namespace-id"]=r.namespaceId),r.rootNamespaceId&&(e["x-gitlab-root-namespace-id"]=r.rootNamespaceId),e["user-agent"]||(e["user-agent"]=`gitlab-ai-provider/${Di}`),e}handleAction(r){if(r.newCheckpoint){let t=r.newCheckpoint;this.emit({type:"checkpoint",data:t}),t.status==="FINISHED"||t.status==="COMPLETED"?this.emit({type:"completed"}):t.status==="FAILED"?this.emit({type:"failed",error:new Error(t.content||"Workflow failed")}):t.status==="STOPPED"||t.status==="CANCELLED"?this.emit({type:"completed"}):t.status==="TOOL_CALL_APPROVAL_REQUIRED"?this.emit({type:"approval-required",tools:this.extractApprovalTools(t)}):t.status==="PLAN_APPROVAL_REQUIRED"&&this.emit({type:"failed",error:new A({message:"Workflow requires plan approval, which is not supported by this client"})});return}if(r.runMCPTool){if(!r.requestID){this.emit({type:"failed",error:new A({message:"Received runMCPTool action without requestID; workflow cannot continue"})});return}this.emit({type:"tool-request",requestID:r.requestID,data:r.runMCPTool});return}let e=[["runReadFile",r.runReadFile],["runReadFiles",r.runReadFiles],["runWriteFile",r.runWriteFile],["runShellCommand",r.runShellCommand],["runEditFile",r.runEditFile],["listDirectory",r.listDirectory],["findFiles",r.findFiles],["grep",r.grep],["mkdir",r.mkdir],["runCommand",r.runCommand],["runGitCommand",r.runGitCommand],["runHTTPRequest",r.runHTTPRequest]];for(let[t,s]of e)if(s){if(!r.requestID){this.emit({type:"failed",error:new A({message:`Received ${t} action without requestID; workflow cannot continue`})});return}this.emit({type:"builtin-tool-request",requestID:r.requestID,toolName:t,data:s});return}}extractApprovalTools(r){if(!r.checkpoint)return[];let e;try{e=JSON.parse(r.checkpoint)}catch{return[]}return(e.channel_values?.ui_chat_log??[]).filter(t=>t.message_type==="request"&&t.tool_info!==null).map(t=>({name:t.tool_info.name,args:JSON.stringify(t.tool_info.args)}))}send(r){if(this.socket?.readyState===be.default.OPEN){let e=JSON.stringify(r);this.socket.send(e),this.lastSendTime=Date.now()}}sendHeartbeatIfNeeded(){Date.now()-this.lastSendTime>=Bc/2&&this.send({heartbeat:{timestamp:Date.now()}})}emit(r){this.eventCallback?.(r)}emitClosed(r,e){this.closedEmitted||(this.closedEmitted=!0,this.emit({type:"closed",code:r,reason:e}))}decodeMessageData(r){return typeof r=="string"?r:Array.isArray(r)?Buffer.concat(r).toString("utf8"):(r instanceof ArrayBuffer,Buffer.from(r).toString("utf8"))}disposeSocket(){this.cleanup();let r=this.socket;if(this.socket=null,r&&(r.onopen=null,r.onmessage=null,r.onerror=null,r.onclose=null,r.readyState===be.default.OPEN||r.readyState===be.default.CONNECTING))try{r.close(1e3,"Reconnecting")}catch{}}startKeepalive(){this.keepaliveInterval&&clearInterval(this.keepaliveInterval),this.keepaliveInterval=setInterval(()=>{if(this.socket?.readyState===be.default.OPEN)try{this.socket.ping()}catch{}},Fd)}startHeartbeat(){this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.heartbeatInterval=setInterval(()=>{this.send({heartbeat:{timestamp:Date.now()}})},Bc)}cleanedUp=!1;cleanup(){this.cleanedUp||(this.cleanedUp=!0,this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null))}},nf=class{static{i(this,"GitLabProjectCache")}cache=new Map;defaultTTL;constructor(r=300*1e3){this.defaultTTL=r}get(r){let e=this.cache.get(r);return e?Date.now()>e.expiresAt?(this.cache.delete(r),null):e.project:null}set(r,e,t){this.cache.set(r,{project:e,expiresAt:Date.now()+(t??this.defaultTTL)})}has(r){return this.get(r)!==null}delete(r){this.cache.delete(r)}clear(){this.cache.clear()}get size(){return this.cache.size}cleanup(){let r=Date.now();for(let[e,t]of this.cache.entries())r>t.expiresAt&&this.cache.delete(e)}},tl=class{static{i(this,"GitLabProjectDetector")}config;fetchFn;cache;constructor(r){this.config={gitTimeout:5e3,...r},this.fetchFn=r.fetch??fetch,this.cache=r.cache??new nf}async detectProject(r,e="origin"){let t=`${el.resolve(r)}\0${e}`,s=this.cache.get(t);if(s)return s;try{let n=await this.getGitRemoteUrl(r,e);if(!n)return null;let o=this.parseGitRemoteUrl(n,this.config.instanceUrl);if(!o)return null;let a=await this.getProjectByPath(o);return this.cache.set(t,a),a}catch(n){throw n instanceof A?n:new A({message:`Project detection failed: ${n}`,cause:n})}}parseGitRemoteUrl(r,e){try{let t=new URL(e).hostname;if(r.startsWith("ssh://")){try{let o=new URL(r);if(o.hostname===t){let a=o.pathname.replace(/^\//,"");return a.endsWith(".git")?a.slice(0,-4):a}}catch{}return null}let s=r.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(s){let[,o,a]=s;if(o===t)return a.endsWith(".git")?a.slice(0,-4):a}let n=r.match(/^(https?):\/\/([^/]+)\/(.+?)(?:\.git)?$/);if(n){let[,,o,a]=n;if(o.split(":")[0]===t)return a.endsWith(".git")?a.slice(0,-4):a}return null}catch{return null}}async getGitRemoteUrl(r,e="origin"){return new Promise(t=>{let s=sf("git",["config","--get",`remote.${e}.url`],{cwd:r,timeout:this.config.gitTimeout}),n="";s.stdout?.on("data",o=>{n+=o.toString()}),s.stderr?.resume(),s.on("close",o=>{o===0&&n.trim()?t(n.trim()):t(null)}),s.on("error",()=>{t(null)})})}async getProjectByPath(r){let e=encodeURIComponent(r),t=`${this.config.instanceUrl}/api/v4/projects/${e}`;try{let s=await this.fetchFn(t,{method:"GET",headers:this.config.getHeaders()});if(!s.ok)throw new A({message:`Failed to fetch project '${r}': ${s.status} ${s.statusText}`});let n=await s.json();return{id:n.id,path:n.path,pathWithNamespace:n.path_with_namespace,name:n.name,namespaceId:n.namespace?.id}}catch(s){throw s instanceof A?s:new A({message:`Failed to fetch project '${r}': ${s}`,cause:s})}}clearCache(){this.cache.clear()}getCache(){return this.cache}};function Vc(r){return"projectId"in r?`p:${r.projectId}`:`n:${r.rootNamespaceId}`}i(Vc,"scopeCacheKey");function of(r){return typeof r=="string"?{rootNamespaceId:r}:r}i(of,"normalizeScope");var af=`
|
|
90
|
+
query aiChatAvailableModels($projectId: ProjectID, $rootNamespaceId: GroupID) {
|
|
91
|
+
metadata {
|
|
92
|
+
featureFlags(names: ["ai_user_model_switching"]) {
|
|
93
|
+
enabled
|
|
94
|
+
name
|
|
95
|
+
}
|
|
96
|
+
version
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
aiChatAvailableModels(projectId: $projectId, rootNamespaceId: $rootNamespaceId) {
|
|
100
|
+
defaultModel {
|
|
101
|
+
name
|
|
102
|
+
ref
|
|
103
|
+
}
|
|
104
|
+
selectableModels {
|
|
105
|
+
name
|
|
106
|
+
ref
|
|
107
|
+
}
|
|
108
|
+
pinnedModel {
|
|
109
|
+
name
|
|
110
|
+
ref
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
`,Xc=600*1e3,rl=class{static{i(this,"GitLabModelDiscovery")}config;fetchFn;cache=new Map;constructor(r){this.config=r,this.fetchFn=r.fetch??fetch}async discover(r){let e=of(r),t=Vc(e),s=this.cache.get(t);if(s&&s.expiresAt>Date.now())return s.data;try{let n=await this.query(e);return this.cache.set(t,{data:n,expiresAt:Date.now()+Xc}),n}catch(n){if("projectId"in e&&e.rootNamespaceId){let o={rootNamespaceId:e.rootNamespaceId},a=await this.query(o);return this.cache.set(Vc(o),{data:a,expiresAt:Date.now()+Xc}),a}throw n}}async query(r){let e=`${this.config.instanceUrl}/api/graphql`;try{let t=await this.fetchFn(e,{method:"POST",headers:{...this.config.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify({query:af,variables:"projectId"in r?{projectId:r.projectId,rootNamespaceId:void 0}:{projectId:void 0,rootNamespaceId:r.rootNamespaceId}})});if(!t.ok){let l=await t.text();throw new A({message:`Model discovery GraphQL request failed: ${t.status} ${t.statusText} - ${l}`,statusCode:t.status,responseBody:l})}let s=await t.json();if(s.errors&&s.errors.length>0)throw new A({message:`Model discovery GraphQL errors: ${s.errors.map(l=>l.message).join(", ")}`});let n=s.data?.aiChatAvailableModels,o=s.data?.metadata,a=o?.featureFlags?.find(l=>l.name==="ai_user_model_switching"),c=a?a.enabled:!0;return{defaultModel:n?.defaultModel??null,selectableModels:n?.selectableModels??[],pinnedModel:n?.pinnedModel??null,modelSwitchingEnabled:c,instanceVersion:o?.version??null}}catch(t){throw t instanceof A?t:new A({message:`Model discovery failed: ${t}`,cause:t})}}async getEffectiveModelRef(r,e){let t=await this.discover(r);return t.pinnedModel?t.pinnedModel.ref:e&&t.modelSwitchingEnabled&&t.selectableModels.some(n=>n.ref===e)?e:t.defaultModel?.ref??null}invalidateCache(){this.cache.clear()}},cf=600*1e3;function lf(){let r=process.env.XDG_CACHE_HOME||yn.join(sl.homedir(),".cache");return yn.join(r,"opencode","gitlab-workflow-model-cache.json")}i(lf,"getCacheFilePath");function uf(r,e,t){let s=(e||"https://gitlab.com").replace(/\/$/,""),n=t?`${r}\0${s}\0${t}`:`${r}\0${s}`;return nl.createHash("sha256").update(n).digest("hex").slice(0,12)}i(uf,"computeCacheKey");var ol=class{static{i(this,"GitLabModelCache")}filePath;key;constructor(r,e,t){this.filePath=lf(),this.key=uf(r,e,t)}readAll(){try{if(!xe.existsSync(this.filePath))return{};let r=xe.readFileSync(this.filePath,"utf-8");return JSON.parse(r)}catch{return{}}}writeAll(r){try{let e=yn.dirname(this.filePath);xe.mkdirSync(e,{recursive:!0,mode:448});let t=`${this.filePath}.${process.pid}.${Date.now()}.tmp`;xe.writeFileSync(t,JSON.stringify(r,null,2),{mode:384}),xe.renameSync(t,this.filePath)}catch{}}load(){return this.readAll()[this.key]??null}save(r){let e=this.readAll();e[this.key]=r,this.writeAll(e)}isDiscoveryExpired(){let r=this.load(),e=r?.discoveryUpdatedAt;if(!r?.discovery||!e)return!0;let t=new Date(e).getTime();return Number.isFinite(t)?Date.now()-t>cf:!0}saveDiscovery(r,e){let t=this.load(),s=new Date().toISOString();this.save({discovery:r,project:e!==void 0?e:t?.project??null,selectedModelRef:t?.selectedModelRef??null,selectedModelName:t?.selectedModelName??null,updatedAt:s,discoveryUpdatedAt:s})}saveSelection(r,e){let t=this.load(),s=e;if(!s&&r&&t?.discovery){let n=t.discovery;s=(n.pinnedModel?.ref===r?n.pinnedModel:n.selectableModels.find(a=>a.ref===r)??(n.defaultModel?.ref===r?n.defaultModel:null))?.name??null}this.save({discovery:t?.discovery??null,project:t?.project??null,selectedModelRef:r,selectedModelName:s,updatedAt:new Date().toISOString(),discoveryUpdatedAt:t?.discoveryUpdatedAt})}clear(){let r=this.readAll();if(delete r[this.key],Object.keys(r).length===0)try{xe.existsSync(this.filePath)&&xe.unlinkSync(this.filePath)}catch{}else this.writeAll(r)}getSelectedModelRef(){return this.load()?.selectedModelRef??null}getSelectedModelName(){return this.load()?.selectedModelName??null}getDiscovery(){return this.load()?.discovery??null}};function Ui(r){if(!r||typeof r!="object")return r;let e={};for(let[t,s]of Object.entries(r))if(!(t==="description"||t==="examples"||t==="default"))if(t==="properties"&&typeof s=="object"&&s!==null){let n={};for(let[o,a]of Object.entries(s))typeof a=="object"&&a!==null?n[o]=Ui(a):n[o]=a;e[t]=n}else t==="items"&&typeof s=="object"&&s!==null?e[t]=Ui(s):e[t]=s;return e}i(Ui,"simplifySchemaObj");function df(r){try{return JSON.stringify(Ui(JSON.parse(r)))}catch{return r}}i(df,"simplifySchema");function ff(r){if(!r||typeof r!="object")return r;let e={type:r.type||"object"};if(r.required&&(e.required=r.required),r.properties&&typeof r.properties=="object"){let t={};for(let[s,n]of Object.entries(r.properties))if(typeof n=="object"&&n!==null){let o=n;t[s]={type:o.type||"string"}}else t[s]={type:"string"};e.properties=t}return e}i(ff,"minimalSchemaObj");function hf(r){try{return JSON.stringify(ff(JSON.parse(r)))}catch{return r}}i(hf,"minimalSchema");var pf=class gn{static{i(this,"_GitLabWorkflowLanguageModel")}specificationVersion="v3";modelId;supportedUrls={};config;workflowOptions;tokenClient;projectDetector;modelDiscovery;modelCache;detectedProjectPath=null;sessionWorkflows=new Map;static MAX_SESSION_WORKFLOWS=50;setSessionWorkflow(e,t){for(this.sessionWorkflows.delete(e),this.sessionWorkflows.set(e,t);this.sessionWorkflows.size>gn.MAX_SESSION_WORKFLOWS;){let s=this.sessionWorkflows.keys().next().value;if(s===void 0)break;this.sessionWorkflows.delete(s)}}currentWorkflowId=null;currentWorkflowDefinition=null;persistedAgentEmitted=new Map;activeClients=new Set;_selectedModelRef;_selectedModelName;_rootNamespaceId;_discoveryPromise;get selectedModelRef(){return this._selectedModelRef??null}set selectedModelRef(e){this._selectedModelRef=e??void 0,this._selectedModelName=void 0,this.modelCache.saveSelection(e,null)}get selectedModelName(){return this._selectedModelName??null}set selectedModelName(e){this._selectedModelName=e??void 0,this.modelCache.saveSelection(this._selectedModelRef??null,e)}_toolExecutor=null;onUsageUpdate=null;sessionPreapprovedTools=[];sessionID="";set approvalHandler(e){this.workflowOptions.approvalHandler=e??void 0}get approvalHandler(){return this.workflowOptions.approvalHandler??null}onSelectModel=null;set systemPrompt(e){this.workflowOptions.systemPrompt=e??void 0}get systemPrompt(){return this.workflowOptions.systemPrompt??null}get toolExecutor(){return this._toolExecutor}set toolExecutor(e){if(e)try{this._toolExecutor=rf.bind(e)}catch{this._toolExecutor=e}else this._toolExecutor=null}constructor(e,t,s={}){this.modelId=e,this.config=t,this.workflowOptions=s;let n=s.workingDirectory??process.cwd();this.modelCache=new ol(n,t.instanceUrl);let o=this.modelCache.load();o?.selectedModelRef&&(this._selectedModelRef=o.selectedModelRef),o?.selectedModelName&&(this._selectedModelName=o.selectedModelName),this.tokenClient=new Jd({instanceUrl:t.instanceUrl,getHeaders:t.getHeaders,refreshApiKey:t.refreshApiKey,fetch:t.fetch,featureFlags:t.featureFlags}),this.projectDetector=new tl({instanceUrl:t.instanceUrl,getHeaders:t.getHeaders,fetch:t.fetch}),this.modelDiscovery=new rl({instanceUrl:t.instanceUrl,getHeaders:t.getHeaders,fetch:t.fetch})}get provider(){return this.config.provider}async resolveProjectId(){if(this.workflowOptions.projectId)return this.workflowOptions.projectId;if(this.detectedProjectPath)return this.detectedProjectPath;let e=this.workflowOptions.workingDirectory??process.cwd(),t=await this.projectDetector.detectProject(e);if(t)return this.detectedProjectPath=t.pathWithNamespace,t.pathWithNamespace}async resolveRootNamespaceId(){if(this.workflowOptions.rootNamespaceId)return this.workflowOptions.rootNamespaceId;if(this._rootNamespaceId!==void 0)return this._rootNamespaceId;let e=this.workflowOptions.workingDirectory??process.cwd(),t=await this.projectDetector.detectProject(e);if(t?.namespaceId){let s=`gid://gitlab/Group/${t.namespaceId}`;return this._rootNamespaceId=s,s}return this._rootNamespaceId=null,null}async resolveDiscoveryScope(){let e=await this.resolveRootNamespaceId(),t=this.workflowOptions.workingDirectory??process.cwd(),s=await this.projectDetector.detectProject(t);return s?.id?{projectId:`gid://gitlab/Project/${s.id}`,...e?{rootNamespaceId:e}:{}}:e?{rootNamespaceId:e}:null}async resolveModelRef(){let e=ef(this.modelId);return this.modelId!=="duo-workflow"?e??"default":this._selectedModelRef?this._selectedModelRef:(this._discoveryPromise||(this._discoveryPromise=this.doResolveModelRef(),this._discoveryPromise.finally(()=>{this._discoveryPromise=void 0})),this._discoveryPromise)}async doResolveModelRef(){let e=await this.resolveDiscoveryScope();if(!e)return this._selectedModelRef="default","default";try{let t=await this.modelDiscovery.discover(e);if(this.modelCache.saveDiscovery(t),t.pinnedModel)return this._selectedModelRef=t.pinnedModel.ref,this._selectedModelName=t.pinnedModel.name,this.modelCache.saveSelection(t.pinnedModel.ref,t.pinnedModel.name),t.pinnedModel.ref;let s=this.onSelectModel??this.workflowOptions.onSelectModel;if(t.selectableModels.length>0&&s){let n=await s(t.selectableModels);if(n){let o=t.selectableModels.find(a=>a.ref===n);if(o)return this._selectedModelRef=o.ref,this._selectedModelName=o.name,this.modelCache.saveSelection(o.ref,o.name),o.ref}}if(t.defaultModel)return this._selectedModelRef=t.defaultModel.ref,this._selectedModelName=t.defaultModel.name,this.modelCache.saveSelection(t.defaultModel.ref,t.defaultModel.name),t.defaultModel.ref}catch{let t=this.modelCache.load();if(t?.selectedModelRef)return this._selectedModelRef=t.selectedModelRef,this._selectedModelName=t.selectedModelName??void 0,t.selectedModelRef}return this._selectedModelRef="default","default"}async discoverModels(e){let t=await this.modelDiscovery.discover(e);return this.modelCache.saveDiscovery(t),t}getModelCache(){return this.modelCache}stopWorkflow(){for(let e of this.activeClients)e.isConnected&&e.stop()}resetWorkflow(e){e?this.sessionWorkflows.delete(e):(this.sessionWorkflows.clear(),this.currentWorkflowId=null,this.persistedAgentEmitted.clear())}get workflowId(){return this.currentWorkflowId}createUsage(e){return{inputTokens:{total:e?.inputTotal,noCache:e?.inputTotal,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e?.outputTotal,text:e?.outputTotal,reasoning:void 0}}}createFinishReason(e,t){return{unified:e,raw:t}}async doGenerate(e){let{stream:t}=await this.doStream(e),s=t.getReader(),n=[],o=[],a={unified:"other",raw:void 0},c=this.createUsage();try{for(;;){let{done:f,value:d}=await s.read();if(f)break;switch(d.type){case"text-delta":n.push(d.delta);break;case"tool-call":o.push({type:"tool-call",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input});break;case"finish":a=d.finishReason,d.usage&&(c=d.usage);break;case"error":try{await s.cancel()}catch{}throw d.error}}}finally{s.releaseLock()}let l=[],u=n.join("");return u&&l.push({type:"text",text:u}),l.push(...o),{content:l,finishReason:a,usage:c,warnings:[]}}async doStream(e){let t=this.extractGoalFromPrompt(e.prompt),s=await this.resolveModelRef(),n=this.extractMcpTools(e),o=[...this.workflowOptions.preapprovedTools??n.map(v=>v.name),...this.sessionPreapprovedTools],a=this.buildAdditionalContext(e.prompt),c=this.toolExecutor??null,l=new Set(e.tools?.map(v=>v.name)??[]),u=e.providerOptions?.gitlab,f=u?.workflowDefinition??this.workflowOptions.workflowDefinition,d=u?.flowConfig??void 0,m=u?.flowConfigSchemaVersion??void 0,h=u?.aiCatalogItemVersionId??void 0;await this.tokenClient.getToken(f??_n,this.workflowOptions.rootNamespaceId);let x=await this.resolveProjectId(),y=d??f??_n,k=this.sessionID,I=this.sessionWorkflows.get(k);I&&I.workflowDefinition!==y&&(this.sessionWorkflows.delete(k),I=void 0);let b=k==="";b&&this.currentWorkflowId&&this.currentWorkflowDefinition!==y&&(this.currentWorkflowId=null,this.currentWorkflowDefinition=null);let L;I?L=I.workflowId:b&&this.currentWorkflowId?L=this.currentWorkflowId:(L=await this.tokenClient.createWorkflow(t,{projectId:x,namespaceId:this.workflowOptions.namespaceId,workflowDefinition:f,agentPrivileges:this.workflowOptions.agentPrivileges,aiCatalogItemVersionId:h}),b?(this.currentWorkflowId=L,this.currentWorkflowDefinition=y):(this.setSessionWorkflow(k,{workflowId:L,workflowDefinition:y,agentEmitted:new Map,toolEntries:new Set}),I=this.sessionWorkflows.get(k)));let T=new Kc;this.activeClients.add(T);let W=0,B={streamClosed:!1,streamedInputChars:0,streamedOutputChars:0,pendingToolCount:0,approvalPending:!1,deferredClose:null,activeTextBlockId:null,agentMessageEmitted:new Map(I?.agentEmitted??this.persistedAgentEmitted),currentAgentMessageId:"",activeClient:T,processedRequestIDs:new Set,emittedToolEntries:new Set(I?.toolEntries),emittedToolKeys:new Set,sessionKey:k};for(let v of e.prompt)if(v.role==="system")B.streamedInputChars+=v.content.length;else if(v.role==="user")for(let D of v.content)D.type==="text"&&(B.streamedInputChars+=D.text.length);let U,H=new ReadableStream({start:i(async v=>{try{await T.connect({instanceUrl:this.config.instanceUrl,modelRef:s,headers:this.config.getHeaders(),projectId:this.workflowOptions.projectId,namespaceId:this.workflowOptions.namespaceId,rootNamespaceId:this.workflowOptions.rootNamespaceId,aiCatalogItemVersionId:h,workflowDefinition:f??this.workflowOptions.workflowDefinition},ko=>{this.handleWorkflowEvent(B,ko,v,T,c,()=>`text-${W++}`,l,U,{aiCatalogItemVersionId:h,workflowDefinition:f??this.workflowOptions.workflowDefinition})});let D=f??_n,O=this.workflowOptions.clientCapabilities??jd,C=await this.buildWorkflowMetadata(),G=JSON.stringify(C),P=JSON.stringify({workflowID:L,clientVersion:Fi,workflowDefinition:D,goal:t,workflowMetadata:G,clientCapabilities:O,preapproved_tools:o}).length+100,V=this.trimPayload(n,a,P),se=o.filter(ko=>V.mcpTools.some(dl=>dl.name===ko));U={workflowID:L,clientVersion:Fi,workflowDefinition:D,goal:t,workflowMetadata:G,additional_context:V.additionalContext,clientCapabilities:O,mcpTools:V.mcpTools,preapproved_tools:se};let Wi=d??this.workflowOptions.flowConfig,Hi=m??this.workflowOptions.flowConfigSchemaVersion;Wi&&(U.flowConfig=Wi),Hi?U.flowConfigSchemaVersion=Hi:U.flowConfig&&(U.flowConfigSchemaVersion="v1"),T.sendStartRequest(U),v.enqueue({type:"stream-start",warnings:[]}),v.enqueue({type:"response-metadata",id:L,modelId:s})}catch(D){B.streamClosed||(v.enqueue({type:"error",error:D instanceof A?D:new A({message:`Workflow connection failed: ${ks(String(D))}`,cause:D})}),B.streamClosed=!0,v.close())}},"start"),cancel:i(v=>{M&&e.abortSignal&&e.abortSignal.removeEventListener("abort",M),T.stop(),T.close(),this.activeClients.delete(T),B.activeClient=null,B.streamClosed||(B.sessionKey?this.sessionWorkflows.delete(B.sessionKey):this.currentWorkflowId=null)},"cancel")}),M=null;return e.abortSignal&&(M=i(()=>{T.stop(),T.close(),this.activeClients.delete(T),B.activeClient=null,B.streamClosed||(B.streamClosed=!0,B.sessionKey?this.sessionWorkflows.delete(B.sessionKey):this.currentWorkflowId=null)},"abortListener"),e.abortSignal.aborted?M():e.abortSignal.addEventListener("abort",M,{once:!0})),{stream:H,request:{body:{workflowId:L,modelRef:s,goal:t}}}}handleWorkflowEvent(e,t,s,n,o,a,c,l,u){if(!e.streamClosed)switch(t.type){case"checkpoint":{this.processCheckpoint(e,t.data,s,a);break}case"tool-request":{let{requestID:f,data:d}=t;if(e.processedRequestIDs.has(f))break;e.processedRequestIDs.add(f),e.emittedToolKeys.add(d.name);let m;try{JSON.parse(d.args),m=d.args}catch{m=d.args||"{}"}e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null),s.enqueue({type:"tool-input-start",id:f,toolName:d.name,providerExecuted:!0}),s.enqueue({type:"tool-input-delta",id:f,delta:m}),s.enqueue({type:"tool-input-end",id:f}),s.enqueue({type:"tool-call",toolCallId:f,toolName:d.name,input:m,providerExecuted:!0}),this.executeToolAndRespond(e,n,s,f,d.name,m,o).catch(()=>{});break}case"builtin-tool-request":{if(e.processedRequestIDs.has(t.requestID))break;e.processedRequestIDs.add(t.requestID);let f=Md(t.toolName,t.data,c);e.emittedToolKeys.add(f.toolName);let d=JSON.stringify(f.args);e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null),s.enqueue({type:"tool-input-start",id:t.requestID,toolName:f.toolName,providerExecuted:!0}),s.enqueue({type:"tool-input-delta",id:t.requestID,delta:d}),s.enqueue({type:"tool-input-end",id:t.requestID}),s.enqueue({type:"tool-call",toolCallId:t.requestID,toolName:f.toolName,input:d,providerExecuted:!0}),this.executeToolAndRespond(e,n,s,t.requestID,f.toolName,d,o).catch(()=>{});break}case"approval-required":{e.approvalPending=!0,this.approveAndResume(e,t.tools,l,s,o,a,c,u).catch(f=>{if(e.approvalPending=!1,e.deferredClose){let d=e.deferredClose;e.deferredClose=null,d()}});break}case"completed":{e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null);let f=i(()=>{if(e.streamClosed)return;let d=Math.ceil(e.streamedInputChars/4),m=Math.ceil(e.streamedOutputChars/4);s.enqueue({type:"finish",finishReason:this.createFinishReason("stop","completed"),usage:this.createUsage({inputTotal:d,outputTotal:m})}),e.streamClosed=!0,s.close(),this.cleanupClient(e,!1)},"doCompleteClose");e.pendingToolCount>0||e.approvalPending?e.deferredClose=f:(e.deferredClose=null,f());break}case"failed":{e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null),s.enqueue({type:"error",error:new A({message:`Workflow failed: ${ks(t.error.message)}`,cause:t.error})}),e.streamClosed=!0,s.close(),this.cleanupClient(e,!0);break}case"closed":{if(e.streamClosed)break;e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null);let f=i(()=>{if(!e.streamClosed)if(t.code!==1e3)s.enqueue({type:"error",error:new A({message:`WebSocket closed unexpectedly: code=${t.code} reason=${ks(t.reason)}`,statusCode:t.code})}),e.streamClosed=!0,s.close(),this.cleanupClient(e,!0);else{let d=Math.ceil(e.streamedInputChars/4),m=Math.ceil(e.streamedOutputChars/4);s.enqueue({type:"finish",finishReason:this.createFinishReason("stop","closed"),usage:this.createUsage({inputTotal:d,outputTotal:m})}),e.streamClosed=!0,s.close(),this.cleanupClient(e,!1)}},"doClose");e.pendingToolCount>0||e.approvalPending?e.deferredClose=f:(e.deferredClose=null,f());break}}}processCheckpoint(e,t,s,n){if(!t.checkpoint){t.content&&(e.activeTextBlockId||(e.activeTextBlockId=n(),s.enqueue({type:"text-start",id:e.activeTextBlockId})),s.enqueue({type:"text-delta",id:e.activeTextBlockId,delta:t.content}),e.streamedOutputChars+=t.content.length);return}let o;try{o=JSON.parse(t.checkpoint)}catch{return}let a=o.channel_values?.ui_chat_log;if(!(!a||!Array.isArray(a)||a.length===0)&&!(t.status!=="RUNNING"&&t.status!=="INPUT_REQUIRED"&&t.status!=="FINISHED"&&t.status!=="COMPLETED"&&t.status!=="TOOL_CALL_APPROVAL_REQUIRED"))for(let c=0;c<a.length;c++){let l=a[c];if(l.message_type==="tool"&&l.tool_info){let y=l.message_id||l.correlation_id||`tool-${c}`;if(e.emittedToolEntries.has(y))continue;let k=l.tool_info.name,I=JSON.stringify(l.tool_info.args??{});if(e.emittedToolKeys.has(k)){e.emittedToolEntries.add(y);let W=this.sessionWorkflows.get(e.sessionKey);W&&W.toolEntries.add(y);continue}e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null),s.enqueue({type:"tool-input-start",id:y,toolName:k,providerExecuted:!0}),s.enqueue({type:"tool-input-delta",id:y,delta:I}),s.enqueue({type:"tool-input-end",id:y}),s.enqueue({type:"tool-call",toolCallId:y,toolName:k,input:I,providerExecuted:!0,dynamic:!0});let b=l.tool_info.tool_response,L=typeof b=="string"?b:b?b.content:l.content||"";s.enqueue({type:"tool-result",toolCallId:y,toolName:k,result:{output:L,title:k,metadata:{}},isError:!1}),e.emittedToolEntries.add(y);let T=this.sessionWorkflows.get(e.sessionKey);T&&T.toolEntries.add(y);continue}if(l.message_type!=="agent")continue;let u=l.content||"",f=l.message_id||`idx-${c}`,d=e.agentMessageEmitted.get(f)??0;if(u.length<=d)continue;let m=u.slice(d);!(f===e.currentAgentMessageId)&&e.activeTextBlockId&&(s.enqueue({type:"text-end",id:e.activeTextBlockId}),e.activeTextBlockId=null),e.activeTextBlockId||(e.activeTextBlockId=n(),s.enqueue({type:"text-start",id:e.activeTextBlockId})),s.enqueue({type:"text-delta",id:e.activeTextBlockId,delta:m}),e.streamedOutputChars+=m.length,e.agentMessageEmitted.set(f,u.length),(this.sessionWorkflows.get(e.sessionKey)?.agentEmitted??this.persistedAgentEmitted).set(f,u.length),e.currentAgentMessageId=f}}async executeToolAndRespond(e,t,s,n,o,a,c){e.pendingToolCount++;let l=i(u=>{if(!e.streamClosed)try{s.enqueue(u)}catch{}},"safeEnqueue");try{if(c){let u=await c(o,a,n);if(u.error&&/^Unknown tool:/.test(u.error)){let h=$d(o,a);h&&(u=h)}t.sendActionResponse(n,u.result,u.error),e.streamedInputChars+=a.length,e.streamedOutputChars+=u.result.length;let f=u.result,d=u.title??`${o} result`,m=u.metadata??{output:u.result};if(u.error){let h;typeof u.error=="string"?h=u.error:u.error&&typeof u.error=="object"?h=JSON.stringify(u.error):h=String(u.error),l({type:"tool-result",toolCallId:n,toolName:o,result:h,isError:!0})}else l({type:"tool-result",toolCallId:n,toolName:o,result:{output:f,title:d,metadata:m},isError:!1})}else{let u=`Tool executor not configured for tool: ${o}`;t.sendActionResponse(n,"",u),l({type:"tool-result",toolCallId:n,toolName:o,result:u,isError:!0})}}catch(u){let f=u instanceof Error?u.message:String(u),d=ks(f);t.sendActionResponse(n,"",d),l({type:"tool-result",toolCallId:n,toolName:o,result:d,isError:!0})}finally{if(e.pendingToolCount--,this.onUsageUpdate)try{this.onUsageUpdate({inputTokens:Math.ceil(e.streamedInputChars/4),outputTokens:Math.ceil(e.streamedOutputChars/4)})}catch{}if(e.pendingToolCount<=0&&e.deferredClose){let u=e.deferredClose;e.deferredClose=null,u()}}}cleanupClient(e,t=!1){e.activeClient&&(e.activeClient.close(),this.activeClients.delete(e.activeClient),e.activeClient=null),t&&(e.sessionKey?this.sessionWorkflows.delete(e.sessionKey):(this.currentWorkflowId=null,this.persistedAgentEmitted.clear()))}async approveAndResume(e,t,s,n,o,a,c,l){let u=this.workflowOptions.approvalHandler;if(!u||!s){if(e.approvalPending=!1,e.deferredClose){let k=e.deferredClose;e.deferredClose=null,k()}return}let f;try{f=await u(t)}catch(k){e.approvalPending=!1,e.streamClosed||n.error(k);return}e.approvalPending=!1,e.deferredClose=null;let d=f.approved?{approval:{tool_name:t[0]?.name,tool_args_json:t[0]?.args}}:{rejection:{message:f.message??"User rejected"}},m={...s,approval:d,preapproved_tools:f.approved?[...s.preapproved_tools??[],...t.map(k=>k.name)]:s.preapproved_tools??[]},h=i(async()=>{if(e.streamClosed)return;await this.closeClientAndWait(e);let k=new Kc;this.activeClients.add(k),e.activeClient=k;let I=await this.resolveModelRef();await k.connect({instanceUrl:this.config.instanceUrl,modelRef:I,headers:this.config.getHeaders(),projectId:this.workflowOptions.projectId,namespaceId:this.workflowOptions.namespaceId,rootNamespaceId:this.workflowOptions.rootNamespaceId,aiCatalogItemVersionId:l?.aiCatalogItemVersionId,workflowDefinition:l?.workflowDefinition},b=>{if(b.type==="closed"&&b.code===Wc){y();return}this.handleWorkflowEvent(e,b,n,k,o,a,c,m,l)}),k.sendStartRequest(m)},"reconnect"),x=0,y=i(async()=>{if(!e.streamClosed){if(++x>Ud){this.failStream(e,n,new A({message:"Failed to acquire lock on workflow after reconnect retries",statusCode:Wc}));return}await new Promise(k=>setTimeout(k,Dd*x)),await h().catch(k=>this.failStream(e,n,k))}},"retryWhileLocked");await h().catch(k=>this.failStream(e,n,k))}async closeClientAndWait(e){let t=e.activeClient;t&&(this.activeClients.delete(t),e.activeClient=null,await t.closeAndWait())}failStream(e,t,s){this.cleanupClient(e,!0),!e.streamClosed&&t.error(s)}async buildWorkflowMetadata(){let e={extended_logging:!1,tool_approval_for_session_enabled:!0};try{let t=this.workflowOptions.workingDirectory??process.cwd(),s=await this.getGitInfo(t);s.url&&(e.git_url=s.url),s.sha&&(e.git_sha=s.sha),s.branch&&(e.git_branch=s.branch)}catch{}return e}async getGitInfo(e){let{execFile:t}=await import("child_process"),{promisify:s}=await import("util"),n=s(t),o={cwd:e,timeout:3e3},a=i(async(f,d)=>{try{let{stdout:m}=await n(f,d,o);return m.trim()||void 0}catch{return}},"run"),[c,l,u]=await Promise.all([a("git",["remote","get-url","origin"]),a("git",["rev-parse","HEAD"]),a("git",["rev-parse","--abbrev-ref","HEAD"])]);return{url:c,sha:l,branch:u}}static SYSTEM_REMINDER_RE=/<system-reminder>([\s\S]*?)<\/system-reminder>/g;extractGoalFromPrompt(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.role==="user"){let n=s.content.filter(o=>o.type==="text").map(o=>o.text);if(n.length>0){let o=n.join(`
|
|
115
|
+
`);return o.replace(gn.SYSTEM_REMINDER_RE,"").trim()||o}}}return""}extractMcpTools(e){return this.workflowOptions.mcpTools&&this.workflowOptions.mcpTools.length>0?this.workflowOptions.mcpTools:!e.tools||e.tools.length===0?[]:e.tools.filter(t=>t.type==="function").map(t=>({name:t.name,description:t.description||"",inputSchema:JSON.stringify(t.inputSchema||{type:"object",properties:{}})}))}static MAX_START_REQUEST_BYTES=4*1024*1024;trimPayload(e,t,s){let n=gn.MAX_START_REQUEST_BYTES-s,o=JSON.stringify(t);if(JSON.stringify(e).length+o.length<=n)return{mcpTools:e,additionalContext:t};let l=e.map(h=>({name:h.name,description:h.description,inputSchema:df(h.inputSchema)}));if(JSON.stringify(l).length+o.length<=n)return{mcpTools:l,additionalContext:t};let f=l.map(h=>({name:h.name,description:h.description,inputSchema:hf(h.inputSchema)}));if(JSON.stringify(f).length+o.length<=n)return{mcpTools:f,additionalContext:t};let m=[...f];for(;m.length>0&&!(JSON.stringify(m).length+o.length<=n);)m.pop();return{mcpTools:m,additionalContext:t}}buildAdditionalContext(e){let t=[];this.workflowOptions.additionalContext&&t.push(...this.workflowOptions.additionalContext);for(let s of e)if(s.role==="system")t.push({category:"system_prompt",content:s.content,metadata:JSON.stringify({role:"system"})});else if(s.role==="assistant"){let n=s.content.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
116
|
+
`);n&&t.push({category:"conversation",content:n,metadata:JSON.stringify({role:"assistant"})})}else if(s.role==="user"){for(let n of s.content)if(n.type==="text"){let a=n.text.matchAll(gn.SYSTEM_REMINDER_RE);for(let c of a){let l=c[1].trim();l&&t.push({category:"agent_context",content:l,metadata:JSON.stringify({source:"system-reminder"})})}}}return t}},mf=Ie.object({access_token:Ie.string(),refresh_token:Ie.string().optional(),expires_in:Ie.number(),created_at:Ie.number()}),gf="1d89f9fdb23ee96d4e603201f6861dab6e143c5c3c00469a018a2d94bdc03d4e",$v="36f2a70cddeb5a0889d4fd8295c241b7e9848e89cf9e599d0eed2d8e5350fbf5",il="https://gitlab.com",_f=300*1e3,Nv=["api"],yf=new Map,al=class{static{i(this,"GitLabOAuthManager")}fetch;inFlightRefreshes=yf;constructor(r=fetch){this.fetch=r}isTokenExpired(r){return Number.isFinite(r)?Date.now()>=r:!0}needsRefresh(r){return Number.isFinite(r)?Date.now()>=r-_f:!0}async refreshIfNeeded(r,e){if(!this.needsRefresh(r.expiresAt))return r;if(!r.refreshToken)throw new A({message:"OAuth token has expired and no refresh token is available"});return this.exchangeRefreshToken({instanceUrl:r.instanceUrl,refreshToken:r.refreshToken,clientId:e})}async exchangeAuthorizationCode(r){let{instanceUrl:e,code:t,codeVerifier:s,clientId:n,redirectUri:o}=r,a=await this.exchangeToken({instanceUrl:e,grantType:"authorization_code",code:t,codeVerifier:s,clientId:n||this.getClientId(e),redirectUri:o});return this.createTokensFromResponse(a,e)}async exchangeRefreshToken(r){let{instanceUrl:e,refreshToken:t,clientId:s}=r,n=`${e}:${t}`,o=this.inFlightRefreshes.get(n);if(o)return o;let a=(async()=>{let c=await this.exchangeToken({instanceUrl:e,grantType:"refresh_token",refreshToken:t,clientId:s||this.getClientId(e)});return this.createTokensFromResponse(c,e,t)})();this.inFlightRefreshes.set(n,a);try{return await a}finally{this.inFlightRefreshes.delete(n)}}getClientId(r){let e=process.env.GITLAB_OAUTH_CLIENT_ID;if(e)return e;if(r===il)return gf;throw new A({message:`No OAuth client ID configured for instance ${r}. Please provide a clientId parameter or set GITLAB_OAUTH_CLIENT_ID environment variable.`})}async exchangeToken(r){let{instanceUrl:e,grantType:t,code:s,codeVerifier:n,refreshToken:o,clientId:a,redirectUri:c}=r,l={client_id:a,grant_type:t};if(t==="authorization_code"){if(!s||!n||!c)throw new A({message:"Authorization code, code verifier, and redirect URI are required for authorization_code grant"});l.code=s,l.code_verifier=n,l.redirect_uri=c}else if(t==="refresh_token"){if(!o)throw new A({message:"Refresh token is required for refresh_token grant"});l.refresh_token=o}let u=`${e}/oauth/token`;try{let f=await this.fetch(u,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l).toString()});if(!f.ok){let h=await f.text();throw new A({message:`OAuth token exchange failed: ${f.status} ${f.statusText}`,cause:new Error(h)})}let d=await f.json(),m=mf.safeParse(d);if(!m.success)throw new A({message:`Invalid OAuth token response: ${m.error.message}`,cause:m.error});return m.data}catch(f){throw f instanceof A?f:new A({message:`Failed to exchange OAuth token: ${f instanceof Error?f.message:String(f)}`,cause:f instanceof Error?f:void 0})}}createTokensFromResponse(r,e,t){let s=this.createExpiresTimestamp(r);return{accessToken:r.access_token,refreshToken:r.refresh_token||t||"",expiresAt:s,instanceUrl:e}}createExpiresTimestamp(r){let e=r.created_at*1e3,t=r.expires_in*1e3;return e+t}};function ll(){let r=cl.homedir(),e=process.env.XDG_DATA_HOME;return e?xo.join(e,"opencode","auth.json"):process.platform!=="win32"?xo.join(r,".local","share","opencode","auth.json"):xo.join(r,".opencode","auth.json")}i(ll,"getOpenCodeAuthPath");async function wf(r){try{let e=ll();if(!ir.existsSync(e))return;let t=JSON.parse(ir.readFileSync(e,"utf-8")),s=r.replace(/\/$/,""),n=t.gitlab;if(n?.type==="oauth"){let a=typeof n.enterpriseUrl=="string"?n.enterpriseUrl.replace(/\/$/,""):void 0;if(a===s||a===void 0&&s===il)return n}else if(n?.type==="api"&&typeof n.key=="string")return n;return t[s]||t[`${s}/`]}catch{return}}i(wf,"loadOpenCodeAuth");var $i=new Map;async function bf(r,e,t){let s=$i.get(e);if(s)return s;let n=(async()=>{let a=await new al().exchangeRefreshToken({instanceUrl:e,refreshToken:r.refresh,clientId:t}),c=ll(),l=JSON.parse(ir.readFileSync(c,"utf-8"));return l.gitlab={type:"oauth",refresh:a.refreshToken,access:a.accessToken,expires:a.expiresAt,enterpriseUrl:e},ir.writeFileSync(c,JSON.stringify(l,null,2),{mode:384}),a.accessToken})();$i.set(e,n);try{return await n}finally{$i.delete(e)}}i(bf,"refreshOAuthToken");async function zc(r,e,t){if(r.apiKey)return r.apiKey;let s=await wf(e);if(s?.type==="api")return s.key;if(s?.type==="oauth")if(new al().needsRefresh(s.expires))try{return await bf(s,e,t)}catch(a){let c=a instanceof Error?a.message:String(a),l=process.env[r.environmentVariableName];if(l)return l;throw new A({message:`OAuth token refresh failed and no fallback ${r.environmentVariableName} environment variable is set. Refresh error: ${c}. Re-authenticate with 'opencode auth login gitlab' or set ${r.environmentVariableName}.`})}else return s.access;let n=process.env[r.environmentVariableName];if(!n)throw new A({message:`${r.description} API key is missing. Pass it as the 'apiKey' parameter, set the ${r.environmentVariableName} environment variable, or authenticate with 'opencode auth login gitlab'.`});return n}i(zc,"loadApiKey");function xf(r,e){let t=r["User-Agent"];return{...r,"User-Agent":t?`${t} ${e}`:e}}i(xf,"withUserAgentSuffix");function kf(r={}){let e=r.instanceUrl??process.env.GITLAB_INSTANCE_URL??"https://gitlab.com",t=r.name??"gitlab",s,n,o,a=i(async()=>{if(s)return s;if(n)return n;n=zc({apiKey:r.apiKey,environmentVariableName:"GITLAB_TOKEN",description:"GitLab"},e,r.clientId);try{return s=await n,s}finally{n=void 0}},"getApiKey"),c=i(async()=>{if(o)return o;o=(async()=>{s=void 0,n=void 0,s=await zc({apiKey:void 0,environmentVariableName:"GITLAB_TOKEN",description:"GitLab"},e,r.clientId)})();try{return await o}finally{o=void 0}},"refreshApiKey"),l=i(()=>{let x=s||r.apiKey||process.env.GITLAB_TOKEN||"";if(!x)throw new A({message:"GitLab API key is missing. Pass it as the 'apiKey' parameter, set the GITLAB_TOKEN environment variable, or authenticate with 'opencode auth login gitlab'."});return xf({Authorization:`Bearer ${x}`,"Content-Type":"application/json",...r.headers},`ai-sdk-gitlab/${Di}`)},"getHeaders"),u=i(async()=>{try{await a()}catch{}},"ensureApiKey");a().catch(()=>{});let f=i((x,y)=>{let k=Gc(x);if(!k)throw new A({message:`Unknown model ID: ${x}. Model must be registered in MODEL_MAPPINGS.`});if(y?.providerModel){let W=zd(k.provider);if(!W.includes(y.providerModel))throw new A({message:`Invalid providerModel '${y.providerModel}' for provider '${k.provider}'. Valid models: ${W.join(", ")}`})}let I={DuoAgentPlatformNext:!0,...r.featureFlags,...y?.featureFlags},L={...{"User-Agent":`gitlab-ai-provider/${Di}`},...r.aiGatewayHeaders,...y?.aiGatewayHeaders},T={provider:`${t}.agentic`,instanceUrl:e,getHeaders:l,ensureApiKey:u,refreshApiKey:c,fetch:r.fetch,maxTokens:y?.maxTokens,featureFlags:I,aiGatewayUrl:r.aiGatewayUrl,aiGatewayHeaders:L};return k.provider==="openai"?new tf(x,{...T,openaiModel:y?.providerModel??k.model,reasoningEffort:y?.reasoningEffort}):new Xd(x,{...T,anthropicModel:y?.providerModel??k.model,thinking:y?.thinking})},"createAgenticChatModel"),d=i((x,y)=>{let k=Gc(x);if(!k||k.provider!=="workflow")throw new A({message:`Unknown workflow model ID: ${x}. Use 'duo-workflow' or a 'duo-workflow-*' model ID.`});return new pf(x,{provider:`${t}.workflow`,instanceUrl:e,getHeaders:l,refreshApiKey:c,fetch:r.fetch,featureFlags:{...r.featureFlags,...y?.featureFlags},aiGatewayUrl:r.aiGatewayUrl},y)},"createWorkflowChatModel"),m=i(x=>Zd(x)?d(x):f(x),"createDefaultModel"),h=Object.assign(x=>m(x),{specificationVersion:"v3",languageModel:m,chat:m,agenticChat:f,workflowChat:d});return h.embeddingModel=x=>{throw new A({message:`GitLab provider does not support text embedding models. Model ID: ${x}`})},h.imageModel=x=>{throw new A({message:`GitLab provider does not support image models. Model ID: ${x}`})},h}i(kf,"createGitLab");var Fv=kf(),Af="https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/raw/main/ai_gateway/model_selection/models.yml",Sf=1440*60*1e3,ji=2e5,qi=64e3;function Bi(){let r=process.env.XDG_CACHE_HOME||wn.join(ul.homedir(),".cache");return wn.join(r,"opencode","gitlab-model-configs.json")}i(Bi,"getCacheFilePath2");function If(){try{let r=Bi();if(!Oe.existsSync(r))return null;let e=Oe.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}i(If,"readCacheFile");function vf(r){try{let e=Bi(),t=wn.dirname(e);Oe.mkdirSync(t,{recursive:!0,mode:448});let s={configs:Object.fromEntries(r),updatedAt:new Date().toISOString()};Oe.writeFileSync(e,JSON.stringify(s,null,2),{mode:384})}catch{}}i(vf,"writeCacheFile");function Yc(r){let e=If();if(!e)return null;let t=new Date(e.updatedAt).getTime();return Date.now()-t>r?null:{configs:new Map(Object.entries(e.configs)),writtenAt:t}}i(Yc,"loadCacheFile");var Pf=class{static{i(this,"GitLabModelConfigRegistry")}url;ttlMs;fetchFn;memCache=null;memExpiresAt=0;pending=null;constructor(r){this.url=r?.url??Af,this.ttlMs=r?.ttlMs??Sf,this.fetchFn=r?.fetch??fetch}async getConfigs(){if(this.memCache&&Date.now()<this.memExpiresAt)return this.memCache;let r=Yc(this.ttlMs);if(r)return this.memCache=r.configs,this.memExpiresAt=r.writtenAt+this.ttlMs,r.configs;if(this.pending)return this.pending;this.pending=this.fetchConfigs();try{return await this.pending}finally{this.pending=null}}async getConfig(r){return(await this.getConfigs()).get(r)??{context:ji,output:qi}}invalidateCache(){this.memCache=null,this.memExpiresAt=0;try{let r=Bi();Oe.existsSync(r)&&Oe.unlinkSync(r)}catch{}}async fetchConfigs(){try{let r=await this.fetchFn(this.url);if(!r.ok)throw new A({message:`Failed to fetch model configs: HTTP ${r.status}`,statusCode:r.status});let e=await r.text(),t=Rf(e);return this.memCache=t,this.memExpiresAt=Date.now()+this.ttlMs,vf(t),t}catch(r){return console.warn(`gitlab-ai-provider: model config fetch failed (${r instanceof Error?r.message:String(r)}); falling back to cached or default model limits`),this.memCache??Yc(1/0)?.configs??new Map}}};function Rf(r){let e=new Map,t=null,s=0,n=0,o=!1,a=-1;for(let c of r.split(`
|
|
117
|
+
`)){let l=c.match(/^\s*gitlab_identifier:\s*"?([^"#\s]+)"?/);l&&(t&&e.set(t,{context:s||ji,output:n||qi}),t=l[1],s=0,n=0,o=!1,a=-1);let u=c.match(/^\s*max_context_tokens:\s*([0-9_]+)/);if(u&&t&&(s=parseInt(u[1].replace(/_/g,""),10)),/^\s*params:\s*$/.test(c)?(o=!0,a=c.match(/^(\s*)/)?.[1].length??0):o&&/^\s*\S+:/.test(c)&&(c.match(/^(\s*)/)?.[1].length??0)<=a&&(o=!1,a=-1),o){let f=c.match(/^\s*max_tokens:\s*([0-9_]+)/);f&&t&&(n=parseInt(f[1].replace(/_/g,""),10))}}return t&&e.set(t,{context:s||ji,output:n||qi}),e}i(Rf,"parseModelsYml");var Ef=new Pf;async function Qc(r,e){let t=await Ef.getConfigs(),s=new Map;for(let[c,l]of Object.entries(qe))l.provider==="workflow"&&c!=="duo-workflow"&&c!=="duo-workflow-default"&&s.set(l.model,c);let n=r.pinnedModel?[r.pinnedModel]:[...r.selectableModels??[],...r.defaultModel?[r.defaultModel]:[]],o=new Set,a=[];for(let c of n){if(!c.ref||o.has(c.ref))continue;o.add(c.ref);let l=s.get(c.ref)??(c.ref.startsWith("__default__")?"duo-workflow-default":`duo-workflow-${c.ref.replace(/[/_]/g,"-")}`),u=t.get(c.ref);a.push({id:l,ref:c.ref,name:c.name,context:u?.context??2e5,output:u?.output??64e3,pinned:!!r.pinnedModel&&r.pinnedModel.ref===c.ref})}return{models:a,project:e}}i(Qc,"buildModels");async function Lv(r,e){let t=new ol(e.workingDirectory,r.instanceUrl,e.cacheKey);if(!t.isDiscoveryExpired()){let l=t.load();if(l?.discovery)return Qc(l.discovery,l.project)}let s=new tl({instanceUrl:r.instanceUrl,getHeaders:r.getHeaders,fetch:r.fetch}),n=null;try{n=await s.detectProject(e.workingDirectory)}catch{return{models:[],project:null}}if(!n?.id)return{models:[],project:n};let o={projectId:`gid://gitlab/Project/${n.id}`,...n.namespaceId?{rootNamespaceId:`gid://gitlab/Group/${n.namespaceId}`}:{}},a=new rl({instanceUrl:r.instanceUrl,getHeaders:r.getHeaders,fetch:r.fetch}),c;try{c=await a.discover(o)}catch{return{models:[],project:n}}if(t.saveDiscovery(c,n),!t.getSelectedModelRef()){let l=c.pinnedModel??c.defaultModel;l&&t.saveSelection(l.ref,l.name)}return Qc(c,n)}i(Lv,"discoverWorkflowModels");export{A as a,Nd as b,Fd as c,Bc as d,_n as e,jd as f,Fi as g,xs as h,Bd as i,Wd as j,Jd as k,Vd as l,Zc as m,Xd as n,qe as o,Gc as p,Pv as q,zd as r,Rv as s,Ev as t,Yd as u,Qd as v,Zd as w,ef as x,Cv as y,tf as z,Di as A,Kc as B,nf as C,tl as D,rl as E,ol as F,pf as G,mf as H,gf as I,$v as J,il as K,_f as L,Nv as M,al as N,kf as O,Fv as P,Pf as Q,Rf as R,Lv as S};
|