@blyp/core 0.1.22 → 0.1.23
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/README.md +52 -726
- package/dist/ai/anthropic.js +7 -7
- package/dist/ai/anthropic.mjs +7 -7
- package/dist/ai/better-agent/index.d.ts +3 -0
- package/dist/ai/better-agent/normalize.d.ts +18 -0
- package/dist/ai/better-agent/plugin.d.ts +3 -0
- package/dist/ai/better-agent/tracker.d.ts +35 -0
- package/dist/ai/better-agent.js +701 -0
- package/dist/ai/better-agent.mjs +701 -0
- package/dist/ai/openai.js +4 -4
- package/dist/ai/openai.mjs +4 -4
- package/dist/ai/shared/trace.d.ts +3 -0
- package/dist/ai/shared/types.d.ts +12 -2
- package/dist/index.js +9 -9
- package/dist/index.mjs +9 -9
- package/package.json +14 -1
package/dist/ai/openai.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import zt from'pino';import {createJiti}from'jiti';import {createRequire}from'module';import {AsyncLocalStorage}from'async_hooks';import w,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import z$1,{resolve,dirname}from'path';import Pn from'os';import {z}from'zod';import {gzipSync}from'fflate';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var dn=Object.defineProperty;var pn=(e,t,n)=>t in e?dn(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var l=(e,t,n)=>pn(e,typeof t!="symbol"?t+"":t,n);var gn=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Je=new Map;function mn(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,n="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof n=="string"&&(n.includes("Cannot find module")||n.includes("Cannot find package"))}function O(e,t,n=`@blyp/core/${e}`){let r=`@blyp/core/${e}`,o=`${r}::${n}`,a=Je.get(o);if(a)return a;try{let s=gn(n);return Je.set(o,s),s}catch(s){if(!mn(s))throw s;let i=t.map(u=>`"${u}"`).join(", "),c=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${r}". Install ${i} to use this API. Example: bun add ${c}. You can also import directly from "${r}".`,{cause:s instanceof Error?s:void 0})}}var hn=createRequire(typeof __filename=="string"?__filename:import.meta.url),Ce=null;function bn(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,n="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof n=="string"&&(n.includes("Cannot find module")||n.includes("Cannot find package"))}function Cn(e){if(typeof e=="function")return e;if(!e||typeof e!="object")return null;let t="default"in e?e.default:void 0;return typeof t=="function"?t:null}function Ge(){if(Ce)return Ce;let e;try{e=hn("pino-pretty");}catch(n){throw bn(n)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:n instanceof Error?n:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:n instanceof Error?n:void 0})}let t=Cn(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return Ce=t,t}var Rn=new AsyncLocalStorage;function we(){return Rn.getStore()}function te(){return we()?.activeLogger}function Re(){return we()?.traceId}function Te(){let e=we();return !e||!e.requestScopedLoggerActive||!e.structuredCollectorActive?false:(e.mixedLoggerWarningShown||(e.mixedLoggerWarningShown=true,console.warn("[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active.")),true)}function ne(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=T(n.cause)),t}function T(e,t=new WeakSet){if(e instanceof Error)return ne(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(n=>T(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[r,o]of Object.entries(e))n[r]=T(o,t);return t.delete(e),n}return e}function ke(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=T(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var Tn="[REDACTED]",kn=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"];var Sn=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],Ln=/\b(?:\d[ -]*?){16}\b/g;function Ve(e){let t=new Set,n=[];for(let r of e)typeof r!="string"||r.length===0||t.has(r)||(t.add(r),n.push(r));return n}function vn(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Dn(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xn(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function En(e){return e.split(".").filter(Boolean)}function Se(e,t,n=0,r=0){if(n===e.length)return r===t.length;let o=e[n];if(o==="**"){if(n===e.length-1)return true;for(let a=r;a<=t.length;a+=1)if(Se(e,t,n+1,a))return true;return false}return r>=t.length||o!=="*"&&o!==t[r]?false:Se(e,t,n+1,r+1)}function _n(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>Se(En(n),e))}function An(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,r=false;for(let o=t.length-1;o>=0;o-=1){let a=Number(t[o]);r&&(a*=2,a>9&&(a-=9)),n+=a,r=!r;}return n%10===0}function Xe(e,t,n){if(n||t.disablePatternScanning)return e;let r=e;for(let{type:o,pattern:a}of Sn)r=r.replace(a,`[REDACTED:${o}]`);r=r.replace(Ln,o=>An(o)?"[REDACTED:card]":o);for(let o of t.patterns)r=r.replace(vn(o),"[REDACTED:pattern]");return r}function re(e,t,n,r){if(typeof e=="string")return Xe(e,t,!!r.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((a,s)=>re(a,t,n,{path:[...r.path,String(s)],skipPatternScanning:r.skipPatternScanning}));if(!Dn(e))return e;let o={};for(let[a,s]of Object.entries(e)){let i=[...r.path,a];if(n.has(a.toLowerCase())||_n(i,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){o[a]=Tn;continue}o[a]=re(s,t,n,{path:i,skipPatternScanning:r.skipPatternScanning});continue}o[a]=re(s,t,n,{path:i,skipPatternScanning:r.skipPatternScanning});}return o}function S(e,t){return {keys:Ve([...kn,...e?.keys??[],...t?.keys??[]]),paths:Ve([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function h(e,t,n={path:[]}){let r=T(e);return re(r,t,xn(t),n)}function
|
|
1
|
+
import zt from'pino';import {createJiti}from'jiti';import {createRequire}from'module';import {AsyncLocalStorage}from'async_hooks';import w,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import z$1,{resolve,dirname}from'path';import Pn from'os';import {z}from'zod';import {gzipSync}from'fflate';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var dn=Object.defineProperty;var pn=(e,t,n)=>t in e?dn(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var l=(e,t,n)=>pn(e,typeof t!="symbol"?t+"":t,n);var gn=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Je=new Map;function mn(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,n="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof n=="string"&&(n.includes("Cannot find module")||n.includes("Cannot find package"))}function O(e,t,n=`@blyp/core/${e}`){let r=`@blyp/core/${e}`,o=`${r}::${n}`,a=Je.get(o);if(a)return a;try{let s=gn(n);return Je.set(o,s),s}catch(s){if(!mn(s))throw s;let i=t.map(u=>`"${u}"`).join(", "),c=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${r}". Install ${i} to use this API. Example: bun add ${c}. You can also import directly from "${r}".`,{cause:s instanceof Error?s:void 0})}}var hn=createRequire(typeof __filename=="string"?__filename:import.meta.url),Ce=null;function bn(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,n="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof n=="string"&&(n.includes("Cannot find module")||n.includes("Cannot find package"))}function Cn(e){if(typeof e=="function")return e;if(!e||typeof e!="object")return null;let t="default"in e?e.default:void 0;return typeof t=="function"?t:null}function Ge(){if(Ce)return Ce;let e;try{e=hn("pino-pretty");}catch(n){throw bn(n)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:n instanceof Error?n:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:n instanceof Error?n:void 0})}let t=Cn(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return Ce=t,t}var Rn=new AsyncLocalStorage;function we(){return Rn.getStore()}function te(){return we()?.activeLogger}function Re(){return we()?.traceId}function Te(){let e=we();return !e||!e.requestScopedLoggerActive||!e.structuredCollectorActive?false:(e.mixedLoggerWarningShown||(e.mixedLoggerWarningShown=true,console.warn("[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active.")),true)}function ne(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=T(n.cause)),t}function T(e,t=new WeakSet){if(e instanceof Error)return ne(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(n=>T(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[r,o]of Object.entries(e))n[r]=T(o,t);return t.delete(e),n}return e}function ke(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=T(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var Tn="[REDACTED]",kn=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"];var Sn=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],Ln=/\b(?:\d[ -]*?){16}\b/g;function Ve(e){let t=new Set,n=[];for(let r of e)typeof r!="string"||r.length===0||t.has(r)||(t.add(r),n.push(r));return n}function vn(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Dn(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xn(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function En(e){return e.split(".").filter(Boolean)}function Se(e,t,n=0,r=0){if(n===e.length)return r===t.length;let o=e[n];if(o==="**"){if(n===e.length-1)return true;for(let a=r;a<=t.length;a+=1)if(Se(e,t,n+1,a))return true;return false}return r>=t.length||o!=="*"&&o!==t[r]?false:Se(e,t,n+1,r+1)}function _n(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>Se(En(n),e))}function An(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,r=false;for(let o=t.length-1;o>=0;o-=1){let a=Number(t[o]);r&&(a*=2,a>9&&(a-=9)),n+=a,r=!r;}return n%10===0}function Xe(e,t,n){if(n||t.disablePatternScanning)return e;let r=e;for(let{type:o,pattern:a}of Sn)r=r.replace(a,`[REDACTED:${o}]`);r=r.replace(Ln,o=>An(o)?"[REDACTED:card]":o);for(let o of t.patterns)r=r.replace(vn(o),"[REDACTED:pattern]");return r}function re(e,t,n,r){if(typeof e=="string")return Xe(e,t,!!r.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((a,s)=>re(a,t,n,{path:[...r.path,String(s)],skipPatternScanning:r.skipPatternScanning}));if(!Dn(e))return e;let o={};for(let[a,s]of Object.entries(e)){let i=[...r.path,a];if(n.has(a.toLowerCase())||_n(i,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){o[a]=Tn;continue}o[a]=re(s,t,n,{path:i,skipPatternScanning:r.skipPatternScanning});continue}o[a]=re(s,t,n,{path:i,skipPatternScanning:r.skipPatternScanning});}return o}function S(e,t){return {keys:Ve([...kn,...e?.keys??[],...t?.keys??[]]),paths:Ve([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function h(e,t,n={path:[]}){let r=T(e);return re(r,t,xn(t),n)}function K(e,t){return typeof e=="string"?Xe(e,t,false):ke(h(e,t))}function Ye(){return z$1.join(Pn.homedir(),".blyp","queue.db")}var Mn=z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),Ze=z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),ve=z.string().trim().min(1);function De(e){return Mn.safeParse(e).success}function xe(e){return Ze.safeParse(e).success}function E(e){return ve.safeParse(e).success}var Ee="/inngest";z.union([z.literal("betterstack"),z.literal("databuddy"),z.literal("posthog"),z.literal("sentry"),z.undefined(),z.object({type:z.literal("otlp"),name:ve})]);function On(e){try{return e()}catch{return}}function In(){return Math.random().toString(36).slice(2,10)}function et(){let e=On(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${In()}`}function Nn(e,t=new Set){return (n,r,o)=>{if(t.has(n)||typeof console>"u")return;let a=console[e];if(typeof a=="function"){if(t.add(n),o===void 0){a.call(console,r);return}a.call(console,r,o);}}}function v(e){return Nn("warn",e)}var Un="@blyp/core",qn=".gitignore",ot=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],$n="blyp.config.json",Kn="https://us.i.posthog.com",Wn="blyp-app",Hn=Wn,Qn=new Set,D=v(Qn),at={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},it={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:at},_e={enabled:true,path:Ee},st=S(),I={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},R={enabled:false,memoryBufferSize:500,durableQueuePath:Ye(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:I},ct={maxRetries:1,backoffMs:100},Jn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:ct},tt={pretty:true,level:"info",destination:"file",file:it,clientLogging:_e,redact:st,connectors:{delivery:R}},W=null;function Gn(e){let t=e;for(;;){let n=resolve(t,"package.json");if(existsSync(n))try{let o=JSON.parse(readFileSync(n,"utf-8"));if(E(o.name))return o.name}catch{}let r=dirname(t);if(r===t)return;t=r;}}function Pe(e=process.cwd()){return Gn(e)??Hn}function Vn(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:Ee},redact:st,connectors:{delivery:R}}}function Xn(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==Un}catch{return true}}function Yn(e){if(ot.some(n=>existsSync(resolve(e,n))))return;let t=resolve(e,$n);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(Vn(),null,2)}
|
|
2
2
|
`);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function Zn(e){let t=resolve(e,qn);if(!existsSync(t)){try{writeFileSync(t,`logs
|
|
3
3
|
.blyp
|
|
4
4
|
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=readFileSync(t,"utf-8"),r=["logs",".blyp"].filter(a=>{let s=a.replace(".","\\.");return !new RegExp(`^(?:/?${s}/?)\\s*$`,"m").test(n)});if(r.length===0)return;let o=n.endsWith(`
|
|
5
5
|
`)?"":`
|
|
6
6
|
`;appendFileSync(t,`${o}${r.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function er(){let e=process.cwd();Xn(e)&&(Yn(e),Zn(e));}function tr(){let e=process.cwd(),t=ot.map(r=>resolve(e,r)).filter(r=>existsSync(r));if(t.length===0)return null;if(t.length>1){let r=t[0];D(`config-multiple:${r}`,`[Blyp] Warning: Multiple config files found. Using ${r} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function ut(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(D(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function nr(e){try{let t=readFileSync(e,"utf-8");return ut(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function rr(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return ut(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function or(e){return e.type==="json"?nr(e.path):rr(e.path)}function nt(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function ar(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function ir(e,t){return {...ct,...e,...t}}function sr(e,t){return {...Jn,...e,...t,retry:ir(e?.retry,t?.retry)}}function cr(e){let t=e.model??"blypLog",r=e.client?.[t];return !!r&&typeof r.create=="function"}function ur(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function lr(e,t){if(!e)return;let n=e.adapter,r=false;t==="json"?D("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?D(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?nt(n)?(r=cr({...n,model:n.model??"blypLog"}),r||D("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):ar(n)&&(r=ur(n),r||D("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):D("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=nt(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:o,delivery:sr(void 0,e.delivery),ready:r,status:r?"enabled":"missing"}}function dr(e,t){return {...at,...e,...t}}function pr(e,t){return {...it,...e,...t,rotation:dr(e?.rotation,t?.rotation)}}function fr(e,t){return {..._e,...e,...t,path:t?.path??e?.path??_e.path}}function gr(e,t){return S(e,t)}function mr(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??I.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??I.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??I.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??I.multiplier),jitter:t?.jitter??e?.jitter??I.jitter}}function yr(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??R.durableQueuePath;return {enabled:t?.enabled??e?.enabled??R.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??R.memoryBufferSize)),durableQueuePath:E(n)?n:R.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??R.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??R.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??R.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??R.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??R.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??R.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??R.overflowStrategy,retry:mr(e?.retry,t?.retry),durableReady:false}}function hr(e,t,n){if(!(!e&&!t))return lr({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function br(e,t){let n=t?.enabled??e?.enabled??false,r=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,a=t?.errorTracking?.mode??o?.mode??"auto",s=t?.errorTracking?.enabled??o?.enabled??n,i=n&&s&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:r,host:t?.host??e?.host??Kn,serviceName:t?.serviceName??e?.serviceName??Pe(),errorTracking:{enabled:s,mode:a,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??a==="auto",ready:i,status:i?"enabled":"missing"}}}function Cr(e,t){let n=t?.enabled??e?.enabled??false,r=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,a=n&&E(r)&&E(o);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:r,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:a,status:a?"enabled":"missing"}}function wr(e,t){let n=t?.sourceToken??e?.sourceToken,r=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,a=e?.enabled===true?e?.errorTracking:void 0,s=Rr(o,a,t?.errorTracking),i=o&&E(n)&&De(r);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:r,serviceName:t?.serviceName??e?.serviceName??Pe(),errorTracking:s,ready:i,status:i?"enabled":"missing"}}function Rr(e,t,n){let r=n?.dsn??t?.dsn,o=n?.enabled??t?.enabled??e,a=o&&E(r);return {enabled:o,dsn:r,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:a,status:a?"enabled":"missing"}}function Tr(e,t){let n=t?.dsn??e?.dsn,r=t?.enabled??e?.enabled??false,o=r&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function kr(e,t){let n=t?.endpoint??e?.endpoint,r=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},a=r&&De(n);return {name:t?.name??e?.name??"",enabled:r,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??Pe(),ready:a,status:a?"enabled":"missing"}}function Sr(e,t){let n=t??e??[],r=new Map;for(let o of n)!o||typeof o.name!="string"||o.name.length===0||(r.has(o.name)&&D(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),r.set(o.name,kr(void 0,o)));return Array.from(r.values())}function Lr(e,t){return {betterstack:wr(e?.betterstack,t?.betterstack),databuddy:Cr(e?.databuddy,t?.databuddy),posthog:br(e?.posthog,t?.posthog),sentry:Tr(e?.sentry,t?.sentry),otlp:Sr(e?.otlp,t?.otlp),delivery:yr(e?.delivery,t?.delivery)}}function Ae(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:pr(e.file,t.file),database:hr(e.database,t.database,n.configFileType),clientLogging:fr(e.clientLogging,t.clientLogging),redact:gr(e.redact,t.redact),connectors:Lr(e.connectors,t.connectors)}}function vr(){if(
|
|
9
|
-
`),n=null;for(let r=2;r<t.length;r+=1){let o=t[r];if(!o)continue;let a=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!a)continue;let s=a[1]||"",i=parseInt(a[2]||"0",10)||null;if(s&&!s.includes("node_modules")&&!Dr(s)){let c=xr(s);if(!ae(c).startsWith("dist/"))return {file:c,line:i};n??(n={file:c,line:i});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var ft
|
|
8
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function er(){let e=process.cwd();Xn(e)&&(Yn(e),Zn(e));}function tr(){let e=process.cwd(),t=ot.map(r=>resolve(e,r)).filter(r=>existsSync(r));if(t.length===0)return null;if(t.length>1){let r=t[0];D(`config-multiple:${r}`,`[Blyp] Warning: Multiple config files found. Using ${r} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function ut(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(D(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function nr(e){try{let t=readFileSync(e,"utf-8");return ut(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function rr(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return ut(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function or(e){return e.type==="json"?nr(e.path):rr(e.path)}function nt(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function ar(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function ir(e,t){return {...ct,...e,...t}}function sr(e,t){return {...Jn,...e,...t,retry:ir(e?.retry,t?.retry)}}function cr(e){let t=e.model??"blypLog",r=e.client?.[t];return !!r&&typeof r.create=="function"}function ur(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function lr(e,t){if(!e)return;let n=e.adapter,r=false;t==="json"?D("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?D(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?nt(n)?(r=cr({...n,model:n.model??"blypLog"}),r||D("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):ar(n)&&(r=ur(n),r||D("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):D("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=nt(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:o,delivery:sr(void 0,e.delivery),ready:r,status:r?"enabled":"missing"}}function dr(e,t){return {...at,...e,...t}}function pr(e,t){return {...it,...e,...t,rotation:dr(e?.rotation,t?.rotation)}}function fr(e,t){return {..._e,...e,...t,path:t?.path??e?.path??_e.path}}function gr(e,t){return S(e,t)}function mr(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??I.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??I.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??I.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??I.multiplier),jitter:t?.jitter??e?.jitter??I.jitter}}function yr(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??R.durableQueuePath;return {enabled:t?.enabled??e?.enabled??R.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??R.memoryBufferSize)),durableQueuePath:E(n)?n:R.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??R.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??R.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??R.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??R.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??R.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??R.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??R.overflowStrategy,retry:mr(e?.retry,t?.retry),durableReady:false}}function hr(e,t,n){if(!(!e&&!t))return lr({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function br(e,t){let n=t?.enabled??e?.enabled??false,r=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,a=t?.errorTracking?.mode??o?.mode??"auto",s=t?.errorTracking?.enabled??o?.enabled??n,i=n&&s&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:r,host:t?.host??e?.host??Kn,serviceName:t?.serviceName??e?.serviceName??Pe(),errorTracking:{enabled:s,mode:a,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??a==="auto",ready:i,status:i?"enabled":"missing"}}}function Cr(e,t){let n=t?.enabled??e?.enabled??false,r=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,a=n&&E(r)&&E(o);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:r,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:a,status:a?"enabled":"missing"}}function wr(e,t){let n=t?.sourceToken??e?.sourceToken,r=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,a=e?.enabled===true?e?.errorTracking:void 0,s=Rr(o,a,t?.errorTracking),i=o&&E(n)&&De(r);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:r,serviceName:t?.serviceName??e?.serviceName??Pe(),errorTracking:s,ready:i,status:i?"enabled":"missing"}}function Rr(e,t,n){let r=n?.dsn??t?.dsn,o=n?.enabled??t?.enabled??e,a=o&&E(r);return {enabled:o,dsn:r,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:a,status:a?"enabled":"missing"}}function Tr(e,t){let n=t?.dsn??e?.dsn,r=t?.enabled??e?.enabled??false,o=r&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function kr(e,t){let n=t?.endpoint??e?.endpoint,r=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},a=r&&De(n);return {name:t?.name??e?.name??"",enabled:r,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??Pe(),ready:a,status:a?"enabled":"missing"}}function Sr(e,t){let n=t??e??[],r=new Map;for(let o of n)!o||typeof o.name!="string"||o.name.length===0||(r.has(o.name)&&D(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),r.set(o.name,kr(void 0,o)));return Array.from(r.values())}function Lr(e,t){return {betterstack:wr(e?.betterstack,t?.betterstack),databuddy:Cr(e?.databuddy,t?.databuddy),posthog:br(e?.posthog,t?.posthog),sentry:Tr(e?.sentry,t?.sentry),otlp:Sr(e?.otlp,t?.otlp),delivery:yr(e?.delivery,t?.delivery)}}function Ae(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:pr(e.file,t.file),database:hr(e.database,t.database,n.configFileType),clientLogging:fr(e.clientLogging,t.clientLogging),redact:gr(e.redact,t.redact),connectors:Lr(e.connectors,t.connectors)}}function vr(){if(W!==null)return W;er();let e=tr();if(e){let t=or(e);W=Ae(tt,t,{configFileType:e.type});}else W=Ae(tt);return W}function lt(e={}){return Ae(vr(),e)}var dt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function ae(e){return e.replace(/\\/g,"/")}function Dr(e){let t=ae(e);return t.startsWith("node:")||t.includes("/node_modules/pino")||t.includes("/node_modules/pino-pretty")||t.includes("/node_modules/@blyp/core/")||t.includes("/blyp/src/core/")||t.includes("/blyp/src/frameworks/")||t.includes("/blyp/src/posthog/")||t.includes("/blyp/dist/")}function xr(e){let t=ae(e),n=ae(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function pt(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
|
|
9
|
+
`),n=null;for(let r=2;r<t.length;r+=1){let o=t[r];if(!o)continue;let a=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!a)continue;let s=a[1]||"",i=parseInt(a[2]||"0",10)||null;if(s&&!s.includes("node_modules")&&!Dr(s)){let c=xr(s);if(!ae(c).startsWith("dist/"))return {file:c,line:i};n??(n={file:c,line:i});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var ft=K;function gt(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function mt(e,t,n,r,o=S()){let{file:a,line:s}=pt(),i=ft(t,o),c={timestamp:new Date().toISOString(),level:dt[e],message:gt(i)},u=Re();return t instanceof Error&&(c.error=h(ne(t),o)),a&&(c.caller=s!==null?`${a}:${s}`:a),n.length===1?c.data=h(n[0],o):n.length>1&&(c.data=h(n,o)),Object.keys(r).length>0&&(c.bindings=h(r,o)),u&&(c.traceId=u),c}function yt(e,t,n,r,o=S()){let{file:a,line:s}=pt(),i=h(n,o),c=Re(),u={message:gt(ft(t,o)),...i};return a&&(u.caller=s!==null?`${a}:${s}`:a),Object.keys(r).length>0&&(u.bindings=h(r,o)),c&&u.traceId===void 0&&(u.traceId=c),u.level=typeof i.level=="string"&&i.level.length>0?i.level:dt[e],u.timestamp=typeof i.timestamp=="string"&&i.timestamp.length>0?i.timestamp:new Date().toISOString(),u}function ht(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function _r(e){return Buffer.from(gzipSync(e))}function Ar(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function ie(e){w.mkdirSync(e,{recursive:true});}function Pr(e){try{return w.statSync(e).size}catch{return 0}}function Br(e){let t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),a=String(e.getUTCMinutes()).padStart(2,"0"),s=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${n}${r}T${o}${a}${s}Z`}function Mr(e,t){let n=`${e}${t}`,r=1;for(;w.existsSync(n);)n=`${e}-${r}${t}`,r+=1;return n}function Or(e,t,n,r){let o=`${t}.`;try{let a=w.readdirSync(e).filter(i=>i.startsWith(o)&&(i.endsWith(".ndjson")||i.endsWith(".ndjson.gz"))).map(i=>z$1.join(e,i)).sort((i,c)=>w.statSync(i).mtimeMs-w.statSync(c).mtimeMs),s=Math.max(a.length-n,0);for(let i=0;i<s;i+=1)w.rmSync(a[i]);}catch(a){r(`Failed to prune archives for ${t}`,a);}}function Ir(){let e=new WeakSet;return (t,n)=>{if(typeof n=="function")return `[Function: ${n.name||"anonymous"}]`;if(n===void 0)return "[undefined]";if(typeof n=="symbol")return n.toString();if(n!==null&&typeof n=="object"){if(e.has(n))return "[Circular]";e.add(n);}return n}}function Nr(e){return JSON.stringify(e,Ir())}function Fr(e){let t=e.file,n=t?.dir||e.logDir||z$1.join(process.cwd(),"logs"),r=t?.archiveDir||z$1.join(n,"archive"),o=t?.rotation;return {enabled:t?.enabled??true,dir:n,archiveDir:r,rotationEnabled:o?.enabled??true,maxSizeBytes:o?.maxSizeBytes??10*1024*1024,maxArchives:o?.maxArchives??5,compress:o?.compress??true}}var Be=class{constructor(t,n={}){l(this,"config");l(this,"gzip");l(this,"warn");l(this,"combined");l(this,"error");this.config=Fr(t),this.gzip=n.gzip??_r,this.warn=n.warn??Ar,this.combined={activePath:z$1.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:z$1.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(ie(this.config.dir),ie(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let n=`${Nr(t)}
|
|
10
10
|
`;this.enqueue(this.combined,n),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,n);}enqueue(t,n){t.queue.push(n),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let n=t.queue.shift();if(n!==void 0)try{this.append(t,n);}catch(r){this.warn(`Failed writing log line for ${t.archivePrefix}`,r);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=Pr(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),w.closeSync(w.openSync(t.activePath,"a")),t.bytes=0);}append(t,n){ie(this.config.dir);let r=Buffer.byteLength(n,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+r>this.config.maxSizeBytes&&this.rotate(t),w.appendFileSync(t.activePath,n,"utf8"),t.bytes+=r;}rotate(t){if(ie(this.config.archiveDir),!w.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let n=Br(new Date),r=z$1.join(this.config.archiveDir,`${t.archivePrefix}.${n}`),o=Mr(r,".ndjson");if(w.renameSync(t.activePath,o),this.config.compress)try{let a=`${o}.gz`,s=this.gzip(w.readFileSync(o));w.writeFileSync(a,s),w.rmSync(o);}catch(a){this.warn(`Failed to gzip archive ${o}`,a);}t.bytes=0,Or(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function bt(e){return new Be(e)}var Me=class{constructor(t){this.logger=t;l(this,"isAsync",false);l(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function Ct(e){return new Me(bt(e))}function wt(e){let t=e.db;if(typeof t?.insert!="function"||e.table===void 0)throw new Error("[Blyp] Drizzle database adapter is missing a db.insert function or table reference.");return {async insert(n){n.length!==0&&await t.insert(e.table).values(n);}}}function zr(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function Rt(e){let t=e.client,n=e.model??"blypLog",r=t[n];if(!r||typeof r.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${n}" delegate or its create method.`);let o=r,a=typeof o.createMany=="function";async function s(i){if(typeof t.$transaction=="function"){await t.$transaction(i.map(c=>o.create({data:c})));return}for(let c of i)await o.create({data:c});}return {async insert(i){if(i.length!==0){if(i.length===1){await o.create({data:i[0]});return}if(!a||typeof o.createMany!="function"){await s(i);return}try{await o.createMany({data:i});}catch(c){if(!zr(c))throw c;a=false,await s(i);}}}}}function Tt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function j(e){return typeof e=="string"&&e.length>0?e:null}function Ur(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function kt(e){let t=T(e);return {id:randomUUID(),timestamp:Ur(e.timestamp),level:e.level,message:e.message,caller:j(e.caller),type:j(e.type),traceId:j(e.traceId),groupId:j(e.groupId),method:j(e.method),path:j(e.path),status:Tt(e.status),duration:Tt(e.duration),hasError:t.error!=null,data:t.data??null,bindings:t.bindings??null,error:t.error??null,events:t.events??null,record:t,createdAt:new Date}}function qr(e){return !!e&&e.type==="prisma"}function $r(e){return !!e&&e.type==="drizzle"}function St(e){if(qr(e.adapter))return Rt(e.adapter);if($r(e.adapter))return wt(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function Kr(e){return new Promise(t=>{setTimeout(t,e);})}var se=class{constructor(t){this.config=t;l(this,"isAsync",true);l(this,"isReady",true);l(this,"warnOnce",v(new Set));l(this,"queue",[]);l(this,"writer");l(this,"timer",null);l(this,"processing",false);l(this,"closed",false);l(this,"terminalError",null);l(this,"activeDispatch",null);this.writer=St(t);}write(t){this.closed||(this.enqueue(kt(t)),this.scheduleDispatch());}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=(async()=>{if(await this.drain(),this.terminalError)throw this.terminalError})(),n=null;try{await Promise.race([t,new Promise((r,o)=>{n=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),o(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{n&&clearTimeout(n);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let n=this.queue.length-this.config.delivery.maxQueueSize;if(!(n<=0)){if(this.warnOnce("database-overflow",`[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`),this.config.delivery.overflowStrategy==="drop-new"){this.queue.splice(this.config.delivery.maxQueueSize);return}this.queue.splice(0,n);}}scheduleDispatch(){if(!this.processing){if(this.config.delivery.strategy==="immediate"){this.drain();return}if(this.queue.length>=this.config.delivery.batchSize){this.drain();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.drain();},this.config.delivery.flushIntervalMs));}}async drain(){if(this.processing){this.activeDispatch&&await this.activeDispatch;return}this.processing=true,this.activeDispatch=this.processQueue();try{await this.activeDispatch;}finally{this.processing=false,this.activeDispatch=null;}}async processQueue(){for(;this.queue.length>0;){let t=this.config.delivery.strategy==="batch"?Math.max(1,this.config.delivery.batchSize):1,n=this.queue.splice(0,t);try{await this.insertWithRetry(n);}catch(r){let o=r instanceof Error?r:new Error(String(r??"Unknown database logging failure"));throw this.terminalError=o,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,o),o}}}async insertWithRetry(t){let n=Math.max(1,this.config.delivery.retry.maxRetries+1),r=0;for(;r<n;){r+=1;try{await this.writer.insert(t);return}catch(o){if(r>=n)throw o;await Kr(this.config.delivery.retry.backoffMs);}}}};var Oe=class{constructor(){l(this,"isAsync",false);l(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},Wr=v(new Set);function Lt(e){if(e.destination!=="database")return Ct(e);let t=e.database;return t?.ready?new se(t):(Wr("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new Oe)}function Hr(e){return xe(e.data)?e.data:e}function Qr(e,t){if(t in e){let o=e[t];if(typeof o=="string"||typeof o=="number")return o}let r=Hr(e)[t];if(typeof r=="string"||typeof r=="number")return r}function vt(e){return Qr(e,"type")}function Dt(e,t){let n=Math.max(1,Math.floor(e)),r=Math.pow(t.multiplier,n-1),o=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*r)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(o+1)):o}var xt="bun:sqlite";var Et="node:sqlite";function _t(){return `
|
|
11
11
|
const { parentPort } = require('node:worker_threads');
|
|
12
12
|
const fs = require('node:fs');
|
|
@@ -697,5 +697,5 @@ parentPort.on('message', async (message) => {
|
|
|
697
697
|
});
|
|
698
698
|
}
|
|
699
699
|
});
|
|
700
|
-
`}var ce=class{constructor(t){this.path=t;l(this,"worker");l(this,"pending",new Map);l(this,"nextId",1);this.worker=new Worker(_t(),{eval:true}),this.worker.on("message",n=>{let r=this.pending.get(n.id);if(r){if(this.pending.delete(n.id),n.ok){r.resolve(n.result);return}r.reject(new Error(n.error??"SQLite worker request failed."));}}),this.worker.on("error",n=>{for(let r of this.pending.values())r.reject(n instanceof Error?n:new Error(String(n)));this.pending.clear();});}request(t,n={}){let r=this.nextId++;return new Promise((o,a)=>{this.pending.set(r,{resolve:o,reject:a}),this.worker.postMessage({id:r,type:t,payload:n});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,n){return this.request("claimDue",{limit:t,now:n})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,n){await this.request("reschedule",{items:t,now:n});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,n){return this.request("retryDeadLetters",{ids:t,now:n})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var At=Symbol("blyp.connector.batch-dispatch"),W=Symbol("blyp.connector.delivery-binder");function H(e){return new Promise(t=>{setTimeout(t,e);})}function Gr(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function Pt(e){return JSON.stringify(e)}function Vr(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Bt(e){let t=new Map;for(let n of e){let r=`${n.connectorType}:${n.connectorTarget??""}`;t.has(r)||t.set(r,{connectorType:n.connectorType,connectorTarget:n.connectorTarget});}return [...t.values()]}var ue=class{constructor(t){this.config=t;l(this,"warnOnce",v(new Set));l(this,"memoryQueue",[]);l(this,"durableStaging",[]);l(this,"dispatchers",new Map);l(this,"activeDispatches",0);l(this,"flushPromise",null);l(this,"durableFlushPromise",null);l(this,"pollTimer",null);l(this,"durablePollRunning",false);l(this,"closed",false);l(this,"durableClient",null);l(this,"durableReady",false);l(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[W]=="function"&&t[W](this);let n=t[At];n&&this.dispatchers.set(n.dispatchKey,n);}unbindTarget(t){typeof t[W]=="function"&&t[W](null);}enqueue(t,n,r,o){this.closed||!Gr(n)||(this.dispatchers.set(r.dispatchKey,r),this.memoryQueue.push({id:et(),connectorType:t,connectorTarget:o,source:"server",record:n,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:r.dispatchKey,dispatcher:r}),this.enforceMemoryCapacity(),this.scheduleDispatch());}async flush(){await this.durableInitPromise?.catch(()=>{}),await this.processUntilIdle(),await this.flushDurableStaging(),await this.drainDurableQueueForFlush(),await this.flushDurableStaging(),await this.processUntilIdle();}async shutdown(){if(this.closed=true,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),await this.durableInitPromise?.catch(()=>{}),this.durableReady){let t=this.memoryQueue.splice(0,this.memoryQueue.length);for(let n of t)this.stageDurableJob(n,n.attemptCount,Math.max(n.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new ce(this.config.durableQueuePath);await t.init(),this.durableClient=t,this.durableReady=!0,this.scheduleDurablePoll();}catch(t){this.durableReady=false,this.durableClient=null,this.warnOnce("connector-durable-disabled",`[Blyp] Warning: Failed to initialize the connector SQLite queue at ${this.config.durableQueuePath}. Falling back to in-memory retries.`,t);}}scheduleDispatch(){this.flushPromise||(this.flushPromise=(async()=>{try{await this.pumpMemoryQueue();}finally{this.flushPromise=null,!this.closed&&this.hasReadyMemoryJobs()&&this.scheduleDispatch();}})());}async pumpMemoryQueue(){for(;!this.closed;){for(;this.activeDispatches<this.config.dispatchConcurrency;){let t=this.takeNextMemoryBatch();if(t.length===0)break;this.activeDispatches+=1,this.dispatchMemoryBatch(t).finally(()=>{this.activeDispatches-=1,this.closed||this.scheduleDispatch();});}if(this.activeDispatches===0||!this.hasReadyMemoryJobs())break;await H(10);}}takeNextMemoryBatch(){let t=Date.now(),n=this.memoryQueue.findIndex(a=>a.nextAttemptAt<=t);if(n===-1)return [];let r=this.memoryQueue[n],o=[r];this.memoryQueue.splice(n,1);for(let a=this.memoryQueue.length-1;a>=0;a-=1){let s=this.memoryQueue[a];s.dispatchKey===r.dispatchKey&&s.connectorTarget===r.connectorTarget&&s.nextAttemptAt<=t&&o.length<this.config.memoryBatchSize&&(o.push(s),this.memoryQueue.splice(a,1));}return o}async dispatchMemoryBatch(t){let n=t[0].dispatcher,r=Date.now(),o=await n.dispatch(t.map(a=>a.record),{source:"server",target:t[0].connectorTarget}).catch(a=>({ok:false,retryable:true,error:a instanceof Error?a.message:String(a)}));if(o.ok){await this.recordSuccessfulDispatch(t,r);return}await this.handleRetryableFailure(t,o,false,r);}async handleRetryableFailure(t,n,r,o){r||await this.durableInitPromise?.catch(()=>{});let a=[],s=[];await this.recordFailedDispatch(t,n,o);for(let i of t){let c=i.attemptCount+1;if(!n.retryable||c>=i.maxAttempts){s.push({id:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,operation:"send",payloadJson:Pt({jobId:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,source:i.source,record:i.record,createdAt:i.createdAt}),attemptCount:c,maxAttempts:i.maxAttempts,lastError:n.error,firstEnqueuedAt:i.createdAt,deadLetteredAt:o,lastAttemptAt:o}),this.warnOnce(`connector-drop:${i.connectorType}:${i.connectorTarget??"default"}:${i.id}`,r&&this.durableReady?`[Blyp] Warning: Dead-lettered ${i.connectorType} connector job after ${c} failed attempt(s). ${n.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${i.connectorType} connector job after ${c} failed attempt(s). ${n.error??"Connector delivery failed."}`);continue}let u=o+Dt(c,this.config.retry);if(r){a.push({id:i.id,attemptCount:c,nextAttemptAt:u,lastError:n.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(i,c,u,n.error);continue}this.memoryQueue.push({...i,attemptCount:c,nextAttemptAt:u});}s.length>0&&await this.durableClient?.deadLetter(s).catch(i=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",i);}),a.length>0&&await this.durableClient?.reschedule(a,o).catch(i=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",i);});}async recordSuccessfulDispatch(t,n){if(!this.durableReady||!this.durableClient||t.length===0)return;let r=Bt(t).map(o=>({connectorType:o.connectorType,connectorTarget:o.connectorTarget,timestamp:n}));await this.durableClient.markSuccess(r).catch(o=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",o);});}async recordFailedDispatch(t,n,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=Bt(t).map(a=>({connectorType:a.connectorType,connectorTarget:a.connectorTarget,timestamp:r,lastError:n.error}));await this.durableClient.markFailure(o).catch(a=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",a);});}stageDurableJob(t,n,r,o){let a=Pt({jobId:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,source:t.source,record:t.record,createdAt:t.createdAt});this.durableStaging.push({id:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,operation:"send",payloadJson:a,attemptCount:n,maxAttempts:t.maxAttempts,nextAttemptAt:r,state:"pending",lastError:o,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(n){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",n),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let n=new Map,r=[];for(let o of t){let a=Vr(o.payloadJson);if(!a){r.push(o.id);continue}let s=o.connectorType==="otlp"?`otlp:${o.connectorTarget??""}`:o.connectorType,i=this.dispatchers.get(s);if(!i){r.push(o.id);continue}let c={id:o.id,connectorType:o.connectorType,connectorTarget:o.connectorTarget,source:a.source,record:a.record,attemptCount:o.attemptCount,maxAttempts:o.maxAttempts,nextAttemptAt:o.nextAttemptAt,createdAt:o.createdAt,dispatchKey:s,dispatcher:i},u=n.get(s)??[];u.push(c),n.set(s,u);}r.length>0&&await this.durableClient.ack(r);for(let o of n.values()){let s=await o[0].dispatcher.dispatch(o.map(i=>i.record),{source:"server",target:o[0].connectorTarget}).catch(i=>({ok:!1,retryable:!0,error:i instanceof Error?i.message:String(i)}));if(s.ok){await this.recordSuccessfulDispatch(o,Date.now()),await this.durableClient.ack(o.map(i=>i.id));continue}await this.handleRetryableFailure(o,s,!0,Date.now());}}}finally{this.durablePollRunning=false;}}}async drainDurableQueueForFlush(){if(!(!this.durableReady||!this.durableClient)){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null);try{for(;!this.closed;){for(;this.durablePollRunning;)await H(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await H(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[n]=this.memoryQueue.splice(t,1);if(!n)break;if(this.durableReady){this.stageDurableJob(n,n.attemptCount,Math.max(Date.now(),n.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${n.connectorType}:${n.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${n.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(n=>n.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(n=>n.nextAttemptAt));await H(Math.max(t-Date.now(),0));}else await H(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var _=class _{constructor(){l(this,"_type",null);}static getInstance(){return _.instance||(_.instance=new _),_.instance}get type(){return this._type===null&&(this._type=this.detectRuntime()),this._type}get isBun(){return this.type==="bun"}get isNode(){return this.type==="node"}detectRuntime(){return typeof Bun<"u"&&typeof Bun.file=="function"?"bun":"node"}};l(_,"instance");var Ie=_,Ne=class{constructor(){l(this,"type","bun");l(this,"isBun",true);l(this,"isNode",false);l(this,"file",{existsSync:t=>{try{let n=Bun.file(t);return n.size>0||n.name!==""}catch{return false}},mkdirSync:(t,n)=>{try{w.mkdirSync(t,n);}catch{}},writeFileSync:(t,n)=>{Bun.write(t,n);}});l(this,"path",{join:(...t)=>z$1.join(...t)});l(this,"env",{get:t=>Bun.env[t]});l(this,"cwd",()=>process.cwd());}},Fe=class{constructor(){l(this,"type","node");l(this,"isBun",false);l(this,"isNode",true);l(this,"file",{existsSync:t=>w.existsSync(t),mkdirSync:(t,n)=>{w.mkdirSync(t,n);},writeFileSync:(t,n)=>{w.writeFileSync(t,n);}});l(this,"path",{join:(...t)=>z$1.join(...t)});l(this,"env",{get:t=>process.env[t]});l(this,"cwd",()=>process.cwd());}};function Xr(){return Ie.getInstance().isBun?new Ne:new Fe}var Ot=Xr();function It(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function Nt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yr(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:Nt(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,r=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${r??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:r,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:Nt(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Zr(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function Ft(e,t){let n=t.redact??S(),r=performance.now(),o=h(t.initialFields??{},n),a=[],s;t.onCreate?.();let i=(u,d,m)=>(a.push({level:u,message:$(d,n),timestamp:new Date().toISOString(),...It(d,m)===void 0?{}:{data:h(It(d,m),n)}}),c),c={set(u){return Object.assign(o,h(u,n)),c},debug(u,...d){return i("debug",u,d)},info(u,...d){return i("info",u,d)},warn(u,...d){return i("warn",u,d)},warning(u,...d){return i("warning",u,d)},error(u,...d){return i("error",u,d)},success(u,...d){return i("success",u,d)},critical(u,...d){return i("critical",u,d)},table(u,d){return i("table",u,d===void 0?[]:[d])},emit(u={}){if(s)return s;let d=h(t.resolveDefaultFields?.()??{},n),m=Zr(u),C=h(Yr(u.error,m),n),P=u.level??(C?"error":"info"),y=h({...d,...o,groupId:e,timestamp:new Date().toISOString(),level:P,duration:Math.round(performance.now()-r),...typeof m=="number"?{status:m}:{},...a.length>0?{events:[...a]}:{},...C?{error:C}:{}},n);return t.write(y,$(u.message??"structured_log",n)),s=y,t.onEmit?.(y),y}};return c}var Qt=Symbol("blyp.logger.factory"),jt={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},Ut={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},eo="\x1B[35m",to="\x1B[0m";function Q(e){return vt(e)==="client_log"}function no(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",ingestingHost:void 0,status:"missing",errorTracking:{enabled:false,ready:false,status:"missing",dsn:void 0,tracesSampleRate:1,environment:void 0,release:void 0},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function ro(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function oo(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",host:"https://us.i.posthog.com",status:"missing",errorTracking:{enabled:false,ready:false,mode:"auto",status:"missing",enableExceptionAutocapture:false},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function ao(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function io(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function so(){return {get:e=>io(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function co(e){return e.connectors?.betterstack?.enabled?O("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):no()}function uo(e){return e.connectors?.databuddy?.enabled?O("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):ro()}function lo(e){return e.connectors?.posthog?.enabled?O("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):oo()}function po(e){return e.connectors?.sentry?.enabled?O("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):ao()}function fo(e){return e.connectors?.otlp?.some(t=>t.enabled)?O("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):so()}function go(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n={};t.data!==void 0&&(n.data=t.data);let r=typeof t.page?.pathname=="string"?t.page.pathname:void 0,o=typeof t.page?.url=="string"?t.page.url:void 0;return (r||o)&&(n.page=r??o),t.metadata!==void 0&&(n.metadata=t.metadata),Object.keys(n).length>0?n:null}function mo(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let n=go(e);return n?{hidden:false,value:n}:{hidden:true}}return {hidden:false,value:e}}function yo(e){if(e.pretty){let n=Ge()({colorize:true,translateTime:"SYS:HH:MM:ss",ignore:"pid,hostname,caller",customColors:{success:"green",critical:"red bold",info:"blue",warning:"yellow",error:"red",debug:"cyan",table:"cyan"},messageFormat:(r,o)=>{let a=String(r[o]??""),s=typeof r.caller=="string"?r.caller.trim():"";return s?`${a} ${eo}${s}${to}`:a}});return zt({level:e.level,customLevels:jt},n)}return zt({level:e.level,customLevels:jt})}function ho(e){let t=e[Qt];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function bo(e,t,n={}){let r=ho(e);return Ft(t,{initialFields:n.initialFields,resolveDefaultFields:()=>({...r.bindings,...n.resolveDefaultFields?.()??{}}),write:(o,a)=>{r.writeStructured(o,a,"structured-flush");},onCreate:n.onCreate,onEmit:n.onEmit,redact:n.redact??r.redact})}function qt(e,t){if(!Q(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function $t(e,t){if(!Q(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Kt(e,t){if(!Q(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Wt(e,t){if(!Q(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Ht(e,t){if(!Q(t))for(let n of e.getAutoForwardTargets())n.send(t,{source:"server",warnIfUnavailable:true});}function je(e,t,n,r,o,a,s,i,c,u={},d="root"){let m=Object.keys(u).length>0?e.child(u):e,C=(f,p,B,M=d)=>{if(M==="root"&&Te())return;let g=mt(f,p,B,u,c),he=g.message,q={caller:g.caller},ee=mo(g.data);!ee.hidden&&ee.value!==void 0&&(q.data=ee.value);let Qe=Ut[f],be=m;(be[Qe]??be.info??((Mo,Oo)=>{})).call(m,q,he),t.write(g),$t(r,g),Kt(o,g),qt(a,g),Wt(s,g),Ht(i,g);},P=(f,p,B="structured-flush")=>{let M=ht(f.level),g=yt(M,p,f,u,c),he=Ut[M],q=m;(q[he]??q.info??((Qe,be)=>{})).call(m,{caller:g.caller,...g},g.message),(B!=="root"||!Te())&&t.write(g),$t(r,g),Kt(o,g),qt(a,g),Wt(s,g),Ht(i,g);},y={success:(f,...p)=>{C("success",f,p);},critical:(f,...p)=>{C("critical",f,p);},warning:(f,...p)=>{C("warning",f,p);},info:(f,...p)=>{C("info",f,p);},debug:(f,...p)=>{C("debug",f,p);},error:(f,...p)=>{C("error",f,p);},warn:(f,...p)=>{C("warn",f,p);},table:(f,p)=>{p&&typeof p=="object"&&Ot.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",f),console.table(h(p,c))),C("table",f,p===void 0?[]:[p]);},flush:async()=>{await t.flush(),n&&await n.flush(),await Promise.allSettled([r.flush(),o.flush(),a.flush(),s.flush(),i.flush()]);},shutdown:async()=>{await t.shutdown(),n&&await n.shutdown(),await Promise.allSettled([r.flush(),o.flush(),a.flush(),s.flush(),i.flush()]);},createStructuredLog:(f,p)=>bo(y,f,{initialFields:p}),child:f=>{let p={...u,...f};return je(e,t,n,r,o,a,s,i,c,p,d)},[Qt]:{bindings:u,betterstack:r,databuddy:o,posthog:a,sentry:s,otlp:i,redact:c,sink:t,create:(f,p=u)=>je(e,t,n,r,o,a,s,i,c,p,f),writeStructured:(f,p,B="structured-flush")=>{P(f,p,B);}}};return y}var ze=null;function Co(e){if(ze)return ze;let t=lt(e),n=yo(t),r=Lt(t),o=co(t),a=uo(t),s=lo(t),i=po(t),c=fo(t),u=t.connectors.delivery.enabled?new ue(t.connectors.delivery):null;if(u){u.bindTarget(o),u.bindTarget(a),u.bindTarget(s),u.bindTarget(i);for(let m of c.getAutoForwardTargets())u.bindTarget(m);}let d=je(n,r,u,o,a,s,i,c,t.redact);return (ze=d),d}var de=Co();var wo=new TextEncoder;function pe(e){return wo.encode(e).length}function Ro(e){if(!e||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function b(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(e instanceof Date)return e.toISOString();if(e instanceof Error)return {name:e.name,message:e.message,stack:e.stack};if(Array.isArray(e))return e.map(n=>b(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";if(t.add(e),!Ro(e)){let n=e.constructor?.name;return n?`[${n}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,b(r,t)]))}return String(e)}function k(e,t){if(t.length===0)return e;let n=b(e);for(let r of t){let o=r.split(".").filter(Boolean);if(o.length===0)continue;let a=n;for(let s=0;s<o.length-1;s+=1){if(!a||typeof a!="object"){a=void 0;break}a=a[o[s]];}a&&typeof a=="object"&&delete a[o[o.length-1]];}return n}function fe(e,t){let n=b(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof n=="string"){if(pe(n)<=t)return {value:n,truncated:false};let a=n;for(;a.length>0&&pe(`${a}\u2026[truncated]`)>t;)a=a.slice(0,Math.max(1,Math.floor(a.length*.8)));return {value:`${a}\u2026[truncated]`,truncated:true}}let r=JSON.stringify(n);if(r===void 0||pe(r)<=t)return {value:n,truncated:false};let o=r;for(;o.length>0&&pe(`${o}\u2026[truncated]`)>t;)o=o.slice(0,Math.max(1,Math.floor(o.length*.8)));return {value:{truncated:true,preview:`${o}\u2026[truncated]`},truncated:true}}function J(e){if(!e)return;let t={inputTokens:typeof e.inputTokens=="number"?e.inputTokens:void 0,outputTokens:typeof e.outputTokens=="number"?e.outputTokens:void 0,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:void 0,reasoningTokens:typeof e.reasoningTokens=="number"?e.reasoningTokens:void 0,cachedInputTokens:typeof e.cachedInputTokens=="number"?e.cachedInputTokens:void 0};if(t.totalTokens===void 0&&(t.inputTokens!==void 0||t.outputTokens!==void 0)&&(t.totalTokens=(t.inputTokens??0)+(t.outputTokens??0)),!Object.values(t).every(n=>n===void 0))return t}function A(e){if(typeof e=="string"&&e.length>0)return e;if(e&&typeof e=="object"){let t=e;for(let n of ["type","reason","stop_reason","finish_reason","raw","unified"]){let r=t[n];if(typeof r=="string"&&r.length>0)return r}}}function G(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Ue(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function Jt(e){if(!e)return {};if(e instanceof Error){let t=e;return {errorType:e.name,errorCode:t.code}}if(typeof e=="object"){let t=e;return {errorType:typeof t.type=="string"?t.type:typeof t.name=="string"?t.name:"Error",errorCode:typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}}return {errorType:typeof e}}function Gt(e){return b(e)}var qe={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},V={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},$e={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function To(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function ko(){return new Date().toISOString()}function Vt(e){return b(e)}function Ke(){return new Date().toISOString()}function So(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...qe,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??qe.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??qe.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??V.providerOptions,requestPaths:[...e.exclude?.requestPaths??V.requestPaths],responsePaths:[...e.exclude?.responsePaths??V.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??V.metadataPaths],toolNames:[...e.exclude?.toolNames??V.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??$e.maxContentBytes,maxEvents:e.limits?.maxEvents??$e.maxEvents,maxToolCalls:e.limits?.maxToolCalls??$e.maxToolCalls},hooks:e.hooks??{}}}function Xt(e={}){return So(e)}function Yt(e){let t=e.config.logger??te()??de,n=To(),r=Ke(),o={traceId:n,provider:e.provider,sdk:e.sdk,operation:e.operation??e.config.operation??e.method,method:e.method,model:e.model,logger:t,metadata:{...e.config.metadata},request:e.request,toolCalls:[],events:[],startedAt:r,startedAtMs:performance.now(),options:e.config,capture:{...e.config.capture},streamed:e.streamed,truncated:false},a={traceId:n,provider:o.provider,sdk:o.sdk,operation:o.operation,method:o.method,logger:t,metadata:o.metadata,request:o.request,get response(){return o.response},get usage(){return o.usage},get finishReason(){return o.finishReason},get input(){return o.input},get output(){return o.output},get toolCalls(){return o.toolCalls.length>0?o.toolCalls:void 0},get startedAt(){return o.startedAt},get firstChunkAt(){return o.firstChunkAt},get endedAt(){return o.endedAt},get error(){return o.error},setMetadata(s){Object.assign(o.metadata,s);},disableCapture(s){o.capture[s]=false;}};return {state:o,context:a}}function ge(e,t){e.usage=J(t);}function me(e,t){e.finishReason=A(t);}function Zt(e,t){e.response=t;}function en(e,t){e.input=t;}function ye(e,t){e.output=t;}function tn(e,t){e.rawProviderPayload=Gt(t);}async function nn(e,t){e.firstChunkAt||(e.firstChunkAt=Ke(),e.firstChunkAtMs=performance.now(),await x(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function rn(e,t,n){e.capture.streamEvents&&await x(e,t,{type:"ai.chunk",data:n});}function U(e,t){let n=t.id??`${t.name}:${e.toolCalls.length}`,r=e.toolCalls.findIndex((o,a)=>(o.id??`${o.name}:${a}`)===n);if(r===-1&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(r===-1){e.toolCalls.push(t);return}e.toolCalls[r]={...e.toolCalls[r],...t};}async function We(e,t,n){U(e,n),await x(e,t,{type:"ai.tool_call.start",data:Ue(n)});}async function on(e,t,n){U(e,n),await x(e,t,{type:"ai.tool_call.result",data:Ue(n)});}function Lo(e){let t=e.toolCalls.filter(n=>!e.options.exclude.toolNames.includes(n.name)).map(n=>{let r={id:n.id,name:n.name,status:n.status};if(e.capture.toolInputs&&n.input!==void 0){let o=X(n.input,e.options.limits.maxContentBytes);r.input=o.value,e.truncated||(e.truncated=o.truncated);}if(e.capture.toolOutputs&&n.output!==void 0){let o=X(n.output,e.options.limits.maxContentBytes);r.output=o.value,e.truncated||(e.truncated=o.truncated);}return n.providerFormat!==void 0&&(r.providerFormat=b(n.providerFormat)),r});return t.length>0?t:void 0}async function Z(e,t,n){if(e.emitted)return;e.emitted=true,n?.error!==void 0&&(e.error=n.error,await x(e,t,{type:"ai.error",data:{error:b(n.error)}}),await Y(e.options.hooks.onError,[t])),e.endedAt=Ke(),await x(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await Y(e.options.hooks.onFinish,[t]);let r={startedAt:e.startedAt,endedAt:e.endedAt,durationMs:Math.max(0,Math.round(performance.now()-e.startedAtMs))};e.firstChunkAt&&e.firstChunkAtMs!==void 0&&(r.firstChunkAt=e.firstChunkAt,r.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs)));let o={provider:e.provider,sdk:e.sdk,model:e.model,operation:e.operation,method:e.method,streamed:e.streamed,timing:r,metadata:k(e.metadata,e.options.exclude.metadataPaths)};if(e.usage&&(o.usage=e.usage),e.finishReason&&(o.finishReason=e.finishReason),e.capture.input&&e.input!==void 0){let i=X(k(b(e.input),e.options.exclude.requestPaths),e.options.limits.maxContentBytes);o.input=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.output&&e.output!==void 0){let i=b(e.output),c=X(typeof i=="object"&&i!==null&&!Array.isArray(i)?k(i,e.options.exclude.responsePaths):i,e.options.limits.maxContentBytes);o.output=c.value,e.truncated||(e.truncated=c.truncated);}let a=Lo(e);if(a&&(o.tools=a),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let i=X(e.rawProviderPayload,e.options.limits.maxContentBytes);o.rawProviderPayload=i.value,e.truncated||(e.truncated=i.truncated);}e.truncated&&o.metadata&&(o.metadata={...o.metadata,truncated:true});let s={...o};if(e.error!==void 0){let{errorType:i,errorCode:c}=Jt(e.error);i&&(s.errorType=i),c!==void 0&&(s.errorCode=c);}try{e.logger.createStructuredLog(e.traceId,{type:"ai_trace",ai:s,events:e.events}).emit({message:"ai_trace",level:e.error===void 0?"info":"error",...e.error===void 0?{}:{error:e.error}});}catch(i){console.warn("[Blyp] Failed to emit AI trace.",Vt(i));}}async function Y(e,t){if(e)try{await e(...t);}catch(n){console.warn("[Blyp] AI middleware hook failed.",Vt(n));}}async function x(e,t,n){e.events.length<e.options.limits.maxEvents?e.events.push({...n,timestamp:n.timestamp??ko()}):e.truncated=true,await Y(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function X(e,t){return fe(e,t)}function an(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function sn(e,t){return {[Symbol.asyncIterator](){let n=e[Symbol.asyncIterator]();return {async next(){try{let r=await n.next();return r.done?(await t.onReturn?.(),r):(await t.onChunk?.(r.value),r)}catch(r){throw await t.onError?.(r),r}},async return(r){try{return typeof n.return=="function"?await n.return(r):{done:!0,value:r}}finally{await t.onReturn?.();}},async throw(r){try{if(typeof n.throw=="function")return await n.throw(r);throw r}catch(o){throw await t.onError?.(o),o}}}}}}function vo(e){let t=e.output;if(!Array.isArray(t))return;let n=[];for(let r of t){if(!r||typeof r!="object")continue;let a=r.content;if(Array.isArray(a))for(let s of a){if(!s||typeof s!="object")continue;let c=s.text;typeof c=="string"&&n.push(c);}}return n.length>0?n.join(""):void 0}function Do(e){let t=e.output;if(!Array.isArray(t))return [];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let o=r,a=o.type;a==="function_call"&&n.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",input:G(o.arguments),status:"started"}),a==="function_call_output"&&n.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",output:o.output,status:"completed"});}return n}function xo(e){let t=e.choices;if(Array.isArray(t))return t.map(n=>{if(!n||typeof n!="object")return "";let r=n.message;return !r||typeof r!="object"?"":typeof r.content=="string"?r.content:""}).join("")}function Eo(e){let t=e.choices;if(!Array.isArray(t))return [];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let o=r.message;if(!o||typeof o!="object")continue;let s=o.tool_calls;if(Array.isArray(s))for(let i of s){if(!i||typeof i!="object")continue;let c=i,u=c.function,d=u&&typeof u=="object"?u:{};n.push({id:typeof c.id=="string"?c.id:void 0,name:typeof d.name=="string"?d.name:"unknown",input:G(d.arguments),providerFormat:c,status:"started"});}}return n}function cn(e,t){if(!e||typeof e!="object")return {toolCalls:[]};let n=e,r=n.usage&&typeof n.usage=="object"?n.usage:void 0,o=t==="chat.completions.create"?J({inputTokens:typeof r?.prompt_tokens=="number"?r.prompt_tokens:void 0,outputTokens:typeof r?.completion_tokens=="number"?r.completion_tokens:void 0,totalTokens:typeof r?.total_tokens=="number"?r.total_tokens:void 0,reasoningTokens:r?.completion_tokens_details&&typeof r.completion_tokens_details=="object"&&typeof r.completion_tokens_details.reasoning_tokens=="number"?r.completion_tokens_details.reasoning_tokens:void 0,cachedInputTokens:r?.prompt_tokens_details&&typeof r.prompt_tokens_details=="object"&&typeof r.prompt_tokens_details.cached_tokens=="number"?r.prompt_tokens_details.cached_tokens:void 0}):J({inputTokens:typeof r?.input_tokens=="number"?r.input_tokens:void 0,outputTokens:typeof r?.output_tokens=="number"?r.output_tokens:void 0,totalTokens:typeof r?.total_tokens=="number"?r.total_tokens:void 0,reasoningTokens:r?.output_tokens_details&&typeof r.output_tokens_details=="object"&&typeof r.output_tokens_details.reasoning_tokens=="number"?r.output_tokens_details.reasoning_tokens:void 0,cachedInputTokens:r?.input_tokens_details&&typeof r.input_tokens_details=="object"&&typeof r.input_tokens_details.cached_tokens=="number"?r.input_tokens_details.cached_tokens:void 0}),a=t==="chat.completions.create"?A(Array.isArray(n.choices)&&n.choices[0]&&typeof n.choices[0]=="object"?n.choices[0].finish_reason:void 0):A(n.status),s=t==="chat.completions.create"?Eo(n):Do(n),i={};return typeof n.id=="string"&&(i.responseId=n.id),typeof n.created_at=="number"&&(i.createdAt=n.created_at),typeof n.provider=="string"&&(i.upstreamProvider=n.provider),{model:typeof n.model=="string"?n.model:void 0,usage:o,finishReason:a,output:t==="chat.completions.create"?xo(n):vo(n),toolCalls:s,metadata:Object.keys(i).length>0?i:void 0}}async function un(e,t,n){if(!n||typeof n!="object")return;await nn(e,t);let r=n,o=r.type;if(typeof o=="string"&&await rn(e,t,{type:o}),o==="response.output_text.delta"&&typeof r.delta=="string"){let a=`${typeof e.output=="string"?e.output:""}${r.delta}`;ye(e,a);}if(o==="response.function_call_arguments.delta"){let a=typeof r.item_id=="string"?r.item_id:void 0,s=typeof r.name=="string"?r.name:"unknown",i=e.toolCalls.find(d=>d.id===a),c=`${typeof i?.input=="string"?i.input:""}${typeof r.delta=="string"?r.delta:""}`,u={id:a,name:s,input:c,status:"started"};i?U(e,u):await We(e,t,u);}if(o==="response.output_item.done"){let a=r.item;if(a&&typeof a=="object"){let s=a;if(s.type==="function_call"){let i={id:typeof s.call_id=="string"?s.call_id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:G(s.arguments),status:"started"};await We(e,t,i);}if(s.type==="function_call_output"){let i={id:typeof s.call_id=="string"?s.call_id:void 0,name:typeof s.name=="string"?s.name:"unknown",output:s.output,status:"completed"};await on(e,t,i);}}}if(o==="response.completed"){let a=r.response;if(a&&typeof a=="object"){let s=a;if(me(e,A(s.status)),s.usage&&typeof s.usage=="object"){let i=s.usage;ge(e,{inputTokens:typeof i.input_tokens=="number"?i.input_tokens:void 0,outputTokens:typeof i.output_tokens=="number"?i.output_tokens:void 0,totalTokens:typeof i.total_tokens=="number"?i.total_tokens:void 0});}}}}async function ln(e,t,n,r,o){let a=Xt({...o,provider:o.provider??"openai"}),{state:s,context:i}=Yt({provider:o.provider??"openai",sdk:"openai-sdk",operation:o.operation,method:t,model:typeof n.model=="string"?n.model:"unknown",request:n,streamed:n.stream===true,config:a});en(s,t==="chat.completions.create"?n.messages:n.input??n),await x(s,i,{type:"ai.start"}),await Y(a.hooks.onStart,[i]);try{let c=await e(n,...r);if(n.stream===!0&&an(c))return sn(c,{onChunk:async m=>{await un(s,i,m);},onReturn:async()=>{await Z(s,i);},onError:async m=>{await Z(s,i,{error:m});}});let u=cn(c,t);Zt(s,c),tn(s,c),u.metadata&&i.setMetadata(u.metadata),u.usage&&ge(s,u.usage),u.finishReason&&me(s,u.finishReason),u.output!==void 0&&ye(s,u.output);for(let d of u.toolCalls)U(s,d);return await Z(s,i),c}catch(c){throw await Z(s,i,{error:c}),c}}function He(e,t,n){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:n})}function _o(e,t={}){let n=Object.create(Object.getPrototypeOf(e));if(Object.assign(n,e),e.responses?.create){let r=e.responses,o=He(r,"create",(async(a,...s)=>ln(r.create.bind(r),"responses.create",a??{},s,t)));n.responses=o;}if(e.chat?.completions?.create){let r=e.chat,o=r.completions,a=He(o,"create",(async(s,...i)=>ln(o.create.bind(o),"chat.completions.create",s??{},i,t)));n.chat=He(r,"completions",a);}return n}function Ao(e={}){return {...e,provider:e.provider??"openai"}}function Po(e,t={}){let n=t.logger??te()??de,r={...t.metadata??{}},o=t.limits?.maxContentBytes??16384,a=t.exclude?.requestPaths??[],s=t.exclude?.responsePaths??[],i=(async(c,u)=>{let d=performance.now(),m=new Date().toISOString(),C=u?.method??(c instanceof Request?c.method:"GET"),P=typeof c=="string"?c:c instanceof URL?c.toString():c.url;try{let y=await e(c,u),f=new Date().toISOString(),p=n.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:P,method:C,status:y.status,startedAt:m,endedAt:f,durationMs:Math.max(0,Math.round(performance.now()-d)),requestId:y.headers.get("x-request-id")??y.headers.get("request-id")??y.headers.get("cf-ray")??void 0,metadata:k(r,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let M=await y.clone().json(),g=fe({request:k(b(u??{}),a),response:k(b(M),s)},o);p.set({fetchBody:g.value});}catch{}return p.emit({message:"fetch_trace",level:y.ok?"info":"error"}),y}catch(y){throw n.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:P,method:C,startedAt:m,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:k(r,t.exclude?.metadataPaths??[])}}).emit({message:"fetch_trace",level:"error",error:b(y)}),y}});return "preconnect"in e&&(i.preconnect=e.preconnect),i}
|
|
700
|
+
`}var ce=class{constructor(t){this.path=t;l(this,"worker");l(this,"pending",new Map);l(this,"nextId",1);this.worker=new Worker(_t(),{eval:true}),this.worker.on("message",n=>{let r=this.pending.get(n.id);if(r){if(this.pending.delete(n.id),n.ok){r.resolve(n.result);return}r.reject(new Error(n.error??"SQLite worker request failed."));}}),this.worker.on("error",n=>{for(let r of this.pending.values())r.reject(n instanceof Error?n:new Error(String(n)));this.pending.clear();});}request(t,n={}){let r=this.nextId++;return new Promise((o,a)=>{this.pending.set(r,{resolve:o,reject:a}),this.worker.postMessage({id:r,type:t,payload:n});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,n){return this.request("claimDue",{limit:t,now:n})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,n){await this.request("reschedule",{items:t,now:n});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,n){return this.request("retryDeadLetters",{ids:t,now:n})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var At=Symbol("blyp.connector.batch-dispatch"),H=Symbol("blyp.connector.delivery-binder");function Q(e){return new Promise(t=>{setTimeout(t,e);})}function Gr(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function Pt(e){return JSON.stringify(e)}function Vr(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Bt(e){let t=new Map;for(let n of e){let r=`${n.connectorType}:${n.connectorTarget??""}`;t.has(r)||t.set(r,{connectorType:n.connectorType,connectorTarget:n.connectorTarget});}return [...t.values()]}var ue=class{constructor(t){this.config=t;l(this,"warnOnce",v(new Set));l(this,"memoryQueue",[]);l(this,"durableStaging",[]);l(this,"dispatchers",new Map);l(this,"activeDispatches",0);l(this,"flushPromise",null);l(this,"durableFlushPromise",null);l(this,"pollTimer",null);l(this,"durablePollRunning",false);l(this,"closed",false);l(this,"durableClient",null);l(this,"durableReady",false);l(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[H]=="function"&&t[H](this);let n=t[At];n&&this.dispatchers.set(n.dispatchKey,n);}unbindTarget(t){typeof t[H]=="function"&&t[H](null);}enqueue(t,n,r,o){this.closed||!Gr(n)||(this.dispatchers.set(r.dispatchKey,r),this.memoryQueue.push({id:et(),connectorType:t,connectorTarget:o,source:"server",record:n,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:r.dispatchKey,dispatcher:r}),this.enforceMemoryCapacity(),this.scheduleDispatch());}async flush(){await this.durableInitPromise?.catch(()=>{}),await this.processUntilIdle(),await this.flushDurableStaging(),await this.drainDurableQueueForFlush(),await this.flushDurableStaging(),await this.processUntilIdle();}async shutdown(){if(this.closed=true,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),await this.durableInitPromise?.catch(()=>{}),this.durableReady){let t=this.memoryQueue.splice(0,this.memoryQueue.length);for(let n of t)this.stageDurableJob(n,n.attemptCount,Math.max(n.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new ce(this.config.durableQueuePath);await t.init(),this.durableClient=t,this.durableReady=!0,this.scheduleDurablePoll();}catch(t){this.durableReady=false,this.durableClient=null,this.warnOnce("connector-durable-disabled",`[Blyp] Warning: Failed to initialize the connector SQLite queue at ${this.config.durableQueuePath}. Falling back to in-memory retries.`,t);}}scheduleDispatch(){this.flushPromise||(this.flushPromise=(async()=>{try{await this.pumpMemoryQueue();}finally{this.flushPromise=null,!this.closed&&this.hasReadyMemoryJobs()&&this.scheduleDispatch();}})());}async pumpMemoryQueue(){for(;!this.closed;){for(;this.activeDispatches<this.config.dispatchConcurrency;){let t=this.takeNextMemoryBatch();if(t.length===0)break;this.activeDispatches+=1,this.dispatchMemoryBatch(t).finally(()=>{this.activeDispatches-=1,this.closed||this.scheduleDispatch();});}if(this.activeDispatches===0||!this.hasReadyMemoryJobs())break;await Q(10);}}takeNextMemoryBatch(){let t=Date.now(),n=this.memoryQueue.findIndex(a=>a.nextAttemptAt<=t);if(n===-1)return [];let r=this.memoryQueue[n],o=[r];this.memoryQueue.splice(n,1);for(let a=this.memoryQueue.length-1;a>=0;a-=1){let s=this.memoryQueue[a];s.dispatchKey===r.dispatchKey&&s.connectorTarget===r.connectorTarget&&s.nextAttemptAt<=t&&o.length<this.config.memoryBatchSize&&(o.push(s),this.memoryQueue.splice(a,1));}return o}async dispatchMemoryBatch(t){let n=t[0].dispatcher,r=Date.now(),o=await n.dispatch(t.map(a=>a.record),{source:"server",target:t[0].connectorTarget}).catch(a=>({ok:false,retryable:true,error:a instanceof Error?a.message:String(a)}));if(o.ok){await this.recordSuccessfulDispatch(t,r);return}await this.handleRetryableFailure(t,o,false,r);}async handleRetryableFailure(t,n,r,o){r||await this.durableInitPromise?.catch(()=>{});let a=[],s=[];await this.recordFailedDispatch(t,n,o);for(let i of t){let c=i.attemptCount+1;if(!n.retryable||c>=i.maxAttempts){s.push({id:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,operation:"send",payloadJson:Pt({jobId:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,source:i.source,record:i.record,createdAt:i.createdAt}),attemptCount:c,maxAttempts:i.maxAttempts,lastError:n.error,firstEnqueuedAt:i.createdAt,deadLetteredAt:o,lastAttemptAt:o}),this.warnOnce(`connector-drop:${i.connectorType}:${i.connectorTarget??"default"}:${i.id}`,r&&this.durableReady?`[Blyp] Warning: Dead-lettered ${i.connectorType} connector job after ${c} failed attempt(s). ${n.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${i.connectorType} connector job after ${c} failed attempt(s). ${n.error??"Connector delivery failed."}`);continue}let u=o+Dt(c,this.config.retry);if(r){a.push({id:i.id,attemptCount:c,nextAttemptAt:u,lastError:n.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(i,c,u,n.error);continue}this.memoryQueue.push({...i,attemptCount:c,nextAttemptAt:u});}s.length>0&&await this.durableClient?.deadLetter(s).catch(i=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",i);}),a.length>0&&await this.durableClient?.reschedule(a,o).catch(i=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",i);});}async recordSuccessfulDispatch(t,n){if(!this.durableReady||!this.durableClient||t.length===0)return;let r=Bt(t).map(o=>({connectorType:o.connectorType,connectorTarget:o.connectorTarget,timestamp:n}));await this.durableClient.markSuccess(r).catch(o=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",o);});}async recordFailedDispatch(t,n,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=Bt(t).map(a=>({connectorType:a.connectorType,connectorTarget:a.connectorTarget,timestamp:r,lastError:n.error}));await this.durableClient.markFailure(o).catch(a=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",a);});}stageDurableJob(t,n,r,o){let a=Pt({jobId:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,source:t.source,record:t.record,createdAt:t.createdAt});this.durableStaging.push({id:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,operation:"send",payloadJson:a,attemptCount:n,maxAttempts:t.maxAttempts,nextAttemptAt:r,state:"pending",lastError:o,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(n){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",n),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let n=new Map,r=[];for(let o of t){let a=Vr(o.payloadJson);if(!a){r.push(o.id);continue}let s=o.connectorType==="otlp"?`otlp:${o.connectorTarget??""}`:o.connectorType,i=this.dispatchers.get(s);if(!i){r.push(o.id);continue}let c={id:o.id,connectorType:o.connectorType,connectorTarget:o.connectorTarget,source:a.source,record:a.record,attemptCount:o.attemptCount,maxAttempts:o.maxAttempts,nextAttemptAt:o.nextAttemptAt,createdAt:o.createdAt,dispatchKey:s,dispatcher:i},u=n.get(s)??[];u.push(c),n.set(s,u);}r.length>0&&await this.durableClient.ack(r);for(let o of n.values()){let s=await o[0].dispatcher.dispatch(o.map(i=>i.record),{source:"server",target:o[0].connectorTarget}).catch(i=>({ok:!1,retryable:!0,error:i instanceof Error?i.message:String(i)}));if(s.ok){await this.recordSuccessfulDispatch(o,Date.now()),await this.durableClient.ack(o.map(i=>i.id));continue}await this.handleRetryableFailure(o,s,!0,Date.now());}}}finally{this.durablePollRunning=false;}}}async drainDurableQueueForFlush(){if(!(!this.durableReady||!this.durableClient)){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null);try{for(;!this.closed;){for(;this.durablePollRunning;)await Q(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await Q(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[n]=this.memoryQueue.splice(t,1);if(!n)break;if(this.durableReady){this.stageDurableJob(n,n.attemptCount,Math.max(Date.now(),n.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${n.connectorType}:${n.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${n.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(n=>n.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(n=>n.nextAttemptAt));await Q(Math.max(t-Date.now(),0));}else await Q(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var _=class _{constructor(){l(this,"_type",null);}static getInstance(){return _.instance||(_.instance=new _),_.instance}get type(){return this._type===null&&(this._type=this.detectRuntime()),this._type}get isBun(){return this.type==="bun"}get isNode(){return this.type==="node"}detectRuntime(){return typeof Bun<"u"&&typeof Bun.file=="function"?"bun":"node"}};l(_,"instance");var Ie=_,Ne=class{constructor(){l(this,"type","bun");l(this,"isBun",true);l(this,"isNode",false);l(this,"file",{existsSync:t=>{try{let n=Bun.file(t);return n.size>0||n.name!==""}catch{return false}},mkdirSync:(t,n)=>{try{w.mkdirSync(t,n);}catch{}},writeFileSync:(t,n)=>{Bun.write(t,n);}});l(this,"path",{join:(...t)=>z$1.join(...t)});l(this,"env",{get:t=>Bun.env[t]});l(this,"cwd",()=>process.cwd());}},Fe=class{constructor(){l(this,"type","node");l(this,"isBun",false);l(this,"isNode",true);l(this,"file",{existsSync:t=>w.existsSync(t),mkdirSync:(t,n)=>{w.mkdirSync(t,n);},writeFileSync:(t,n)=>{w.writeFileSync(t,n);}});l(this,"path",{join:(...t)=>z$1.join(...t)});l(this,"env",{get:t=>process.env[t]});l(this,"cwd",()=>process.cwd());}};function Xr(){return Ie.getInstance().isBun?new Ne:new Fe}var Ot=Xr();function It(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function Nt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yr(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:Nt(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,r=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${r??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:r,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:Nt(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Zr(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function Ft(e,t){let n=t.redact??S(),r=performance.now(),o=h(t.initialFields??{},n),a=[],s;t.onCreate?.();let i=(u,d,m)=>(a.push({level:u,message:K(d,n),timestamp:new Date().toISOString(),...It(d,m)===void 0?{}:{data:h(It(d,m),n)}}),c),c={set(u){return Object.assign(o,h(u,n)),c},debug(u,...d){return i("debug",u,d)},info(u,...d){return i("info",u,d)},warn(u,...d){return i("warn",u,d)},warning(u,...d){return i("warning",u,d)},error(u,...d){return i("error",u,d)},success(u,...d){return i("success",u,d)},critical(u,...d){return i("critical",u,d)},table(u,d){return i("table",u,d===void 0?[]:[d])},emit(u={}){if(s)return s;let d=h(t.resolveDefaultFields?.()??{},n),m=Zr(u),C=h(Yr(u.error,m),n),P=u.level??(C?"error":"info"),y=h({...d,...o,groupId:e,timestamp:new Date().toISOString(),level:P,duration:Math.round(performance.now()-r),...typeof m=="number"?{status:m}:{},...a.length>0?{events:[...a]}:{},...C?{error:C}:{}},n);return t.write(y,K(u.message??"structured_log",n)),s=y,t.onEmit?.(y),y}};return c}var Qt=Symbol("blyp.logger.factory"),jt={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},Ut={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},eo="\x1B[35m",to="\x1B[0m";function J(e){return vt(e)==="client_log"}function no(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",ingestingHost:void 0,status:"missing",errorTracking:{enabled:false,ready:false,status:"missing",dsn:void 0,tracesSampleRate:1,environment:void 0,release:void 0},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function ro(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function oo(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",host:"https://us.i.posthog.com",status:"missing",errorTracking:{enabled:false,ready:false,mode:"auto",status:"missing",enableExceptionAutocapture:false},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function ao(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function io(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function so(){return {get:e=>io(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function co(e){return e.connectors?.betterstack?.enabled?O("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):no()}function uo(e){return e.connectors?.databuddy?.enabled?O("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):ro()}function lo(e){return e.connectors?.posthog?.enabled?O("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):oo()}function po(e){return e.connectors?.sentry?.enabled?O("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):ao()}function fo(e){return e.connectors?.otlp?.some(t=>t.enabled)?O("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):so()}function go(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n={};t.data!==void 0&&(n.data=t.data);let r=typeof t.page?.pathname=="string"?t.page.pathname:void 0,o=typeof t.page?.url=="string"?t.page.url:void 0;return (r||o)&&(n.page=r??o),t.metadata!==void 0&&(n.metadata=t.metadata),Object.keys(n).length>0?n:null}function mo(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let n=go(e);return n?{hidden:false,value:n}:{hidden:true}}return {hidden:false,value:e}}function yo(e){if(e.pretty){let n=Ge()({colorize:true,translateTime:"SYS:HH:MM:ss",ignore:"pid,hostname,caller",customColors:{success:"green",critical:"red bold",info:"blue",warning:"yellow",error:"red",debug:"cyan",table:"cyan"},messageFormat:(r,o)=>{let a=String(r[o]??""),s=typeof r.caller=="string"?r.caller.trim():"";return s?`${a} ${eo}${s}${to}`:a}});return zt({level:e.level,customLevels:jt},n)}return zt({level:e.level,customLevels:jt})}function ho(e){let t=e[Qt];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function bo(e,t,n={}){let r=ho(e);return Ft(t,{initialFields:n.initialFields,resolveDefaultFields:()=>({...r.bindings,...n.resolveDefaultFields?.()??{}}),write:(o,a)=>{r.writeStructured(o,a,"structured-flush");},onCreate:n.onCreate,onEmit:n.onEmit,redact:n.redact??r.redact})}function qt(e,t){if(!J(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function $t(e,t){if(!J(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Kt(e,t){if(!J(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Wt(e,t){if(!J(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Ht(e,t){if(!J(t))for(let n of e.getAutoForwardTargets())n.send(t,{source:"server",warnIfUnavailable:true});}function je(e,t,n,r,o,a,s,i,c,u={},d="root"){let m=Object.keys(u).length>0?e.child(u):e,C=(f,p,B,M=d)=>{if(M==="root"&&Te())return;let g=mt(f,p,B,u,c),he=g.message,$={caller:g.caller},ee=mo(g.data);!ee.hidden&&ee.value!==void 0&&($.data=ee.value);let Qe=Ut[f],be=m;(be[Qe]??be.info??((Mo,Oo)=>{})).call(m,$,he),t.write(g),$t(r,g),Kt(o,g),qt(a,g),Wt(s,g),Ht(i,g);},P=(f,p,B="structured-flush")=>{let M=ht(f.level),g=yt(M,p,f,u,c),he=Ut[M],$=m;($[he]??$.info??((Qe,be)=>{})).call(m,{caller:g.caller,...g},g.message),(B!=="root"||!Te())&&t.write(g),$t(r,g),Kt(o,g),qt(a,g),Wt(s,g),Ht(i,g);},y={success:(f,...p)=>{C("success",f,p);},critical:(f,...p)=>{C("critical",f,p);},warning:(f,...p)=>{C("warning",f,p);},info:(f,...p)=>{C("info",f,p);},debug:(f,...p)=>{C("debug",f,p);},error:(f,...p)=>{C("error",f,p);},warn:(f,...p)=>{C("warn",f,p);},table:(f,p)=>{p&&typeof p=="object"&&Ot.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",f),console.table(h(p,c))),C("table",f,p===void 0?[]:[p]);},flush:async()=>{await t.flush(),n&&await n.flush(),await Promise.allSettled([r.flush(),o.flush(),a.flush(),s.flush(),i.flush()]);},shutdown:async()=>{await t.shutdown(),n&&await n.shutdown(),await Promise.allSettled([r.flush(),o.flush(),a.flush(),s.flush(),i.flush()]);},createStructuredLog:(f,p)=>bo(y,f,{initialFields:p}),child:f=>{let p={...u,...f};return je(e,t,n,r,o,a,s,i,c,p,d)},[Qt]:{bindings:u,betterstack:r,databuddy:o,posthog:a,sentry:s,otlp:i,redact:c,sink:t,create:(f,p=u)=>je(e,t,n,r,o,a,s,i,c,p,f),writeStructured:(f,p,B="structured-flush")=>{P(f,p,B);}}};return y}var ze=null;function Co(e){if(ze)return ze;let t=lt(e),n=yo(t),r=Lt(t),o=co(t),a=uo(t),s=lo(t),i=po(t),c=fo(t),u=t.connectors.delivery.enabled?new ue(t.connectors.delivery):null;if(u){u.bindTarget(o),u.bindTarget(a),u.bindTarget(s),u.bindTarget(i);for(let m of c.getAutoForwardTargets())u.bindTarget(m);}let d=je(n,r,u,o,a,s,i,c,t.redact);return (ze=d),d}var de=Co();var wo=new TextEncoder;function pe(e){return wo.encode(e).length}function Ro(e){if(!e||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function b(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(e instanceof Date)return e.toISOString();if(e instanceof Error)return {name:e.name,message:e.message,stack:e.stack};if(Array.isArray(e))return e.map(n=>b(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";if(t.add(e),!Ro(e)){let n=e.constructor?.name;return n?`[${n}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,b(r,t)]))}return String(e)}function k(e,t){if(t.length===0)return e;let n=b(e);for(let r of t){let o=r.split(".").filter(Boolean);if(o.length===0)continue;let a=n;for(let s=0;s<o.length-1;s+=1){if(!a||typeof a!="object"){a=void 0;break}a=a[o[s]];}a&&typeof a=="object"&&delete a[o[o.length-1]];}return n}function fe(e,t){let n=b(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof n=="string"){if(pe(n)<=t)return {value:n,truncated:false};let a=n;for(;a.length>0&&pe(`${a}\u2026[truncated]`)>t;)a=a.slice(0,Math.max(1,Math.floor(a.length*.8)));return {value:`${a}\u2026[truncated]`,truncated:true}}let r=JSON.stringify(n);if(r===void 0||pe(r)<=t)return {value:n,truncated:false};let o=r;for(;o.length>0&&pe(`${o}\u2026[truncated]`)>t;)o=o.slice(0,Math.max(1,Math.floor(o.length*.8)));return {value:{truncated:true,preview:`${o}\u2026[truncated]`},truncated:true}}function G(e){if(!e)return;let t={inputTokens:typeof e.inputTokens=="number"?e.inputTokens:void 0,outputTokens:typeof e.outputTokens=="number"?e.outputTokens:void 0,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:void 0,reasoningTokens:typeof e.reasoningTokens=="number"?e.reasoningTokens:void 0,cachedInputTokens:typeof e.cachedInputTokens=="number"?e.cachedInputTokens:void 0};if(t.totalTokens===void 0&&(t.inputTokens!==void 0||t.outputTokens!==void 0)&&(t.totalTokens=(t.inputTokens??0)+(t.outputTokens??0)),!Object.values(t).every(n=>n===void 0))return t}function A(e){if(typeof e=="string"&&e.length>0)return e;if(e&&typeof e=="object"){let t=e;for(let n of ["type","reason","stop_reason","finish_reason","raw","unified"]){let r=t[n];if(typeof r=="string"&&r.length>0)return r}}}function V(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Ue(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function Jt(e){if(!e)return {};if(e instanceof Error){let t=e;return {errorType:e.name,errorCode:t.code}}if(typeof e=="object"){let t=e;return {errorType:typeof t.type=="string"?t.type:typeof t.name=="string"?t.name:"Error",errorCode:typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}}return {errorType:typeof e}}function Gt(e){return b(e)}var qe={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},X={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},$e={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function To(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function ko(){return new Date().toISOString()}function Vt(e){return b(e)}function Ke(){return new Date().toISOString()}function So(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...qe,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??qe.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??qe.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??X.providerOptions,requestPaths:[...e.exclude?.requestPaths??X.requestPaths],responsePaths:[...e.exclude?.responsePaths??X.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??X.metadataPaths],toolNames:[...e.exclude?.toolNames??X.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??$e.maxContentBytes,maxEvents:e.limits?.maxEvents??$e.maxEvents,maxToolCalls:e.limits?.maxToolCalls??$e.maxToolCalls},hooks:e.hooks??{}}}function Xt(e={}){return So(e)}function Yt(e){let t=e.config.logger??te()??de,n=To(),r=Ke(),o={traceId:n,provider:e.provider,sdk:e.sdk,operation:e.operation??e.config.operation??e.method,method:e.method,model:e.model,logger:t,metadata:{...e.config.metadata},request:e.request,toolCalls:[],events:[],startedAt:r,startedAtMs:performance.now(),options:e.config,capture:{...e.config.capture},streamed:e.streamed,truncated:false},a={traceId:n,provider:o.provider,sdk:o.sdk,operation:o.operation,method:o.method,logger:t,metadata:o.metadata,request:o.request,get response(){return o.response},get usage(){return o.usage},get finishReason(){return o.finishReason},get input(){return o.input},get output(){return o.output},get reasoning(){return o.reasoning},get toolCalls(){return o.toolCalls.length>0?o.toolCalls:void 0},get startedAt(){return o.startedAt},get firstChunkAt(){return o.firstChunkAt},get endedAt(){return o.endedAt},get error(){return o.error},setMetadata(s){Object.assign(o.metadata,s);},disableCapture(s){o.capture[s]=false;}};return {state:o,context:a}}function ge(e,t){e.usage=G(t);}function me(e,t){e.finishReason=A(t);}function Zt(e,t){e.response=t;}function en(e,t){e.input=t;}function ye(e,t){e.output=t;}function tn(e,t){e.rawProviderPayload=Gt(t);}async function nn(e,t){e.firstChunkAt||(e.firstChunkAt=Ke(),e.firstChunkAtMs=performance.now(),await x(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function rn(e,t,n){e.capture.streamEvents&&await x(e,t,{type:"ai.chunk",data:n});}function q(e,t){let n=t.id??`${t.name}:${e.toolCalls.length}`,r=e.toolCalls.findIndex((o,a)=>(o.id??`${o.name}:${a}`)===n);if(r===-1&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(r===-1){e.toolCalls.push(t);return}e.toolCalls[r]={...e.toolCalls[r],...t};}async function We(e,t,n){q(e,n),await x(e,t,{type:"ai.tool_call.start",data:Ue(n)});}async function on(e,t,n){q(e,n),await x(e,t,{type:"ai.tool_call.result",data:Ue(n)});}function Lo(e){let t=e.toolCalls.filter(n=>!e.options.exclude.toolNames.includes(n.name)).map(n=>{let r={id:n.id,name:n.name,status:n.status};if(e.capture.toolInputs&&n.input!==void 0){let o=U(n.input,e.options.limits.maxContentBytes);r.input=o.value,e.truncated||(e.truncated=o.truncated);}if(e.capture.toolOutputs&&n.output!==void 0){let o=U(n.output,e.options.limits.maxContentBytes);r.output=o.value,e.truncated||(e.truncated=o.truncated);}return n.providerFormat!==void 0&&(r.providerFormat=b(n.providerFormat)),r});return t.length>0?t:void 0}async function Z(e,t,n){if(e.emitted)return;e.emitted=true,n?.error!==void 0&&(e.error=n.error,await x(e,t,{type:"ai.error",data:{error:b(n.error)}}),await Y(e.options.hooks.onError,[t])),e.endedAt=Ke(),await x(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await Y(e.options.hooks.onFinish,[t]);let r={startedAt:e.startedAt,endedAt:e.endedAt,durationMs:Math.max(0,Math.round(performance.now()-e.startedAtMs))};e.firstChunkAt&&e.firstChunkAtMs!==void 0&&(r.firstChunkAt=e.firstChunkAt,r.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs)));let o={provider:e.provider,sdk:e.sdk,model:e.model,operation:e.operation,method:e.method,streamed:e.streamed,timing:r,metadata:k(e.metadata,e.options.exclude.metadataPaths)};if(e.usage&&(o.usage=e.usage),e.finishReason&&(o.finishReason=e.finishReason),e.capture.input&&e.input!==void 0){let i=U(k(b(e.input),e.options.exclude.requestPaths),e.options.limits.maxContentBytes);o.input=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.output&&e.output!==void 0){let i=b(e.output),c=U(typeof i=="object"&&i!==null&&!Array.isArray(i)?k(i,e.options.exclude.responsePaths):i,e.options.limits.maxContentBytes);o.output=c.value,e.truncated||(e.truncated=c.truncated);}if(e.capture.reasoning&&e.reasoning!==void 0){let i=b(e.reasoning),c=U(i,e.options.limits.maxContentBytes);o.reasoning=c.value,e.truncated||(e.truncated=c.truncated);}let a=Lo(e);if(a&&(o.tools=a,o.toolCalls=a),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let i=U(e.rawProviderPayload,e.options.limits.maxContentBytes);o.rawProviderPayload=i.value,e.truncated||(e.truncated=i.truncated);}e.truncated&&o.metadata&&(o.metadata={...o.metadata,truncated:true});let s={...o};if(e.error!==void 0){let{errorType:i,errorCode:c}=Jt(e.error);i&&(s.errorType=i),c!==void 0&&(s.errorCode=c);}try{e.logger.createStructuredLog(e.traceId,{type:"ai_trace",ai:s,events:e.events}).emit({message:"ai_trace",level:e.error===void 0?"info":"error",...e.error===void 0?{}:{error:e.error}});}catch(i){console.warn("[Blyp] Failed to emit AI trace.",Vt(i));}}async function Y(e,t){if(e)try{await e(...t);}catch(n){console.warn("[Blyp] AI middleware hook failed.",Vt(n));}}async function x(e,t,n){e.events.length<e.options.limits.maxEvents?e.events.push({...n,timestamp:n.timestamp??ko()}):e.truncated=true,await Y(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function U(e,t){return fe(e,t)}function an(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function sn(e,t){return {[Symbol.asyncIterator](){let n=e[Symbol.asyncIterator]();return {async next(){try{let r=await n.next();return r.done?(await t.onReturn?.(),r):(await t.onChunk?.(r.value),r)}catch(r){throw await t.onError?.(r),r}},async return(r){try{return typeof n.return=="function"?await n.return(r):{done:!0,value:r}}finally{await t.onReturn?.();}},async throw(r){try{if(typeof n.throw=="function")return await n.throw(r);throw r}catch(o){throw await t.onError?.(o),o}}}}}}function vo(e){let t=e.output;if(!Array.isArray(t))return;let n=[];for(let r of t){if(!r||typeof r!="object")continue;let a=r.content;if(Array.isArray(a))for(let s of a){if(!s||typeof s!="object")continue;let c=s.text;typeof c=="string"&&n.push(c);}}return n.length>0?n.join(""):void 0}function Do(e){let t=e.output;if(!Array.isArray(t))return [];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let o=r,a=o.type;a==="function_call"&&n.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",input:V(o.arguments),status:"started"}),a==="function_call_output"&&n.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",output:o.output,status:"completed"});}return n}function xo(e){let t=e.choices;if(Array.isArray(t))return t.map(n=>{if(!n||typeof n!="object")return "";let r=n.message;return !r||typeof r!="object"?"":typeof r.content=="string"?r.content:""}).join("")}function Eo(e){let t=e.choices;if(!Array.isArray(t))return [];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let o=r.message;if(!o||typeof o!="object")continue;let s=o.tool_calls;if(Array.isArray(s))for(let i of s){if(!i||typeof i!="object")continue;let c=i,u=c.function,d=u&&typeof u=="object"?u:{};n.push({id:typeof c.id=="string"?c.id:void 0,name:typeof d.name=="string"?d.name:"unknown",input:V(d.arguments),providerFormat:c,status:"started"});}}return n}function cn(e,t){if(!e||typeof e!="object")return {toolCalls:[]};let n=e,r=n.usage&&typeof n.usage=="object"?n.usage:void 0,o=t==="chat.completions.create"?G({inputTokens:typeof r?.prompt_tokens=="number"?r.prompt_tokens:void 0,outputTokens:typeof r?.completion_tokens=="number"?r.completion_tokens:void 0,totalTokens:typeof r?.total_tokens=="number"?r.total_tokens:void 0,reasoningTokens:r?.completion_tokens_details&&typeof r.completion_tokens_details=="object"&&typeof r.completion_tokens_details.reasoning_tokens=="number"?r.completion_tokens_details.reasoning_tokens:void 0,cachedInputTokens:r?.prompt_tokens_details&&typeof r.prompt_tokens_details=="object"&&typeof r.prompt_tokens_details.cached_tokens=="number"?r.prompt_tokens_details.cached_tokens:void 0}):G({inputTokens:typeof r?.input_tokens=="number"?r.input_tokens:void 0,outputTokens:typeof r?.output_tokens=="number"?r.output_tokens:void 0,totalTokens:typeof r?.total_tokens=="number"?r.total_tokens:void 0,reasoningTokens:r?.output_tokens_details&&typeof r.output_tokens_details=="object"&&typeof r.output_tokens_details.reasoning_tokens=="number"?r.output_tokens_details.reasoning_tokens:void 0,cachedInputTokens:r?.input_tokens_details&&typeof r.input_tokens_details=="object"&&typeof r.input_tokens_details.cached_tokens=="number"?r.input_tokens_details.cached_tokens:void 0}),a=t==="chat.completions.create"?A(Array.isArray(n.choices)&&n.choices[0]&&typeof n.choices[0]=="object"?n.choices[0].finish_reason:void 0):A(n.status),s=t==="chat.completions.create"?Eo(n):Do(n),i={};return typeof n.id=="string"&&(i.responseId=n.id),typeof n.created_at=="number"&&(i.createdAt=n.created_at),typeof n.provider=="string"&&(i.upstreamProvider=n.provider),{model:typeof n.model=="string"?n.model:void 0,usage:o,finishReason:a,output:t==="chat.completions.create"?xo(n):vo(n),toolCalls:s,metadata:Object.keys(i).length>0?i:void 0}}async function un(e,t,n){if(!n||typeof n!="object")return;await nn(e,t);let r=n,o=r.type;if(typeof o=="string"&&await rn(e,t,{type:o}),o==="response.output_text.delta"&&typeof r.delta=="string"){let a=`${typeof e.output=="string"?e.output:""}${r.delta}`;ye(e,a);}if(o==="response.function_call_arguments.delta"){let a=typeof r.item_id=="string"?r.item_id:void 0,s=typeof r.name=="string"?r.name:"unknown",i=e.toolCalls.find(d=>d.id===a),c=`${typeof i?.input=="string"?i.input:""}${typeof r.delta=="string"?r.delta:""}`,u={id:a,name:s,input:c,status:"started"};i?q(e,u):await We(e,t,u);}if(o==="response.output_item.done"){let a=r.item;if(a&&typeof a=="object"){let s=a;if(s.type==="function_call"){let i={id:typeof s.call_id=="string"?s.call_id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:V(s.arguments),status:"started"};await We(e,t,i);}if(s.type==="function_call_output"){let i={id:typeof s.call_id=="string"?s.call_id:void 0,name:typeof s.name=="string"?s.name:"unknown",output:s.output,status:"completed"};await on(e,t,i);}}}if(o==="response.completed"){let a=r.response;if(a&&typeof a=="object"){let s=a;if(me(e,A(s.status)),s.usage&&typeof s.usage=="object"){let i=s.usage;ge(e,{inputTokens:typeof i.input_tokens=="number"?i.input_tokens:void 0,outputTokens:typeof i.output_tokens=="number"?i.output_tokens:void 0,totalTokens:typeof i.total_tokens=="number"?i.total_tokens:void 0});}}}}async function ln(e,t,n,r,o){let a=Xt({...o,provider:o.provider??"openai"}),{state:s,context:i}=Yt({provider:o.provider??"openai",sdk:"openai-sdk",operation:o.operation,method:t,model:typeof n.model=="string"?n.model:"unknown",request:n,streamed:n.stream===true,config:a});en(s,t==="chat.completions.create"?n.messages:n.input??n),await x(s,i,{type:"ai.start"}),await Y(a.hooks.onStart,[i]);try{let c=await e(n,...r);if(n.stream===!0&&an(c))return sn(c,{onChunk:async m=>{await un(s,i,m);},onReturn:async()=>{await Z(s,i);},onError:async m=>{await Z(s,i,{error:m});}});let u=cn(c,t);Zt(s,c),tn(s,c),u.metadata&&i.setMetadata(u.metadata),u.usage&&ge(s,u.usage),u.finishReason&&me(s,u.finishReason),u.output!==void 0&&ye(s,u.output);for(let d of u.toolCalls)q(s,d);return await Z(s,i),c}catch(c){throw await Z(s,i,{error:c}),c}}function He(e,t,n){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:n})}function _o(e,t={}){let n=Object.create(Object.getPrototypeOf(e));if(Object.assign(n,e),e.responses?.create){let r=e.responses,o=He(r,"create",(async(a,...s)=>ln(r.create.bind(r),"responses.create",a??{},s,t)));n.responses=o;}if(e.chat?.completions?.create){let r=e.chat,o=r.completions,a=He(o,"create",(async(s,...i)=>ln(o.create.bind(o),"chat.completions.create",s??{},i,t)));n.chat=He(r,"completions",a);}return n}function Ao(e={}){return {...e,provider:e.provider??"openai"}}function Po(e,t={}){let n=t.logger??te()??de,r={...t.metadata??{}},o=t.limits?.maxContentBytes??16384,a=t.exclude?.requestPaths??[],s=t.exclude?.responsePaths??[],i=(async(c,u)=>{let d=performance.now(),m=new Date().toISOString(),C=u?.method??(c instanceof Request?c.method:"GET"),P=typeof c=="string"?c:c instanceof URL?c.toString():c.url;try{let y=await e(c,u),f=new Date().toISOString(),p=n.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:P,method:C,status:y.status,startedAt:m,endedAt:f,durationMs:Math.max(0,Math.round(performance.now()-d)),requestId:y.headers.get("x-request-id")??y.headers.get("request-id")??y.headers.get("cf-ray")??void 0,metadata:k(r,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let M=await y.clone().json(),g=fe({request:k(b(u??{}),a),response:k(b(M),s)},o);p.set({fetchBody:g.value});}catch{}return p.emit({message:"fetch_trace",level:y.ok?"info":"error"}),y}catch(y){throw n.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:P,method:C,startedAt:m,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:k(r,t.exclude?.metadataPaths??[])}}).emit({message:"fetch_trace",level:"error",error:b(y)}),y}});return "preconnect"in e&&(i.preconnect=e.preconnect),i}
|
|
701
701
|
export{Po as blypFetch,Ao as createOpenAITracker,_o as wrapOpenAI};
|
|
@@ -46,6 +46,7 @@ type MutableSDKTrace = {
|
|
|
46
46
|
finishReason?: string;
|
|
47
47
|
input?: unknown;
|
|
48
48
|
output?: unknown;
|
|
49
|
+
reasoning?: unknown;
|
|
49
50
|
toolCalls: AIToolCallRecord[];
|
|
50
51
|
events: BlypTraceEvent[];
|
|
51
52
|
error?: unknown;
|
|
@@ -80,7 +81,9 @@ export declare function recordSDKFinishReason(state: MutableSDKTrace, reason: un
|
|
|
80
81
|
export declare function setSDKResponse(state: MutableSDKTrace, response: unknown): void;
|
|
81
82
|
export declare function setSDKInput(state: MutableSDKTrace, input: unknown): void;
|
|
82
83
|
export declare function setSDKOutput(state: MutableSDKTrace, output: unknown): void;
|
|
84
|
+
export declare function setSDKReasoning(state: MutableSDKTrace, reasoning: unknown): void;
|
|
83
85
|
export declare function setSDKRawProviderPayload(state: MutableSDKTrace, payload: unknown): void;
|
|
86
|
+
export declare function setSDKStreamed(state: MutableSDKTrace, streamed: boolean): void;
|
|
84
87
|
export declare function markSDKFirstChunk(state: MutableSDKTrace, context: BlypSDKContext): Promise<void>;
|
|
85
88
|
export declare function addSDKChunkEvent(state: MutableSDKTrace, context: BlypSDKContext, data: Record<string, unknown>): Promise<void>;
|
|
86
89
|
export declare function upsertSDKToolCall(state: MutableSDKTrace, toolCall: AIToolCallRecord): void;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { LanguageModelMiddleware } from 'ai';
|
|
2
2
|
import type { LanguageModelV3 } from '@ai-sdk/provider';
|
|
3
3
|
import type { BlypLogger } from '../../core/logger';
|
|
4
|
-
export type BlypAIProvider = 'openai' | 'anthropic' | 'openrouter';
|
|
5
|
-
export type BlypAISDK = 'ai-sdk' | 'openai-sdk' | 'anthropic-sdk';
|
|
4
|
+
export type BlypAIProvider = 'openai' | 'anthropic' | 'openrouter' | 'better-agent' | (string & {});
|
|
5
|
+
export type BlypAISDK = 'ai-sdk' | 'openai-sdk' | 'anthropic-sdk' | 'better-agent-sdk';
|
|
6
6
|
export type BlypTraceEvent = {
|
|
7
7
|
type: 'ai.start' | 'ai.first_chunk' | 'ai.chunk' | 'ai.tool_call.start' | 'ai.tool_call.result' | 'ai.finish' | 'ai.error';
|
|
8
8
|
timestamp: string;
|
|
@@ -102,6 +102,7 @@ export type BlypSDKContext = {
|
|
|
102
102
|
finishReason?: string;
|
|
103
103
|
input?: unknown;
|
|
104
104
|
output?: unknown;
|
|
105
|
+
reasoning?: unknown;
|
|
105
106
|
toolCalls?: AIToolCallRecord[];
|
|
106
107
|
startedAt: string;
|
|
107
108
|
firstChunkAt?: string;
|
|
@@ -133,8 +134,17 @@ export type BlypLLMTrace = {
|
|
|
133
134
|
providerFormat?: unknown;
|
|
134
135
|
status: 'started' | 'completed' | 'failed';
|
|
135
136
|
}>;
|
|
137
|
+
toolCalls?: Array<{
|
|
138
|
+
id?: string;
|
|
139
|
+
name: string;
|
|
140
|
+
input?: unknown;
|
|
141
|
+
output?: unknown;
|
|
142
|
+
providerFormat?: unknown;
|
|
143
|
+
status: 'started' | 'completed' | 'failed';
|
|
144
|
+
}>;
|
|
136
145
|
input?: unknown;
|
|
137
146
|
output?: unknown;
|
|
147
|
+
reasoning?: unknown;
|
|
138
148
|
timing: {
|
|
139
149
|
startedAt: string;
|
|
140
150
|
firstChunkAt?: string;
|