@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/anthropic.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import Ot from'pino';import {createJiti}from'jiti';import {createRequire}from'module';import {AsyncLocalStorage}from'async_hooks';import w,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import F,{resolve,dirname}from'path';import xn from'os';import {z as z$1}from'zod';import {gzipSync}from'fflate';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var sn=Object.defineProperty;var cn=(e,t,n)=>t in e?sn(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var l=(e,t,n)=>cn(e,typeof t!="symbol"?t+"":t,n);var ln=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Ke=new Map;function dn(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 M(e,t,n=`@blyp/core/${e}`){let
|
|
1
|
+
import Ot from'pino';import {createJiti}from'jiti';import {createRequire}from'module';import {AsyncLocalStorage}from'async_hooks';import w,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import F,{resolve,dirname}from'path';import xn from'os';import {z as z$1}from'zod';import {gzipSync}from'fflate';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var sn=Object.defineProperty;var cn=(e,t,n)=>t in e?sn(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var l=(e,t,n)=>cn(e,typeof t!="symbol"?t+"":t,n);var ln=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Ke=new Map;function dn(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 M(e,t,n=`@blyp/core/${e}`){let o=`@blyp/core/${e}`,r=`${o}::${n}`,a=Ke.get(r);if(a)return a;try{let s=ln(n);return Ke.set(r,s),s}catch(s){if(!dn(s))throw s;let i=t.map(u=>`"${u}"`).join(", "),c=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${o}". Install ${i} to use this API. Example: bun add ${c}. You can also import directly from "${o}".`,{cause:s instanceof Error?s:void 0})}}var fn=createRequire(typeof __filename=="string"?__filename:import.meta.url),be=null;function gn(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 mn(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 We(){if(be)return be;let e;try{e=fn("pino-pretty");}catch(n){throw gn(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=mn(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return be=t,t}var hn=new AsyncLocalStorage;function Ce(){return hn.getStore()}function Z(){return Ce()?.activeLogger}function we(){return Ce()?.traceId}function Re(){let e=Ce();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 ee(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 ee(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[o,r]of Object.entries(e))n[o]=T(r,t);return t.delete(e),n}return e}function Te(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 bn="[REDACTED]",Cn=["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 wn=[{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}],Rn=/\b(?:\d[ -]*?){16}\b/g;function He(e){let t=new Set,n=[];for(let o of e)typeof o!="string"||o.length===0||t.has(o)||(t.add(o),n.push(o));return n}function Tn(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Sn(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function kn(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Ln(e){return e.split(".").filter(Boolean)}function Se(e,t,n=0,o=0){if(n===e.length)return o===t.length;let r=e[n];if(r==="**"){if(n===e.length-1)return true;for(let a=o;a<=t.length;a+=1)if(Se(e,t,n+1,a))return true;return false}return o>=t.length||r!=="*"&&r!==t[o]?false:Se(e,t,n+1,o+1)}function vn(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>Se(Ln(n),e))}function Dn(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,o=false;for(let r=t.length-1;r>=0;r-=1){let a=Number(t[r]);o&&(a*=2,a>9&&(a-=9)),n+=a,o=!o;}return n%10===0}function Qe(e,t,n){if(n||t.disablePatternScanning)return e;let o=e;for(let{type:r,pattern:a}of wn)o=o.replace(a,`[REDACTED:${r}]`);o=o.replace(Rn,r=>Dn(r)?"[REDACTED:card]":r);for(let r of t.patterns)o=o.replace(Tn(r),"[REDACTED:pattern]");return o}function te(e,t,n,o){if(typeof e=="string")return Qe(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((a,s)=>te(a,t,n,{path:[...o.path,String(s)],skipPatternScanning:o.skipPatternScanning}));if(!Sn(e))return e;let r={};for(let[a,s]of Object.entries(e)){let i=[...o.path,a];if(n.has(a.toLowerCase())||vn(i,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[a]=bn;continue}r[a]=te(s,t,n,{path:i,skipPatternScanning:o.skipPatternScanning});continue}r[a]=te(s,t,n,{path:i,skipPatternScanning:o.skipPatternScanning});}return r}function k(e,t){return {keys:He([...Cn,...e?.keys??[],...t?.keys??[]]),paths:He([...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 o=T(e);return te(o,t,kn(t),n)}function q(e,t){return typeof e=="string"?Qe(e,t,false):Te(h(e,t))}function Je(){return F.join(xn.homedir(),".blyp","queue.db")}var An=z$1.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"}),Ge=z$1.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),Le=z$1.string().trim().min(1);function ve(e){return An.safeParse(e).success}function De(e){return Ge.safeParse(e).success}function x(e){return Le.safeParse(e).success}var xe="/inngest";z$1.union([z$1.literal("betterstack"),z$1.literal("databuddy"),z$1.literal("posthog"),z$1.literal("sentry"),z$1.undefined(),z$1.object({type:z$1.literal("otlp"),name:Le})]);function _n(e){try{return e()}catch{return}}function Pn(){return Math.random().toString(36).slice(2,10)}function Ve(){let e=_n(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${Pn()}`}function Bn(e,t=new Set){return (n,o,r)=>{if(t.has(n)||typeof console>"u")return;let a=console[e];if(typeof a=="function"){if(t.add(n),r===void 0){a.call(console,o);return}a.call(console,o,r);}}}function v(e){return Bn("warn",e)}var Nn="@blyp/core",Fn=".gitignore",et=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],zn="blyp.config.json",jn="https://us.i.posthog.com",Un="blyp-app",qn=Un,$n=new Set,D=v($n),tt={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},nt={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:tt},Ee={enabled:true,path:xe},rt=k(),O={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},R={enabled:false,memoryBufferSize:500,durableQueuePath:Je(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:O},ot={maxRetries:1,backoffMs:100},Kn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:ot},Xe={pretty:true,level:"info",destination:"file",file:nt,clientLogging:Ee,redact:rt,connectors:{delivery:R}},$=null;function Wn(e){let t=e;for(;;){let n=resolve(t,"package.json");if(existsSync(n))try{let r=JSON.parse(readFileSync(n,"utf-8"));if(x(r.name))return r.name}catch{}let o=dirname(t);if(o===t)return;t=o;}}function _e(e=process.cwd()){return Wn(e)??qn}function Hn(){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:xe},redact:rt,connectors:{delivery:R}}}function Qn(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==Nn}catch{return true}}function Jn(e){if(et.some(n=>existsSync(resolve(e,n))))return;let t=resolve(e,zn);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(Hn(),null,2)}
|
|
2
2
|
`);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function Gn(e){let t=resolve(e,Fn);if(!existsSync(t)){try{writeFileSync(t,`logs
|
|
3
3
|
.blyp
|
|
4
|
-
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=readFileSync(t,"utf-8"),
|
|
4
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=readFileSync(t,"utf-8"),o=["logs",".blyp"].filter(a=>{let s=a.replace(".","\\.");return !new RegExp(`^(?:/?${s}/?)\\s*$`,"m").test(n)});if(o.length===0)return;let r=n.endsWith(`
|
|
5
5
|
`)?"":`
|
|
6
|
-
`;appendFileSync(t,`${
|
|
6
|
+
`;appendFileSync(t,`${r}${o.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function Vn(){let e=process.cwd();Qn(e)&&(Jn(e),Gn(e));}function Xn(){let e=process.cwd(),t=et.map(
|
|
9
|
-
`),n=null;for(let
|
|
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(
|
|
8
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function Vn(){let e=process.cwd();Qn(e)&&(Jn(e),Gn(e));}function Xn(){let e=process.cwd(),t=et.map(o=>resolve(e,o)).filter(o=>existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];D(`config-multiple:${o}`,`[Blyp] Warning: Multiple config files found. Using ${o} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function at(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 Yn(e){try{let t=readFileSync(e,"utf-8");return at(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function Zn(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return at(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function er(e){return e.type==="json"?Yn(e.path):Zn(e.path)}function Ye(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function tr(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function nr(e,t){return {...ot,...e,...t}}function rr(e,t){return {...Kn,...e,...t,retry:nr(e?.retry,t?.retry)}}function or(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function ar(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function ir(e,t){if(!e)return;let n=e.adapter,o=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?Ye(n)?(o=or({...n,model:n.model??"blypLog"}),o||D("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):tr(n)&&(o=ar(n),o||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 r=Ye(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:r,delivery:rr(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function sr(e,t){return {...tt,...e,...t}}function cr(e,t){return {...nt,...e,...t,rotation:sr(e?.rotation,t?.rotation)}}function ur(e,t){return {...Ee,...e,...t,path:t?.path??e?.path??Ee.path}}function lr(e,t){return k(e,t)}function dr(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??O.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??O.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??O.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??O.multiplier),jitter:t?.jitter??e?.jitter??O.jitter}}function pr(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:x(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:dr(e?.retry,t?.retry),durableReady:false}}function fr(e,t,n){if(!(!e&&!t))return ir({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function gr(e,t){let n=t?.enabled??e?.enabled??false,o=t?.projectKey??e?.projectKey,r=e?.enabled===true?e?.errorTracking:void 0,a=t?.errorTracking?.mode??r?.mode??"auto",s=t?.errorTracking?.enabled??r?.enabled??n,i=n&&s&&typeof o=="string"&&o.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:o,host:t?.host??e?.host??jn,serviceName:t?.serviceName??e?.serviceName??_e(),errorTracking:{enabled:s,mode:a,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??r?.enableExceptionAutocapture??a==="auto",ready:i,status:i?"enabled":"missing"}}}function mr(e,t){let n=t?.enabled??e?.enabled??false,o=t?.apiKey??e?.apiKey,r=t?.websiteId??e?.websiteId,a=n&&x(o)&&x(r);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:o,websiteId:r,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 yr(e,t){let n=t?.sourceToken??e?.sourceToken,o=t?.ingestingHost??e?.ingestingHost,r=t?.enabled??e?.enabled??false,a=e?.enabled===true?e?.errorTracking:void 0,s=hr(r,a,t?.errorTracking),i=r&&x(n)&&ve(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??_e(),errorTracking:s,ready:i,status:i?"enabled":"missing"}}function hr(e,t,n){let o=n?.dsn??t?.dsn,r=n?.enabled??t?.enabled??e,a=r&&x(o);return {enabled:r,dsn:o,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:a,status:a?"enabled":"missing"}}function br(e,t){let n=t?.dsn??e?.dsn,o=t?.enabled??e?.enabled??false,r=o&&typeof n=="string"&&n.trim().length>0;return {enabled:o,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:r,status:r?"enabled":"missing"}}function Cr(e,t){let n=t?.endpoint??e?.endpoint,o=t?.enabled??e?.enabled??false,r={...{},...t?.headers??{}},a=o&&ve(n);return {name:t?.name??e?.name??"",enabled:o,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:r,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??_e(),ready:a,status:a?"enabled":"missing"}}function wr(e,t){let n=t??e??[],o=new Map;for(let r of n)!r||typeof r.name!="string"||r.name.length===0||(o.has(r.name)&&D(`otlp-duplicate:${r.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${r.name}" found. Using the last definition.`),o.set(r.name,Cr(void 0,r)));return Array.from(o.values())}function Rr(e,t){return {betterstack:yr(e?.betterstack,t?.betterstack),databuddy:mr(e?.databuddy,t?.databuddy),posthog:gr(e?.posthog,t?.posthog),sentry:br(e?.sentry,t?.sentry),otlp:wr(e?.otlp,t?.otlp),delivery:pr(e?.delivery,t?.delivery)}}function Ae(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:cr(e.file,t.file),database:fr(e.database,t.database,n.configFileType),clientLogging:ur(e.clientLogging,t.clientLogging),redact:lr(e.redact,t.redact),connectors:Rr(e.connectors,t.connectors)}}function Tr(){if($!==null)return $;Vn();let e=Xn();if(e){let t=er(e);$=Ae(Xe,t,{configFileType:e.type});}else $=Ae(Xe);return $}function it(e={}){return Ae(Tr(),e)}var st={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function re(e){return e.replace(/\\/g,"/")}function Sr(e){let t=re(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 kr(e){let t=re(e),n=re(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function ct(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
|
|
9
|
+
`),n=null;for(let o=2;o<t.length;o+=1){let r=t[o];if(!r)continue;let a=r.match(/\((.*):(\d+):\d+\)/)||r.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")&&!Sr(s)){let c=kr(s);if(!re(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 ut=q;function lt(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function dt(e,t,n,o,r=k()){let{file:a,line:s}=ct(),i=ut(t,r),c={timestamp:new Date().toISOString(),level:st[e],message:lt(i)},u=we();return t instanceof Error&&(c.error=h(ee(t),r)),a&&(c.caller=s!==null?`${a}:${s}`:a),n.length===1?c.data=h(n[0],r):n.length>1&&(c.data=h(n,r)),Object.keys(o).length>0&&(c.bindings=h(o,r)),u&&(c.traceId=u),c}function pt(e,t,n,o,r=k()){let{file:a,line:s}=ct(),i=h(n,r),c=we(),u={message:lt(ut(t,r)),...i};return a&&(u.caller=s!==null?`${a}:${s}`:a),Object.keys(o).length>0&&(u.bindings=h(o,r)),c&&u.traceId===void 0&&(u.traceId=c),u.level=typeof i.level=="string"&&i.level.length>0?i.level:st[e],u.timestamp=typeof i.timestamp=="string"&&i.timestamp.length>0?i.timestamp:new Date().toISOString(),u}function ft(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 vr(e){return Buffer.from(gzipSync(e))}function Dr(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function oe(e){w.mkdirSync(e,{recursive:true});}function xr(e){try{return w.statSync(e).size}catch{return 0}}function Er(e){let t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),o=String(e.getUTCDate()).padStart(2,"0"),r=String(e.getUTCHours()).padStart(2,"0"),a=String(e.getUTCMinutes()).padStart(2,"0"),s=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${n}${o}T${r}${a}${s}Z`}function Ar(e,t){let n=`${e}${t}`,o=1;for(;w.existsSync(n);)n=`${e}-${o}${t}`,o+=1;return n}function _r(e,t,n,o){let r=`${t}.`;try{let a=w.readdirSync(e).filter(i=>i.startsWith(r)&&(i.endsWith(".ndjson")||i.endsWith(".ndjson.gz"))).map(i=>F.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){o(`Failed to prune archives for ${t}`,a);}}function Pr(){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 Br(e){return JSON.stringify(e,Pr())}function Mr(e){let t=e.file,n=t?.dir||e.logDir||F.join(process.cwd(),"logs"),o=t?.archiveDir||F.join(n,"archive"),r=t?.rotation;return {enabled:t?.enabled??true,dir:n,archiveDir:o,rotationEnabled:r?.enabled??true,maxSizeBytes:r?.maxSizeBytes??10*1024*1024,maxArchives:r?.maxArchives??5,compress:r?.compress??true}}var Pe=class{constructor(t,n={}){l(this,"config");l(this,"gzip");l(this,"warn");l(this,"combined");l(this,"error");this.config=Mr(t),this.gzip=n.gzip??vr,this.warn=n.warn??Dr,this.combined={activePath:F.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:F.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(oe(this.config.dir),oe(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let n=`${Br(t)}
|
|
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(o){this.warn(`Failed writing log line for ${t.archivePrefix}`,o);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=xr(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){oe(this.config.dir);let o=Buffer.byteLength(n,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+o>this.config.maxSizeBytes&&this.rotate(t),w.appendFileSync(t.activePath,n,"utf8"),t.bytes+=o;}rotate(t){if(oe(this.config.archiveDir),!w.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let n=Er(new Date),o=F.join(this.config.archiveDir,`${t.archivePrefix}.${n}`),r=Ar(o,".ndjson");if(w.renameSync(t.activePath,r),this.config.compress)try{let a=`${r}.gz`,s=this.gzip(w.readFileSync(r));w.writeFileSync(a,s),w.rmSync(r);}catch(a){this.warn(`Failed to gzip archive ${r}`,a);}t.bytes=0,_r(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function gt(e){return new Pe(e)}var Be=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 mt(e){return new Be(gt(e))}function yt(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 Or(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function ht(e){let t=e.client,n=e.model??"blypLog",o=t[n];if(!o||typeof o.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${n}" delegate or its create method.`);let r=o,a=typeof r.createMany=="function";async function s(i){if(typeof t.$transaction=="function"){await t.$transaction(i.map(c=>r.create({data:c})));return}for(let c of i)await r.create({data:c});}return {async insert(i){if(i.length!==0){if(i.length===1){await r.create({data:i[0]});return}if(!a||typeof r.createMany!="function"){await s(i);return}try{await r.createMany({data:i});}catch(c){if(!Or(c))throw c;a=false,await s(i);}}}}}function bt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function z(e){return typeof e=="string"&&e.length>0?e:null}function Nr(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function Ct(e){let t=T(e);return {id:randomUUID(),timestamp:Nr(e.timestamp),level:e.level,message:e.message,caller:z(e.caller),type:z(e.type),traceId:z(e.traceId),groupId:z(e.groupId),method:z(e.method),path:z(e.path),status:bt(e.status),duration:bt(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 Fr(e){return !!e&&e.type==="prisma"}function zr(e){return !!e&&e.type==="drizzle"}function wt(e){if(Fr(e.adapter))return ht(e.adapter);if(zr(e.adapter))return yt(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function jr(e){return new Promise(t=>{setTimeout(t,e);})}var ae=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=wt(t);}write(t){this.closed||(this.enqueue(Ct(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((o,r)=>{n=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),r(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(o){let r=o instanceof Error?o:new Error(String(o??"Unknown database logging failure"));throw this.terminalError=r,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,r),r}}}async insertWithRetry(t){let n=Math.max(1,this.config.delivery.retry.maxRetries+1),o=0;for(;o<n;){o+=1;try{await this.writer.insert(t);return}catch(r){if(o>=n)throw r;await jr(this.config.delivery.retry.backoffMs);}}}};var Me=class{constructor(){l(this,"isAsync",false);l(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},Ur=v(new Set);function Rt(e){if(e.destination!=="database")return mt(e);let t=e.database;return t?.ready?new ae(t):(Ur("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new Me)}function qr(e){return De(e.data)?e.data:e}function $r(e,t){if(t in e){let r=e[t];if(typeof r=="string"||typeof r=="number")return r}let o=qr(e)[t];if(typeof o=="string"||typeof o=="number")return o}function Tt(e){return $r(e,"type")}function St(e,t){let n=Math.max(1,Math.floor(e)),o=Math.pow(t.multiplier,n-1),r=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*o)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(r+1)):r}var kt="bun:sqlite";var Lt="node:sqlite";function vt(){return `
|
|
11
11
|
const { parentPort } = require('node:worker_threads');
|
|
12
12
|
const fs = require('node:fs');
|
|
13
13
|
const path = require('node:path');
|
|
@@ -697,5 +697,5 @@ parentPort.on('message', async (message) => {
|
|
|
697
697
|
});
|
|
698
698
|
}
|
|
699
699
|
});
|
|
700
|
-
`}var ie=class{constructor(t){this.path=t;l(this,"worker");l(this,"pending",new Map);l(this,"nextId",1);this.worker=new Worker(vt(),{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 Dt=Symbol("blyp.connector.batch-dispatch"),$=Symbol("blyp.connector.delivery-binder");function K(e){return new Promise(t=>{setTimeout(t,e);})}function Wr(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function xt(e){return JSON.stringify(e)}function Hr(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Et(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 se=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[$]=="function"&&t[$](this);let n=t[Dt];n&&this.dispatchers.set(n.dispatchKey,n);}unbindTarget(t){typeof t[$]=="function"&&t[$](null);}enqueue(t,n,r,o){this.closed||!Wr(n)||(this.dispatchers.set(r.dispatchKey,r),this.memoryQueue.push({id:Ve(),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 ie(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 K(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:xt({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+St(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=Et(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=Et(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=xt({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=Hr(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 K(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await K(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 K(Math.max(t-Date.now(),0));}else await K(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var E=class E{constructor(){l(this,"_type",null);}static getInstance(){return E.instance||(E.instance=new E),E.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(E,"instance");var Oe=E,Ie=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)=>F.join(...t)});l(this,"env",{get:t=>Bun.env[t]});l(this,"cwd",()=>process.cwd());}},Ne=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)=>F.join(...t)});l(this,"env",{get:t=>process.env[t]});l(this,"cwd",()=>process.cwd());}};function Qr(){return Oe.getInstance().isBun?new Ie:new Ne}var _t=Qr();function Pt(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 Bt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Jr(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:Bt(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:Bt(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Gr(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 Mt(e,t){let n=t.redact??k(),r=performance.now(),o=h(t.initialFields??{},n),a=[],s;t.onCreate?.();let i=(u,d,g)=>(a.push({level:u,message:U(d,n),timestamp:new Date().toISOString(),...Pt(d,g)===void 0?{}:{data:h(Pt(d,g),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),g=Gr(u),C=h(Jr(u.error,g),n),_=u.level??(C?"error":"info"),y=h({...d,...o,groupId:e,timestamp:new Date().toISOString(),level:_,duration:Math.round(performance.now()-r),...typeof g=="number"?{status:g}:{},...a.length>0?{events:[...a]}:{},...C?{error:C}:{}},n);return t.write(y,U(u.message??"structured_log",n)),s=y,t.onEmit?.(y),y}};return c}var $t=Symbol("blyp.logger.factory"),It={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},Nt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Vr="\x1B[35m",Xr="\x1B[0m";function W(e){return Tt(e)==="client_log"}function Yr(){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 Zr(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function eo(){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 to(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function no(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function ro(){return {get:e=>no(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function oo(e){return e.connectors?.betterstack?.enabled?M("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Yr()}function ao(e){return e.connectors?.databuddy?.enabled?M("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Zr()}function io(e){return e.connectors?.posthog?.enabled?M("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):eo()}function so(e){return e.connectors?.sentry?.enabled?M("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):to()}function co(e){return e.connectors?.otlp?.some(t=>t.enabled)?M("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):ro()}function uo(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 lo(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=uo(e);return n?{hidden:false,value:n}:{hidden:true}}return {hidden:false,value:e}}function po(e){if(e.pretty){let n=We()({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} ${Vr}${s}${Xr}`:a}});return Ot({level:e.level,customLevels:It},n)}return Ot({level:e.level,customLevels:It})}function fo(e){let t=e[$t];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function go(e,t,n={}){let r=fo(e);return Mt(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 Ft(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function zt(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function jt(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Ut(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function qt(e,t){if(!W(t))for(let n of e.getAutoForwardTargets())n.send(t,{source:"server",warnIfUnavailable:true});}function ze(e,t,n,r,o,a,s,i,c,u={},d="root"){let g=Object.keys(u).length>0?e.child(u):e,C=(f,p,P,B=d)=>{if(B==="root"&&Re())return;let m=dt(f,p,P,u,c),ye=m.message,j={caller:m.caller},Y=lo(m.data);!Y.hidden&&Y.value!==void 0&&(j.data=Y.value);let $e=Nt[f],he=g;(he[$e]??he.info??((vo,Do)=>{})).call(g,j,ye),t.write(m),zt(r,m),jt(o,m),Ft(a,m),Ut(s,m),qt(i,m);},_=(f,p,P="structured-flush")=>{let B=ft(f.level),m=pt(B,p,f,u,c),ye=Nt[B],j=g;(j[ye]??j.info??(($e,he)=>{})).call(g,{caller:m.caller,...m},m.message),(P!=="root"||!Re())&&t.write(m),zt(r,m),jt(o,m),Ft(a,m),Ut(s,m),qt(i,m);},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"&&_t.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)=>go(y,f,{initialFields:p}),child:f=>{let p={...u,...f};return ze(e,t,n,r,o,a,s,i,c,p,d)},[$t]:{bindings:u,betterstack:r,databuddy:o,posthog:a,sentry:s,otlp:i,redact:c,sink:t,create:(f,p=u)=>ze(e,t,n,r,o,a,s,i,c,p,f),writeStructured:(f,p,P="structured-flush")=>{_(f,p,P);}}};return y}var Fe=null;function mo(e){if(Fe)return Fe;let t=it(e),n=po(t),r=Rt(t),o=oo(t),a=ao(t),s=io(t),i=so(t),c=co(t),u=t.connectors.delivery.enabled?new se(t.connectors.delivery):null;if(u){u.bindTarget(o),u.bindTarget(a),u.bindTarget(s),u.bindTarget(i);for(let g of c.getAutoForwardTargets())u.bindTarget(g);}let d=ze(n,r,u,o,a,s,i,c,t.redact);return (Fe=d),d}var ue=mo();var yo=new TextEncoder;function le(e){return yo.encode(e).length}function ho(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),!ho(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 S(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 de(e,t){let n=b(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof n=="string"){if(le(n)<=t)return {value:n,truncated:false};let a=n;for(;a.length>0&&le(`${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||le(r)<=t)return {value:n,truncated:false};let o=r;for(;o.length>0&&le(`${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 pe(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 fe(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 Kt(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function Wt(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 Ht(e){return b(e)}var je={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},H={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},Ue={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function bo(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function Co(){return new Date().toISOString()}function Qt(e){return b(e)}function qe(){return new Date().toISOString()}function wo(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...je,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??je.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??je.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??H.providerOptions,requestPaths:[...e.exclude?.requestPaths??H.requestPaths],responsePaths:[...e.exclude?.responsePaths??H.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??H.metadataPaths],toolNames:[...e.exclude?.toolNames??H.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??Ue.maxContentBytes,maxEvents:e.limits?.maxEvents??Ue.maxEvents,maxToolCalls:e.limits?.maxToolCalls??Ue.maxToolCalls},hooks:e.hooks??{}}}function Jt(e={}){return wo(e)}function Gt(e){let t=e.config.logger??Z()??ue,n=bo(),r=qe(),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 G(e,t){e.usage=pe(t);}function ge(e,t){e.finishReason=fe(t);}function Vt(e,t){e.response=t;}function Xt(e,t){e.input=t;}function me(e,t){e.output=t;}function Yt(e,t){e.rawProviderPayload=Ht(t);}async function Zt(e,t){e.firstChunkAt||(e.firstChunkAt=qe(),e.firstChunkAtMs=performance.now(),await A(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function en(e,t,n){e.capture.streamEvents&&await A(e,t,{type:"ai.chunk",data:n});}function V(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 tn(e,t,n){V(e,n),await A(e,t,{type:"ai.tool_call.start",data:Kt(n)});}function Ro(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=Q(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=Q(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 X(e,t,n){if(e.emitted)return;e.emitted=true,n?.error!==void 0&&(e.error=n.error,await A(e,t,{type:"ai.error",data:{error:b(n.error)}}),await J(e.options.hooks.onError,[t])),e.endedAt=qe(),await A(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await J(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:S(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=Q(S(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=Q(typeof i=="object"&&i!==null&&!Array.isArray(i)?S(i,e.options.exclude.responsePaths):i,e.options.limits.maxContentBytes);o.output=c.value,e.truncated||(e.truncated=c.truncated);}let a=Ro(e);if(a&&(o.tools=a),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let i=Q(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}=Wt(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.",Qt(i));}}async function J(e,t){if(e)try{await e(...t);}catch(n){console.warn("[Blyp] AI middleware hook failed.",Qt(n));}}async function A(e,t,n){e.events.length<e.options.limits.maxEvents?e.events.push({...n,timestamp:n.timestamp??Co()}):e.truncated=true,await J(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function Q(e,t){return de(e,t)}function nn(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function rn(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 on(e){if(!e||typeof e!="object")return {toolCalls:[]};let t=e,n=t.usage&&typeof t.usage=="object"?pe({inputTokens:typeof t.usage.input_tokens=="number"?t.usage.input_tokens:void 0,outputTokens:typeof t.usage.output_tokens=="number"?t.usage.output_tokens:void 0,cachedInputTokens:typeof t.usage.cache_read_input_tokens=="number"?t.usage.cache_read_input_tokens:void 0}):void 0,r=Array.isArray(t.content)?t.content:[],o=r.filter(s=>!!s&&typeof s=="object").filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join(""),a=r.filter(s=>!!s&&typeof s=="object").filter(s=>s.type==="tool_use").map(s=>({id:typeof s.id=="string"?s.id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:s.input,status:"started"}));return {model:typeof t.model=="string"?t.model:void 0,usage:n,finishReason:fe(t.stop_reason),output:o||void 0,toolCalls:a}}async function an(e,t,n){if(!n||typeof n!="object")return;let r=n,o=r.type;if(typeof o=="string"){if(await Zt(e,t),await en(e,t,{type:o}),o==="content_block_delta"){let a=r.delta;if(a&&typeof a=="object"){let s=a;if(s.type==="text_delta"&&typeof s.text=="string"&&me(e,`${typeof e.output=="string"?e.output:""}${s.text}`),s.type==="input_json_delta"&&typeof s.partial_json=="string"){let i=typeof r.index=="number"?r.index:0,c=e.toolCalls[i];V(e,{id:c?.id,name:c?.name??"unknown",input:`${typeof c?.input=="string"?c.input:""}${s.partial_json}`,status:c?.status??"started"});}}}if(o==="content_block_start"){let a=r.content_block;if(a&&typeof a=="object"){let s=a;s.type==="tool_use"&&await tn(e,t,{id:typeof s.id=="string"?s.id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:s.input,status:"started"});}}if(o==="message_delta"&&(ge(e,r.stop_reason),r.usage&&typeof r.usage=="object")){let a=r.usage;G(e,{outputTokens:typeof a.output_tokens=="number"?a.output_tokens:void 0});}if(o==="message_stop"&&r.usage&&typeof r.usage=="object"){let a=r.usage;G(e,{inputTokens:typeof a.input_tokens=="number"?a.input_tokens:void 0,outputTokens:typeof a.output_tokens=="number"?a.output_tokens:void 0});}}}function To(e,t,n){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:n})}function So(e,t={}){let n=Object.create(Object.getPrototypeOf(e));if(Object.assign(n,e),!e.messages?.create)return n;let r=async(o,...a)=>{let s=Jt({...t,provider:"anthropic"}),{state:i,context:c}=Gt({provider:"anthropic",sdk:"anthropic-sdk",operation:t.operation,method:"messages.create",model:typeof o?.model=="string"?o.model:"unknown",request:o,streamed:o?.stream===true,config:s});Xt(i,o?.messages??o),await A(i,c,{type:"ai.start"}),await J(s.hooks.onStart,[c]);try{let u=await e.messages.create(o,...a);if(o?.stream===!0&&nn(u))return rn(u,{onChunk:async g=>{await an(i,c,g);},onReturn:async()=>{await X(i,c);},onError:async g=>{await X(i,c,{error:g});}});let d=on(u);Vt(i,u),Yt(i,u),d.usage&&G(i,d.usage),d.finishReason&&ge(i,d.finishReason),d.output!==void 0&&me(i,d.output);for(let g of d.toolCalls)V(i,g);return await X(i,c),u}catch(u){throw await X(i,c,{error:u}),u}};return n.messages=To(e.messages,"create",r),n}function ko(e,t={}){let n=t.logger??Z()??ue,r={...t.metadata??{}},o=t.limits?.maxContentBytes??16384,a=t.exclude?.requestPaths??[],s=t.exclude?.responsePaths??[],i=(async(c,u)=>{let d=performance.now(),g=new Date().toISOString(),C=u?.method??(c instanceof Request?c.method:"GET"),_=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:_,method:C,status:y.status,startedAt:g,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:S(r,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let B=await y.clone().json(),m=de({request:S(b(u??{}),a),response:S(b(B),s)},o);p.set({fetchBody:m.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:_,method:C,startedAt:g,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:S(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 ie=class{constructor(t){this.path=t;l(this,"worker");l(this,"pending",new Map);l(this,"nextId",1);this.worker=new Worker(vt(),{eval:true}),this.worker.on("message",n=>{let o=this.pending.get(n.id);if(o){if(this.pending.delete(n.id),n.ok){o.resolve(n.result);return}o.reject(new Error(n.error??"SQLite worker request failed."));}}),this.worker.on("error",n=>{for(let o of this.pending.values())o.reject(n instanceof Error?n:new Error(String(n)));this.pending.clear();});}request(t,n={}){let o=this.nextId++;return new Promise((r,a)=>{this.pending.set(o,{resolve:r,reject:a}),this.worker.postMessage({id:o,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 Dt=Symbol("blyp.connector.batch-dispatch"),K=Symbol("blyp.connector.delivery-binder");function W(e){return new Promise(t=>{setTimeout(t,e);})}function Wr(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function xt(e){return JSON.stringify(e)}function Hr(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Et(e){let t=new Map;for(let n of e){let o=`${n.connectorType}:${n.connectorTarget??""}`;t.has(o)||t.set(o,{connectorType:n.connectorType,connectorTarget:n.connectorTarget});}return [...t.values()]}var se=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[K]=="function"&&t[K](this);let n=t[Dt];n&&this.dispatchers.set(n.dispatchKey,n);}unbindTarget(t){typeof t[K]=="function"&&t[K](null);}enqueue(t,n,o,r){this.closed||!Wr(n)||(this.dispatchers.set(o.dispatchKey,o),this.memoryQueue.push({id:Ve(),connectorType:t,connectorTarget:r,source:"server",record:n,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:o.dispatchKey,dispatcher:o}),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 ie(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 W(10);}}takeNextMemoryBatch(){let t=Date.now(),n=this.memoryQueue.findIndex(a=>a.nextAttemptAt<=t);if(n===-1)return [];let o=this.memoryQueue[n],r=[o];this.memoryQueue.splice(n,1);for(let a=this.memoryQueue.length-1;a>=0;a-=1){let s=this.memoryQueue[a];s.dispatchKey===o.dispatchKey&&s.connectorTarget===o.connectorTarget&&s.nextAttemptAt<=t&&r.length<this.config.memoryBatchSize&&(r.push(s),this.memoryQueue.splice(a,1));}return r}async dispatchMemoryBatch(t){let n=t[0].dispatcher,o=Date.now(),r=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(r.ok){await this.recordSuccessfulDispatch(t,o);return}await this.handleRetryableFailure(t,r,false,o);}async handleRetryableFailure(t,n,o,r){o||await this.durableInitPromise?.catch(()=>{});let a=[],s=[];await this.recordFailedDispatch(t,n,r);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:xt({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:r,lastAttemptAt:r}),this.warnOnce(`connector-drop:${i.connectorType}:${i.connectorTarget??"default"}:${i.id}`,o&&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=r+St(c,this.config.retry);if(o){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,r).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 o=Et(t).map(r=>({connectorType:r.connectorType,connectorTarget:r.connectorTarget,timestamp:n}));await this.durableClient.markSuccess(o).catch(r=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",r);});}async recordFailedDispatch(t,n,o){if(!this.durableReady||!this.durableClient||t.length===0)return;let r=Et(t).map(a=>({connectorType:a.connectorType,connectorTarget:a.connectorTarget,timestamp:o,lastError:n.error}));await this.durableClient.markFailure(r).catch(a=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",a);});}stageDurableJob(t,n,o,r){let a=xt({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:o,state:"pending",lastError:r,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,o=[];for(let r of t){let a=Hr(r.payloadJson);if(!a){o.push(r.id);continue}let s=r.connectorType==="otlp"?`otlp:${r.connectorTarget??""}`:r.connectorType,i=this.dispatchers.get(s);if(!i){o.push(r.id);continue}let c={id:r.id,connectorType:r.connectorType,connectorTarget:r.connectorTarget,source:a.source,record:a.record,attemptCount:r.attemptCount,maxAttempts:r.maxAttempts,nextAttemptAt:r.nextAttemptAt,createdAt:r.createdAt,dispatchKey:s,dispatcher:i},u=n.get(s)??[];u.push(c),n.set(s,u);}o.length>0&&await this.durableClient.ack(o);for(let r of n.values()){let s=await r[0].dispatcher.dispatch(r.map(i=>i.record),{source:"server",target:r[0].connectorTarget}).catch(i=>({ok:!1,retryable:!0,error:i instanceof Error?i.message:String(i)}));if(s.ok){await this.recordSuccessfulDispatch(r,Date.now()),await this.durableClient.ack(r.map(i=>i.id));continue}await this.handleRetryableFailure(r,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 W(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await W(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 W(Math.max(t-Date.now(),0));}else await W(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var E=class E{constructor(){l(this,"_type",null);}static getInstance(){return E.instance||(E.instance=new E),E.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(E,"instance");var Oe=E,Ie=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)=>F.join(...t)});l(this,"env",{get:t=>Bun.env[t]});l(this,"cwd",()=>process.cwd());}},Ne=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)=>F.join(...t)});l(this,"env",{get:t=>process.env[t]});l(this,"cwd",()=>process.cwd());}};function Qr(){return Oe.getInstance().isBun?new Ie:new Ne}var _t=Qr();function Pt(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 Bt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Jr(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:Bt(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,o=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${o??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:o,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:Bt(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Gr(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 Mt(e,t){let n=t.redact??k(),o=performance.now(),r=h(t.initialFields??{},n),a=[],s;t.onCreate?.();let i=(u,d,g)=>(a.push({level:u,message:q(d,n),timestamp:new Date().toISOString(),...Pt(d,g)===void 0?{}:{data:h(Pt(d,g),n)}}),c),c={set(u){return Object.assign(r,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),g=Gr(u),C=h(Jr(u.error,g),n),_=u.level??(C?"error":"info"),y=h({...d,...r,groupId:e,timestamp:new Date().toISOString(),level:_,duration:Math.round(performance.now()-o),...typeof g=="number"?{status:g}:{},...a.length>0?{events:[...a]}:{},...C?{error:C}:{}},n);return t.write(y,q(u.message??"structured_log",n)),s=y,t.onEmit?.(y),y}};return c}var $t=Symbol("blyp.logger.factory"),It={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},Nt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Vr="\x1B[35m",Xr="\x1B[0m";function H(e){return Tt(e)==="client_log"}function Yr(){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 Zr(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function eo(){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 to(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function no(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function ro(){return {get:e=>no(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function oo(e){return e.connectors?.betterstack?.enabled?M("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Yr()}function ao(e){return e.connectors?.databuddy?.enabled?M("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Zr()}function io(e){return e.connectors?.posthog?.enabled?M("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):eo()}function so(e){return e.connectors?.sentry?.enabled?M("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):to()}function co(e){return e.connectors?.otlp?.some(t=>t.enabled)?M("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):ro()}function uo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n={};t.data!==void 0&&(n.data=t.data);let o=typeof t.page?.pathname=="string"?t.page.pathname:void 0,r=typeof t.page?.url=="string"?t.page.url:void 0;return (o||r)&&(n.page=o??r),t.metadata!==void 0&&(n.metadata=t.metadata),Object.keys(n).length>0?n:null}function lo(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=uo(e);return n?{hidden:false,value:n}:{hidden:true}}return {hidden:false,value:e}}function po(e){if(e.pretty){let n=We()({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:(o,r)=>{let a=String(o[r]??""),s=typeof o.caller=="string"?o.caller.trim():"";return s?`${a} ${Vr}${s}${Xr}`:a}});return Ot({level:e.level,customLevels:It},n)}return Ot({level:e.level,customLevels:It})}function fo(e){let t=e[$t];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function go(e,t,n={}){let o=fo(e);return Mt(t,{initialFields:n.initialFields,resolveDefaultFields:()=>({...o.bindings,...n.resolveDefaultFields?.()??{}}),write:(r,a)=>{o.writeStructured(r,a,"structured-flush");},onCreate:n.onCreate,onEmit:n.onEmit,redact:n.redact??o.redact})}function Ft(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function zt(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function jt(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Ut(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function qt(e,t){if(!H(t))for(let n of e.getAutoForwardTargets())n.send(t,{source:"server",warnIfUnavailable:true});}function ze(e,t,n,o,r,a,s,i,c,u={},d="root"){let g=Object.keys(u).length>0?e.child(u):e,C=(f,p,P,B=d)=>{if(B==="root"&&Re())return;let m=dt(f,p,P,u,c),ye=m.message,U={caller:m.caller},Y=lo(m.data);!Y.hidden&&Y.value!==void 0&&(U.data=Y.value);let $e=Nt[f],he=g;(he[$e]??he.info??((vo,Do)=>{})).call(g,U,ye),t.write(m),zt(o,m),jt(r,m),Ft(a,m),Ut(s,m),qt(i,m);},_=(f,p,P="structured-flush")=>{let B=ft(f.level),m=pt(B,p,f,u,c),ye=Nt[B],U=g;(U[ye]??U.info??(($e,he)=>{})).call(g,{caller:m.caller,...m},m.message),(P!=="root"||!Re())&&t.write(m),zt(o,m),jt(r,m),Ft(a,m),Ut(s,m),qt(i,m);},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"&&_t.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([o.flush(),r.flush(),a.flush(),s.flush(),i.flush()]);},shutdown:async()=>{await t.shutdown(),n&&await n.shutdown(),await Promise.allSettled([o.flush(),r.flush(),a.flush(),s.flush(),i.flush()]);},createStructuredLog:(f,p)=>go(y,f,{initialFields:p}),child:f=>{let p={...u,...f};return ze(e,t,n,o,r,a,s,i,c,p,d)},[$t]:{bindings:u,betterstack:o,databuddy:r,posthog:a,sentry:s,otlp:i,redact:c,sink:t,create:(f,p=u)=>ze(e,t,n,o,r,a,s,i,c,p,f),writeStructured:(f,p,P="structured-flush")=>{_(f,p,P);}}};return y}var Fe=null;function mo(e){if(Fe)return Fe;let t=it(e),n=po(t),o=Rt(t),r=oo(t),a=ao(t),s=io(t),i=so(t),c=co(t),u=t.connectors.delivery.enabled?new se(t.connectors.delivery):null;if(u){u.bindTarget(r),u.bindTarget(a),u.bindTarget(s),u.bindTarget(i);for(let g of c.getAutoForwardTargets())u.bindTarget(g);}let d=ze(n,o,u,r,a,s,i,c,t.redact);return (Fe=d),d}var ue=mo();var yo=new TextEncoder;function le(e){return yo.encode(e).length}function ho(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),!ho(e)){let n=e.constructor?.name;return n?`[${n}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,b(o,t)]))}return String(e)}function S(e,t){if(t.length===0)return e;let n=b(e);for(let o of t){let r=o.split(".").filter(Boolean);if(r.length===0)continue;let a=n;for(let s=0;s<r.length-1;s+=1){if(!a||typeof a!="object"){a=void 0;break}a=a[r[s]];}a&&typeof a=="object"&&delete a[r[r.length-1]];}return n}function de(e,t){let n=b(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof n=="string"){if(le(n)<=t)return {value:n,truncated:false};let a=n;for(;a.length>0&&le(`${a}\u2026[truncated]`)>t;)a=a.slice(0,Math.max(1,Math.floor(a.length*.8)));return {value:`${a}\u2026[truncated]`,truncated:true}}let o=JSON.stringify(n);if(o===void 0||le(o)<=t)return {value:n,truncated:false};let r=o;for(;r.length>0&&le(`${r}\u2026[truncated]`)>t;)r=r.slice(0,Math.max(1,Math.floor(r.length*.8)));return {value:{truncated:true,preview:`${r}\u2026[truncated]`},truncated:true}}function pe(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 fe(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 o=t[n];if(typeof o=="string"&&o.length>0)return o}}}function Kt(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function Wt(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 Ht(e){return b(e)}var je={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},Q={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},Ue={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function bo(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function Co(){return new Date().toISOString()}function Qt(e){return b(e)}function qe(){return new Date().toISOString()}function wo(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...je,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??je.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??je.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??Q.providerOptions,requestPaths:[...e.exclude?.requestPaths??Q.requestPaths],responsePaths:[...e.exclude?.responsePaths??Q.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??Q.metadataPaths],toolNames:[...e.exclude?.toolNames??Q.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??Ue.maxContentBytes,maxEvents:e.limits?.maxEvents??Ue.maxEvents,maxToolCalls:e.limits?.maxToolCalls??Ue.maxToolCalls},hooks:e.hooks??{}}}function Jt(e={}){return wo(e)}function Gt(e){let t=e.config.logger??Z()??ue,n=bo(),o=qe(),r={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:o,startedAtMs:performance.now(),options:e.config,capture:{...e.config.capture},streamed:e.streamed,truncated:false},a={traceId:n,provider:r.provider,sdk:r.sdk,operation:r.operation,method:r.method,logger:t,metadata:r.metadata,request:r.request,get response(){return r.response},get usage(){return r.usage},get finishReason(){return r.finishReason},get input(){return r.input},get output(){return r.output},get reasoning(){return r.reasoning},get toolCalls(){return r.toolCalls.length>0?r.toolCalls:void 0},get startedAt(){return r.startedAt},get firstChunkAt(){return r.firstChunkAt},get endedAt(){return r.endedAt},get error(){return r.error},setMetadata(s){Object.assign(r.metadata,s);},disableCapture(s){r.capture[s]=false;}};return {state:r,context:a}}function G(e,t){e.usage=pe(t);}function ge(e,t){e.finishReason=fe(t);}function Vt(e,t){e.response=t;}function Xt(e,t){e.input=t;}function me(e,t){e.output=t;}function Yt(e,t){e.rawProviderPayload=Ht(t);}async function Zt(e,t){e.firstChunkAt||(e.firstChunkAt=qe(),e.firstChunkAtMs=performance.now(),await A(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function en(e,t,n){e.capture.streamEvents&&await A(e,t,{type:"ai.chunk",data:n});}function V(e,t){let n=t.id??`${t.name}:${e.toolCalls.length}`,o=e.toolCalls.findIndex((r,a)=>(r.id??`${r.name}:${a}`)===n);if(o===-1&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(o===-1){e.toolCalls.push(t);return}e.toolCalls[o]={...e.toolCalls[o],...t};}async function tn(e,t,n){V(e,n),await A(e,t,{type:"ai.tool_call.start",data:Kt(n)});}function Ro(e){let t=e.toolCalls.filter(n=>!e.options.exclude.toolNames.includes(n.name)).map(n=>{let o={id:n.id,name:n.name,status:n.status};if(e.capture.toolInputs&&n.input!==void 0){let r=j(n.input,e.options.limits.maxContentBytes);o.input=r.value,e.truncated||(e.truncated=r.truncated);}if(e.capture.toolOutputs&&n.output!==void 0){let r=j(n.output,e.options.limits.maxContentBytes);o.output=r.value,e.truncated||(e.truncated=r.truncated);}return n.providerFormat!==void 0&&(o.providerFormat=b(n.providerFormat)),o});return t.length>0?t:void 0}async function X(e,t,n){if(e.emitted)return;e.emitted=true,n?.error!==void 0&&(e.error=n.error,await A(e,t,{type:"ai.error",data:{error:b(n.error)}}),await J(e.options.hooks.onError,[t])),e.endedAt=qe(),await A(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await J(e.options.hooks.onFinish,[t]);let o={startedAt:e.startedAt,endedAt:e.endedAt,durationMs:Math.max(0,Math.round(performance.now()-e.startedAtMs))};e.firstChunkAt&&e.firstChunkAtMs!==void 0&&(o.firstChunkAt=e.firstChunkAt,o.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs)));let r={provider:e.provider,sdk:e.sdk,model:e.model,operation:e.operation,method:e.method,streamed:e.streamed,timing:o,metadata:S(e.metadata,e.options.exclude.metadataPaths)};if(e.usage&&(r.usage=e.usage),e.finishReason&&(r.finishReason=e.finishReason),e.capture.input&&e.input!==void 0){let i=j(S(b(e.input),e.options.exclude.requestPaths),e.options.limits.maxContentBytes);r.input=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.output&&e.output!==void 0){let i=b(e.output),c=j(typeof i=="object"&&i!==null&&!Array.isArray(i)?S(i,e.options.exclude.responsePaths):i,e.options.limits.maxContentBytes);r.output=c.value,e.truncated||(e.truncated=c.truncated);}if(e.capture.reasoning&&e.reasoning!==void 0){let i=b(e.reasoning),c=j(i,e.options.limits.maxContentBytes);r.reasoning=c.value,e.truncated||(e.truncated=c.truncated);}let a=Ro(e);if(a&&(r.tools=a,r.toolCalls=a),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let i=j(e.rawProviderPayload,e.options.limits.maxContentBytes);r.rawProviderPayload=i.value,e.truncated||(e.truncated=i.truncated);}e.truncated&&r.metadata&&(r.metadata={...r.metadata,truncated:true});let s={...r};if(e.error!==void 0){let{errorType:i,errorCode:c}=Wt(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.",Qt(i));}}async function J(e,t){if(e)try{await e(...t);}catch(n){console.warn("[Blyp] AI middleware hook failed.",Qt(n));}}async function A(e,t,n){e.events.length<e.options.limits.maxEvents?e.events.push({...n,timestamp:n.timestamp??Co()}):e.truncated=true,await J(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function j(e,t){return de(e,t)}function nn(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function rn(e,t){return {[Symbol.asyncIterator](){let n=e[Symbol.asyncIterator]();return {async next(){try{let o=await n.next();return o.done?(await t.onReturn?.(),o):(await t.onChunk?.(o.value),o)}catch(o){throw await t.onError?.(o),o}},async return(o){try{return typeof n.return=="function"?await n.return(o):{done:!0,value:o}}finally{await t.onReturn?.();}},async throw(o){try{if(typeof n.throw=="function")return await n.throw(o);throw o}catch(r){throw await t.onError?.(r),r}}}}}}function on(e){if(!e||typeof e!="object")return {toolCalls:[]};let t=e,n=t.usage&&typeof t.usage=="object"?pe({inputTokens:typeof t.usage.input_tokens=="number"?t.usage.input_tokens:void 0,outputTokens:typeof t.usage.output_tokens=="number"?t.usage.output_tokens:void 0,cachedInputTokens:typeof t.usage.cache_read_input_tokens=="number"?t.usage.cache_read_input_tokens:void 0}):void 0,o=Array.isArray(t.content)?t.content:[],r=o.filter(s=>!!s&&typeof s=="object").filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join(""),a=o.filter(s=>!!s&&typeof s=="object").filter(s=>s.type==="tool_use").map(s=>({id:typeof s.id=="string"?s.id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:s.input,status:"started"}));return {model:typeof t.model=="string"?t.model:void 0,usage:n,finishReason:fe(t.stop_reason),output:r||void 0,toolCalls:a}}async function an(e,t,n){if(!n||typeof n!="object")return;let o=n,r=o.type;if(typeof r=="string"){if(await Zt(e,t),await en(e,t,{type:r}),r==="content_block_delta"){let a=o.delta;if(a&&typeof a=="object"){let s=a;if(s.type==="text_delta"&&typeof s.text=="string"&&me(e,`${typeof e.output=="string"?e.output:""}${s.text}`),s.type==="input_json_delta"&&typeof s.partial_json=="string"){let i=typeof o.index=="number"?o.index:0,c=e.toolCalls[i];V(e,{id:c?.id,name:c?.name??"unknown",input:`${typeof c?.input=="string"?c.input:""}${s.partial_json}`,status:c?.status??"started"});}}}if(r==="content_block_start"){let a=o.content_block;if(a&&typeof a=="object"){let s=a;s.type==="tool_use"&&await tn(e,t,{id:typeof s.id=="string"?s.id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:s.input,status:"started"});}}if(r==="message_delta"&&(ge(e,o.stop_reason),o.usage&&typeof o.usage=="object")){let a=o.usage;G(e,{outputTokens:typeof a.output_tokens=="number"?a.output_tokens:void 0});}if(r==="message_stop"&&o.usage&&typeof o.usage=="object"){let a=o.usage;G(e,{inputTokens:typeof a.input_tokens=="number"?a.input_tokens:void 0,outputTokens:typeof a.output_tokens=="number"?a.output_tokens:void 0});}}}function To(e,t,n){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:n})}function So(e,t={}){let n=Object.create(Object.getPrototypeOf(e));if(Object.assign(n,e),!e.messages?.create)return n;let o=async(r,...a)=>{let s=Jt({...t,provider:"anthropic"}),{state:i,context:c}=Gt({provider:"anthropic",sdk:"anthropic-sdk",operation:t.operation,method:"messages.create",model:typeof r?.model=="string"?r.model:"unknown",request:r,streamed:r?.stream===true,config:s});Xt(i,r?.messages??r),await A(i,c,{type:"ai.start"}),await J(s.hooks.onStart,[c]);try{let u=await e.messages.create(r,...a);if(r?.stream===!0&&nn(u))return rn(u,{onChunk:async g=>{await an(i,c,g);},onReturn:async()=>{await X(i,c);},onError:async g=>{await X(i,c,{error:g});}});let d=on(u);Vt(i,u),Yt(i,u),d.usage&&G(i,d.usage),d.finishReason&&ge(i,d.finishReason),d.output!==void 0&&me(i,d.output);for(let g of d.toolCalls)V(i,g);return await X(i,c),u}catch(u){throw await X(i,c,{error:u}),u}};return n.messages=To(e.messages,"create",o),n}function ko(e,t={}){let n=t.logger??Z()??ue,o={...t.metadata??{}},r=t.limits?.maxContentBytes??16384,a=t.exclude?.requestPaths??[],s=t.exclude?.responsePaths??[],i=(async(c,u)=>{let d=performance.now(),g=new Date().toISOString(),C=u?.method??(c instanceof Request?c.method:"GET"),_=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:_,method:C,status:y.status,startedAt:g,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:S(o,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let B=await y.clone().json(),m=de({request:S(b(u??{}),a),response:S(b(B),s)},r);p.set({fetchBody:m.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:_,method:C,startedAt:g,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:S(o,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{ko as blypFetch,So as wrapAnthropic};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Event as BetterAgentEvent } from '@better-agent/core/events';
|
|
2
|
+
import type { GenerativeModelResponse } from '@better-agent/core/providers';
|
|
3
|
+
import { normalizeTokenUsage } from '../shared/normalize';
|
|
4
|
+
export type BetterAgentNormalizedUsage = ReturnType<typeof normalizeTokenUsage>;
|
|
5
|
+
export declare function mergeBetterAgentUsage(current: BetterAgentNormalizedUsage, next: BetterAgentNormalizedUsage): BetterAgentNormalizedUsage;
|
|
6
|
+
export declare function normalizeBetterAgentUsage(response: GenerativeModelResponse): BetterAgentNormalizedUsage;
|
|
7
|
+
export declare function normalizeBetterAgentFinishReason(response: GenerativeModelResponse): string | undefined;
|
|
8
|
+
export declare function extractBetterAgentOutput(response: GenerativeModelResponse): {
|
|
9
|
+
output?: string;
|
|
10
|
+
reasoning?: string;
|
|
11
|
+
};
|
|
12
|
+
export declare function extractBetterAgentProviderPayload(response: GenerativeModelResponse): {
|
|
13
|
+
request?: unknown;
|
|
14
|
+
response?: unknown;
|
|
15
|
+
} | undefined;
|
|
16
|
+
export declare function isBetterAgentTerminalEvent(event: BetterAgentEvent): boolean;
|
|
17
|
+
export declare function isBetterAgentLiveEvent(event: BetterAgentEvent): boolean;
|
|
18
|
+
export declare function parseBetterAgentToolArgs(value: unknown): unknown;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Event as BetterAgentEvent } from '@better-agent/core/events';
|
|
2
|
+
import type { GenerativeModelResponse } from '@better-agent/core/providers';
|
|
3
|
+
import type { BlypAIProvider, BlypProviderOptions } from '../shared/types';
|
|
4
|
+
export type BlypBetterAgentRunResolver = (ctx: {
|
|
5
|
+
runId: string;
|
|
6
|
+
agentName: string;
|
|
7
|
+
conversationId?: string;
|
|
8
|
+
}) => {
|
|
9
|
+
provider?: BlypAIProvider;
|
|
10
|
+
model?: string;
|
|
11
|
+
operation?: string;
|
|
12
|
+
method?: string;
|
|
13
|
+
metadata?: Record<string, unknown>;
|
|
14
|
+
streamed?: boolean;
|
|
15
|
+
} | Promise<{
|
|
16
|
+
provider?: BlypAIProvider;
|
|
17
|
+
model?: string;
|
|
18
|
+
operation?: string;
|
|
19
|
+
method?: string;
|
|
20
|
+
metadata?: Record<string, unknown>;
|
|
21
|
+
streamed?: boolean;
|
|
22
|
+
} | undefined> | undefined;
|
|
23
|
+
export type BlypBetterAgentOptions = Omit<BlypProviderOptions, 'provider' | 'operation' | 'metadata'> & {
|
|
24
|
+
provider?: BlypAIProvider;
|
|
25
|
+
operation?: string;
|
|
26
|
+
metadata?: Record<string, unknown>;
|
|
27
|
+
resolveRun?: BlypBetterAgentRunResolver;
|
|
28
|
+
};
|
|
29
|
+
export type BlypBetterAgentTracker = {
|
|
30
|
+
onEvent(event: BetterAgentEvent): Promise<void>;
|
|
31
|
+
onAfterModelCall(response: GenerativeModelResponse, info?: {
|
|
32
|
+
stepIndex?: number;
|
|
33
|
+
}): Promise<void>;
|
|
34
|
+
};
|
|
35
|
+
export declare function createBetterAgentTracker(options?: BlypBetterAgentOptions): BlypBetterAgentTracker;
|