alchemylab-opencode 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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-ND6UHXWL.js +18 -0
- package/dist/app-runtime-ZWWQ4JTM.js +18 -0
- package/dist/chunk-2MRHL4B2.js +18 -0
- package/dist/chunk-2XWBNI3L.js +1490 -0
- package/dist/chunk-4MBUHJHY.js +22 -0
- package/dist/chunk-6MAPFAXY.js +190 -0
- package/dist/chunk-7XX6TY62.js +259 -0
- package/dist/chunk-ANF3QA3Z.js +48 -0
- package/dist/chunk-AUB2TEYJ.js +55 -0
- package/dist/chunk-AZUMH3TO.js +18 -0
- package/dist/chunk-BQ4IEPN3.js +19 -0
- package/dist/chunk-CYRZU5QM.js +33 -0
- package/dist/chunk-DGJQZN2Q.js +18 -0
- package/dist/chunk-DO2UZ6NY.js +18 -0
- package/dist/chunk-DZ6G4VSD.js +19 -0
- package/dist/chunk-EK6FQQHY.js +20 -0
- package/dist/chunk-ELPXQ32J.js +90 -0
- package/dist/chunk-F5PY52BY.js +18 -0
- package/dist/chunk-FGLPSSRK.js +19 -0
- package/dist/chunk-FV7U6PVP.js +18 -0
- package/dist/chunk-FYYAOZPU.js +18 -0
- package/dist/chunk-GDWO6EXN.js +22 -0
- package/dist/chunk-GW3ZRKAI.js +20 -0
- package/dist/chunk-IQSFXWDQ.js +18 -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-L3CE2Y3L.js +55 -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-OCWGUTZJ.js +36 -0
- package/dist/chunk-OGDRUXMJ.js +18 -0
- package/dist/chunk-OGJKLJC7.js +29 -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-RIA6SDOY.js +780 -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-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-WL33KE3H.js +920 -0
- package/dist/chunk-WPMP2ZFE.js +40 -0
- package/dist/chunk-WRTNIOI3.js +18 -0
- package/dist/chunk-WZ4237YY.js +19 -0
- package/dist/chunk-X5F46HR5.js +18 -0
- package/dist/chunk-XPS7TQZG.js +22 -0
- package/dist/chunk-XSKT4AXR.js +878 -0
- package/dist/chunk-YJPP6IQ3.js +23 -0
- package/dist/chunk-ZYQWFC55.js +22 -0
- package/dist/code-mode-H3HRSD24.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/dist-HXJTF22W.js +32 -0
- package/dist/dist-JFXI53ZF.js +22 -0
- package/dist/dist-KBYKWVT5.js +22 -0
- package/dist/dist-KGNO5AP7.js +35 -0
- package/dist/dist-KTNLTEHB.js +18 -0
- package/dist/dist-KZ5R5QM5.js +24 -0
- package/dist/{20260605042240_add_context_epoch_agent-W6IQYZXE.js → dist-LOXU6IEM.js} +5 -1
- 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-WZJ3LNRG.js +28 -0
- package/dist/dist-XAFENVUS.js +22 -0
- package/dist/dist-XPFB35TX.js +32 -0
- package/dist/dist-es-43ZM44MP.js +18 -0
- package/dist/dist-es-CH2YKBKX.js +18 -0
- package/dist/{20260428004200_add_session_path-LGW75WYA.js → dist-es-DHCTZZ2E.js} +5 -1
- package/dist/dist-es-EVVG3KDV.js +26 -0
- package/dist/dist-es-HRCONNGK.js +18 -0
- package/dist/dist-es-L2GU465G.js +18 -0
- package/dist/dist-es-RGEIM2BP.js +18 -0
- package/dist/dist-es-RZ25XEH6.js +18 -0
- package/dist/dist-es-SITTNOGV.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-7VH6D2QJ.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-GSWEOYZ5.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-XRUYBM7W.js +21 -0
- package/dist/session-4BXV4JJH.js +18 -0
- package/dist/signin-DKBWDEYP.js +18 -0
- package/dist/src-JODD73WX.js +18 -0
- package/dist/src-QJHT5SCV.js +18 -0
- package/dist/src-SMM4U63G.js +18 -0
- package/dist/src-WDYKISPD.js +20 -0
- package/dist/sso-oidc-S3P64MCY.js +18 -0
- package/dist/sts-RG44NMOQ.js +18 -0
- package/dist/token-2V62AM3G.js +18 -0
- package/dist/token-util-VXONHEUD.js +18 -0
- package/dist/unified-W3ZKZ4HG.js +18 -0
- package/dist/worktree-B2LROS2B.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,18 @@
|
|
|
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{c as K}from"./chunk-OCWGUTZJ.js";import{f as N,j as H}from"./chunk-CYRZU5QM.js";import{a as d,g as y}from"./chunk-2MRHL4B2.js";var F=y(K()),p=y(N());var f=y(N()),b=y(H());import{createHash as v,createPrivateKey as _,createPublicKey as B,sign as q}from"node:crypto";import{promises as D}from"node:fs";import{homedir as U}from"node:os";import{dirname as j,join as R}from"node:path";var m=class a{static{d(this,"LoginCredentialsFetcher")}profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300*1e3;constructor(e,t,s){this.profileData=e,this.init=t,this.callerClientConfig=s}async loadCredentials(){let e=await this.loadToken();if(!e)throw new f.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let t=e.accessToken,s=Date.now();return new Date(t.expiresAt).getTime()-s<=a.REFRESH_THRESHOLD?this.refresh(e):this.toCredentials(e.accessToken)}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}toCredentials(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,sessionToken:e.sessionToken,accountId:e.accountId,expiration:new Date(e.expiresAt)}}async refresh(e){let t=await this.loadToken().catch(()=>e),s=Date.now(),r=new Date(t.accessToken.expiresAt).getTime(),i=new Date(e.accessToken.expiresAt).getTime(),o=r<=s&&i>s?e:t;if(new Date(o.accessToken.expiresAt).getTime()-Date.now()>a.REFRESH_THRESHOLD)return this.toCredentials(o.accessToken);let{SigninClient:h,CreateOAuth2TokenCommand:T}=await import("./signin-DKBWDEYP.js"),{logger:x,userAgentAppId:E}=this.callerClientConfig??{},S=d(n=>n?.metadata?.handlerProtocol==="h2","isH2")(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,u=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,k=new h({credentials:{accessKeyId:"",secretAccessKey:""},region:u,requestHandler:S,logger:x,userAgentAppId:E,...this.init?.clientConfig});this.createDPoPInterceptor(k.middlewareStack);let I={tokenInput:{clientId:o.clientId,refreshToken:o.refreshToken,grantType:"refresh_token"}};try{let n=await k.send(new T(I)),{accessKeyId:l,secretAccessKey:w,sessionToken:g}=n.tokenOutput?.accessToken??{},{refreshToken:P,expiresIn:L}=n.tokenOutput??{};if(!l||!w||!g||!P)throw new f.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let O=(L??900)*1e3,$=new Date(Date.now()+O),A={...o,accessToken:{...o.accessToken,accessKeyId:l,secretAccessKey:w,sessionToken:g,expiresAt:$.toISOString()},refreshToken:P};return await this.saveToken(A),this.toCredentials(A.accessToken)}catch(n){if(n.name==="AccessDeniedException"){let w=n.error,g;switch(w){case"TOKEN_EXPIRED":g="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":g="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":g="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:g=`Failed to refresh token: ${String(n)}. Please re-authenticate using \`aws login\``}throw new f.CredentialsProviderError(g,{logger:this.logger,tryNextLink:!1})}if(new Date(o.accessToken.expiresAt).getTime()>Date.now())return this.logger?.warn?.(`Failed to refresh token: ${String(n)}. Using existing token until expiry.`),this.toCredentials(o.accessToken);throw new f.CredentialsProviderError(`Failed to refresh token: ${String(n)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let t=await D.readFile(e,"utf8"),s=JSON.parse(t),r=["accessToken","clientId","refreshToken","dpopKey"].filter(i=>!s[i]);if(s.accessToken?.accountId||r.push("accountId"),r.length>0)throw new f.CredentialsProviderError(`Token validation failed, missing fields: ${r.join(", ")}`,{logger:this.logger,tryNextLink:!1});return s}catch(t){throw new f.CredentialsProviderError(`Failed to load token from ${e}: ${String(t)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let t=this.getTokenFilePath(),s=j(t);try{await D.mkdir(s,{recursive:!0})}catch{}await D.writeFile(t,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??R(U(),".aws","login","cache"),t=Buffer.from(this.loginSession,"utf8"),s=v("sha256").update(t).digest("hex");return R(e,`${s}.json`)}derToRawSignature(e){let t=2;if(e[t]!==2)throw new Error("Invalid DER signature");t++;let s=e[t++],r=e.subarray(t,t+s);if(t+=s,e[t]!==2)throw new Error("Invalid DER signature");t++;let i=e[t++],o=e.subarray(t,t+i);r=r[0]===0?r.subarray(1):r,o=o[0]===0?o.subarray(1):o;let c=Buffer.concat([Buffer.alloc(32-r.length),r]),h=Buffer.concat([Buffer.alloc(32-o.length),o]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add(t=>async s=>{if(b.HttpRequest.isInstance(s.request)){let r=s.request,i=`${r.protocol}//${r.hostname}${r.port?`:${r.port}`:""}${r.path}`,o=await this.generateDpop(r.method,i);r.headers={...r.headers,DPoP:o}}return t(s)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",t){let s=await this.loadToken();try{let r=_({key:s.dpopKey,format:"pem",type:"sec1"}),o=B(r).export({format:"der",type:"spki"}),c=-1;for(let l=0;l<o.length;l++)if(o[l]===4){c=l;break}let h=o.slice(c+1,c+33),T=o.slice(c+33,c+65),x={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:T.toString("base64url")}},E={jti:crypto.randomUUID(),htm:e,htu:t,iat:Math.floor(Date.now()/1e3)},C=Buffer.from(JSON.stringify(x)).toString("base64url"),S=Buffer.from(JSON.stringify(E)).toString("base64url"),u=`${C}.${S}`,k=q("sha256",Buffer.from(u),r),n=this.derToRawSignature(k).toString("base64url");return`${u}.${n}`}catch(r){throw new f.CredentialsProviderError(`Failed to generate Dpop proof: ${r instanceof Error?r.message:String(r)}`,{logger:this.logger,tryNextLink:!1})}}};var G=d(a=>async({callerClientConfig:e}={})=>{a?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await(0,p.parseKnownFiles)(a||{}),s=(0,p.getProfileName)({profile:a?.profile??e?.profile}),r=t[s];if(!r?.login_session)throw new p.CredentialsProviderError(`Profile ${s} does not contain login_session.`,{tryNextLink:!0,logger:a?.logger});let o=await new m(r,a,e).loadCredentials();return(0,F.setCredentialFeature)(o,"CREDENTIALS_LOGIN","AD")},"fromLoginCredentials");export{G as a};
|
|
@@ -0,0 +1,19 @@
|
|
|
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 Re,b as Ae,c as Ue,d as we,e as ve,f as qe,g as $e,h as De,i as Be,j as xe,k as _,l as m,m as re,n as Fe,o as _e,p as Se,q as V,r as G,s as Ce,t as He,u as Je,v as Le,w as We}from"./chunk-VXAPFOIL.js";import{b as Ee,e as Pe,g as Me,k as je,n as be}from"./chunk-WKZYINC7.js";import{A as e}from"./chunk-WPMP2ZFE.js";import{a as v}from"./chunk-2MRHL4B2.js";var gt="3.0.111",bt=_(()=>m(e.object({type:e.literal("error"),error:e.object({type:e.string(),message:e.string()})}))),Ke=He({errorSchema:bt,errorToMessage:v(t=>t.error.message,"errorToMessage")}),nt=e.object({type:e.string(),category:e.string().nullish(),explanation:e.string().nullish(),recommended_model:e.string().nullish()}),pe=e.union([e.object({type:e.literal("code_execution_20250825"),tool_id:e.string()}),e.object({type:e.literal("code_execution_20260120"),tool_id:e.string()}),e.object({type:e.literal("direct")})]),ft=_(()=>m(e.object({type:e.literal("message"),id:e.string().nullish(),model:e.string().nullish(),input_transformations:e.array(e.looseObject({type:e.string(),path:e.string().nullish(),reason:e.string().nullish()})).nullish(),content:e.array(e.discriminatedUnion("type",[e.object({type:e.literal("text"),text:e.string(),citations:e.array(e.discriminatedUnion("type",[e.object({type:e.literal("web_search_result_location"),cited_text:e.string(),url:e.string(),title:e.string(),encrypted_index:e.string()}),e.object({type:e.literal("page_location"),cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),start_page_number:e.number(),end_page_number:e.number()}),e.object({type:e.literal("char_location"),cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),start_char_index:e.number(),end_char_index:e.number()})])).optional()}),e.object({type:e.literal("thinking"),thinking:e.string(),signature:e.string()}),e.object({type:e.literal("redacted_thinking"),data:e.string()}),e.object({type:e.literal("compaction"),content:e.string()}),e.object({type:e.literal("tool_use"),id:e.string(),name:e.string(),input:e.unknown(),caller:pe.optional()}),e.object({type:e.literal("server_tool_use"),id:e.string(),name:e.string(),input:e.record(e.string(),e.unknown()).nullish(),caller:pe.optional()}),e.object({type:e.literal("mcp_tool_use"),id:e.string(),name:e.string(),input:e.unknown(),server_name:e.string()}),e.object({type:e.literal("mcp_tool_result"),tool_use_id:e.string(),is_error:e.boolean(),content:e.array(e.union([e.string(),e.object({type:e.literal("text"),text:e.string()})]))}),e.object({type:e.literal("web_fetch_tool_result"),tool_use_id:e.string(),caller:pe.optional(),content:e.union([e.object({type:e.literal("web_fetch_result"),url:e.string(),retrieved_at:e.string(),content:e.object({type:e.literal("document"),title:e.string().nullable(),citations:e.object({enabled:e.boolean()}).optional(),source:e.union([e.object({type:e.literal("base64"),media_type:e.literal("application/pdf"),data:e.string()}),e.object({type:e.literal("text"),media_type:e.literal("text/plain"),data:e.string()})])})}),e.object({type:e.literal("web_fetch_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("web_search_tool_result"),tool_use_id:e.string(),caller:pe.optional(),content:e.union([e.array(e.object({type:e.literal("web_search_result"),url:e.string(),title:e.string(),encrypted_content:e.string(),page_age:e.string().nullish()})),e.object({type:e.literal("web_search_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("code_execution_tool_result"),tool_use_id:e.string(),content:e.union([e.object({type:e.literal("code_execution_result"),stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("encrypted_code_execution_result"),encrypted_stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("code_execution_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("bash_code_execution_tool_result"),tool_use_id:e.string(),content:e.discriminatedUnion("type",[e.object({type:e.literal("bash_code_execution_result"),content:e.array(e.object({type:e.literal("bash_code_execution_output"),file_id:e.string()})),stdout:e.string(),stderr:e.string(),return_code:e.number()}),e.object({type:e.literal("bash_code_execution_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("text_editor_code_execution_tool_result"),tool_use_id:e.string(),content:e.discriminatedUnion("type",[e.object({type:e.literal("text_editor_code_execution_tool_result_error"),error_code:e.string()}),e.object({type:e.literal("text_editor_code_execution_view_result"),content:e.string(),file_type:e.string(),num_lines:e.number().nullable(),start_line:e.number().nullable(),total_lines:e.number().nullable()}),e.object({type:e.literal("text_editor_code_execution_create_result"),is_file_update:e.boolean()}),e.object({type:e.literal("text_editor_code_execution_str_replace_result"),lines:e.array(e.string()).nullable(),new_lines:e.number().nullable(),new_start:e.number().nullable(),old_lines:e.number().nullable(),old_start:e.number().nullable()})])}),e.object({type:e.literal("tool_search_tool_result"),tool_use_id:e.string(),content:e.union([e.object({type:e.literal("tool_search_tool_search_result"),tool_references:e.array(e.object({type:e.literal("tool_reference"),tool_name:e.string()}))}),e.object({type:e.literal("tool_search_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("advisor_tool_result"),tool_use_id:e.string(),content:e.discriminatedUnion("type",[e.object({type:e.literal("advisor_result"),text:e.string()}),e.object({type:e.literal("advisor_redacted_result"),encrypted_content:e.string()}),e.object({type:e.literal("advisor_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("fallback")})])),stop_reason:e.string().nullish(),stop_sequence:e.string().nullish(),stop_details:nt.nullish(),usage:e.looseObject({input_tokens:e.number(),output_tokens:e.number(),output_tokens_details:e.object({thinking_tokens:e.number().nullish()}).nullish(),cache_creation_input_tokens:e.number().nullish(),cache_read_input_tokens:e.number().nullish(),iterations:e.array(e.object({type:e.union([e.literal("compaction"),e.literal("message"),e.literal("advisor_message"),e.literal("fallback_message")]),model:e.string().nullish(),input_tokens:e.number(),output_tokens:e.number(),cache_creation_input_tokens:e.number().nullish(),cache_read_input_tokens:e.number().nullish()})).nullish()}),container:e.object({expires_at:e.string(),id:e.string(),skills:e.array(e.object({type:e.union([e.literal("anthropic"),e.literal("custom")]),skill_id:e.string(),version:e.string()})).nullish()}).nullish(),context_management:e.object({applied_edits:e.array(e.union([e.object({type:e.literal("clear_tool_uses_20250919"),cleared_tool_uses:e.number(),cleared_input_tokens:e.number()}),e.object({type:e.literal("clear_thinking_20251015"),cleared_thinking_turns:e.number(),cleared_input_tokens:e.number()}),e.object({type:e.literal("compact_20260112")})]))}).nullish()}))),vt=_(()=>m(e.discriminatedUnion("type",[e.object({type:e.literal("message_start"),message:e.object({id:e.string().nullish(),model:e.string().nullish(),role:e.string().nullish(),input_transformations:e.array(e.looseObject({type:e.string(),path:e.string().nullish(),reason:e.string().nullish()})).nullish(),usage:e.looseObject({input_tokens:e.number(),cache_creation_input_tokens:e.number().nullish(),cache_read_input_tokens:e.number().nullish()}),content:e.array(e.discriminatedUnion("type",[e.object({type:e.literal("tool_use"),id:e.string(),name:e.string(),input:e.unknown(),caller:pe.optional()})])).nullish(),stop_reason:e.string().nullish(),container:e.object({expires_at:e.string(),id:e.string()}).nullish()})}),e.object({type:e.literal("content_block_start"),index:e.number(),content_block:e.discriminatedUnion("type",[e.object({type:e.literal("text"),text:e.string()}),e.object({type:e.literal("thinking"),thinking:e.string()}),e.object({type:e.literal("tool_use"),id:e.string(),name:e.string(),input:e.record(e.string(),e.unknown()).optional(),caller:pe.optional()}),e.object({type:e.literal("redacted_thinking"),data:e.string()}),e.object({type:e.literal("compaction"),content:e.string().nullish()}),e.object({type:e.literal("server_tool_use"),id:e.string(),name:e.string(),input:e.record(e.string(),e.unknown()).nullish(),caller:pe.optional()}),e.object({type:e.literal("mcp_tool_use"),id:e.string(),name:e.string(),input:e.unknown(),server_name:e.string()}),e.object({type:e.literal("mcp_tool_result"),tool_use_id:e.string(),is_error:e.boolean(),content:e.array(e.union([e.string(),e.object({type:e.literal("text"),text:e.string()})]))}),e.object({type:e.literal("web_fetch_tool_result"),tool_use_id:e.string(),caller:pe.optional(),content:e.union([e.object({type:e.literal("web_fetch_result"),url:e.string(),retrieved_at:e.string(),content:e.object({type:e.literal("document"),title:e.string().nullable(),citations:e.object({enabled:e.boolean()}).optional(),source:e.union([e.object({type:e.literal("base64"),media_type:e.literal("application/pdf"),data:e.string()}),e.object({type:e.literal("text"),media_type:e.literal("text/plain"),data:e.string()})])})}),e.object({type:e.literal("web_fetch_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("web_search_tool_result"),tool_use_id:e.string(),caller:pe.optional(),content:e.union([e.array(e.object({type:e.literal("web_search_result"),url:e.string(),title:e.string(),encrypted_content:e.string(),page_age:e.string().nullish()})),e.object({type:e.literal("web_search_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("code_execution_tool_result"),tool_use_id:e.string(),content:e.union([e.object({type:e.literal("code_execution_result"),stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("encrypted_code_execution_result"),encrypted_stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("code_execution_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("bash_code_execution_tool_result"),tool_use_id:e.string(),content:e.discriminatedUnion("type",[e.object({type:e.literal("bash_code_execution_result"),content:e.array(e.object({type:e.literal("bash_code_execution_output"),file_id:e.string()})),stdout:e.string(),stderr:e.string(),return_code:e.number()}),e.object({type:e.literal("bash_code_execution_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("text_editor_code_execution_tool_result"),tool_use_id:e.string(),content:e.discriminatedUnion("type",[e.object({type:e.literal("text_editor_code_execution_tool_result_error"),error_code:e.string()}),e.object({type:e.literal("text_editor_code_execution_view_result"),content:e.string(),file_type:e.string(),num_lines:e.number().nullable(),start_line:e.number().nullable(),total_lines:e.number().nullable()}),e.object({type:e.literal("text_editor_code_execution_create_result"),is_file_update:e.boolean()}),e.object({type:e.literal("text_editor_code_execution_str_replace_result"),lines:e.array(e.string()).nullable(),new_lines:e.number().nullable(),new_start:e.number().nullable(),old_lines:e.number().nullable(),old_start:e.number().nullable()})])}),e.object({type:e.literal("tool_search_tool_result"),tool_use_id:e.string(),content:e.union([e.object({type:e.literal("tool_search_tool_search_result"),tool_references:e.array(e.object({type:e.literal("tool_reference"),tool_name:e.string()}))}),e.object({type:e.literal("tool_search_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("advisor_tool_result"),tool_use_id:e.string(),content:e.discriminatedUnion("type",[e.object({type:e.literal("advisor_result"),text:e.string()}),e.object({type:e.literal("advisor_redacted_result"),encrypted_content:e.string()}),e.object({type:e.literal("advisor_tool_result_error"),error_code:e.string()})])}),e.object({type:e.literal("fallback")})])}),e.object({type:e.literal("content_block_delta"),index:e.number(),delta:e.discriminatedUnion("type",[e.object({type:e.literal("input_json_delta"),partial_json:e.string()}),e.object({type:e.literal("text_delta"),text:e.string()}),e.object({type:e.literal("thinking_delta"),thinking:e.string()}),e.object({type:e.literal("signature_delta"),signature:e.string()}),e.object({type:e.literal("compaction_delta"),content:e.string().nullish()}),e.object({type:e.literal("citations_delta"),citation:e.discriminatedUnion("type",[e.object({type:e.literal("web_search_result_location"),cited_text:e.string(),url:e.string(),title:e.string(),encrypted_index:e.string()}),e.object({type:e.literal("page_location"),cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),start_page_number:e.number(),end_page_number:e.number()}),e.object({type:e.literal("char_location"),cited_text:e.string(),document_index:e.number(),document_title:e.string().nullable(),start_char_index:e.number(),end_char_index:e.number()})])})])}),e.object({type:e.literal("content_block_stop"),index:e.number()}),e.object({type:e.literal("error"),error:e.object({type:e.string(),message:e.string()})}),e.object({type:e.literal("message_delta"),delta:e.object({stop_reason:e.string().nullish(),stop_sequence:e.string().nullish(),stop_details:nt.nullish(),container:e.object({expires_at:e.string(),id:e.string(),skills:e.array(e.object({type:e.union([e.literal("anthropic"),e.literal("custom")]),skill_id:e.string(),version:e.string()})).nullish()}).nullish()}),usage:e.looseObject({input_tokens:e.number().nullish(),output_tokens:e.number(),output_tokens_details:e.object({thinking_tokens:e.number().nullish()}).nullish(),cache_creation_input_tokens:e.number().nullish(),cache_read_input_tokens:e.number().nullish(),iterations:e.array(e.object({type:e.union([e.literal("compaction"),e.literal("message"),e.literal("advisor_message"),e.literal("fallback_message")]),model:e.string().nullish(),input_tokens:e.number(),output_tokens:e.number(),cache_creation_input_tokens:e.number().nullish(),cache_read_input_tokens:e.number().nullish()})).nullish()}),context_management:e.object({applied_edits:e.array(e.union([e.object({type:e.literal("clear_tool_uses_20250919"),cleared_tool_uses:e.number(),cleared_input_tokens:e.number()}),e.object({type:e.literal("clear_thinking_20251015"),cleared_thinking_turns:e.number(),cleared_input_tokens:e.number()}),e.object({type:e.literal("compact_20260112")})]))}).nullish()}),e.object({type:e.literal("message_stop")}),e.object({type:e.literal("ping")})]))),xt=_(()=>m(e.object({signature:e.string().optional(),redactedData:e.string().optional()}))),Ve=e.object({citations:e.object({enabled:e.boolean()}).optional(),title:e.string().optional(),context:e.string().optional()}),kt=e.object({toolChanges:e.array(e.discriminatedUnion("type",[e.object({type:e.literal("tool_addition"),toolName:e.string()}),e.object({type:e.literal("tool_removal"),toolName:e.string()})])).optional()}),Ge=e.object({sendReasoning:e.boolean().optional(),structuredOutputMode:e.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:e.discriminatedUnion("type",[e.object({type:e.literal("adaptive"),display:e.enum(["omitted","summarized"]).optional(),blockBinding:e.object({prefixMismatchBehavior:e.enum(["error","drop_block"])}).optional()}),e.object({type:e.literal("enabled"),budgetTokens:e.number().optional(),blockBinding:e.object({prefixMismatchBehavior:e.enum(["error","drop_block"])}).optional()}),e.object({type:e.literal("disabled")})]).optional(),disableParallelToolUse:e.boolean().optional(),cacheControl:e.object({type:e.literal("ephemeral"),ttl:e.union([e.literal("5m"),e.literal("1h")]).optional()}).optional(),metadata:e.object({userId:e.string().optional()}).optional(),mcpServers:e.array(e.object({type:e.literal("url"),name:e.string(),url:e.string(),authorizationToken:e.string().nullish(),toolConfiguration:e.object({enabled:e.boolean().nullish(),allowedTools:e.array(e.string()).nullish()}).nullish()})).optional(),container:e.object({id:e.string().optional(),skills:e.array(e.object({type:e.union([e.literal("anthropic"),e.literal("custom")]),skillId:e.string(),version:e.string().optional()})).optional()}).optional(),toolStreaming:e.boolean().optional(),effort:e.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:e.object({type:e.literal("tokens"),total:e.number().int().min(2e4),remaining:e.number().int().min(0).optional()}).optional(),speed:e.enum(["fast","standard"]).optional(),inferenceGeo:e.enum(["us","global"]).optional(),fallbacks:e.union([e.literal("default"),e.array(e.object({model:e.string(),max_tokens:e.number().int().optional(),thinking:e.record(e.string(),e.unknown()).optional(),output_config:e.record(e.string(),e.unknown()).optional(),speed:e.enum(["fast","standard"]).optional()}))]).optional(),anthropicBeta:e.array(e.string()).optional(),contextManagement:e.object({edits:e.array(e.discriminatedUnion("type",[e.object({type:e.literal("clear_tool_uses_20250919"),trigger:e.discriminatedUnion("type",[e.object({type:e.literal("input_tokens"),value:e.number()}),e.object({type:e.literal("tool_uses"),value:e.number()})]).optional(),keep:e.object({type:e.literal("tool_uses"),value:e.number()}).optional(),clearAtLeast:e.object({type:e.literal("input_tokens"),value:e.number()}).optional(),clearToolInputs:e.boolean().optional(),excludeTools:e.array(e.string()).optional()}),e.object({type:e.literal("clear_thinking_20251015"),keep:e.union([e.literal("all"),e.object({type:e.literal("thinking_turns"),value:e.number()})]).optional()}),e.object({type:e.literal("compact_20260112"),trigger:e.object({type:e.literal("input_tokens"),value:e.number()}).optional(),pauseAfterCompaction:e.boolean().optional(),instructions:e.string().optional()})]))}).optional()}),Ye=4;function jt(t){var a;let n=t?.anthropic;return(a=n?.cacheControl)!=null?a:n?.cache_control}v(jt,"getCacheControl");var Ie=class{static{v(this,"CacheControlValidator")}constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(t,a){let n=jt(t);if(n){if(!a.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${a.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>Ye){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${Ye} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},wt=_(()=>m(e.object({model:e.string(),maxUses:e.number().optional(),caching:e.object({type:e.literal("ephemeral"),ttl:e.union([e.literal("5m"),e.literal("1h")])}).optional()}))),at=_(()=>m(e.discriminatedUnion("type",[e.object({type:e.literal("advisor_result"),text:e.string()}),e.object({type:e.literal("advisor_redacted_result"),encryptedContent:e.string()}),e.object({type:e.literal("advisor_tool_result_error"),errorCode:e.string()})]))),St=_(()=>m(e.object({}).strict())),Ct=G({id:"anthropic.advisor_20260301",inputSchema:St,outputSchema:at,supportsDeferredResults:!0}),Tt=v(t=>Ct(t),"advisor_20260301"),Nt=_(()=>m(e.object({maxCharacters:e.number().optional()}))),Ot=_(()=>m(e.object({command:e.enum(["view","create","str_replace","insert"]),path:e.string(),file_text:e.string().optional(),insert_line:e.number().int().optional(),new_str:e.string().optional(),insert_text:e.string().optional(),old_str:e.string().optional(),view_range:e.array(e.number().int()).optional()}))),It=V({id:"anthropic.text_editor_20250728",inputSchema:Ot}),zt=v((t={})=>It(t),"textEditor_20250728"),Et=_(()=>m(e.object({maxUses:e.number().optional(),allowedDomains:e.array(e.string()).optional(),blockedDomains:e.array(e.string()).optional(),userLocation:e.object({type:e.literal("approximate"),city:e.string().optional(),region:e.string().optional(),country:e.string().optional(),timezone:e.string().optional()}).optional()}))),Pt=_(()=>m(e.array(e.object({url:e.string(),title:e.string().nullable(),pageAge:e.string().nullable(),encryptedContent:e.string(),type:e.literal("web_search_result")})))),Mt=_(()=>m(e.object({query:e.string()}))),Rt=G({id:"anthropic.web_search_20260209",inputSchema:Mt,outputSchema:Pt,supportsDeferredResults:!0}),At=v((t={})=>Rt(t),"webSearch_20260209"),Ut=_(()=>m(e.object({maxUses:e.number().optional(),allowedDomains:e.array(e.string()).optional(),blockedDomains:e.array(e.string()).optional(),userLocation:e.object({type:e.literal("approximate"),city:e.string().optional(),region:e.string().optional(),country:e.string().optional(),timezone:e.string().optional()}).optional()}))),it=_(()=>m(e.array(e.object({url:e.string(),title:e.string().nullable(),pageAge:e.string().nullable(),encryptedContent:e.string(),type:e.literal("web_search_result")})))),qt=_(()=>m(e.object({query:e.string()}))),$t=G({id:"anthropic.web_search_20250305",inputSchema:qt,outputSchema:it,supportsDeferredResults:!0}),Dt=v((t={})=>$t(t),"webSearch_20250305"),Bt=_(()=>m(e.object({maxUses:e.number().optional(),allowedDomains:e.array(e.string()).optional(),blockedDomains:e.array(e.string()).optional(),citations:e.object({enabled:e.boolean()}).optional(),maxContentTokens:e.number().optional()}))),Ft=_(()=>m(e.object({type:e.literal("web_fetch_result"),url:e.string(),content:e.object({type:e.literal("document"),title:e.string().nullable(),citations:e.object({enabled:e.boolean()}).optional(),source:e.union([e.object({type:e.literal("base64"),mediaType:e.literal("application/pdf"),data:e.string()}),e.object({type:e.literal("text"),mediaType:e.literal("text/plain"),data:e.string()})])}),retrievedAt:e.string().nullable()}))),Ht=_(()=>m(e.object({url:e.string()}))),Jt=G({id:"anthropic.web_fetch_20260209",inputSchema:Ht,outputSchema:Ft,supportsDeferredResults:!0}),Lt=v((t={})=>Jt(t),"webFetch_20260209"),Wt=_(()=>m(e.object({maxUses:e.number().optional(),allowedDomains:e.array(e.string()).optional(),blockedDomains:e.array(e.string()).optional(),citations:e.object({enabled:e.boolean()}).optional(),maxContentTokens:e.number().optional()}))),lt=_(()=>m(e.object({type:e.literal("web_fetch_result"),url:e.string(),content:e.object({type:e.literal("document"),title:e.string().nullable(),citations:e.object({enabled:e.boolean()}).optional(),source:e.union([e.object({type:e.literal("base64"),mediaType:e.literal("application/pdf"),data:e.string()}),e.object({type:e.literal("text"),mediaType:e.literal("text/plain"),data:e.string()})])}),retrievedAt:e.string().nullable()}))),Kt=_(()=>m(e.object({url:e.string()}))),Vt=G({id:"anthropic.web_fetch_20250910",inputSchema:Kt,outputSchema:lt,supportsDeferredResults:!0}),Gt=v((t={})=>Vt(t),"webFetch_20250910");async function Yt({tools:t,toolChoice:a,disableParallelToolUse:n,cacheControlValidator:c,supportsStructuredOutput:y,supportsStrictTools:P,defaultEagerInputStreaming:q=!1}){var T,F;t=t?.length?t:void 0;let I=[],z=new Set,H=c||new Ie;if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:I,betas:z};let E=[];for(let x of t)switch(x.type){case"function":{let j=H.getCacheControl(x.providerOptions,{type:"tool definition",canCache:!0}),A=(T=x.providerOptions)==null?void 0:T.anthropic,J=(F=A?.eagerInputStreaming)!=null?F:q,Q=A?.deferLoading,U=A?.allowedCallers;!P&&x.strict!=null&&I.push({type:"unsupported",feature:"strict",details:`Tool '${x.name}' has strict: ${x.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),E.push({name:x.name,description:x.description,input_schema:x.inputSchema,cache_control:j,...J?{eager_input_streaming:!0}:{},...P===!0&&x.strict!=null?{strict:x.strict}:{},...Q!=null?{defer_loading:Q}:{},...U!=null?{allowed_callers:U}:{},...x.inputExamples!=null?{input_examples:x.inputExamples.map(le=>le.input)}:{}}),y===!0&&z.add("structured-outputs-2025-11-13"),(x.inputExamples!=null||U!=null)&&z.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(x.id){case"anthropic.code_execution_20250522":{z.add("code-execution-2025-05-22"),E.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{z.add("code-execution-2025-08-25"),E.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{E.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{z.add("computer-use-2025-01-24"),E.push({name:"computer",type:"computer_20250124",display_width_px:x.args.displayWidthPx,display_height_px:x.args.displayHeightPx,display_number:x.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{z.add("computer-use-2025-11-24"),E.push({name:"computer",type:"computer_20251124",display_width_px:x.args.displayWidthPx,display_height_px:x.args.displayHeightPx,display_number:x.args.displayNumber,enable_zoom:x.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{z.add("computer-use-2024-10-22"),E.push({name:"computer",type:"computer_20241022",display_width_px:x.args.displayWidthPx,display_height_px:x.args.displayHeightPx,display_number:x.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{z.add("computer-use-2025-01-24"),E.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{z.add("computer-use-2024-10-22"),E.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{z.add("computer-use-2025-01-24"),E.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let j=await re({value:x.args,schema:Nt});E.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:j.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{z.add("computer-use-2025-01-24"),E.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{z.add("computer-use-2024-10-22"),E.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{z.add("context-management-2025-06-27"),E.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{z.add("web-fetch-2025-09-10");let j=await re({value:x.args,schema:Wt});E.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:j.maxUses,allowed_domains:j.allowedDomains,blocked_domains:j.blockedDomains,citations:j.citations,max_content_tokens:j.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{z.add("code-execution-web-tools-2026-02-09");let j=await re({value:x.args,schema:Bt});E.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:j.maxUses,allowed_domains:j.allowedDomains,blocked_domains:j.blockedDomains,citations:j.citations,max_content_tokens:j.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let j=await re({value:x.args,schema:Ut});E.push({type:"web_search_20250305",name:"web_search",max_uses:j.maxUses,allowed_domains:j.allowedDomains,blocked_domains:j.blockedDomains,user_location:j.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{z.add("code-execution-web-tools-2026-02-09");let j=await re({value:x.args,schema:Et});E.push({type:"web_search_20260209",name:"web_search",max_uses:j.maxUses,allowed_domains:j.allowedDomains,blocked_domains:j.blockedDomains,user_location:j.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{E.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{E.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}case"anthropic.advisor_20260301":{z.add("advisor-tool-2026-03-01");let j=await re({value:x.args,schema:wt});E.push({type:"advisor_20260301",name:"advisor",model:j.model,...j.maxUses!==void 0&&{max_uses:j.maxUses},...j.caching!==void 0&&{caching:j.caching}});break}default:{I.push({type:"unsupported",feature:`provider-defined tool ${x.id}`});break}}break}default:{I.push({type:"unsupported",feature:`tool ${x}`});break}}if(a==null)return{tools:E,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:I,betas:z};let R=a.type;switch(R){case"auto":return{tools:E,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:I,betas:z};case"required":return{tools:E,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:I,betas:z};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:I,betas:z};case"tool":return{tools:E,toolChoice:{type:"tool",name:a.toolName,disable_parallel_tool_use:n},toolWarnings:I,betas:z};default:{let x=R;throw new be({functionality:`tool choice type: ${x}`})}}}v(Yt,"prepareTools");function Ze({usage:t,rawUsage:a}){var n,c,y,P,q;let T=(n=t.cache_creation_input_tokens)!=null?n:0,F=(c=t.cache_read_input_tokens)!=null?c:0,I=(P=(y=t.output_tokens_details)==null?void 0:y.thinking_tokens)!=null?P:void 0,z,H,E=(q=t.iterations)==null?void 0:q.some(R=>R.type==="fallback_message");if(t.iterations&&t.iterations.length>0&&!E){let R=t.iterations.filter(x=>x.type==="compaction"||x.type==="message");if(R.length>0){let x=R.reduce((j,A)=>({input:j.input+A.input_tokens,output:j.output+A.output_tokens}),{input:0,output:0});z=x.input,H=x.output}else z=t.input_tokens,H=t.output_tokens}else z=t.input_tokens,H=t.output_tokens;return{inputTokens:{total:z+T+F,noCache:z,cacheRead:F,cacheWrite:T},outputTokens:{total:H,text:I==null?void 0:H-I,reasoning:I},raw:a??t}}v(Ze,"convertAnthropicMessagesUsage");var st=_(()=>m(e.object({type:e.literal("code_execution_result"),stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}))),Zt=_(()=>m(e.object({code:e.string()}))),Xt=G({id:"anthropic.code_execution_20250522",inputSchema:Zt,outputSchema:st}),Qt=v((t={})=>Xt(t),"codeExecution_20250522"),ct=_(()=>m(e.discriminatedUnion("type",[e.object({type:e.literal("code_execution_result"),stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("bash_code_execution_result"),content:e.array(e.object({type:e.literal("bash_code_execution_output"),file_id:e.string()})),stdout:e.string(),stderr:e.string(),return_code:e.number()}),e.object({type:e.literal("bash_code_execution_tool_result_error"),error_code:e.string()}),e.object({type:e.literal("text_editor_code_execution_tool_result_error"),error_code:e.string()}),e.object({type:e.literal("text_editor_code_execution_view_result"),content:e.string(),file_type:e.string(),num_lines:e.number().nullable(),start_line:e.number().nullable(),total_lines:e.number().nullable()}),e.object({type:e.literal("text_editor_code_execution_create_result"),is_file_update:e.boolean()}),e.object({type:e.literal("text_editor_code_execution_str_replace_result"),lines:e.array(e.string()).nullable(),new_lines:e.number().nullable(),new_start:e.number().nullable(),old_lines:e.number().nullable(),old_start:e.number().nullable()})]))),eo=_(()=>m(e.discriminatedUnion("type",[e.object({type:e.literal("programmatic-tool-call"),code:e.string()}),e.object({type:e.literal("bash_code_execution"),command:e.string()}),e.discriminatedUnion("command",[e.object({type:e.literal("text_editor_code_execution"),command:e.literal("view"),path:e.string()}),e.object({type:e.literal("text_editor_code_execution"),command:e.literal("create"),path:e.string(),file_text:e.string().nullish()}),e.object({type:e.literal("text_editor_code_execution"),command:e.literal("str_replace"),path:e.string(),old_str:e.string(),new_str:e.string()})])]))),to=G({id:"anthropic.code_execution_20250825",inputSchema:eo,outputSchema:ct,supportsDeferredResults:!0}),oo=v((t={})=>to(t),"codeExecution_20250825"),ut=_(()=>m(e.discriminatedUnion("type",[e.object({type:e.literal("code_execution_result"),stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("encrypted_code_execution_result"),encrypted_stdout:e.string(),stderr:e.string(),return_code:e.number(),content:e.array(e.object({type:e.literal("code_execution_output"),file_id:e.string()})).optional().default([])}),e.object({type:e.literal("bash_code_execution_result"),content:e.array(e.object({type:e.literal("bash_code_execution_output"),file_id:e.string()})),stdout:e.string(),stderr:e.string(),return_code:e.number()}),e.object({type:e.literal("bash_code_execution_tool_result_error"),error_code:e.string()}),e.object({type:e.literal("text_editor_code_execution_tool_result_error"),error_code:e.string()}),e.object({type:e.literal("text_editor_code_execution_view_result"),content:e.string(),file_type:e.string(),num_lines:e.number().nullable(),start_line:e.number().nullable(),total_lines:e.number().nullable()}),e.object({type:e.literal("text_editor_code_execution_create_result"),is_file_update:e.boolean()}),e.object({type:e.literal("text_editor_code_execution_str_replace_result"),lines:e.array(e.string()).nullable(),new_lines:e.number().nullable(),new_start:e.number().nullable(),old_lines:e.number().nullable(),old_start:e.number().nullable()})]))),ro=_(()=>m(e.discriminatedUnion("type",[e.object({type:e.literal("programmatic-tool-call"),code:e.string()}),e.object({type:e.literal("bash_code_execution"),command:e.string()}),e.discriminatedUnion("command",[e.object({type:e.literal("text_editor_code_execution"),command:e.literal("view"),path:e.string()}),e.object({type:e.literal("text_editor_code_execution"),command:e.literal("create"),path:e.string(),file_text:e.string().nullish()}),e.object({type:e.literal("text_editor_code_execution"),command:e.literal("str_replace"),path:e.string(),old_str:e.string(),new_str:e.string()})])]))),no=G({id:"anthropic.code_execution_20260120",inputSchema:ro,outputSchema:ut,supportsDeferredResults:!0}),ao=v((t={})=>no(t),"codeExecution_20260120"),pt=_(()=>m(e.array(e.object({type:e.literal("tool_reference"),toolName:e.string()})))),io=_(()=>m(e.object({pattern:e.string(),limit:e.number().optional()}))),lo=G({id:"anthropic.tool_search_regex_20251119",inputSchema:io,outputSchema:pt,supportsDeferredResults:!0}),so=v((t={})=>lo(t),"toolSearchRegex_20251119");function co(t){if(typeof t=="string")return new TextDecoder().decode(Ue(t));if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw t instanceof URL?new be({functionality:"URL-based text documents are not supported for citations"}):new be({functionality:`unsupported data type for text documents: ${typeof t}`})}v(co,"convertToString");function Te(t){return t instanceof URL||uo(t)}v(Te,"isUrlData");function uo(t){return typeof t=="string"&&/^https?:\/\//i.test(t)}v(uo,"isUrlString");function Ne(t){return t instanceof URL?t.toString():t}v(Ne,"getUrlString");async function Xe(t){if(typeof t=="string"){let a=await Fe({text:t});return a.success&&typeof a.value=="object"&&a.value!==null?a.value:{errorCode:"unavailable"}}return typeof t=="object"&&t!==null?t:{}}v(Xe,"extractErrorValue");async function po({prompt:t,sendReasoning:a,warnings:n,cacheControlValidator:c,toolNameMapping:y}){var P,q,T,F,I,z,H,E,R,x,j,A,J,Q,U,le,N,ne,ue,se,r;let d=new Set,B=_o(t),L=c||new Ie,ee,ce=[];async function i(D){var Y,de;let oe=await _e({provider:"anthropic",providerOptions:D,schema:Ve});return(de=(Y=oe?.citations)==null?void 0:Y.enabled)!=null?de:!1}v(i,"shouldEnableCitations");async function te(D){let Y=await _e({provider:"anthropic",providerOptions:D,schema:Ve});return{title:Y?.title,context:Y?.context}}v(te,"getDocumentMetadata");for(let D=0;D<B.length;D++){let Y=B[D],de=D===B.length-1,oe=Y.type;switch(oe){case"system":{let g=[],p=0;for(let{content:Z,providerOptions:X}of Y.messages){let W=await _e({provider:"anthropic",providerOptions:X,schema:kt}),S=(P=W?.toolChanges)!=null?P:[];(Z!==""||S.length===0)&&g.push({type:"text",text:Z,cache_control:L.getCacheControl(X,{type:"system message",canCache:!0})});for(let $ of S)p++,g.push({type:$.type,tool:{type:"tool_reference",name:y.toProviderToolName($.toolName)}})}D===0||ee==null&&p===0?(p>0&&n.push({type:"other",message:"tool changes on the initial system message are not supported by Anthropic. Configure the initial tool set via the tools option instead. The tool changes have been ignored."}),ee=g.filter(Z=>Z.type==="text")):(ce.push({role:"system",content:g}),d.add("mid-conversation-system-2026-04-07"),p>0&&d.add("mid-conversation-tool-changes-2026-07-01"));break}case"user":{let g=[];for(let p of Y.messages){let{role:Z,content:X}=p;switch(Z){case"user":{for(let W=0;W<X.length;W++){let S=X[W],$=W===X.length-1,l=(q=L.getCacheControl(S.providerOptions,{type:"user message part",canCache:!0}))!=null?q:$?L.getCacheControl(p.providerOptions,{type:"user message",canCache:!0}):void 0;switch(S.type){case"text":{g.push({type:"text",text:S.text,cache_control:l});break}case"file":{if(S.mediaType.startsWith("image/"))g.push({type:"image",source:Te(S.data)?{type:"url",url:Ne(S.data)}:{type:"base64",media_type:S.mediaType==="image/*"?"image/jpeg":S.mediaType,data:we(S.data)},cache_control:l});else if(S.mediaType==="application/pdf"){d.add("pdfs-2024-09-25");let ae=await i(S.providerOptions),O=await te(S.providerOptions);g.push({type:"document",source:Te(S.data)?{type:"url",url:Ne(S.data)}:{type:"base64",media_type:"application/pdf",data:we(S.data)},title:(T=O.title)!=null?T:S.filename,...O.context&&{context:O.context},...ae&&{citations:{enabled:!0}},cache_control:l})}else if(S.mediaType==="text/plain"){let ae=await i(S.providerOptions),O=await te(S.providerOptions);g.push({type:"document",source:Te(S.data)?{type:"url",url:Ne(S.data)}:{type:"text",media_type:"text/plain",data:co(S.data)},title:(F=O.title)!=null?F:S.filename,...O.context&&{context:O.context},...ae&&{citations:{enabled:!0}},cache_control:l})}else throw new be({functionality:`media type: ${S.mediaType}`});break}}}break}case"tool":{for(let W=0;W<X.length;W++){let S=X[W];if(S.type==="tool-approval-response")continue;let $=S.output,l="providerOptions"in $?$.providerOptions:$.type==="content"?(I=$.value.find(w=>w.providerOptions!=null))==null?void 0:I.providerOptions:void 0,ae=W===X.length-1,O=(H=(z=L.getCacheControl(S.providerOptions,{type:"tool result part",canCache:!0}))!=null?z:L.getCacheControl(l,{type:"tool result output",canCache:!0}))!=null?H:ae?L.getCacheControl(p.providerOptions,{type:"tool result message",canCache:!0}):void 0,f;switch($.type){case"content":f=$.value.map(w=>{var b;switch(w.type){case"text":return{type:"text",text:w.text};case"image-data":return{type:"image",source:{type:"base64",media_type:w.mediaType,data:w.data}};case"image-url":return{type:"image",source:{type:"url",url:w.url}};case"file-url":return{type:"document",source:{type:"url",url:w.url}};case"file-data":{if(w.mediaType==="application/pdf")return d.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:w.mediaType,data:w.data}};n.push({type:"other",message:`unsupported tool content part type: ${w.type} with media type: ${w.mediaType}`});return}case"custom":{let u=(b=w.providerOptions)==null?void 0:b.anthropic;if(u?.type==="tool-reference")return{type:"tool_reference",tool_name:u.toolName};n.push({type:"other",message:"unsupported custom tool content part"});return}default:{n.push({type:"other",message:`unsupported tool content part type: ${w.type}`});return}}}).filter($e);break;case"text":case"error-text":f=$.value;break;case"execution-denied":f=(E=$.reason)!=null?E:"Tool call execution denied.";break;default:f=JSON.stringify($.value);break}g.push({type:"tool_result",tool_use_id:S.toolCallId,content:f,is_error:$.type==="error-text"||$.type==="error-json"?!0:void 0,cache_control:O})}break}default:{let W=Z;throw new Error(`Unsupported role: ${W}`)}}}ce.push({role:"user",content:g});break}case"assistant":{let g=[],p=new Set;for(let Z=0;Z<Y.messages.length;Z++){let X=Y.messages[Z],W=Z===Y.messages.length-1,{content:S}=X;for(let $=0;$<S.length;$++){let l=S[$],ae=$===S.length-1,O=(R=L.getCacheControl(l.providerOptions,{type:"assistant message part",canCache:!0}))!=null?R:ae?L.getCacheControl(X.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(l.type){case"text":{let f=(x=l.providerOptions)==null?void 0:x.anthropic;f?.type==="compaction"?g.push({type:"compaction",content:l.text,cache_control:O}):g.push({type:"text",text:de&&W&&ae?l.text.trim():l.text,...f?.citations!=null&&{citations:f.citations},cache_control:O});break}case"reasoning":{if(a){let f=await _e({provider:"anthropic",providerOptions:l.providerOptions,schema:xt});f!=null?f.signature!=null?(L.getCacheControl(l.providerOptions,{type:"thinking block",canCache:!1}),g.push({type:"thinking",thinking:l.text,signature:f.signature})):f.redactedData!=null?(L.getCacheControl(l.providerOptions,{type:"redacted thinking block",canCache:!1}),g.push({type:"redacted_thinking",data:f.redactedData})):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{let f=Qe(l.providerOptions);if(l.providerExecuted){let w=y.toProviderToolName(l.toolName);if(((A=(j=l.providerOptions)==null?void 0:j.anthropic)==null?void 0:A.type)==="mcp-tool-use"){p.add(l.toolCallId);let u=(Q=(J=l.providerOptions)==null?void 0:J.anthropic)==null?void 0:Q.serverName;if(u==null||typeof u!="string"){n.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}g.push({type:"mcp_tool_use",id:l.toolCallId,name:l.toolName,input:l.input,server_name:u,cache_control:O})}else if(w==="code_execution"&&l.input!=null&&typeof l.input=="object"&&"type"in l.input&&typeof l.input.type=="string"&&(l.input.type==="bash_code_execution"||l.input.type==="text_editor_code_execution")){let{type:u,...K}=l.input;g.push({type:"server_tool_use",id:l.toolCallId,name:u,input:K,...f&&{caller:f},cache_control:O})}else if(w==="code_execution"&&l.input!=null&&typeof l.input=="object"&&"type"in l.input&&l.input.type==="programmatic-tool-call"){let{type:u,...K}=l.input;g.push({type:"server_tool_use",id:l.toolCallId,name:"code_execution",input:K,...f&&{caller:f},cache_control:O})}else w==="code_execution"||w==="web_fetch"||w==="web_search"?g.push({type:"server_tool_use",id:l.toolCallId,name:w,input:l.input,...f&&{caller:f},cache_control:O}):w==="tool_search_tool_regex"||w==="tool_search_tool_bm25"?g.push({type:"server_tool_use",id:l.toolCallId,name:w,input:l.input,...f&&{caller:f},cache_control:O}):w==="advisor"?g.push({type:"server_tool_use",id:l.toolCallId,name:"advisor",input:{},...f&&{caller:f},cache_control:O}):n.push({type:"other",message:`provider executed tool call for tool ${l.toolName} is not supported`});break}g.push({type:"tool_use",id:l.toolCallId,name:l.toolName,input:l.input,...f&&{caller:f},cache_control:O});break}case"tool-result":{let f=y.toProviderToolName(l.toolName),w=Qe(l.providerOptions);if(p.has(l.toolCallId)){let b=l.output;if(b.type!=="json"&&b.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${b.type} for tool ${l.toolName} is not supported`});break}g.push({type:"mcp_tool_result",tool_use_id:l.toolCallId,is_error:b.type==="error-json",content:b.value,cache_control:O})}else if(f==="code_execution"){let b=l.output;if(b.type==="error-text"||b.type==="error-json"){let u={};try{typeof b.value=="string"?u=xe(b.value):typeof b.value=="object"&&b.value!==null&&(u=b.value)}catch{}u.type==="code_execution_tool_result_error"?g.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(U=u.errorCode)!=null?U:"unknown"},cache_control:O}):g.push({type:"bash_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:O,content:{type:"bash_code_execution_tool_result_error",error_code:(le=u.errorCode)!=null?le:"unknown"}});break}if(b.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${b.type} for tool ${l.toolName} is not supported`});break}if(b.value==null||typeof b.value!="object"||!("type"in b.value)||typeof b.value.type!="string"){n.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${l.toolName}`});break}if(b.value.type==="code_execution_result"){let u=await re({value:b.value,schema:st});g.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:u.type,stdout:u.stdout,stderr:u.stderr,return_code:u.return_code,content:(N=u.content)!=null?N:[]},cache_control:O})}else if(b.value.type==="encrypted_code_execution_result"){let u=await re({value:b.value,schema:ut});u.type==="encrypted_code_execution_result"&&g.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:u.type,encrypted_stdout:u.encrypted_stdout,stderr:u.stderr,return_code:u.return_code,content:(ne=u.content)!=null?ne:[]},cache_control:O})}else{let u=await re({value:b.value,schema:ct});u.type==="code_execution_result"?g.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:u.type,stdout:u.stdout,stderr:u.stderr,return_code:u.return_code,content:(ue=u.content)!=null?ue:[]},cache_control:O}):u.type==="bash_code_execution_result"||u.type==="bash_code_execution_tool_result_error"?g.push({type:"bash_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:O,content:u.type==="bash_code_execution_result"?{type:u.type,stdout:u.stdout,stderr:u.stderr,return_code:u.return_code,content:u.content}:u}):g.push({type:"text_editor_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:O,content:u})}break}if(f==="web_fetch"){let b=l.output;if(b.type==="error-json"){g.push({type:"web_fetch_tool_result",tool_use_id:l.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(se=(await Xe(b.value)).errorCode)!=null?se:"unavailable"},...w&&{caller:w},cache_control:O});break}if(b.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${b.type} for tool ${l.toolName} is not supported`});break}let u=await re({value:b.value,schema:lt});g.push({type:"web_fetch_tool_result",tool_use_id:l.toolCallId,content:{type:"web_fetch_result",url:u.url,retrieved_at:u.retrievedAt,content:{type:"document",title:u.content.title,citations:u.content.citations,source:{type:u.content.source.type,media_type:u.content.source.mediaType,data:u.content.source.data}}},...w&&{caller:w},cache_control:O});break}if(f==="web_search"){let b=l.output;if(b.type==="error-json"){g.push({type:"web_search_tool_result",tool_use_id:l.toolCallId,content:{type:"web_search_tool_result_error",error_code:(r=(await Xe(b.value)).errorCode)!=null?r:"unavailable"},...w&&{caller:w},cache_control:O});break}if(b.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${b.type} for tool ${l.toolName} is not supported`});break}let u=await re({value:b.value,schema:it});g.push({type:"web_search_tool_result",tool_use_id:l.toolCallId,content:u.map(K=>({url:K.url,title:K.title,page_age:K.pageAge,encrypted_content:K.encryptedContent,type:K.type})),...w&&{caller:w},cache_control:O});break}if(f==="tool_search_tool_regex"||f==="tool_search_tool_bm25"){let b=l.output;if(b.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${b.type} for tool ${l.toolName} is not supported`});break}let K=(await re({value:b.value,schema:pt})).map(he=>({type:"tool_reference",tool_name:he.toolName}));g.push({type:"tool_search_tool_result",tool_use_id:l.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:K},cache_control:O});break}if(f==="advisor"){let b=l.output;if(b.type!=="json"&&b.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${b.type} for tool ${l.toolName} is not supported`});break}let u=await re({value:b.value,schema:at});u.type==="advisor_result"?g.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_result",text:u.text},cache_control:O}):u.type==="advisor_redacted_result"?g.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:u.encryptedContent},cache_control:O}):g.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_tool_result_error",error_code:u.errorCode},cache_control:O});break}n.push({type:"other",message:`provider executed tool result for tool ${l.toolName} is not supported`});break}}}}ce.push({role:"assistant",content:mo(g)});break}default:{let g=oe;throw new Error(`content type: ${g}`)}}}return{prompt:{system:ee,messages:ce},betas:d}}v(po,"convertToAnthropicMessagesPrompt");function _o(t){let a=[],n;for(let c of t){let{role:y}=c;switch(y){case"system":{n?.type!=="system"&&(n={type:"system",messages:[]},a.push(n)),n.messages.push(c);break}case"assistant":{n?.type!=="assistant"&&(n={type:"assistant",messages:[]},a.push(n)),n.messages.push(c);break}case"user":{n?.type!=="user"&&(n={type:"user",messages:[]},a.push(n)),n.messages.push(c);break}case"tool":{n?.type!=="user"&&(n={type:"user",messages:[]},a.push(n)),n.messages.push(c);break}default:{let P=y;throw new Error(`Unsupported role: ${P}`)}}}return a}v(_o,"groupIntoBlocks");function mo(t){let a=[],n=[];function c(){a.push(...n.filter(y=>y.type!=="tool_use"),...n.filter(y=>y.type==="tool_use")),n=[]}v(c,"flushSegment");for(let y of t)y.type==="thinking"||y.type==="redacted_thinking"?(c(),a.push(y)):n.push(y);return c(),a}v(mo,"moveToolUseBlocksToEnd");function Qe(t){var a;let n=(a=t?.anthropic)==null?void 0:a.caller;return(n?.type==="code_execution_20250825"||n?.type==="code_execution_20260120")&&n.toolId?{type:n.type,tool_id:n.toolId}:n?.type==="direct"?{type:"direct"}:void 0}v(Qe,"getAnthropicCaller");function Oe({finishReason:t,isJsonResponseFromTool:a}){switch(t){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return a?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}v(Oe,"mapAnthropicStopReason");var dt=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),ho=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function yo(t){return _t(t)}v(yo,"sanitizeJsonSchema");function me(t){return typeof t=="boolean"||!vo(t)?t:_t(t)}v(me,"sanitizeDefinition");function _t(t){let a={},n=t;if(t.$ref!=null)return{$ref:t.$ref};if(t.$schema!=null&&(a.$schema=t.$schema),t.$id!=null&&(a.$id=t.$id),t.title!=null&&(a.title=t.title),t.description!=null&&(a.description=t.description),t.default!==void 0&&(a.default=t.default),t.const!==void 0&&(a.const=t.const),t.enum!=null&&(a.enum=t.enum),t.type!=null&&(a.type=t.type),t.anyOf!=null?a.anyOf=t.anyOf.map(me):t.oneOf!=null&&(a.anyOf=t.oneOf.map(me)),t.allOf!=null&&(a.allOf=t.allOf.map(me)),t.definitions!=null&&(a.definitions=Object.fromEntries(Object.entries(t.definitions).map(([y,P])=>[y,me(P)]))),n.$defs!=null){let y=a;y.$defs=Object.fromEntries(Object.entries(n.$defs).map(([P,q])=>[P,me(q)]))}(t.type==="object"||t.properties!=null)&&(t.properties!=null&&(a.properties=Object.fromEntries(Object.entries(t.properties).map(([y,P])=>[y,me(P)]))),a.additionalProperties=!1,t.required!=null&&(a.required=t.required)),t.items!=null&&(a.items=Array.isArray(t.items)?t.items.map(me):me(t.items)),typeof t.format=="string"&&dt.has(t.format)&&(a.format=t.format);let c=go(t);return c!=null&&(a.description=a.description==null?c:`${a.description}
|
|
19
|
+
${c}`),a}v(_t,"sanitizeSchema");function go(t){let a=ho.flatMap(n=>{let c=t[n];return c==null||c===!1?[]:`${bo(n)}: ${fo(c)}`});return typeof t.format=="string"&&!dt.has(t.format)&&a.push(`format: ${t.format}`),a.length===0?void 0:`${a.join("; ")}.`}v(go,"getConstraintDescription");function bo(t){return t.replace(/[A-Z]/g,a=>` ${a.toLowerCase()}`)}v(bo,"formatConstraintName");function fo(t){return typeof t=="string"?t:JSON.stringify(t)}v(fo,"formatConstraintValue");function vo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}v(vo,"isPlainObject");function et(t,a,n){var c;if(t.type==="web_search_result_location")return{type:"source",sourceType:"url",id:n(),url:t.url,title:t.title,providerMetadata:{anthropic:{citedText:t.cited_text,encryptedIndex:t.encrypted_index}}};if(t.type!=="page_location"&&t.type!=="char_location")return;let y=a[t.document_index];if(y)return{type:"source",sourceType:"document",id:n(),mediaType:y.mediaType,title:(c=t.document_title)!=null?c:y.title,filename:y.filename,providerMetadata:{anthropic:t.type==="page_location"?{citedText:t.cited_text,startPageNumber:t.start_page_number,endPageNumber:t.end_page_number}:{citedText:t.cited_text,startCharIndex:t.start_char_index,endCharIndex:t.end_char_index}}}}v(et,"createCitationSource");function ke(t){return t==null?void 0:{type:t.type,toolId:"tool_id"in t?t.tool_id:void 0}}v(ke,"getAnthropicCallerInfo");function ie(t){let a=ke(t);return a==null?{}:{providerMetadata:{anthropic:{caller:a}}}}v(ie,"getAnthropicCallerMetadata");var xo=class{static{v(this,"AnthropicMessagesLanguageModel")}constructor(t,a){this.specificationVersion="v3";var n;this.modelId=t,this.config=a,this.generateId=(n=a.generateId)!=null?n:ve}supportsUrl(t){return t.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let t=this.config.provider,a=t.indexOf(".");return a===-1?t:t.substring(0,a)}get supportedUrls(){var t,a,n;return(n=(a=(t=this.config).supportedUrls)==null?void 0:a.call(t))!=null?n:{}}async getArgs({userSuppliedBetas:t,prompt:a,maxOutputTokens:n,temperature:c,topP:y,topK:P,frequencyPenalty:q,presencePenalty:T,stopSequences:F,responseFormat:I,seed:z,tools:H,toolChoice:E,providerOptions:R,stream:x}){var j,A,J,Q,U,le,N,ne,ue,se,r;let d=[];q!=null&&d.push({type:"unsupported",feature:"frequencyPenalty"}),T!=null&&d.push({type:"unsupported",feature:"presencePenalty"}),z!=null&&d.push({type:"unsupported",feature:"seed"}),c!=null&&c>1?(d.push({type:"unsupported",feature:"temperature",details:`${c} exceeds anthropic maximum of 1.0. clamped to 1.0`}),c=1):c!=null&&c<0&&(d.push({type:"unsupported",feature:"temperature",details:`${c} is below anthropic minimum of 0. clamped to 0`}),c=0),I?.type==="json"&&I.schema==null&&d.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let B=this.providerOptionsName,L=await _e({provider:"anthropic",providerOptions:R,schema:Ge}),ee=B!=="anthropic"?await _e({provider:B,providerOptions:R,schema:Ge}):null,ce=ee!=null,i=Object.assign({},L??{},ee??{}),{maxOutputTokens:te,supportsStructuredOutput:D,rejectsSamplingParameters:Y,rejectsThinkingDisabledAboveHighEffort:de,isKnownModel:oe}=ko(this.modelId);!oe&&n==null&&d.push({type:"compatibility",feature:"maxOutputTokens",details:`The model "${this.modelId}" is unknown. The max output tokens have been limited to ${te}. Set maxOutputTokens explicitly to override this limit.`}),Y&&(c!=null&&(d.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),c=void 0),P!=null&&(d.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),P=void 0),y!=null&&(d.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),y=void 0));let g=oe||this.modelId.includes("claude-"),p=((j=this.config.supportsNativeStructuredOutput)!=null?j:!0)&&D,Z=((A=this.config.supportsStrictTools)!=null?A:!0)&&D,X=(J=i?.structuredOutputMode)!=null?J:"auto",W=X==="outputFormat"||X==="auto"&&p,S=I?.type==="json"&&I.schema!=null&&!W?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:I.schema}:void 0;S!=null&&i?.disableParallelToolUse===!1&&d.push({type:"unsupported",feature:"providerOptions.anthropic.disableParallelToolUse",details:"`disableParallelToolUse: false` is ignored when using the JSON response tool. Parallel tool use is disabled to ensure a single coherent JSON tool call."});let $=i?.contextManagement,l=new Ie,ae=Ae({tools:H,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),{prompt:O,betas:f}=await po({prompt:a,sendReasoning:(Q=i?.sendReasoning)!=null?Q:!0,warnings:d,cacheControlValidator:l,toolNameMapping:ae});de&&((U=i?.thinking)==null?void 0:U.type)==="disabled"&&(i.effort==="xhigh"||i.effort==="max")&&(d.push({type:"unsupported",feature:"providerOptions.anthropic.effort",details:`effort '${i.effort}' is not supported by ${this.modelId} when thinking is disabled. The effort has been lowered to 'high'.`}),i.effort="high");let w=(le=i?.thinking)==null?void 0:le.type,b=w==="enabled"||w==="adaptive",u=b||w==="disabled",K=w==="enabled"?(N=i?.thinking)==null?void 0:N.budgetTokens:void 0,he=w==="adaptive"?(ne=i?.thinking)==null?void 0:ne.display:void 0,s=b?i?.thinking==null?void 0:i.thinking.blockBinding:void 0,o=n??te,k={model:this.modelId,max_tokens:o,temperature:c,top_k:P,top_p:y,stop_sequences:F,...u&&{thinking:{type:w,...K!=null&&{budget_tokens:K},...he!=null&&{display:he},...s!=null&&{block_binding:{prefix_mismatch_behavior:s.prefixMismatchBehavior}}}},...(i?.effort||i?.taskBudget||W&&I?.type==="json"&&I.schema!=null)&&{output_config:{...i?.effort&&{effort:i.effort},...i?.taskBudget&&{task_budget:{type:i.taskBudget.type,total:i.taskBudget.total,...i.taskBudget.remaining!=null&&{remaining:i.taskBudget.remaining}}},...W&&I?.type==="json"&&I.schema!=null&&{format:{type:"json_schema",schema:yo(I.schema)}}}},...i?.speed&&{speed:i.speed},...i?.inferenceGeo&&{inference_geo:i.inferenceGeo},...i?.fallbacks!=null&&(i.fallbacks==="default"||i.fallbacks.length>0)&&{fallbacks:i.fallbacks},...i?.cacheControl&&{cache_control:i.cacheControl},...((ue=i?.metadata)==null?void 0:ue.userId)!=null&&{metadata:{user_id:i.metadata.userId}},...i?.mcpServers&&i.mcpServers.length>0&&{mcp_servers:i.mcpServers.map(C=>({type:C.type,name:C.name,url:C.url,authorization_token:C.authorizationToken,tool_configuration:C.toolConfiguration?{allowed_tools:C.toolConfiguration.allowedTools,enabled:C.toolConfiguration.enabled}:void 0}))},...i?.container&&{container:i.container.skills&&i.container.skills.length>0?{id:i.container.id,skills:i.container.skills.map(C=>({type:C.type,skill_id:C.skillId,version:C.version}))}:i.container.id},system:O.system,messages:O.messages,...$&&{context_management:{edits:$.edits.map(C=>{let ze=C.type;switch(ze){case"clear_tool_uses_20250919":return{type:C.type,...C.trigger!==void 0&&{trigger:C.trigger},...C.keep!==void 0&&{keep:C.keep},...C.clearAtLeast!==void 0&&{clear_at_least:C.clearAtLeast},...C.clearToolInputs!==void 0&&{clear_tool_inputs:C.clearToolInputs},...C.excludeTools!==void 0&&{exclude_tools:C.excludeTools}};case"clear_thinking_20251015":return{type:C.type,...C.keep!==void 0&&{keep:C.keep}};case"compact_20260112":return{type:C.type,...C.trigger!==void 0&&{trigger:C.trigger},...C.pauseAfterCompaction!==void 0&&{pause_after_compaction:C.pauseAfterCompaction},...C.instructions!==void 0&&{instructions:C.instructions}};default:d.push({type:"other",message:`Unknown context management strategy: ${ze}`});return}}).filter(C=>C!==void 0)}}};b?(w==="enabled"&&K==null&&(d.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),k.thinking={type:"enabled",budget_tokens:1024},K=1024),k.temperature!=null&&(k.temperature=void 0,d.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),P!=null&&(k.top_k=void 0,d.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),y!=null&&(k.top_p=void 0,d.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),k.max_tokens=o+(K??0)):g&&y!=null&&c!=null&&(d.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),k.top_p=void 0),oe&&k.max_tokens>te&&(n!=null&&d.push({type:"unsupported",feature:"maxOutputTokens",details:`${k.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${te} max output tokens. The max output tokens have been limited to ${te}.`}),k.max_tokens=te),i?.mcpServers&&i.mcpServers.length>0&&f.add("mcp-client-2025-04-04"),$&&(f.add("context-management-2025-06-27"),$.edits.some(C=>C.type==="compact_20260112")&&f.add("compact-2026-01-12")),i?.container&&i.container.skills&&i.container.skills.length>0&&(f.add("code-execution-2025-08-25"),f.add("skills-2025-10-02"),f.add("files-api-2025-04-14"),H?.some(C=>C.type==="provider"&&(C.id==="anthropic.code_execution_20250825"||C.id==="anthropic.code_execution_20260120"))||d.push({type:"other",message:"code execution tool is required when using skills"})),i?.taskBudget&&f.add("task-budgets-2026-03-13"),i?.speed==="fast"&&f.add("fast-mode-2026-02-01"),i?.fallbacks==="default"?f.add("server-side-fallback-2026-07-01"):i?.fallbacks&&i.fallbacks.length>0&&f.add("server-side-fallback-2026-06-01"),s!=null&&f.add("thinking-binding-controls-2026-08-01");let h=x&&((se=i?.toolStreaming)!=null?se:!0),{tools:M,toolChoice:ge,toolWarnings:ye,betas:fe}=await Yt(S!=null?{tools:[...H??[],S],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:l,supportsStructuredOutput:!1,supportsStrictTools:Z,defaultEagerInputStreaming:h}:{tools:H??[],toolChoice:E,disableParallelToolUse:i?.disableParallelToolUse,cacheControlValidator:l,supportsStructuredOutput:p,supportsStrictTools:Z,defaultEagerInputStreaming:h}),yt=l.getWarnings();return{args:{...k,tools:M,tool_choice:ge,stream:x===!0?!0:void 0},warnings:[...d,...ye,...yt],betas:new Set([...f,...fe,...t,...(r=i?.anthropicBeta)!=null?r:[]]),usesJsonResponseTool:S!=null,toolNameMapping:ae,providerOptionsName:B,usedCustomProviderKey:ce}}async getHeaders({betas:t,headers:a}){return Re(await Ce(this.config.headers),a,t.size>0?{"anthropic-beta":Array.from(t).join(",")}:{})}async getBetasFromHeaders(t){var a,n;let y=(a=(await Ce(this.config.headers))["anthropic-beta"])!=null?a:"",P=(n=t?.["anthropic-beta"])!=null?n:"";return new Set([...y.toLowerCase().split(","),...P.toLowerCase().split(",")].map(q=>q.trim()).filter(q=>q!==""))}buildRequestUrl(t){var a,n,c;return(c=(n=(a=this.config).buildRequestUrl)==null?void 0:n.call(a,this.config.baseURL,t))!=null?c:`${this.config.baseURL}/messages`}transformRequestBody(t,a){var n,c,y;return(y=(c=(n=this.config).transformRequestBody)==null?void 0:c.call(n,t,a))!=null?y:t}extractCitationDocuments(t){let a=v(n=>{var c,y;if(n.type!=="file"||n.mediaType!=="application/pdf"&&n.mediaType!=="text/plain")return!1;let P=(c=n.providerOptions)==null?void 0:c.anthropic,q=P?.citations;return(y=q?.enabled)!=null?y:!1},"isCitationPart");return t.filter(n=>n.role==="user").flatMap(n=>n.content).filter(a).map(n=>{var c;let y=n;return{title:(c=y.filename)!=null?c:"Untitled Document",filename:y.filename,mediaType:y.mediaType}})}async doGenerate(t){var a,n,c,y,P,q,T,F;let{args:I,warnings:z,betas:H,usesJsonResponseTool:E,toolNameMapping:R,providerOptionsName:x,usedCustomProviderKey:j}=await this.getArgs({...t,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),A=[...this.extractCitationDocuments(t.prompt)],J=tt(I.tools),{responseHeaders:Q,value:U,rawValue:le}=await Se({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:H,headers:t.headers}),body:this.transformRequestBody(I,H),failedResponseHandler:Ke,successfulResponseHandler:Le(ft),abortSignal:t.abortSignal,fetch:this.config.fetch}),N=[],ne={},ue={},se=!1;for(let r of U.content)switch(r.type){case"text":{if(!E){let d=(a=r.citations)==null?void 0:a.filter(B=>B.type==="web_search_result_location");if(N.push({type:"text",text:r.text,...d!=null&&d.length>0&&{providerMetadata:{anthropic:{citations:d}}}}),r.citations)for(let B of r.citations){let L=et(B,A,this.generateId);L&&N.push(L)}}break}case"thinking":{N.push({type:"reasoning",text:r.thinking,providerMetadata:{anthropic:{signature:r.signature}}});break}case"redacted_thinking":{N.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:r.data}}});break}case"compaction":{N.push({type:"text",text:r.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{E&&r.name==="json"?(se=!0,N.push({type:"text",text:JSON.stringify(r.input)})):N.push({type:"tool-call",toolCallId:r.id,toolName:r.name,input:JSON.stringify(r.input),...ie(r.caller)});break}case"server_tool_use":{if(r.name==="text_editor_code_execution"||r.name==="bash_code_execution")N.push({type:"tool-call",toolCallId:r.id,toolName:R.toCustomToolName("code_execution"),input:JSON.stringify({type:r.name,...r.input}),providerExecuted:!0,...J&&"code_execution"==="code_execution"?{dynamic:!0}:{},...ie(r.caller)});else if(r.name==="web_search"||r.name==="code_execution"||r.name==="web_fetch"){let d=r.name==="code_execution"&&r.input!=null&&typeof r.input=="object"&&"code"in r.input&&!("type"in r.input)?{type:"programmatic-tool-call",...r.input}:r.input;N.push({type:"tool-call",toolCallId:r.id,toolName:R.toCustomToolName(r.name),input:JSON.stringify(d),providerExecuted:!0,...J&&r.name==="code_execution"?{dynamic:!0}:{},...ie(r.caller)})}else r.name==="tool_search_tool_regex"||r.name==="tool_search_tool_bm25"?(ue[r.id]=r.name,N.push({type:"tool-call",toolCallId:r.id,toolName:R.toCustomToolName(r.name),input:JSON.stringify(r.input),providerExecuted:!0,...ie(r.caller)})):r.name==="advisor"&&N.push({type:"tool-call",toolCallId:r.id,toolName:R.toCustomToolName("advisor"),input:JSON.stringify(r.input),providerExecuted:!0,...ie(r.caller)});break}case"mcp_tool_use":{ne[r.id]={type:"tool-call",toolCallId:r.id,toolName:r.name,input:JSON.stringify(r.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:r.server_name}}},N.push(ne[r.id]);break}case"mcp_tool_result":{N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:ne[r.tool_use_id].toolName,isError:r.is_error,result:r.content,dynamic:!0,providerMetadata:ne[r.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{r.content.type==="web_fetch_result"?(A.push({title:(n=r.content.content.title)!=null?n:r.content.url,mediaType:r.content.content.source.media_type}),N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:r.content.url,retrievedAt:r.content.retrieved_at,content:{type:r.content.content.type,title:r.content.content.title,citations:r.content.content.citations,source:{type:r.content.content.source.type,mediaType:r.content.content.source.media_type,data:r.content.content.source.data}}},...ie(r.caller)})):r.content.type==="web_fetch_tool_result_error"&&N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:r.content.error_code},...ie(r.caller)});break}case"web_search_tool_result":{if(Array.isArray(r.content)){N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("web_search"),result:r.content.map(d=>{var B;return{url:d.url,title:d.title,pageAge:(B=d.page_age)!=null?B:null,encryptedContent:d.encrypted_content,type:d.type}}),...ie(r.caller)});for(let d of r.content)N.push({type:"source",sourceType:"url",id:this.generateId(),url:d.url,title:d.title,providerMetadata:{anthropic:{pageAge:(c=d.page_age)!=null?c:null}}})}else N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:r.content.error_code},...ie(r.caller)});break}case"code_execution_tool_result":{r.content.type==="code_execution_result"?N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("code_execution"),result:{type:r.content.type,stdout:r.content.stdout,stderr:r.content.stderr,return_code:r.content.return_code,content:(y=r.content.content)!=null?y:[]}}):r.content.type==="encrypted_code_execution_result"?N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("code_execution"),result:{type:r.content.type,encrypted_stdout:r.content.encrypted_stdout,stderr:r.content.stderr,return_code:r.content.return_code,content:(P=r.content.content)!=null?P:[]}}):r.content.type==="code_execution_tool_result_error"&&N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:r.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName("code_execution"),result:r.content});break}case"tool_search_tool_result":{let d=ue[r.tool_use_id];if(d==null){let B=R.toCustomToolName("tool_search_tool_bm25"),L=R.toCustomToolName("tool_search_tool_regex");B!=="tool_search_tool_bm25"?d="tool_search_tool_bm25":d="tool_search_tool_regex"}r.content.type==="tool_search_tool_search_result"?N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName(d),result:r.content.tool_references.map(B=>({type:B.type,toolName:B.tool_name}))}):N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:R.toCustomToolName(d),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:r.content.error_code}});break}case"advisor_tool_result":{let d=R.toCustomToolName("advisor");r.content.type==="advisor_result"?N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:d,result:{type:"advisor_result",text:r.content.text}}):r.content.type==="advisor_redacted_result"?N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:d,result:{type:"advisor_redacted_result",encryptedContent:r.content.encrypted_content}}):N.push({type:"tool-result",toolCallId:r.tool_use_id,toolName:d,isError:!0,result:{type:"advisor_tool_result_error",errorCode:r.content.error_code}});break}case"fallback":break}return{content:N,finishReason:{unified:Oe({finishReason:U.stop_reason,isJsonResponseFromTool:se}),raw:(q=U.stop_reason)!=null?q:void 0},usage:Ze({usage:U.usage}),request:{body:I},response:{id:(T=U.id)!=null?T:void 0,modelId:(F=U.model)!=null?F:void 0,headers:Q,body:le},warnings:z,providerMetadata:(()=>{var r,d,B,L,ee;let ce=rt(U.stop_details),i={usage:U.usage,cacheCreationInputTokens:(r=U.usage.cache_creation_input_tokens)!=null?r:null,stopSequence:(d=U.stop_sequence)!=null?d:null,...ce!=null?{stopDetails:ce}:{},...U.input_transformations!=null?{inputTransformations:U.input_transformations}:{},iterations:U.usage.iterations?U.usage.iterations.map(D=>({type:D.type,...D.model!=null?{model:D.model}:{},inputTokens:D.input_tokens,outputTokens:D.output_tokens,...D.cache_creation_input_tokens?{cacheCreationInputTokens:D.cache_creation_input_tokens}:{},...D.cache_read_input_tokens?{cacheReadInputTokens:D.cache_read_input_tokens}:{}})):null,container:U.container?{expiresAt:U.container.expires_at,id:U.container.id,skills:(L=(B=U.container.skills)==null?void 0:B.map(D=>({type:D.type,skillId:D.skill_id,version:D.version})))!=null?L:null}:null,contextManagement:(ee=ot(U.context_management))!=null?ee:null},te={anthropic:i};return j&&x!=="anthropic"&&(te[x]=i),te})()}}async doStream(t){var a,n;let{args:c,warnings:y,betas:P,usesJsonResponseTool:q,toolNameMapping:T,providerOptionsName:F,usedCustomProviderKey:I}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),z=[...this.extractCitationDocuments(t.prompt)],H=tt(c.tools),E=this.buildRequestUrl(!0),{responseHeaders:R,value:x}=await Se({url:E,headers:await this.getHeaders({betas:P,headers:t.headers}),body:this.transformRequestBody(c,P),failedResponseHandler:Ke,successfulResponseHandler:Je(vt),abortSignal:t.abortSignal,fetch:this.config.fetch}),j={unified:"other",raw:void 0},A={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},J={},Q={},U={},le=null,N,ne=null,ue=null,se,r,d=null,B=!1,L=!1,ee,ce=!1,i,te=this.generateId,D=x.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:y})},transform(g,p){var Z,X,W,S,$,l,ae,O,f,w,b,u,K,he;if(ce)return;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){p.enqueue({type:"error",error:g.error});return}let s=g.value;switch(s.type){case"ping":return;case"content_block_start":{let o=s.content_block,k=o.type;if(k==="fallback")return;switch(i=k,k){case"text":{if(q)return;J[s.index]={type:"text",citations:[]},p.enqueue({type:"text-start",id:String(s.index)});return}case"thinking":{J[s.index]={type:"reasoning"},p.enqueue({type:"reasoning-start",id:String(s.index)});return}case"redacted_thinking":{J[s.index]={type:"reasoning"},p.enqueue({type:"reasoning-start",id:String(s.index),providerMetadata:{anthropic:{redactedData:o.data}}});return}case"compaction":{J[s.index]={type:"text",citations:[]},p.enqueue({type:"text-start",id:String(s.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(q&&o.name==="json")B=!0,J[s.index]={type:"text",citations:[]},p.enqueue({type:"text-start",id:String(s.index)});else{let M=ke(o.caller),ye=o.input&&Object.keys(o.input).length>0?JSON.stringify(o.input):"";J[s.index]={type:"tool-call",toolCallId:o.id,toolName:o.name,input:ye,firstDelta:ye.length===0,...M&&{caller:M}},p.enqueue({type:"tool-input-start",id:o.id,toolName:o.name})}return}case"server_tool_use":{let h=ke(o.caller);if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(o.name)){let M=o.name==="text_editor_code_execution"||o.name==="bash_code_execution"?"code_execution":o.name,ge=o.name==="text_editor_code_execution"||o.name==="bash_code_execution"?o.name:o.name==="code_execution"?"programmatic-tool-call":void 0,ye=T.toCustomToolName(M),fe=o.input!=null&&typeof o.input=="object"&&Object.keys(o.input).length>0?JSON.stringify(o.input):"";J[s.index]={type:"tool-call",toolCallId:o.id,toolName:ye,input:fe,providerExecuted:!0,...H&&M==="code_execution"?{dynamic:!0}:{},firstDelta:fe.length===0,providerToolName:M,providerToolInputType:ge,...h&&{caller:h}},p.enqueue({type:"tool-input-start",id:o.id,toolName:ye,providerExecuted:!0,...H&&M==="code_execution"?{dynamic:!0}:{}})}else if(o.name==="tool_search_tool_regex"||o.name==="tool_search_tool_bm25"){U[o.id]=o.name;let M=T.toCustomToolName(o.name);J[s.index]={type:"tool-call",toolCallId:o.id,toolName:M,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:o.name,...h&&{caller:h}},p.enqueue({type:"tool-input-start",id:o.id,toolName:M,providerExecuted:!0})}else if(o.name==="advisor"){let M=T.toCustomToolName("advisor");J[s.index]={type:"tool-call",toolCallId:o.id,toolName:M,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:o.name,...h&&{caller:h}},p.enqueue({type:"tool-input-start",id:o.id,toolName:M,providerExecuted:!0})}return}case"web_fetch_tool_result":{o.content.type==="web_fetch_result"?(z.push({title:(Z=o.content.content.title)!=null?Z:o.content.url,mediaType:o.content.content.source.media_type}),p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:o.content.url,retrievedAt:o.content.retrieved_at,content:{type:o.content.content.type,title:o.content.content.title,citations:o.content.content.citations,source:{type:o.content.content.source.type,mediaType:o.content.content.source.media_type,data:o.content.content.source.data}}},...ie(o.caller)})):o.content.type==="web_fetch_tool_result_error"&&p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:o.content.error_code},...ie(o.caller)});return}case"web_search_tool_result":{if(Array.isArray(o.content)){p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("web_search"),result:o.content.map(h=>{var M;return{url:h.url,title:h.title,pageAge:(M=h.page_age)!=null?M:null,encryptedContent:h.encrypted_content,type:h.type}}),...ie(o.caller)});for(let h of o.content)p.enqueue({type:"source",sourceType:"url",id:te(),url:h.url,title:h.title,providerMetadata:{anthropic:{pageAge:(X=h.page_age)!=null?X:null}}})}else p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:o.content.error_code},...ie(o.caller)});return}case"code_execution_tool_result":{o.content.type==="code_execution_result"?p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("code_execution"),result:{type:o.content.type,stdout:o.content.stdout,stderr:o.content.stderr,return_code:o.content.return_code,content:(W=o.content.content)!=null?W:[]}}):o.content.type==="encrypted_code_execution_result"?p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("code_execution"),result:{type:o.content.type,encrypted_stdout:o.content.encrypted_stdout,stderr:o.content.stderr,return_code:o.content.return_code,content:(S=o.content.content)!=null?S:[]}}):o.content.type==="code_execution_tool_result_error"&&p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:o.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName("code_execution"),result:o.content});return}case"tool_search_tool_result":{let h=U[o.tool_use_id];if(h==null){let M=T.toCustomToolName("tool_search_tool_bm25"),ge=T.toCustomToolName("tool_search_tool_regex");M!=="tool_search_tool_bm25"?h="tool_search_tool_bm25":h="tool_search_tool_regex"}o.content.type==="tool_search_tool_search_result"?p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName(h),result:o.content.tool_references.map(M=>({type:M.type,toolName:M.tool_name}))}):p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:T.toCustomToolName(h),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:o.content.error_code}});return}case"advisor_tool_result":{let h=T.toCustomToolName("advisor");o.content.type==="advisor_result"?p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:h,result:{type:"advisor_result",text:o.content.text}}):o.content.type==="advisor_redacted_result"?p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:h,result:{type:"advisor_redacted_result",encryptedContent:o.content.encrypted_content}}):p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:h,isError:!0,result:{type:"advisor_tool_result_error",errorCode:o.content.error_code}});return}case"mcp_tool_use":{Q[o.id]={type:"tool-call",toolCallId:o.id,toolName:o.name,input:JSON.stringify(o.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:o.server_name}}},p.enqueue(Q[o.id]);return}case"mcp_tool_result":{p.enqueue({type:"tool-result",toolCallId:o.tool_use_id,toolName:Q[o.tool_use_id].toolName,isError:o.is_error,result:o.content,dynamic:!0,providerMetadata:Q[o.tool_use_id].providerMetadata});return}default:{let h=k;throw new Error(`Unsupported content block type: ${h}`)}}}case"content_block_stop":{if(J[s.index]!=null){let o=J[s.index];switch(o.type){case"text":{p.enqueue({type:"text-end",id:String(s.index),...o.citations.length>0&&{providerMetadata:{anthropic:{citations:o.citations}}}});break}case"reasoning":{p.enqueue({type:"reasoning-end",id:String(s.index)});break}case"tool-call":if(!(q&&o.toolName==="json")){p.enqueue({type:"tool-input-end",id:o.toolCallId});let h=o.input===""?"{}":o.input;if(o.providerToolName==="code_execution")try{let M=xe(h);M!=null&&typeof M=="object"&&"code"in M&&!("type"in M)&&(h=JSON.stringify({type:"programmatic-tool-call",...M}))}catch{}p.enqueue({type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:h,providerExecuted:o.providerExecuted,...H&&o.providerToolName==="code_execution"?{dynamic:!0}:{},...o.caller&&{providerMetadata:{anthropic:{caller:o.caller}}}})}break}delete J[s.index]}i=void 0;return}case"content_block_delta":{let o=s.delta.type;switch(o){case"text_delta":{if(q)return;p.enqueue({type:"text-delta",id:String(s.index),delta:s.delta.text});return}case"thinking_delta":{p.enqueue({type:"reasoning-delta",id:String(s.index),delta:s.delta.thinking});return}case"signature_delta":{i==="thinking"&&p.enqueue({type:"reasoning-delta",id:String(s.index),delta:"",providerMetadata:{anthropic:{signature:s.delta.signature}}});return}case"compaction_delta":{s.delta.content!=null&&p.enqueue({type:"text-delta",id:String(s.index),delta:s.delta.content});return}case"input_json_delta":{let k=J[s.index],h=s.delta.partial_json;if(h.length===0)return;if(B){if(k?.type!=="text")return;p.enqueue({type:"text-delta",id:String(s.index),delta:h})}else{if(k?.type!=="tool-call")return;k.firstDelta&&k.providerToolInputType!=null&&(h=`{"type": "${k.providerToolInputType}",${h.substring(1)}`),p.enqueue({type:"tool-input-delta",id:k.toolCallId,delta:h}),k.input+=h,k.firstDelta=!1}return}case"citations_delta":{let k=s.delta.citation,h=J[s.index];h?.type==="text"&&k.type==="web_search_result_location"&&h.citations.push(k);let M=et(k,z,te);M&&p.enqueue(M);return}default:{let k=o;throw new Error(`Unsupported delta type: ${k}`)}}}case"message_start":{if(L){if(ee===s.message.id)return;ce=!0,p.enqueue({type:"error",error:new Me({data:s,message:`Received message_start for message ${JSON.stringify(s.message.id)} while message ${JSON.stringify(ee)} is still open.`})});return}if(L=!0,ee=s.message.id,A.input_tokens=s.message.usage.input_tokens,s.message.input_transformations!=null&&(r=s.message.input_transformations),A.cache_read_input_tokens=($=s.message.usage.cache_read_input_tokens)!=null?$:0,A.cache_creation_input_tokens=(l=s.message.usage.cache_creation_input_tokens)!=null?l:0,N={...s.message.usage},ne=(ae=s.message.usage.cache_creation_input_tokens)!=null?ae:null,s.message.container!=null&&(d={expiresAt:s.message.container.expires_at,id:s.message.container.id,skills:null}),s.message.stop_reason!=null&&(j={unified:Oe({finishReason:s.message.stop_reason,isJsonResponseFromTool:B}),raw:s.message.stop_reason}),p.enqueue({type:"response-metadata",id:(O=s.message.id)!=null?O:void 0,modelId:(f=s.message.model)!=null?f:void 0}),s.message.content!=null)for(let o=0;o<s.message.content.length;o++){let k=s.message.content[o];if(k.type==="tool_use"){let h=ke(k.caller);p.enqueue({type:"tool-input-start",id:k.id,toolName:k.name});let M=JSON.stringify((w=k.input)!=null?w:{});p.enqueue({type:"tool-input-delta",id:k.id,delta:M}),p.enqueue({type:"tool-input-end",id:k.id}),p.enqueue({type:"tool-call",toolCallId:k.id,toolName:k.name,input:M,...h&&{providerMetadata:{anthropic:{caller:h}}}})}}return}case"message_delta":{s.usage.input_tokens!=null&&A.input_tokens!==s.usage.input_tokens&&(A.input_tokens=s.usage.input_tokens),A.output_tokens=s.usage.output_tokens,s.usage.output_tokens_details!=null&&(A.output_tokens_details=s.usage.output_tokens_details),s.usage.cache_read_input_tokens!=null&&(A.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.cache_creation_input_tokens!=null&&(A.cache_creation_input_tokens=s.usage.cache_creation_input_tokens,ne=s.usage.cache_creation_input_tokens),s.usage.iterations!=null&&(A.iterations=s.usage.iterations),j={unified:Oe({finishReason:s.delta.stop_reason,isJsonResponseFromTool:B}),raw:(b=s.delta.stop_reason)!=null?b:void 0},ue=(u=s.delta.stop_sequence)!=null?u:null,se=rt(s.delta.stop_details),d=s.delta.container!=null?{expiresAt:s.delta.container.expires_at,id:s.delta.container.id,skills:(he=(K=s.delta.container.skills)==null?void 0:K.map(o=>({type:o.type,skillId:o.skill_id,version:o.version})))!=null?he:null}:null,s.context_management&&(le=ot(s.context_management)),N={...N,...s.usage};return}case"message_stop":{L=!1,ee=void 0;let o={usage:N??null,cacheCreationInputTokens:ne,stopSequence:ue,...se!=null?{stopDetails:se}:{},...r!=null?{inputTransformations:r}:{},iterations:A.iterations?A.iterations.map(h=>({type:h.type,...h.model!=null?{model:h.model}:{},inputTokens:h.input_tokens,outputTokens:h.output_tokens,...h.cache_creation_input_tokens?{cacheCreationInputTokens:h.cache_creation_input_tokens}:{},...h.cache_read_input_tokens?{cacheReadInputTokens:h.cache_read_input_tokens}:{}})):null,container:d,contextManagement:le},k={anthropic:o};I&&F!=="anthropic"&&(k[F]=o),p.enqueue({type:"finish",finishReason:j,usage:Ze({usage:A,rawUsage:N}),providerMetadata:k});return}case"error":{p.enqueue({type:"error",error:s.error});return}default:{let o=s;throw new Error(`Unsupported chunk type: ${o}`)}}}})),[Y,de]=D.tee(),oe=Y.getReader();try{await oe.read();let g=await oe.read();if(((a=g.value)==null?void 0:a.type)==="raw"&&(g=await oe.read()),((n=g.value)==null?void 0:n.type)==="error"){let p=g.value.error;throw new Ee({message:p.message,url:E,requestBodyValues:c,statusCode:p.type==="overloaded_error"?529:500,responseHeaders:R,responseBody:JSON.stringify(p),isRetryable:p.type==="overloaded_error"})}}finally{oe.cancel().catch(()=>{}),oe.releaseLock()}return{stream:de,request:{body:c},response:{headers:R}}}};function ko(t){return t.includes("claude-opus-5")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,rejectsThinkingDisabledAboveHighEffort:!0,isKnownModel:!0}:t.includes("claude-opus-4-8")||t.includes("claude-opus-4-7")||t.includes("claude-fable-5")||t.includes("claude-sonnet-5")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:t.includes("claude-sonnet-4-6")||t.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:t.includes("claude-sonnet-4-5")||t.includes("claude-opus-4-5")||t.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:t.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:t.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:t.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:t.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0}:/claude-(?:instant(?:-|$)|v?2(?=$|[-.:])|3(?=$|[-.]))/.test(t)?{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!1}:t.includes("claude-")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,rejectsThinkingDisabledAboveHighEffort:!0,isKnownModel:!1}:{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!1}}v(ko,"getModelCapabilities");function tt(t){if(!t)return!1;let a=!1,n=!1;for(let c of t){if("type"in c&&(c.type==="web_fetch_20260209"||c.type==="web_search_20260209")){a=!0;continue}if(c.name==="code_execution"){n=!0;break}}return a&&!n}v(tt,"hasWebTool20260209WithoutCodeExecution");function ot(t){return t?{appliedEdits:t.applied_edits.map(a=>{switch(a.type){case"clear_tool_uses_20250919":return{type:a.type,clearedToolUses:a.cleared_tool_uses,clearedInputTokens:a.cleared_input_tokens};case"clear_thinking_20251015":return{type:a.type,clearedThinkingTurns:a.cleared_thinking_turns,clearedInputTokens:a.cleared_input_tokens};case"compact_20260112":return{type:a.type}}}).filter(a=>a!==void 0)}:null}v(ot,"mapAnthropicResponseContextManagement");function rt(t){if(t!=null)return{type:t.type,...t.category!=null?{category:t.category}:{},...t.explanation!=null?{explanation:t.explanation}:{},...t.recommended_model!=null?{recommendedModel:t.recommended_model}:{}}}v(rt,"mapAnthropicStopDetails");var jo=_(()=>m(e.object({command:e.string(),restart:e.boolean().optional()}))),wo=V({id:"anthropic.bash_20241022",inputSchema:jo}),So=_(()=>m(e.object({command:e.string(),restart:e.boolean().optional()}))),Co=V({id:"anthropic.bash_20250124",inputSchema:So}),To=_(()=>m(e.object({action:e.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:e.array(e.number().int()).optional(),text:e.string().optional()}))),No=V({id:"anthropic.computer_20241022",inputSchema:To}),Oo=_(()=>m(e.object({action:e.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:e.tuple([e.number().int(),e.number().int()]).optional(),duration:e.number().optional(),scroll_amount:e.number().optional(),scroll_direction:e.enum(["up","down","left","right"]).optional(),start_coordinate:e.tuple([e.number().int(),e.number().int()]).optional(),text:e.string().optional()}))),Io=V({id:"anthropic.computer_20250124",inputSchema:Oo}),zo=_(()=>m(e.object({action:e.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:e.tuple([e.number().int(),e.number().int()]).optional(),duration:e.number().optional(),region:e.tuple([e.number().int(),e.number().int(),e.number().int(),e.number().int()]).optional(),scroll_amount:e.number().optional(),scroll_direction:e.enum(["up","down","left","right"]).optional(),start_coordinate:e.tuple([e.number().int(),e.number().int()]).optional(),text:e.string().optional()}))),Eo=V({id:"anthropic.computer_20251124",inputSchema:zo}),Po=_(()=>m(e.discriminatedUnion("command",[e.object({command:e.literal("view"),path:e.string(),view_range:e.tuple([e.number(),e.number()]).optional()}),e.object({command:e.literal("create"),path:e.string(),file_text:e.string()}),e.object({command:e.literal("str_replace"),path:e.string(),old_str:e.string(),new_str:e.string()}),e.object({command:e.literal("insert"),path:e.string(),insert_line:e.number(),insert_text:e.string()}),e.object({command:e.literal("delete"),path:e.string()}),e.object({command:e.literal("rename"),old_path:e.string(),new_path:e.string()})]))),Mo=V({id:"anthropic.memory_20250818",inputSchema:Po}),Ro=_(()=>m(e.object({command:e.enum(["view","create","str_replace","insert","undo_edit"]),path:e.string(),file_text:e.string().optional(),insert_line:e.number().int().optional(),new_str:e.string().optional(),insert_text:e.string().optional(),old_str:e.string().optional(),view_range:e.array(e.number().int()).optional()}))),Ao=V({id:"anthropic.text_editor_20241022",inputSchema:Ro}),Uo=_(()=>m(e.object({command:e.enum(["view","create","str_replace","insert","undo_edit"]),path:e.string(),file_text:e.string().optional(),insert_line:e.number().int().optional(),new_str:e.string().optional(),insert_text:e.string().optional(),old_str:e.string().optional(),view_range:e.array(e.number().int()).optional()}))),qo=V({id:"anthropic.text_editor_20250124",inputSchema:Uo}),$o=_(()=>m(e.object({command:e.enum(["view","create","str_replace","insert"]),path:e.string(),file_text:e.string().optional(),insert_line:e.number().int().optional(),new_str:e.string().optional(),insert_text:e.string().optional(),old_str:e.string().optional(),view_range:e.array(e.number().int()).optional()}))),Do=V({id:"anthropic.text_editor_20250429",inputSchema:$o}),Bo=_(()=>m(e.array(e.object({type:e.literal("tool_reference"),toolName:e.string()})))),Fo=_(()=>m(e.object({query:e.string(),limit:e.number().optional()}))),Ho=G({id:"anthropic.tool_search_bm25_20251119",inputSchema:Fo,outputSchema:Bo,supportsDeferredResults:!0}),Jo=v((t={})=>Ho(t),"toolSearchBm25_20251119"),Lo={advisor_20260301:Tt,bash_20241022:wo,bash_20250124:Co,codeExecution_20250522:Qt,codeExecution_20250825:oo,codeExecution_20260120:ao,computer_20241022:No,computer_20250124:Io,computer_20251124:Eo,memory_20250818:Mo,textEditor_20241022:Ao,textEditor_20250124:qo,textEditor_20250429:Do,textEditor_20250728:zt,webFetch_20250910:Gt,webFetch_20260209:Lt,webSearch_20250305:Dt,webSearch_20260209:At,toolSearchRegex_20251119:so,toolSearchBm25_20251119:Jo},mt="https://api.anthropic.com",ht=`${mt}/v1`;function Wo(t){let a=We(t);return a===mt?ht:a}v(Wo,"normalizeBaseURL");function Ko(t={}){var a,n;let c=(a=Wo(Be({settingValue:t.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?a:ht,y=(n=t.name)!=null?n:"anthropic.messages";if(t.apiKey&&t.authToken)throw new Pe({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let P=v(()=>{let F=t.authToken?{Authorization:`Bearer ${t.authToken}`}:{"x-api-key":De({apiKey:t.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return qe({"anthropic-version":"2023-06-01",...F,...t.headers},`ai-sdk/anthropic/${gt}`)},"getHeaders"),q=v(F=>{var I;return new xo(F,{provider:y,baseURL:c,headers:P,fetch:t.fetch,generateId:(I=t.generateId)!=null?I:ve,supportedUrls:v(()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]}),"supportedUrls")})},"createChatModel"),T=v(function(F){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return q(F)},"provider");return T.specificationVersion="v3",T.languageModel=q,T.chat=q,T.messages=q,T.embeddingModel=F=>{throw new je({modelId:F,modelType:"embeddingModel"})},T.textEmbeddingModel=T.embeddingModel,T.imageModel=F=>{throw new je({modelId:F,modelType:"imageModel"})},T.tools=Lo,T}v(Ko,"createAnthropic");var Kr=Ko();function Vr({steps:t}){var a,n,c;for(let y=t.length-1;y>=0;y--){let P=(c=(n=(a=t[y].providerMetadata)==null?void 0:a.anthropic)==null?void 0:n.container)==null?void 0:c.id;if(P)return{providerOptions:{anthropic:{container:{id:P}}}}}}v(Vr,"forwardAnthropicContainerIdFromLastStep");export{gt as a,Ko as b,Kr as c,Vr as d};
|
|
@@ -0,0 +1,18 @@
|
|
|
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 u,b as v,d as _}from"./chunk-2MRHL4B2.js";var C=_(a=>{"use strict";var g=u((t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),"a"),B=g(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sync=t.isexe=void 0;var e=v("node:fs"),r=v("node:fs/promises"),n=u(async(c,o={})=>{let{ignoreErrors:i=!1}=o;try{return p(await(0,r.stat)(c),o)}catch(l){let f=l;if(i||f.code==="EACCES")return!1;throw f}},"q");t.isexe=n;var s=u((c,o={})=>{let{ignoreErrors:i=!1}=o;try{return p((0,e.statSync)(c),o)}catch(l){let f=l;if(i||f.code==="EACCES")return!1;throw f}},"m");t.sync=s;var p=u((c,o)=>c.isFile()&&h(c,o),"d"),h=u((c,o)=>{let i=o.uid??process.getuid?.(),l=o.groups??process.getgroups?.()??[],f=o.gid??process.getgid?.()??l[0];if(i===void 0||f===void 0)throw new Error("cannot get uid or gid");let E=new Set([f,...l]),d=c.mode,x=c.uid,H=c.gid,w=parseInt("100",8),y=parseInt("010",8),N=parseInt("001",8),R=w|y;return!!(d&N||d&y&&E.has(H)||d&w&&x===i||d&R&&i===0)},"A")}),m=g(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sync=t.isexe=void 0;var e=v("node:fs"),r=v("node:fs/promises"),n=v("node:path"),s=u(async(o,i={})=>{let{ignoreErrors:l=!1}=i;try{return c(await(0,r.stat)(o),o,i)}catch(f){let E=f;if(l||E.code==="EACCES")return!1;throw E}},"F");t.isexe=s;var p=u((o,i={})=>{let{ignoreErrors:l=!1}=i;try{return c((0,e.statSync)(o),o,i)}catch(f){let E=f;if(l||E.code==="EACCES")return!1;throw E}},"L");t.sync=p;var h=u((o,i)=>{let{pathExt:l=process.env.PATHEXT||""}=i,f=l.split(n.delimiter);if(f.indexOf("")!==-1)return!0;for(let E of f){let d=E.toLowerCase(),x=o.substring(o.length-d.length).toLowerCase();if(d&&x===d)return!0}return!1},"B"),c=u((o,i,l)=>o.isFile()&&h(i,l),"y")}),D=g(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})}),O=a&&a.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:u(function(){return e[r]},"get")}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),G=a&&a.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),P=a&&a.__importStar||(function(){var t=u(function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)},"t");return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&O(r,e,n[s]);return G(r,e),r}})(),W=a&&a.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&O(e,t,r)};Object.defineProperty(a,"__esModule",{value:!0});a.sync=a.isexe=a.posix=a.win32=void 0;var b=P(B());a.posix=b;var j=P(m());a.win32=j;W(D(),a);var k=process.env._ISEXE_TEST_PLATFORM_||process.platform,S=k==="win32"?j:b;a.isexe=S.isexe;a.sync=S.sync});var Y=_((et,X)=>{var{isexe:z,sync:J}=C(),{join:K,delimiter:Q,sep:M,posix:T}=v("path"),A=process.platform==="win32",q=new RegExp(`[${T.sep}${M===T.sep?"":M}]`.replace(/(\\)/g,"\\$1")),U=new RegExp(`^\\.${q.source}`),I=u(t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),"getNotFoundError"),$=u((t,{path:e=process.env.PATH,pathExt:r=process.env.PATHEXT,delimiter:n=Q})=>{let s=t.match(q)?[""]:[...A?[process.cwd()]:[],...(e||"").split(n)];if(A){let p=r||[".EXE",".CMD",".BAT",".COM"].join(n),h=p.split(n).flatMap(c=>[c,c.toLowerCase()]);return t.includes(".")&&h[0]!==""&&h.unshift(""),{pathEnv:s,pathExt:h,pathExtExe:p}}return{pathEnv:s,pathExt:[""]}},"getPathInfo"),F=u((t,e)=>{let r=/^".*"$/.test(t)?t.slice(1,-1):t;return(!r&&U.test(e)?e.slice(0,2):"")+K(r,e)},"getPathPart"),L=u(async(t,e={})=>{let{pathEnv:r,pathExt:n,pathExtExe:s}=$(t,e),p=[];for(let h of r){let c=F(h,t);for(let o of n){let i=c+o;if(await z(i,{pathExt:s,ignoreErrors:!0})){if(!e.all)return i;p.push(i)}}}if(e.all&&p.length)return p;if(e.nothrow)return null;throw I(t)},"which"),V=u((t,e={})=>{let{pathEnv:r,pathExt:n,pathExtExe:s}=$(t,e),p=[];for(let h of r){let c=F(h,t);for(let o of n){let i=c+o;if(J(i,{pathExt:s,ignoreErrors:!0})){if(!e.all)return i;p.push(i)}}}if(e.all&&p.length)return p;if(e.nothrow)return null;throw I(t)},"whichSync");X.exports=L;L.sync=V});export{Y as a};
|
|
@@ -0,0 +1,18 @@
|
|
|
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{c as At,d as se}from"./chunk-V6HERYFV.js";import{a as mt,b as lt,c as I,d as ft,e as P,f as c,g as St,h as re,j as B,k as U,l as Et,n as Tt,p as st,q as Lt,r as it,s as gt,t as x,u as Pt,w as z,x as xt,z as S}from"./chunk-DO2UZ6NY.js";import{a as R}from"./chunk-AZUMH3TO.js";import{a as o,c as d,e as ee,g as O}from"./chunk-2MRHL4B2.js";var Ct,Ot=d(()=>{Ct="exception"});var h,T,$,wt=d(()=>{h=O(R());S();T=O(re());Ot();$=class{static{o(this,"SpanImpl")}_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:h.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(t){let e=Date.now();if(this._spanContext=t.spanContext,this._performanceStartTime=B.now(),this._performanceOffset=e-(this._performanceStartTime+B.timeOrigin),this._startTimeProvided=t.startTime!=null,this._spanLimits=t.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=t.spanProcessor,this.name=t.name,this.parentSpanContext=t.parentSpanContext,this.kind=t.kind,t.links)for(let r of t.links)this.addLink(r);this.startTime=this._getTime(t.startTime??e),this.resource=t.resource,this.instrumentationScope=t.scope,this._recordEndMetrics=t.recordEndMetrics,t.attributes!=null&&this.setAttributes(t.attributes),this._spanProcessor.onStart(this,t.context)}spanContext(){return this._spanContext}setAttribute(t,e){if(e==null||this._isSpanEnded())return this;if(t.length===0)return h.diag.warn(`Invalid attribute key: ${t}`),this;if(!ft(e))return h.diag.warn(`Invalid attribute value set for key: ${t}`),this;let{attributeCountLimit:r}=this._spanLimits,i=!Object.prototype.hasOwnProperty.call(this.attributes,t);return r!==void 0&&this._attributesCount>=r&&i?(this._droppedAttributesCount++,this):(this.attributes[t]=this._truncateToSize(e),i&&this._attributesCount++,this)}setAttributes(t){for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&this.setAttribute(e,t[e]);return this}addEvent(t,e,r){if(this._isSpanEnded())return this;let{eventCountLimit:i}=this._spanLimits;if(i===0)return h.diag.warn("No events allowed."),this._droppedEventsCount++,this;i!==void 0&&this.events.length>=i&&(this._droppedEventsCount===0&&h.diag.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),it(e)&&(it(r)||(r=e),e=void 0);let n=I(e),{attributePerEventCountLimit:p}=this._spanLimits,a={},m=0,_=0;for(let E in n){if(!Object.prototype.hasOwnProperty.call(n,E))continue;let k=n[E];if(p!==void 0&&_>=p){m++;continue}a[E]=this._truncateToSize(k),_++}return this.events.push({name:t,attributes:a,time:this._getTime(r),droppedAttributesCount:m}),this}addLink(t){if(this._isSpanEnded())return this;let{linkCountLimit:e}=this._spanLimits;if(e===0)return this._droppedLinksCount++,this;e!==void 0&&this.links.length>=e&&(this._droppedLinksCount===0&&h.diag.debug("Dropping extra links."),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:r}=this._spanLimits,i=I(t.attributes),n={},p=0,a=0;for(let _ in i){if(!Object.prototype.hasOwnProperty.call(i,_))continue;let E=i[_];if(r!==void 0&&a>=r){p++;continue}n[_]=this._truncateToSize(E),a++}let m={context:t.context};return a>0&&(m.attributes=n),p>0&&(m.droppedAttributesCount=p),this.links.push(m),this}addLinks(t){for(let e of t)this.addLink(e);return this}setStatus(t){if(this._isSpanEnded())return this;if(t.code===h.SpanStatusCode.UNSET)return this;if(this.status.code===h.SpanStatusCode.OK)return this;let e={code:t.code};return t.code===h.SpanStatusCode.ERROR&&(typeof t.message=="string"?e.message=t.message:t.message!=null&&h.diag.warn(`Dropping invalid status.message of type '${typeof t.message}', expected 'string'`)),this.status=e,this}updateName(t){return this._isSpanEnded()?this:(this.name=t,this)}end(t){if(this._isSpanEnded()){h.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(t),this._duration=Tt(this.startTime,this.endTime),this._duration[0]<0&&(h.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&h.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&h.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(t){if(typeof t=="number"&&t<=B.now())return Et(t+this._performanceOffset);if(typeof t=="number")return U(t);if(t instanceof Date)return U(t.getTime());if(Lt(t))return t;if(this._startTimeProvided)return U(Date.now());let e=B.now()-this._performanceStartTime;return gt(this.startTime,U(e))}isRecording(){return this._ended===!1}recordException(t,e){let r={};typeof t=="string"?r[T.ATTR_EXCEPTION_MESSAGE]=t:t&&(t.code?r[T.ATTR_EXCEPTION_TYPE]=t.code.toString():t.name&&(r[T.ATTR_EXCEPTION_TYPE]=t.name),t.message&&(r[T.ATTR_EXCEPTION_MESSAGE]=t.message),t.stack&&(r[T.ATTR_EXCEPTION_STACKTRACE]=t.stack)),r[T.ATTR_EXCEPTION_TYPE]||r[T.ATTR_EXCEPTION_MESSAGE]?this.addEvent(Ct,r,e):h.diag.warn(`Failed to record an exception ${t}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let t=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);h.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,t)}return this._ended}_truncateToLimitUtil(t,e){return t.length<=e?t:t.substring(0,e)}_truncateToSize(t){let e=this._attributeValueLengthLimit;return e<=0?(h.diag.warn(`Attribute value limit must be positive, got ${e}`),t):typeof t=="string"?this._truncateToLimitUtil(t,e):Array.isArray(t)?t.map(r=>typeof r=="string"?this._truncateToLimitUtil(r,e):r):t}}});var l,M=d(()=>{(function(s){s[s.NOT_RECORD=0]="NOT_RECORD",s[s.RECORD=1]="RECORD",s[s.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(l||(l={}))});var L,G=d(()=>{M();L=class{static{o(this,"AlwaysOffSampler")}shouldSample(){return{decision:l.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}});var f,V=d(()=>{M();f=class{static{o(this,"AlwaysOnSampler")}shouldSample(){return{decision:l.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}});var b,A,nt=d(()=>{b=O(R());S();G();V();A=class{static{o(this,"ParentBasedSampler")}_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(t){this._root=t.root,this._root||(P(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new f),this._remoteParentSampled=t.remoteParentSampled??new f,this._remoteParentNotSampled=t.remoteParentNotSampled??new L,this._localParentSampled=t.localParentSampled??new f,this._localParentNotSampled=t.localParentNotSampled??new L}shouldSample(t,e,r,i,n,p){let a=b.trace.getSpanContext(t);return!a||!(0,b.isSpanContextValid)(a)?this._root.shouldSample(t,e,r,i,n,p):a.isRemote?a.traceFlags&b.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(t,e,r,i,n,p):this._remoteParentNotSampled.shouldSample(t,e,r,i,n,p):a.traceFlags&b.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(t,e,r,i,n,p):this._localParentNotSampled.shouldSample(t,e,r,i,n,p)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}});var Rt,N,ot=d(()=>{Rt=O(R());M();N=class{static{o(this,"TraceIdRatioBasedSampler")}_ratio;_upperBound;constructor(t=0){this._ratio=this._normalize(t),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(t,e){return{decision:(0,Rt.isValidTraceId)(e)&&this._accumulate(e)<this._upperBound?l.RECORD_AND_SAMPLED:l.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(t){return typeof t!="number"||isNaN(t)?0:t>=1?1:t<=0?0:t}_accumulate(t){let e=0;for(let r=0;r<t.length/8;r++){let i=r*8,n=parseInt(t.slice(i,i+8),16);e=(e^n)>>>0}return e}}});function j(){return{sampler:at(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:c("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:c("OTEL_ATTRIBUTE_COUNT_LIMIT")??128},spanLimits:{attributeValueLengthLimit:c("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:c("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??128,linkCountLimit:c("OTEL_SPAN_LINK_COUNT_LIMIT")??128,eventCountLimit:c("OTEL_SPAN_EVENT_COUNT_LIMIT")??128,attributePerEventCountLimit:c("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT")??128,attributePerLinkCountLimit:c("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT")??128}}}function at(){let s=St("OTEL_TRACES_SAMPLER")??g.ParentBasedAlwaysOn;switch(s){case g.AlwaysOn:return new f;case g.AlwaysOff:return new L;case g.ParentBasedAlwaysOn:return new A({root:new f});case g.ParentBasedAlwaysOff:return new A({root:new L});case g.TraceIdRatio:return new N(It());case g.ParentBasedTraceIdRatio:return new A({root:new N(It())});default:return Q.diag.error(`OTEL_TRACES_SAMPLER value "${s}" invalid, defaulting to "${g.ParentBasedAlwaysOn}".`),new A({root:new f})}}function It(){let s=c("OTEL_TRACES_SAMPLER_ARG");return s==null?(Q.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${H}.`),H):s<0||s>1?(Q.diag.error(`OTEL_TRACES_SAMPLER_ARG=${s} was given, but it is out of range ([0..1]), defaulting to ${H}.`),H):s}var Q,g,H,pt=d(()=>{Q=O(R());S();G();V();nt();ot();(function(s){s.AlwaysOff="always_off",s.AlwaysOn="always_on",s.ParentBasedAlwaysOff="parentbased_always_off",s.ParentBasedAlwaysOn="parentbased_always_on",s.ParentBasedTraceIdRatio="parentbased_traceidratio",s.TraceIdRatio="traceidratio"})(g||(g={}));H=1;o(j,"loadDefaultConfig");o(at,"buildSamplerFromEnv");o(It,"getSamplerProbabilityFromEnv")});function bt(s){let t={sampler:at()},e=j(),r=Object.assign({},e,t,s);return r.generalLimits=Object.assign({},e.generalLimits,s.generalLimits||{}),r.spanLimits=Object.assign({},e.spanLimits,s.spanLimits||{}),r}function Nt(s){let t=Object.assign({},s.spanLimits);return t.attributeCountLimit=s.spanLimits?.attributeCountLimit??s.generalLimits?.attributeCountLimit??c("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??c("OTEL_ATTRIBUTE_COUNT_LIMIT")??ie,t.attributeValueLengthLimit=s.spanLimits?.attributeValueLengthLimit??s.generalLimits?.attributeValueLengthLimit??c("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??c("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??ne,Object.assign({},s,{spanLimits:t})}var ie,ne,ut=d(()=>{pt();S();ie=128,ne=1/0;o(bt,"mergeConfig");o(Nt,"reconfigureLimits")});var C,Y,Dt=d(()=>{C=O(R());S();Y=class{static{o(this,"BatchSpanProcessorBase")}_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(t,e){this._exporter=t,this._maxExportBatchSize=typeof e?.maxExportBatchSize=="number"?e.maxExportBatchSize:c("OTEL_BSP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=typeof e?.maxQueueSize=="number"?e.maxQueueSize:c("OTEL_BSP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=typeof e?.scheduledDelayMillis=="number"?e.scheduledDelayMillis:c("OTEL_BSP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=typeof e?.exportTimeoutMillis=="number"?e.exportTimeoutMillis:c("OTEL_BSP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new z(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(C.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(t,e){}onEnd(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&C.TraceFlags.SAMPLED)!==0&&this._addToBuffer(t)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&C.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(C.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()}_flushAll(){return new Promise((t,e)=>{let r=[],i=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let n=0,p=i;n<p;n++)r.push(this._flushOneBatch());Promise.all(r).then(()=>{t()}).catch(e)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((t,e)=>{let r=setTimeout(()=>{e(new Error("Timeout"))},this._exportTimeoutMillis);C.context.with(mt(C.context.active()),()=>{let i;this._finishedSpans.length<=this._maxExportBatchSize?(i=this._finishedSpans,this._finishedSpans=[]):i=this._finishedSpans.splice(0,this._maxExportBatchSize);let n=o(()=>this._exporter.export(i,a=>{clearTimeout(r),a.code===x.SUCCESS?t():e(a.error??new Error("BatchSpanProcessor: span export failed"))}),"doExport"),p=null;for(let a=0,m=i.length;a<m;a++){let _=i[a];_.resource.asyncAttributesPending&&_.resource.waitForAsyncAttributes&&(p??=[],p.push(_.resource.waitForAsyncAttributes()))}p===null?n():Promise.all(p).then(n,a=>{P(a),e(a)})})})}_maybeStartTimer(){if(this._isExporting)return;let t=o(()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,P(e)})},"flush");if(this._finishedSpans.length>=this._maxExportBatchSize)return t();this._timer===void 0&&(this._timer=setTimeout(()=>t(),this._scheduledDelayMillis),typeof this._timer!="number"&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}}});var v,Mt=d(()=>{Dt();v=class extends Y{static{o(this,"BatchSpanProcessor")}onShutdown(){}}});function vt(s){return o(function(){for(let e=0;e<s/4;e++)X.writeUInt32BE(Math.random()*2**32>>>0,e*4);for(let e=0;e<s&&!(X[e]>0);e++)e===s-1&&(X[s-1]=1);return X.toString("hex",0,s)},"generateId")}var w,X,yt=d(()=>{w=class{static{o(this,"RandomIdGenerator")}generateTraceId=vt(16);generateSpanId=vt(8)},X=Buffer.allocUnsafe(16);o(vt,"getIdGenerator")});var Bt=d(()=>{Mt();yt()});var dt=d(()=>{Bt()});var Ut,ct,kt,Ft,zt=d(()=>{Ut="otel.span.parent.origin",ct="otel.span.sampling_result",kt="otel.sdk.span.live",Ft="otel.sdk.span.started"});function oe(s){return s?s.isRemote?"remote":"local":"none"}function ae(s){switch(s){case l.RECORD_AND_SAMPLED:return"RECORD_AND_SAMPLE";case l.RECORD:return"RECORD_ONLY";case l.NOT_RECORD:return"DROP"}}var K,$t=d(()=>{M();zt();K=class{static{o(this,"TracerMetrics")}startedSpans;liveSpans;constructor(t){this.startedSpans=t.createCounter(Ft,{unit:"{span}",description:"The number of created spans."}),this.liveSpans=t.createUpDownCounter(kt,{unit:"{span}",description:"The number of currently live spans."})}startSpan(t,e){let r=ae(e);if(this.startedSpans.add(1,{[Ut]:oe(t),[ct]:r}),e===l.NOT_RECORD)return()=>{};let i={[ct]:r};return this.liveSpans.add(1,i),()=>{this.liveSpans.add(-1,i)}}};o(oe,"parentOrigin");o(ae,"samplingDecisionToString")});var Gt,Vt=d(()=>{Gt="2.6.1"});var u,Z,Ht=d(()=>{u=O(R());S();wt();ut();dt();$t();Vt();Z=class{static{o(this,"Tracer")}_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(t,e,r,i){let n=bt(e);this._sampler=n.sampler,this._generalLimits=n.generalLimits,this._spanLimits=n.spanLimits,this._idGenerator=e.idGenerator||new w,this._resource=r,this._spanProcessor=i,this.instrumentationScope=t;let p=n.meterProvider?n.meterProvider.getMeter("@opentelemetry/sdk-trace",Gt):u.createNoopMeter();this._tracerMetrics=new K(p)}startSpan(t,e={},r=u.context.active()){e.root&&(r=u.trace.deleteSpan(r));let i=u.trace.getSpan(r);if(lt(r))return u.diag.debug("Instrumentation suppressed, returning Noop Span"),u.trace.wrapSpanContext(u.INVALID_SPAN_CONTEXT);let n=i?.spanContext(),p=this._idGenerator.generateSpanId(),a,m,_;!n||!u.trace.isSpanContextValid(n)?m=this._idGenerator.generateTraceId():(m=n.traceId,_=n.traceState,a=n);let E=e.kind??u.SpanKind.INTERNAL,k=(e.links??[]).map(F=>({context:F.context,attributes:I(F.attributes)})),ht=I(e.attributes),y=this._sampler.shouldSample(r,m,t,E,ht,k),Wt=this._tracerMetrics.startSpan(n,y.decision);_=y.traceState??_;let Jt=y.decision===u.SamplingDecision.RECORD_AND_SAMPLED?u.TraceFlags.SAMPLED:u.TraceFlags.NONE,_t={traceId:m,spanId:p,traceFlags:Jt,traceState:_};if(y.decision===u.SamplingDecision.NOT_RECORD)return u.diag.debug("Recording is off, propagating context in a non-recording span"),u.trace.wrapSpanContext(_t);let te=I(Object.assign(ht,y.attributes));return new $({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:_t,name:t,kind:E,links:k,parentSpanContext:a,attributes:te,startTime:e.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:Wt})}startActiveSpan(t,e,r,i){let n,p,a;if(arguments.length<2)return;arguments.length===2?a=e:arguments.length===3?(n=e,a=r):(n=e,p=r,a=i);let m=p??u.context.active(),_=this.startSpan(t,n,m),E=u.trace.setSpan(m,_);return u.context.with(E,a,void 0,_)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}});var q,Qt=d(()=>{S();q=class{static{o(this,"MultiSpanProcessor")}_spanProcessors;constructor(t){this._spanProcessors=t}forceFlush(){let t=[];for(let e of this._spanProcessors)t.push(e.forceFlush());return new Promise(e=>{Promise.all(t).then(()=>{e()}).catch(r=>{P(r||new Error("MultiSpanProcessor: forceFlush failed")),e()})})}onStart(t,e){for(let r of this._spanProcessors)r.onStart(t,e)}onEnding(t){for(let e of this._spanProcessors)e.onEnding&&e.onEnding(t)}onEnd(t){for(let e of this._spanProcessors)e.onEnd(t)}shutdown(){let t=[];for(let e of this._spanProcessors)t.push(e.shutdown());return new Promise((e,r)=>{Promise.all(t).then(()=>{e()},r)})}}});var D,W,jt=d(()=>{S();se();Ht();pt();Qt();ut();(function(s){s[s.resolved=0]="resolved",s[s.timeout=1]="timeout",s[s.error=2]="error",s[s.unresolved=3]="unresolved"})(D||(D={}));W=class{static{o(this,"BasicTracerProvider")}_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(t={}){let e=Pt({},j(),Nt(t));this._resource=e.resource??At(),this._config=Object.assign({},e,{resource:this._resource});let r=[];t.spanProcessors?.length&&r.push(...t.spanProcessors),this._activeSpanProcessor=new q(r)}getTracer(t,e,r){let i=`${t}@${e||""}:${r?.schemaUrl||""}`;return this._tracers.has(i)||this._tracers.set(i,new Z({name:t,version:e,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(i)}forceFlush(){let t=this._config.forceFlushTimeoutMillis,e=this._activeSpanProcessor._spanProcessors.map(r=>new Promise(i=>{let n,p=setTimeout(()=>{i(new Error(`Span processor did not completed within timeout period of ${t} ms`)),n=D.timeout},t);r.forceFlush().then(()=>{clearTimeout(p),n!==D.timeout&&(n=D.resolved,i(n))}).catch(a=>{clearTimeout(p),n=D.error,i(a)})}));return new Promise((r,i)=>{Promise.all(e).then(n=>{let p=n.filter(a=>a!==D.resolved);p.length>0?i(p):r()}).catch(n=>i([n]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}});var J,Yt=d(()=>{S();J=class{static{o(this,"ConsoleSpanExporter")}export(t,e){return this._sendSpans(t,e)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(t){return{resource:{attributes:t.resource.attributes},instrumentationScope:t.instrumentationScope,traceId:t.spanContext().traceId,parentSpanContext:t.parentSpanContext,traceState:t.spanContext().traceState?.serialize(),name:t.name,id:t.spanContext().spanId,kind:t.kind,timestamp:st(t.startTime),duration:st(t.duration),attributes:t.attributes,status:t.status,events:t.events,links:t.links}}_sendSpans(t,e){for(let r of t)console.dir(this._exportInfo(r),{depth:3});if(e)return e({code:x.SUCCESS})}}});var tt,Xt=d(()=>{S();tt=class{static{o(this,"InMemorySpanExporter")}_finishedSpans=[];_stopped=!1;export(t,e){if(this._stopped)return e({code:x.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...t),setTimeout(()=>e({code:x.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}});var Kt,et,Zt=d(()=>{Kt=O(R());S();et=class{static{o(this,"SimpleSpanProcessor")}_exporter;_shutdownOnce;_pendingExports;constructor(t){this._exporter=t,this._shutdownOnce=new z(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(t,e){}onEnd(t){if(this._shutdownOnce.isCalled||(t.spanContext().traceFlags&Kt.TraceFlags.SAMPLED)===0)return;let e=this._doExport(t).catch(r=>P(r));this._pendingExports.add(e),e.finally(()=>this._pendingExports.delete(e))}async _doExport(t){t.resource.asyncAttributesPending&&await t.resource.waitForAsyncAttributes?.();let e=await xt._export(this._exporter,[t]);if(e.code!==x.SUCCESS)throw e.error??new Error(`SimpleSpanProcessor: span export failed (status ${e})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}});var rt,qt=d(()=>{rt=class{static{o(this,"NoopSpanProcessor")}onStart(t,e){}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}});var pe={};ee(pe,{AlwaysOffSampler:()=>L,AlwaysOnSampler:()=>f,BasicTracerProvider:()=>W,BatchSpanProcessor:()=>v,ConsoleSpanExporter:()=>J,InMemorySpanExporter:()=>tt,NoopSpanProcessor:()=>rt,ParentBasedSampler:()=>A,RandomIdGenerator:()=>w,SamplingDecision:()=>l,SimpleSpanProcessor:()=>et,TraceIdRatioBasedSampler:()=>N});var ue=d(()=>{jt();dt();Yt();Xt();Zt();qt();G();V();nt();ot();M()});export{l as a,L as b,f as c,A as d,N as e,v as f,w as g,W as h,J as i,tt as j,et as k,rt as l,pe as m,ue as n};
|
|
@@ -0,0 +1,22 @@
|
|
|
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 T,b as y,c as R,e as E,h as _,m as b,r as z}from"./chunk-WKZYINC7.js";import{a as l}from"./chunk-Q3WIUQXB.js";import{c as j,e as U}from"./chunk-WPMP2ZFE.js";import{a as s}from"./chunk-2MRHL4B2.js";function bt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}s(bt,"combineHeaders");function k(e){return Object.fromEntries([...e.headers])}s(k,"extractResponseHeaders");var{btoa:ae,atob:oe}=globalThis;function Pt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=oe(t);return Uint8Array.from(r,n=>n.codePointAt(0))}s(Pt,"convertBase64ToUint8Array");function se(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return ae(t)}s(se,"convertUint8ArrayToBase64");function _t(e){return e instanceof Uint8Array?se(e):e}s(_t,"convertToBase64");function At(e,t={}){let{useArrayBrackets:r=!0}=t,n=new FormData;for(let[a,o]of Object.entries(e))if(o!=null){if(Array.isArray(o)){if(o.length===1){n.append(a,o[0]);continue}let i=r?`${a}[]`:a;for(let u of o)n.append(i,u);continue}n.append(a,o)}return n}s(At,"convertToFormData");var V="AI_DownloadError",K=`vercel.ai.error.${V}`,ie=Symbol.for(K),M,B,w=class extends(B=T,M=ie,B){static{s(this,"DownloadError")}constructor({url:e,statusCode:t,statusText:r,cause:n,message:a=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:V,message:a,cause:n}),this[M]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return T.hasMarker(e,K)}},G=2*1024*1024*1024;async function ue({response:e,url:t,maxBytes:r=G}){let n=e.headers.get("content-length");if(n!=null){let p=parseInt(n,10);if(!isNaN(p)&&p>r)throw new w({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${p}).`})}let a=e.body;if(a==null)return new Uint8Array(0);let o=a.getReader(),i=[],u=0;try{for(;;){let{done:p,value:A}=await o.read();if(p)break;if(u+=A.length,u>r)throw new w({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(A)}}finally{try{await o.cancel()}finally{o.releaseLock()}}let f=new Uint8Array(u),c=0;for(let p of i)f.set(p,c),c+=p.length;return f}s(ue,"readResponseWithSizeLimit");function J(e){let t;try{t=new URL(e)}catch{throw new w({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new w({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});let r=t.hostname;if(!r)throw new w({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new w({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){let n=r.slice(1,-1);if(ce(n))throw new w({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(X(r)){if(I(r))throw new w({url:e,message:`URL with IP address ${r} is not allowed`});return}}s(J,"validateDownloadUrl");function X(e){let t=e.split(".");return t.length!==4?!1:t.every(r=>{let n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}s(X,"isIPv4");function I(e){let t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}s(I,"isPrivateIPv4");function ce(e){let t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){let r=t.slice(7);if(X(r))return I(r);let n=r.split(":");if(n.length===2){let a=parseInt(n[0],16),o=parseInt(n[1],16);if(!isNaN(a)&&!isNaN(o)){let i=a>>8&255,u=a&255,f=o>>8&255,c=o&255;return I(`${i}.${u}.${f}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}s(ce,"isPrivateIPv6");async function kt(e,t){var r,n;J(e);try{let a=await fetch(e,{signal:t?.abortSignal});if(a.redirected&&J(a.url),!a.ok)throw new w({url:e,statusCode:a.status,statusText:a.statusText});let o=await ue({response:a,url:e,maxBytes:(r=t?.maxBytes)!=null?r:G}),i=(n=a.headers.get("content-type"))!=null?n:void 0;return new Blob([o],i?{type:i}:void 0)}catch(a){throw w.isInstance(a)?a:new w({url:e,cause:a})}}s(kt,"downloadBlob");var le=s(({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let a=s(()=>{let o=r.length,i=new Array(t);for(let u=0;u<t;u++)i[u]=r[Math.random()*o|0];return i.join("")},"generator");if(e==null)return a;if(r.includes(n))throw new E({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${a()}`},"createIdGenerator"),Tt=le();function Z(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}s(Z,"isAbortError");var fe=["fetch failed","failed to fetch"],de=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function pe(e){if(!(e instanceof Error))return!1;let t=e.code;return!!(typeof t=="string"&&de.includes(t))}s(pe,"isBunNetworkError");function me({error:e,url:t,requestBodyValues:r}){if(Z(e))return e;if(e instanceof TypeError&&fe.includes(e.message.toLowerCase())){let n=e.cause;if(n!=null)return new y({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return pe(e)?new y({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}s(me,"handleFetchError");function ye(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}s(ye,"getRuntimeEnvironmentUserAgent");function he(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(let[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}s(he,"normalizeHeaders");function ve(e,...t){let r=new Headers(he(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}s(ve,"withUserAgentSuffix");var ge="4.0.23";var we=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,be=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function H(e){let t=JSON.parse(e);return t===null||typeof t!="object"||we.test(e)===!1&&be.test(e)===!1?t:Pe(t)}s(H,"_parse");function Pe(e){let t=[e];for(;t.length;){let r=t;t=[];for(let n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor=="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let a in n){let o=n[a];o&&typeof o=="object"&&t.push(o)}}}return e}s(Pe,"filter");function D(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return H(e)}try{return H(e)}finally{Error.stackTraceLimit=t}}s(D,"secureJsonParse");function C(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;let{properties:r}=e;if(r!=null)for(let n of Object.keys(r))r[n]=P(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(P):P(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(P)),e.allOf!=null&&(e.allOf=e.allOf.map(P)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(P));let{definitions:t}=e;if(t!=null)for(let r of Object.keys(t))t[r]=P(t[r]);return e}s(C,"addAdditionalPropertiesToJsonSchema");function P(e){return typeof e=="boolean"?e:C(e)}s(P,"visit");var _e=Symbol("Let zodToJsonSchema decide on which parser to use"),W={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Ae=s(e=>typeof e=="string"?{...W,name:e}:{...W,...e},"getDefaultOptions");function h(){return{}}s(h,"parseAnyDef");function Ee(e,t){var r,n,a;let o={type:"array"};return(r=e.type)!=null&&r._def&&((a=(n=e.type)==null?void 0:n._def)==null?void 0:a.typeName)!==l.ZodAny&&(o.items=d(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}s(Ee,"parseArrayDef");function ke(e){let t={type:"integer",format:"int64"};if(!e.checks)return t;for(let r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}s(ke,"parseBigintDef");function Oe(){return{type:"boolean"}}s(Oe,"parseBooleanDef");function Y(e,t){return d(e.type._def,t)}s(Y,"parseBrandedDef");var Te=s((e,t)=>d(e.innerType._def,t),"parseCatchDef");function Q(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((a,o)=>Q(e,t,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Se(e)}}s(Q,"parseDateDef");var Se=s(e=>{let t={type:"integer",format:"unix-time"};for(let r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t},"integerDateParser");function $e(e,t){return{...d(e.innerType._def,t),default:e.defaultValue()}}s($e,"parseDefaultDef");function Ie(e,t){return t.effectStrategy==="input"?d(e.schema._def,t):h()}s(Ie,"parseEffectsDef");function Ze(e){return{type:"string",enum:Array.from(e.values)}}s(Ze,"parseEnumDef");var Fe=s(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function Ne(e,t){let r=[d(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),d(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),n=[];return r.forEach(a=>{if(Fe(a))n.push(...a.allOf);else{let o=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:i,...u}=a;o=u}n.push(o)}}),n.length?{allOf:n}:void 0}s(Ne,"parseIntersectionDef");function De(e){let t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}s(De,"parseLiteralDef");var S=void 0,v={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:s(()=>(S===void 0&&(S=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),S),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ee(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":g(r,"email",n.message,t);break;case"format:idn-email":g(r,"idn-email",n.message,t);break;case"pattern:zod":m(r,v.email,n.message,t);break}break;case"url":g(r,"uri",n.message,t);break;case"uuid":g(r,"uuid",n.message,t);break;case"regex":m(r,n.regex,n.message,t);break;case"cuid":m(r,v.cuid,n.message,t);break;case"cuid2":m(r,v.cuid2,n.message,t);break;case"startsWith":m(r,RegExp(`^${$(n.value,t)}`),n.message,t);break;case"endsWith":m(r,RegExp(`${$(n.value,t)}$`),n.message,t);break;case"datetime":g(r,"date-time",n.message,t);break;case"date":g(r,"date",n.message,t);break;case"time":g(r,"time",n.message,t);break;case"duration":g(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{m(r,RegExp($(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&g(r,"ipv4",n.message,t),n.version!=="v4"&&g(r,"ipv6",n.message,t);break}case"base64url":m(r,v.base64url,n.message,t);break;case"jwt":m(r,v.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&m(r,v.ipv4Cidr,n.message,t),n.version!=="v4"&&m(r,v.ipv6Cidr,n.message,t);break}case"emoji":m(r,v.emoji(),n.message,t);break;case"ulid":{m(r,v.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{g(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{m(r,v.base64,n.message,t);break}}break}case"nanoid":m(r,v.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}s(ee,"parseStringDef");function $(e,t){return t.patternStrategy==="escape"?xe(e):e}s($,"escapeLiteralCheckValue");var Ce=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function xe(e){let t="";for(let r=0;r<e.length;r++)Ce.has(e[r])||(t+="\\"),t+=e[r];return t}s(xe,"escapeNonAlphaNumeric");function g(e,t,r,n){var a;e.format||(a=e.anyOf)!=null&&a.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}s(g,"addFormat");function m(e,t,r,n){var a;e.pattern||(a=e.allOf)!=null&&a.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:q(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=q(t,n)}s(m,"addPattern");function q(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=n.i?e.source.toLowerCase():e.source,o="",i=!1,u=!1,f=!1;for(let c=0;c<a.length;c++){if(i){o+=a[c],i=!1;continue}if(n.i){if(u){if(a[c].match(/[a-z]/)){f?(o+=a[c],o+=`${a[c-2]}-${a[c]}`.toUpperCase(),f=!1):a[c+1]==="-"&&((r=a[c+2])!=null&&r.match(/[a-z]/))?(o+=a[c],f=!0):o+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){o+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(n.m){if(a[c]==="^"){o+=`(^|(?<=[\r
|
|
19
|
+
]))`;continue}else if(a[c]==="$"){o+=`($|(?=[\r
|
|
20
|
+
]))`;continue}}if(n.s&&a[c]==="."){o+=u?`${a[c]}\r
|
|
21
|
+
`:`[${a[c]}\r
|
|
22
|
+
]`;continue}o+=a[c],a[c]==="\\"?i=!0:u&&a[c]==="]"?u=!1:!u&&a[c]==="["&&(u=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}s(q,"stringifyRegExpWithFlags");function te(e,t){var r,n,a,o,i,u;let f={type:"object",additionalProperties:(r=d(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===l.ZodString&&((a=e.keyType._def.checks)!=null&&a.length)){let{type:c,...p}=ee(e.keyType._def,t);return{...f,propertyNames:p}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===l.ZodEnum)return{...f,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===l.ZodBranded&&e.keyType._def.type._def.typeName===l.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){let{type:c,...p}=Y(e.keyType._def,t);return{...f,propertyNames:p}}}return f}s(te,"parseRecordDef");function Le(e,t){if(t.mapStrategy==="record")return te(e,t);let r=d(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||h(),n=d(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||h();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}s(Le,"parseMapDef");function Re(e){let t=e.values,n=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),a=Array.from(new Set(n.map(o=>typeof o)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}s(Re,"parseNativeEnumDef");function je(){return{not:h()}}s(je,"parseNeverDef");function Ue(){return{type:"null"}}s(Ue,"parseNullDef");var F={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ze(e,t){let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in F&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((a,o)=>{let i=F[o._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((a,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":if(o._def.value===null)return[...a,"null"];default:return a}},[]);if(n.length===r.length){let a=n.filter((o,i,u)=>u.indexOf(o)===i);return{type:a.length>1?a:a[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(o=>!n.includes(o))],[])};return Me(e,t)}s(ze,"parseUnionDef");var Me=s((e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,a)=>d(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0},"asAnyOf");function Be(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[F[e.innerType._def.typeName],"null"]};let r=d(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}s(Be,"parseNullableDef");function Je(e){let t={type:"number"};if(!e.checks)return t;for(let r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}s(Je,"parseNumberDef");function He(e,t){let r={type:"object",properties:{}},n=[],a=e.shape();for(let i in a){let u=a[i];if(u===void 0||u._def===void 0)continue;let f=qe(u),c=d(u._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,f||n.push(i))}n.length&&(r.required=n);let o=We(e,t);return o!==void 0&&(r.additionalProperties=o),r}s(He,"parseObjectDef");function We(e,t){if(e.catchall._def.typeName!=="ZodNever")return d(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}s(We,"decideAdditionalProperties");function qe(e){try{return e.isOptional()}catch{return!0}}s(qe,"safeIsOptional");var Ve=s((e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return d(e.innerType._def,t);let n=d(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:h()},n]}:h()},"parseOptionalDef"),Ke=s((e,t)=>{if(t.pipeStrategy==="input")return d(e.in._def,t);if(t.pipeStrategy==="output")return d(e.out._def,t);let r=d(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=d(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}},"parsePipelineDef");function Ge(e,t){return d(e.type._def,t)}s(Ge,"parsePromiseDef");function Xe(e,t){let n={type:"array",uniqueItems:!0,items:d(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}s(Xe,"parseSetDef");function Ye(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>d(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:d(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>d(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}s(Ye,"parseTupleDef");function Qe(){return{not:h()}}s(Qe,"parseUndefinedDef");function et(){return h()}s(et,"parseUnknownDef");var tt=s((e,t)=>d(e.innerType._def,t),"parseReadonlyDef"),rt=s((e,t,r)=>{switch(t){case l.ZodString:return ee(e,r);case l.ZodNumber:return Je(e);case l.ZodObject:return He(e,r);case l.ZodBigInt:return ke(e);case l.ZodBoolean:return Oe();case l.ZodDate:return Q(e,r);case l.ZodUndefined:return Qe();case l.ZodNull:return Ue();case l.ZodArray:return Ee(e,r);case l.ZodUnion:case l.ZodDiscriminatedUnion:return ze(e,r);case l.ZodIntersection:return Ne(e,r);case l.ZodTuple:return Ye(e,r);case l.ZodRecord:return te(e,r);case l.ZodLiteral:return De(e);case l.ZodEnum:return Ze(e);case l.ZodNativeEnum:return Re(e);case l.ZodNullable:return Be(e,r);case l.ZodOptional:return Ve(e,r);case l.ZodMap:return Le(e,r);case l.ZodSet:return Xe(e,r);case l.ZodLazy:return()=>e.getter()._def;case l.ZodPromise:return Ge(e,r);case l.ZodNaN:case l.ZodNever:return je();case l.ZodEffects:return Ie(e,r);case l.ZodAny:return h();case l.ZodUnknown:return et();case l.ZodDefault:return $e(e,r);case l.ZodBranded:return Y(e,r);case l.ZodReadonly:return tt(e,r);case l.ZodCatch:return Te(e,r);case l.ZodPipeline:return Ke(e,r);case l.ZodFunction:case l.ZodVoid:case l.ZodSymbol:return;default:return(n=>{})(t)}},"selectParser"),nt=s((e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},"getRelativePath");function d(e,t,r=!1){var n;let a=t.seen.get(e);if(t.override){let f=(n=t.override)==null?void 0:n.call(t,e,t,a,r);if(f!==_e)return f}if(a&&!r){let f=at(a,t);if(f!==void 0)return f}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=rt(e,e.typeName,t),u=typeof i=="function"?d(i(),t):i;if(u&&ot(e,t,u),t.postProcess){let f=t.postProcess(u,e,t);return o.jsonSchema=u,f}return o.jsonSchema=u,u}s(d,"parseDef");var at=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:nt(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),h()):t.$refStrategy==="seen"?h():void 0}},"get$ref"),ot=s((e,t,r)=>(e.description&&(r.description=e.description),r),"addMeta"),st=s(e=>{let t=Ae(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},"getRefs"),it=s((e,t)=>{var r;let n=st(t),a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[p,A])=>{var L;return{...c,[p]:(L=d(A._def,{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0))!=null?L:h()}},{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=d(e._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:h(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(i.title=u);let f=o===void 0?a?{...i,[n.definitionPath]:a}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...a,[o]:i}};return f.$schema="http://json-schema.org/draft-07/schema#",f},"zod3ToJsonSchema"),N=Symbol.for("vercel.ai.schema");function O(e,{validate:t}={}){return{[N]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s(O,"jsonSchema");function ut(e){return typeof e=="object"&&e!==null&&N in e&&e[N]===!0&&"jsonSchema"in e&&"validate"in e}s(ut,"isSchema");function ct(e){return e==null?O({properties:{},additionalProperties:!1}):ut(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?mt(e):lt(e):e()}s(ct,"asSchema");function lt(e){return O(()=>C(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:s(async t=>{let r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new b({value:t,cause:r.issues})}},"validate")})}s(lt,"standardSchema");function ft(e,t){var r;let n=(r=t?.useReferences)!=null?r:!1;return O(()=>it(e,{$refStrategy:n?"root":"none"}),{validate:s(async a=>{let o=await e.safeParseAsync(a);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}},"validate")})}s(ft,"zod3Schema");function dt(e,t){var r;let n=(r=t?.useReferences)!=null?r:!1;return O(()=>C(j(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:s(async a=>{let o=await U(e,a);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}},"validate")})}s(dt,"zod4Schema");function pt(e){return"_zod"in e}s(pt,"isZod4Schema");function mt(e,t){return pt(e)?dt(e,t):ft(e,t)}s(mt,"zodSchema");async function yt({value:e,schema:t,context:r}){let n=await x({value:e,schema:t,context:r});if(!n.success)throw b.wrap({value:e,cause:n.error,context:r});return n.value}s(yt,"validateTypes");async function x({value:e,schema:t,context:r}){let n=ct(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let a=await n.validate(e);return a.success?{success:!0,value:a.value,rawValue:e}:{success:!1,error:b.wrap({value:e,cause:a.error,context:r}),rawValue:e}}catch(a){return{success:!1,error:b.wrap({value:e,cause:a,context:r}),rawValue:e}}}s(x,"safeValidateTypes");async function ht({text:e,schema:t}){try{let r=D(e);return t==null?r:yt({value:r,schema:t})}catch(r){throw _.isInstance(r)||b.isInstance(r)?r:new _({text:e,cause:r})}}s(ht,"parseJSON");async function re({text:e,schema:t}){try{let r=D(e);return t==null?{success:!0,value:r,rawValue:r}:await x({value:r,schema:t})}catch(r){return{success:!1,error:_.isInstance(r)?r:new _({text:e,cause:r}),rawValue:void 0}}}s(re,"safeParseJSON");function Ct(e){try{return D(e),!0}catch{return!1}}s(Ct,"isParsableJson");function vt({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new z).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await re({text:r,schema:t}))}}))}s(vt,"parseJsonEventStream");async function Rt({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;let n=await x({value:t[e],schema:r});if(!n.success)throw new E({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}s(Rt,"parseProviderOptions");var gt=s(()=>globalThis.fetch,"getOriginalFetch2"),Ut=s(async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:a,abortSignal:o,fetch:i})=>ne({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:a,abortSignal:o,fetch:i}),"postJsonToApi"),zt=s(async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:a,abortSignal:o,fetch:i})=>ne({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:a,abortSignal:o,fetch:i}),"postFormDataToApi"),ne=s(async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:a,abortSignal:o,fetch:i=gt()})=>{try{let u=await i(e,{method:"POST",headers:ve(t,`ai-sdk/provider-utils/${ge}`,ye()),body:r.content,signal:o}),f=k(u);if(!u.ok){let c;try{c=await a({response:u,url:e,requestBodyValues:r.values})}catch(p){throw Z(p)||y.isInstance(p)?p:new y({message:"Failed to process error response",cause:p,statusCode:u.status,url:e,responseHeaders:f,requestBodyValues:r.values})}throw c.value}try{return await n({response:u,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Z(c)||y.isInstance(c))?c:new y({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:f,requestBodyValues:r.values})}}catch(u){throw me({error:u,url:e,requestBodyValues:r.values})}},"postToApi");var Bt=s(({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:a,requestBodyValues:o})=>{let i=await n.text(),u=k(n);if(i.trim()==="")return{responseHeaders:u,value:new y({message:n.statusText,url:a,requestBodyValues:o,statusCode:n.status,responseHeaders:u,responseBody:i,isRetryable:r?.(n)})};try{let f=await ht({text:i,schema:e});return{responseHeaders:u,value:new y({message:t(f),url:a,requestBodyValues:o,statusCode:n.status,responseHeaders:u,responseBody:i,data:f,isRetryable:r?.(n,f)})}}catch{return{responseHeaders:u,value:new y({message:n.statusText,url:a,requestBodyValues:o,statusCode:n.status,responseHeaders:u,responseBody:i,isRetryable:r?.(n)})}}},"createJsonErrorResponseHandler"),Jt=s(e=>async({response:t})=>{let r=k(t);if(t.body==null)throw new R({});return{responseHeaders:r,value:vt({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Ht=s(e=>async({response:t,url:r,requestBodyValues:n})=>{let a=await t.text(),o=await re({text:a,schema:e}),i=k(t);if(!o.success)throw new y({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:i,responseBody:a,url:r,requestBodyValues:n});return{responseHeaders:i,value:o.value,rawValue:o.rawValue}},"createJsonResponseHandler");function Wt(e){return e?.replace(/\/$/,"")}s(Wt,"withoutTrailingSlash");export{bt as a,Pt as b,_t as c,At as d,kt as e,Tt as f,ve as g,Ct as h,Rt as i,Ut as j,zt as k,Bt as l,Jt as m,Ht as n,Wt as o};
|
|
@@ -0,0 +1,20 @@
|
|
|
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 t}from"./chunk-2MRHL4B2.js";import ce from"node:process";import N from"node:path";import{fileURLToPath as Ge}from"node:url";import Ke from"node:child_process";import Ye,{constants as Ve}from"node:fs/promises";import Se from"node:path";import{promisify as Pe}from"node:util";import ve from"node:child_process";import I,{constants as j}from"node:fs/promises";import X from"node:process";import ue from"node:os";import F from"node:fs";import fe from"node:fs";import R from"node:fs";var E;function me(){try{return R.statSync("/.dockerenv"),!0}catch{return!1}}t(me,"hasDockerEnv");function le(){try{return R.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}t(le,"hasDockerCGroup");function C(){return E===void 0&&(E=me()||le()),E}t(C,"isDocker");var B,pe=t(()=>{try{return fe.statSync("/run/.containerenv"),!0}catch{return!1}},"hasContainerEnv");function d(){return B===void 0&&(B=pe()||C()),B}t(d,"isInsideContainer");var z=t(()=>{if(X.platform!=="linux")return!1;if(ue.release().toLowerCase().includes("microsoft"))return!d();try{if(F.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!d()}catch{}return F.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||F.existsSync("/run/WSL")?!d():!1},"isWsl"),p=X.env.__IS_WSL_TEST__?z:z();import G from"node:process";import{Buffer as de}from"node:buffer";import{promisify as we}from"node:util";import he from"node:child_process";var ge=we(he.execFile),O=t(()=>`${G.env.SYSTEMROOT||G.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,"powerShellPath");var K=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"],Y=t(e=>de.from(e,"utf16le").toString("base64"),"encodeCommand"),xe=t(e=>`'${String(e).replaceAll(/['‘’‚‛]/g,r=>r+r)}'`,"escapeArgument"),V=t(e=>[...K,Y(e)],"createArguments"),ye=t(e=>({encoding:"utf8",...e,shell:!1}),"createExecFileOptions"),l=t(async(e,r={})=>{let{powerShellPath:o,...n}=r;return ge(o??O(),V(e),ye(n))},"executePowerShell");l.argumentsPrefix=K;l.encodeCommand=Y;l.escapeArgument=xe;l.createArguments=V;function q(e){for(let r of e.split(`
|
|
19
|
+
`)){if(/^\s*#/.test(r))continue;let o=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(r);if(o)return o.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}t(q,"parseMountPointFromConfig");var Ae=Pe(ve.execFile),be=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let o="/etc/wsl.conf",n=!1;try{await I.access(o,j.F_OK),n=!0}catch{}if(!n)return e;let s=await I.readFile(o,{encoding:"utf8"}),a=q(s);return a===void 0?e:(r=a,r=r.endsWith("/")?r:`${r}/`,r)}})(),Ee=t(async()=>`${await be()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,"powerShellPathFromWsl"),v=p?Ee:O,J,Q=t(async()=>(J??=(async()=>{try{let e=await v();return await I.access(e,j.X_OK),!0}catch{return!1}})(),J),"canAccessPowerShell"),Z=t(async()=>{let e=await v(),r=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:o}=await l(r,{powerShellPath:e,cwd:Se.dirname(e)});return o.trim()},"wslDefaultBrowser"),Ce=t(e=>/^[a-z]+:\/\//i.test(e),"isUrl"),Be=t(async(e,r)=>{let o=r.startsWith("-")?[e,"--",r]:[e,r];try{let{stdout:n}=await Ae("wslpath",o,{encoding:"utf8"});return n.replace(/\r?\n$/,"")||r}catch{return r}},"convertPath"),ee=t(async e=>{let r=Array.isArray(e),o=r?e:[e],n=await Promise.all(o.map(s=>Ce(s)?s:Be("-aw",s)));return r?n:n[0]},"convertWslPathToWindows");function w(e,r,o){let n=t(s=>Object.defineProperty(e,r,{value:s,enumerable:!0,writable:!0}),"define");return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let s=o();return n(s),s},set(s){n(s)}}),e}t(w,"defineLazyProperty");import{promisify as Ne}from"node:util";import H from"node:process";import{execFile as Ue}from"node:child_process";import{promisify as Fe}from"node:util";import Oe from"node:process";import{execFile as Ie}from"node:child_process";var Te=Fe(Ie);async function T(){if(Oe.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Te("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),o=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return o==="com.apple.safari"?"com.apple.Safari":o}t(T,"defaultBrowserId");import Me from"node:process";import{promisify as We}from"node:util";import{execFile as Le,execFileSync as kr}from"node:child_process";var _e=We(Le);async function re(e,{humanReadableOutput:r=!0,signal:o}={}){if(Me.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],s={};o&&(s.signal=o);let{stdout:a}=await _e("osascript",["-e",e,n],s);return a.trim()}t(re,"runAppleScript");var He=/^[^\n\r"\\]+$/u;async function M(e){if(typeof e!="string")throw new TypeError("Expected a string bundle identifier");if(!He.test(e))throw new TypeError(`Invalid bundle identifier: ${JSON.stringify(e)}`);return re(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
20
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}t(M,"bundleName");import te from"node:process";import{promisify as $e}from"node:util";import{execFile as ke}from"node:child_process";var De=$e(ke),A={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},L=new Map(Object.entries(A)),W=class extends Error{static{t(this,"UnknownBrowserError")}};async function _(e=De){let r=`${te.env.SYSTEMROOT??te.env.windir??"C:\\Windows"}\\System32\\reg.exe`,{stdout:o}=await e(r,["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(o);if(!n)throw new W(`Cannot find Windows browser in stdout: ${JSON.stringify(o)}`);let{id:s}=n.groups,a=s.lastIndexOf("."),u=s.lastIndexOf("-"),x=a===-1?void 0:s.slice(0,a),c=u===-1?void 0:s.slice(0,u);return A[s]??A[x]??A[c]??{name:s,id:s}}t(_,"defaultBrowser");var Re=Ne(Ue),ze=t(e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase()),"titleize");async function $(){if(H.platform==="darwin"){let e=await T();return{name:await M(e),id:e}}if(H.platform==="linux"){let{stdout:e}=await Re("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:ze(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(H.platform==="win32")return _();throw new Error("Only macOS, Linux, and Windows are supported")}t($,"defaultBrowser");import k from"node:process";var Xe=!!(k.env.SSH_CONNECTION||k.env.SSH_CLIENT||k.env.SSH_TTY),oe=Xe;var b=Symbol("fallbackAttempt"),D=import.meta.url?N.dirname(Ge(import.meta.url)):"",ne=N.join(D,"xdg-open"),{platform:h,arch:se}=ce,ie=t(async(e,r)=>{if(e.length===0)return;let o=[];for(let n of e)try{return await r(n)}catch(s){o.push(s)}throw new AggregateError(o,"Failed to open in all supported apps")},"tryEachApp"),S=t(async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let r=e[b]===!0;if(delete e[b],Array.isArray(e.app))return ie(e.app,i=>S({...e,app:i,[b]:!0}));let{name:o,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(o))return ie(o,i=>S({...e,app:{name:i,arguments:n},[b]:!0}));if(o==="browser"||o==="browserPrivate"){let i={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},m={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},f;if(p){let y=await Z();f=L.get(y)??{}}else f=await $();let U=f.id?.toLowerCase();if(Object.hasOwn(i,U)){let y=i[U];if(o==="browserPrivate"){if(y==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(m[y])}return S({...e,app:{name:g[y],arguments:n}})}throw new Error(`${f.name} is not supported as a default browser`)}let s,a=[],u={},x=!1;if(p&&!d()&&!oe&&!o&&(x=await Q()),h==="darwin")s="open",e.wait&&a.push("--wait-apps"),e.background&&a.push("--background"),e.newInstance&&a.push("--new"),o&&a.push("-a",o);else if(h==="win32"||x){s=await v(),a.push(...l.argumentsPrefix),p||(u.windowsVerbatimArguments=!0),p&&e.target&&(e.target=await ee(e.target));let i=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&i.push("-Wait"),o?(i.push(l.escapeArgument(o)),e.target&&n.push(e.target)):e.target&&i.push(l.escapeArgument(e.target)),n.length>0&&(n=n.map(m=>l.escapeArgument(m)),i.push("-ArgumentList",n.join(","))),e.target=l.encodeCommand(i.join(" ")),e.wait||(u.stdio="ignore"),p&&(u.cwd=N.dirname(s))}else{if(o)s=o;else{let i=!D||D==="/",m=!1;try{await Ye.access(ne,Ve.X_OK),m=!0}catch{}s=ce.versions.electron??(h==="android"||i||!m)?"xdg-open":ne}n.length>0&&a.push(...n),e.wait||(u.stdio="ignore",u.detached=!0)}h==="darwin"&&n.length>0&&a.push("--args",...n),e.target&&a.push(e.target);let c=Ke.spawn(s,a,u);return e.wait?new Promise((i,m)=>{c.once("error",m),c.once("close",f=>{if(!e.allowNonzeroExitCode&&f!==0){m(new Error(`Exited with code ${f}`));return}i(c)})}):r||h==="win32"||x?new Promise((i,m)=>{c.once("error",m),c.once("spawn",()=>{c.once("close",f=>{if(c.off("error",m),r&&f!==0){m(new Error(`Exited with code ${f}`));return}c.unref(),i(c)})})}):(c.unref(),new Promise((i,m)=>{c.once("error",m),c.once("spawn",()=>{c.off("error",m),i(c)})}))},"baseOpen"),qe=t((e,r)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return S({...r,target:e})},"open"),gt=t((e,r)=>{if(typeof e!="string"&&!Array.isArray(e))throw new TypeError("Expected a valid `name`");let{arguments:o=[]}=r??{};if(o!=null&&!Array.isArray(o))throw new TypeError("Expected `appArguments` as Array type");return S({...r,app:{name:e,arguments:o}})},"openApp");function ae(e){if(typeof e=="string"||Array.isArray(e))return e;let{[se]:r}=e;if(!r)throw new Error(`${se} is not supported`);return r}t(ae,"detectArchBinary");function P({[h]:e},{wsl:r}={}){if(r&&p)return ae(r);if(!e)throw new Error(`${h} is not supported`);return ae(e)}t(P,"detectPlatformBinary");var g={browser:"browser",browserPrivate:"browserPrivate"};w(g,"chrome",()=>P({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));w(g,"brave",()=>P({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));w(g,"firefox",()=>P({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));w(g,"edge",()=>P({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));w(g,"safari",()=>P({darwin:"Safari"}));var xt=qe;export{gt as a,g as b,xt as c};
|