blink 1.1.19 → 1.1.21
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/dist/browser/agent/client/index.cjs +7 -7
- package/dist/browser/agent/client/index.js +6 -6
- package/dist/cli/{auth-CoJASYGP.js → auth-BilZuH-1.js} +2 -2
- package/dist/cli/{chat-BDAEIrJW.js → chat-CAtArOPl.js} +1 -1
- package/dist/cli/chat-manager-DfVg04yc.js +21 -0
- package/dist/cli/connect-DWScpJzS.js +1 -0
- package/dist/cli/create-slack-app-CyVPwWsG.js +1 -0
- package/dist/cli/{dev-BShY-dVP.js → dev-DRWR8F1H.js} +212 -176
- package/dist/cli/execAsync-Dwktgsum.js +1 -0
- package/dist/cli/execAsync-qNF4iDpO.js +1 -0
- package/dist/cli/{getMachineId-bsd-BQaAhwjO.js → getMachineId-bsd-0cOO_RKK.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Cw8CWhxJ.js → getMachineId-bsd-BDrKPt3B.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DcR5dlLj.js → getMachineId-bsd-BJ3yH7j4.js} +1 -1
- package/dist/{node/getMachineId-bsd-BxqlJcyA.js → cli/getMachineId-bsd-BpxYEV3F.js} +1 -1
- package/dist/cli/getMachineId-bsd-BrJwIGYU.js +1 -0
- package/dist/cli/getMachineId-bsd-C6osJ6-S.js +1 -0
- package/dist/cli/{getMachineId-bsd-CbeuYR7X.js → getMachineId-bsd-CHVQhSq2.js} +1 -1
- package/dist/cli/getMachineId-bsd-DeIJ5F9l.js +1 -0
- package/dist/cli/{getMachineId-darwin-D7CuR-jd.js → getMachineId-darwin-0AdOS_kz.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DJ-H8l7s.js → getMachineId-darwin-BaA8JJgE.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DYCKXuZX.js → getMachineId-darwin-BeAdNwpL.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DyN_uugK.js → getMachineId-darwin-C8-xkmnZ.js} +1 -1
- package/dist/{node/getMachineId-darwin-Bf4P0U5b.js → cli/getMachineId-darwin-CJ2gOzlU.js} +1 -1
- package/dist/cli/getMachineId-darwin-CYvRIQbp.js +2 -0
- package/dist/cli/getMachineId-darwin-DWSKszGZ.js +2 -0
- package/dist/cli/getMachineId-darwin-wYLDmdQt.js +2 -0
- package/dist/cli/getMachineId-linux-D0cDy6Ik.js +1 -0
- package/dist/cli/getMachineId-linux-DgyKUIyK.js +1 -0
- package/dist/cli/getMachineId-linux-DnzutOBC.js +1 -0
- package/dist/cli/getMachineId-linux-nBO1QX9q.js +1 -0
- package/dist/cli/getMachineId-unsupported-DQBLgw4s.js +1 -0
- package/dist/cli/getMachineId-unsupported-DTFeADdG.js +1 -0
- package/dist/cli/getMachineId-unsupported-DgVzHx1H.js +1 -0
- package/dist/cli/getMachineId-unsupported-TE5qi9PD.js +1 -0
- package/dist/cli/{getMachineId-win-BB1s3SWz.js → getMachineId-win-4Psd7Tlr.js} +1 -1
- package/dist/cli/{getMachineId-win-BrQ4d5bO.js → getMachineId-win-BA0Li8oF.js} +1 -1
- package/dist/cli/{getMachineId-win-CgPYGelR.js → getMachineId-win-BvGLfEpq.js} +1 -1
- package/dist/cli/getMachineId-win-BzRwVWue.js +1 -0
- package/dist/cli/{getMachineId-win-B7f9VGFu.js → getMachineId-win-C4wjvjxC.js} +1 -1
- package/dist/cli/getMachineId-win-DXCyELQJ.js +1 -0
- package/dist/cli/getMachineId-win-hHwtD9GX.js +1 -0
- package/dist/cli/getMachineId-win-lhgCxX3y.js +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/cli/init-BuMKmaaZ.js +23 -0
- package/dist/cli/{init-templates-MqyReSD9.js → init-templates-B9PG-9Ei.js} +257 -263
- package/dist/cli/login-Bbj133_1.js +1 -0
- package/dist/cli/{run-DFYLWiOa.js → run-DF1dwAY_.js} +1 -1
- package/dist/cli/setup-slack-app-DagQxNol.js +1 -0
- package/dist/cli/{token-DNRiDJM-.js → token-BdYp2nw_.js} +1 -1
- package/dist/cli/token-util-C9doIH9w.js +1 -0
- package/dist/cli/{token-util-IqDtKhK6.js → token-util-KdD-UX1l.js} +1 -1
- package/dist/cli/undici-Bm_EanIy.js +1 -0
- package/dist/cli/util-CUfifM0g.js +5 -0
- package/dist/cli/util-k3x8m_i5.js +33 -0
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.d.cts +2 -2
- package/dist/node/agent/index.node.d.ts +2 -2
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/build/index.cjs +1 -1
- package/dist/node/build/index.d.cts +1 -1
- package/dist/node/build/index.d.ts +1 -1
- package/dist/node/build/index.js +1 -1
- package/dist/node/{build-D_L0gFGa.js → build-DYI55eX2.js} +1 -1
- package/dist/node/{build-BzoNpizh.cjs → build-EgdtUZTI.cjs} +1 -1
- package/dist/node/execAsync-CY8juV7n.js +1 -0
- package/dist/node/{getMachineId-bsd-C10eVJgT.js → getMachineId-bsd-Ckr9jSoT.js} +1 -1
- package/dist/node/{getMachineId-bsd-B84ixt26.cjs → getMachineId-bsd-O0bNSuuh.cjs} +1 -1
- package/dist/node/{getMachineId-darwin-JB29MQsG.js → getMachineId-darwin-36SFRv2R.js} +1 -1
- package/dist/node/{getMachineId-darwin-Cyng5kFG.cjs → getMachineId-darwin-DivkCgLG.cjs} +1 -1
- package/dist/node/{getMachineId-win-CjJkZMZe.cjs → getMachineId-win-B_okYUv6.cjs} +1 -1
- package/dist/node/{getMachineId-win-C4G-fkEF.js → getMachineId-win-CGqZ4f4O.js} +1 -1
- package/dist/node/{index-DlWgNLmT.d.cts → index-B4OXlWm3.d.ts} +1 -1
- package/dist/node/{index-C28Wm0bG.d.ts → index-DYOqnOdZ.d.cts} +1 -1
- package/dist/node/index.node-Bvp48I1R.cjs +50 -0
- package/dist/node/{index.node-B6plkLLA.d.cts → index.node-CFw4ITad.d.cts} +1 -21
- package/dist/node/{index.node-qJt_7e9E.d.ts → index.node-D5_czyKY.d.ts} +1 -21
- package/dist/node/index.node-ppzOWVGE.js +50 -0
- package/dist/node/react/index.node.cjs +354 -361
- package/dist/node/react/index.node.d.cts +2 -2
- package/dist/node/react/index.node.d.ts +2 -2
- package/dist/node/react/index.node.js +308 -315
- package/dist/node/{token-DOfE6QlD.js → token-CI2_C_5D.js} +1 -1
- package/dist/node/{token-BBGr-czK.cjs → token-D4jFpAk0.cjs} +1 -1
- package/dist/node/token-util-BENsR1Bn.cjs +1 -0
- package/dist/node/{token-util-C_uzN2q9.js → token-util-idU3T5iM.js} +1 -1
- package/package.json +20 -1
- package/dist/cli/chat-manager-BRchJngj.js +0 -21
- package/dist/cli/connect-WyCmuQHj.js +0 -1
- package/dist/cli/create-slack-app-CNDXDwfs.js +0 -1
- package/dist/cli/init-DoMgv4kU.js +0 -25
- package/dist/cli/login-DZFx5155.js +0 -1
- package/dist/cli/setup-slack-app-DQ3iSM5s.js +0 -1
- package/dist/cli/token-util-C6Xu44iO.js +0 -1
- package/dist/cli/undici-L5V8WBce.js +0 -1
- package/dist/cli/util-BQ3TH_Sv.js +0 -33
- package/dist/cli/util-BgbIWOFE.js +0 -6
- package/dist/node/execAsync-pJEPzmP4.cjs +0 -1
- package/dist/node/getMachineId-bsd-BudRe7J9.cjs +0 -1
- package/dist/node/getMachineId-darwin-ZVi3EKE3.cjs +0 -2
- package/dist/node/getMachineId-linux-CJXPQ8U5.cjs +0 -1
- package/dist/node/getMachineId-linux-CmMSYp7C.js +0 -1
- package/dist/node/getMachineId-unsupported-DM7fz1pP.cjs +0 -1
- package/dist/node/getMachineId-unsupported-Dtt3HTNZ.js +0 -1
- package/dist/node/getMachineId-win-D1szVnqR.js +0 -1
- package/dist/node/getMachineId-win-DDz2FyEp.cjs +0 -1
- package/dist/node/index.node-D7Cvmag9.cjs +0 -55
- package/dist/node/index.node-TFdiI8lm.js +0 -55
- package/dist/node/token-util-D9kCwzE6.cjs +0 -1
- /package/dist/cli/{connect-CQUVd44y.js → connect-BCK40kvG.js} +0 -0
- /package/dist/cli/{devtools-DvNholmW.js → devtools-DsAYEmyP.js} +0 -0
- /package/dist/cli/{execAsync-Bhq3YKvl.js → execAsync-BOPj9Mml.js} +0 -0
- /package/dist/cli/{execAsync-BnYBiViJ.js → execAsync-Bv4jTnD3.js} +0 -0
- /package/dist/cli/{execAsync-Djebuxfm.js → execAsync-CyP3Ojec.js} +0 -0
- /package/dist/cli/{execAsync-_tP2SNTy.js → execAsync-DHh3DKKp.js} +0 -0
- /package/dist/{node/execAsync-DzxhVi7q.js → cli/execAsync-DdLzES9n.js} +0 -0
- /package/dist/{node/execAsync-epR2wT1r.js → cli/execAsync-Dv6XOE2I.js} +0 -0
- /package/dist/cli/{getMachineId-linux-BCOAWAJr.js → getMachineId-linux-BQISLgy5.js} +0 -0
- /package/dist/cli/{getMachineId-linux-CBDQri3D.js → getMachineId-linux-Bg5YnekM.js} +0 -0
- /package/dist/cli/{getMachineId-linux-EqaaEzYC.js → getMachineId-linux-Boq-GGfA.js} +0 -0
- /package/dist/cli/{getMachineId-linux-QFNGh16E.js → getMachineId-linux-C9BHlxRm.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-BLalsIU8.js → getMachineId-unsupported-4qhSqb7w.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CNgpP2gn.js → getMachineId-unsupported-BsEK_LG9.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CQrnjCuH.js → getMachineId-unsupported-C6cVb167.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CcRcqdy3.js → getMachineId-unsupported-CqJy0sqq.js} +0 -0
- /package/dist/cli/{token-error-DVSfBVaT.js → token-error-COQY18OP.js} +0 -0
- /package/dist/cli/{undici-BUZTy5qm.js → undici-CRntNDHY.js} +0 -0
- /package/dist/node/{execAsync-C9Unrkco.cjs → execAsync-BMxJf0Eg.cjs} +0 -0
- /package/dist/node/{getMachineId-linux-B-CtXK0L.cjs → getMachineId-linux-C8A0ak4z.cjs} +0 -0
- /package/dist/node/{getMachineId-linux-BPnkHJah.js → getMachineId-linux-ZoT5w75D.js} +0 -0
- /package/dist/node/{getMachineId-unsupported--0R36RP6.cjs → getMachineId-unsupported-DSRCXJha.cjs} +0 -0
- /package/dist/node/{getMachineId-unsupported-C_4fnT4Z.js → getMachineId-unsupported-XVp8oFCM.js} +0 -0
- /package/dist/node/{token-util-BOoyY0PX.cjs → token-util-BxSJFXkT.cjs} +0 -0
- /package/dist/node/{token-util-_pz5CtFI.js → token-util-ChGcRyiF.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e}from"./chunk-D9KrCrVq.js";import{require_token_error as t}from"./token-error-488npYdU.js";import{require_token_util as n}from"./token-util-
|
|
1
|
+
import{__commonJSMin as e}from"./chunk-D9KrCrVq.js";import{require_token_error as t}from"./token-error-488npYdU.js";import{require_token_util as n}from"./token-util-ChGcRyiF.js";var r=e(((e,r)=>{var i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of o(t))!s.call(e,c)&&c!==n&&i(e,c,{get:()=>t[c],enumerable:!(r=a(t,c))||r.enumerable});return e},u=e=>l(i({},`__esModule`,{value:!0}),e),d={};c(d,{refreshToken:()=>m}),r.exports=u(d);var f=t(),p=n();async function m(){let{projectId:e,teamId:t}=(0,p.findProjectInfo)(),n=(0,p.loadToken)(e);if(!n||(0,p.isExpired)((0,p.getTokenPayload)(n.token))){let r=(0,p.getVercelCliToken)();if(!r)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token: login to vercel cli`);if(!e)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token: project id not found`);if(n=await(0,p.getVercelOidcToken)(r,e,t),!n)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token`);(0,p.saveToken)(n,e)}process.env.VERCEL_OIDC_TOKEN=n.token}}));export default r();export{};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`./chunk-iXuH7AlR.cjs`),t=require(`./token-error-BoNG8ooW.cjs`),n=require(`./token-util-
|
|
1
|
+
const e=require(`./chunk-iXuH7AlR.cjs`),t=require(`./token-error-BoNG8ooW.cjs`),n=require(`./token-util-BxSJFXkT.cjs`);var r=e.__commonJSMin(((e,r)=>{var i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of o(t))!s.call(e,c)&&c!==n&&i(e,c,{get:()=>t[c],enumerable:!(r=a(t,c))||r.enumerable});return e},u=e=>l(i({},`__esModule`,{value:!0}),e),d={};c(d,{refreshToken:()=>m}),r.exports=u(d);var f=t.require_token_error(),p=n.require_token_util();async function m(){let{projectId:e,teamId:t}=(0,p.findProjectInfo)(),n=(0,p.loadToken)(e);if(!n||(0,p.isExpired)((0,p.getTokenPayload)(n.token))){let r=(0,p.getVercelCliToken)();if(!r)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token: login to vercel cli`);if(!e)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token: project id not found`);if(n=await(0,p.getVercelOidcToken)(r,e,t),!n)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token`);(0,p.saveToken)(n,e)}process.env.VERCEL_OIDC_TOKEN=n.token}}));Object.defineProperty(exports,`default`,{enumerable:!0,get:function(){return r()}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
require(`./token-error-BoNG8ooW.cjs`);const e=require(`./token-util-BxSJFXkT.cjs`);Object.defineProperty(exports,`default`,{enumerable:!0,get:function(){return e.require_token_util()}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./token-error-488npYdU.js";import{require_token_util as e}from"./token-util-
|
|
1
|
+
import"./token-error-488npYdU.js";import{require_token_util as e}from"./token-util-ChGcRyiF.js";export default e();export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blink",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.21",
|
|
4
4
|
"description": "Blink is a tool for building and deploying AI agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -78,19 +78,36 @@
|
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
80
|
"@ai-sdk/anthropic": "^2.0.15",
|
|
81
|
+
"@ai-sdk/gateway": "^2.0.0",
|
|
81
82
|
"@ai-sdk/google": "^2.0.13",
|
|
82
83
|
"@ai-sdk/openai": "^2.0.28",
|
|
83
84
|
"@ai-sdk/openai-compatible": "^1.0.19",
|
|
84
85
|
"@ai-sdk/react": "^2.0.35",
|
|
85
86
|
"@ai-sdk/xai": "^2.0.16",
|
|
87
|
+
"@blink-sdk/compute": "^0.0.15",
|
|
88
|
+
"@blink-sdk/events": "workspace:*",
|
|
86
89
|
"@blink.so/api": "^1.0.0",
|
|
87
90
|
"@clack/prompts": "^0.11.0",
|
|
88
91
|
"@hono/node-server": "^1.19.3",
|
|
89
92
|
"@hugodutka/gemini-cli": "npm:@kylecarbs/gemini-cli@0.6.0-nightly-20250912-6",
|
|
93
|
+
"@lydell/node-pty": "^1.1.0",
|
|
94
|
+
"@opentelemetry/api": "^1.9.0",
|
|
90
95
|
"@opentelemetry/auto-instrumentations-node": "^0.64.6",
|
|
96
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.206.0",
|
|
97
|
+
"@opentelemetry/instrumentation": "^0.206.0",
|
|
98
|
+
"@opentelemetry/instrumentation-undici": "^0.17.0",
|
|
99
|
+
"@opentelemetry/resources": "^2.1.0",
|
|
100
|
+
"@opentelemetry/sdk-trace-base": "^2.1.0",
|
|
101
|
+
"@opentelemetry/sdk-trace-node": "^2.1.0",
|
|
102
|
+
"@opentelemetry/semantic-conventions": "^1.37.0",
|
|
91
103
|
"@types/marked-terminal": "^6.1.1",
|
|
104
|
+
"@types/react": "^19.2.2",
|
|
105
|
+
"@types/ws": "^8.18.1",
|
|
92
106
|
"@whatwg-node/server": "^0.10.12",
|
|
107
|
+
"@xterm/headless": "^5.5.0",
|
|
108
|
+
"chalk": "^5.6.2",
|
|
93
109
|
"commander": "^14.0.0",
|
|
110
|
+
"dotenv": "^17.2.3",
|
|
94
111
|
"emittery": "^1.2.0",
|
|
95
112
|
"eventsource-parser": "^3.0.6",
|
|
96
113
|
"filenamify": "^7.0.0",
|
|
@@ -100,6 +117,7 @@
|
|
|
100
117
|
"ink": "^6.2.3",
|
|
101
118
|
"ink-spinner": "^5.0.0",
|
|
102
119
|
"ink-text-input": "^6.0.0",
|
|
120
|
+
"json-stable-stringify": "^1.3.0",
|
|
103
121
|
"marked": "^16.2.1",
|
|
104
122
|
"marked-terminal": "^7.3.0",
|
|
105
123
|
"open": "^10.2.0",
|
|
@@ -108,6 +126,7 @@
|
|
|
108
126
|
"sonda": "^0.9.0",
|
|
109
127
|
"tsdown": "0.14.2",
|
|
110
128
|
"uuid": "^13.0.0",
|
|
129
|
+
"ws": "^8.18.3",
|
|
111
130
|
"xdg-app-paths": "^8.3.0"
|
|
112
131
|
},
|
|
113
132
|
"optionalDependencies": {
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import*as e from"node:path";import*as t from"node:fs";import n,{z as r}from"zod/v4";import"zod/v3";import{convertToModelMessages as i,createUIMessageStream as a,getToolName as o,isToolOrDynamicToolUIPart as s,isToolUIPart as c,readUIMessageStream as l,streamText as u}from"ai";const d=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`);function f(e){return e?.then!=null}function p(e){let t=e;return t&&t.then&&t.catch&&t.finally}function m(e,t,n,r){let i=h().then(e).then(t,n);return r&&(i=i.finally(r)),S(i)}function h(e){return e&&p(e)?e:f(e)?{then:(t,n)=>h(e.then(t,n)),catch:t=>h(e.then(e=>e,t)),finally:t=>h(t?x(e,t):e),[Symbol.toStringTag]:`Promise`}:{then(t){if(t)try{return h(t(e))}catch(e){return v(e)}return this},catch(){return this},finally(t){if(t)try{return h(t()).then(()=>e,()=>e)}catch(e){return v(e)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:e,[d]:`resolved`}}function g(){if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise(function(n,r){e=n,t=r}),get resolve(){return e},get reject(){return t}}}function _(e,t,n){if(e?.length===0)return;let r=e[Symbol.iterator](),i=0;function a(){let{done:e,value:o}=r.next();if(e)return;let s=!1;function c(){s=!0}return m(function(){return t(o,c,i++)},function(e){if(e&&n?.push(e),!s)return a()})}return a()}function v(e){return{then(t,n){if(n)try{return h(n(e))}catch(e){return v(e)}return this},catch(t){if(t)try{return h(t(e))}catch(e){return v(e)}return this},finally(e){if(e)try{e()}catch(e){return v(e)}return this},__fakeRejectError:e,[Symbol.toStringTag]:`Promise`,[d]:`rejected`}}function y(e){return e?.[d]===`resolved`}function b(e){return e?.[d]===`rejected`}function x(e,t){return`finally`in e?e.finally(t):e.then(e=>{let n=t();return f(n)?n.then(()=>e):e},e=>{let n=t();if(f(n))return n.then(()=>{throw e});throw e})}function S(e){if(y(e))return e.__fakePromiseValue;if(b(e))throw e.__fakeRejectError;return e}function C(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function w(e){return e.socket?.localPort?e.socket?.localPort:(e.headers?.[`:authority`]||e.headers?.host)?.split(`:`)?.[1]||80}function ee(e){if(e.headers?.[`:authority`])return e.headers?.[`:authority`];if(e.headers?.host)return e.headers?.host;let t=w(e);if(e.hostname)return e.hostname+`:`+t;let n=e.socket?.localAddress;return n&&!n?.includes(`::`)&&!n?.includes(`ffff`)?`${n}:${t}`:`localhost`}function te(e){let t=ee(e),n=e.protocol||(e.socket?.encrypted?`https`:`http`),r=e.originalUrl||e.url||`/graphql`;return`${n}://${t}${r}`}function ne(e){let t=e[Symbol.toStringTag];return!!(typeof e==`string`||t===`Uint8Array`||t===`Blob`||t===`FormData`||t===`URLSearchParams`||C(e))}function re(e,t,n,r){let i=e.raw||e.req||e,a=te(i);if(e.query){let n=new t.URL(a);for(let t in e.query)n.searchParams.set(t,e.query[t]);a=n.toString()}let o=e.headers;if(e.headers?.[`:method`])for(let t in o={},e.headers)t.startsWith(`:`)||(o[t]=e.headers[t]);let s=r?Ce():new AbortController;if(n?.once){let e=()=>{s.signal.aborted||(Object.defineProperty(i,`aborted`,{value:!0}),s.abort(n.errored??void 0))};n.once(`error`,e),n.once(`close`,e),n.once(`finish`,()=>{n.removeListener(`close`,e)})}if(e.method===`GET`||e.method===`HEAD`)return new t.Request(a,{method:e.method,headers:o,signal:s.signal});let c=e.body;if(c!=null&&Object.keys(c).length>0){if(ne(c))return new t.Request(a,{method:e.method||`GET`,headers:o,body:c,signal:s.signal});let n=new t.Request(a,{method:e.method||`GET`,headers:o,signal:s.signal});return n.headers.get(`content-type`)?.includes(`json`)||n.headers.set(`content-type`,`application/json; charset=utf-8`),new Proxy(n,{get:(e,t,n)=>{switch(t){case`json`:return()=>h(c);case`text`:return()=>h(JSON.stringify(c));default:return globalThis.Bun?Reflect.get(e,t):Reflect.get(e,t,n)}}})}return new t.Request(a,{method:e.method,headers:o,signal:s.signal,body:i,duplex:`half`})}function ie(e){return e.read!=null}function ae(e){return ie(e)}function oe(e){return e!=null&&e.setHeader!=null&&e.end!=null&&e.once!=null&&e.write!=null}function se(e){return e!=null&&e.getReader!=null}function ce(e){return e!=null&&e.request!=null&&e.respondWith!=null}function le(e){e?.socket?.setTimeout?.(0),e?.socket?.setNoDelay?.(!0),e?.socket?.setKeepAlive?.(!0)}function T(e){e.end(null,null,null)}function ue(e,t){let n=!1,r=()=>{n=!0};e.once(`error`,r),e.once(`close`,r),e.once(`finish`,()=>{e.removeListener(`close`,r),e.removeListener(`error`,r)});let i=t[Symbol.asyncIterator](),a=()=>i.next().then(({done:t,value:r})=>{if(!(n||t))return m(()=>E(r,e),()=>n?T(e):a())});return a()}function E(e,t){if(!t.write(e))return new Promise(e=>t.once(`drain`,e))}function de(e,t,n,r){if(t.closed||t.destroyed||t.writableEnded)return;if(!e){t.statusCode=404,T(t);return}if(r&&e.headers?.headersInit&&!Array.isArray(e.headers.headersInit)&&!e.headers.headersInit.get&&!e.headers._map&&!e.headers._setCookies?.length)t.writeHead(e.status,e.statusText,e.headers.headersInit);else{if(t.setHeaders)t.setHeaders(e.headers);else{let n=!1;e.headers.forEach((r,i)=>{if(i===`set-cookie`){if(n)return;n=!0;let r=e.headers.getSetCookie?.();if(r){t.setHeader(`set-cookie`,r);return}}t.setHeader(i,r)})}t.writeHead(e.status,e.statusText)}if(e.bodyType===`String`)return m(()=>E(e.bodyInit,t),()=>T(t));let i=e._buffer;if(i)return m(()=>E(i,t),()=>T(t));let a=e.body;if(a==null){T(t);return}if(a[Symbol.toStringTag]===`Uint8Array`)return m(()=>E(a,t),()=>T(t));if(le(n),ie(a)){t.once(`close`,()=>{a.destroy()}),a.pipe(t,{end:!0});return}if(se(a))return fe(n,t,a);if(C(a))return ue(t,a)}function fe(e,t,n){let r=n.getReader();e?.once?.(`error`,e=>{r.cancel(e)});function i(){return r.read().then(({done:e,value:n})=>e?T(t):m(()=>E(n,t),i))}return i()}function pe(e){return typeof e==`object`&&!!e&&(`body`in e||`cache`in e||`credentials`in e||`headers`in e||`integrity`in e||`keepalive`in e||`method`in e||`mode`in e||`redirect`in e||`referrer`in e||`referrerPolicy`in e||`signal`in e||`window`in e)}function me(...e){let[t,...n]=e.filter(e=>typeof e==`object`&&!!e);return n.forEach(e=>{let n=Object.getOwnPropertyNames(e).reduce((t,n)=>(Object.getOwnPropertyDescriptor(e,n)&&(t[n]=Object.getOwnPropertyDescriptor(e,n)),t),{});Object.getOwnPropertySymbols(e).forEach(t=>{let r=Object.getOwnPropertyDescriptor(e,t);r?.enumerable&&(n[t]=r)}),Object.defineProperties(t,n)}),t}function he(e,t){return new t(e.stack||e.message||e.toString(),{status:e.status||500})}function ge(e,t){return e==null?t==null?{}:{waitUntil:t}:me(Object.create(e),{waitUntil:t},e)}function _e(e,t){if(t?.aborted)throw t.reason;if(f(e)&&t){let n=g();function r(){n.reject(t.reason)}return t.addEventListener(`abort`,r,{once:!0}),e.then(function(e){n.resolve(e)}).catch(function(e){n.reject(e)}).finally(()=>{t.removeEventListener(`abort`,r)}),n.promise}return e}const ve=[`SIGINT`,`exit`,`SIGTERM`],D=new Set;let ye=!1;function be(){if(!ye){ye=!0;for(let e of ve)globalThis.process.once(e,function(){return Promise.allSettled([...D].map(e=>!e.disposed&&e.disposeAsync()))})}}function xe(e){globalThis.process&&(be(),D.has(e)||(D.add(e),e.defer(()=>{D.delete(e)})))}var Se=class extends EventTarget{aborted=!1;_onabort=null;_reason;constructor(){super();let e=globalThis.process?.getBuiltinModule?.(`node:events`);e?.kMaxEventTargetListeners&&(this[e.kMaxEventTargetListeners]=0)}throwIfAborted(){if(this._nativeCtrl?.signal?.throwIfAborted)return this._nativeCtrl.signal.throwIfAborted();if(this.aborted)throw this._reason}_nativeCtrl;ensureNativeCtrl(){if(!this._nativeCtrl){let e=this.aborted;this._nativeCtrl=new AbortController,e&&this._nativeCtrl.abort(this._reason)}return this._nativeCtrl}abort(e){if(this._nativeCtrl?.abort)return this._nativeCtrl?.abort(e);this._reason=e||new DOMException(`This operation was aborted`,`AbortError`),this.aborted=!0,this.dispatchEvent(new Event(`abort`))}get signal(){return this._nativeCtrl?.signal?this._nativeCtrl.signal:this}get reason(){return this._nativeCtrl?.signal?this._nativeCtrl.signal.reason:this._reason}get onabort(){return this._onabort,this._onabort}set onabort(e){if(this._nativeCtrl?.signal){this._nativeCtrl.signal.onabort=e;return}this._onabort&&this.removeEventListener(`abort`,this._onabort),this._onabort=e,e&&this.addEventListener(`abort`,e)}};function Ce(){return globalThis.Bun||globalThis.Deno?new AbortController:new Proxy(new Se,{get(e,t,n){if(t.toString().includes(`kDependantSignals`)){let n=e.ensureNativeCtrl();return Reflect.get(n.signal,t,n.signal)}return Reflect.get(e,t,n)},set(e,t,n,r){if(t.toString().includes(`kDependantSignals`)){let r=e.ensureNativeCtrl();return Reflect.set(r.signal,t,n,r.signal)}return Reflect.set(e,t,n,r)},getPrototypeOf(){return AbortSignal.prototype}})}var we=class extends Error{constructor(e,t){super(e),this.response=t}};const Te=Object.freeze({withContext(e,t){let n={};for(let r of Object.keys(e))n[r]=e[r].withContext(t);return n},with(e,t){let n={};for(let r of Object.keys(e))n[r]=e[r].withContext(t);return n},async withApproval(e){let t={};for(let[n,r]of Object.entries(e.tools)){let e=r.execute;t[n]={...r,execute:async(t,n)=>r.autoApprove&&e&&await r.autoApprove(t)?e(t,n):{type:`tool-approval`,outcome:`pending`}}}let n=e.messages[e.messages.length-1];if(!n?.parts)return t;let r=[];for(let t of n.parts){if(!c(t))continue;let n=o(t),i=e.tools[n];i&&t.state===`output-available`&&i.execute&&Ee(t.output)&&t.output.outcome===`approved`&&r.push({toolName:o(t),tool:i,input:t.input,toolCallId:t.toolCallId})}if(r.length>0){let t=a({execute:async({writer:t})=>{t.write({type:`start-step`}),await Promise.all(r.map(async n=>{if(!n.tool.execute)throw Error(`Tool does not support execute.`);t.write({type:`tool-input-available`,toolCallId:n.toolCallId,toolName:n.toolName,input:n.input});try{let r=await n.tool.execute(n.input,{toolCallId:n.toolCallId,messages:i(e.messages,{tools:e.tools}),abortSignal:e.abortSignal}),a=r;if(C(r))for await(let e of r)a=e,t.write({type:`tool-output-available`,toolCallId:n.toolCallId,output:e,preliminary:!0});t.write({type:`tool-output-available`,toolCallId:n.toolCallId,output:a})}catch(e){t.write({type:`tool-output-error`,toolCallId:n.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),t.write({type:`finish`})}});throw new we(`Executing tools`,t)}return t},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}});function Ee(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}var De=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},Oe=e=>{let{groups:t,path:n}=ke(e),r=De(n);return Ae(r,t)},ke=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},Ae=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},je={},Me=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return je[r]||(n[2]?je[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:je[r]=[e,n[1],!0]),je[r]}return null},Ne=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Pe=e=>Ne(e,decodeURI),Fe=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return Pe(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},Ie=e=>{let t=Fe(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},Le=(e,t,...n)=>(n.length&&(t=Le(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),Re=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},ze=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:Ne(e,Ue)):e,Be=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return ze(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=ze(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=ze(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},Ve=Be,He=(e,t)=>Be(e,t,!0),Ue=decodeURIComponent,We=/^[\w!#$%&'*.^`|~+-]+$/,Ge=/^[ !#-:<-[\]-~]*$/,Ke=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!We.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),Ge.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:Ne(a,Ue),t))break}return r},qe=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},Je=(e,t,n)=>(t=encodeURIComponent(t),qe(e,t,n));function Ye(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Xe(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ze=/^\.+(\\|\/)|^\.+$/,Qe=/[. ]+$/,$e=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,et=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,tt=e=>e===``,nt=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,rt=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let it;function at(){return it??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),it}function ot(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ye().test(n)||[...n].some(e=>et.test(e)&&!tt(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(rt,` `),n.length>0&&(e=e.replaceAll(nt,`$1`)),e=e.replace(Qe,``),e=e.replace(Ze,n),e=e.replace(Ye(),n),e=e.replaceAll($e,e=>tt(e)?e:n),e.length===0&&(e=n),e=Xe().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=st(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=st(n,a)+i}}return e}function st(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of at().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function ct(e){return`${e}.lock`}function lt(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function ut(e,n={}){let r=ct(e),i=process.pid.toString();try{return t.writeFileSync(r,i,{flag:`wx`}),!0}catch(i){if(i.code!==`EEXIST`)throw i;if(n.stale===0)return!1;let a;try{a=parseInt(t.readFileSync(r,`utf8`),10)}catch{return t.unlinkSync(r),ut(e,{...n,stale:0})}if(!lt(a))try{return t.unlinkSync(r),ut(e,{...n,stale:0})}catch(t){if(t.code===`ENOENT`)return ut(e,{...n,stale:0});throw t}return!1}}async function dt(t,n={}){let r={stale:!0,retries:0,retryInterval:100,...n},i=e.resolve(t),a=0;for(;a<=r.retries;){if(ut(i,r))return()=>ft(i);a<r.retries&&await new Promise(e=>setTimeout(e,r.retryInterval)),a++}let o=Error(`Lock file is already being held`);throw o.code=`ELOCKED`,o.file=i,o}function ft(n){let r=e.resolve(n),i=ct(r);try{if(parseInt(t.readFileSync(i,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}t.unlinkSync(i)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function pt(n){let r=e.resolve(n),i=ct(r);try{if(!t.existsSync(i))return{locked:!1};let e=t.readFileSync(i,`utf8`),n=parseInt(e,10);return lt(n)?{locked:!0,pid:n}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const mt=e=>{t.mkdirSync(e,{recursive:!0})},ht=e=>{try{t.fdatasyncSync(e)}catch{}try{t.closeSync(e)}catch{}},gt=e=>{try{let n=t.openSync(e,`r`);try{t.fsyncSync(n)}finally{t.closeSync(n)}}catch{}},_t=(n,r)=>{let i=e.dirname(n);mt(i);let a=e.join(i,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),o;try{o=t.openSync(a,`w`),t.writeFileSync(o,r,`utf-8`),ht(o),o=void 0,t.renameSync(a,n),gt(n),gt(i)}catch(e){if(o!==void 0)try{t.closeSync(o)}catch{}try{t.rmSync(a,{force:!0})}catch{}throw e}},vt=(n,r)=>{let i=new Map,a,o=e=>{if(t.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(t.readFileSync(e,`utf-8`))},s=(e,t)=>{_t(e,JSON.stringify(t,null,2))},c=async()=>{if(a)throw Error(`Index is already locked`);let r=e.join(n,`index.json`);mt(n),t.existsSync(r)||t.writeFileSync(r,JSON.stringify({ids:{}}),`utf-8`);let i=await dt(r,{stale:!0,retries:5,retryInterval:100});return a=()=>Promise.resolve(i()),()=>{i(),a=void 0}},l=async()=>{let t=e.join(n,`index.json`),r=o(t)??{ids:{}};return r.ids||={},r},u=async t=>{let r=e.join(n,`index.json`);s(r,t)},d=async t=>{let r=(await l()).ids[t];if(r)return e.join(n,r)},f=async r=>{let i=(await l()).ids[r];if(!i)return;let a=e.join(n,i);if(t.statSync(a,{throwIfNoEntry:!1}))return JSON.parse(t.readFileSync(a,`utf-8`))},p=async t=>{let i=t[r],a=String(i),o=ot(a,{replacement:`_`})+`.json`,d=await c();try{let r=await l();r.ids[a]=o,r.current=a;let i=e.join(n,o);s(i,t),await u(r)}finally{await d()}};return{async get(e){return await f(e)},async list(){if(!t.statSync(n,{throwIfNoEntry:!1}))return[];let r=await l(),i=[];for(let[a,o]of Object.entries(r.ids)){let r=e.join(n,o),s=t.statSync(r,{throwIfNoEntry:!1});if(!s)continue;let c=pt(r);i.push({key:a,locked:c.locked,pid:c.pid,mtime:s.mtimeMs})}return i.sort((e,t)=>t.mtime-e.mtime),i},async lock(a,o){if(i.has(a))throw Error(`Key "${a}" is already locked in this process`);let s=await d(a);if(!s){let r=ot(a,{replacement:`_`})+`.json`,i=await c();try{let i=await l();i.ids[a]=r;let o=e.join(n,r);mt(n),t.writeFileSync(o,JSON.stringify({}),`utf-8`),await u(i),s=o}finally{await i()}}if(o?.force){let e=pt(s);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let m=await dt(s,{stale:!0,retries:o?.force?10:5,retryInterval:(o?.force,100)});return i.set(a,()=>Promise.resolve(m())),{async get(){let e=await f(a);if(!e)throw Error(`Key ${a} not found`);return e},async set(e){await p(e)},async update(e){let t=await f(a);if(!t||!(r in t))throw Error(`Key ${a} not found`);await p({...t,...e})},async delete(){let r=await c();try{let r=await l(),i=r.ids[a];if(i){delete r.ids[a],r.current===a&&(r.current=void 0),await u(r);let o=e.join(n,i);try{t.rmSync(o,{force:!0}),gt(n)}catch{}}}finally{await r()}},async release(){try{m()}finally{i.delete(a)}}}},dispose(){i.clear()}}},yt=(n,r)=>{let i=r?.pollInterval??200,a=r?.debounce??50,o=new Set,s,c,l=new Map,u=new Map,d=e.join(n,`index.json`),f=()=>{try{if(!t.statSync(d,{throwIfNoEntry:!1}))return{ids:{}};let e=t.readFileSync(d,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},p=(e,t,n,r)=>{for(let i of o)try{i({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},m=(r,i,a=!1)=>{let o=e.join(n,i);try{let e=t.statSync(o,{throwIfNoEntry:!1}),n=u.get(i);if(!e){n&&(u.delete(i),p(r,void 0,!1));return}let s=e.mtimeMs,c=n?{locked:n.locked,pid:n.pid}:{locked:!1,pid:void 0};if((a||!n)&&(c=pt(o)),!n||n.mtime!==s||n.locked!==c.locked||n.pid!==c.pid){let e;e=!n||n.mtime!==s?JSON.parse(t.readFileSync(o,`utf-8`)):n.cachedValue,u.set(i,{mtime:s,key:r,locked:c.locked,pid:c.pid,cachedValue:e}),p(r,e,c.locked,c.pid)}}catch{}},h=()=>{try{let e=f(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))m(t,n,!0);for(let[e,n]of u.entries())t.has(n.key)||(u.delete(e),p(n.key,void 0,!1))}catch{}},g=(e,t,n=!1)=>{let r=l.get(e);r&&clearTimeout(r),l.set(e,setTimeout(()=>{l.delete(e),m(e,t,n)},a))},_=()=>{if(s)return;try{t.mkdirSync(n,{recursive:!0})}catch{}s=t.watch(n,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){h();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=f(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&m(r,e,!0);return}let n=f(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&g(r,t,!1)});let e=()=>{h(),c=setTimeout(e,i)};h(),c=setTimeout(e,i)};return{onChange(e){return o.size===0&&_(),o.add(e),()=>{if(o.delete(e),o.size===0){s&&=(s.close(),void 0),c&&=(clearTimeout(c),void 0);for(let e of l.values())clearTimeout(e);l.clear(),u.clear()}}},dispose(){s&&=(s.close(),void 0),c&&=(clearTimeout(c),void 0);for(let e of l.values())clearTimeout(e);l.clear(),o.clear(),u.clear()}}};var bt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function xt(e){}function St(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=xt,onError:n=xt,onRetry:r=xt,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ct(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
2
|
-
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new bt(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new bt(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
3
|
-
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Ct(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
4
|
-
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
5
|
-
`&&r++}}return[t,n]}var wt=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=St({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},Tt=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Et=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},Dt=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t},Ot=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},kt=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function At(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jt(e,t){if(!At(e)&&!At(t))return t;let n={...e};for(let e in t){let r=t[e];At(n[e])&&At(r)?n[e]=jt(n[e],r):n[e]=r}return n}var Mt=(e,t)=>new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return Mt(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}}),Nt=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=Dt(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Je(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=kt(a),a=Et(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},Pt=(e,t)=>Mt(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=Tt(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Et(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+Dt(r.args[0].query).toString())),e=kt(e),new URL(e)}if(o===`ws`){let e=Ot(r.args[0]&&r.args[0].param?Et(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;return i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)}),((...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e))(n.toString())}let l=new Nt(c,o);if(o){t??={};let e=jt(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]),Ft=`vercel.ai.error`,It=Symbol.for(Ft),Lt,Rt=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Lt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ft)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Lt=It;var O=Rt,zt=`AI_APICallError`,Bt=`vercel.ai.error.${zt}`,Vt=Symbol.for(Bt),Ht,k=class extends O{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:zt,message:e,cause:o}),this[Ht]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return O.hasMarker(e,Bt)}};Ht=Vt;var Ut=`AI_EmptyResponseBodyError`,Wt=`vercel.ai.error.${Ut}`,Gt=Symbol.for(Wt),Kt,qt=class extends O{constructor({message:e=`Empty response body`}={}){super({name:Ut,message:e}),this[Kt]=!0}static isInstance(e){return O.hasMarker(e,Wt)}};Kt=Gt;function Jt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Yt=`AI_InvalidArgumentError`,Xt=`vercel.ai.error.${Yt}`,Zt=Symbol.for(Xt),Qt,$t=class extends O{constructor({message:e,cause:t,argument:n}){super({name:Yt,message:e,cause:t}),this[Qt]=!0,this.argument=n}static isInstance(e){return O.hasMarker(e,Xt)}};Qt=Zt;var en=`AI_InvalidPromptError`,tn=`vercel.ai.error.${en}`,nn=Symbol.for(tn),rn,an=class extends O{constructor({prompt:e,message:t,cause:n}){super({name:en,message:`Invalid prompt: ${t}`,cause:n}),this[rn]=!0,this.prompt=e}static isInstance(e){return O.hasMarker(e,tn)}};rn=nn;var on=`AI_InvalidResponseDataError`,sn=`vercel.ai.error.${on}`,cn=Symbol.for(sn),ln,un=class extends O{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:on,message:t}),this[ln]=!0,this.data=e}static isInstance(e){return O.hasMarker(e,sn)}};ln=cn;var dn=`AI_JSONParseError`,fn=`vercel.ai.error.${dn}`,pn=Symbol.for(fn),mn,hn=class extends O{constructor({text:e,cause:t}){super({name:dn,message:`JSON parsing failed: Text: ${e}.
|
|
6
|
-
Error message: ${Jt(t)}`,cause:t}),this[mn]=!0,this.text=e}static isInstance(e){return O.hasMarker(e,fn)}};mn=pn;var gn=`AI_LoadAPIKeyError`,_n=`vercel.ai.error.${gn}`,vn=Symbol.for(_n),yn,A=class extends O{constructor({message:e}){super({name:gn,message:e}),this[yn]=!0}static isInstance(e){return O.hasMarker(e,_n)}};yn=vn;var bn=`AI_NoSuchModelError`,xn=`vercel.ai.error.${bn}`,Sn=Symbol.for(xn),Cn,j=class extends O{constructor({errorName:e=bn,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[Cn]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return O.hasMarker(e,xn)}};Cn=Sn;var wn=`AI_TooManyEmbeddingValuesForCallError`,Tn=`vercel.ai.error.${wn}`,En=Symbol.for(Tn),Dn,On=class extends O{constructor(e){super({name:wn,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Dn]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return O.hasMarker(e,Tn)}};Dn=En;var kn=`AI_TypeValidationError`,An=`vercel.ai.error.${kn}`,jn=Symbol.for(An),Mn,Nn=class e extends O{constructor({value:e,cause:t}){super({name:kn,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
7
|
-
Error message: ${Jt(t)}`,cause:t}),this[Mn]=!0,this.value=e}static isInstance(e){return O.hasMarker(e,An)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Mn=jn;var M=Nn,Pn=`AI_UnsupportedFunctionalityError`,Fn=`vercel.ai.error.${Pn}`,In=Symbol.for(Fn),Ln,N=class extends O{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Pn,message:t}),this[Ln]=!0,this.functionality=e}static isInstance(e){return O.hasMarker(e,Fn)}};Ln=In;function P(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function F(e){return Object.fromEntries([...e.headers])}function Rn(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function zn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function I(e,...t){let n=zn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var L=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new $t({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function R(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Bn=[`fetch failed`,`failed to fetch`];function Vn({error:e,url:t,requestBodyValues:n}){if(R(e))return e;if(e instanceof TypeError&&Bn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new k({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Hn=`3.0.10`,Un=()=>globalThis.fetch,Wn=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:i,fetch:a=Un()})=>{try{let o=await a(e,{method:`GET`,headers:I(t,`ai-sdk/provider-utils/${Hn}`,Rn()),signal:i}),s=F(o);if(!o.ok){let t;try{t=await r({response:o,url:e,requestBodyValues:{}})}catch(t){throw R(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw t.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(t){throw t instanceof Error&&(R(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(t){throw Vn({error:t,url:e,requestBodyValues:{}})}};function Gn({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new A({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new A({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new A({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new A({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Kn({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function qn(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var Jn=/"__proto__"\s*:/,Yn=/"constructor"\s*:/;function Xn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Jn.test(e)===!1&&Yn.test(e)===!1?t:Zn(t)}function Zn(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Qn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Xn(e)}finally{Error.stackTraceLimit=t}}var $n=Symbol.for(`vercel.ai.validator`);function er(e){return{[$n]:!0,validate:e}}function tr(e){return typeof e==`object`&&!!e&&$n in e&&e[$n]===!0&&`validate`in e}function nr(e){return tr(e)?e:rr(e)}function rr(e){return er(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new M({value:t,cause:n.issues})}})}async function ir({value:e,schema:t}){let n=await ar({value:e,schema:t});if(!n.success)throw M.wrap({value:e,cause:n.error});return n.value}async function ar({value:e,schema:t}){let n=nr(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:M.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:M.wrap({value:e,cause:t}),rawValue:e}}}async function or({text:e,schema:t}){try{let n=Qn(e);return t==null?n:ir({value:n,schema:t})}catch(t){throw hn.isInstance(t)||M.isInstance(t)?t:new hn({text:e,cause:t})}}async function sr({text:e,schema:t}){try{let n=Qn(e);return t==null?{success:!0,value:n,rawValue:n}:await ar({value:n,schema:t})}catch(t){return{success:!1,error:hn.isInstance(t)?t:new hn({text:e,cause:t}),rawValue:void 0}}}function cr(e){try{return Qn(e),!0}catch{return!1}}function lr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new wt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await sr({text:e,schema:t}))}}))}async function z({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await ar({value:t[e],schema:n});if(!r.success)throw new $t({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var ur=()=>globalThis.fetch,B=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>fr({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),dr=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>fr({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),fr=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=ur()})=>{try{let s=await o(e,{method:`POST`,headers:I(t,`ai-sdk/provider-utils/${Hn}`,Rn()),body:n.content,signal:a}),c=F(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw R(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(R(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw Vn({error:t,url:e,requestBodyValues:n.values})}};function pr(e){return e}function V({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>pr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function H({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>pr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function U(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var W=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),s=F(r);if(o.trim()===``)return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await or({text:o,schema:e});return{responseHeaders:s,value:new k({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},G=e=>async({response:t})=>{let n=F(t);if(t.body==null)throw new qt({});return{responseHeaders:n,value:lr({stream:t.body,schema:e})}},K=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await sr({text:i,schema:e}),o=F(t);if(!a.success)throw new k({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},mr=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=F(e);if(!e.body)throw new k({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new k({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},{btoa:hr,atob:gr}=globalThis;function _r(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=gr(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function vr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return hr(t)}function q(e){return e instanceof Uint8Array?vr(e):e}function J(e){return e?.replace(/\/$/,``)}var yr=`2.0.23`,br=r.object({type:r.literal(`error`),error:r.object({type:r.string(),message:r.string()})}),xr=W({errorSchema:br,errorToMessage:e=>e.error.message}),Sr=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),Cr=r.object({sendReasoning:r.boolean().optional(),thinking:r.object({type:r.union([r.literal(`enabled`),r.literal(`disabled`)]),budgetTokens:r.number().optional()}).optional(),disableParallelToolUse:r.boolean().optional(),cacheControl:r.object({type:r.literal(`ephemeral`),ttl:r.union([r.literal(`5m`),r.literal(`1h`)]).optional()}).optional()});function Y(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var wr=r.object({maxCharacters:r.number().optional()}),Tr=V({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),Er=(e={})=>Tr(e),Dr=r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal(`approximate`),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}),Or=r.array(r.object({url:r.string(),title:r.string(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal(`web_search_result`)})),kr=H({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.object({query:r.string()}),outputSchema:Or}),Ar=(e={})=>kr(e),jr=r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}),Mr=r.object({type:r.literal(`web_fetch_result`),url:r.string(),content:r.object({type:r.literal(`document`),title:r.string(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal(`base64`),mediaType:r.literal(`application/pdf`),data:r.string()}),r.object({type:r.literal(`text`),mediaType:r.literal(`text/plain`),data:r.string()})])}),retrievedAt:r.string().nullable()}),Nr=H({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.object({url:r.string()}),outputSchema:Mr}),Pr=(e={})=>Nr(e);function Fr({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Y(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=wr.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=jr.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Dr.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new N({functionality:`tool choice type: ${o}`})}}var Ir=r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),Lr=H({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.object({code:r.string()}),outputSchema:Ir}),Rr=(e={})=>Lr(e);function zr(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new N({functionality:`URL-based text documents are not supported for citations`}):new N({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Br({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Vr(e),a,o=[];async function s(e){return(await z({provider:`anthropic`,providerOptions:e,schema:Sr}))?.citations?.enabled??!1}async function c(e){let t=await z({provider:`anthropic`,providerOptions:e,schema:Sr});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new N({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Y(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Y(a.providerOptions)??(o?Y(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:q(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:q(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:zr(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new N({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Y(r.providerOptions)??(a?Y(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new N({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Y(s.providerOptions)??(c?Y(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await z({provider:`anthropic`,providerOptions:s.providerOptions,schema:Yr});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ir.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Mr.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Or.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Vr(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function Hr({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var X={webSearchResult:r.object({type:r.literal(`web_search_result_location`),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),pageLocation:r.object({type:r.literal(`page_location`),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),charLocation:r.object({type:r.literal(`char_location`),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})},Ur=r.discriminatedUnion(`type`,[X.webSearchResult,X.pageLocation,X.charLocation]);r.discriminatedUnion(`type`,[X.pageLocation,X.charLocation]);function Wr(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Gr(e,t,n);i&&r(i)}}function Gr(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var Kr=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??L}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await z({provider:`anthropic`,providerOptions:f,schema:Cr}),{prompt:g,betas:_}=await Br({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new N({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:S,toolWarnings:C,betas:w}=Fr(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:S},warnings:[...p,...C],betas:new Set([..._,...w]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return P(await U(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await B({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:xr,successfulResponseHandler:K(qr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)Wr(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:Hr({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await B({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:xr,successfulResponseHandler:G(Jr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;Wr(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=Hr({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},qr=r.object({type:r.literal(`message`),id:r.string().nullish(),model:r.string().nullish(),content:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`text`),text:r.string(),citations:r.array(Ur).optional()}),r.object({type:r.literal(`thinking`),thinking:r.string(),signature:r.string()}),r.object({type:r.literal(`redacted_thinking`),data:r.string()}),r.object({type:r.literal(`tool_use`),id:r.string(),name:r.string(),input:r.unknown()}),r.object({type:r.literal(`server_tool_use`),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish()}),r.object({type:r.literal(`web_fetch_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`web_fetch_result`),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal(`document`),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.object({type:r.literal(`text`),media_type:r.string(),data:r.string()})})}),r.object({type:r.literal(`web_fetch_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`web_search_tool_result`),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal(`web_search_result`),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal(`web_search_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`code_execution_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal(`code_execution_tool_result_error`),error_code:r.string()})])})])),stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})}),Jr=r.discriminatedUnion(`type`,[r.object({type:r.literal(`message_start`),message:r.object({id:r.string().nullish(),model:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})})}),r.object({type:r.literal(`content_block_start`),index:r.number(),content_block:r.discriminatedUnion(`type`,[r.object({type:r.literal(`text`),text:r.string()}),r.object({type:r.literal(`thinking`),thinking:r.string()}),r.object({type:r.literal(`tool_use`),id:r.string(),name:r.string()}),r.object({type:r.literal(`redacted_thinking`),data:r.string()}),r.object({type:r.literal(`server_tool_use`),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish()}),r.object({type:r.literal(`web_fetch_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`web_fetch_result`),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal(`document`),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.object({type:r.literal(`text`),media_type:r.string(),data:r.string()})})}),r.object({type:r.literal(`web_fetch_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`web_search_tool_result`),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal(`web_search_result`),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal(`web_search_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`code_execution_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal(`code_execution_tool_result_error`),error_code:r.string()})])})])}),r.object({type:r.literal(`content_block_delta`),index:r.number(),delta:r.discriminatedUnion(`type`,[r.object({type:r.literal(`input_json_delta`),partial_json:r.string()}),r.object({type:r.literal(`text_delta`),text:r.string()}),r.object({type:r.literal(`thinking_delta`),thinking:r.string()}),r.object({type:r.literal(`signature_delta`),signature:r.string()}),r.object({type:r.literal(`citations_delta`),citation:Ur})])}),r.object({type:r.literal(`content_block_stop`),index:r.number()}),r.object({type:r.literal(`error`),error:r.object({type:r.string(),message:r.string()})}),r.object({type:r.literal(`message_delta`),delta:r.object({stop_reason:r.string().nullish(),stop_sequence:r.string().nullish()}),usage:r.looseObject({output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish()})}),r.object({type:r.literal(`message_stop`)}),r.object({type:r.literal(`ping`)})]),Yr=r.object({signature:r.string().optional(),redactedData:r.string().optional()}),Xr=V({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:n.object({command:n.string(),restart:n.boolean().optional()})}),Zr=V({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:n.object({command:n.string(),restart:n.boolean().optional()})}),Qr=V({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.object({action:r.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.array(r.number().int()).optional(),text:r.string().optional()})}),$r=V({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.object({action:r.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:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()})}),ei=V({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ti=V({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ni=V({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ri={bash_20241022:Xr,bash_20250124:Zr,codeExecution_20250522:Rr,computer_20241022:Qr,computer_20250124:$r,textEditor_20241022:ei,textEditor_20250124:ti,textEditor_20250429:ni,textEditor_20250728:Er,webFetch_20250910:Pr,webSearch_20250305:Ar};function ii(e={}){let t=J(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>I({"anthropic-version":`2023-06-01`,"x-api-key":Gn({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${yr}`),r=r=>new Kr(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??L,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new j({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new j({modelId:e,modelType:`imageModel`})},i.tools=ri,i}ii();var ai=`2.0.17`,oi=r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}),Z=W({errorSchema:oi,errorToMessage:e=>e.error.message}),si=r.object({outputDimensionality:r.number().optional(),taskType:r.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ci=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await z({provider:`google`,providerOptions:r,schema:si});if(e.length>this.maxEmbeddingsPerCall)throw new On({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=P(await U(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await B({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Z,successfulResponseHandler:K(ui),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await B({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Z,successfulResponseHandler:K(li),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},li=r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}),ui=r.object({embedding:r.object({values:r.array(r.number())})});function Q(e){if(e==null||di(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=Q(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(Q):Q(a)),o&&(p.allOf=o.map(Q)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=Q(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(Q),p.nullable=!0}else p.anyOf=s.map(Q);return c&&(p.oneOf=c.map(Q)),d!==void 0&&(p.minLength=d),p}function di(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function fi(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new N({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:q(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new N({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new N({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:q(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
8
|
-
|
|
9
|
-
`);r[0].parts.unshift({text:e+`
|
|
10
|
-
|
|
11
|
-
`})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function pi(e){return e.includes(`/`)?e:`models/${e}`}var mi=r.object({responseModalities:r.array(r.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:r.object({thinkingBudget:r.number().optional(),includeThoughts:r.boolean().optional()}).optional(),cachedContent:r.string().optional(),structuredOutputs:r.boolean().optional(),safetySettings:r.array(r.object({category:r.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:r.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:r.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r.boolean().optional(),labels:r.record(r.string(),r.string()).optional()});function hi({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:Q(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new N({functionality:`tool choice type: ${l}`})}}function gi({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var _i=r.object({web:r.object({uri:r.string(),title:r.string()}).nullish(),retrievedContext:r.object({uri:r.string(),title:r.string()}).nullish()}),vi=r.object({webSearchQueries:r.array(r.string()).nullish(),retrievalQueries:r.array(r.string()).nullish(),searchEntryPoint:r.object({renderedContent:r.string()}).nullish(),groundingChunks:r.array(_i).nullish(),groundingSupports:r.array(r.object({segment:r.object({startIndex:r.number().nullish(),endIndex:r.number().nullish(),text:r.string().nullish()}),segment_text:r.string().nullish(),groundingChunkIndices:r.array(r.number()).nullish(),supportChunkIndices:r.array(r.number()).nullish(),confidenceScores:r.array(r.number()).nullish(),confidenceScore:r.array(r.number()).nullish()})).nullish(),retrievalMetadata:r.union([r.object({webDynamicRetrievalScore:r.number()}),r.object({})]).nullish()}),yi=V({id:`google.google_search`,name:`google_search`,inputSchema:r.object({mode:r.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:r.number().default(1)})}),bi=r.object({retrievedUrl:r.string(),urlRetrievalStatus:r.string()}),xi=r.object({urlMetadata:r.array(bi)}),Si=V({id:`google.url_context`,name:`url_context`,inputSchema:r.object({})}),Ci=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??L}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await z({provider:`google`,providerOptions:f,schema:mi});m?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&p.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let h=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:g,systemInstruction:_}=fi(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=hi({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(m?.structuredOutputs??!0)?Q(c.schema):void 0,...m?.audioTimestamp&&{audioTimestamp:m.audioTimestamp},responseModalities:m?.responseModalities,thinkingConfig:m?.thinkingConfig},contents:g,systemInstruction:h?void 0:_,safetySettings:m?.safetySettings,tools:v,toolConfig:y,cachedContent:m?.cachedContent,labels:m?.labels},warnings:[...p,...b]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=P(await U(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await B({url:`${this.config.baseURL}/${pi(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:Z,successfulResponseHandler:K(Ai),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.candidates[0],l=[],u=c.content?.parts??[],d=o.usageMetadata,f;for(let e of u)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();f=t,l.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(l.push({type:`tool-result`,toolCallId:f,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),f=void 0):`text`in e&&e.text!=null&&e.text.length>0?l.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?l.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&l.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let p=Ei({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:gi({finishReason:c.finishReason,hasToolCalls:l.some(e=>e.type===`tool-call`)}),usage:{inputTokens:d?.promptTokenCount??void 0,outputTokens:d?.candidatesTokenCount??void 0,totalTokens:d?.totalTokenCount??void 0,reasoningTokens:d?.thoughtsTokenCount??void 0,cachedInputTokens:d?.cachedContentTokenCount??void 0},warnings:n,providerMetadata:{google:{promptFeedback:o.promptFeedback??null,groundingMetadata:c.groundingMetadata??null,urlContextMetadata:c.urlContextMetadata??null,safetyRatings:c.safetyRatings??null,usageMetadata:d??null}},request:{body:r},response:{headers:a,body:s}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=P(await U(this.config.headers),e.headers),{responseHeaders:a,value:o}=await B({url:`${this.config.baseURL}/${pi(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Z,successfulResponseHandler:G(ji),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(c.inputTokens=i.promptTokenCount??void 0,c.outputTokens=i.candidatesTokenCount??void 0,c.totalTokens=i.totalTokenCount??void 0,c.reasoningTokens=i.thoughtsTokenCount??void 0,c.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,_=Ei({groundingMetadata:a.groundingMetadata,generateId:u});if(_!=null)for(let e of _)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=Ti(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=wi({parts:o.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}a.finishReason!=null&&(s=gi({finishReason:a.finishReason,hasToolCalls:d}),l={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(l.google.usageMetadata=i))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function wi({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function Ti(e){return e?.filter(e=>`inlineData`in e)}function Ei({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var Di=r.object({parts:r.array(r.union([r.object({functionCall:r.object({name:r.string(),args:r.unknown()}),thoughtSignature:r.string().nullish()}),r.object({inlineData:r.object({mimeType:r.string(),data:r.string()})}),r.object({executableCode:r.object({language:r.string(),code:r.string()}).nullish(),codeExecutionResult:r.object({outcome:r.string(),output:r.string()}).nullish(),text:r.string().nullish(),thought:r.boolean().nullish(),thoughtSignature:r.string().nullish()})])).nullish()}),Oi=r.object({category:r.string().nullish(),probability:r.string().nullish(),probabilityScore:r.number().nullish(),severity:r.string().nullish(),severityScore:r.number().nullish(),blocked:r.boolean().nullish()}),ki=r.object({cachedContentTokenCount:r.number().nullish(),thoughtsTokenCount:r.number().nullish(),promptTokenCount:r.number().nullish(),candidatesTokenCount:r.number().nullish(),totalTokenCount:r.number().nullish()}),Ai=r.object({candidates:r.array(r.object({content:Di.nullish().or(r.object({}).strict()),finishReason:r.string().nullish(),safetyRatings:r.array(Oi).nullish(),groundingMetadata:vi.nullish(),urlContextMetadata:xi.nullish()})),usageMetadata:ki.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(Oi).nullish()}).nullish()}),ji=r.object({candidates:r.array(r.object({content:Di.nullish(),finishReason:r.string().nullish(),safetyRatings:r.array(Oi).nullish(),groundingMetadata:vi.nullish(),urlContextMetadata:xi.nullish()})).nullish(),usageMetadata:ki.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(Oi).nullish()}).nullish()}),Mi=H({id:`google.code_execution`,name:`code_execution`,inputSchema:r.object({language:r.string().describe(`The programming language of the code.`),code:r.string().describe(`The code to be executed.`)}),outputSchema:r.object({outcome:r.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:r.string().describe(`The output from the code execution.`)})}),Ni={googleSearch:yi,urlContext:Si,codeExecution:Mi},Pi=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var t;let{prompt:n,n:r=1,size:i=`1024x1024`,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l}=e,u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&u.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let d=await z({provider:`google`,providerOptions:s,schema:Ii}),f=((t=this.config._internal)?.currentDate)?.call(t)??new Date,p={sampleCount:r};a!=null&&(p.aspectRatio=a),d&&Object.assign(p,d);let m={instances:[{prompt:n}],parameters:p},{responseHeaders:h,value:g}=await B({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:P(await U(this.config.headers),c),body:m,failedResponseHandler:Z,successfulResponseHandler:K(Fi),abortSignal:l,fetch:this.config.fetch});return{images:g.predictions.map(e=>e.bytesBase64Encoded),warnings:u??[],providerMetadata:{google:{images:g.predictions.map(e=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:h}}}},Fi=r.object({predictions:r.array(r.object({bytesBase64Encoded:r.string()})).default([])}),Ii=r.object({personGeneration:r.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:r.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function Li(e={}){let t=J(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>I({"x-goog-api-key":Gn({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${ai}`),r=r=>new Ci(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??L,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),i=r=>new ci(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Pi(r,i,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),o=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return r(e)};return o.languageModel=r,o.chat=r,o.generativeAI=r,o.embedding=i,o.textEmbedding=i,o.textEmbeddingModel=i,o.image=a,o.imageModel=a,o.tools=Ni,o}Li();var Ri=r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),$=W({errorSchema:Ri,errorToMessage:e=>e.error.message});function zi({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${q(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new N({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:q(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:q(e.data),format:`mp3`}};default:throw new N({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new N({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${q(e.data)}`}}}else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Bi({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Vi(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Hi=r.object({logitBias:r.record(r.coerce.number(),r.number()).optional(),logprobs:r.union([r.boolean(),r.number()]).optional(),parallelToolCalls:r.boolean().optional(),user:r.string().optional(),reasoningEffort:r.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:r.number().optional(),store:r.boolean().optional(),metadata:r.record(r.string().max(64),r.string().max(512)).optional(),prediction:r.record(r.string(),r.any()).optional(),structuredOutputs:r.boolean().optional(),serviceTier:r.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:r.boolean().optional(),textVerbosity:r.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:r.string().optional(),safetyIdentifier:r.string().optional()});function Ui({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new N({functionality:`tool choice type: ${o}`})}}var Wi=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await z({provider:`openai`,providerOptions:f,schema:Hi})??{},h=m.structuredOutputs??!0;i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!h&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:g,warnings:_}=zi({prompt:e,systemMessageMode:Zi(this.modelId)});p.push(..._);let v=m.strictJsonSchema??!1,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?h&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,safety_identifier:m.safetyIdentifier,messages:g};Ji(this.modelId)?(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!Yi(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!Xi(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),y.service_tier=void 0);let{tools:b,toolChoice:x,toolWarnings:S}=Ui({tools:u,toolChoice:d,structuredOutputs:h,strictJsonSchema:v});return{args:{...y,tools:b,tool_choice:x},warnings:[...p,...S]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:$,successfulResponseHandler:K(Ki),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[],c=o.message.content;c!=null&&c.length>0&&s.push({type:`text`,text:c});for(let e of o.message.tool_calls??[])s.push({type:`tool-call`,toolCallId:e.id??L(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:L(),url:e.url,title:e.title});let l=i.usage?.completion_tokens_details,u=i.usage?.prompt_tokens_details,d={openai:{}};return l?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=l?.accepted_prediction_tokens),l?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=l?.rejected_prediction_tokens),o.logprobs?.content!=null&&(d.openai.logprobs=o.logprobs.content),{content:s,finishReason:Vi(o.finish_reason),usage:{inputTokens:i.usage?.prompt_tokens??void 0,outputTokens:i.usage?.completion_tokens??void 0,totalTokens:i.usage?.total_tokens??void 0,reasoningTokens:l?.reasoning_tokens??void 0,cachedInputTokens:u?.cached_tokens??void 0},request:{body:t},response:{...Bi(i),headers:r,body:a},warnings:n,providerMetadata:d}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:G(qi),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Bi(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=Vi(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new un({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new un({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new un({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),cr(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??L(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&cr(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??L(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:L(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},Gi=r.object({prompt_tokens:r.number().nullish(),completion_tokens:r.number().nullish(),total_tokens:r.number().nullish(),prompt_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish(),accepted_prediction_tokens:r.number().nullish(),rejected_prediction_tokens:r.number().nullish()}).nullish()}).nullish(),Ki=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`).nullish(),content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string().nullish(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish(),annotations:r.array(r.object({type:r.literal(`url_citation`),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()})).nullish()}),index:r.number(),logprobs:r.object({content:r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})).nullish()}).nullish(),finish_reason:r.string().nullish()})),usage:Gi}),qi=r.union([r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({delta:r.object({role:r.enum([`assistant`]).nullish(),content:r.string().nullish(),tool_calls:r.array(r.object({index:r.number(),id:r.string().nullish(),type:r.literal(`function`).nullish(),function:r.object({name:r.string().nullish(),arguments:r.string().nullish()})})).nullish(),annotations:r.array(r.object({type:r.literal(`url_citation`),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()})).nullish()}).nullish(),logprobs:r.object({content:r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})).nullish()}).nullish(),finish_reason:r.string().nullish(),index:r.number()})),usage:Gi}),Ri]);function Ji(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Yi(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Xi(e){return e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)}function Zi(e){return Ji(e)?Qi[e]?.systemMessageMode??`developer`:`system`}var Qi={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function $i({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
|
|
12
|
-
|
|
13
|
-
`,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new an({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
|
|
14
|
-
${e}
|
|
15
|
-
|
|
16
|
-
`;break}case`assistant`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new N({functionality:`tool-call messages`})}}).join(``);r+=`${n}:
|
|
17
|
-
${e}
|
|
18
|
-
|
|
19
|
-
`;break}case`tool`:throw new N({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
|
|
20
|
-
`,{prompt:r,stopSequences:[`
|
|
21
|
-
${t}:`]}}function ea({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function ta(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var na=r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional(),logprobs:r.union([r.boolean(),r.number()]).optional()}),ra=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await z({provider:`openai`,providerOptions:f,schema:na}),...await z({provider:this.providerOptionsName,providerOptions:f,schema:na})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=$i({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:$,successfulResponseHandler:K(aa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:ta(o.finish_reason),request:{body:t},response:{...ea(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:G(oa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...ea(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=ta(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},ia=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}),aa=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:ia.nullish()}),oa=r.union([r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string().nullish(),index:r.number(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:ia.nullish()}),Ri]),sa=r.object({dimensions:r.number().optional(),user:r.string().optional()}),ca=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new On({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await z({provider:`openai`,providerOptions:r,schema:sa})??{},{responseHeaders:a,value:o,rawValue:s}=await B({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:P(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:$,successfulResponseHandler:K(la),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},la=r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}),ua={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},da=new Set([`gpt-image-1`]),fa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return ua[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await B({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:P(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...da.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:K(pa),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},pa=r.object({data:r.array(r.object({b64_json:r.string(),revised_prompt:r.string().optional()}))}),ma=r.object({code:r.string().nullish(),containerId:r.string()}),ha=r.object({outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullish()}),ga=r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}),_a=H({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:ma,outputSchema:ha}),va=(e={})=>_a(e),ya=r.object({key:r.string(),type:r.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:r.union([r.string(),r.number(),r.boolean()])}),ba=r.object({type:r.enum([`and`,`or`]),filters:r.array(r.union([ya,r.lazy(()=>ba)]))}),xa=r.object({vectorStoreIds:r.array(r.string()),maxNumResults:r.number().optional(),ranking:r.object({ranker:r.string().optional(),scoreThreshold:r.number().optional()}).optional(),filters:r.union([ya,ba]).optional()}),Sa=r.object({queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),fileId:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullable()}),Ca=H({id:`openai.file_search`,name:`file_search`,inputSchema:r.object({}),outputSchema:Sa}),wa=r.object({background:r.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:r.enum([`low`,`high`]).optional(),inputImageMask:r.object({fileId:r.string().optional(),imageUrl:r.string().optional()}).optional(),model:r.string().optional(),moderation:r.enum([`auto`]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),outputFormat:r.enum([`png`,`jpeg`,`webp`]).optional(),quality:r.enum([`auto`,`low`,`medium`,`high`]).optional(),size:r.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Ta=r.object({result:r.string()}),Ea=H({id:`openai.image_generation`,name:`image_generation`,inputSchema:r.object({}),outputSchema:Ta}),Da=(e={})=>Ea(e),Oa=r.object({action:r.object({type:r.literal(`exec`),command:r.array(r.string()),timeoutMs:r.number().optional(),user:r.string().optional(),workingDirectory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),ka=r.object({output:r.string()}),Aa=H({id:`openai.local_shell`,name:`local_shell`,inputSchema:Oa,outputSchema:ka}),ja=r.object({filters:r.object({allowedDomains:r.array(r.string()).optional()}).optional(),searchContextSize:r.enum([`low`,`medium`,`high`]).optional(),userLocation:r.object({type:r.literal(`approximate`),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}),Ma=V({id:`openai.web_search`,name:`web_search`,inputSchema:r.object({action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()})}),Na=(e={})=>Ma(e),Pa=r.object({searchContextSize:r.enum([`low`,`medium`,`high`]).optional(),userLocation:r.object({type:r.literal(`approximate`),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}),Fa=V({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:r.object({action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()})}),Ia={codeInterpreter:va,fileSearch:Ca,imageGeneration:Da,localShell:Aa,webSearchPreview:Fa,webSearch:Na};function La(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Ra({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&La(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${q(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&La(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${q(e.data)}`}};else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=Oa.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await z({provider:`openai`,providerOptions:n.providerOptions,schema:za}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:ka.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var za=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function Ba({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Va({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=xa.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=Pa.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=ja.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=ga.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=wa.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new N({functionality:`tool choice type: ${a}`})}}var Ha=r.object({type:r.literal(`web_search_call`),id:r.string(),status:r.string(),action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()}),Ua=r.object({type:r.literal(`file_search_call`),id:r.string(),queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),file_id:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullish()}),Wa=r.object({type:r.literal(`code_interpreter_call`),id:r.string(),code:r.string().nullable(),container_id:r.string(),outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullable()}),Ga=r.object({type:r.literal(`local_shell_call`),id:r.string(),call_id:r.string(),action:r.object({type:r.literal(`exec`),command:r.array(r.string()),timeout_ms:r.number().optional(),user:r.string().optional(),working_directory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),Ka=r.object({type:r.literal(`image_generation_call`),id:r.string(),result:r.string()}),qa=20,Ja=r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})),Ya=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=To(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await z({provider:`openai`,providerOptions:l,schema:Eo}),{input:g,warnings:_}=await Ra({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?qa:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:ee,toolChoice:te,toolWarnings:ne}=Va({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:ee,tool_choice:te},warnings:[...p,...ne]}}async doGenerate(e){var t,n;let{args:i,warnings:a,webSearchToolName:o}=await this.getArgs(e),s=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await B({url:s,headers:P(this.config.headers(),e.headers),body:i,failedResponseHandler:$,successfulResponseHandler:K(r.object({id:r.string(),created_at:r.number(),error:r.object({code:r.string(),message:r.string()}).nullish(),model:r.string(),output:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),role:r.literal(`assistant`),id:r.string(),content:r.array(r.object({type:r.literal(`output_text`),text:r.string(),logprobs:Ja.nullish(),annotations:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`url_citation`),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()}),r.object({type:r.literal(`file_citation`),file_id:r.string(),filename:r.string().nullish(),index:r.number().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),quote:r.string().nullish()}),r.object({type:r.literal(`container_file_citation`)})]))}))}),Ha,Ua,Wa,Ka,Ga,r.object({type:r.literal(`function_call`),call_id:r.string(),name:r.string(),arguments:r.string(),id:r.string()}),r.object({type:r.literal(`computer_call`),id:r.string(),status:r.string().optional()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish(),summary:r.array(r.object({type:r.literal(`summary_text`),text:r.string()}))})])),service_tier:r.string().nullish(),incomplete_details:r.object({reason:r.string()}).nullish(),usage:Xa})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new k({message:l.error.message,url:s,requestBodyValues:i,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??L(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??L(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:o??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:o??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Ba({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:i},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:a}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:$,successfulResponseHandler:G(lo),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(yo(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):bo(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(fo(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(po(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(go(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(_o(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(vo(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ho(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):uo(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):So(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):Co(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):mo(g)?(s=Ba({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):xo(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??L(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??L(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):wo(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Xa=r.object({input_tokens:r.number(),input_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),output_tokens:r.number(),output_tokens_details:r.object({reasoning_tokens:r.number().nullish()}).nullish()}),Za=r.object({type:r.literal(`response.output_text.delta`),item_id:r.string(),delta:r.string(),logprobs:Ja.nullish()}),Qa=r.object({type:r.literal(`error`),code:r.string(),message:r.string(),param:r.string().nullish(),sequence_number:r.number()}),$a=r.object({type:r.enum([`response.completed`,`response.incomplete`]),response:r.object({incomplete_details:r.object({reason:r.string()}).nullish(),usage:Xa,service_tier:r.string().nullish()})}),eo=r.object({type:r.literal(`response.created`),response:r.object({id:r.string(),created_at:r.number(),model:r.string(),service_tier:r.string().nullish()})}),to=r.object({type:r.literal(`response.output_item.added`),output_index:r.number(),item:r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),id:r.string()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal(`function_call`),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string()}),r.object({type:r.literal(`web_search_call`),id:r.string(),status:r.string(),action:r.object({type:r.literal(`search`),query:r.string().optional()}).nullish()}),r.object({type:r.literal(`computer_call`),id:r.string(),status:r.string()}),r.object({type:r.literal(`file_search_call`),id:r.string()}),r.object({type:r.literal(`image_generation_call`),id:r.string()}),r.object({type:r.literal(`code_interpreter_call`),id:r.string(),container_id:r.string(),code:r.string().nullable(),outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullable(),status:r.string()})])}),no=r.object({type:r.literal(`response.output_item.done`),output_index:r.number(),item:r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),id:r.string()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal(`function_call`),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string(),status:r.literal(`completed`)}),Wa,Ka,Ha,Ua,Ga,r.object({type:r.literal(`computer_call`),id:r.string(),status:r.literal(`completed`)})])}),ro=r.object({type:r.literal(`response.function_call_arguments.delta`),item_id:r.string(),output_index:r.number(),delta:r.string()}),io=r.object({type:r.literal(`response.code_interpreter_call_code.delta`),item_id:r.string(),output_index:r.number(),delta:r.string()}),ao=r.object({type:r.literal(`response.code_interpreter_call_code.done`),item_id:r.string(),output_index:r.number(),code:r.string()}),oo=r.object({type:r.literal(`response.output_text.annotation.added`),annotation:r.discriminatedUnion(`type`,[r.object({type:r.literal(`url_citation`),url:r.string(),title:r.string()}),r.object({type:r.literal(`file_citation`),file_id:r.string(),filename:r.string().nullish(),index:r.number().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),quote:r.string().nullish()})])}),so=r.object({type:r.literal(`response.reasoning_summary_part.added`),item_id:r.string(),summary_index:r.number()}),co=r.object({type:r.literal(`response.reasoning_summary_text.delta`),item_id:r.string(),summary_index:r.number(),delta:r.string()}),lo=r.union([Za,$a,eo,to,no,ro,io,ao,oo,so,co,Qa,r.object({type:r.string()}).loose()]);function uo(e){return e.type===`response.output_text.delta`}function fo(e){return e.type===`response.output_item.done`}function po(e){return fo(e)&&e.item.type===`reasoning`}function mo(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ho(e){return e.type===`response.created`}function go(e){return e.type===`response.function_call_arguments.delta`}function _o(e){return e.type===`response.code_interpreter_call_code.delta`}function vo(e){return e.type===`response.code_interpreter_call_code.done`}function yo(e){return e.type===`response.output_item.added`}function bo(e){return yo(e)&&e.item.type===`reasoning`}function xo(e){return e.type===`response.output_text.annotation.added`}function So(e){return e.type===`response.reasoning_summary_part.added`}function Co(e){return e.type===`response.reasoning_summary_text.delta`}function wo(e){return e.type===`error`}function To(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Eo=r.object({include:r.array(r.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:r.string().nullish(),logprobs:r.union([r.boolean(),r.number().min(1).max(qa)]).optional(),maxToolCalls:r.number().nullish(),metadata:r.any().nullish(),parallelToolCalls:r.boolean().nullish(),previousResponseId:r.string().nullish(),promptCacheKey:r.string().nullish(),reasoningEffort:r.string().nullish(),reasoningSummary:r.string().nullish(),safetyIdentifier:r.string().nullish(),serviceTier:r.enum([`auto`,`flex`,`priority`]).nullish(),store:r.boolean().nullish(),strictJsonSchema:r.boolean().nullish(),textVerbosity:r.enum([`low`,`medium`,`high`]).nullish(),user:r.string().nullish()}),Do=r.object({instructions:r.string().nullish(),speed:r.number().min(.25).max(4).default(1).nullish()}),Oo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await z({provider:`openai`,providerOptions:o,schema:Do}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await B({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:mr(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},ko=r.object({include:r.array(r.string()).optional(),language:r.string().optional(),prompt:r.string().optional(),temperature:r.number().min(0).max(1).default(0).optional(),timestampGranularities:r.array(r.enum([`word`,`segment`])).default([`segment`]).optional()}),Ao={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},jo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await z({provider:`openai`,providerOptions:n,schema:ko}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([_r(e)]);a.append(`model`,this.modelId);let s=qn(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await dr({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),formData:r,failedResponseHandler:$,successfulResponseHandler:K(Mo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Ao?Ao[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Mo=r.object({text:r.string(),language:r.string().nullish(),duration:r.number().nullish(),words:r.array(r.object({word:r.string(),start:r.number(),end:r.number()})).nullish(),segments:r.array(r.object({id:r.number(),seek:r.number(),start:r.number(),end:r.number(),text:r.string(),tokens:r.array(r.number()),temperature:r.number(),avg_logprob:r.number(),compression_ratio:r.number(),no_speech_prob:r.number()})).nullish()}),No=`2.0.42`;function Po(e={}){let t=J(Kn({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>I({Authorization:`Bearer ${Gn({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${No}`),i=i=>new Wi(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ra(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new ca(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new fa(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new jo(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new Oo(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ya(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Ia,f}Po(),r.object({user:r.string().optional(),reasoningEffort:r.string().optional()});var Fo={errorSchema:r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),errorToMessage:e=>e.error.message},Io=r.object({prompt_tokens:r.number().nullish(),completion_tokens:r.number().nullish(),total_tokens:r.number().nullish(),prompt_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish(),accepted_prediction_tokens:r.number().nullish(),rejected_prediction_tokens:r.number().nullish()}).nullish()}).nullish();r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`).nullish(),content:r.string().nullish(),reasoning_content:r.string().nullish(),reasoning:r.string().nullish(),tool_calls:r.array(r.object({id:r.string().nullish(),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),finish_reason:r.string().nullish()})),usage:Io}),r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional()});var Lo=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()});r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string()})),usage:Lo.nullish()}),r.object({dimensions:r.number().optional(),user:r.string().optional()}),r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish(),providerMetadata:r.record(r.string(),r.record(r.string(),r.any())).optional()});var Ro=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await B({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:P(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:W(this.config.errorStructure??Fo),successfulResponseHandler:K(zo),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},zo=r.object({data:r.array(r.object({b64_json:r.string()}))});function Bo(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${q(e.data)}`}}}else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function Vo({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Ho(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var Uo=r.object({type:r.literal(`web`),country:r.string().length(2).optional(),excludedWebsites:r.array(r.string()).max(5).optional(),allowedWebsites:r.array(r.string()).max(5).optional(),safeSearch:r.boolean().optional()}),Wo=r.object({type:r.literal(`x`),excludedXHandles:r.array(r.string()).optional(),includedXHandles:r.array(r.string()).optional(),postFavoriteCount:r.number().int().optional(),postViewCount:r.number().int().optional(),xHandles:r.array(r.string()).optional()}),Go=r.object({type:r.literal(`news`),country:r.string().length(2).optional(),excludedWebsites:r.array(r.string()).max(5).optional(),safeSearch:r.boolean().optional()}),Ko=r.object({type:r.literal(`rss`),links:r.array(r.string().url()).max(1)}),qo=r.discriminatedUnion(`type`,[Uo,Wo,Go,Ko]),Jo=r.object({reasoningEffort:r.enum([`low`,`high`]).optional(),searchParameters:r.object({mode:r.enum([`off`,`auto`,`on`]),returnCitations:r.boolean().optional(),fromDate:r.string().optional(),toDate:r.string().optional(),maxSearchResults:r.number().min(1).max(50).optional(),sources:r.array(qo).optional()}).optional()}),Yo=r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),Xo=W({errorSchema:Yo,errorToMessage:e=>e.error.message});function Zo({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new N({functionality:`tool choice type: ${i}`})}}var Qo=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await z({provider:`xai`,providerOptions:u,schema:Jo})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=Bo(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=Zo({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:Xo,successfulResponseHandler:K(es),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:Ho(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...Vo(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:Xo,successfulResponseHandler:G(ts),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...Vo(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=Ho(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},$o=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish()}).nullish()}),es=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`),content:r.string().nullish(),reasoning_content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),index:r.number(),finish_reason:r.string().nullish()})),object:r.literal(`chat.completion`),usage:$o,citations:r.array(r.string().url()).nullish()}),ts=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({delta:r.object({role:r.enum([`assistant`]).optional(),content:r.string().nullish(),reasoning_content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),finish_reason:r.string().nullish(),index:r.number()})),usage:$o.nullish(),citations:r.array(r.string().url()).nullish()}),ns=`2.0.23`,rs={errorSchema:Yo,errorToMessage:e=>e.error.message};function os(e={}){let t=J(e.baseURL??`https://api.x.ai/v1`),n=()=>I({Authorization:`Bearer ${Gn({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${ns}`),r=r=>new Qo(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:L,fetch:e.fetch}),i=r=>new Ro(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:rs}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new j({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}os();function ss(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function cs(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(`x-blink-stream-response-format`);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new wt).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>u({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Po({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Po({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(ii({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Li({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(os({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}const ls=`BLINK_API_URL`;var us=class{baseUrl;client;constructor(e){this.client=Pt(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),cs(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};async function ds({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=fs}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),u=l({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of u)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const fs=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(s);return n.length===0||n.some(e=>Ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},ps=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function ms(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var hs=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=vt(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=yt(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!ms(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!s(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ds({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=o.getReader();n.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||n.signal.aborted)break;u||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};export{k as APICallError,ls as APIServerURLEnvironmentVariable,hs as ChatManager,us as Client,we as CustomChatResponseError,wt as EventSourceParserStream,j as NoSuchModelError,Re as checkOptionalParameter,P as combineHeaders,me as completeAssign,ps as convertMessage,ii as createAnthropic,Ce as createCustomAbortControllerSignal,vt as createDiskStore,G as createEventSourceResponseHandler,W as createJsonErrorResponseHandler,K as createJsonResponseHandler,Po as createOpenAI,St as createParser,Ue as decodeURIComponent_,xe as ensureDisposableStackRegisteredForTerminateEvents,h as fakePromise,Wn as getFromApi,pt as getLockInfo,Fe as getPath,Ie as getPathNoStrict,Me as getPattern,Ve as getQueryParam,He as getQueryParams,_e as handleAbortSignalAndPromiseResponse,he as handleErrorFromRequestHandler,m as handleMaybePromise,Pt as hc,ce as isFetchEvent,ae as isNodeRequest,f as isPromise,pe as isRequestInit,oe as isServerResponse,ms as isStoredMessageMetadata,Ee as isToolApprovalOutput,ge as isolateObject,_ as iterateAsync,ss as lastUIOptions,Kn as loadOptionalSetting,dt as lock,Le as mergePath,re as normalizeNodeRequest,Ke as parse,B as postJsonToApi,U as resolve,de as sendNodeResponse,De as splitPath,Oe as splitRoutingPath,Te as tools,Ne as tryDecode,S as unfakePromise,I as withUserAgentSuffix,J as withoutTrailingSlash};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./wrapper-B0SBsJWP.js";import{WorkspaceConnect as e,connect as t}from"./connect-CQUVd44y.js";export{e as WorkspaceConnect,t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{dirname as e,join as t}from"path";import{existsSync as n,mkdirSync as r,readFileSync as i,unlinkSync as a,writeFileSync as o}from"fs";import{z as s}from"zod";function c(e){return t(e,`data`,`devhook.txt`)}function l(e){return n(c(e))}function u(e){let t=c(e);if(n(t))return i(t,`utf-8`).trim()}function d(t){let a=c(t);if(r(e(a),{recursive:!0}),n(a))return i(a,`utf-8`);let s=crypto.randomUUID();return o(a,s),s}function f(e){let t=c(e);n(t)&&a(t)}function p(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const m=s.union([s.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),s.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),s.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),s.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),s.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),s.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),s.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),s.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),s.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),s.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),s.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),s.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),s.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),s.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),s.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),s.literal(`file_created`).describe(`File was created. Requires scope: files:read`),s.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),s.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),s.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),s.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),s.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),s.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),s.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),s.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),s.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),s.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),s.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),s.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),s.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),s.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),s.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),s.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),s.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),s.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),s.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),s.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),s.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),h=s.union([s.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),s.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),s.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),s.literal(`channels:join`).describe(`Join public channels`),s.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),s.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),s.literal(`chat:write`).describe(`Send messages as the bot`),s.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),s.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),s.literal(`commands`).describe(`Add and use slash commands`),s.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),s.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),s.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),s.literal(`files:write`).describe(`Upload, edit, and delete files`),s.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),s.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),s.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),s.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),s.literal(`im:read`).describe(`View basic information about direct messages with the bot`),s.literal(`im:write`).describe(`Start and manage direct messages with users`),s.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),s.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),s.literal(`metadata.message:read`).describe(`Read message metadata`),s.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),s.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),s.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),s.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),s.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),s.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),s.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),s.literal(`reminders:read`).describe(`View reminders created by the bot`),s.literal(`reminders:write`).describe(`Create, update, and delete reminders`),s.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),s.literal(`usergroups:read`).describe(`View user groups and their members`),s.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),s.literal(`users.profile:read`).describe(`View profile information about users`),s.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),s.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),s.literal(`users:write`).describe(`Set presence and status for the bot user`)]),g=s.union([s.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),s.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),s.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),s.literal(`chat:write`).describe(`Send messages on behalf of the user`),s.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),s.literal(`files:read`).describe(`View files on behalf of the user`),s.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),s.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),s.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),s.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),s.literal(`im:history`).describe(`Read direct message history on behalf of the user`),s.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),s.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),s.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),s.literal(`links:write`).describe(`Show URL previews on behalf of the user`),s.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),s.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),s.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),s.literal(`pins:read`).describe(`View pinned items on behalf of the user`),s.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),s.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),s.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),s.literal(`reminders:read`).describe(`View reminders on behalf of the user`),s.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),s.literal(`search:read`).describe(`Search messages and files on behalf of the user`),s.literal(`stars:read`).describe(`View starred items on behalf of the user`),s.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),s.literal(`team:read`).describe(`View workspace information on behalf of the user`),s.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),s.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),s.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),s.literal(`users.profile:write`).describe(`Edit the user's profile information`),s.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),s.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),s.literal(`users:write`).describe(`Set presence for the user`)]),_=s.object({display_information:s.object({name:s.string().describe(`The name of the Slack app.`),description:s.string().optional().describe(`A short description of the app.`),background_color:s.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:s.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:s.object({bot_user:s.object({display_name:s.string().describe(`The display name for the bot user.`),always_online:s.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:s.object({home_tab_enabled:s.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:s.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:s.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:s.object({assistant_description:s.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:s.array(s.object({command:s.string().regex(/^\//).describe(`The command (must start with /).`),description:s.string().describe(`Description of the command.`),usage_hint:s.string().optional().describe(`Usage hint for the command.`),should_escape:s.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:s.array(s.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:s.object({redirect_urls:s.array(s.url()).optional().describe(`OAuth redirect URLs.`),scopes:s.object({bot:s.array(s.union([h,s.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:s.array(s.union([g,s.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:s.object({event_subscriptions:s.object({request_url:s.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:s.array(s.union([m,s.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:s.object({is_enabled:s.boolean().describe(`Enable interactivity.`),request_url:s.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:s.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:s.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:s.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:s.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});export{d as createDevhookID,p as createSlackApp,_ as createSlackAppSchema,u as getDevhookID,l as hasDevhook,f as resetDevhookID};
|