blink 1.1.14 → 1.1.15
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/cli/{auth-vk-Wh2Tb.js → auth-DCUw-BJE.js} +1 -1
- package/dist/cli/{chat-1VNeGtdY.js → chat-ebiRKqit.js} +1 -1
- package/dist/cli/connect-C3y3nGPW.js +1 -0
- package/dist/cli/{connect-lKAgssA8.js → connect-C__b725p.js} +1 -1
- package/dist/cli/create-slack-app-CNDXDwfs.js +1 -0
- package/dist/cli/{dev-C7WLllYl.js → dev-D6lIT1u-.js} +64 -64
- package/dist/cli/{getMachineId-bsd-CNyWjFgv.js → getMachineId-bsd-2l7jEJ9H.js} +1 -1
- package/dist/cli/{getMachineId-bsd-CbJ9B5uX.js → getMachineId-bsd-BQaAhwjO.js} +1 -1
- package/dist/cli/{getMachineId-bsd-hom6rwXG.js → getMachineId-bsd-CbeuYR7X.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DD6K1Ylh.js → getMachineId-bsd-Cn9OZifa.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DSrNAXcz.js → getMachineId-bsd-Cw8CWhxJ.js} +1 -1
- package/dist/cli/getMachineId-bsd-DP_S0ZSE.js +1 -0
- package/dist/cli/getMachineId-bsd-DcR5dlLj.js +1 -0
- package/dist/cli/{getMachineId-darwin-B2z5T7Xs.js → getMachineId-darwin-C-kdKVWl.js} +1 -1
- package/dist/cli/{getMachineId-darwin-Do9xDlln.js → getMachineId-darwin-D6Y_ttQ1.js} +1 -1
- package/dist/cli/{getMachineId-darwin-CjZYhlFh.js → getMachineId-darwin-D7CuR-jd.js} +1 -1
- package/dist/cli/{getMachineId-darwin-CsiYkPo-.js → getMachineId-darwin-D9mTsu57.js} +1 -1
- package/dist/cli/{getMachineId-darwin-CCg1DW1T.js → getMachineId-darwin-DJ-H8l7s.js} +1 -1
- package/dist/cli/getMachineId-darwin-DYCKXuZX.js +2 -0
- package/dist/cli/getMachineId-darwin-DyN_uugK.js +2 -0
- package/dist/cli/{getMachineId-linux--nJ0-hXg.js → getMachineId-linux-BCOAWAJr.js} +1 -1
- package/dist/cli/{getMachineId-linux-BUWGstOo.js → getMachineId-linux-CBDQri3D.js} +1 -1
- package/dist/cli/{getMachineId-linux-CFErR3im.js → getMachineId-linux-CI6sk5r7.js} +1 -1
- package/dist/cli/{getMachineId-linux-CZHIN7gw.js → getMachineId-linux-DA2UB-e3.js} +1 -1
- package/dist/cli/getMachineId-linux-DGORKISs.js +1 -0
- package/dist/cli/getMachineId-linux-EqaaEzYC.js +1 -0
- package/dist/cli/getMachineId-linux-QFNGh16E.js +1 -0
- package/dist/cli/{getMachineId-unsupported-CT_22mpw.js → getMachineId-unsupported-B4t2intc.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-CjlL_DiJ.js → getMachineId-unsupported-B6Ips7oB.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-DiRlSG-9.js → getMachineId-unsupported-BLalsIU8.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-Dx9tfp2U.js → getMachineId-unsupported-CNgpP2gn.js} +1 -1
- package/dist/cli/getMachineId-unsupported-CQrnjCuH.js +1 -0
- package/dist/cli/getMachineId-unsupported-CcRcqdy3.js +1 -0
- package/dist/cli/getMachineId-unsupported-Cxfw7WwT.js +1 -0
- package/dist/cli/{getMachineId-win-CBB5d89h.js → getMachineId-win-B6FQ_uBq.js} +1 -1
- package/dist/cli/{getMachineId-win-Ca7mM30T.js → getMachineId-win-B7f9VGFu.js} +1 -1
- package/dist/cli/{getMachineId-win-CRfkH29Y.js → getMachineId-win-BB1s3SWz.js} +1 -1
- package/dist/cli/{getMachineId-win-dkRkgiL3.js → getMachineId-win-BrQ4d5bO.js} +1 -1
- package/dist/cli/{getMachineId-win-CybVbRb1.js → getMachineId-win-CgPYGelR.js} +1 -1
- package/dist/cli/getMachineId-win-Dr2KTzTp.js +1 -0
- package/dist/cli/getMachineId-win-QxOtxJWo.js +1 -0
- package/dist/cli/index.js +3 -3
- package/dist/cli/init-DYcep43s.js +3 -0
- package/dist/cli/{init-CcRVlAi3.js → init-templates-C_keoZ45.js} +2 -4
- package/dist/cli/login-P-KIKeEv.js +1 -0
- package/dist/cli/{run-D-Kl9E0k.js → run-DT3wRuFc.js} +1 -1
- package/dist/cli/setup-slack-app-Bo1yEsSq.js +1 -0
- package/dist/cli/{token-B1evCYHV.js → token-CrWhcy44.js} +1 -1
- package/dist/cli/{token-util-DFNCn3fC.js → token-util-1KocPoKS.js} +1 -1
- package/dist/cli/token-util-CRJP9Uji.js +1 -0
- package/dist/cli/undici-CeDxbuSU.js +1 -0
- package/dist/cli/{util-x4GqZFrj.js → util-DBfnc6lD.js} +1 -1
- package/dist/node/react/index.node.cjs +1136 -6
- package/dist/node/react/index.node.js +1169 -39
- package/package.json +1 -1
- package/dist/cli/connect-C4Z_U2Zf.js +0 -1
- package/dist/cli/getMachineId-bsd-D_6s5Cdq.js +0 -1
- package/dist/cli/getMachineId-bsd-bqULO5m0.js +0 -1
- package/dist/cli/getMachineId-darwin-carDgaew.js +0 -2
- package/dist/cli/getMachineId-darwin-zV0HrpSD.js +0 -2
- package/dist/cli/getMachineId-linux-DVSYpC_y.js +0 -1
- package/dist/cli/getMachineId-linux-DZtobVSz.js +0 -1
- package/dist/cli/getMachineId-linux-MYg9wcZ6.js +0 -1
- package/dist/cli/getMachineId-unsupported-bzLHzE4h.js +0 -1
- package/dist/cli/getMachineId-unsupported-rhjt9gIv.js +0 -1
- package/dist/cli/getMachineId-unsupported-sqVpruKF.js +0 -1
- package/dist/cli/getMachineId-win-pYcO6KSJ.js +0 -1
- package/dist/cli/getMachineId-win-vPBnzYB3.js +0 -1
- package/dist/cli/init-DtC2zW4S.js +0 -1
- package/dist/cli/login-65v3CFjc.js +0 -1
- package/dist/cli/setup-slack-app-wU8aMoUF.js +0 -1
- package/dist/cli/token-util-B3-W38hT.js +0 -1
- package/dist/cli/undici-DxKEEM9B.js +0 -1
- /package/dist/cli/{chat-manager-XyOX_Hmk.js → chat-manager-BtRfjylv.js} +0 -0
- /package/dist/cli/{devtools-C6zo-VIa.js → devtools-CcsObSm8.js} +0 -0
- /package/dist/cli/{dist-DxkSGwUH.js → dist-AXHevRdg.js} +0 -0
- /package/dist/cli/{esm-CBbRLxmL.js → esm-C_RXU0lI.js} +0 -0
- /package/dist/cli/{execAsync-B4RcmQib.js → execAsync-BeUIz9nV.js} +0 -0
- /package/dist/cli/{execAsync-BEK5YUm1.js → execAsync-Bhq3YKvl.js} +0 -0
- /package/dist/cli/{execAsync-CpqeGF36.js → execAsync-BnYBiViJ.js} +0 -0
- /package/dist/cli/{execAsync-DXjxl3NT.js → execAsync-Byz_iObc.js} +0 -0
- /package/dist/cli/{execAsync-SGF4O5TO.js → execAsync-CQurQFgT.js} +0 -0
- /package/dist/cli/{execAsync-yuWNzIOa.js → execAsync-Djebuxfm.js} +0 -0
- /package/dist/cli/{execAsync-zgZE3anO.js → execAsync-_tP2SNTy.js} +0 -0
- /package/dist/cli/{open-S_jcQ0nw.js → open-DCYivxgo.js} +0 -0
- /package/dist/cli/{server-C8plsU0X-DRRpA-nw.js → server-C8plsU0X-b-FVGGZ1.js} +0 -0
- /package/dist/cli/{token-error-BH5_eVU3.js → token-error-CoDMyqH1.js} +0 -0
- /package/dist/cli/{undici-w5avb4CY.js → undici-DS7K19Do.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-sb6fILn2.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-BzoNpizh.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:buffer`);i=e.__toESM(i);let a=require(`node:fs`);a=e.__toESM(a);let o=require(`node:url`);o=e.__toESM(o);let s=require(`node:stream`);s=e.__toESM(s);let c=require(`node:util`);c=e.__toESM(c);let l=require(`node:crypto`);l=e.__toESM(l),require(`crypto`);let u=require(`http`);u=e.__toESM(u);let d=require(`path`);d=e.__toESM(d);let f=require(`module`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:readline`);S=e.__toESM(S);let C=require(`node:child_process`);C=e.__toESM(C);let w=require(`node:fs/promises`);w=e.__toESM(w);let T=require(`node:os`);T=e.__toESM(T);var E=`2.0.23`,D=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),O=t.createJsonErrorResponseHandler({errorSchema:D,errorToMessage:e=>e.error.message}),k=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),A=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function j(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var M=r.z.object({maxCharacters:r.z.number().optional()}),N=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),P=(e={})=>N(e),F=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ee=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),te=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ee}),I=(e={})=>te(e),L=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),R=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),z=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:R}),B=(e={})=>z(e);function V({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=j(t.providerOptions);o.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`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.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`:a.add(`computer-use-2024-10-22`),o.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`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=M.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=L.parse(t.args);o.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=F.parse(t.args);o.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:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var H=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),ne=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:H}),U=(e={})=>ne(e);function re(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 t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function W({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=ie(e),o,s=[];async function c(e){return(await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k}))?.citations?.enabled??!1}async function l(e){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k});return{title:n?.title,context:n?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:j(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=j(o.providerOptions)??(s?j(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:t.convertToBase64(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let n=await c(o.providerOptions),r=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:t.convertToBase64(o.data)},title:r.title??o.filename,...r.context&&{context:r.context},...n&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:re(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=j(i.providerOptions)??(o?j(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.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 t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let i=0;i<u.messages.length;i++){let a=u.messages[i],o=i===u.messages.length-1,{content:s}=a;for(let i=0;i<s.length;i++){let c=s[i],l=i===s.length-1,u=j(c.providerOptions)??(l?j(a.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:d&&o&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(n){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:c.providerOptions,schema:fe});n==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):n.signature==null?n.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:n.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:n.signature,cache_control:u})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){c.toolName===`code_execution`||c.toolName===`web_fetch`||c.toolName===`web_search`?e.push({type:`server_tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u}):r.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=H.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:u});break}if(c.toolName===`web_fetch`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=R.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:c.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:u});break}if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=ee.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}r.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function ie(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 G({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 ae={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},oe=r.z.discriminatedUnion(`type`,[ae.webSearchResult,ae.pageLocation,ae.charLocation]);r.z.discriminatedUnion(`type`,[ae.pageLocation,ae.charLocation]);function se(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=ce(e,t,n);i&&r(i)}}function ce(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 le=class{constructor(e,n){this.specificationVersion=`v2`,this.modelId=e,this.config=n,this.generateId=n.generateId??t.generateId}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:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await t.parseProviderOptions({provider:`anthropic`,providerOptions:p,schema:A}),{prompt:_,betas:v}=await W({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=V(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:n}){return t.combineHeaders(await t.resolve(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},n)}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:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(n),failedResponseHandler:O,successfulResponseHandler:t.createJsonResponseHandler(ue),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=[];for(let e of c.content)switch(e.type){case`text`:if(!a&&(u.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)se(t,o,this.generateId,e=>u.push(e));break;case`thinking`:u.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:u.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:u.push(a?{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`)&&u.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`?u.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`&&u.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)){u.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)u.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else u.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`?u.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`&&u.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:u,finishReason:G({finishReason:c.stop_reason,isJsonResponseFromTool:a}),usage:{inputTokens:c.usage.input_tokens,outputTokens:c.usage.output_tokens,totalTokens:c.usage.input_tokens+c.usage.output_tokens,cachedInputTokens:c.usage.cache_read_input_tokens??void 0},request:{body:n},response:{id:c.id??void 0,modelId:c.model??void 0,headers:s,body:l},warnings:r,providerMetadata:{anthropic:{usage:c.usage,cacheCreationInputTokens:c.usage.cache_creation_input_tokens??null,stopSequence:c.stop_sequence??null}}}}async doStream(e){let{args:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...n,stream:!0},{responseHeaders:c,value:l}=await t.postJsonToApi({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:O,successfulResponseHandler:t.createEventSourceResponseHandler(de),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=`unknown`,d={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},f={},p,m=null,h=null,g,_=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},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(g=e,e){case`text`:f[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:f[r.index]=a?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(a?{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`)&&(f[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:_(),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(f[r.index]!=null){let e=f[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`:a||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete f[r.index]}g=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(a)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`:g===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=f[r.index],t=r.delta.partial_json;if(a){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;se(e,o,_,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:d.inputTokens=r.message.usage.input_tokens,d.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,p={...r.message.usage},m=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`:d.outputTokens=r.usage.output_tokens,d.totalTokens=(d.inputTokens??0)+(r.usage.output_tokens??0),u=G({finishReason:r.delta.stop_reason,isJsonResponseFromTool:a}),h=r.delta.stop_sequence??null,p={...p,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:u,usage:d,providerMetadata:{anthropic:{usage:p??null,cacheCreationInputTokens:m,stopSequence:h}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:s},response:{headers:c}}}},ue=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(oe).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),de=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:oe})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),fe=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),pe=t.createProviderDefinedToolFactory({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),me=t.createProviderDefinedToolFactory({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),he=t.createProviderDefinedToolFactory({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),ge=t.createProviderDefinedToolFactory({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.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.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),K=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),_e=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ve=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ye={bash_20241022:pe,bash_20250124:me,codeExecution_20250522:U,computer_20241022:he,computer_20250124:ge,textEditor_20241022:K,textEditor_20250124:_e,textEditor_20250429:ve,textEditor_20250728:P,webFetch_20250910:B,webSearch_20250305:I};function be(e={}){let n=t.withoutTrailingSlash(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>t.withUserAgentSuffix({"anthropic-version":`2023-06-01`,"x-api-key":t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${E}`),i=i=>new le(i,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??t.generateId,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ye,a}var xe=be(),Se=`2.0.17`,Ce=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),we=t.createJsonErrorResponseHandler({errorSchema:Ce,errorToMessage:e=>e.error.message}),Te=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Ee=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:n,abortSignal:r,providerOptions:i}){let a=await t.parseProviderOptions({provider:`google`,providerOptions:i,schema:Te});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=t.combineHeaders(await t.resolve(this.config.headers),n);if(e.length===1){let{responseHeaders:n,value:i,rawValue:s}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:we,successfulResponseHandler:t.createJsonResponseHandler(Oe),abortSignal:r,fetch:this.config.fetch});return{embeddings:[i.embedding.values],usage:void 0,response:{headers:n,body:s}}}let{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:we,successfulResponseHandler:t.createJsonResponseHandler(De),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},De=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),Oe=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function q(e){if(e==null||ke(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 ke(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Ae(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let n of o)switch(n.type){case`text`:e.push({text:n.text});break;case`file`:{let r=n.mediaType===`image/*`?`image/jpeg`:n.mediaType;e.push(n.data instanceof URL?{fileData:{mimeType:r,fileUri:n.data.toString()}}:{inlineData:{mimeType:r,data:t.convertToBase64(n.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.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 t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:t.convertToBase64(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`:{a=!1;let e=[];for(let t of o){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}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
1
|
+
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-sb6fILn2.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-BzoNpizh.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:buffer`);i=e.__toESM(i);let a=require(`node:fs`);a=e.__toESM(a);let o=require(`node:url`);o=e.__toESM(o);let s=require(`node:stream`);s=e.__toESM(s);let c=require(`node:util`);c=e.__toESM(c);let l=require(`node:crypto`);l=e.__toESM(l);let u=require(`http`);u=e.__toESM(u);let d=require(`path`);d=e.__toESM(d);let f=require(`module`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:readline`);S=e.__toESM(S);let C=require(`node:child_process`);C=e.__toESM(C);let w=require(`node:fs/promises`);w=e.__toESM(w);let T=require(`node:os`);T=e.__toESM(T);var E=`2.0.23`,D=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),O=t.createJsonErrorResponseHandler({errorSchema:D,errorToMessage:e=>e.error.message}),k=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),A=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function j(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var M=r.z.object({maxCharacters:r.z.number().optional()}),N=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),P=(e={})=>N(e),F=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ee=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),te=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ee}),I=(e={})=>te(e),L=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),R=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),z=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:R}),B=(e={})=>z(e);function V({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=j(t.providerOptions);o.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`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.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`:a.add(`computer-use-2024-10-22`),o.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`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=M.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=L.parse(t.args);o.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=F.parse(t.args);o.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:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var H=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),ne=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:H}),U=(e={})=>ne(e);function re(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 t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function W({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=ie(e),o,s=[];async function c(e){return(await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k}))?.citations?.enabled??!1}async function l(e){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k});return{title:n?.title,context:n?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:j(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=j(o.providerOptions)??(s?j(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:t.convertToBase64(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let n=await c(o.providerOptions),r=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:t.convertToBase64(o.data)},title:r.title??o.filename,...r.context&&{context:r.context},...n&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:re(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=j(i.providerOptions)??(o?j(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.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 t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let i=0;i<u.messages.length;i++){let a=u.messages[i],o=i===u.messages.length-1,{content:s}=a;for(let i=0;i<s.length;i++){let c=s[i],l=i===s.length-1,u=j(c.providerOptions)??(l?j(a.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:d&&o&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(n){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:c.providerOptions,schema:fe});n==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):n.signature==null?n.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:n.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:n.signature,cache_control:u})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){c.toolName===`code_execution`||c.toolName===`web_fetch`||c.toolName===`web_search`?e.push({type:`server_tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u}):r.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=H.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:u});break}if(c.toolName===`web_fetch`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=R.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:c.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:u});break}if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=ee.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}r.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function ie(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 G({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 ae={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},oe=r.z.discriminatedUnion(`type`,[ae.webSearchResult,ae.pageLocation,ae.charLocation]);r.z.discriminatedUnion(`type`,[ae.pageLocation,ae.charLocation]);function se(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=ce(e,t,n);i&&r(i)}}function ce(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 le=class{constructor(e,n){this.specificationVersion=`v2`,this.modelId=e,this.config=n,this.generateId=n.generateId??t.generateId}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:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await t.parseProviderOptions({provider:`anthropic`,providerOptions:p,schema:A}),{prompt:_,betas:v}=await W({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=V(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:n}){return t.combineHeaders(await t.resolve(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},n)}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:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(n),failedResponseHandler:O,successfulResponseHandler:t.createJsonResponseHandler(ue),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=[];for(let e of c.content)switch(e.type){case`text`:if(!a&&(u.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)se(t,o,this.generateId,e=>u.push(e));break;case`thinking`:u.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:u.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:u.push(a?{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`)&&u.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`?u.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`&&u.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)){u.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)u.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else u.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`?u.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`&&u.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:u,finishReason:G({finishReason:c.stop_reason,isJsonResponseFromTool:a}),usage:{inputTokens:c.usage.input_tokens,outputTokens:c.usage.output_tokens,totalTokens:c.usage.input_tokens+c.usage.output_tokens,cachedInputTokens:c.usage.cache_read_input_tokens??void 0},request:{body:n},response:{id:c.id??void 0,modelId:c.model??void 0,headers:s,body:l},warnings:r,providerMetadata:{anthropic:{usage:c.usage,cacheCreationInputTokens:c.usage.cache_creation_input_tokens??null,stopSequence:c.stop_sequence??null}}}}async doStream(e){let{args:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...n,stream:!0},{responseHeaders:c,value:l}=await t.postJsonToApi({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:O,successfulResponseHandler:t.createEventSourceResponseHandler(de),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=`unknown`,d={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},f={},p,m=null,h=null,g,_=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},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(g=e,e){case`text`:f[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:f[r.index]=a?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(a?{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`)&&(f[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:_(),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(f[r.index]!=null){let e=f[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`:a||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete f[r.index]}g=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(a)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`:g===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=f[r.index],t=r.delta.partial_json;if(a){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;se(e,o,_,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:d.inputTokens=r.message.usage.input_tokens,d.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,p={...r.message.usage},m=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`:d.outputTokens=r.usage.output_tokens,d.totalTokens=(d.inputTokens??0)+(r.usage.output_tokens??0),u=G({finishReason:r.delta.stop_reason,isJsonResponseFromTool:a}),h=r.delta.stop_sequence??null,p={...p,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:u,usage:d,providerMetadata:{anthropic:{usage:p??null,cacheCreationInputTokens:m,stopSequence:h}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:s},response:{headers:c}}}},ue=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(oe).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),de=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:oe})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),fe=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),pe=t.createProviderDefinedToolFactory({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),me=t.createProviderDefinedToolFactory({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),he=t.createProviderDefinedToolFactory({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),ge=t.createProviderDefinedToolFactory({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.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.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),K=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),_e=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ve=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ye={bash_20241022:pe,bash_20250124:me,codeExecution_20250522:U,computer_20241022:he,computer_20250124:ge,textEditor_20241022:K,textEditor_20250124:_e,textEditor_20250429:ve,textEditor_20250728:P,webFetch_20250910:B,webSearch_20250305:I};function be(e={}){let n=t.withoutTrailingSlash(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>t.withUserAgentSuffix({"anthropic-version":`2023-06-01`,"x-api-key":t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${E}`),i=i=>new le(i,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??t.generateId,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ye,a}var xe=be(),Se=`2.0.17`,Ce=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),we=t.createJsonErrorResponseHandler({errorSchema:Ce,errorToMessage:e=>e.error.message}),Te=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Ee=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:n,abortSignal:r,providerOptions:i}){let a=await t.parseProviderOptions({provider:`google`,providerOptions:i,schema:Te});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=t.combineHeaders(await t.resolve(this.config.headers),n);if(e.length===1){let{responseHeaders:n,value:i,rawValue:s}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:we,successfulResponseHandler:t.createJsonResponseHandler(Oe),abortSignal:r,fetch:this.config.fetch});return{embeddings:[i.embedding.values],usage:void 0,response:{headers:n,body:s}}}let{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:we,successfulResponseHandler:t.createJsonResponseHandler(De),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},De=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),Oe=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function q(e){if(e==null||ke(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 ke(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Ae(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let n of o)switch(n.type){case`text`:e.push({text:n.text});break;case`file`:{let r=n.mediaType===`image/*`?`image/jpeg`:n.mediaType;e.push(n.data instanceof URL?{fileData:{mimeType:r,fileUri:n.data.toString()}}:{inlineData:{mimeType:r,data:t.convertToBase64(n.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.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 t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:t.convertToBase64(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`:{a=!1;let e=[];for(let t of o){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}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
2
2
|
|
|
3
3
|
`);i[0].parts.unshift({text:e+`
|
|
4
4
|
|
|
@@ -252,7 +252,1137 @@ for await (const chunk of exa.streamAnswer(query)) {
|
|
|
252
252
|
// Handle chunks
|
|
253
253
|
}`,400);let n=t?.outputSchema;n&&_v(n)&&(n=vv(n));let r={query:e,stream:!1,text:t?.text??!1,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n,userLocation:t?.userLocation};return await this.request(`/answer`,`POST`,r)}async*streamAnswer(e,t){let n=t?.outputSchema;n&&_v(n)&&(n=vv(n));let r={query:e,text:t?.text??!1,stream:!0,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n},i=await jv(this.baseURL+`/answer`,{method:`POST`,headers:this.headers,body:JSON.stringify(r)});if(!i.ok){let e=await i.text();throw new gv(e,i.status,new Date().toISOString())}let a=i.body?.getReader();if(!a)throw new gv(`No response body available for streaming.`,500,new Date().toISOString());let o=new TextDecoder,s=``;try{for(;;){let{done:e,value:t}=await a.read();if(e)break;s+=o.decode(t,{stream:!0});let n=s.split(`
|
|
254
254
|
`);s=n.pop()||``;for(let e of n){if(!e.startsWith(`data: `))continue;let t=e.replace(/^data:\s*/,``).trim();if(!t||t===`[DONE]`)continue;let n;try{n=JSON.parse(t)}catch{continue}let r=this.processChunk(n);(r.content||r.citations)&&(yield r)}}if(s.startsWith(`data: `)){let e=s.replace(/^data:\s*/,``).trim();if(e&&e!==`[DONE]`)try{let t=JSON.parse(e),n=this.processChunk(t);(n.content||n.citations)&&(yield n)}catch{}}}finally{a.releaseLock()}}processChunk(e){let t,n;return e.choices&&e.choices[0]&&e.choices[0].delta&&(t=e.choices[0].delta.content),e.citations&&e.citations!==`null`&&(n=e.citations.map(e=>({id:e.id,url:e.url,title:e.title,publishedDate:e.publishedDate,author:e.author,text:e.text}))),{content:t,citations:n}}async parseSSEStream(e){let t=e.body?.getReader();if(!t)throw new gv(`No response body available for streaming.`,500,new Date().toISOString());let n=new TextDecoder,r=``;return new Promise(async(e,i)=>{try{for(;;){let{done:a,value:o}=await t.read();if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
255
|
-
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new gv(e,500,new Date().toISOString()));return}default:break}}}i(new gv(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const Pv=()=>{let e;if(process.env.EXA_API_KEY)e=new Nv(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new Nv(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new Nv(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},Fv={web_search:n_({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:y.z.object({query:y.z.string()}),execute:async({query:e})=>await Pv().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})};function Iv(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Lv=y.z.union([y.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),y.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),y.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),y.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),y.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),y.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),y.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),y.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),y.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),y.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),y.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),y.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),y.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),y.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),y.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),y.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),y.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),y.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),y.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),y.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),y.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),y.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),y.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),y.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),y.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),y.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),y.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),y.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),y.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),y.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),y.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),y.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),y.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),y.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),y.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Rv=y.z.union([y.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),y.z.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`),y.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),y.z.literal(`channels:join`).describe(`Join public channels`),y.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),y.z.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`),y.z.literal(`chat:write`).describe(`Send messages as the bot`),y.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),y.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),y.z.literal(`commands`).describe(`Add and use slash commands`),y.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),y.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),y.z.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`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files`),y.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),y.z.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`),y.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),y.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),y.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),y.z.literal(`im:write`).describe(`Start and manage direct messages with users`),y.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),y.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),y.z.literal(`metadata.message:read`).describe(`Read message metadata`),y.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),y.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),y.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),y.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),y.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),y.z.literal(`reminders:read`).describe(`View reminders created by the bot`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),y.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),y.z.literal(`usergroups:read`).describe(`View user groups and their members`),y.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),y.z.literal(`users.profile:read`).describe(`View profile information about users`),y.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),y.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),y.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),zv=y.z.union([y.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),y.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),y.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),y.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),y.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),y.z.literal(`files:read`).describe(`View files on behalf of the user`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),y.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),y.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),y.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),y.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),y.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),y.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),y.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),y.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),y.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),y.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),y.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),y.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),y.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),y.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),y.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),y.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),y.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),y.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),y.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),y.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),y.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),y.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),y.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),y.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),y.z.literal(`users:write`).describe(`Set presence for the user`)]),Bv=y.z.object({display_information:y.z.object({name:y.z.string().describe(`The name of the Slack app.`),description:y.z.string().optional().describe(`A short description of the app.`),background_color:y.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:y.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:y.z.object({bot_user:y.z.object({display_name:y.z.string().describe(`The display name for the bot user.`),always_online:y.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:y.z.object({home_tab_enabled:y.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:y.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:y.z.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:y.z.object({assistant_description:y.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:y.z.array(y.z.object({command:y.z.string().regex(/^\//).describe(`The command (must start with /).`),description:y.z.string().describe(`Description of the command.`),usage_hint:y.z.string().optional().describe(`Usage hint for the command.`),should_escape:y.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:y.z.array(y.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:y.z.object({redirect_urls:y.z.array(y.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:y.z.object({bot:y.z.array(y.z.union([Rv,y.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:y.z.array(y.z.union([zv,y.z.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:y.z.object({event_subscriptions:y.z.object({request_url:y.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:y.z.array(y.z.union([Lv,y.z.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:y.z.object({is_enabled:y.z.boolean().describe(`Enable interactivity.`),request_url:y.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:y.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:y.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:y.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:y.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});var Vv=e.__toESM(fc());function Hv(e,n,r){let i,a=u.default.createServer(t.createServerAdapter(async t=>{let o=new URL(t.url,i);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await r?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await r?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let n=t.message;return new Response(`Error: ${n}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{a.close()}let c={...e,redirect_url:i},l=`<!DOCTYPE html>
|
|
255
|
+
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new gv(e,500,new Date().toISOString()));return}default:break}}}i(new gv(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const Pv=()=>{let e;if(process.env.EXA_API_KEY)e=new Nv(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new Nv(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new Nv(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},Fv={web_search:n_({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:y.z.object({query:y.z.string()}),execute:async({query:e})=>await Pv().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})},Iv={scratch:{"agent.ts":`import { convertToModelMessages, streamText, tool } from "ai";
|
|
256
|
+
import * as blink from "blink";
|
|
257
|
+
import { z } from "zod";
|
|
258
|
+
|
|
259
|
+
const agent = blink.agent();
|
|
260
|
+
|
|
261
|
+
agent.on("chat", async ({ messages }) => {
|
|
262
|
+
return streamText({
|
|
263
|
+
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
264
|
+
system: \`You are a basic agent the user will customize.
|
|
265
|
+
|
|
266
|
+
Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
|
|
267
|
+
Demonstrate your capabilities with the IP tool.\`,
|
|
268
|
+
messages: convertToModelMessages(messages),
|
|
269
|
+
tools: {
|
|
270
|
+
get_ip_info: tool({
|
|
271
|
+
description: "Get IP address information of the computer.",
|
|
272
|
+
inputSchema: z.object({}),
|
|
273
|
+
execute: async () => {
|
|
274
|
+
const response = await fetch("https://ipinfo.io/json");
|
|
275
|
+
return response.json();
|
|
276
|
+
},
|
|
277
|
+
}),
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
agent.serve();
|
|
283
|
+
`,"package.json":`{
|
|
284
|
+
"name": "{{name}}",
|
|
285
|
+
"main": "agent.ts",
|
|
286
|
+
"type": "module",
|
|
287
|
+
"private": true,
|
|
288
|
+
"scripts": {
|
|
289
|
+
"dev": "blink dev",
|
|
290
|
+
"deploy": "blink deploy"
|
|
291
|
+
},
|
|
292
|
+
"devDependencies": {
|
|
293
|
+
"zod": "latest",
|
|
294
|
+
"ai": "latest",
|
|
295
|
+
"blink": "latest",
|
|
296
|
+
"esbuild": "latest",
|
|
297
|
+
"@types/node": "latest",
|
|
298
|
+
"typescript": "latest"
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
`,".gitignore":`# dependencies
|
|
302
|
+
node_modules
|
|
303
|
+
|
|
304
|
+
# config and build
|
|
305
|
+
data
|
|
306
|
+
|
|
307
|
+
# dotenv environment variables file
|
|
308
|
+
.env
|
|
309
|
+
.env.*
|
|
310
|
+
|
|
311
|
+
# Finder (MacOS) folder config
|
|
312
|
+
.DS_Store
|
|
313
|
+
`,"tsconfig.json":`{
|
|
314
|
+
"compilerOptions": {
|
|
315
|
+
"lib": ["ESNext"],
|
|
316
|
+
"target": "ESNext",
|
|
317
|
+
"module": "Preserve",
|
|
318
|
+
"moduleDetection": "force",
|
|
319
|
+
|
|
320
|
+
"moduleResolution": "bundler",
|
|
321
|
+
"allowImportingTsExtensions": true,
|
|
322
|
+
"verbatimModuleSyntax": true,
|
|
323
|
+
"resolveJsonModule": true,
|
|
324
|
+
"noEmit": true,
|
|
325
|
+
|
|
326
|
+
"strict": true,
|
|
327
|
+
"skipLibCheck": true,
|
|
328
|
+
"noFallthroughCasesInSwitch": true,
|
|
329
|
+
"noUncheckedIndexedAccess": true,
|
|
330
|
+
"noImplicitOverride": true,
|
|
331
|
+
|
|
332
|
+
"noUnusedLocals": false,
|
|
333
|
+
"noUnusedParameters": false,
|
|
334
|
+
|
|
335
|
+
"types": ["node"]
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
`,"AGENTS.md":`This project is a Blink agent.
|
|
339
|
+
|
|
340
|
+
You are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.
|
|
341
|
+
|
|
342
|
+
<communication>
|
|
343
|
+
1. Be concise, direct, and to the point.
|
|
344
|
+
2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
|
|
345
|
+
3. NEVER use emojis unless the user explicitly asks for them.
|
|
346
|
+
4. You must avoid text before/after your response, such as "The answer is" or "Short answer:", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".
|
|
347
|
+
5. Mimic the style of the user's messages.
|
|
348
|
+
6. Do not remind the user you are happy to help.
|
|
349
|
+
7. Do not act with sycophantic flattery or over-the-top enthusiasm.
|
|
350
|
+
8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
|
|
351
|
+
9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
|
|
352
|
+
10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
|
|
353
|
+
</communication>
|
|
354
|
+
|
|
355
|
+
<goals>
|
|
356
|
+
Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
|
|
357
|
+
|
|
358
|
+
You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
|
|
359
|
+
|
|
360
|
+
The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
|
|
361
|
+
|
|
362
|
+
<example>
|
|
363
|
+
user: i want a coding agent
|
|
364
|
+
assistant: Let me take a look at your codebase...
|
|
365
|
+
... tool calls to investigate the codebase...
|
|
366
|
+
assistant: I've created tools for linting, testing, and formatting. Hop back in run mode to use your agent! If you ever encounter undesired behavior from your agent, switch back to edit mode to refine your agent.
|
|
367
|
+
</example>
|
|
368
|
+
|
|
369
|
+
Always investigate the current state of the agent before assisting the user.
|
|
370
|
+
</goals>
|
|
371
|
+
|
|
372
|
+
<agent_development>
|
|
373
|
+
Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
|
|
374
|
+
|
|
375
|
+
Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
|
|
376
|
+
|
|
377
|
+
Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
|
|
378
|
+
|
|
379
|
+
1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
|
|
380
|
+
2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
|
|
381
|
+
3. Test your changes to the user's agent by using the \`message_user_agent\` tool. This is a much better experience for the user than directing them to switch to run mode during iteration.
|
|
382
|
+
4. Use console.log for debugging. The console output appears for the user.
|
|
383
|
+
5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
|
|
384
|
+
6. Output tokens can be increased using the \`maxOutputTokens\` option on \`streamText\` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.
|
|
385
|
+
7. Use the TypeScript language service tools (\`typescript_completions\`, \`typescript_quickinfo\`, \`typescript_definition\`, \`typescript_diagnostics\`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.
|
|
386
|
+
|
|
387
|
+
If the user is asking for a behavioral change, you should update the agent's system prompt.
|
|
388
|
+
This will not ensure the behavior, but it will guide the agent towards the desired behavior.
|
|
389
|
+
If the user needs 100% behavioral certainty, adjust tool behavior instead.
|
|
390
|
+
</agent_development>
|
|
391
|
+
|
|
392
|
+
<agent_web_requests>
|
|
393
|
+
Agents are HTTP servers, so they can handle web requests. This is commonly used to async-invoke an agent. e.g. for a Slack bot, messages are sent to the agent via a webhook.
|
|
394
|
+
|
|
395
|
+
Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
|
|
396
|
+
|
|
397
|
+
To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
|
|
398
|
+
</agent_web_requests>
|
|
399
|
+
|
|
400
|
+
<technical_knowledge>
|
|
401
|
+
Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
|
|
402
|
+
|
|
403
|
+
\`\`\`typescript
|
|
404
|
+
import { convertToModelMessages, streamText } from "ai";
|
|
405
|
+
import * as blink from "blink";
|
|
406
|
+
|
|
407
|
+
const agent = new blink.Agent();
|
|
408
|
+
|
|
409
|
+
agent.on("chat", async ({ messages, chat, abortSignal }) => {
|
|
410
|
+
return streamText({
|
|
411
|
+
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
412
|
+
system: "You are a helpful assistant.",
|
|
413
|
+
messages: convertToModelMessages(messages, {
|
|
414
|
+
ignoreIncompleteToolCalls: true,
|
|
415
|
+
}),
|
|
416
|
+
tools: {
|
|
417
|
+
/* your tools */
|
|
418
|
+
},
|
|
419
|
+
});
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
agent.on("request", async (request) => {
|
|
423
|
+
// Handle webhooks, OAuth callbacks, etc.
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
agent.serve();
|
|
427
|
+
\`\`\`
|
|
428
|
+
|
|
429
|
+
Event Handlers:
|
|
430
|
+
|
|
431
|
+
**\`agent.on("chat", handler)\`**
|
|
432
|
+
|
|
433
|
+
1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
|
|
434
|
+
2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
|
|
435
|
+
3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
|
|
436
|
+
|
|
437
|
+
_NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
|
|
438
|
+
|
|
439
|
+
**\`agent.on("request", handler)\`**
|
|
440
|
+
• Handles raw HTTP requests before Blink processes them
|
|
441
|
+
• Use for: OAuth callbacks, webhook verification, custom endpoints
|
|
442
|
+
• Return \`Response\` to handle, or \`void\` to pass through
|
|
443
|
+
|
|
444
|
+
**\`agent.on("ui", handler)\`**
|
|
445
|
+
• Provides dynamic UI options for chat interfaces
|
|
446
|
+
• Returns schema defining user-selectable options
|
|
447
|
+
|
|
448
|
+
**\`agent.on("error", handler)\`**
|
|
449
|
+
• Global error handler for the agent
|
|
450
|
+
|
|
451
|
+
Chat Management:
|
|
452
|
+
|
|
453
|
+
Blink automatically manages chat state:
|
|
454
|
+
|
|
455
|
+
\`\`\`typescript
|
|
456
|
+
// Create or get existing chat
|
|
457
|
+
// The parameter can be any JSON-serializable value.
|
|
458
|
+
// e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
|
|
459
|
+
const chat = await agent.chat.upsert("unique-key");
|
|
460
|
+
|
|
461
|
+
// Send a message to a chat
|
|
462
|
+
await agent.chat.sendMessages(
|
|
463
|
+
chat.id,
|
|
464
|
+
[
|
|
465
|
+
{
|
|
466
|
+
role: "user",
|
|
467
|
+
parts: [{ type: "text", text: "Message" }],
|
|
468
|
+
},
|
|
469
|
+
],
|
|
470
|
+
{
|
|
471
|
+
behavior: "interrupt" | "enqueue" | "append",
|
|
472
|
+
}
|
|
473
|
+
);
|
|
474
|
+
|
|
475
|
+
// When sending messages, feel free to inject additional parts to direct the model.
|
|
476
|
+
// e.g. if the user is asking for specific behavior in specific scenarios, the simplest
|
|
477
|
+
// answer is to append a text part: "always do X when Y".
|
|
478
|
+
\`\`\`
|
|
479
|
+
|
|
480
|
+
Behaviors:
|
|
481
|
+
• "interrupt": Stop current processing and handle immediately
|
|
482
|
+
• "enqueue": Queue message, process when current chat finishes
|
|
483
|
+
• "append": Add to history without triggering processing
|
|
484
|
+
|
|
485
|
+
Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
|
|
486
|
+
|
|
487
|
+
Storage API:
|
|
488
|
+
|
|
489
|
+
Persistent key-value storage per agent:
|
|
490
|
+
|
|
491
|
+
\`\`\`typescript
|
|
492
|
+
// Store data
|
|
493
|
+
await agent.store.set("key", "value", { ttl: 3600 });
|
|
494
|
+
|
|
495
|
+
// Retrieve data
|
|
496
|
+
const value = await agent.store.get("key");
|
|
497
|
+
|
|
498
|
+
// Delete data
|
|
499
|
+
await agent.store.delete("key");
|
|
500
|
+
|
|
501
|
+
// List keys by prefix
|
|
502
|
+
const result = await agent.store.list("prefix-", { limit: 100 });
|
|
503
|
+
\`\`\`
|
|
504
|
+
|
|
505
|
+
Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
|
|
506
|
+
|
|
507
|
+
Tools:
|
|
508
|
+
|
|
509
|
+
Tools follow Vercel AI SDK patterns with Zod validation:
|
|
510
|
+
|
|
511
|
+
\`\`\`typescript
|
|
512
|
+
import { tool } from "ai";
|
|
513
|
+
import { z } from "zod";
|
|
514
|
+
|
|
515
|
+
const myTool = tool({
|
|
516
|
+
description: "Clear description of what this tool does",
|
|
517
|
+
inputSchema: z.object({
|
|
518
|
+
param: z.string().describe("Parameter description"),
|
|
519
|
+
}),
|
|
520
|
+
execute: async (args, opts) => {
|
|
521
|
+
// opts.abortSignal for cancellation
|
|
522
|
+
// opts.toolCallId for unique identification
|
|
523
|
+
return result;
|
|
524
|
+
},
|
|
525
|
+
});
|
|
526
|
+
\`\`\`
|
|
527
|
+
|
|
528
|
+
Tool Approvals for destructive operations:
|
|
529
|
+
|
|
530
|
+
\`\`\`typescript
|
|
531
|
+
...await blink.tools.withApproval({
|
|
532
|
+
messages,
|
|
533
|
+
tools: {
|
|
534
|
+
delete_database: tool({ /* ... */ }),
|
|
535
|
+
},
|
|
536
|
+
})
|
|
537
|
+
\`\`\`
|
|
538
|
+
|
|
539
|
+
Tool Context for dependency injection:
|
|
540
|
+
|
|
541
|
+
\`\`\`typescript
|
|
542
|
+
...blink.tools.withContext(github.tools, {
|
|
543
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
544
|
+
})
|
|
545
|
+
\`\`\`
|
|
546
|
+
|
|
547
|
+
Tool Prefixing to avoid collisions:
|
|
548
|
+
|
|
549
|
+
\`\`\`typescript
|
|
550
|
+
...blink.tools.prefix(github.tools, "github_")
|
|
551
|
+
\`\`\`
|
|
552
|
+
|
|
553
|
+
LLM Models:
|
|
554
|
+
|
|
555
|
+
**Option 1: Blink Gateway** (Quick Start)
|
|
556
|
+
|
|
557
|
+
\`\`\`typescript
|
|
558
|
+
model: blink.model("anthropic/claude-sonnet-4.5");
|
|
559
|
+
model: blink.model("openai/gpt-5");
|
|
560
|
+
\`\`\`
|
|
561
|
+
|
|
562
|
+
Requires: \`blink login\` or \`BLINK_TOKEN\` env var
|
|
563
|
+
|
|
564
|
+
**Option 2: Direct Provider** (Production Recommended)
|
|
565
|
+
|
|
566
|
+
\`\`\`typescript
|
|
567
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
568
|
+
import { openai } from "@ai-sdk/openai";
|
|
569
|
+
|
|
570
|
+
model: anthropic("claude-sonnet-4.5", {
|
|
571
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
572
|
+
});
|
|
573
|
+
model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
574
|
+
\`\`\`
|
|
575
|
+
|
|
576
|
+
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
577
|
+
|
|
578
|
+
1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
|
|
579
|
+
2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
|
|
580
|
+
3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
|
|
581
|
+
|
|
582
|
+
Available SDKs:
|
|
583
|
+
|
|
584
|
+
**@blink-sdk/compute**
|
|
585
|
+
|
|
586
|
+
\`\`\`typescript
|
|
587
|
+
import * as compute from "@blink-sdk/compute";
|
|
588
|
+
|
|
589
|
+
tools: {
|
|
590
|
+
...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
|
|
591
|
+
}
|
|
592
|
+
\`\`\`
|
|
593
|
+
|
|
594
|
+
**@blink-sdk/github**
|
|
595
|
+
|
|
596
|
+
\`\`\`typescript
|
|
597
|
+
import * as github from "@blink-sdk/github";
|
|
598
|
+
|
|
599
|
+
tools: {
|
|
600
|
+
...blink.tools.withContext(github.tools, {
|
|
601
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
602
|
+
}),
|
|
603
|
+
}
|
|
604
|
+
\`\`\`
|
|
605
|
+
|
|
606
|
+
**@blink-sdk/slack**
|
|
607
|
+
|
|
608
|
+
\`\`\`typescript
|
|
609
|
+
import * as slack from "@blink-sdk/slack";
|
|
610
|
+
import { App } from "@slack/bolt";
|
|
611
|
+
|
|
612
|
+
const receiver = new slack.Receiver();
|
|
613
|
+
const app = new App({
|
|
614
|
+
token: process.env.SLACK_BOT_TOKEN,
|
|
615
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
616
|
+
receiver,
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
// This will trigger when the bot is @mentioned.
|
|
620
|
+
app.event("app_mention", async ({ event }) => {
|
|
621
|
+
// The argument here is a JSON-serializable value.
|
|
622
|
+
// To maintain the same chat context, use the same key.
|
|
623
|
+
const chat = await agent.chat.upsert([
|
|
624
|
+
"slack",
|
|
625
|
+
event.channel,
|
|
626
|
+
event.thread_ts ?? event.ts,
|
|
627
|
+
]);
|
|
628
|
+
const { message } = await slack.createMessageFromEvent({
|
|
629
|
+
client: app.client,
|
|
630
|
+
event,
|
|
631
|
+
});
|
|
632
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
633
|
+
// This is a nice immediate indicator for the user.
|
|
634
|
+
await app.client.assistant.threads.setStatus({
|
|
635
|
+
channel_id: event.channel,
|
|
636
|
+
status: "is typing...",
|
|
637
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
638
|
+
});
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
const agent = new blink.Agent();
|
|
642
|
+
|
|
643
|
+
agent.on("request", async (request) => {
|
|
644
|
+
return receiver.handle(app, request);
|
|
645
|
+
});
|
|
646
|
+
|
|
647
|
+
agent.on("chat", async ({ messages }) => {
|
|
648
|
+
const tools = slack.createTools({ client: app.client });
|
|
649
|
+
return streamText({
|
|
650
|
+
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
651
|
+
system: "You chatting with users in Slack.",
|
|
652
|
+
messages: convertToModelMessages(messages, {
|
|
653
|
+
ignoreIncompleteToolCalls: true,
|
|
654
|
+
tools,
|
|
655
|
+
}),
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
\`\`\`
|
|
659
|
+
|
|
660
|
+
Slack SDK Notes:
|
|
661
|
+
|
|
662
|
+
- "app_mention" event is triggered in both private channels and public channels.
|
|
663
|
+
- "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
|
|
664
|
+
- _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
|
|
665
|
+
- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.
|
|
666
|
+
- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. \`message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${channel} thread_ts=\${thread_ts}" })\`
|
|
667
|
+
- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".
|
|
668
|
+
|
|
669
|
+
Slack App Manifest:
|
|
670
|
+
|
|
671
|
+
- _ALWAYS_ include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You _MUST_ provide "assistant_view" if you provide this scope.
|
|
672
|
+
- The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
673
|
+
- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
|
|
674
|
+
- _ALWAYS_ default "token_rotation_enabled" to false unless the user explicitly asks for it. It is a _much_ simpler user-experience to not rotate tokens.
|
|
675
|
+
- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
|
|
676
|
+
- "app_mentions:read"
|
|
677
|
+
- "reactions:write"
|
|
678
|
+
- "reactions:read"
|
|
679
|
+
- "channels:history"
|
|
680
|
+
- "chat:write"
|
|
681
|
+
- "groups:history"
|
|
682
|
+
- "groups:read"
|
|
683
|
+
- "files:read"
|
|
684
|
+
- "im:history"
|
|
685
|
+
- "im:read"
|
|
686
|
+
- "im:write"
|
|
687
|
+
- "mpim:history"
|
|
688
|
+
- "mpim:read"
|
|
689
|
+
- "users:read"
|
|
690
|
+
- "links:read"
|
|
691
|
+
- "commands"
|
|
692
|
+
- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
|
|
693
|
+
- "app_mention"
|
|
694
|
+
- "message.channels",
|
|
695
|
+
- "message.groups",
|
|
696
|
+
- "message.im",
|
|
697
|
+
- "reaction_added"
|
|
698
|
+
- "reaction_removed"
|
|
699
|
+
- "assistant_thread_started"
|
|
700
|
+
- "member_joined_channel"
|
|
701
|
+
- _NEVER_ include USER SCOPES unless the user explicitly asks for them.
|
|
702
|
+
|
|
703
|
+
WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
|
|
704
|
+
|
|
705
|
+
**@blink-sdk/web-search**
|
|
706
|
+
|
|
707
|
+
\`\`\`typescript
|
|
708
|
+
import * as webSearch from "@blink-sdk/web-search";
|
|
709
|
+
|
|
710
|
+
tools: {
|
|
711
|
+
...webSearch.tools,
|
|
712
|
+
}
|
|
713
|
+
\`\`\`
|
|
714
|
+
|
|
715
|
+
State Management:
|
|
716
|
+
|
|
717
|
+
Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
|
|
718
|
+
|
|
719
|
+
_NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
|
|
720
|
+
|
|
721
|
+
For global state persistence, you can use the agent store:
|
|
722
|
+
|
|
723
|
+
- Use \`agent.store\` for persistent key-value storage
|
|
724
|
+
- Query external APIs to fetch current state
|
|
725
|
+
- Use webhooks to trigger actions rather than polling in-memory state
|
|
726
|
+
|
|
727
|
+
For message-level state persistence, use message metadata:
|
|
728
|
+
|
|
729
|
+
\`\`\`typescript
|
|
730
|
+
import { UIMessage } from "blink";
|
|
731
|
+
import * as blink from "blink";
|
|
732
|
+
|
|
733
|
+
const agent = new blink.Agent<
|
|
734
|
+
UIMessage<{
|
|
735
|
+
source: "github";
|
|
736
|
+
associated_id: string;
|
|
737
|
+
}>
|
|
738
|
+
>();
|
|
739
|
+
|
|
740
|
+
agent.on("request", async (request) => {
|
|
741
|
+
// comes from github, we want to do something deterministic in the chat loop with that ID...
|
|
742
|
+
// insert a message with that metadata into the chat
|
|
743
|
+
const chat = await agent.chat.upsert("some-github-key");
|
|
744
|
+
await agent.chat.sendMessages(request.chat.id, [
|
|
745
|
+
{
|
|
746
|
+
role: "user",
|
|
747
|
+
parts: [
|
|
748
|
+
{
|
|
749
|
+
type: "text",
|
|
750
|
+
text: "example",
|
|
751
|
+
},
|
|
752
|
+
],
|
|
753
|
+
metadata: {
|
|
754
|
+
source: "github",
|
|
755
|
+
associated_id: "some-github-id",
|
|
756
|
+
},
|
|
757
|
+
},
|
|
758
|
+
]);
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
agent.on("chat", async ({ messages }) => {
|
|
762
|
+
const message = messages.find(
|
|
763
|
+
(message) => message.metadata?.source === "github"
|
|
764
|
+
);
|
|
765
|
+
|
|
766
|
+
// Now we can use that metadata...
|
|
767
|
+
});
|
|
768
|
+
\`\`\`
|
|
769
|
+
|
|
770
|
+
The agent process can restart at any time, so all important state must be externalized.
|
|
771
|
+
</technical_knowledge>
|
|
772
|
+
|
|
773
|
+
<code_quality>
|
|
774
|
+
|
|
775
|
+
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
776
|
+
</code_quality>
|
|
777
|
+
`,".env.local":`
|
|
778
|
+
# Store local environment variables here.
|
|
779
|
+
# They will be used by blink dev for development.
|
|
780
|
+
# EXTERNAL_SERVICE_API_KEY=
|
|
781
|
+
`,".env.production":`
|
|
782
|
+
# Store production environment variables here.
|
|
783
|
+
# They will be upserted as secrets on blink deploy.
|
|
784
|
+
# EXTERNAL_SERVICE_API_KEY=
|
|
785
|
+
`},"slack-bot":{"agent.ts":`import { convertToModelMessages, streamText } from "ai";
|
|
786
|
+
import * as blink from "blink";
|
|
787
|
+
import * as slack from "@blink-sdk/slack";
|
|
788
|
+
import { App } from "@slack/bolt";
|
|
789
|
+
|
|
790
|
+
const receiver = new slack.Receiver();
|
|
791
|
+
const app = new App({
|
|
792
|
+
token: process.env.SLACK_BOT_TOKEN,
|
|
793
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
794
|
+
receiver,
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
// Handle messages in channels (only when @mentioned)
|
|
798
|
+
app.event("app_mention", async ({ event }) => {
|
|
799
|
+
const chat = await agent.chat.upsert([
|
|
800
|
+
"slack",
|
|
801
|
+
event.channel,
|
|
802
|
+
event.thread_ts ?? event.ts,
|
|
803
|
+
]);
|
|
804
|
+
const { message } = await slack.createMessageFromEvent({
|
|
805
|
+
client: app.client,
|
|
806
|
+
event,
|
|
807
|
+
});
|
|
808
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
809
|
+
await app.client.assistant.threads.setStatus({
|
|
810
|
+
channel_id: event.channel,
|
|
811
|
+
status: "is typing...",
|
|
812
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
813
|
+
});
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
// Handle direct messages (always respond)
|
|
817
|
+
app.event("message", async ({ event }) => {
|
|
818
|
+
// Ignore bot messages and message changes
|
|
819
|
+
if (event.subtype || event.bot_id) {
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
// Only handle DMs (channel type is 'im')
|
|
823
|
+
const channelInfo = await app.client.conversations.info({
|
|
824
|
+
channel: event.channel,
|
|
825
|
+
});
|
|
826
|
+
if (!channelInfo.channel?.is_im) {
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
const chat = await agent.chat.upsert(["slack", event.channel]);
|
|
830
|
+
const { message } = await slack.createMessageFromEvent({
|
|
831
|
+
client: app.client,
|
|
832
|
+
event,
|
|
833
|
+
});
|
|
834
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
835
|
+
await app.client.assistant.threads.setStatus({
|
|
836
|
+
channel_id: event.channel,
|
|
837
|
+
status: "is typing...",
|
|
838
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
839
|
+
});
|
|
840
|
+
});
|
|
841
|
+
const agent = new blink.Agent();
|
|
842
|
+
|
|
843
|
+
agent.on("request", async (request) => {
|
|
844
|
+
return receiver.handle(app, request);
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
agent.on("chat", async ({ messages }) => {
|
|
848
|
+
const tools = slack.createTools({ client: app.client });
|
|
849
|
+
const lastMessage = messages[messages.length - 1];
|
|
850
|
+
const threadInfo = lastMessage?.metadata as
|
|
851
|
+
| { channel?: string; thread_ts?: string }
|
|
852
|
+
| undefined;
|
|
853
|
+
|
|
854
|
+
// Add instruction to clear status after completion
|
|
855
|
+
if (threadInfo?.channel && threadInfo?.thread_ts) {
|
|
856
|
+
const clonedMessages = structuredClone(messages);
|
|
857
|
+
const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
|
|
858
|
+
if (lastClonedMessage) {
|
|
859
|
+
lastClonedMessage.parts.push({
|
|
860
|
+
type: "text",
|
|
861
|
+
text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
messages = clonedMessages;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
return streamText({
|
|
868
|
+
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
869
|
+
system: "You are a helpful Slack bot assistant.",
|
|
870
|
+
messages: convertToModelMessages(messages, {
|
|
871
|
+
ignoreIncompleteToolCalls: true,
|
|
872
|
+
tools,
|
|
873
|
+
}),
|
|
874
|
+
tools,
|
|
875
|
+
});
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
agent.serve();
|
|
879
|
+
`,"package.json":`{
|
|
880
|
+
"name": "{{name}}",
|
|
881
|
+
"main": "agent.ts",
|
|
882
|
+
"type": "module",
|
|
883
|
+
"private": true,
|
|
884
|
+
"scripts": {
|
|
885
|
+
"dev": "blink dev",
|
|
886
|
+
"deploy": "blink deploy"
|
|
887
|
+
},
|
|
888
|
+
"devDependencies": {
|
|
889
|
+
"zod": "latest",
|
|
890
|
+
"ai": "latest",
|
|
891
|
+
"blink": "latest",
|
|
892
|
+
"esbuild": "latest",
|
|
893
|
+
"@types/node": "latest",
|
|
894
|
+
"typescript": "latest",
|
|
895
|
+
"@slack/bolt": "latest",
|
|
896
|
+
"@blink-sdk/slack": "latest"
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
`,".gitignore":`# dependencies
|
|
900
|
+
node_modules
|
|
901
|
+
|
|
902
|
+
# config and build
|
|
903
|
+
data
|
|
904
|
+
|
|
905
|
+
# dotenv environment variables file
|
|
906
|
+
.env
|
|
907
|
+
.env.*
|
|
908
|
+
|
|
909
|
+
# Finder (MacOS) folder config
|
|
910
|
+
.DS_Store
|
|
911
|
+
`,"tsconfig.json":`{
|
|
912
|
+
"compilerOptions": {
|
|
913
|
+
"lib": ["ESNext"],
|
|
914
|
+
"target": "ESNext",
|
|
915
|
+
"module": "Preserve",
|
|
916
|
+
"moduleDetection": "force",
|
|
917
|
+
|
|
918
|
+
"moduleResolution": "bundler",
|
|
919
|
+
"allowImportingTsExtensions": true,
|
|
920
|
+
"verbatimModuleSyntax": true,
|
|
921
|
+
"resolveJsonModule": true,
|
|
922
|
+
"noEmit": true,
|
|
923
|
+
|
|
924
|
+
"strict": true,
|
|
925
|
+
"skipLibCheck": true,
|
|
926
|
+
"noFallthroughCasesInSwitch": true,
|
|
927
|
+
"noUncheckedIndexedAccess": true,
|
|
928
|
+
"noImplicitOverride": true,
|
|
929
|
+
|
|
930
|
+
"noUnusedLocals": false,
|
|
931
|
+
"noUnusedParameters": false,
|
|
932
|
+
|
|
933
|
+
"types": ["node"]
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
`,"AGENTS.md":`This project is a Blink agent.
|
|
937
|
+
|
|
938
|
+
You are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.
|
|
939
|
+
|
|
940
|
+
<communication>
|
|
941
|
+
1. Be concise, direct, and to the point.
|
|
942
|
+
2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
|
|
943
|
+
3. NEVER use emojis unless the user explicitly asks for them.
|
|
944
|
+
4. You must avoid text before/after your response, such as "The answer is" or "Short answer:", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".
|
|
945
|
+
5. Mimic the style of the user's messages.
|
|
946
|
+
6. Do not remind the user you are happy to help.
|
|
947
|
+
7. Do not act with sycophantic flattery or over-the-top enthusiasm.
|
|
948
|
+
8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
|
|
949
|
+
9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
|
|
950
|
+
10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
|
|
951
|
+
</communication>
|
|
952
|
+
|
|
953
|
+
<goals>
|
|
954
|
+
Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
|
|
955
|
+
|
|
956
|
+
You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
|
|
957
|
+
|
|
958
|
+
The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
|
|
959
|
+
|
|
960
|
+
<example>
|
|
961
|
+
user: i want a coding agent
|
|
962
|
+
assistant: Let me take a look at your codebase...
|
|
963
|
+
... tool calls to investigate the codebase...
|
|
964
|
+
assistant: I've created tools for linting, testing, and formatting. Hop back in run mode to use your agent! If you ever encounter undesired behavior from your agent, switch back to edit mode to refine your agent.
|
|
965
|
+
</example>
|
|
966
|
+
|
|
967
|
+
Always investigate the current state of the agent before assisting the user.
|
|
968
|
+
</goals>
|
|
969
|
+
|
|
970
|
+
<agent_development>
|
|
971
|
+
Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
|
|
972
|
+
|
|
973
|
+
Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
|
|
974
|
+
|
|
975
|
+
Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
|
|
976
|
+
|
|
977
|
+
1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
|
|
978
|
+
2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
|
|
979
|
+
3. Test your changes to the user's agent by using the \`message_user_agent\` tool. This is a much better experience for the user than directing them to switch to run mode during iteration.
|
|
980
|
+
4. Use console.log for debugging. The console output appears for the user.
|
|
981
|
+
5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
|
|
982
|
+
6. Output tokens can be increased using the \`maxOutputTokens\` option on \`streamText\` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.
|
|
983
|
+
7. Use the TypeScript language service tools (\`typescript_completions\`, \`typescript_quickinfo\`, \`typescript_definition\`, \`typescript_diagnostics\`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.
|
|
984
|
+
|
|
985
|
+
If the user is asking for a behavioral change, you should update the agent's system prompt.
|
|
986
|
+
This will not ensure the behavior, but it will guide the agent towards the desired behavior.
|
|
987
|
+
If the user needs 100% behavioral certainty, adjust tool behavior instead.
|
|
988
|
+
</agent_development>
|
|
989
|
+
|
|
990
|
+
<agent_web_requests>
|
|
991
|
+
Agents are HTTP servers, so they can handle web requests. This is commonly used to async-invoke an agent. e.g. for a Slack bot, messages are sent to the agent via a webhook.
|
|
992
|
+
|
|
993
|
+
Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
|
|
994
|
+
|
|
995
|
+
To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
|
|
996
|
+
</agent_web_requests>
|
|
997
|
+
|
|
998
|
+
<technical_knowledge>
|
|
999
|
+
Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
|
|
1000
|
+
|
|
1001
|
+
\`\`\`typescript
|
|
1002
|
+
import { convertToModelMessages, streamText } from "ai";
|
|
1003
|
+
import * as blink from "blink";
|
|
1004
|
+
|
|
1005
|
+
const agent = new blink.Agent();
|
|
1006
|
+
|
|
1007
|
+
agent.on("chat", async ({ messages, chat, abortSignal }) => {
|
|
1008
|
+
return streamText({
|
|
1009
|
+
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
1010
|
+
system: "You are a helpful assistant.",
|
|
1011
|
+
messages: convertToModelMessages(messages, {
|
|
1012
|
+
ignoreIncompleteToolCalls: true,
|
|
1013
|
+
}),
|
|
1014
|
+
tools: {
|
|
1015
|
+
/* your tools */
|
|
1016
|
+
},
|
|
1017
|
+
});
|
|
1018
|
+
});
|
|
1019
|
+
|
|
1020
|
+
agent.on("request", async (request) => {
|
|
1021
|
+
// Handle webhooks, OAuth callbacks, etc.
|
|
1022
|
+
});
|
|
1023
|
+
|
|
1024
|
+
agent.serve();
|
|
1025
|
+
\`\`\`
|
|
1026
|
+
|
|
1027
|
+
Event Handlers:
|
|
1028
|
+
|
|
1029
|
+
**\`agent.on("chat", handler)\`**
|
|
1030
|
+
|
|
1031
|
+
1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
|
|
1032
|
+
2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
|
|
1033
|
+
3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
|
|
1034
|
+
|
|
1035
|
+
_NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
|
|
1036
|
+
|
|
1037
|
+
**\`agent.on("request", handler)\`**
|
|
1038
|
+
• Handles raw HTTP requests before Blink processes them
|
|
1039
|
+
• Use for: OAuth callbacks, webhook verification, custom endpoints
|
|
1040
|
+
• Return \`Response\` to handle, or \`void\` to pass through
|
|
1041
|
+
|
|
1042
|
+
**\`agent.on("ui", handler)\`**
|
|
1043
|
+
• Provides dynamic UI options for chat interfaces
|
|
1044
|
+
• Returns schema defining user-selectable options
|
|
1045
|
+
|
|
1046
|
+
**\`agent.on("error", handler)\`**
|
|
1047
|
+
• Global error handler for the agent
|
|
1048
|
+
|
|
1049
|
+
Chat Management:
|
|
1050
|
+
|
|
1051
|
+
Blink automatically manages chat state:
|
|
1052
|
+
|
|
1053
|
+
\`\`\`typescript
|
|
1054
|
+
// Create or get existing chat
|
|
1055
|
+
// The parameter can be any JSON-serializable value.
|
|
1056
|
+
// e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
|
|
1057
|
+
const chat = await agent.chat.upsert("unique-key");
|
|
1058
|
+
|
|
1059
|
+
// Send a message to a chat
|
|
1060
|
+
await agent.chat.sendMessages(
|
|
1061
|
+
chat.id,
|
|
1062
|
+
[
|
|
1063
|
+
{
|
|
1064
|
+
role: "user",
|
|
1065
|
+
parts: [{ type: "text", text: "Message" }],
|
|
1066
|
+
},
|
|
1067
|
+
],
|
|
1068
|
+
{
|
|
1069
|
+
behavior: "interrupt" | "enqueue" | "append",
|
|
1070
|
+
}
|
|
1071
|
+
);
|
|
1072
|
+
|
|
1073
|
+
// When sending messages, feel free to inject additional parts to direct the model.
|
|
1074
|
+
// e.g. if the user is asking for specific behavior in specific scenarios, the simplest
|
|
1075
|
+
// answer is to append a text part: "always do X when Y".
|
|
1076
|
+
\`\`\`
|
|
1077
|
+
|
|
1078
|
+
Behaviors:
|
|
1079
|
+
• "interrupt": Stop current processing and handle immediately
|
|
1080
|
+
• "enqueue": Queue message, process when current chat finishes
|
|
1081
|
+
• "append": Add to history without triggering processing
|
|
1082
|
+
|
|
1083
|
+
Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
|
|
1084
|
+
|
|
1085
|
+
Storage API:
|
|
1086
|
+
|
|
1087
|
+
Persistent key-value storage per agent:
|
|
1088
|
+
|
|
1089
|
+
\`\`\`typescript
|
|
1090
|
+
// Store data
|
|
1091
|
+
await agent.store.set("key", "value", { ttl: 3600 });
|
|
1092
|
+
|
|
1093
|
+
// Retrieve data
|
|
1094
|
+
const value = await agent.store.get("key");
|
|
1095
|
+
|
|
1096
|
+
// Delete data
|
|
1097
|
+
await agent.store.delete("key");
|
|
1098
|
+
|
|
1099
|
+
// List keys by prefix
|
|
1100
|
+
const result = await agent.store.list("prefix-", { limit: 100 });
|
|
1101
|
+
\`\`\`
|
|
1102
|
+
|
|
1103
|
+
Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
|
|
1104
|
+
|
|
1105
|
+
Tools:
|
|
1106
|
+
|
|
1107
|
+
Tools follow Vercel AI SDK patterns with Zod validation:
|
|
1108
|
+
|
|
1109
|
+
\`\`\`typescript
|
|
1110
|
+
import { tool } from "ai";
|
|
1111
|
+
import { z } from "zod";
|
|
1112
|
+
|
|
1113
|
+
const myTool = tool({
|
|
1114
|
+
description: "Clear description of what this tool does",
|
|
1115
|
+
inputSchema: z.object({
|
|
1116
|
+
param: z.string().describe("Parameter description"),
|
|
1117
|
+
}),
|
|
1118
|
+
execute: async (args, opts) => {
|
|
1119
|
+
// opts.abortSignal for cancellation
|
|
1120
|
+
// opts.toolCallId for unique identification
|
|
1121
|
+
return result;
|
|
1122
|
+
},
|
|
1123
|
+
});
|
|
1124
|
+
\`\`\`
|
|
1125
|
+
|
|
1126
|
+
Tool Approvals for destructive operations:
|
|
1127
|
+
|
|
1128
|
+
\`\`\`typescript
|
|
1129
|
+
...await blink.tools.withApproval({
|
|
1130
|
+
messages,
|
|
1131
|
+
tools: {
|
|
1132
|
+
delete_database: tool({ /* ... */ }),
|
|
1133
|
+
},
|
|
1134
|
+
})
|
|
1135
|
+
\`\`\`
|
|
1136
|
+
|
|
1137
|
+
Tool Context for dependency injection:
|
|
1138
|
+
|
|
1139
|
+
\`\`\`typescript
|
|
1140
|
+
...blink.tools.withContext(github.tools, {
|
|
1141
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
1142
|
+
})
|
|
1143
|
+
\`\`\`
|
|
1144
|
+
|
|
1145
|
+
Tool Prefixing to avoid collisions:
|
|
1146
|
+
|
|
1147
|
+
\`\`\`typescript
|
|
1148
|
+
...blink.tools.prefix(github.tools, "github_")
|
|
1149
|
+
\`\`\`
|
|
1150
|
+
|
|
1151
|
+
LLM Models:
|
|
1152
|
+
|
|
1153
|
+
**Option 1: Blink Gateway** (Quick Start)
|
|
1154
|
+
|
|
1155
|
+
\`\`\`typescript
|
|
1156
|
+
model: blink.model("anthropic/claude-sonnet-4.5");
|
|
1157
|
+
model: blink.model("openai/gpt-5");
|
|
1158
|
+
\`\`\`
|
|
1159
|
+
|
|
1160
|
+
Requires: \`blink login\` or \`BLINK_TOKEN\` env var
|
|
1161
|
+
|
|
1162
|
+
**Option 2: Direct Provider** (Production Recommended)
|
|
1163
|
+
|
|
1164
|
+
\`\`\`typescript
|
|
1165
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
1166
|
+
import { openai } from "@ai-sdk/openai";
|
|
1167
|
+
|
|
1168
|
+
model: anthropic("claude-sonnet-4.5", {
|
|
1169
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
1170
|
+
});
|
|
1171
|
+
model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
1172
|
+
\`\`\`
|
|
1173
|
+
|
|
1174
|
+
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
1175
|
+
|
|
1176
|
+
1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
|
|
1177
|
+
2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
|
|
1178
|
+
3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
|
|
1179
|
+
|
|
1180
|
+
Available SDKs:
|
|
1181
|
+
|
|
1182
|
+
**@blink-sdk/compute**
|
|
1183
|
+
|
|
1184
|
+
\`\`\`typescript
|
|
1185
|
+
import * as compute from "@blink-sdk/compute";
|
|
1186
|
+
|
|
1187
|
+
tools: {
|
|
1188
|
+
...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
|
|
1189
|
+
}
|
|
1190
|
+
\`\`\`
|
|
1191
|
+
|
|
1192
|
+
**@blink-sdk/github**
|
|
1193
|
+
|
|
1194
|
+
\`\`\`typescript
|
|
1195
|
+
import * as github from "@blink-sdk/github";
|
|
1196
|
+
|
|
1197
|
+
tools: {
|
|
1198
|
+
...blink.tools.withContext(github.tools, {
|
|
1199
|
+
accessToken: process.env.GITHUB_TOKEN,
|
|
1200
|
+
}),
|
|
1201
|
+
}
|
|
1202
|
+
\`\`\`
|
|
1203
|
+
|
|
1204
|
+
**@blink-sdk/slack**
|
|
1205
|
+
|
|
1206
|
+
\`\`\`typescript
|
|
1207
|
+
import * as slack from "@blink-sdk/slack";
|
|
1208
|
+
import { App } from "@slack/bolt";
|
|
1209
|
+
|
|
1210
|
+
const receiver = new slack.Receiver();
|
|
1211
|
+
const app = new App({
|
|
1212
|
+
token: process.env.SLACK_BOT_TOKEN,
|
|
1213
|
+
signingSecret: process.env.SLACK_SIGNING_SECRET,
|
|
1214
|
+
receiver,
|
|
1215
|
+
});
|
|
1216
|
+
|
|
1217
|
+
// This will trigger when the bot is @mentioned.
|
|
1218
|
+
app.event("app_mention", async ({ event }) => {
|
|
1219
|
+
// The argument here is a JSON-serializable value.
|
|
1220
|
+
// To maintain the same chat context, use the same key.
|
|
1221
|
+
const chat = await agent.chat.upsert([
|
|
1222
|
+
"slack",
|
|
1223
|
+
event.channel,
|
|
1224
|
+
event.thread_ts ?? event.ts,
|
|
1225
|
+
]);
|
|
1226
|
+
const { message } = await slack.createMessageFromEvent({
|
|
1227
|
+
client: app.client,
|
|
1228
|
+
event,
|
|
1229
|
+
});
|
|
1230
|
+
await agent.chat.sendMessages(chat.id, [message]);
|
|
1231
|
+
// This is a nice immediate indicator for the user.
|
|
1232
|
+
await app.client.assistant.threads.setStatus({
|
|
1233
|
+
channel_id: event.channel,
|
|
1234
|
+
status: "is typing...",
|
|
1235
|
+
thread_ts: event.thread_ts ?? event.ts,
|
|
1236
|
+
});
|
|
1237
|
+
});
|
|
1238
|
+
|
|
1239
|
+
const agent = new blink.Agent();
|
|
1240
|
+
|
|
1241
|
+
agent.on("request", async (request) => {
|
|
1242
|
+
return receiver.handle(app, request);
|
|
1243
|
+
});
|
|
1244
|
+
|
|
1245
|
+
agent.on("chat", async ({ messages }) => {
|
|
1246
|
+
const tools = slack.createTools({ client: app.client });
|
|
1247
|
+
return streamText({
|
|
1248
|
+
model: blink.model("anthropic/claude-sonnet-4.5"),
|
|
1249
|
+
system: "You chatting with users in Slack.",
|
|
1250
|
+
messages: convertToModelMessages(messages, {
|
|
1251
|
+
ignoreIncompleteToolCalls: true,
|
|
1252
|
+
tools,
|
|
1253
|
+
}),
|
|
1254
|
+
});
|
|
1255
|
+
});
|
|
1256
|
+
\`\`\`
|
|
1257
|
+
|
|
1258
|
+
Slack SDK Notes:
|
|
1259
|
+
|
|
1260
|
+
- "app_mention" event is triggered in both private channels and public channels.
|
|
1261
|
+
- "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
|
|
1262
|
+
- _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
|
|
1263
|
+
- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.
|
|
1264
|
+
- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. \`message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${channel} thread_ts=\${thread_ts}" })\`
|
|
1265
|
+
- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".
|
|
1266
|
+
|
|
1267
|
+
Slack App Manifest:
|
|
1268
|
+
|
|
1269
|
+
- _ALWAYS_ include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You _MUST_ provide "assistant_view" if you provide this scope.
|
|
1270
|
+
- The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
1271
|
+
- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
|
|
1272
|
+
- _ALWAYS_ default "token_rotation_enabled" to false unless the user explicitly asks for it. It is a _much_ simpler user-experience to not rotate tokens.
|
|
1273
|
+
- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
|
|
1274
|
+
- "app_mentions:read"
|
|
1275
|
+
- "reactions:write"
|
|
1276
|
+
- "reactions:read"
|
|
1277
|
+
- "channels:history"
|
|
1278
|
+
- "chat:write"
|
|
1279
|
+
- "groups:history"
|
|
1280
|
+
- "groups:read"
|
|
1281
|
+
- "files:read"
|
|
1282
|
+
- "im:history"
|
|
1283
|
+
- "im:read"
|
|
1284
|
+
- "im:write"
|
|
1285
|
+
- "mpim:history"
|
|
1286
|
+
- "mpim:read"
|
|
1287
|
+
- "users:read"
|
|
1288
|
+
- "links:read"
|
|
1289
|
+
- "commands"
|
|
1290
|
+
- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
|
|
1291
|
+
- "app_mention"
|
|
1292
|
+
- "message.channels",
|
|
1293
|
+
- "message.groups",
|
|
1294
|
+
- "message.im",
|
|
1295
|
+
- "reaction_added"
|
|
1296
|
+
- "reaction_removed"
|
|
1297
|
+
- "assistant_thread_started"
|
|
1298
|
+
- "member_joined_channel"
|
|
1299
|
+
- _NEVER_ include USER SCOPES unless the user explicitly asks for them.
|
|
1300
|
+
|
|
1301
|
+
WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
|
|
1302
|
+
|
|
1303
|
+
**@blink-sdk/web-search**
|
|
1304
|
+
|
|
1305
|
+
\`\`\`typescript
|
|
1306
|
+
import * as webSearch from "@blink-sdk/web-search";
|
|
1307
|
+
|
|
1308
|
+
tools: {
|
|
1309
|
+
...webSearch.tools,
|
|
1310
|
+
}
|
|
1311
|
+
\`\`\`
|
|
1312
|
+
|
|
1313
|
+
State Management:
|
|
1314
|
+
|
|
1315
|
+
Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
|
|
1316
|
+
|
|
1317
|
+
_NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
|
|
1318
|
+
|
|
1319
|
+
For global state persistence, you can use the agent store:
|
|
1320
|
+
|
|
1321
|
+
- Use \`agent.store\` for persistent key-value storage
|
|
1322
|
+
- Query external APIs to fetch current state
|
|
1323
|
+
- Use webhooks to trigger actions rather than polling in-memory state
|
|
1324
|
+
|
|
1325
|
+
For message-level state persistence, use message metadata:
|
|
1326
|
+
|
|
1327
|
+
\`\`\`typescript
|
|
1328
|
+
import { UIMessage } from "blink";
|
|
1329
|
+
import * as blink from "blink";
|
|
1330
|
+
|
|
1331
|
+
const agent = new blink.Agent<
|
|
1332
|
+
UIMessage<{
|
|
1333
|
+
source: "github";
|
|
1334
|
+
associated_id: string;
|
|
1335
|
+
}>
|
|
1336
|
+
>();
|
|
1337
|
+
|
|
1338
|
+
agent.on("request", async (request) => {
|
|
1339
|
+
// comes from github, we want to do something deterministic in the chat loop with that ID...
|
|
1340
|
+
// insert a message with that metadata into the chat
|
|
1341
|
+
const chat = await agent.chat.upsert("some-github-key");
|
|
1342
|
+
await agent.chat.sendMessages(request.chat.id, [
|
|
1343
|
+
{
|
|
1344
|
+
role: "user",
|
|
1345
|
+
parts: [
|
|
1346
|
+
{
|
|
1347
|
+
type: "text",
|
|
1348
|
+
text: "example",
|
|
1349
|
+
},
|
|
1350
|
+
],
|
|
1351
|
+
metadata: {
|
|
1352
|
+
source: "github",
|
|
1353
|
+
associated_id: "some-github-id",
|
|
1354
|
+
},
|
|
1355
|
+
},
|
|
1356
|
+
]);
|
|
1357
|
+
});
|
|
1358
|
+
|
|
1359
|
+
agent.on("chat", async ({ messages }) => {
|
|
1360
|
+
const message = messages.find(
|
|
1361
|
+
(message) => message.metadata?.source === "github"
|
|
1362
|
+
);
|
|
1363
|
+
|
|
1364
|
+
// Now we can use that metadata...
|
|
1365
|
+
});
|
|
1366
|
+
\`\`\`
|
|
1367
|
+
|
|
1368
|
+
The agent process can restart at any time, so all important state must be externalized.
|
|
1369
|
+
</technical_knowledge>
|
|
1370
|
+
|
|
1371
|
+
<code_quality>
|
|
1372
|
+
|
|
1373
|
+
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
1374
|
+
</code_quality>
|
|
1375
|
+
`,".env.local":`
|
|
1376
|
+
# Store local environment variables here.
|
|
1377
|
+
# They will be used by blink dev for development.
|
|
1378
|
+
SLACK_BOT_TOKEN=xoxb-your-token-here
|
|
1379
|
+
SLACK_SIGNING_SECRET=your-signing-secret-here
|
|
1380
|
+
`,".env.production":`
|
|
1381
|
+
# Store production environment variables here.
|
|
1382
|
+
# They will be upserted as secrets on blink deploy.
|
|
1383
|
+
SLACK_BOT_TOKEN=
|
|
1384
|
+
SLACK_SIGNING_SECRET=
|
|
1385
|
+
`}};function Lv(e,n,r){let i,a=u.default.createServer(t.createServerAdapter(async t=>{let o=new URL(t.url,i);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await r?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await r?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let n=t.message;return new Response(`Error: ${n}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{a.close()}let c={...e,redirect_url:i},l=`<!DOCTYPE html>
|
|
256
1386
|
<html>
|
|
257
1387
|
<body>
|
|
258
1388
|
<form id="f" method="POST" action="${n?`https://github.com/organizations/${n}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
@@ -260,7 +1390,7 @@ for await (const chunk of exa.streamAnswer(query)) {
|
|
|
260
1390
|
</form>
|
|
261
1391
|
<script>document.getElementById('f').submit()<\/script>
|
|
262
1392
|
</body>
|
|
263
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const Uv=y.z.enum([`read`,`write`]),Wv=y.z.union([y.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),y.z.literal(`check_run`).describe(`Check run created, completed, or requested`),y.z.literal(`check_suite`).describe(`Check suite completed or requested`),y.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),y.z.literal(`commit_comment`).describe(`Commit comment created`),y.z.literal(`create`).describe(`Branch or tag created`),y.z.literal(`delete`).describe(`Branch or tag deleted`),y.z.literal(`deployment`).describe(`Deployment created`),y.z.literal(`deployment_status`).describe(`Deployment status created`),y.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),y.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),y.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),y.z.literal(`fork`).describe(`Repository forked`),y.z.literal(`gollum`).describe(`Wiki page created or updated`),y.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),y.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),y.z.literal(`label`).describe(`Label created, edited, or deleted`),y.z.literal(`member`).describe(`Collaborator added, removed, or edited`),y.z.literal(`membership`).describe(`Team membership added or removed`),y.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),y.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),y.z.literal(`organization`).describe(`Organization member added, removed, or invited`),y.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),y.z.literal(`package`).describe(`Package published or updated`),y.z.literal(`page_build`).describe(`GitHub Pages site built`),y.z.literal(`project`).describe(`Project created, updated, or deleted`),y.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),y.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),y.z.literal(`public`).describe(`Repository visibility changed to public`),y.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),y.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),y.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),y.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),y.z.literal(`push`).describe(`Git push to a repository`),y.z.literal(`registry_package`).describe(`Registry package published or updated`),y.z.literal(`release`).describe(`Release published or edited`),y.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),y.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),y.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),y.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),y.z.literal(`star`).describe(`Repository starred or unstarred`),y.z.literal(`status`).describe(`Commit status created`),y.z.literal(`team`).describe(`Team created, deleted, or edited`),y.z.literal(`team_add`).describe(`Repository added to team`),y.z.literal(`watch`).describe(`User started watching repository`),y.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),y.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),y.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Gv=y.z.object({name:y.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:y.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:y.z.string().optional().describe(`The description of the GitHub App.`),public:y.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:y.z.object({url:y.z.url(),active:y.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:y.z.array(y.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:y.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:y.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:y.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:y.z.array(Wv).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:y.z.record(y.z.string(),Uv).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function Kv(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1393
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const Rv=y.z.enum([`read`,`write`]),zv=y.z.union([y.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),y.z.literal(`check_run`).describe(`Check run created, completed, or requested`),y.z.literal(`check_suite`).describe(`Check suite completed or requested`),y.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),y.z.literal(`commit_comment`).describe(`Commit comment created`),y.z.literal(`create`).describe(`Branch or tag created`),y.z.literal(`delete`).describe(`Branch or tag deleted`),y.z.literal(`deployment`).describe(`Deployment created`),y.z.literal(`deployment_status`).describe(`Deployment status created`),y.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),y.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),y.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),y.z.literal(`fork`).describe(`Repository forked`),y.z.literal(`gollum`).describe(`Wiki page created or updated`),y.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),y.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),y.z.literal(`label`).describe(`Label created, edited, or deleted`),y.z.literal(`member`).describe(`Collaborator added, removed, or edited`),y.z.literal(`membership`).describe(`Team membership added or removed`),y.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),y.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),y.z.literal(`organization`).describe(`Organization member added, removed, or invited`),y.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),y.z.literal(`package`).describe(`Package published or updated`),y.z.literal(`page_build`).describe(`GitHub Pages site built`),y.z.literal(`project`).describe(`Project created, updated, or deleted`),y.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),y.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),y.z.literal(`public`).describe(`Repository visibility changed to public`),y.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),y.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),y.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),y.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),y.z.literal(`push`).describe(`Git push to a repository`),y.z.literal(`registry_package`).describe(`Registry package published or updated`),y.z.literal(`release`).describe(`Release published or edited`),y.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),y.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),y.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),y.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),y.z.literal(`star`).describe(`Repository starred or unstarred`),y.z.literal(`status`).describe(`Commit status created`),y.z.literal(`team`).describe(`Team created, deleted, or edited`),y.z.literal(`team_add`).describe(`Repository added to team`),y.z.literal(`watch`).describe(`User started watching repository`),y.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),y.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),y.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Bv=y.z.object({name:y.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:y.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:y.z.string().optional().describe(`The description of the GitHub App.`),public:y.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:y.z.object({url:y.z.url(),active:y.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:y.z.array(y.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:y.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:y.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:y.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:y.z.array(zv).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:y.z.record(y.z.string(),Rv).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function Vv(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Hv=y.z.union([y.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),y.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),y.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),y.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),y.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),y.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),y.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),y.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),y.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),y.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),y.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),y.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),y.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),y.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),y.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),y.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),y.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),y.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),y.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),y.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),y.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),y.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),y.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),y.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),y.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),y.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),y.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),y.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),y.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),y.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),y.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),y.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),y.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),y.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),y.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Uv=y.z.union([y.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),y.z.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`),y.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),y.z.literal(`channels:join`).describe(`Join public channels`),y.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),y.z.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`),y.z.literal(`chat:write`).describe(`Send messages as the bot`),y.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),y.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),y.z.literal(`commands`).describe(`Add and use slash commands`),y.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),y.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),y.z.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`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files`),y.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),y.z.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`),y.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),y.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),y.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),y.z.literal(`im:write`).describe(`Start and manage direct messages with users`),y.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),y.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),y.z.literal(`metadata.message:read`).describe(`Read message metadata`),y.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),y.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),y.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),y.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),y.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),y.z.literal(`reminders:read`).describe(`View reminders created by the bot`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),y.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),y.z.literal(`usergroups:read`).describe(`View user groups and their members`),y.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),y.z.literal(`users.profile:read`).describe(`View profile information about users`),y.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),y.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),y.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Wv=y.z.union([y.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),y.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),y.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),y.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),y.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),y.z.literal(`files:read`).describe(`View files on behalf of the user`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),y.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),y.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),y.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),y.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),y.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),y.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),y.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),y.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),y.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),y.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),y.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),y.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),y.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),y.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),y.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),y.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),y.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),y.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),y.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),y.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),y.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),y.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),y.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),y.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),y.z.literal(`users:write`).describe(`Set presence for the user`)]),Gv=y.z.object({display_information:y.z.object({name:y.z.string().describe(`The name of the Slack app.`),description:y.z.string().optional().describe(`A short description of the app.`),background_color:y.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:y.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:y.z.object({bot_user:y.z.object({display_name:y.z.string().describe(`The display name for the bot user.`),always_online:y.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:y.z.object({home_tab_enabled:y.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:y.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:y.z.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:y.z.object({assistant_description:y.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:y.z.array(y.z.object({command:y.z.string().regex(/^\//).describe(`The command (must start with /).`),description:y.z.string().describe(`Description of the command.`),usage_hint:y.z.string().optional().describe(`Usage hint for the command.`),should_escape:y.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:y.z.array(y.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:y.z.object({redirect_urls:y.z.array(y.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:y.z.object({bot:y.z.array(y.z.union([Uv,y.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:y.z.array(y.z.union([Wv,y.z.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:y.z.object({event_subscriptions:y.z.object({request_url:y.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:y.z.array(y.z.union([Hv,y.z.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:y.z.object({is_enabled:y.z.boolean().describe(`Enable interactivity.`),request_url:y.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:y.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:y.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:y.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:y.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Kv(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
264
1394
|
|
|
265
1395
|
The agent source code is in the directory: "${e.directory}".
|
|
266
1396
|
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
@@ -301,7 +1431,7 @@ You *must* ensure the organization is correct - ask the user prior.
|
|
|
301
1431
|
|
|
302
1432
|
Once they complete the app creation, environment variables will be automatically set in the provided environment file.
|
|
303
1433
|
|
|
304
|
-
After approval, the URL will be opened automatically in their browser.`,inputSchema:y.z.object({manifest:
|
|
1434
|
+
After approval, the URL will be opened automatically in their browser.`,inputSchema:y.z.object({manifest:Bv,envFile:y.z.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:y.z.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(t,r)=>{let a=await Lv(t.manifest,t.organization,async(r,a)=>{if(r){await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${r.message}`}]}]);return}if(a){try{let n=t.envFile===`production`?`.env.production`:`.env.local`,r=(0,d.join)(e.directory,n),i=``;try{i=await(0,h.readFile)(r,`utf-8`)}catch{}let o=`
|
|
305
1435
|
# GitHub App credentials (created with the blink edit agent)
|
|
306
1436
|
GITHUB_APP_ID=${a.id}
|
|
307
1437
|
GITHUB_CLIENT_ID=${a.client_id}
|
|
@@ -316,7 +1446,7 @@ IMPORTANT - when ran, you MUST:
|
|
|
316
1446
|
3. Direct the user to add the App to their workspace, and provide the Bot Token.
|
|
317
1447
|
|
|
318
1448
|
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.
|
|
319
|
-
`,inputSchema:
|
|
1449
|
+
`,inputSchema:Gv,execute:async(e,t)=>{let n=Vv(e);return(await cd(n)).once(`error`,e=>{console.log(`Could not open the browser. Please visit the URL manually: ${n}`)}),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:(0,m.tool)({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
320
1450
|
|
|
321
1451
|
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:y.z.object({message:y.z.string()}),execute:async(e,t)=>{if(!r)return`User agent URL is not available. Cannot test user agent.`;let n=await new mi({baseUrl:r}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:t.abortSignal}),i=(0,m.readUIMessageStream)({stream:n}),a;for await(let e of i)a=e;return a}}),typecheck_agent:(0,m.tool)({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
|
|
322
1452
|
|
|
@@ -353,4 +1483,4 @@ Slack:
|
|
|
353
1483
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
354
1484
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
355
1485
|
</agent_development>
|
|
356
|
-
`});let v=
|
|
1486
|
+
`});let v=Iv.scratch[`AGENTS.md`];try{v=await(0,h.readFile)((0,d.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:v}),(0,m.streamText)({model:qv(e.token),messages:_,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function qv(e){return process.env.ANTHROPIC_API_KEY?be({apiKey:process.env.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`):process.env.OPENAI_API_KEY?er({apiKey:process.env.OPENAI_API_KEY}).responses(`gpt-5`):t.model(`anthropic/claude-sonnet-4.5`,{token:e})}function Jv(e){let[t,n]=(0,_.useState)(void 0),[r,i]=(0,_.useState)(void 0),a=(0,_.useRef)(void 0);return(0,_.useEffect)(()=>{let t=new AbortController,r=!1;return i(void 0),n(void 0),(async()=>{a.current=Kv({directory:e.directory,token:e.token,getDevhookUrl:e.getDevhookUrl});let r=await Yv(),i=a.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}a.current?.cleanup()});let o=new mi({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(o)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.token,e.getDevhookUrl]),(0,_.useMemo)(()=>({client:t,error:r,setUserAgentUrl:e=>{a.current?.setUserAgentUrl(e)}}),[t,r])}async function Yv(){let e=(0,u.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Xv(e){let{directory:n}=e,[r,i]=(0,_.useState)(),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(`run`),l=(0,_.useRef)(`run`);(0,_.useEffect)(()=>{l.current=s},[s]);let u=(0,_.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),f=(0,_.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:p,status:h,result:g,entry:v}=md({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=pd({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=Af(n),x=(0,_.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,_.useRef)(void 0),w=(0,_.useMemo)(()=>Sf({port:0,dataDirectory:(0,d.join)(n,`data`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=hi({buildResult:g,env:x,apiServerUrl:w.url}),{client:k,error:A,setUserAgentUrl:j}=Jv({directory:n,apiServerUrl:w.url,token:y.token,getDevhookUrl:(0,_.useCallback)(()=>{let e=Jd(n)??Yd(n);return R(e),`https://${e}.blink.host`},[n])}),[M,N]=(0,_.useState)(`00000000-0000-0000-0000-000000000000`);(0,_.useEffect)(()=>{C.current=T},[T]),(0,_.useEffect)(()=>{T&&j(T.baseUrl),(s===`run`&&!T||s===`edit`&&!k)&&w.getChatManager(M)?.stopStreaming()},[T,k,s,M,w,j]);let P=(0,_.useRef)(void 0),F=Kd({chatId:M,agent:s===`run`?T:k,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&P.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:P.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(Wd(e.metadata)||e.mode===`edit`)}),ee=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(E.length===ee.current)return;let t=ee.current;for(let n of E.slice(t))e.onAgentLog?.(n);ee.current=E.length},[E,e.onAgentLog,F.upsertMessage]);let[te,I]=(0,_.useState)([]);(0,_.useEffect)(()=>{w.listChats().then(e=>{I(e.map(e=>e.key))})},[w]),(0,_.useEffect)(()=>{M&&!te.includes(M)&&I(e=>[...e,M])},[M,te]);let[L,R]=(0,_.useState)(()=>Jd(n)),z=Tf({id:L,directory:n,disabled:!O?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});(0,_.useEffect)(()=>{z.status!==`connected`||!z.url||e.onDevhookConnected?.(z.url)},[z.status,z.url]);let{schema:B,options:V,error:H,setOption:ne}=Cf({agent:s===`run`?T:k,capabilities:O,messages:F.messages});(0,_.useEffect)(()=>{P.current=V},[V]);let U=(0,_.useMemo)(()=>{let e=new Map;return D&&s===`run`&&e.set(`agent`,D.message),A&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${A.message}`),F.error&&h!==`building`&&e.set(`chat`,`Chat error: ${F.error}`),H&&e.set(`options`,`Options error: ${H.message}`),e},[D,A,F.error,H,s,h]),re=(0,_.useRef)(new Map);(0,_.useEffect)(()=>{let t=re.current,n=U;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);re.current=new Map(n)},[U,e.onError]);let W=(0,_.useMemo)(()=>{let e=[...F.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||r===e.id)return;let n=e.parts.filter(m.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[F.messages,r]),ie=(0,_.useCallback)(async(e,n)=>{if(!W)return;n&&e&&o(!0),i(W.id);let r=F.messages;if(r.length===0)return;let a=r[r.length-1];if(!a||a.role!==`assistant`||!Array.isArray(a.parts))return;let s=a.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await F.upsertMessage({...a,parts:s}),await F.start()},[W,F]);(0,_.useEffect)(()=>{a&&W&&ie(!0)},[a,W,ie]);let G=(0,_.useCallback)(()=>{let e=crypto.randomUUID();N(e),I(t=>[...t,e]),i(void 0)},[]),ae=(0,_.useCallback)(e=>{N(e),i(void 0)},[]),oe=(0,_.useMemo)(()=>{if(W)return{message:W,approve:e=>ie(!0,e),reject:()=>ie(!1),autoApproveEnabled:a}},[W,ie,a]),se=(0,_.useMemo)(()=>{let e=F.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[F.messages]),ce=(0,_.useMemo)(()=>{if(F.status!==`streaming`)return!1;if(!F.streamingMessage)return!0;let e=F.streamingMessage.parts.filter(m.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[F.status,F.streamingMessage]);return{mode:s,setMode:u,toggleMode:f,chat:F,chats:te,switchChat:ae,newChat:G,build:{status:h,error:p,entrypoint:v},devhook:{connected:z.status===`connected`,url:z.status===`connected`?z.url:void 0},capabilities:O,options:{schema:B,selected:V,error:H,setOption:ne},approval:oe,tokenUsage:se,auth:y,server:w,showWaitingPlaceholder:ce}}exports.useAgent=hi,exports.useAuth=pd,exports.useBundler=md,exports.useChat=Kd,exports.useDevMode=Xv,exports.useDevhook=Tf,exports.useDotenv=Af,exports.useEditAgent=Jv,exports.useOptions=Cf;
|