typebulb 0.49.3 → 0.50.0

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/servers.js CHANGED
@@ -1134,16 +1134,16 @@ ${nv}
1134
1134
  });
1135
1135
  }
1136
1136
  })();
1137
- `;var SQ=gi(xd(),1);import{execFile as EQ}from"child_process";import{promisify as CQ}from"util";import{builtinModules as IQ}from"node:module";var yU=CQ(EQ),gU=new Set(IQ);var rv=t=>t!=null&&t>=0&&t<=3?t:void 0;var lr=class extends Error{constructor(e,n="unknown",r=!1){super(e),this.code=n,this.retryable=r}},Dn=class{getPath(e,n){return this.path}parseError(e,n){return this.parseJsonError(e,n)}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}extractSystemMessages(e,n=`
1137
+ `;var SQ=gi(xd(),1);import{execFile as EQ}from"child_process";import{promisify as CQ}from"util";import{builtinModules as IQ}from"node:module";var yU=CQ(EQ),gU=new Set(IQ);var rv=t=>t!=null&&t>=0&&t<=4?t:void 0;var lr=class extends Error{constructor(e,n="unknown",r=!1){super(e),this.code=n,this.retryable=r}},Dn=class{getPath(e,n){return this.path}parseError(e,n){return this.parseJsonError(e,n)}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}extractSystemMessages(e,n=`
1138
1138
 
1139
- `){let r=e.filter(s=>s.role==="system").map(s=>s.content);return{system:r.length?r.join(n):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,n){if(!e)return{message:`HTTP ${n}`};try{let r=JSON.parse(e);return r.error&&typeof r.error=="object"?{message:r.error.message||`HTTP ${n}`,type:r.error.type}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let n=e;if(n.type==="error"&&"message"in n){let r=n.code||"unknown";throw new lr(n.message,r,!!n.retryable)}if(n.error){let r=n.error,s=typeof r=="object"&&r!==null?String(r.type??r.code??""):"",o=/rate_limit|too_many_requests/i.test(s),i=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new lr(this.extractErrorMessage(n.error),o?"rate_limit":a?"context_exceeded":"unknown",o||i)}}extractErrorMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);return n.error?.message||n.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}};var Pl=class extends Dn{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,n,r,s){let o=this.convertMessagesToInput(e),i={model:n,input:o,stream:s};if(r?.webSearch!==!1&&(i.tools=[{type:"web_search"}]),r?.effort!==void 0){let a=this.effortMap[r.effort];i.reasoning=a==="none"?{effort:a}:{effort:a,summary:"auto"}}return i}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let n=e.output_text||"",r;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(r=s.summary.map(o=>o.text).join(`
1139
+ `){let r=e.filter(s=>s.role==="system").map(s=>s.content);return{system:r.length?r.join(n):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,n){if(!e)return{message:`HTTP ${n}`};try{let r=JSON.parse(e);return r.error&&typeof r.error=="object"?{message:r.error.message||`HTTP ${n}`,type:r.error.type}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let n=e;if(n.type==="error"&&"message"in n){let r=n.code||"unknown";throw new lr(n.message,r,!!n.retryable)}if(n.error){let r=n.error,s=typeof r=="object"&&r!==null?String(r.type??r.code??""):"",o=/rate_limit|too_many_requests/i.test(s),i=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new lr(this.extractErrorMessage(n.error),o?"rate_limit":a?"context_exceeded":"unknown",o||i)}}extractErrorMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);return n.error?.message||n.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}};var Pl=class extends Dn{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",1:"low",2:"medium",3:"high",4:"xhigh"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,n,r,s){let o=this.convertMessagesToInput(e),i={model:n,input:o,stream:s};if(r?.webSearch!==!1&&(i.tools=[{type:"web_search"}]),r?.effort!==void 0){let a=this.effortMap[r.effort];i.reasoning=a==="none"?{effort:a}:{effort:a,summary:"auto"}}return r?.maxOutputTokens!==void 0&&(i.max_output_tokens=r.maxOutputTokens),i}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let n=e.output_text||"",r;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(r=s.summary.map(o=>o.text).join(`
1140
1140
  `)),!n&&s.type==="message"&&s.content&&(n=s.content.filter(o=>o.type==="output_text").map(o=>o.text).join(""));return{text:n,reasoning:r}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let r=e.response?.error,s=r?.message||"Response failed",o=r?.code==="insufficient_quota"||r?.code==="rate_limit_exceeded";throw new lr(s,o?"rate_limit":"unknown",o)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};default:return null}}convertMessagesToInput(e){return e.map(n=>n.role==="system"?`System: ${n.content}`:n.role==="user"?`User: ${n.content}`:n.role==="assistant"?`Assistant: ${n.content}`:n.content).join(`
1141
1141
 
1142
- `)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}};var Fs=class extends Dn{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let n=e,r=n.choices[0],s=r?.message,o=s?.content??r?.text??"",i=s?.reasoning??s?.reasoning_content??n.reasoning;return{text:o,reasoning:i}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let n=e.choices[0];if(!n)return null;let r=n.delta||n.message;if(!r)return null;let s=r.content||void 0,o=r.reasoning||r.reasoning_content||void 0;return!s&&!o?null:{text:s,reasoning:o}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}};var Bl=class extends Fs{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e,n){let r={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return n&&(r["HTTP-Referer"]=n,r.Referer=n,r.Origin=n),r}buildPayload(e,n,r,s){let o={model:n,messages:e,stream:s};r?.webSearch===!0&&(o.plugins=[{id:"web"}]);let i=r?.effort;return i!==void 0&&(o.reasoning={effort:this.effortMap[i]}),o}};var Rl=class extends Dn{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,n,r,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e),a={model:n,max_tokens:this.getMaxTokens(n),messages:this.withTailMessagesCached(i),stream:s};r?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),o&&(a.system=[{type:"text",text:o,cache_control:{type:"ephemeral"}}]);let l=r?.effort;if(l!==void 0){if(this.isModernModel(n))if(l===0)this.alwaysThinks(n)||(a.thinking={type:"disabled"}),a.output_config={effort:"low"};else{let c={1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive",display:"summarized"},a.output_config={effort:c[l]}}else if(l!==0){let c={1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:c[l]}}}return a}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),r=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
1142
+ `)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}};var Fs=class extends Dn{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let n=e,r=n.choices[0],s=r?.message,o=s?.content??r?.text??"",i=s?.reasoning??s?.reasoning_content??n.reasoning;return{text:o,reasoning:i}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let n=e.choices[0];if(!n)return null;let r=n.delta||n.message;if(!r)return null;let s=r.content||void 0,o=r.reasoning||r.reasoning_content||void 0;return!s&&!o?null:{text:s,reasoning:o}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}};var Bl=class extends Fs{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high",4:"xhigh"}}buildHeaders(e,n){let r={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return n&&(r["HTTP-Referer"]=n,r.Referer=n,r.Origin=n),r}buildPayload(e,n,r,s){let o={model:n,messages:e,stream:s};r?.webSearch===!0&&(o.plugins=[{id:"web"}]);let i=r?.effort;return i!==void 0&&(o.reasoning={effort:this.effortMap[i]}),r?.maxOutputTokens!==void 0&&(o.max_tokens=r.maxOutputTokens),o}};var Rl=class extends Dn{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,n,r,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e),a={model:n,max_tokens:Math.min(this.getMaxTokens(n),r?.maxOutputTokens??1/0),messages:this.withTailMessagesCached(i),stream:s};r?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),o&&(a.system=[{type:"text",text:o,cache_control:{type:"ephemeral"}}]);let l=r?.effort;if(l!==void 0){if(this.isModernModel(n))if(l===0)this.alwaysThinks(n)||(a.thinking={type:"disabled"}),a.output_config={effort:"low"};else{let c={1:"low",2:"medium",3:"high",4:"max"};a.thinking={type:"adaptive",display:"summarized"},a.output_config={effort:c[l]}}else if(l!==0){let c={1:2048,2:4096,3:8192,4:16384};a.thinking={type:"enabled",budget_tokens:c[l]}}}return a}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),r=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
1143
1143
 
1144
- `);return{text:n,reasoning:r||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withTailMessagesCached(e){let n=Math.max(0,e.length-2);return e.map((r,s)=>s>=n?{role:r.role,content:[{type:"text",text:r.content,cache_control:{type:"ephemeral"}}]}:r)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let n=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!n)return!1;let r=+n[1],s=n[2]?+n[2]:0;return r>4||r===4&&s>=6}alwaysThinks(e){return/^claude-(fable|mythos)\b/i.test(e)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var Ol=class extends Dn{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1}}getPath(e,n){return`/v1beta/models/${e}:${n?"streamGenerateContent":"generateContent"}${n?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,n,r,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e,`
1145
- `),l={contents:i.map(h=>({role:h.role==="assistant"?"model":"user",parts:[{text:h.content}]}))};r?.webSearch!==!1&&(l.tools=[{google_search:{}}]),o&&(l.systemInstruction={role:"system",parts:[{text:o}]});let c=r?.effort;if(c!==void 0){let h=this.geminiVersion(n),u=h!==null&&h>=3?{thinkingLevel:this.thinkingLevelFor(h,c)}:{thinkingBudget:this.budgetMap[c]};l.generationConfig={thinkingConfig:c===0?u:{includeThoughts:!0,...u}}}return l}parseError(e,n){if(!e)return{message:`HTTP ${n}`};try{let r=JSON.parse(e),s=Array.isArray(r)?r[0]?.error:r?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${n}`).split(`
1146
- `)[0],type:s.status,code:s.code?.toString()}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let n=this.extractParts(e).text||"",r=e.candidates?.[0]?.finishReason,s="complete";return r==="MAX_TOKENS"?s="interrupted":(r==="SAFETY"||r==="RECITATION")&&(s="failed"),{text:n,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let n=this.extractParts(e);return n.text||n.reasoning?n:null}geminiVersion(e){let n=e.match(/^gemini-(\d+(?:\.\d+)?)/);return n?Number(n[1]):null}thinkingLevelFor(e,n){let r=["minimal","low","medium","high"][n];return r==="minimal"&&e<3.5?"low":r}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let n=e.candidates?.[0]?.content?.parts;if(!n)return{};let r="",s="";for(let o of n)o.text&&(o.thought?s+=o.text:r+=o.text);return{text:r||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let n=e.promptFeedback.blockReason;throw new lr(`Prompt blocked: ${n}`)}}};var Ll=class extends Fs{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let n={"Content-Type":"application/json",Accept:"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}buildPayload(e,n,r,s){return{model:n,messages:e,stream:s}}};var sv=new Ll,_Q=new Map([["openai",new Pl],["openrouter",new Bl],["anthropic",new Rl],["gemini",new Ol],["ollama",sv],["openai-compat",sv]]);function pi(t){let e=_Q.get(t);if(!e)throw new Error(`Unsupported protocol: ${t}`);return e}function NQ(t,e){return t.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function _d(t,e){let n=pi(t.protocol),r=n.getPath(t.model,e.stream),s=NQ(t.baseUrl,r),o=n.buildHeaders(t.apiKey,e.origin),i=n.buildPayload(e.messages,t.model,{effort:e.effort,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(i),fetch(s,{method:"POST",headers:o,body:JSON.stringify(i),signal:e.signal})}import{readFileSync as OQ,existsSync as hJ}from"fs";import*as Dl from"path";function LQ(t){return[...t?[`.env.${t}.local`,`.env.${t}`]:[],".env.local",".env"]}function*DQ(t){for(let e of t.split(`
1144
+ `);return{text:n,reasoning:r||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withTailMessagesCached(e){let n=Math.max(0,e.length-2);return e.map((r,s)=>s>=n?{role:r.role,content:[{type:"text",text:r.content,cache_control:{type:"ephemeral"}}]}:r)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let n=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!n)return!1;let r=+n[1],s=n[2]?+n[2]:0;return r>4||r===4&&s>=6}alwaysThinks(e){return/^claude-(fable|mythos)\b/i.test(e)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var Ol=class extends Dn{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1,4:-1}}getPath(e,n){return`/v1beta/models/${e}:${n?"streamGenerateContent":"generateContent"}${n?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,n,r,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e,`
1145
+ `),l={contents:i.map(h=>({role:h.role==="assistant"?"model":"user",parts:[{text:h.content}]}))};r?.webSearch!==!1&&(l.tools=[{google_search:{}}]),o&&(l.systemInstruction={role:"system",parts:[{text:o}]});let c=r?.effort;if(c!==void 0){let h=this.geminiVersion(n),u=h!==null&&h>=3?{thinkingLevel:this.thinkingLevelFor(h,c)}:{thinkingBudget:this.budgetMap[c]};l.generationConfig={thinkingConfig:c===0?u:{includeThoughts:!0,...u}}}return r?.maxOutputTokens!==void 0&&(l.generationConfig={...l.generationConfig,maxOutputTokens:r.maxOutputTokens}),l}parseError(e,n){if(!e)return{message:`HTTP ${n}`};try{let r=JSON.parse(e),s=Array.isArray(r)?r[0]?.error:r?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${n}`).split(`
1146
+ `)[0],type:s.status,code:s.code?.toString()}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let n=this.extractParts(e).text||"",r=e.candidates?.[0]?.finishReason,s="complete";return r==="MAX_TOKENS"?s="interrupted":(r==="SAFETY"||r==="RECITATION")&&(s="failed"),{text:n,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let n=this.extractParts(e);return n.text||n.reasoning?n:null}geminiVersion(e){let n=e.match(/^gemini-(\d+(?:\.\d+)?)/);return n?Number(n[1]):null}thinkingLevelFor(e,n){let r=["minimal","low","medium","high","high"][n];return r==="minimal"&&e<3.5?"low":r}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let n=e.candidates?.[0]?.content?.parts;if(!n)return{};let r="",s="";for(let o of n)o.text&&(o.thought?s+=o.text:r+=o.text);return{text:r||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let n=e.promptFeedback.blockReason;throw new lr(`Prompt blocked: ${n}`)}}};var Ll=class extends Fs{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let n={"Content-Type":"application/json",Accept:"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}buildPayload(e,n,r,s){return{model:n,messages:e,stream:s}}};var sv=new Ll,_Q=new Map([["openai",new Pl],["openrouter",new Bl],["anthropic",new Rl],["gemini",new Ol],["ollama",sv],["openai-compat",sv]]);function pi(t){let e=_Q.get(t);if(!e)throw new Error(`Unsupported protocol: ${t}`);return e}function NQ(t,e){return t.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function _d(t,e){let n=pi(t.protocol),r=n.getPath(t.model,e.stream),s=NQ(t.baseUrl,r),o=n.buildHeaders(t.apiKey,e.origin),i=n.buildPayload(e.messages,t.model,{effort:e.effort,webSearch:e.webSearch,maxOutputTokens:e.maxOutputTokens},e.stream);return fetch(s,{method:"POST",headers:o,body:JSON.stringify(i),signal:e.signal})}import{readFileSync as OQ,existsSync as hJ}from"fs";import*as Dl from"path";function LQ(t){return[...t?[`.env.${t}.local`,`.env.${t}`]:[],".env.local",".env"]}function*DQ(t){for(let e of t.split(`
1147
1147
  `)){let n=e.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let s=n.slice(0,r).trim(),o=n.slice(r+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),yield[s,o]}}function QQ(t,e=process.cwd()){for(let n of LQ()){let r;try{r=OQ(Dl.resolve(e,n),"utf-8")}catch{continue}for(let[s,o]of DQ(r))if(s===t)return o}return process.env[t]}function ov(){return`.env loads from ${process.cwd()} (the directory you ran from, not the bulb's)`}var Nd={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};function ql(t){return(t.includes("://")?t:`http://${t}`).replace(/\/+$/,"")}var qQ="https://api.typebulb.com/api/models",MQ=1440*60*1e3,$Q=5e3,FQ=60*1e3,di=null,Ql=null,fi=null;function jQ(){return fi}async function av(){let[t,e]=await Promise.all([JQ(),UQ()]);return KQ([...HQ(e),...t],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function KQ(t,e,n){return!e||!n?t:t.map(r=>r.provider===e&&r.name===n?{...r,default:!0}:r)}async function iv(){let t;try{t=await fetch(qQ,{signal:AbortSignal.timeout($Q)})}catch(e){return fi=`catalog fetch failed: ${e?.message??e}`,null}if(!t.ok)return fi=`catalog fetch failed: HTTP ${t.status}`,null;try{return await t.json()}catch(e){return fi=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function UQ(){if(di&&Date.now()-di.fetchedAt<=MQ)return di.models;let t=await iv()??await iv();return t?(di={models:t,fetchedAt:Date.now()},fi=null,t):di?.models??[]}async function JQ(){if(Ql&&Date.now()-Ql.fetchedAt<=FQ)return Ql.models;let t=ql(process.env.OLLAMA_HOST??"http://localhost:11434"),e=[];try{let n=await fetch(new URL("/api/tags",t).toString());n.ok&&(e=((await n.json()).models??[]).map(s=>s.name).filter(s=>!!s).map(s=>({provider:"ollama",name:s,friendlyName:s,providerName:"Ollama"})))}catch{}return Ql={models:e,fetchedAt:Date.now()},e}function HQ(t){let e=new Set(Object.entries(Nd).filter(([,n])=>!!process.env[n]).map(([n])=>n));return t.filter(n=>e.has(n.provider))}function lv(t,e){let n=t??process.env.TB_AI_PROVIDER,r=e??process.env.TB_AI_MODEL;if(!n)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!r)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=pi(n)}catch{return`Unknown provider '${n}'.`}if(n==="ollama")return{apiKey:"",baseUrl:`${ql(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:n,model:r,isFreeModel:!1};if(n==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:n,model:r,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let o=Nd[n];if(!o)return`Unknown provider '${n}'.`;let i=process.env[o];return i?{apiKey:i,baseUrl:s.defaultBaseUrl,protocol:n,model:r,isFreeModel:!1}:`No API key for '${n}'. Set ${o} \u2014 ${ov()}.`}function cv(t,e){let n=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return _d(t,{messages:n,stream:!0,effort:rv(e.effort),webSearch:e.webSearch??!0,signal:e.signal})}function Pd(t,e){let n=wn.resolve(t),r=wn.join(wn.dirname(n),wn.basename(n).replace(/\.bulb\.md$/,""));return e?wn.join(r,"batches",e):r}var hi=(t,e)=>wn.join(Pd(t,e),"assets");function uv(t){let[e,n,r,s]=t.split(wn.sep).slice(-4);if(!(e!=="typebulbs"||n!=="u"||!r||!s?.endsWith(".bulb.md")))return{userSlug:r,slug:s.slice(0,-8)}}function fv(t,e,n){if(e>8)return n;let r;try{r=pv(t,{withFileTypes:!0})}catch{return n}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;fv(Ml(t,s.name),e+1,n)}else s.isFile()&&s.name.endsWith(".bulb.md")&&n.push(Ml(t,s.name));return n}function YQ(t){let e=Ml(Pd(t),"batches"),n;try{n=pv(e,{withFileTypes:!0})}catch{return[]}return n.filter(r=>r.isDirectory()).map(r=>{let s=0;try{s=dv(Ml(e,r.name)).mtimeMs}catch{}return{name:r.name,mtime:s}}).sort((r,s)=>s.mtime-r.mtime).map(r=>r.name)}function WQ(t){return fv(t,0,[]).map(e=>{let n=0;try{n=dv(e).mtimeMs}catch{}let r,s=!1;try{let o=GQ(e,"utf8");r=ga(o.slice(0,1024));let i=$n(o);s=!!i&&Jm(Eo(i))}catch{}return{path:e,name:r??VQ(e).replace(/\.bulb\.md$/,""),mtime:n,serverOnly:s}})}import{mkdir as o3,readFile as XQ,writeFile as i3}from"fs/promises";import{join as hv}from"path";var zQ=20100,mv=100,ZQ=19;var u3=mv-1;function eq(){return hv(jr(),"blocks")}function tq(t){return hv(eq(),`${t}.json`)}async function nq(t){try{let e=JSON.parse(await XQ(tq(t),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function rq(t){let e=Sn(t);for(let n=0;n<ZQ;n++){let r=await nq(zQ+n*mv);if(r?.cwd===e)return s=>r.slots[Sn(s)]?.usedAt??0}return()=>0}import{readFile as sq}from"fs/promises";function yv(t){if(t.server.trim())return"server-side code (server.ts)";let e=t.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||t.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}async function oq(t){try{let e=$n(await sq(t,"utf-8"));return e?yv(Eo(e)):void 0}catch{return}}function iq(t){let e=$n(t);if(!e)return t;let n=e.files.get("code.tsx");if(!n)return t;let r=zT(n);if(!r.length)return t;let s=e.files.get("config.json"),o={};if(s)try{let c=JSON.parse(s);c&&typeof c=="object"&&(o=c)}catch{}let i=o.dependencies&&typeof o.dependencies=="object"?{...o.dependencies}:{},a=r.filter(c=>!(c in i));if(!a.length)return t;for(let c of a)i[c]="latest";o.dependencies=i;let l={name:e.frontmatter.name};for(let[c,h]of e.files){let u=Ud(c);u&&(l[u]=h)}return l.config=JSON.stringify(o,null,2),Wd(l)}import{spawn as gv}from"child_process";import{basename as aq}from"path";function lq(){return process.env.TYPEBULB_EDITOR||"code"}var cq=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i;function uq(t,e,n){return n==null?[e]:cq.test(aq(t))?["-g",`${e}:${n}`]:[`+${n}`,e]}function pq(t,e){let n=lq();return{command:n,args:uq(n,t,e)}}function dq(t,e){let{command:n,args:r}=pq(t,e),s=process.platform==="win32"?gv("cmd.exe",["/d","/s","/c",n,...r],{detached:!0,stdio:"ignore",windowsHide:!0}):gv(n,r,{detached:!0,stdio:"ignore"});s.on("error",o=>console.error("[typebulb] editor launch failed:",o?.message??o)),s.unref()}import{readFileSync as fq,writeFileSync as hq,mkdirSync as mq}from"fs";import{join as yq}from"path";function Bd(){return yq(jr(),"trust.json")}function Rd(){try{let t=JSON.parse(fq(Bd(),"utf8"));return new Set(Array.isArray(t)?t:[])}catch{return new Set}}function gq(t){try{mq(jr(),{recursive:!0}),hq(Bd(),JSON.stringify([...t]))}catch(e){throw new Error(`can't write ${Bd()} \u2014 trust not remembered (unwritable home; sandboxed shell?): ${e.message}`)}}function Tq(t){return Rd().has(Sn(t))}function kq(t,e){let n=Rd(),r=Sn(t);(e?n.has(r):!n.has(r))||(e?n.add(r):n.delete(r),gq(n))}function Aq(){return[...Rd()]}import{readFileSync as S3,existsSync as vq}from"fs";import*as js from"path";import{fileURLToPath as wq}from"url";function bq(){let t=js.dirname(wq(import.meta.url));for(;!vq(js.join(t,"package.json"));){let e=js.dirname(t);if(e===t)break;t=e}return t}function xq(){return js.join(bq(),"SKILL.md")}import*as pn from"fs/promises";import*as Qn from"path";import{createHash as Eq}from"crypto";var Tv=(t,e)=>Qn.join("typebulbs","u",t,`${e}.bulb.md`),Od=t=>`${t.origin}/u/${encodeURIComponent(t.userSlug)}/${encodeURIComponent(t.slug)}.md`,$l=t=>t.split("/").map(encodeURIComponent).join("/"),mi=t=>`${t.origin}/u/${encodeURIComponent(t.userSlug)}/${encodeURIComponent(t.slug)}/assets`;async function Ld(t,e,n){let r=[...t],s=async()=>{for(let o=r.shift();o!==void 0;o=r.shift())await n(o)};await Promise.all(Array.from({length:Math.min(e,t.length)},s))}var Dd=t=>Eq("md5").update(t).digest("hex");function Ks(t){try{return JSON.parse(t).error||t}catch{return t}}async function Qd(t,e){try{let n=await fetch(mi(t),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});return n.ok?n.headers.get("content-type")?.includes("json")?{entries:await n.json()}:{error:"manifest response is not JSON \u2014 wrong origin?"}:{error:`manifest request failed (${n.status}): ${Ks(await n.text())}`}}catch(n){return{error:n instanceof Error?n.message:String(n)}}}function Cq(t,e,n){if(/^https?:\/\//i.test(t)){let o=new URL(t),i=o.pathname.split("/").filter(Boolean).map(decodeURIComponent),a=i[0]==="api"&&i[1]==="scripts"?i.slice(2):i;if(a[0]!=="u"||!a[1]||!a[2])throw new Error(`Not a bulb URL: ${t}
1148
1148
  Expected <origin>/u/<user>/<slug>`);let l=a[1],c=a[2].replace(/(\.bulb)?\.md$/,"");return{origin:o.origin,userSlug:l,slug:c,dest:Qn.join(e,Tv(l,c))}}let r=Qn.resolve(e,t),s=uv(r);if(!s)throw new Error(`Not a conventional bulb path: ${t}
1149
1149
  A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:n,...s,dest:r}}async function Iq(t,e){let n=await Qd(t,e);if("error"in n||!n.entries.length)return{kind:"none"};let r=n.entries,s=hi(t.dest),o=[],i=[],a=0;for(let l of r){let c=await pn.readFile(Qn.join(s,...l.path.split("/"))).catch(()=>{});c===void 0?o.push(l.path):Dd(c)===l.md5?a++:e.force?o.push(l.path):i.push(l.path)}return i.length?{kind:"conflict",paths:i}:{kind:"plan",toGet:o,unchanged:a}}async function Sq(t,e,n){let r=hi(t.dest),s=[],o=0;return await Ld(e.toGet,4,async i=>{try{let a=await fetch(`${mi(t)}/${$l(i)}`,{headers:n.token?{Authorization:`Bearer ${n.token}`}:{},signal:AbortSignal.timeout(n.timeoutMs??3e4)});if(!a.ok){s.push(`${i}: HTTP ${a.status}`);return}let l=Qn.join(r,...i.split("/"));await pn.mkdir(Qn.dirname(l),{recursive:!0}),await pn.writeFile(l,new Uint8Array(await a.arrayBuffer())),o++}catch(a){s.push(`${i}: ${a instanceof Error?a.message:String(a)}`)}}),{downloaded:o,unchanged:e.unchanged,errors:s}}async function _q(t,e={}){let n=await fetch(Od(t),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!n.ok)return{kind:"http-error",status:n.status};let r=n.headers.get("content-type");if(!r?.includes("text/markdown"))return{kind:"not-markdown",contentType:r};let s=await n.text(),o;try{o=await pn.readFile(t.dest,"utf-8")}catch{}let i=o!==void 0&&Nq(o,s);if(o!==void 0&&!i&&!e.force){let{mtime:c}=await pn.stat(t.dest);return{kind:"conflict",dest:t.dest,localMtime:c,remoteLastModified:n.headers.get("last-modified")}}let a=await Iq(t,e);if(a.kind==="conflict")return{kind:"asset-conflict",dest:t.dest,paths:a.paths};if(!i){await pn.mkdir(Qn.dirname(t.dest),{recursive:!0}),await pn.writeFile(t.dest,s);let c=new Date(n.headers.get("last-modified")??"");isNaN(c.getTime())||await pn.utimes(t.dest,new Date,c)}let l=a.kind==="plan"?await Sq(t,a,e):void 0;return i?{kind:"up-to-date",dest:t.dest,assets:l}:{kind:"written",dest:t.dest,created:o===void 0,assets:l}}function Nq(t,e){let n=o=>o.replace(/\r\n/g,`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typebulb",
3
- "version": "0.49.3",
3
+ "version": "0.50.0",
4
4
  "description": "Typebulb CLI to run single-file markdown apps called bulbs, either as standalone web apps or embedded in agent responses.",
5
5
  "keywords": [
6
6
  "bulb",