@juspay/neurolink 12.21.1 → 12.21.2
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/CHANGELOG.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
## [12.21.
|
|
1
|
+
## [12.21.2](https://github.com/juspay/neurolink/compare/v12.21.1...v12.21.2) (2026-09-24)
|
|
2
2
|
|
|
3
3
|
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(
|
|
6
|
-
- **(
|
|
7
|
-
- **(
|
|
5
|
+
- **(images):** label transcoded image parts with their real media type on the OpenAI wire ([2a6591d](https://github.com/juspay/neurolink/commit/2a6591decfe4003afc0dfec379ccfb862e553e3a))
|
|
6
|
+
- **(landing):** override fflate to the patched version on the OG request path ([6453cf8](https://github.com/juspay/neurolink/commit/6453cf8297d0865383e21ca2e5c3debaac39b65e))
|
|
7
|
+
- **(yama-review):** fail the job when a run posts no review ([8aff399](https://github.com/juspay/neurolink/commit/8aff3992b82757379841c227cec18a7614aa323f)), closes [#1746](https://github.com/juspay/neurolink/issues/1746) [#1754](https://github.com/juspay/neurolink/issues/1754) [#1754](https://github.com/juspay/neurolink/issues/1754)
|
|
8
8
|
|
|
9
9
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
10
10
|
|
|
@@ -949,7 +949,7 @@ ${y}
|
|
|
949
949
|
|
|
950
950
|
Example: analyzeCSV(filePath="${e}", operation="count_by_column", column="merchant_id")
|
|
951
951
|
|
|
952
|
-
`}var Omt,Nmt,IM,HV,jV,VV,RM=b({"src/lib/utils/messageBuilder.ts"(){"use strict";on(),Ho(),vb(),Yh(),bGe(),OAr(),$b(),Tl(),Oo(),sZe(),lt(),Ja(),s7(),Zh(),tt(),smt(),d7(),umt(),HXe(),rf(),z(),EQe(),Ut(),_tt(),DXe(),is(),Omt=Object.fromEntries(Xh.flatMap(e=>e.extensions.map(t=>[t.slice(1),e.fileType]))),Nmt=Object.fromEntries(Xh.flatMap(e=>e.mimeTypes.map(t=>[t.toLowerCase(),e.fileType]))),IM=new WeakMap,HV=3e4,jV=4,VV=3e4}});function Lmt(e){let t=0;for(const r of e)if(typeof r.content=="string")t+=r.content.length;else if(Array.isArray(r.content))for(const n of r.content)"text"in n&&typeof n.text=="string"&&(t+=n.text.length);return t}function Fmt(e){const t=e.input,r=!!t?.images?.length,n=!!t?.content?.length,o=!!t?.csvFiles?.length,s=!!t?.pdfFiles?.length,i=!!t?.files?.length,a=!!t?.audioFiles?.length,c=!!t?.videoFiles?.length;return{isMultimodal:r||n||o||s||i||a||c,hasImages:r,hasFiles:o||s||i||a||c}}var WV,jIr=b({"src/lib/core/modules/MessageBuilder.ts"(){"use strict";Ja(),z(),RM(),WV=class{constructor(e,t){this.providerName=e,this.modelName=t}providerName;modelName;async buildMessages(e){return dt({name:"neurolink.message.build",tracer:$e.sdk,attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName}},async t=>{const{isMultimodal:r,hasImages:n,hasFiles:o}=Fmt(e);t.setAttribute(be.MSG_IS_MULTIMODAL,r);let s;if(r){process.env.NEUROLINK_DEBUG==="true"&&p.debug("Detected multimodal input, using multimodal message builder");const a=e.input,c={input:{text:e.prompt||e.input?.text||"",images:a?.images,content:a?.content,csvFiles:a?.csvFiles,pdfFiles:a?.pdfFiles,audioFiles:a?.audioFiles,videoFiles:a?.videoFiles,files:a?.files},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,conversationHistory:e.conversationMessages,schema:e.schema,output:e.output,fileRegistry:e.fileRegistry};s=await AM(c,this.providerName,this.modelName),c.systemPrompt&&c.systemPrompt!==e.systemPrompt&&(e.systemPrompt=c.systemPrompt)}else process.env.NEUROLINK_DEBUG==="true"&&p.debug("No multimodal input detected, using standard message builder"),s=await BV(e);const i=s.map(a=>{const c=a.providerOptions;return typeof a.content=="string"?{role:a.role,content:a.content,...c&&{providerOptions:c}}:{role:a.role,content:a.content.map(l=>{const u=l.providerOptions;return l.type==="text"?{type:"text",text:l.text||"",...u&&{providerOptions:u}}:l.type==="image"?{type:"image",image:l.image||"",...u&&{providerOptions:u}}:l}),...c&&{providerOptions:c}}});return t.setAttribute(be.MSG_COUNT,i.length),t.setAttribute(be.MSG_HAS_IMAGES,n),t.setAttribute(be.MSG_HAS_FILES,o),t.setAttribute(be.MSG_HAS_SYSTEM_PROMPT,!!e.systemPrompt),t.setAttribute(be.MSG_TOTAL_CONTENT_LENGTH,Lmt(i)),i})}async buildMessagesForStream(e){return dt({name:"neurolink.message.build_for_stream",tracer:$e.sdk,attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName}},async t=>{const{isMultimodal:r,hasImages:n,hasFiles:o}=Fmt(e);t.setAttribute(be.MSG_IS_MULTIMODAL,r);let s;if(r){process.env.NEUROLINK_DEBUG==="true"&&p.debug(`${this.providerName}: Detected multimodal input, using multimodal message builder`);const a=e.input,c={input:{text:e.prompt||e.input?.text||"",images:a?.images,content:a?.content,csvFiles:a?.csvFiles,pdfFiles:a?.pdfFiles,audioFiles:a?.audioFiles,videoFiles:a?.videoFiles,files:a?.files},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,conversationHistory:e.conversationMessages,schema:e.schema,output:e.output,fileRegistry:e.fileRegistry};s=await AM(c,this.providerName,this.modelName),c.systemPrompt&&c.systemPrompt!==e.systemPrompt&&(e.systemPrompt=c.systemPrompt)}else process.env.NEUROLINK_DEBUG==="true"&&p.debug(`${this.providerName}: No multimodal input detected, using standard message builder`),s=await BV(e);const i=s.map(a=>{const c=a.providerOptions;return typeof a.content=="string"?{role:a.role,content:a.content,...c&&{providerOptions:c}}:{role:a.role,content:a.content.map(l=>{const u=l.providerOptions;return l.type==="text"?{type:"text",text:l.text||"",...u&&{providerOptions:u}}:l.type==="image"?{type:"image",image:l.image||"",...u&&{providerOptions:u}}:l}),...c&&{providerOptions:c}}});return t.setAttribute(be.MSG_COUNT,i.length),t.setAttribute(be.MSG_HAS_IMAGES,n),t.setAttribute(be.MSG_HAS_FILES,o),t.setAttribute(be.MSG_HAS_SYSTEM_PROMPT,!!e.systemPrompt),t.setAttribute(be.MSG_TOTAL_CONTENT_LENGTH,Lmt(i)),i})}}}}),$mt={};te($mt,{DEFAULT_BEFORE_STEP_TIMEOUT_MS:()=>o9,MAX_PPT_PAGES:()=>NM,MAX_PPT_PROMPT_LENGTH:()=>FM,MIN_PPT_PAGES:()=>OM,MIN_PPT_PROMPT_LENGTH:()=>LM,ValidationError:()=>bt,createValidationSummary:()=>r_,hasOnlyWarnings:()=>QIr,validateAsyncFunction:()=>Umt,validateDirectorModeInput:()=>XIr,validateExecutionControl:()=>Gmt,validateGenerateOptions:()=>WIr,validateImageForVideo:()=>YV,validateMCPTool:()=>PM,validateNumberRange:()=>mf,validateObjectStructure:()=>VIr,validatePPTGenerationInput:()=>ZIr,validatePPTOutputOptions:()=>zmt,validatePPTProvider:()=>qmt,validateRequiredString:()=>x0,validateStreamOptions:()=>KV,validateTextGenerationOptions:()=>Bmt,validateToolBatch:()=>JIr,validateToolDescription:()=>MM,validateToolExecutionParams:()=>KIr,validateToolName:()=>t_,validateVideoGenerationInput:()=>YIr,validateVideoOutputOptions:()=>JV});function x0(e,t,r=1){return e==null?new bt(`${t} is required`,t,"REQUIRED_FIELD",[`Provide a valid ${t.toLowerCase()}`]):typeof e!="string"?new bt(`${t} must be a string, received ${typeof e}`,t,"INVALID_TYPE",[`Convert ${t.toLowerCase()} to string format`]):e.trim().length<r?new bt(`${t} must be at least ${r} character${r>1?"s":""} long`,t,"MIN_LENGTH",[`Provide a meaningful ${t.toLowerCase()}`]):null}function mf(e,t,r,n,o=!1){return e==null?o?new bt(`${t} is required`,t,"REQUIRED_FIELD",[`Provide a number between ${r} and ${n}`]):null:typeof e!="number"||isNaN(e)?new bt(`${t} must be a valid number, received ${typeof e}`,t,"INVALID_TYPE",[`Provide a number between ${r} and ${n}`]):e<r||e>n?new bt(`${t} must be between ${r} and ${n}, received ${e}`,t,"OUT_OF_RANGE",[`Use a value between ${r} and ${n}`]):null}function Umt(e,t,r=[]){if(typeof e!="function")return new bt(`${t} must be a function, received ${typeof e}`,t,"INVALID_TYPE",["Provide an async function",`Expected signature: async (${r.join(", ")}) => Promise<unknown>`]);const n=e.toString();return n.includes("async")||n.includes("Promise")?null:new bt(`${t} must be an async function that returns a Promise`,t,"NOT_ASYNC",["Add 'async' keyword to function declaration","Return a Promise from the function",`Example: async (${r.join(", ")}) => { return result; }`])}function VIr(e,t,r,n=[]){if(!Xt(e))return new bt(`${t} must be an object, received ${typeof e}`,t,"INVALID_TYPE",[`Provide an object with properties: ${r.join(", ")}`,...n.length>0?[`Optional properties: ${n.join(", ")}`]:[]]);const o=e,s=r.filter(i=>!(i in o));return s.length>0?new bt(`${t} is missing required properties: ${s.join(", ")}`,t,"MISSING_PROPERTIES",[`Add missing properties: ${s.join(", ")}`]):null}function t_(e){const t=x0(e,"Tool name",1);if(t)return t;const r=e;return/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(r)?r.length>64?new bt(`Tool name too long: ${r.length} characters (max: 64)`,"name","MAX_LENGTH",["Use a shorter, more concise name"]):["execute","validate","setup","init","config"].includes(r.toLowerCase())?new bt(`Tool name '${r}' is reserved`,"name","RESERVED_NAME",["Choose a different name","Add a prefix or suffix to make it unique"]):null:new bt("Tool name must start with a letter and contain only letters, numbers, underscores, and hyphens","name","INVALID_FORMAT",["Use alphanumeric characters, underscores, and hyphens only","Start with a letter","Examples: 'calculateSum', 'data_processor', 'api-client'"])}function MM(e){const t=x0(e,"Tool description",10);if(t)return t;const r=e;return r.length>500?new bt(`Tool description too long: ${r.length} characters (max: 500)`,"description","MAX_LENGTH",["Keep description concise and focused","Use under 500 characters"]):r.split(/\s+/).filter(o=>o.length>2).length<3?new bt("Tool description should be more descriptive","description","TOO_BRIEF",["Explain what the tool does","Include expected parameters","Describe the return value"]):null}function PM(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Tool must be an object","tool","INVALID_TYPE",["Provide a valid tool object with name, description, and execute properties"])),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e,s=t_(o.name);s&&t.push(s);const i=MM(o.description);i&&t.push(i);const a=Umt(o.execute,"execute function",["params","context"]);return a&&t.push(a),o.execute&&typeof o.execute!="function"&&t.push(new bt("Execute must be a function","execute","INVALID_TYPE",["Provide a function for the execute property"])),o.inputSchema&&!Xt(o.inputSchema)&&(r.push("inputSchema should be an object if provided"),n.push("Provide a valid JSON schema or Zod schema for input validation")),o.outputSchema&&!Xt(o.outputSchema)&&(r.push("outputSchema should be an object if provided"),n.push("Provide a valid JSON schema or Zod schema for output validation")),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function Bmt(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Options must be an object","options","INVALID_TYPE")),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e,s=o.output?.mode,i=s==="video"||s==="avatar"||s==="music",a=!!o.stt?.audio;if(!i&&!a){const u=x0(o.prompt,"prompt",1);u&&t.push(u)}o.prompt&&o.prompt.length>Ta.MAX_PROMPT_LENGTH&&t.push(new bt(`Prompt too large: ${o.prompt.length} characters (max: ${Ta.MAX_PROMPT_LENGTH})`,"prompt","MAX_LENGTH",["Break prompt into smaller chunks","Use summarization for long content","Consider using streaming for large inputs"]));const c=mf(o.temperature,"temperature",0,2);c&&t.push(c);const l=mf(o.maxTokens,"maxTokens",1,128e3);return l&&t.push(l),o.timeout!==void 0&&(typeof o.timeout=="string"?/^\d+[smh]?$/.test(o.timeout)||t.push(new bt("Invalid timeout format. Use number (ms) or string like '30s', '2m', '1h'","timeout","INVALID_FORMAT",["Use format: 30000 (ms), '30s', '2m', or '1h'"])):typeof o.timeout=="number"?(o.timeout<1e3||o.timeout>6e5)&&(r.push("Timeout outside recommended range (1s - 10m)"),n.push("Use timeout between 1000ms (1s) and 600000ms (10m)")):t.push(new bt("Timeout must be a number (ms) or string","timeout","INVALID_TYPE"))),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function KV(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Options must be an object","options","INVALID_TYPE")),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e;if(!o.input||!Xt(o.input))t.push(new bt("input is required and must be an object with text property","input","REQUIRED_FIELD",["Provide input: { text: 'your prompt here' }"]));else{const a=x0(o.input.text,"input.text",1);a&&t.push(a)}const s=mf(o.temperature,"temperature",0,2);s&&t.push(s);const i=mf(o.maxTokens,"maxTokens",1,128e3);return i&&t.push(i),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function WIr(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Options must be an object","options","INVALID_TYPE")),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e;if(!o.input||!Xt(o.input))t.push(new bt("input is required and must be an object with text property","input","REQUIRED_FIELD",["Provide input: { text: 'your prompt here' }"]));else{const a=x0(o.input.text,"input.text",1);a&&t.push(a)}const s=mf(o.temperature,"temperature",0,2);s&&t.push(s);const i=mf(o.maxTokens,"maxTokens",1,128e3);return i&&t.push(i),o.factoryConfig&&!Xt(o.factoryConfig)&&(r.push("factoryConfig should be an object if provided"),n.push("Provide valid factory configuration or remove the property")),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function KIr(e,t,r){const n=[],o=[],s=[];if(t!=null&&!Xt(t))return n.push(new bt(`Parameters for tool '${e}' must be an object`,"params","INVALID_TYPE",["Provide parameters as an object: { key: value, ... }"])),{isValid:!1,errors:n,warnings:o,suggestions:s};if(r&&t)try{o.push("Schema validation not yet implemented"),s.push("Implement Zod schema validation for tool parameters")}catch(i){n.push(new bt(`Parameter validation failed: ${i instanceof Error?i.message:String(i)}`,"params","SCHEMA_VALIDATION",["Check parameter format against tool schema"]))}return{isValid:n.length===0,errors:n,warnings:o,suggestions:s}}function JIr(e){const t=[],r=[],n={};for(const[o,s]of Object.entries(e)){const i=t_(o),a=PM(s),c={isValid:!i&&a.isValid,errors:i?[i,...a.errors]:a.errors,warnings:a.warnings,suggestions:a.suggestions};n[o]=c,c.isValid?t.push(o):r.push(o)}return{isValid:r.length===0,validTools:t,invalidTools:r,results:n}}function Ji(e){const t=e.field??e.context?.field;return new bt(e.message,t,e.code,e.suggestions)}function JV(e){return e.resolution&&!Hmt.includes(e.resolution)?ue.invalidVideoResolution(e.resolution):e.length!==void 0&&!jmt.includes(e.length)?ue.invalidVideoLength(e.length):e.aspectRatio&&!Vmt.includes(e.aspectRatio)?ue.invalidVideoAspectRatio(e.aspectRatio):e.audio!==void 0&&typeof e.audio!="boolean"?ue.invalidVideoAudio(e.audio):null}function YV(e,t=Wmt){if(e==null)return ue.invalidImageType();if(typeof e=="string")return e.trim().length===0?ue.emptyImagePath():null;if(!Buffer.isBuffer(e))return ue.invalidImageType();if(e.length>t){const i=(e.length/1024/1024).toFixed(2),a=(t/1024/1024).toFixed(0);return ue.imageTooLarge(i,a)}if(e.length<8)return ue.imageTooSmall();const r=e[0]===255&&e[1]===216&&e[2]===255,n=e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71,o=e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80;return r||n||o?null:ue.invalidImageFormat()}function YIr(e){const t=[],r=[],n=[];if(e.output?.mode!=="video"&&t.push(Ji(ue.invalidVideoMode())),!e.input?.images||e.input.images.length===0?t.push(Ji(ue.missingVideoImage())):e.input.images.length>1&&(r.push("Only the first image will be used for video generation. Additional images will be ignored."),n.push("Provide a single image for video generation")),e.input?.images&&e.input.images.length>0){const s=e.input.images[0],i=typeof s=="object"&&"data"in s?s.data:s;if(typeof i!="string"){const a=YV(i);a&&t.push(Ji(a))}}const o=e.input?.text?.trim()||"";if(o.length===0?t.push(Ji(ue.emptyVideoPrompt())):o.length>ZV&&t.push(Ji(ue.videoPromptTooLong(o.length,ZV))),e.output?.video){const s=JV(e.output.video);s&&t.push(Ji(s))}return t.length===0&&r.length===0&&n.push("Video generation takes 60-180 seconds. Consider setting a longer timeout."),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function XIr(e){const t=[],r=[],n=[],o=e.input?.segments;if(!o||!Array.isArray(o))return t.push(new bt("Director Mode requires an input.segments array","input.segments",We.DIRECTOR_SEGMENT_MISMATCH)),{isValid:!1,errors:t,warnings:r,suggestions:n};if(o.length<QV||o.length>DM)return t.push(new bt(`Director Mode requires ${QV}-${DM} segments, got ${o.length}`,"input.segments",o.length>DM?We.DIRECTOR_SEGMENT_LIMIT_EXCEEDED:We.DIRECTOR_SEGMENT_MISMATCH)),{isValid:!1,errors:t,warnings:r,suggestions:n};for(let a=0;a<o.length;a++){const c=o[a];if(!c||typeof c!="object"){t.push(new bt(`Segment ${a} must be an object with prompt and image`,`input.segments[${a}]`,We.DIRECTOR_SEGMENT_MISMATCH));continue}(!c.prompt||typeof c.prompt!="string"||c.prompt.trim().length===0)&&t.push(new bt(`Segment ${a} requires a non-empty prompt`,`input.segments[${a}].prompt`,We.DIRECTOR_SEGMENT_MISMATCH)),(c.image===void 0||c.image===null)&&t.push(new bt(`Segment ${a} requires a valid image (Buffer, URL, path, or ImageWithAltText)`,`input.segments[${a}].image`,We.DIRECTOR_SEGMENT_MISMATCH))}const s=e.output?.director,i=o.length-1;if(s?.transitionPrompts&&s.transitionPrompts.length!==i&&t.push(new bt(`Expected ${i} transition prompts, got ${s.transitionPrompts.length}`,"output.director.transitionPrompts",We.DIRECTOR_SEGMENT_MISMATCH)),s?.transitionDurations)if(s.transitionDurations.length!==i)t.push(new bt(`Expected ${i} transition durations, got ${s.transitionDurations.length}`,"output.director.transitionDurations",We.DIRECTOR_SEGMENT_MISMATCH));else for(let a=0;a<s.transitionDurations.length;a++){const c=s.transitionDurations[a];Kmt.includes(c)||t.push(new bt(`Invalid transition duration at index ${a}: ${c}. Use 4, 6, or 8`,`output.director.transitionDurations[${a}]`,We.DIRECTOR_INVALID_TRANSITION_DURATION))}if(e.output?.video){const a=JV(e.output.video);a&&t.push(Ji(a))}if(t.length===0){const a=o.length+i;n.push(`Director Mode will make ${a} API calls (${o.length} clips + ${i} transitions). Ensure adequate timeout.`)}return{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function zmt(e){if(e.pages===void 0||e.pages===null)return ue.invalidPPTPages(void 0,"pages is required");if(typeof e.pages!="number")return ue.invalidPPTPages(e.pages,"not a number");if(!Number.isInteger(e.pages))return ue.invalidPPTPages(e.pages,"not an integer");if(e.pages<OM||e.pages>NM)return ue.invalidPPTPages(e.pages,`out of range (${OM}-${NM})`);if(e.format!==void 0&&!Jmt.includes(e.format))return ue.invalidPPTFormat(e.format);if(e.theme!==void 0&&!e9.includes(e.theme))return ue.invalidPPTOutputOptions("theme",e.theme,Array.from(e9));if(e.audience!==void 0&&!t9.includes(e.audience))return ue.invalidPPTOutputOptions("audience",e.audience,Array.from(t9));if(e.tone!==void 0&&!r9.includes(e.tone))return ue.invalidPPTOutputOptions("tone",e.tone,Array.from(r9));if(e.aspectRatio!==void 0&&!n9.includes(e.aspectRatio))return ue.invalidPPTOutputOptions("aspectRatio",e.aspectRatio,Array.from(n9));if(e.generateAIImages!==void 0&&typeof e.generateAIImages!="boolean")return ue.invalidPPTOutputOptions("generateAIImages",e.generateAIImages,["true","false"]);if(e.logoPath!==void 0){if(typeof e.logoPath=="string"){if(e.logoPath.trim().length===0)return ue.invalidPPTLogoPath(e.logoPath,"empty string")}else if(!Buffer.isBuffer(e.logoPath))if(typeof e.logoPath=="object"&&"data"in e.logoPath){const t=e.logoPath.data;if(typeof t=="string"){if(t.trim().length===0)return ue.invalidPPTLogoPath(e.logoPath,"empty string")}else if(!Buffer.isBuffer(t))return ue.invalidPPTLogoPath(e.logoPath,"invalid data type")}else return ue.invalidPPTLogoPath(e.logoPath,"invalid type")}if(e.outputPath!==void 0){if(typeof e.outputPath!="string")return ue.invalidPPTOutputPath(e.outputPath,"not a string");if(e.outputPath.trim().length===0)return ue.invalidPPTOutputPath(e.outputPath,"empty string")}return null}function qmt(e){const t=["vertex","openai","azure","anthropic","google-ai","bedrock"],r=String(e).toLowerCase();return t.includes(r)?null:ue.invalidPPTProvider(e)}function ZIr(e){const t=[],r=[],n=[];if(!e.input?.text)return t.push(Ji(ue.invalidPPTPrompt("input.text is required"))),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e.input.text.trim();if(o===""?t.push(Ji(ue.invalidPPTPrompt("empty prompt"))):o.length<LM?t.push(Ji(ue.invalidPPTPrompt(`prompt too short (${o.length} characters, minimum ${LM} required)`))):o.length>FM&&t.push(Ji(ue.invalidPPTPrompt(`prompt too long (${o.length} characters, max ${FM})`))),e.input.images&&e.input.images.length>0&&(r.push("Images can be unused in PPT generation due to fail in quality standards and can lead to longer generation times."),n.push("Only provide high-quality, relevant images for PPT generation.")),e.provider!==void 0){const s=qmt(e.provider);s&&t.push(Ji(s))}if(e.output?.mode!==void 0&&e.output.mode!=="ppt"&&t.push(Ji(ue.invalidPPTMode())),e.output?.ppt){const s=zmt(e.output.ppt);s&&t.push(Ji(s));const i=e.output.ppt.pages;i!==void 0&&i>30&&r.push(`Generating ${i} slides may take significant time (estimated: ${Math.ceil(i*3)}-${Math.ceil(i*5)} seconds)`),(e.output.ppt.generateAIImages===void 0||e.output.ppt.generateAIImages===!0)&&n.push("AI image generation is enabled. Each slide with images will take additional time (~2-5 seconds per image).");const a=[];e.output.ppt.theme===void 0&&a.push("theme"),e.output.ppt.audience===void 0&&a.push("audience"),e.output.ppt.tone===void 0&&a.push("tone"),a.length>0&&n.push(`AI will decide: ${a.join(", ")} (based on topic analysis)`)}else t.push(Ji(ue.missingPPTProperty("output.ppt",["Provide PPT generation options under output.ppt","pages is required, theme/audience/tone are optional (AI will decide if not specified)"])));return t.length===0&&r.length===0&&n.push("PPT generation typically takes 30-120 seconds depending on slide count and image generation."),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function r_(e){const t=[];return e.errors.length>0&&t.push(`Errors: ${e.errors.map(r=>r.message).join("; ")}`),e.warnings.length>0&&t.push(`Warnings: ${e.warnings.join("; ")}`),e.suggestions.length>0&&t.push(`Suggestions: ${e.suggestions.join("; ")}`),t.join(" | ")}function QIr(e){return e.errors.length===0&&e.warnings.length>0}function XV(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Gmt(e,t,r,n={}){const{turnTimeoutMs:o,toolTimeoutMs:s}=n;if(e==null)return;if(!Xt(e))throw new bt("executionControl must be an object","executionControl","INVALID_TYPE");if(!r)throw new bt(`executionControl is not supported by provider "${t}" \u2014 it is implemented only on the native Anthropic stream path. Remove it, or route this turn to anthropic.`,"executionControl","UNSUPPORTED_PROVIDER",["Use provider: 'anthropic' for turns that need executionControl","Use turnTimeoutMs / maxSteps for other providers"]);const i=e;if(!XV(i.requestTimeoutMs))throw new bt(`executionControl.requestTimeoutMs is required and must be a finite positive number of milliseconds (received ${String(i.requestTimeoutMs)}). It is the deadline that bounds a stalled upstream even when the turn has no lifetime ceiling, so there is no valid turn without it.`,"executionControl.requestTimeoutMs","INVALID_VALUE");if(i.lifetimeTimeoutMs!==void 0&&i.lifetimeTimeoutMs!==null&&!XV(i.lifetimeTimeoutMs))throw new bt(`executionControl.lifetimeTimeoutMs must be null (no lifetime ceiling), a finite positive number of milliseconds, or absent (inherit the legacy timeout handling). Received ${String(i.lifetimeTimeoutMs)}.`,"executionControl.lifetimeTimeoutMs","INVALID_VALUE");if(i.lifetimeTimeoutMs!==void 0&&typeof o=="number"&&Number.isFinite(o)&&o>0)throw new bt(`turnTimeoutMs (${o}) cannot be combined with executionControl.lifetimeTimeoutMs (${String(i.lifetimeTimeoutMs)}): both set the turn's wall-clock ceiling, and executionControl wins, so the turnTimeoutMs would be ignored. Set exactly one of them.`,"executionControl.lifetimeTimeoutMs","INVALID_VALUE",["Drop turnTimeoutMs and express the ceiling as executionControl.lifetimeTimeoutMs","Or drop executionControl.lifetimeTimeoutMs to inherit turnTimeoutMs unchanged"]);if(i.lifetimeTimeoutMs===null&&s===null)throw new bt("executionControl.lifetimeTimeoutMs: null removes the turn's wall-clock ceiling, which leaves toolTimeoutMs as the only bound on a tool that never returns \u2014 and toolTimeoutMs: null removes that one too, so the turn would have no bound anywhere. Keep one of them.","executionControl.lifetimeTimeoutMs","INVALID_VALUE",["Give toolTimeoutMs a finite bound, or omit it to take the 300000ms default","Or give executionControl.lifetimeTimeoutMs a finite ceiling instead of null"]);if(i.beforeStep!==void 0&&typeof i.beforeStep!="function")throw new bt("executionControl.beforeStep must be a function","executionControl.beforeStep","INVALID_TYPE");if(i.beforeStepTimeoutMs!==void 0&&!XV(i.beforeStepTimeoutMs))throw new bt(`executionControl.beforeStepTimeoutMs must be a finite positive number of milliseconds when supplied. Received ${String(i.beforeStepTimeoutMs)}.`,"executionControl.beforeStepTimeoutMs","INVALID_VALUE")}var bt,Hmt,jmt,Vmt,ZV,Wmt,QV,DM,Kmt,e9,t9,r9,n9,Jmt,OM,NM,LM,FM,o9,Sd=b({"src/lib/utils/parameterValidation.ts"(){"use strict";Ju(),Oo(),tt(),Eh(),bt=class extends Error{constructor(e,t,r,n){super(e),this.field=t,this.code=r,this.suggestions=n,this.name="ValidationError"}field;code;suggestions},Hmt=["720p","1080p"],jmt=[4,5,6,8,10],Vmt=["9:16","16:9"],ZV=500,Wmt=10*1024*1024,QV=2,DM=10,Kmt=[4,6,8],e9=["modern","corporate","creative","minimal","dark"],t9=["business","students","technical","general"],r9=["professional","casual","educational","persuasive"],n9=["16:9","4:3"],Jmt=["pptx"],OM=5,NM=50,LM=10,FM=1e3,o9=3e4}});async function pf(e,t,r){let n="error",o={promptTokens:0,completionTokens:0,inputTokens:0,outputTokens:0,totalTokens:0};if(t){try{t.finishReason!==void 0&&(n=await Promise.resolve(t.finishReason))}catch{}try{t.totalUsage!==void 0&&(o=await Promise.resolve(t.totalUsage))}catch{}}const s=r instanceof Error?r:r!==void 0?new Error(String(r)):e instanceof Error?e:new Error(String(e)),i=s.message,a=s.cause,c=e!==null&&typeof e=="object"?e.cause:void 0,l=a!==void 0?a:c,u=l!==void 0?String(l).slice(0,500):`${s.name}: ${s.message}`.slice(0,500);return{content:"",metadata:{noOutput:!0,errorType:"NoOutputGeneratedError",finishReason:n,usage:o,providerError:i,modelResponseRaw:u}}}async function eRr(e,t){if(e.finishReason===void 0)return null;try{return await Promise.resolve(e.finishReason),null}catch(r){return ru.isInstance(r)?{sentinel:await pf(r,e,t),error:r}:null}}function hf(e){try{const t=ut.getSpan(hr.active());if(!t)return;t.setAttribute("neurolink.no_output",!0),t.setAttribute("langfuse.status_message",tRr(e.metadata.finishReason,e.metadata.usage)),t.setAttribute("neurolink.no_output.finish_reason",String(e.metadata.finishReason))}catch{}}function tRr(e,t){const r=t,n=r?.inputTokens??r?.promptTokens??0,o=r?.outputTokens??r?.completionTokens??0;return`Stream produced no output (NoOutputGeneratedError): finishReason=${String(e)}, inputTokens=${n}, outputTokens=${o}`}var s9=b({"src/lib/utils/noOutputSentinel.ts"(){"use strict";Yt(),Mm()}}),Ymt,rRr=b({"node_modules/.pnpm/nanoid@5.1.16/node_modules/nanoid/url-alphabet/index.js"(){Ymt="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"}});function nRr(e){if(e<0)throw new RangeError("Wrong ID size");try{!ep||ep.length<e?(ep=Buffer.allocUnsafe(e*Xmt),R1.getRandomValues(ep),R0=0):R0+e>ep.length&&(R1.getRandomValues(ep),R0=0)}catch(t){throw ep=void 0,t}R0+=e}function I0(e=21){nRr(e|=0);let t="";for(let r=R0-e;r<R0;r++)t+=Ymt[ep[r]&63];return t}var Xmt,ep,R0,$M=b({"node_modules/.pnpm/nanoid@5.1.16/node_modules/nanoid/index.js"(){Wr(),rRr(),Xmt=128}}),i9,oRr=b({"src/lib/core/modules/StreamHandler.ts"(){"use strict";Yt(),Ja(),z(),Sd(),s9(),Oo(),cb(),$M(),Mm(),i9=class{constructor(e,t){this.providerName=e,this.modelName=t}providerName;modelName;validateStreamOptions(e){const t=$e.stream.startSpan("neurolink.stream.validate",{attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName,"stream.has_max_steps":e.maxSteps!==void 0}});try{const r=KV(e);if(!r.isValid){const n=r_(r);throw t.setAttribute("stream.validation_errors",r.errors?.length??0),new bt(`Stream options validation failed: ${n}`,"options","VALIDATION_FAILED",r.suggestions)}if(r.warnings.length>0&&(p.warn("Stream options validation warnings:",r.warnings),t.addEvent("stream.validation.warnings",{"warning.count":r.warnings.length,warnings:r.warnings.join("; ").substring(0,500)})),e.maxSteps!==void 0&&(e.maxSteps<ks.min||e.maxSteps>ks.max))throw new bt(`maxSteps must be between ${ks.min} and ${ks.max}`,"maxSteps","OUT_OF_RANGE",[`Use a value between ${ks.min} and ${ks.max} for optimal performance`])}catch(r){throw t.recordException(r instanceof Error?r:new Error(String(r))),t.setStatus({code:Fe.ERROR,message:r instanceof Error?r.message:String(r)}),r}finally{t.end()}}createTextStream(e,t){const r=this.providerName;return(async function*(){let n=0,o=0;const s=Date.now();let i;try{for await(const c of e.textStream){if(n++,o+=c.length,!i){i=Date.now();const l=ut.getSpan(hr.active());l&&l.addEvent("stream.first_chunk",{"stream.ttfc_ms":i-s,"stream.provider":r})}yield{content:c}}}catch(c){if(ru.isInstance(c)){p.warn(`${r}: Stream produced no output (NoOutputGeneratedError), returning empty stream`);const l=await pf(c,e,t?.());hf(l),yield l;return}else throw c}if(n===0){const c=await eRr(e,t?.());c&&(p.warn(`${r}: Stream produced no output (NoOutputGeneratedError) \u2014 caught from finishReason rejection`),hf(c.sentinel),yield c.sentinel)}const a=ut.getSpan(hr.active());a&&a.addEvent("stream.complete",{"stream.chunk_count":n,"stream.total_bytes":o,"stream.duration_ms":Date.now()-s,"stream.ttfc_ms":i?i-s:-1})})()}createStreamResult(e,t={}){return{stream:e,provider:this.providerName,model:this.modelName,...t}}async createStreamAnalytics(e,t,r){return dt({name:"neurolink.stream.analytics",tracer:$e.stream,attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName,[be.NL_STREAM_MODE]:!0}},async n=>{try{const o=Date.now()-t;return n.setAttribute("stream.duration_ms",o),u0(this.providerName,this.modelName,e,o,{requestId:`${this.providerName}-stream-${I0()}`,streamingMode:!0,...r.context})}catch(o){p.warn(`Analytics creation failed for ${this.providerName}:`,o);return}})}validateStreamOptionsOnly(e){if(!e.input)throw new bt("Stream options must include input","input","MISSING_REQUIRED",["Provide options.input with text content"]);if(!e.input.text&&!e.input.images?.length)throw new bt("Stream input must include either text or images","input","MISSING_REQUIRED",["Provide options.input.text or options.input.images"])}}}});function sRr(e){return{provider:e.provider,models:Object.keys(e.models||{}),costPerToken:e.defaultCost,requiresApiKey:e.requiredEnvVars,performance:e.performance}}function iRr(){const e={},t=zh.getAllConfigurations();for(const[r,n]of t)e[r]=sRr(n);return e}function aRr(e,t){const r=a9.get(e)||{responseTime:[],successRate:0,tokenThroughput:0,costEfficiency:0,lastUpdated:new Date,sampleCount:0};r.responseTime.push(t.responseTime),r.responseTime.length>50&&r.responseTime.shift();const n=r.sampleCount+1;if(r.successRate=(r.successRate*r.sampleCount+(t.success?1:0))/n,t.responseTime>0){const o=t.tokensGenerated/(t.responseTime/1e3);r.tokenThroughput=(r.tokenThroughput*r.sampleCount+o)/n}if(t.cost>0){const o=t.tokensGenerated/t.cost;r.costEfficiency=(r.costEfficiency*r.sampleCount+o)/n}r.sampleCount=n,r.lastUpdated=new Date,a9.set(e,r)}var a9,cRr,lRr=b({"src/lib/core/evaluationProviders.ts"(){"use strict";qh(),a9=new Map,cRr=iRr()}}),wu,Zmt,Qmt,c9=b({"otel-stub:@opentelemetry/core"(){wu={SUCCESS:0,FAILED:1},Zmt=()=>({}),Qmt=class{inject(){}extract(e){return e}fields(){return[]}}}}),ept,uRr=b({"otel-stub:@opentelemetry/exporter-logs-otlp-http"(){ept=class{export(){}shutdown(){return Promise.resolve()}}}}),tpt,dRr=b({"otel-stub:@opentelemetry/exporter-metrics-otlp-http"(){tpt=class{constructor(){}export(){}shutdown(){return Promise.resolve()}}}}),rpt,npt,opt,mRr=b({"otel-stub:@opentelemetry/sdk-metrics"(){rpt={createCounter(){return{add(){}}},createHistogram(){return{record(){}}},createUpDownCounter(){return{add(){}}},createObservableGauge(){return{addCallback(){}}}},npt=class{constructor(){}getMeter(){return rpt}addMetricReader(){}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},opt=class{constructor(){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}}}),l9,u9,spt=b({"otel-stub:@opentelemetry/sdk-logs"(){l9=class{constructor(){}getLogger(){return{emit(){}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},u9=class{onStart(){}onEnd(){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}}}),d9,ipt,apt,pRr=b({"otel-stub:@opentelemetry/sdk-trace-node"(){d9={setAttribute(){return this},setAttributes(){return this},addEvent(){return this},setStatus(){return this},updateName(){return this},end(){},isRecording(){return!1},recordException(){},spanContext(){return{traceId:"0",spanId:"0",traceFlags:0}}},ipt={startSpan(){return d9},startActiveSpan(e,t,r){return(typeof t=="function"?t:r)(d9)}},apt=class{register(){}addSpanProcessor(){}getTracer(){return ipt}shutdown(){return Promise.resolve()}}}}),hRr,M0,fRr,gRr,yRr,UM,cpt,m9,vRr,TRr,wRr,ERr,n_=b({"node-stub:async_hooks"(){hRr=globalThis.crypto,M0=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},fRr=globalThis.ReadableStream||class{},gRr=globalThis.URL,yRr=globalThis.URLSearchParams,UM=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},UM.custom=Symbol.for("nodejs.util.inspect.custom"),UM.colors={},UM.styles={},cpt=globalThis.TextDecoder,m9=globalThis.TextEncoder,vRr=globalThis.performance||{now:()=>Date.now()},TRr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new m9().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new m9().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new cpt().decode(this)}},wRr=globalThis.clearTimeout,ERr=globalThis.clearInterval}});function BM(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!="object")return"";const r=t.content;return Array.isArray(r)?r.filter(o=>o!==null&&typeof o=="object"&&o.type==="text"&&typeof o.text=="string"&&o.text.length>0).map(o=>o.text).join(" ").substring(0,500):""}function lpt(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}if(!t||typeof t!="object"||t.isError!==!0)return;const r=BM(t);return r?`MCP tool returned isError: ${r}`:"MCP tool returned isError: true"}function zM(e){const t=lpt(e);return t||(e!==null&&typeof e=="object"&&typeof e.error=="string"&&e.error.length>0?e.error:null)}var o_=b({"src/lib/utils/mcpErrorText.ts"(){"use strict"}}),p9={};te(p9,{createContextEnricher:()=>hpt,flushOpenTelemetry:()=>GM,getLangfuseContext:()=>i_,getLangfuseHealthStatus:()=>g9,getLangfuseSpanProcessor:()=>mpt,getLoggerProvider:()=>ARr,getSpanProcessors:()=>fpt,getTracer:()=>jM,getTracerProvider:()=>ppt,initializeOpenTelemetry:()=>qM,isLangfuseInternalSpan:()=>h9,isOpenTelemetryInitialized:()=>s_,isUsingExternalTracerProvider:()=>gpt,langfuseShouldExportSpan:()=>f9,runWithCurrentLangfuseContext:()=>D0,setLangfuseContext:()=>P0,shutdownOpenTelemetry:()=>HM,stampGuestRescueIdentity:()=>y9});function SRr(e,t){return r4({[hH]:t,[fH]:e.release||"v1.0.0","deployment.environment":e.environment||"dev"})}function upt(e,t,r){if(t){try{const n=new tpt({url:`${t}/v1/metrics`}),o=new opt({exporter:n,exportIntervalMillis:15e3,exportTimeoutMillis:1e4});Cd=new npt({resource:e,readers:[o]}),Yp.setGlobalMeterProvider(Cd),p.info(`${Ft} OTLP metric exporter added \u2014 MeterProvider registered globally`,{endpoint:`${t}/v1/metrics`,exportIntervalMs:15e3,serviceName:r,meterProviderType:Cd.constructor.name})}catch(n){p.warn(`${Ft} Failed to create OTLP metric exporter (non-fatal)`,{error:n instanceof Error?n.message:String(n),endpoint:t})}try{const n=new ept({url:`${t}/v1/logs`}),o=new u9(n,{maxQueueSize:2048,maxExportBatchSize:64,scheduledDelayMillis:2e3,exportTimeoutMillis:3e4});tp=new l9({resource:e,processors:[o]}),p.info(`${Ft} OTLP log exporter added \u2014 LoggerProvider created`,{endpoint:`${t}/v1/logs`,serviceName:r})}catch(n){p.warn(`${Ft} Failed to create OTLP log exporter (non-fatal)`,{error:n instanceof Error?n.message:String(n),endpoint:t})}}}function bRr(e){const t=e["ai.toolCall.result"];if(typeof t!="string"||t.length===0)return;let r;try{r=JSON.parse(t)}catch{return}if(!r||typeof r!="object"||r.isError!==!0)return;e["langfuse.level"]="ERROR";const n=BM(r),o=typeof e["ai.toolCall.name"]=="string"?e["ai.toolCall.name"]:"tool";e["langfuse.status_message"]=n||`MCP ${o} returned isError=true`}function _Rr(e){const t=e["ai.finishReason"]??e["gen_ai.response.finish_reasons"],r=Array.isArray(t)?t.join(","):String(t??"");if(r.includes("content-filter")||r==="length"){e["langfuse.level"]="WARNING",e["langfuse.status_message"]=`Generation stopped: finishReason=${r}`;return}if(e["neurolink.no_output"]===!0){e["langfuse.level"]="WARNING",typeof e["langfuse.status_message"]!="string"&&(e["langfuse.status_message"]="Stream produced no output (NoOutputGeneratedError)");return}r==="aborted"&&(e["langfuse.level"]="WARNING",e["langfuse.status_message"]="Generation aborted by client")}async function dpt(e){const t=await Ic("@langfuse/otel","Langfuse observability");return new t.LangfuseSpanProcessor({publicKey:e.publicKey,secretKey:e.secretKey,baseUrl:e.baseUrl||"https://cloud.langfuse.com",environment:e.environment||"dev",release:e.release||"v1.0.0",shouldExportSpan:f9})}function h9(e){return e.attributes?.["langfuse.internal"]===!0}function f9({otelSpan:e}){return!h9(e)}async function CRr(e,t,r,n,o,s){if(o&&!s){if(!r){p.warn(`${Ft} External provider mode requested Langfuse but credentials are missing, and no OTLP endpoint is configured; skipping initialization`,{hasPublicKey:!!e?.publicKey,hasSecretKey:!!e?.secretKey}),Yi=!0,ff=!1;return}p.warn(`${Ft} External provider mode missing Langfuse credentials; continuing with OTLP-only metrics/logs`,{hasPublicKey:!!e?.publicKey,hasSecretKey:!!e?.secretKey,otlpEnabled:!0})}try{Xi=e,ff=s,Fo=o&&s?await dpt(e):null,Eu=!0,Yi=!0,upt(t,r,n);try{const i=ut.getTracerProvider(),a=i;if(i&&typeof a.addSpanProcessor=="function"){a.addSpanProcessor(new a_);const l=(a._registeredSpanProcessors??[]).some(d=>d==null||typeof d!="object"?!1:"langfuseClient"in d?!0:d.constructor?.name==="LangfuseSpanProcessor"),u=e.skipLangfuseSpanProcessor===!0||!Fo||l;l&&!e.skipLangfuseSpanProcessor&&p.info(`${Ft} Auto-detected existing LangfuseSpanProcessor \u2014 skipping SDK registration to avoid duplicates`),!u&&Fo&&a.addSpanProcessor(Fo),p.info(`${Ft} Auto-registered processors with global TracerProvider`,{processors:u?["ContextEnricher"]:["ContextEnricher","LangfuseSpanProcessor"],reason:"External provider mode with auto-registration",skippedLangfuseSpanProcessor:u});return}p.info(`${Ft} Using external TracerProvider mode`,{reason:e.useExternalTracerProvider?"useExternalTracerProvider=true":"autoDetectExternalProvider=true (trusting host signal)",instructions:"Add span processors to your TracerProvider using getSpanProcessors()"}),p.info(`${Ft} Span processors ready for external use`,{processors:Fo?["ContextEnricher","LangfuseSpanProcessor"]:["ContextEnricher"],usage:"import { getSpanProcessors } from '@juspay/neurolink'"})}catch(i){p.warn(`${Ft} Auto-registration failed, manual registration required`,{error:i instanceof Error?i.message:String(i),instructions:"Add span processors to your TracerProvider using getSpanProcessors()"})}}catch(i){p.error(`${Ft} Failed to create span processor for external mode`,{error:i instanceof Error?i.message:String(i),stack:i instanceof Error?i.stack:void 0}),Yi=!0}}async function kRr(e,t,r,n,o,s){if((!o||!s)&&!r){o&&!s?p.warn(`${Ft} Langfuse requested but credentials are missing, and no OTLP endpoint is configured; skipping initialization`,{hasPublicKey:!!e.publicKey,hasSecretKey:!!e.secretKey}):p.debug(`${Ft} Langfuse disabled and OTLP endpoint missing, skipping initialization`),Yi=!0;return}o&&!s&&p.warn(`${Ft} Langfuse requested but credentials are missing; continuing with OTLP-only telemetry`,{hasPublicKey:!!e.publicKey,hasSecretKey:!!e.secretKey,otlpEnabled:!!r});try{Xi=e,ff=s,Fo=o&&s?await dpt(e):null,p.debug(`${Ft} Standalone observability mode`,{langfuseEnabled:!!Fo,otlpEnabled:!!r,baseUrl:e.baseUrl||"https://cloud.langfuse.com",environment:e.environment||"dev"});const i=[new a_];if(Fo&&i.push(Fo),r)try{const a=new mH({url:`${r}/v1/traces`});i.push(new dH(a,{maxQueueSize:2048,maxExportBatchSize:512,scheduledDelayMillis:1e3,exportTimeoutMillis:3e4})),p.info(`${Ft} OTLP trace exporter added`,{endpoint:`${r}/v1/traces`,serviceName:n})}catch(a){p.warn(`${Ft} Failed to create OTLP exporter (non-fatal)`,{error:a instanceof Error?a.message:String(a),endpoint:r})}_d=new apt({resource:t,spanProcessors:i}),_d.register({propagator:new Qmt}),Eu=!1,Yi=!0,upt(t,r,n),p.info(`${Ft} Observability initialized`,{baseUrl:e.baseUrl||"https://cloud.langfuse.com",environment:e.environment||"dev",release:e.release||"v1.0.0",mode:"standalone",langfuseEnabled:!!Fo,otlpEnabled:!!r,serviceName:n})}catch(i){const a=i instanceof Error?i.message:String(i);if(a.includes("duplicate registration")||a.includes("already registered")||a.includes("already set")){p.warn(`${Ft} TracerProvider already registered, switching to external mode`,{error:a,recommendation:"Set useExternalTracerProvider=true or autoDetectExternalProvider=true in config"}),Eu=!0,Yi=!0;return}throw p.error(`${Ft} Initialization failed`,{error:a,stack:i instanceof Error?i.stack:void 0}),i}}async function qM(e){if(Yi){Xi=e,p.debug(`${Ft} Already initialized, config updated`,{usingExternalProvider:Eu,hasLangfuseProcessor:!!Fo,hasTraceNameFormat:typeof e.traceNameFormat=="function"});return}const t=e?.useExternalTracerProvider===!0||e?.autoDetectExternalProvider===!0,r=process.env.OTEL_EXPORTER_OTLP_ENDPOINT,n=e?.enabled===!0,o=!!e.publicKey&&!!e.secretKey,s=process.env.OTEL_SERVICE_NAME||"neurolink",i=SRr(e,s);if(t){await CRr(e,i,r,s,n,o);return}await kRr(e,i,r,s,n,o)}async function GM(){if(!Yi){p.debug(`${Ft} Not initialized, skipping flush`);return}const e=[];if(Fo)try{p.info(`${Ft} Flushing Langfuse spans...`),await Fo.forceFlush()}catch(t){e.push({signal:"langfuse",error:t}),p.error(`${Ft} Langfuse flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} Langfuse disabled, skipping Langfuse flush`);if(_d&&!Eu)try{p.info(`${Ft} Flushing OTLP traces...`),await _d.forceFlush()}catch(t){e.push({signal:"traces",error:t}),p.error(`${Ft} Trace flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} No TracerProvider to flush`);if(Cd)try{p.info(`${Ft} Flushing OTLP metrics...`),await Cd.forceFlush()}catch(t){e.push({signal:"metrics",error:t}),p.error(`${Ft} Metric flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} No MeterProvider to flush`);if(tp)try{p.info(`${Ft} Flushing OTLP logs...`),await tp.forceFlush()}catch(t){e.push({signal:"logs",error:t}),p.error(`${Ft} Log flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} No LoggerProvider to flush`);if(e.length>0)throw new Error(`${Ft} Flush failed for: ${e.map(t=>t.signal).join(", ")}`);p.info(`${Ft} Flush complete`)}async function HM(){if(Yi)try{_d&&!Eu&&await _d.shutdown(),Fo&&await Fo.shutdown(),gf&&await gf.shutdown(),Cd&&await Cd.shutdown(),tp&&await tp.shutdown(),_d=null,Cd=null,tp=null,Fo=null,gf=null,Yi=!1,ff=!1,Eu=!1,p.debug(`${Ft} Shutdown complete`)}catch(e){p.error(`${Ft} Shutdown failed`,{error:e instanceof Error?e.message:String(e)})}}function mpt(){return Fo}function ppt(){return _d}function ARr(){return tp}function s_(){return Yi}function g9(){return{isHealthy:!!(Xi?.enabled&&Yi&&ff&&Fo!==null),initialized:Yi,credentialsValid:ff,enabled:Xi?.enabled||!1,hasProcessor:Fo!==null,usingExternalProvider:Eu,config:Xi?{baseUrl:Xi.baseUrl||"https://cloud.langfuse.com",environment:Xi.environment||"dev",release:Xi.release||"v1.0.0"}:void 0}}async function P0(e,t){const r=bd.getStore()||{},n={userId:e.userId!==void 0?e.userId:r.userId,sessionId:e.sessionId!==void 0?e.sessionId:r.sessionId,conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId,requestId:e.requestId!==void 0?e.requestId:r.requestId,traceName:e.traceName!==void 0?e.traceName:r.traceName,metadata:e.metadata!==void 0?e.metadata:r.metadata,operationName:e.operationName!==void 0?e.operationName:r.operationName,autoDetectOperationName:e.autoDetectOperationName!==void 0?e.autoDetectOperationName:r.autoDetectOperationName,customAttributes:e.customAttributes!==void 0?e.customAttributes:r.customAttributes};if(t)return await bd.run(n,t);bd.enterWith(n)}function i_(){return bd.getStore()}function y9(e,t,r){const n=i_(),o=t,s=typeof o?.userId=="string"&&o.userId?o.userId:void 0,i=typeof o?.sessionId=="string"&&o.sessionId?o.sessionId:void 0;if(r&&!n?.traceName&&!n?.userId){const a=typeof o?.traceName=="string"&&o.traceName?o.traceName:s;a&&(e.setAttribute(To.TRACE_NAME,a),e.setAttribute("trace.name",a))}s&&!n?.userId&&e.setAttribute("user.id",s),i&&!n?.sessionId&&e.setAttribute("session.id",i)}function D0(e){const t=bd.getStore();return t?()=>bd.run(t,e):e}function jM(e="neurolink",t){return ut.getTracer(e,t)}function hpt(){return new a_}function fpt(){return!Yi||!Fo?(p.warn(`${Ft} getSpanProcessors called but not initialized`),[]):(gf||(gf=new a_),[gf,Fo])}function gpt(){return Eu}var Ft,bd,_d,Cd,tp,Fo,Yi,ff,Xi,Eu,gf,a_,rp=b({"src/lib/services/server/ai/observability/instrumentation.ts"(){"use strict";Yt(),c9(),uRr(),dRr(),d$e(),pH(),mRr(),spt(),u$e(),pRr(),m$e(),n_(),o_(),z(),gu(),i4(),Ft="[OpenTelemetry]",bd=new M0,_d=null,Cd=null,tp=null,Fo=null,Yi=!1,ff=!1,Xi=null,Eu=!1,gf=null,a_=class zar{static MAX_DETECTED_OPERATIONS=1e4;detectedOperations=new Map;onStart(t,r){const n=bd.getStore(),o=n?.userId??Xi?.userId??"guest",s=n?.sessionId??Xi?.sessionId,i=t.name,a=this.shouldAutoDetectOperationName(n),c=this.resolveOperationName(n?.operationName,i,a);try{if(c&&i?.startsWith("ai.")){const m=t.spanContext?.()?.traceId;if(m&&!this.detectedOperations.has(m)){if(this.detectedOperations.size>=zar.MAX_DETECTED_OPERATIONS){const h=this.detectedOperations.keys().next().value;h&&this.detectedOperations.delete(h)}this.detectedOperations.set(m,c)}}}catch{}const l=this.buildTraceName(n?.traceName,o,c);if(n?.customAttributes)for(const[m,h]of Object.entries(n.customAttributes))t.setAttribute(m,h);o&&o!=="guest"&&t.setAttribute("user.id",o),s&&t.setAttribute("session.id",s),n?.conversationId&&t.setAttribute("conversation.id",n.conversationId),n?.requestId&&t.setAttribute("request.id",n.requestId);const u=!ut.getSpan(r);l&&u&&(t.setAttribute("langfuse.trace.name",l),t.setAttribute("trace.name",l)),c&&t.setAttribute("gen_ai.operation.name",c);const d=n?.metadata;if(d&&typeof d=="object")for(const[m,h]of Object.entries(d))h!=null&&(typeof h=="string"||typeof h=="number"||typeof h=="boolean"?d&&u&&t.setAttribute("langfuse.trace.metadata",JSON.stringify(d)):Array.isArray(h)&&h.every(f=>typeof f=="string"||typeof f=="number"||typeof f=="boolean")?t.setAttribute(`metadata.${m}`,JSON.stringify(h)):t.setAttribute(`metadata.${m}`,JSON.stringify(h)))}shouldAutoDetectOperationName(t){return t?.autoDetectOperationName!==void 0?t.autoDetectOperationName:Xi?.autoDetectOperationName!==!1}resolveOperationName(t,r,n){if(t)return t;if(n&&r&&(r.startsWith("ai.")||r==="chat"||r==="embeddings"||r==="text_completion"))return r}buildTraceName(t,r,n){if(t)return t;const o=Xi?.traceNameFormat??"userId:operationName";if(typeof o=="function")return o({userId:r,operationName:n});switch(o){case"userId:operationName":return n?`${r}:${n}`:r;case"operationName:userId":return n?`${n}:${r}`:r;case"operationName":return n||r;default:return r}}onEnd(t){try{const r=t.attributes??{};try{const s=t.spanContext?.()?.traceId;if(s){const i=r["langfuse.span.type"]==="trace-root",a=this.detectedOperations.get(s);if(i&&a){const c=bd.getStore(),l=r["user.id"]||c?.userId||Xi?.userId||"guest",u=r["langfuse.trace.name"];if(!(c?.traceName||u&&u!==l)){const m=this.buildTraceName(null,l,a);t.setAttribute("langfuse.trace.name",m),t.setAttribute("trace.name",m),t.setAttribute("gen_ai.operation.name",a),p.debug(`${Ft} Updated trace-root span with detected operation`,{traceId:s,operation:a,newTraceName:m})}this.detectedOperations.delete(s)}}}catch{}if(r["gen_ai.system"]||r["ai.model.id"]||r["gen_ai.request.model"]){const s=r["gen_ai.request.model"]||r["ai.model.id"],i=r["gen_ai.system"]||r["ai.model.provider"];p.debug(`${Ft} GenAI span detected`,{spanName:t.name,model:s,provider:i});try{const a=t.attributes;s&&(a["gen_ai.response.model"]=s);const c=r["gen_ai.usage.input_tokens"]??r["ai.usage.promptTokens"],l=r["gen_ai.usage.output_tokens"]??r["ai.usage.completionTokens"],u=r["gen_ai.usage.total_tokens"]??(c!==void 0&&l!==void 0?c+l:void 0),d=r["gen_ai.usage.reasoning_tokens"]??r["ai.usage.reasoningTokens"],m=r["gen_ai.usage.input_cached_tokens"];if(c!==void 0||l!==void 0){const y={};c!==void 0&&(y.input=c),l!==void 0&&(y.output=l),u!==void 0&&(y.total=u),d!==void 0&&(y.reasoning_tokens=d),m!==void 0&&(y.input_cached_tokens=m),a["langfuse.usage_details"]=JSON.stringify(y),p.debug(`${Ft} Token usage captured`,{inputTokens:c,outputTokens:l,totalTokens:u})}const h=r["gen_ai.request.temperature"]??r["ai.settings.temperature"],f=r["gen_ai.request.max_tokens"]??r["ai.settings.maxTokens"],g=r["gen_ai.request.top_p"]??r["ai.settings.topP"];if(h!==void 0||f!==void 0||g!==void 0){const y={};h!==void 0&&(y.temperature=h),f!==void 0&&(y.max_tokens=f),g!==void 0&&(y.top_p=g),a["gen_ai.request.model_parameters"]=JSON.stringify(y)}}catch{}}const o=t.status;try{const s=t.attributes;t.name==="ai.toolCall"&&o?.code!==Fe.ERROR&&bRr(s),o?.code===Fe.ERROR?(s["langfuse.level"]="ERROR",o.message&&(s["langfuse.status_message"]=o.message)):s["langfuse.level"]===void 0&&_Rr(s)}catch{p.debug(`${Ft} Could not set langfuse.level on span (read-only attributes)`)}}catch(r){p.debug(`${Ft} Error reading span attributes`,{error:r instanceof Error?r.message:String(r)})}}shutdown(){return this.detectedOperations.clear(),Promise.resolve()}forceFlush(){return Promise.resolve()}}}});function ypt(e){const t={...Tpt,...e};return t.relevance=Math.max(0,Math.min(10,t.relevance)),t.accuracy=Math.max(0,Math.min(10,t.accuracy)),t.completeness=Math.max(0,Math.min(10,t.completeness)),t.overall=Math.max(0,Math.min(10,t.overall)),t.domainAlignment!==void 0&&(t.domainAlignment=Math.max(0,Math.min(10,t.domainAlignment))),t.terminologyAccuracy!==void 0&&(t.terminologyAccuracy=Math.max(0,Math.min(10,t.terminologyAccuracy))),t.toolEffectiveness!==void 0&&(t.toolEffectiveness=Math.max(0,Math.min(10,t.toolEffectiveness))),["low","medium","high","none"].includes(t.alertSeverity)||(t.alertSeverity="none"),t.reasoning=vpt(t.reasoning,150),t.suggestedImprovements&&(t.suggestedImprovements=vpt(t.suggestedImprovements,100)),t.evaluationTime=Math.max(0,t.evaluationTime),t.evaluationAttempt!==void 0&&(t.evaluationAttempt=Math.max(0,t.evaluationAttempt)),t.evaluationConfig&&(t.evaluationConfig={mode:t.evaluationConfig.mode||"default",fallbackUsed:!!t.evaluationConfig.fallbackUsed,costEstimate:Math.max(0,t.evaluationConfig.costEstimate||0)}),t}function vpt(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}var Tpt,xRr=b({"src/lib/utils/evaluationUtils.ts"(){"use strict";Tpt={relevance:0,accuracy:0,completeness:0,overall:0,isOffTopic:!1,alertSeverity:"none",reasoning:"",evaluationModel:"unknown",evaluationTime:0,evaluationProvider:"unknown",evaluationAttempt:0,evaluationConfig:{mode:"default",fallbackUsed:!1,costEstimate:0}}}}),wpt={};te(wpt,{evaluateResponse:()=>IRr,generateEvaluation:()=>Spt,getDefaultEvaluation:()=>VM,parseEvaluationResult:()=>Ept});function VM(e,t,r){return p.debug("[getDefaultEvaluation] Creating default evaluation",{reason:e,evaluationTime:t,hasContext:!!r}),{relevance:1,accuracy:1,completeness:1,overall:1,domainAlignment:1,terminologyAccuracy:1,toolEffectiveness:1,isOffTopic:!1,alertSeverity:"low",reasoning:`Default evaluation used due to: ${e}`,contextUtilization:{conversationUsed:!1,toolsUsed:!1,domainKnowledgeUsed:!1},evaluationContext:{domain:r.primaryDomain||"general",toolsEvaluated:[],conversationTurns:0},evaluationModel:"default",evaluationTime:t,evaluationProvider:"default",evaluationAttempt:1,evaluationConfig:{mode:"fallback",fallbackUsed:!0,costEstimate:0}}}function Ept(e,t){const r="parseEvaluationResult";try{p.debug(`[${r}] Parsing evaluation response`,{responseLength:e.length,domain:t.primaryDomain,hasToolUsage:!!t.toolUsage?.length,hasConversationHistory:!!t.conversationHistory?.length});const n=e.match(/\{[^}]*\}/s);if(n)try{return JSON.parse(n[0])}catch(a){p.debug(`[${r}] JSON parsing failed, trying regex`,{error:a instanceof Error?a.message:String(a),jsonContent:n[0].substring(0,100)})}const o={},s={relevance:/relevance[:\s]*([0-9]+(?:\.[0-9]+)?)/i,accuracy:/accuracy[:\s]*([0-9]+(?:\.[0-9]+)?)/i,completeness:/completeness[:\s]*([0-9]+(?:\.[0-9]+)?)/i,overall:/overall[:\s]*([0-9]+(?:\.[0-9]+)?)/i,reasoning:/reasoning[:\s]*(.+?)(?=\n\s*\w+:|\n\s*$|$)/is};for(const[a,c]of Object.entries(s)){const l=e.match(c);if(l)if(a==="reasoning")o.reasoning=l[1].trim();else{const u=parseFloat(l[1]);if(u>=1&&u<=10){const d=Math.round(u);a==="relevance"?o.relevance=d:a==="accuracy"?o.accuracy=d:a==="completeness"?o.completeness=d:a==="overall"&&(o.overall=d)}}}const i={relevance:o.relevance||1,accuracy:o.accuracy||1,completeness:o.completeness||1,overall:o.overall||1,domainAlignment:o.domainAlignment||(t.primaryDomain?5:void 0),terminologyAccuracy:o.terminologyAccuracy||(t.primaryDomain?5:void 0),toolEffectiveness:o.toolEffectiveness||(t.toolUsage?.length?5:void 0)};try{const a=v9.parse(i);let c=o.reasoning||"No detailed reasoning provided";return t.primaryDomain&&(c+=` (Domain: ${t.primaryDomain})`),t.toolUsage?.length&&(c+=` (Tools used: ${t.toolUsage.map(l=>l.toolName).join(", ")})`),t.conversationHistory?.length&&(c+=` (Conversation turns: ${t.conversationHistory.length})`),{...a,reasoning:c}}catch(a){return p.warn(`[${r}] Schema validation failed, using fallback`,{validationError:a,originalData:i}),{relevance:Math.max(1,Math.min(10,o.relevance||1)),accuracy:Math.max(1,Math.min(10,o.accuracy||1)),completeness:Math.max(1,Math.min(10,o.completeness||1)),overall:Math.max(1,Math.min(10,o.overall||1)),reasoning:o.reasoning||"No detailed reasoning provided"}}}catch(n){return p.error(`[${r}] Failed to parse evaluation result`,{error:n}),{relevance:1,accuracy:1,completeness:1,overall:1,reasoning:"Error occurred during evaluation parsing"}}}async function Spt(e){const t="generateEvaluation",r=Date.now();p.debug(`[${t}] Starting evaluation`,{hasUserQuery:!!e.userQuery,hasAiResponse:!!e.aiResponse,domain:e.primaryDomain});try{await Xd.registerAllProviders();const n=process.env.NEUROLINK_EVALUATION_PROVIDER||"google-ai",o=process.env.NEUROLINK_EVALUATION_MODEL||zh.getModelForTier(n,"fast")||"gemini-2.5-flash";p.debug(`[${t}] Using provider: ${n}, model: ${o}`);const s=await Dn.createProvider(n,o);if(!s)return p.debug(`[${t}] No evaluation provider available, returning defaults`),VM("no-provider",Date.now()-r,e);const i=`
|
|
952
|
+
`}var Omt,Nmt,IM,HV,jV,VV,RM=b({"src/lib/utils/messageBuilder.ts"(){"use strict";on(),Ho(),vb(),Yh(),bGe(),OAr(),$b(),Tl(),Oo(),sZe(),lt(),Ja(),s7(),Zh(),tt(),smt(),d7(),umt(),HXe(),rf(),z(),EQe(),Ut(),_tt(),DXe(),is(),Omt=Object.fromEntries(Xh.flatMap(e=>e.extensions.map(t=>[t.slice(1),e.fileType]))),Nmt=Object.fromEntries(Xh.flatMap(e=>e.mimeTypes.map(t=>[t.toLowerCase(),e.fileType]))),IM=new WeakMap,HV=3e4,jV=4,VV=3e4}});function Lmt(e){let t=0;for(const r of e)if(typeof r.content=="string")t+=r.content.length;else if(Array.isArray(r.content))for(const n of r.content)"text"in n&&typeof n.text=="string"&&(t+=n.text.length);return t}function Fmt(e){const t=e.input,r=!!t?.images?.length,n=!!t?.content?.length,o=!!t?.csvFiles?.length,s=!!t?.pdfFiles?.length,i=!!t?.files?.length,a=!!t?.audioFiles?.length,c=!!t?.videoFiles?.length;return{isMultimodal:r||n||o||s||i||a||c,hasImages:r,hasFiles:o||s||i||a||c}}var WV,jIr=b({"src/lib/core/modules/MessageBuilder.ts"(){"use strict";Ja(),z(),RM(),WV=class{constructor(e,t){this.providerName=e,this.modelName=t}providerName;modelName;async buildMessages(e){return dt({name:"neurolink.message.build",tracer:$e.sdk,attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName}},async t=>{const{isMultimodal:r,hasImages:n,hasFiles:o}=Fmt(e);t.setAttribute(be.MSG_IS_MULTIMODAL,r);let s;if(r){process.env.NEUROLINK_DEBUG==="true"&&p.debug("Detected multimodal input, using multimodal message builder");const a=e.input,c={input:{text:e.prompt||e.input?.text||"",images:a?.images,content:a?.content,csvFiles:a?.csvFiles,pdfFiles:a?.pdfFiles,audioFiles:a?.audioFiles,videoFiles:a?.videoFiles,files:a?.files},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,conversationHistory:e.conversationMessages,schema:e.schema,output:e.output,fileRegistry:e.fileRegistry};s=await AM(c,this.providerName,this.modelName),c.systemPrompt&&c.systemPrompt!==e.systemPrompt&&(e.systemPrompt=c.systemPrompt)}else process.env.NEUROLINK_DEBUG==="true"&&p.debug("No multimodal input detected, using standard message builder"),s=await BV(e);const i=s.map(a=>{const c=a.providerOptions;return typeof a.content=="string"?{role:a.role,content:a.content,...c&&{providerOptions:c}}:{role:a.role,content:a.content.map(l=>{const u=l.providerOptions;if(l.type==="text")return{type:"text",text:l.text||"",...u&&{providerOptions:u}};if(l.type==="image"){const d=l.mediaType??l.mimeType;return{type:"image",image:l.image||"",...d&&{mediaType:d},...u&&{providerOptions:u}}}return l}),...c&&{providerOptions:c}}});return t.setAttribute(be.MSG_COUNT,i.length),t.setAttribute(be.MSG_HAS_IMAGES,n),t.setAttribute(be.MSG_HAS_FILES,o),t.setAttribute(be.MSG_HAS_SYSTEM_PROMPT,!!e.systemPrompt),t.setAttribute(be.MSG_TOTAL_CONTENT_LENGTH,Lmt(i)),i})}async buildMessagesForStream(e){return dt({name:"neurolink.message.build_for_stream",tracer:$e.sdk,attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName}},async t=>{const{isMultimodal:r,hasImages:n,hasFiles:o}=Fmt(e);t.setAttribute(be.MSG_IS_MULTIMODAL,r);let s;if(r){process.env.NEUROLINK_DEBUG==="true"&&p.debug(`${this.providerName}: Detected multimodal input, using multimodal message builder`);const a=e.input,c={input:{text:e.prompt||e.input?.text||"",images:a?.images,content:a?.content,csvFiles:a?.csvFiles,pdfFiles:a?.pdfFiles,audioFiles:a?.audioFiles,videoFiles:a?.videoFiles,files:a?.files},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,conversationHistory:e.conversationMessages,schema:e.schema,output:e.output,fileRegistry:e.fileRegistry};s=await AM(c,this.providerName,this.modelName),c.systemPrompt&&c.systemPrompt!==e.systemPrompt&&(e.systemPrompt=c.systemPrompt)}else process.env.NEUROLINK_DEBUG==="true"&&p.debug(`${this.providerName}: No multimodal input detected, using standard message builder`),s=await BV(e);const i=s.map(a=>{const c=a.providerOptions;return typeof a.content=="string"?{role:a.role,content:a.content,...c&&{providerOptions:c}}:{role:a.role,content:a.content.map(l=>{const u=l.providerOptions;if(l.type==="text")return{type:"text",text:l.text||"",...u&&{providerOptions:u}};if(l.type==="image"){const d=l.mediaType??l.mimeType;return{type:"image",image:l.image||"",...d&&{mediaType:d},...u&&{providerOptions:u}}}return l}),...c&&{providerOptions:c}}});return t.setAttribute(be.MSG_COUNT,i.length),t.setAttribute(be.MSG_HAS_IMAGES,n),t.setAttribute(be.MSG_HAS_FILES,o),t.setAttribute(be.MSG_HAS_SYSTEM_PROMPT,!!e.systemPrompt),t.setAttribute(be.MSG_TOTAL_CONTENT_LENGTH,Lmt(i)),i})}}}}),$mt={};te($mt,{DEFAULT_BEFORE_STEP_TIMEOUT_MS:()=>o9,MAX_PPT_PAGES:()=>NM,MAX_PPT_PROMPT_LENGTH:()=>FM,MIN_PPT_PAGES:()=>OM,MIN_PPT_PROMPT_LENGTH:()=>LM,ValidationError:()=>bt,createValidationSummary:()=>r_,hasOnlyWarnings:()=>QIr,validateAsyncFunction:()=>Umt,validateDirectorModeInput:()=>XIr,validateExecutionControl:()=>Gmt,validateGenerateOptions:()=>WIr,validateImageForVideo:()=>YV,validateMCPTool:()=>PM,validateNumberRange:()=>mf,validateObjectStructure:()=>VIr,validatePPTGenerationInput:()=>ZIr,validatePPTOutputOptions:()=>zmt,validatePPTProvider:()=>qmt,validateRequiredString:()=>x0,validateStreamOptions:()=>KV,validateTextGenerationOptions:()=>Bmt,validateToolBatch:()=>JIr,validateToolDescription:()=>MM,validateToolExecutionParams:()=>KIr,validateToolName:()=>t_,validateVideoGenerationInput:()=>YIr,validateVideoOutputOptions:()=>JV});function x0(e,t,r=1){return e==null?new bt(`${t} is required`,t,"REQUIRED_FIELD",[`Provide a valid ${t.toLowerCase()}`]):typeof e!="string"?new bt(`${t} must be a string, received ${typeof e}`,t,"INVALID_TYPE",[`Convert ${t.toLowerCase()} to string format`]):e.trim().length<r?new bt(`${t} must be at least ${r} character${r>1?"s":""} long`,t,"MIN_LENGTH",[`Provide a meaningful ${t.toLowerCase()}`]):null}function mf(e,t,r,n,o=!1){return e==null?o?new bt(`${t} is required`,t,"REQUIRED_FIELD",[`Provide a number between ${r} and ${n}`]):null:typeof e!="number"||isNaN(e)?new bt(`${t} must be a valid number, received ${typeof e}`,t,"INVALID_TYPE",[`Provide a number between ${r} and ${n}`]):e<r||e>n?new bt(`${t} must be between ${r} and ${n}, received ${e}`,t,"OUT_OF_RANGE",[`Use a value between ${r} and ${n}`]):null}function Umt(e,t,r=[]){if(typeof e!="function")return new bt(`${t} must be a function, received ${typeof e}`,t,"INVALID_TYPE",["Provide an async function",`Expected signature: async (${r.join(", ")}) => Promise<unknown>`]);const n=e.toString();return n.includes("async")||n.includes("Promise")?null:new bt(`${t} must be an async function that returns a Promise`,t,"NOT_ASYNC",["Add 'async' keyword to function declaration","Return a Promise from the function",`Example: async (${r.join(", ")}) => { return result; }`])}function VIr(e,t,r,n=[]){if(!Xt(e))return new bt(`${t} must be an object, received ${typeof e}`,t,"INVALID_TYPE",[`Provide an object with properties: ${r.join(", ")}`,...n.length>0?[`Optional properties: ${n.join(", ")}`]:[]]);const o=e,s=r.filter(i=>!(i in o));return s.length>0?new bt(`${t} is missing required properties: ${s.join(", ")}`,t,"MISSING_PROPERTIES",[`Add missing properties: ${s.join(", ")}`]):null}function t_(e){const t=x0(e,"Tool name",1);if(t)return t;const r=e;return/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(r)?r.length>64?new bt(`Tool name too long: ${r.length} characters (max: 64)`,"name","MAX_LENGTH",["Use a shorter, more concise name"]):["execute","validate","setup","init","config"].includes(r.toLowerCase())?new bt(`Tool name '${r}' is reserved`,"name","RESERVED_NAME",["Choose a different name","Add a prefix or suffix to make it unique"]):null:new bt("Tool name must start with a letter and contain only letters, numbers, underscores, and hyphens","name","INVALID_FORMAT",["Use alphanumeric characters, underscores, and hyphens only","Start with a letter","Examples: 'calculateSum', 'data_processor', 'api-client'"])}function MM(e){const t=x0(e,"Tool description",10);if(t)return t;const r=e;return r.length>500?new bt(`Tool description too long: ${r.length} characters (max: 500)`,"description","MAX_LENGTH",["Keep description concise and focused","Use under 500 characters"]):r.split(/\s+/).filter(o=>o.length>2).length<3?new bt("Tool description should be more descriptive","description","TOO_BRIEF",["Explain what the tool does","Include expected parameters","Describe the return value"]):null}function PM(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Tool must be an object","tool","INVALID_TYPE",["Provide a valid tool object with name, description, and execute properties"])),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e,s=t_(o.name);s&&t.push(s);const i=MM(o.description);i&&t.push(i);const a=Umt(o.execute,"execute function",["params","context"]);return a&&t.push(a),o.execute&&typeof o.execute!="function"&&t.push(new bt("Execute must be a function","execute","INVALID_TYPE",["Provide a function for the execute property"])),o.inputSchema&&!Xt(o.inputSchema)&&(r.push("inputSchema should be an object if provided"),n.push("Provide a valid JSON schema or Zod schema for input validation")),o.outputSchema&&!Xt(o.outputSchema)&&(r.push("outputSchema should be an object if provided"),n.push("Provide a valid JSON schema or Zod schema for output validation")),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function Bmt(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Options must be an object","options","INVALID_TYPE")),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e,s=o.output?.mode,i=s==="video"||s==="avatar"||s==="music",a=!!o.stt?.audio;if(!i&&!a){const u=x0(o.prompt,"prompt",1);u&&t.push(u)}o.prompt&&o.prompt.length>Ta.MAX_PROMPT_LENGTH&&t.push(new bt(`Prompt too large: ${o.prompt.length} characters (max: ${Ta.MAX_PROMPT_LENGTH})`,"prompt","MAX_LENGTH",["Break prompt into smaller chunks","Use summarization for long content","Consider using streaming for large inputs"]));const c=mf(o.temperature,"temperature",0,2);c&&t.push(c);const l=mf(o.maxTokens,"maxTokens",1,128e3);return l&&t.push(l),o.timeout!==void 0&&(typeof o.timeout=="string"?/^\d+[smh]?$/.test(o.timeout)||t.push(new bt("Invalid timeout format. Use number (ms) or string like '30s', '2m', '1h'","timeout","INVALID_FORMAT",["Use format: 30000 (ms), '30s', '2m', or '1h'"])):typeof o.timeout=="number"?(o.timeout<1e3||o.timeout>6e5)&&(r.push("Timeout outside recommended range (1s - 10m)"),n.push("Use timeout between 1000ms (1s) and 600000ms (10m)")):t.push(new bt("Timeout must be a number (ms) or string","timeout","INVALID_TYPE"))),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function KV(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Options must be an object","options","INVALID_TYPE")),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e;if(!o.input||!Xt(o.input))t.push(new bt("input is required and must be an object with text property","input","REQUIRED_FIELD",["Provide input: { text: 'your prompt here' }"]));else{const a=x0(o.input.text,"input.text",1);a&&t.push(a)}const s=mf(o.temperature,"temperature",0,2);s&&t.push(s);const i=mf(o.maxTokens,"maxTokens",1,128e3);return i&&t.push(i),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function WIr(e){const t=[],r=[],n=[];if(!Xt(e))return t.push(new bt("Options must be an object","options","INVALID_TYPE")),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e;if(!o.input||!Xt(o.input))t.push(new bt("input is required and must be an object with text property","input","REQUIRED_FIELD",["Provide input: { text: 'your prompt here' }"]));else{const a=x0(o.input.text,"input.text",1);a&&t.push(a)}const s=mf(o.temperature,"temperature",0,2);s&&t.push(s);const i=mf(o.maxTokens,"maxTokens",1,128e3);return i&&t.push(i),o.factoryConfig&&!Xt(o.factoryConfig)&&(r.push("factoryConfig should be an object if provided"),n.push("Provide valid factory configuration or remove the property")),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function KIr(e,t,r){const n=[],o=[],s=[];if(t!=null&&!Xt(t))return n.push(new bt(`Parameters for tool '${e}' must be an object`,"params","INVALID_TYPE",["Provide parameters as an object: { key: value, ... }"])),{isValid:!1,errors:n,warnings:o,suggestions:s};if(r&&t)try{o.push("Schema validation not yet implemented"),s.push("Implement Zod schema validation for tool parameters")}catch(i){n.push(new bt(`Parameter validation failed: ${i instanceof Error?i.message:String(i)}`,"params","SCHEMA_VALIDATION",["Check parameter format against tool schema"]))}return{isValid:n.length===0,errors:n,warnings:o,suggestions:s}}function JIr(e){const t=[],r=[],n={};for(const[o,s]of Object.entries(e)){const i=t_(o),a=PM(s),c={isValid:!i&&a.isValid,errors:i?[i,...a.errors]:a.errors,warnings:a.warnings,suggestions:a.suggestions};n[o]=c,c.isValid?t.push(o):r.push(o)}return{isValid:r.length===0,validTools:t,invalidTools:r,results:n}}function Ji(e){const t=e.field??e.context?.field;return new bt(e.message,t,e.code,e.suggestions)}function JV(e){return e.resolution&&!Hmt.includes(e.resolution)?ue.invalidVideoResolution(e.resolution):e.length!==void 0&&!jmt.includes(e.length)?ue.invalidVideoLength(e.length):e.aspectRatio&&!Vmt.includes(e.aspectRatio)?ue.invalidVideoAspectRatio(e.aspectRatio):e.audio!==void 0&&typeof e.audio!="boolean"?ue.invalidVideoAudio(e.audio):null}function YV(e,t=Wmt){if(e==null)return ue.invalidImageType();if(typeof e=="string")return e.trim().length===0?ue.emptyImagePath():null;if(!Buffer.isBuffer(e))return ue.invalidImageType();if(e.length>t){const i=(e.length/1024/1024).toFixed(2),a=(t/1024/1024).toFixed(0);return ue.imageTooLarge(i,a)}if(e.length<8)return ue.imageTooSmall();const r=e[0]===255&&e[1]===216&&e[2]===255,n=e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71,o=e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80;return r||n||o?null:ue.invalidImageFormat()}function YIr(e){const t=[],r=[],n=[];if(e.output?.mode!=="video"&&t.push(Ji(ue.invalidVideoMode())),!e.input?.images||e.input.images.length===0?t.push(Ji(ue.missingVideoImage())):e.input.images.length>1&&(r.push("Only the first image will be used for video generation. Additional images will be ignored."),n.push("Provide a single image for video generation")),e.input?.images&&e.input.images.length>0){const s=e.input.images[0],i=typeof s=="object"&&"data"in s?s.data:s;if(typeof i!="string"){const a=YV(i);a&&t.push(Ji(a))}}const o=e.input?.text?.trim()||"";if(o.length===0?t.push(Ji(ue.emptyVideoPrompt())):o.length>ZV&&t.push(Ji(ue.videoPromptTooLong(o.length,ZV))),e.output?.video){const s=JV(e.output.video);s&&t.push(Ji(s))}return t.length===0&&r.length===0&&n.push("Video generation takes 60-180 seconds. Consider setting a longer timeout."),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function XIr(e){const t=[],r=[],n=[],o=e.input?.segments;if(!o||!Array.isArray(o))return t.push(new bt("Director Mode requires an input.segments array","input.segments",We.DIRECTOR_SEGMENT_MISMATCH)),{isValid:!1,errors:t,warnings:r,suggestions:n};if(o.length<QV||o.length>DM)return t.push(new bt(`Director Mode requires ${QV}-${DM} segments, got ${o.length}`,"input.segments",o.length>DM?We.DIRECTOR_SEGMENT_LIMIT_EXCEEDED:We.DIRECTOR_SEGMENT_MISMATCH)),{isValid:!1,errors:t,warnings:r,suggestions:n};for(let a=0;a<o.length;a++){const c=o[a];if(!c||typeof c!="object"){t.push(new bt(`Segment ${a} must be an object with prompt and image`,`input.segments[${a}]`,We.DIRECTOR_SEGMENT_MISMATCH));continue}(!c.prompt||typeof c.prompt!="string"||c.prompt.trim().length===0)&&t.push(new bt(`Segment ${a} requires a non-empty prompt`,`input.segments[${a}].prompt`,We.DIRECTOR_SEGMENT_MISMATCH)),(c.image===void 0||c.image===null)&&t.push(new bt(`Segment ${a} requires a valid image (Buffer, URL, path, or ImageWithAltText)`,`input.segments[${a}].image`,We.DIRECTOR_SEGMENT_MISMATCH))}const s=e.output?.director,i=o.length-1;if(s?.transitionPrompts&&s.transitionPrompts.length!==i&&t.push(new bt(`Expected ${i} transition prompts, got ${s.transitionPrompts.length}`,"output.director.transitionPrompts",We.DIRECTOR_SEGMENT_MISMATCH)),s?.transitionDurations)if(s.transitionDurations.length!==i)t.push(new bt(`Expected ${i} transition durations, got ${s.transitionDurations.length}`,"output.director.transitionDurations",We.DIRECTOR_SEGMENT_MISMATCH));else for(let a=0;a<s.transitionDurations.length;a++){const c=s.transitionDurations[a];Kmt.includes(c)||t.push(new bt(`Invalid transition duration at index ${a}: ${c}. Use 4, 6, or 8`,`output.director.transitionDurations[${a}]`,We.DIRECTOR_INVALID_TRANSITION_DURATION))}if(e.output?.video){const a=JV(e.output.video);a&&t.push(Ji(a))}if(t.length===0){const a=o.length+i;n.push(`Director Mode will make ${a} API calls (${o.length} clips + ${i} transitions). Ensure adequate timeout.`)}return{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function zmt(e){if(e.pages===void 0||e.pages===null)return ue.invalidPPTPages(void 0,"pages is required");if(typeof e.pages!="number")return ue.invalidPPTPages(e.pages,"not a number");if(!Number.isInteger(e.pages))return ue.invalidPPTPages(e.pages,"not an integer");if(e.pages<OM||e.pages>NM)return ue.invalidPPTPages(e.pages,`out of range (${OM}-${NM})`);if(e.format!==void 0&&!Jmt.includes(e.format))return ue.invalidPPTFormat(e.format);if(e.theme!==void 0&&!e9.includes(e.theme))return ue.invalidPPTOutputOptions("theme",e.theme,Array.from(e9));if(e.audience!==void 0&&!t9.includes(e.audience))return ue.invalidPPTOutputOptions("audience",e.audience,Array.from(t9));if(e.tone!==void 0&&!r9.includes(e.tone))return ue.invalidPPTOutputOptions("tone",e.tone,Array.from(r9));if(e.aspectRatio!==void 0&&!n9.includes(e.aspectRatio))return ue.invalidPPTOutputOptions("aspectRatio",e.aspectRatio,Array.from(n9));if(e.generateAIImages!==void 0&&typeof e.generateAIImages!="boolean")return ue.invalidPPTOutputOptions("generateAIImages",e.generateAIImages,["true","false"]);if(e.logoPath!==void 0){if(typeof e.logoPath=="string"){if(e.logoPath.trim().length===0)return ue.invalidPPTLogoPath(e.logoPath,"empty string")}else if(!Buffer.isBuffer(e.logoPath))if(typeof e.logoPath=="object"&&"data"in e.logoPath){const t=e.logoPath.data;if(typeof t=="string"){if(t.trim().length===0)return ue.invalidPPTLogoPath(e.logoPath,"empty string")}else if(!Buffer.isBuffer(t))return ue.invalidPPTLogoPath(e.logoPath,"invalid data type")}else return ue.invalidPPTLogoPath(e.logoPath,"invalid type")}if(e.outputPath!==void 0){if(typeof e.outputPath!="string")return ue.invalidPPTOutputPath(e.outputPath,"not a string");if(e.outputPath.trim().length===0)return ue.invalidPPTOutputPath(e.outputPath,"empty string")}return null}function qmt(e){const t=["vertex","openai","azure","anthropic","google-ai","bedrock"],r=String(e).toLowerCase();return t.includes(r)?null:ue.invalidPPTProvider(e)}function ZIr(e){const t=[],r=[],n=[];if(!e.input?.text)return t.push(Ji(ue.invalidPPTPrompt("input.text is required"))),{isValid:!1,errors:t,warnings:r,suggestions:n};const o=e.input.text.trim();if(o===""?t.push(Ji(ue.invalidPPTPrompt("empty prompt"))):o.length<LM?t.push(Ji(ue.invalidPPTPrompt(`prompt too short (${o.length} characters, minimum ${LM} required)`))):o.length>FM&&t.push(Ji(ue.invalidPPTPrompt(`prompt too long (${o.length} characters, max ${FM})`))),e.input.images&&e.input.images.length>0&&(r.push("Images can be unused in PPT generation due to fail in quality standards and can lead to longer generation times."),n.push("Only provide high-quality, relevant images for PPT generation.")),e.provider!==void 0){const s=qmt(e.provider);s&&t.push(Ji(s))}if(e.output?.mode!==void 0&&e.output.mode!=="ppt"&&t.push(Ji(ue.invalidPPTMode())),e.output?.ppt){const s=zmt(e.output.ppt);s&&t.push(Ji(s));const i=e.output.ppt.pages;i!==void 0&&i>30&&r.push(`Generating ${i} slides may take significant time (estimated: ${Math.ceil(i*3)}-${Math.ceil(i*5)} seconds)`),(e.output.ppt.generateAIImages===void 0||e.output.ppt.generateAIImages===!0)&&n.push("AI image generation is enabled. Each slide with images will take additional time (~2-5 seconds per image).");const a=[];e.output.ppt.theme===void 0&&a.push("theme"),e.output.ppt.audience===void 0&&a.push("audience"),e.output.ppt.tone===void 0&&a.push("tone"),a.length>0&&n.push(`AI will decide: ${a.join(", ")} (based on topic analysis)`)}else t.push(Ji(ue.missingPPTProperty("output.ppt",["Provide PPT generation options under output.ppt","pages is required, theme/audience/tone are optional (AI will decide if not specified)"])));return t.length===0&&r.length===0&&n.push("PPT generation typically takes 30-120 seconds depending on slide count and image generation."),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}function r_(e){const t=[];return e.errors.length>0&&t.push(`Errors: ${e.errors.map(r=>r.message).join("; ")}`),e.warnings.length>0&&t.push(`Warnings: ${e.warnings.join("; ")}`),e.suggestions.length>0&&t.push(`Suggestions: ${e.suggestions.join("; ")}`),t.join(" | ")}function QIr(e){return e.errors.length===0&&e.warnings.length>0}function XV(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Gmt(e,t,r,n={}){const{turnTimeoutMs:o,toolTimeoutMs:s}=n;if(e==null)return;if(!Xt(e))throw new bt("executionControl must be an object","executionControl","INVALID_TYPE");if(!r)throw new bt(`executionControl is not supported by provider "${t}" \u2014 it is implemented only on the native Anthropic stream path. Remove it, or route this turn to anthropic.`,"executionControl","UNSUPPORTED_PROVIDER",["Use provider: 'anthropic' for turns that need executionControl","Use turnTimeoutMs / maxSteps for other providers"]);const i=e;if(!XV(i.requestTimeoutMs))throw new bt(`executionControl.requestTimeoutMs is required and must be a finite positive number of milliseconds (received ${String(i.requestTimeoutMs)}). It is the deadline that bounds a stalled upstream even when the turn has no lifetime ceiling, so there is no valid turn without it.`,"executionControl.requestTimeoutMs","INVALID_VALUE");if(i.lifetimeTimeoutMs!==void 0&&i.lifetimeTimeoutMs!==null&&!XV(i.lifetimeTimeoutMs))throw new bt(`executionControl.lifetimeTimeoutMs must be null (no lifetime ceiling), a finite positive number of milliseconds, or absent (inherit the legacy timeout handling). Received ${String(i.lifetimeTimeoutMs)}.`,"executionControl.lifetimeTimeoutMs","INVALID_VALUE");if(i.lifetimeTimeoutMs!==void 0&&typeof o=="number"&&Number.isFinite(o)&&o>0)throw new bt(`turnTimeoutMs (${o}) cannot be combined with executionControl.lifetimeTimeoutMs (${String(i.lifetimeTimeoutMs)}): both set the turn's wall-clock ceiling, and executionControl wins, so the turnTimeoutMs would be ignored. Set exactly one of them.`,"executionControl.lifetimeTimeoutMs","INVALID_VALUE",["Drop turnTimeoutMs and express the ceiling as executionControl.lifetimeTimeoutMs","Or drop executionControl.lifetimeTimeoutMs to inherit turnTimeoutMs unchanged"]);if(i.lifetimeTimeoutMs===null&&s===null)throw new bt("executionControl.lifetimeTimeoutMs: null removes the turn's wall-clock ceiling, which leaves toolTimeoutMs as the only bound on a tool that never returns \u2014 and toolTimeoutMs: null removes that one too, so the turn would have no bound anywhere. Keep one of them.","executionControl.lifetimeTimeoutMs","INVALID_VALUE",["Give toolTimeoutMs a finite bound, or omit it to take the 300000ms default","Or give executionControl.lifetimeTimeoutMs a finite ceiling instead of null"]);if(i.beforeStep!==void 0&&typeof i.beforeStep!="function")throw new bt("executionControl.beforeStep must be a function","executionControl.beforeStep","INVALID_TYPE");if(i.beforeStepTimeoutMs!==void 0&&!XV(i.beforeStepTimeoutMs))throw new bt(`executionControl.beforeStepTimeoutMs must be a finite positive number of milliseconds when supplied. Received ${String(i.beforeStepTimeoutMs)}.`,"executionControl.beforeStepTimeoutMs","INVALID_VALUE")}var bt,Hmt,jmt,Vmt,ZV,Wmt,QV,DM,Kmt,e9,t9,r9,n9,Jmt,OM,NM,LM,FM,o9,Sd=b({"src/lib/utils/parameterValidation.ts"(){"use strict";Ju(),Oo(),tt(),Eh(),bt=class extends Error{constructor(e,t,r,n){super(e),this.field=t,this.code=r,this.suggestions=n,this.name="ValidationError"}field;code;suggestions},Hmt=["720p","1080p"],jmt=[4,5,6,8,10],Vmt=["9:16","16:9"],ZV=500,Wmt=10*1024*1024,QV=2,DM=10,Kmt=[4,6,8],e9=["modern","corporate","creative","minimal","dark"],t9=["business","students","technical","general"],r9=["professional","casual","educational","persuasive"],n9=["16:9","4:3"],Jmt=["pptx"],OM=5,NM=50,LM=10,FM=1e3,o9=3e4}});async function pf(e,t,r){let n="error",o={promptTokens:0,completionTokens:0,inputTokens:0,outputTokens:0,totalTokens:0};if(t){try{t.finishReason!==void 0&&(n=await Promise.resolve(t.finishReason))}catch{}try{t.totalUsage!==void 0&&(o=await Promise.resolve(t.totalUsage))}catch{}}const s=r instanceof Error?r:r!==void 0?new Error(String(r)):e instanceof Error?e:new Error(String(e)),i=s.message,a=s.cause,c=e!==null&&typeof e=="object"?e.cause:void 0,l=a!==void 0?a:c,u=l!==void 0?String(l).slice(0,500):`${s.name}: ${s.message}`.slice(0,500);return{content:"",metadata:{noOutput:!0,errorType:"NoOutputGeneratedError",finishReason:n,usage:o,providerError:i,modelResponseRaw:u}}}async function eRr(e,t){if(e.finishReason===void 0)return null;try{return await Promise.resolve(e.finishReason),null}catch(r){return ru.isInstance(r)?{sentinel:await pf(r,e,t),error:r}:null}}function hf(e){try{const t=ut.getSpan(hr.active());if(!t)return;t.setAttribute("neurolink.no_output",!0),t.setAttribute("langfuse.status_message",tRr(e.metadata.finishReason,e.metadata.usage)),t.setAttribute("neurolink.no_output.finish_reason",String(e.metadata.finishReason))}catch{}}function tRr(e,t){const r=t,n=r?.inputTokens??r?.promptTokens??0,o=r?.outputTokens??r?.completionTokens??0;return`Stream produced no output (NoOutputGeneratedError): finishReason=${String(e)}, inputTokens=${n}, outputTokens=${o}`}var s9=b({"src/lib/utils/noOutputSentinel.ts"(){"use strict";Yt(),Mm()}}),Ymt,rRr=b({"node_modules/.pnpm/nanoid@5.1.16/node_modules/nanoid/url-alphabet/index.js"(){Ymt="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"}});function nRr(e){if(e<0)throw new RangeError("Wrong ID size");try{!ep||ep.length<e?(ep=Buffer.allocUnsafe(e*Xmt),R1.getRandomValues(ep),R0=0):R0+e>ep.length&&(R1.getRandomValues(ep),R0=0)}catch(t){throw ep=void 0,t}R0+=e}function I0(e=21){nRr(e|=0);let t="";for(let r=R0-e;r<R0;r++)t+=Ymt[ep[r]&63];return t}var Xmt,ep,R0,$M=b({"node_modules/.pnpm/nanoid@5.1.16/node_modules/nanoid/index.js"(){Wr(),rRr(),Xmt=128}}),i9,oRr=b({"src/lib/core/modules/StreamHandler.ts"(){"use strict";Yt(),Ja(),z(),Sd(),s9(),Oo(),cb(),$M(),Mm(),i9=class{constructor(e,t){this.providerName=e,this.modelName=t}providerName;modelName;validateStreamOptions(e){const t=$e.stream.startSpan("neurolink.stream.validate",{attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName,"stream.has_max_steps":e.maxSteps!==void 0}});try{const r=KV(e);if(!r.isValid){const n=r_(r);throw t.setAttribute("stream.validation_errors",r.errors?.length??0),new bt(`Stream options validation failed: ${n}`,"options","VALIDATION_FAILED",r.suggestions)}if(r.warnings.length>0&&(p.warn("Stream options validation warnings:",r.warnings),t.addEvent("stream.validation.warnings",{"warning.count":r.warnings.length,warnings:r.warnings.join("; ").substring(0,500)})),e.maxSteps!==void 0&&(e.maxSteps<ks.min||e.maxSteps>ks.max))throw new bt(`maxSteps must be between ${ks.min} and ${ks.max}`,"maxSteps","OUT_OF_RANGE",[`Use a value between ${ks.min} and ${ks.max} for optimal performance`])}catch(r){throw t.recordException(r instanceof Error?r:new Error(String(r))),t.setStatus({code:Fe.ERROR,message:r instanceof Error?r.message:String(r)}),r}finally{t.end()}}createTextStream(e,t){const r=this.providerName;return(async function*(){let n=0,o=0;const s=Date.now();let i;try{for await(const c of e.textStream){if(n++,o+=c.length,!i){i=Date.now();const l=ut.getSpan(hr.active());l&&l.addEvent("stream.first_chunk",{"stream.ttfc_ms":i-s,"stream.provider":r})}yield{content:c}}}catch(c){if(ru.isInstance(c)){p.warn(`${r}: Stream produced no output (NoOutputGeneratedError), returning empty stream`);const l=await pf(c,e,t?.());hf(l),yield l;return}else throw c}if(n===0){const c=await eRr(e,t?.());c&&(p.warn(`${r}: Stream produced no output (NoOutputGeneratedError) \u2014 caught from finishReason rejection`),hf(c.sentinel),yield c.sentinel)}const a=ut.getSpan(hr.active());a&&a.addEvent("stream.complete",{"stream.chunk_count":n,"stream.total_bytes":o,"stream.duration_ms":Date.now()-s,"stream.ttfc_ms":i?i-s:-1})})()}createStreamResult(e,t={}){return{stream:e,provider:this.providerName,model:this.modelName,...t}}async createStreamAnalytics(e,t,r){return dt({name:"neurolink.stream.analytics",tracer:$e.stream,attributes:{[be.NL_PROVIDER]:this.providerName,[be.NL_MODEL]:this.modelName,[be.NL_STREAM_MODE]:!0}},async n=>{try{const o=Date.now()-t;return n.setAttribute("stream.duration_ms",o),u0(this.providerName,this.modelName,e,o,{requestId:`${this.providerName}-stream-${I0()}`,streamingMode:!0,...r.context})}catch(o){p.warn(`Analytics creation failed for ${this.providerName}:`,o);return}})}validateStreamOptionsOnly(e){if(!e.input)throw new bt("Stream options must include input","input","MISSING_REQUIRED",["Provide options.input with text content"]);if(!e.input.text&&!e.input.images?.length)throw new bt("Stream input must include either text or images","input","MISSING_REQUIRED",["Provide options.input.text or options.input.images"])}}}});function sRr(e){return{provider:e.provider,models:Object.keys(e.models||{}),costPerToken:e.defaultCost,requiresApiKey:e.requiredEnvVars,performance:e.performance}}function iRr(){const e={},t=zh.getAllConfigurations();for(const[r,n]of t)e[r]=sRr(n);return e}function aRr(e,t){const r=a9.get(e)||{responseTime:[],successRate:0,tokenThroughput:0,costEfficiency:0,lastUpdated:new Date,sampleCount:0};r.responseTime.push(t.responseTime),r.responseTime.length>50&&r.responseTime.shift();const n=r.sampleCount+1;if(r.successRate=(r.successRate*r.sampleCount+(t.success?1:0))/n,t.responseTime>0){const o=t.tokensGenerated/(t.responseTime/1e3);r.tokenThroughput=(r.tokenThroughput*r.sampleCount+o)/n}if(t.cost>0){const o=t.tokensGenerated/t.cost;r.costEfficiency=(r.costEfficiency*r.sampleCount+o)/n}r.sampleCount=n,r.lastUpdated=new Date,a9.set(e,r)}var a9,cRr,lRr=b({"src/lib/core/evaluationProviders.ts"(){"use strict";qh(),a9=new Map,cRr=iRr()}}),wu,Zmt,Qmt,c9=b({"otel-stub:@opentelemetry/core"(){wu={SUCCESS:0,FAILED:1},Zmt=()=>({}),Qmt=class{inject(){}extract(e){return e}fields(){return[]}}}}),ept,uRr=b({"otel-stub:@opentelemetry/exporter-logs-otlp-http"(){ept=class{export(){}shutdown(){return Promise.resolve()}}}}),tpt,dRr=b({"otel-stub:@opentelemetry/exporter-metrics-otlp-http"(){tpt=class{constructor(){}export(){}shutdown(){return Promise.resolve()}}}}),rpt,npt,opt,mRr=b({"otel-stub:@opentelemetry/sdk-metrics"(){rpt={createCounter(){return{add(){}}},createHistogram(){return{record(){}}},createUpDownCounter(){return{add(){}}},createObservableGauge(){return{addCallback(){}}}},npt=class{constructor(){}getMeter(){return rpt}addMetricReader(){}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},opt=class{constructor(){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}}}),l9,u9,spt=b({"otel-stub:@opentelemetry/sdk-logs"(){l9=class{constructor(){}getLogger(){return{emit(){}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},u9=class{onStart(){}onEnd(){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}}}),d9,ipt,apt,pRr=b({"otel-stub:@opentelemetry/sdk-trace-node"(){d9={setAttribute(){return this},setAttributes(){return this},addEvent(){return this},setStatus(){return this},updateName(){return this},end(){},isRecording(){return!1},recordException(){},spanContext(){return{traceId:"0",spanId:"0",traceFlags:0}}},ipt={startSpan(){return d9},startActiveSpan(e,t,r){return(typeof t=="function"?t:r)(d9)}},apt=class{register(){}addSpanProcessor(){}getTracer(){return ipt}shutdown(){return Promise.resolve()}}}}),hRr,M0,fRr,gRr,yRr,UM,cpt,m9,vRr,TRr,wRr,ERr,n_=b({"node-stub:async_hooks"(){hRr=globalThis.crypto,M0=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},fRr=globalThis.ReadableStream||class{},gRr=globalThis.URL,yRr=globalThis.URLSearchParams,UM=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},UM.custom=Symbol.for("nodejs.util.inspect.custom"),UM.colors={},UM.styles={},cpt=globalThis.TextDecoder,m9=globalThis.TextEncoder,vRr=globalThis.performance||{now:()=>Date.now()},TRr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new m9().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new m9().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new cpt().decode(this)}},wRr=globalThis.clearTimeout,ERr=globalThis.clearInterval}});function BM(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!="object")return"";const r=t.content;return Array.isArray(r)?r.filter(o=>o!==null&&typeof o=="object"&&o.type==="text"&&typeof o.text=="string"&&o.text.length>0).map(o=>o.text).join(" ").substring(0,500):""}function lpt(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}if(!t||typeof t!="object"||t.isError!==!0)return;const r=BM(t);return r?`MCP tool returned isError: ${r}`:"MCP tool returned isError: true"}function zM(e){const t=lpt(e);return t||(e!==null&&typeof e=="object"&&typeof e.error=="string"&&e.error.length>0?e.error:null)}var o_=b({"src/lib/utils/mcpErrorText.ts"(){"use strict"}}),p9={};te(p9,{createContextEnricher:()=>hpt,flushOpenTelemetry:()=>GM,getLangfuseContext:()=>i_,getLangfuseHealthStatus:()=>g9,getLangfuseSpanProcessor:()=>mpt,getLoggerProvider:()=>ARr,getSpanProcessors:()=>fpt,getTracer:()=>jM,getTracerProvider:()=>ppt,initializeOpenTelemetry:()=>qM,isLangfuseInternalSpan:()=>h9,isOpenTelemetryInitialized:()=>s_,isUsingExternalTracerProvider:()=>gpt,langfuseShouldExportSpan:()=>f9,runWithCurrentLangfuseContext:()=>D0,setLangfuseContext:()=>P0,shutdownOpenTelemetry:()=>HM,stampGuestRescueIdentity:()=>y9});function SRr(e,t){return r4({[hH]:t,[fH]:e.release||"v1.0.0","deployment.environment":e.environment||"dev"})}function upt(e,t,r){if(t){try{const n=new tpt({url:`${t}/v1/metrics`}),o=new opt({exporter:n,exportIntervalMillis:15e3,exportTimeoutMillis:1e4});Cd=new npt({resource:e,readers:[o]}),Yp.setGlobalMeterProvider(Cd),p.info(`${Ft} OTLP metric exporter added \u2014 MeterProvider registered globally`,{endpoint:`${t}/v1/metrics`,exportIntervalMs:15e3,serviceName:r,meterProviderType:Cd.constructor.name})}catch(n){p.warn(`${Ft} Failed to create OTLP metric exporter (non-fatal)`,{error:n instanceof Error?n.message:String(n),endpoint:t})}try{const n=new ept({url:`${t}/v1/logs`}),o=new u9(n,{maxQueueSize:2048,maxExportBatchSize:64,scheduledDelayMillis:2e3,exportTimeoutMillis:3e4});tp=new l9({resource:e,processors:[o]}),p.info(`${Ft} OTLP log exporter added \u2014 LoggerProvider created`,{endpoint:`${t}/v1/logs`,serviceName:r})}catch(n){p.warn(`${Ft} Failed to create OTLP log exporter (non-fatal)`,{error:n instanceof Error?n.message:String(n),endpoint:t})}}}function bRr(e){const t=e["ai.toolCall.result"];if(typeof t!="string"||t.length===0)return;let r;try{r=JSON.parse(t)}catch{return}if(!r||typeof r!="object"||r.isError!==!0)return;e["langfuse.level"]="ERROR";const n=BM(r),o=typeof e["ai.toolCall.name"]=="string"?e["ai.toolCall.name"]:"tool";e["langfuse.status_message"]=n||`MCP ${o} returned isError=true`}function _Rr(e){const t=e["ai.finishReason"]??e["gen_ai.response.finish_reasons"],r=Array.isArray(t)?t.join(","):String(t??"");if(r.includes("content-filter")||r==="length"){e["langfuse.level"]="WARNING",e["langfuse.status_message"]=`Generation stopped: finishReason=${r}`;return}if(e["neurolink.no_output"]===!0){e["langfuse.level"]="WARNING",typeof e["langfuse.status_message"]!="string"&&(e["langfuse.status_message"]="Stream produced no output (NoOutputGeneratedError)");return}r==="aborted"&&(e["langfuse.level"]="WARNING",e["langfuse.status_message"]="Generation aborted by client")}async function dpt(e){const t=await Ic("@langfuse/otel","Langfuse observability");return new t.LangfuseSpanProcessor({publicKey:e.publicKey,secretKey:e.secretKey,baseUrl:e.baseUrl||"https://cloud.langfuse.com",environment:e.environment||"dev",release:e.release||"v1.0.0",shouldExportSpan:f9})}function h9(e){return e.attributes?.["langfuse.internal"]===!0}function f9({otelSpan:e}){return!h9(e)}async function CRr(e,t,r,n,o,s){if(o&&!s){if(!r){p.warn(`${Ft} External provider mode requested Langfuse but credentials are missing, and no OTLP endpoint is configured; skipping initialization`,{hasPublicKey:!!e?.publicKey,hasSecretKey:!!e?.secretKey}),Yi=!0,ff=!1;return}p.warn(`${Ft} External provider mode missing Langfuse credentials; continuing with OTLP-only metrics/logs`,{hasPublicKey:!!e?.publicKey,hasSecretKey:!!e?.secretKey,otlpEnabled:!0})}try{Xi=e,ff=s,Fo=o&&s?await dpt(e):null,Eu=!0,Yi=!0,upt(t,r,n);try{const i=ut.getTracerProvider(),a=i;if(i&&typeof a.addSpanProcessor=="function"){a.addSpanProcessor(new a_);const l=(a._registeredSpanProcessors??[]).some(d=>d==null||typeof d!="object"?!1:"langfuseClient"in d?!0:d.constructor?.name==="LangfuseSpanProcessor"),u=e.skipLangfuseSpanProcessor===!0||!Fo||l;l&&!e.skipLangfuseSpanProcessor&&p.info(`${Ft} Auto-detected existing LangfuseSpanProcessor \u2014 skipping SDK registration to avoid duplicates`),!u&&Fo&&a.addSpanProcessor(Fo),p.info(`${Ft} Auto-registered processors with global TracerProvider`,{processors:u?["ContextEnricher"]:["ContextEnricher","LangfuseSpanProcessor"],reason:"External provider mode with auto-registration",skippedLangfuseSpanProcessor:u});return}p.info(`${Ft} Using external TracerProvider mode`,{reason:e.useExternalTracerProvider?"useExternalTracerProvider=true":"autoDetectExternalProvider=true (trusting host signal)",instructions:"Add span processors to your TracerProvider using getSpanProcessors()"}),p.info(`${Ft} Span processors ready for external use`,{processors:Fo?["ContextEnricher","LangfuseSpanProcessor"]:["ContextEnricher"],usage:"import { getSpanProcessors } from '@juspay/neurolink'"})}catch(i){p.warn(`${Ft} Auto-registration failed, manual registration required`,{error:i instanceof Error?i.message:String(i),instructions:"Add span processors to your TracerProvider using getSpanProcessors()"})}}catch(i){p.error(`${Ft} Failed to create span processor for external mode`,{error:i instanceof Error?i.message:String(i),stack:i instanceof Error?i.stack:void 0}),Yi=!0}}async function kRr(e,t,r,n,o,s){if((!o||!s)&&!r){o&&!s?p.warn(`${Ft} Langfuse requested but credentials are missing, and no OTLP endpoint is configured; skipping initialization`,{hasPublicKey:!!e.publicKey,hasSecretKey:!!e.secretKey}):p.debug(`${Ft} Langfuse disabled and OTLP endpoint missing, skipping initialization`),Yi=!0;return}o&&!s&&p.warn(`${Ft} Langfuse requested but credentials are missing; continuing with OTLP-only telemetry`,{hasPublicKey:!!e.publicKey,hasSecretKey:!!e.secretKey,otlpEnabled:!!r});try{Xi=e,ff=s,Fo=o&&s?await dpt(e):null,p.debug(`${Ft} Standalone observability mode`,{langfuseEnabled:!!Fo,otlpEnabled:!!r,baseUrl:e.baseUrl||"https://cloud.langfuse.com",environment:e.environment||"dev"});const i=[new a_];if(Fo&&i.push(Fo),r)try{const a=new mH({url:`${r}/v1/traces`});i.push(new dH(a,{maxQueueSize:2048,maxExportBatchSize:512,scheduledDelayMillis:1e3,exportTimeoutMillis:3e4})),p.info(`${Ft} OTLP trace exporter added`,{endpoint:`${r}/v1/traces`,serviceName:n})}catch(a){p.warn(`${Ft} Failed to create OTLP exporter (non-fatal)`,{error:a instanceof Error?a.message:String(a),endpoint:r})}_d=new apt({resource:t,spanProcessors:i}),_d.register({propagator:new Qmt}),Eu=!1,Yi=!0,upt(t,r,n),p.info(`${Ft} Observability initialized`,{baseUrl:e.baseUrl||"https://cloud.langfuse.com",environment:e.environment||"dev",release:e.release||"v1.0.0",mode:"standalone",langfuseEnabled:!!Fo,otlpEnabled:!!r,serviceName:n})}catch(i){const a=i instanceof Error?i.message:String(i);if(a.includes("duplicate registration")||a.includes("already registered")||a.includes("already set")){p.warn(`${Ft} TracerProvider already registered, switching to external mode`,{error:a,recommendation:"Set useExternalTracerProvider=true or autoDetectExternalProvider=true in config"}),Eu=!0,Yi=!0;return}throw p.error(`${Ft} Initialization failed`,{error:a,stack:i instanceof Error?i.stack:void 0}),i}}async function qM(e){if(Yi){Xi=e,p.debug(`${Ft} Already initialized, config updated`,{usingExternalProvider:Eu,hasLangfuseProcessor:!!Fo,hasTraceNameFormat:typeof e.traceNameFormat=="function"});return}const t=e?.useExternalTracerProvider===!0||e?.autoDetectExternalProvider===!0,r=process.env.OTEL_EXPORTER_OTLP_ENDPOINT,n=e?.enabled===!0,o=!!e.publicKey&&!!e.secretKey,s=process.env.OTEL_SERVICE_NAME||"neurolink",i=SRr(e,s);if(t){await CRr(e,i,r,s,n,o);return}await kRr(e,i,r,s,n,o)}async function GM(){if(!Yi){p.debug(`${Ft} Not initialized, skipping flush`);return}const e=[];if(Fo)try{p.info(`${Ft} Flushing Langfuse spans...`),await Fo.forceFlush()}catch(t){e.push({signal:"langfuse",error:t}),p.error(`${Ft} Langfuse flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} Langfuse disabled, skipping Langfuse flush`);if(_d&&!Eu)try{p.info(`${Ft} Flushing OTLP traces...`),await _d.forceFlush()}catch(t){e.push({signal:"traces",error:t}),p.error(`${Ft} Trace flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} No TracerProvider to flush`);if(Cd)try{p.info(`${Ft} Flushing OTLP metrics...`),await Cd.forceFlush()}catch(t){e.push({signal:"metrics",error:t}),p.error(`${Ft} Metric flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} No MeterProvider to flush`);if(tp)try{p.info(`${Ft} Flushing OTLP logs...`),await tp.forceFlush()}catch(t){e.push({signal:"logs",error:t}),p.error(`${Ft} Log flush failed`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}else p.debug(`${Ft} No LoggerProvider to flush`);if(e.length>0)throw new Error(`${Ft} Flush failed for: ${e.map(t=>t.signal).join(", ")}`);p.info(`${Ft} Flush complete`)}async function HM(){if(Yi)try{_d&&!Eu&&await _d.shutdown(),Fo&&await Fo.shutdown(),gf&&await gf.shutdown(),Cd&&await Cd.shutdown(),tp&&await tp.shutdown(),_d=null,Cd=null,tp=null,Fo=null,gf=null,Yi=!1,ff=!1,Eu=!1,p.debug(`${Ft} Shutdown complete`)}catch(e){p.error(`${Ft} Shutdown failed`,{error:e instanceof Error?e.message:String(e)})}}function mpt(){return Fo}function ppt(){return _d}function ARr(){return tp}function s_(){return Yi}function g9(){return{isHealthy:!!(Xi?.enabled&&Yi&&ff&&Fo!==null),initialized:Yi,credentialsValid:ff,enabled:Xi?.enabled||!1,hasProcessor:Fo!==null,usingExternalProvider:Eu,config:Xi?{baseUrl:Xi.baseUrl||"https://cloud.langfuse.com",environment:Xi.environment||"dev",release:Xi.release||"v1.0.0"}:void 0}}async function P0(e,t){const r=bd.getStore()||{},n={userId:e.userId!==void 0?e.userId:r.userId,sessionId:e.sessionId!==void 0?e.sessionId:r.sessionId,conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId,requestId:e.requestId!==void 0?e.requestId:r.requestId,traceName:e.traceName!==void 0?e.traceName:r.traceName,metadata:e.metadata!==void 0?e.metadata:r.metadata,operationName:e.operationName!==void 0?e.operationName:r.operationName,autoDetectOperationName:e.autoDetectOperationName!==void 0?e.autoDetectOperationName:r.autoDetectOperationName,customAttributes:e.customAttributes!==void 0?e.customAttributes:r.customAttributes};if(t)return await bd.run(n,t);bd.enterWith(n)}function i_(){return bd.getStore()}function y9(e,t,r){const n=i_(),o=t,s=typeof o?.userId=="string"&&o.userId?o.userId:void 0,i=typeof o?.sessionId=="string"&&o.sessionId?o.sessionId:void 0;if(r&&!n?.traceName&&!n?.userId){const a=typeof o?.traceName=="string"&&o.traceName?o.traceName:s;a&&(e.setAttribute(To.TRACE_NAME,a),e.setAttribute("trace.name",a))}s&&!n?.userId&&e.setAttribute("user.id",s),i&&!n?.sessionId&&e.setAttribute("session.id",i)}function D0(e){const t=bd.getStore();return t?()=>bd.run(t,e):e}function jM(e="neurolink",t){return ut.getTracer(e,t)}function hpt(){return new a_}function fpt(){return!Yi||!Fo?(p.warn(`${Ft} getSpanProcessors called but not initialized`),[]):(gf||(gf=new a_),[gf,Fo])}function gpt(){return Eu}var Ft,bd,_d,Cd,tp,Fo,Yi,ff,Xi,Eu,gf,a_,rp=b({"src/lib/services/server/ai/observability/instrumentation.ts"(){"use strict";Yt(),c9(),uRr(),dRr(),d$e(),pH(),mRr(),spt(),u$e(),pRr(),m$e(),n_(),o_(),z(),gu(),i4(),Ft="[OpenTelemetry]",bd=new M0,_d=null,Cd=null,tp=null,Fo=null,Yi=!1,ff=!1,Xi=null,Eu=!1,gf=null,a_=class zar{static MAX_DETECTED_OPERATIONS=1e4;detectedOperations=new Map;onStart(t,r){const n=bd.getStore(),o=n?.userId??Xi?.userId??"guest",s=n?.sessionId??Xi?.sessionId,i=t.name,a=this.shouldAutoDetectOperationName(n),c=this.resolveOperationName(n?.operationName,i,a);try{if(c&&i?.startsWith("ai.")){const m=t.spanContext?.()?.traceId;if(m&&!this.detectedOperations.has(m)){if(this.detectedOperations.size>=zar.MAX_DETECTED_OPERATIONS){const h=this.detectedOperations.keys().next().value;h&&this.detectedOperations.delete(h)}this.detectedOperations.set(m,c)}}}catch{}const l=this.buildTraceName(n?.traceName,o,c);if(n?.customAttributes)for(const[m,h]of Object.entries(n.customAttributes))t.setAttribute(m,h);o&&o!=="guest"&&t.setAttribute("user.id",o),s&&t.setAttribute("session.id",s),n?.conversationId&&t.setAttribute("conversation.id",n.conversationId),n?.requestId&&t.setAttribute("request.id",n.requestId);const u=!ut.getSpan(r);l&&u&&(t.setAttribute("langfuse.trace.name",l),t.setAttribute("trace.name",l)),c&&t.setAttribute("gen_ai.operation.name",c);const d=n?.metadata;if(d&&typeof d=="object")for(const[m,h]of Object.entries(d))h!=null&&(typeof h=="string"||typeof h=="number"||typeof h=="boolean"?d&&u&&t.setAttribute("langfuse.trace.metadata",JSON.stringify(d)):Array.isArray(h)&&h.every(f=>typeof f=="string"||typeof f=="number"||typeof f=="boolean")?t.setAttribute(`metadata.${m}`,JSON.stringify(h)):t.setAttribute(`metadata.${m}`,JSON.stringify(h)))}shouldAutoDetectOperationName(t){return t?.autoDetectOperationName!==void 0?t.autoDetectOperationName:Xi?.autoDetectOperationName!==!1}resolveOperationName(t,r,n){if(t)return t;if(n&&r&&(r.startsWith("ai.")||r==="chat"||r==="embeddings"||r==="text_completion"))return r}buildTraceName(t,r,n){if(t)return t;const o=Xi?.traceNameFormat??"userId:operationName";if(typeof o=="function")return o({userId:r,operationName:n});switch(o){case"userId:operationName":return n?`${r}:${n}`:r;case"operationName:userId":return n?`${n}:${r}`:r;case"operationName":return n||r;default:return r}}onEnd(t){try{const r=t.attributes??{};try{const s=t.spanContext?.()?.traceId;if(s){const i=r["langfuse.span.type"]==="trace-root",a=this.detectedOperations.get(s);if(i&&a){const c=bd.getStore(),l=r["user.id"]||c?.userId||Xi?.userId||"guest",u=r["langfuse.trace.name"];if(!(c?.traceName||u&&u!==l)){const m=this.buildTraceName(null,l,a);t.setAttribute("langfuse.trace.name",m),t.setAttribute("trace.name",m),t.setAttribute("gen_ai.operation.name",a),p.debug(`${Ft} Updated trace-root span with detected operation`,{traceId:s,operation:a,newTraceName:m})}this.detectedOperations.delete(s)}}}catch{}if(r["gen_ai.system"]||r["ai.model.id"]||r["gen_ai.request.model"]){const s=r["gen_ai.request.model"]||r["ai.model.id"],i=r["gen_ai.system"]||r["ai.model.provider"];p.debug(`${Ft} GenAI span detected`,{spanName:t.name,model:s,provider:i});try{const a=t.attributes;s&&(a["gen_ai.response.model"]=s);const c=r["gen_ai.usage.input_tokens"]??r["ai.usage.promptTokens"],l=r["gen_ai.usage.output_tokens"]??r["ai.usage.completionTokens"],u=r["gen_ai.usage.total_tokens"]??(c!==void 0&&l!==void 0?c+l:void 0),d=r["gen_ai.usage.reasoning_tokens"]??r["ai.usage.reasoningTokens"],m=r["gen_ai.usage.input_cached_tokens"];if(c!==void 0||l!==void 0){const y={};c!==void 0&&(y.input=c),l!==void 0&&(y.output=l),u!==void 0&&(y.total=u),d!==void 0&&(y.reasoning_tokens=d),m!==void 0&&(y.input_cached_tokens=m),a["langfuse.usage_details"]=JSON.stringify(y),p.debug(`${Ft} Token usage captured`,{inputTokens:c,outputTokens:l,totalTokens:u})}const h=r["gen_ai.request.temperature"]??r["ai.settings.temperature"],f=r["gen_ai.request.max_tokens"]??r["ai.settings.maxTokens"],g=r["gen_ai.request.top_p"]??r["ai.settings.topP"];if(h!==void 0||f!==void 0||g!==void 0){const y={};h!==void 0&&(y.temperature=h),f!==void 0&&(y.max_tokens=f),g!==void 0&&(y.top_p=g),a["gen_ai.request.model_parameters"]=JSON.stringify(y)}}catch{}}const o=t.status;try{const s=t.attributes;t.name==="ai.toolCall"&&o?.code!==Fe.ERROR&&bRr(s),o?.code===Fe.ERROR?(s["langfuse.level"]="ERROR",o.message&&(s["langfuse.status_message"]=o.message)):s["langfuse.level"]===void 0&&_Rr(s)}catch{p.debug(`${Ft} Could not set langfuse.level on span (read-only attributes)`)}}catch(r){p.debug(`${Ft} Error reading span attributes`,{error:r instanceof Error?r.message:String(r)})}}shutdown(){return this.detectedOperations.clear(),Promise.resolve()}forceFlush(){return Promise.resolve()}}}});function ypt(e){const t={...Tpt,...e};return t.relevance=Math.max(0,Math.min(10,t.relevance)),t.accuracy=Math.max(0,Math.min(10,t.accuracy)),t.completeness=Math.max(0,Math.min(10,t.completeness)),t.overall=Math.max(0,Math.min(10,t.overall)),t.domainAlignment!==void 0&&(t.domainAlignment=Math.max(0,Math.min(10,t.domainAlignment))),t.terminologyAccuracy!==void 0&&(t.terminologyAccuracy=Math.max(0,Math.min(10,t.terminologyAccuracy))),t.toolEffectiveness!==void 0&&(t.toolEffectiveness=Math.max(0,Math.min(10,t.toolEffectiveness))),["low","medium","high","none"].includes(t.alertSeverity)||(t.alertSeverity="none"),t.reasoning=vpt(t.reasoning,150),t.suggestedImprovements&&(t.suggestedImprovements=vpt(t.suggestedImprovements,100)),t.evaluationTime=Math.max(0,t.evaluationTime),t.evaluationAttempt!==void 0&&(t.evaluationAttempt=Math.max(0,t.evaluationAttempt)),t.evaluationConfig&&(t.evaluationConfig={mode:t.evaluationConfig.mode||"default",fallbackUsed:!!t.evaluationConfig.fallbackUsed,costEstimate:Math.max(0,t.evaluationConfig.costEstimate||0)}),t}function vpt(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}var Tpt,xRr=b({"src/lib/utils/evaluationUtils.ts"(){"use strict";Tpt={relevance:0,accuracy:0,completeness:0,overall:0,isOffTopic:!1,alertSeverity:"none",reasoning:"",evaluationModel:"unknown",evaluationTime:0,evaluationProvider:"unknown",evaluationAttempt:0,evaluationConfig:{mode:"default",fallbackUsed:!1,costEstimate:0}}}}),wpt={};te(wpt,{evaluateResponse:()=>IRr,generateEvaluation:()=>Spt,getDefaultEvaluation:()=>VM,parseEvaluationResult:()=>Ept});function VM(e,t,r){return p.debug("[getDefaultEvaluation] Creating default evaluation",{reason:e,evaluationTime:t,hasContext:!!r}),{relevance:1,accuracy:1,completeness:1,overall:1,domainAlignment:1,terminologyAccuracy:1,toolEffectiveness:1,isOffTopic:!1,alertSeverity:"low",reasoning:`Default evaluation used due to: ${e}`,contextUtilization:{conversationUsed:!1,toolsUsed:!1,domainKnowledgeUsed:!1},evaluationContext:{domain:r.primaryDomain||"general",toolsEvaluated:[],conversationTurns:0},evaluationModel:"default",evaluationTime:t,evaluationProvider:"default",evaluationAttempt:1,evaluationConfig:{mode:"fallback",fallbackUsed:!0,costEstimate:0}}}function Ept(e,t){const r="parseEvaluationResult";try{p.debug(`[${r}] Parsing evaluation response`,{responseLength:e.length,domain:t.primaryDomain,hasToolUsage:!!t.toolUsage?.length,hasConversationHistory:!!t.conversationHistory?.length});const n=e.match(/\{[^}]*\}/s);if(n)try{return JSON.parse(n[0])}catch(a){p.debug(`[${r}] JSON parsing failed, trying regex`,{error:a instanceof Error?a.message:String(a),jsonContent:n[0].substring(0,100)})}const o={},s={relevance:/relevance[:\s]*([0-9]+(?:\.[0-9]+)?)/i,accuracy:/accuracy[:\s]*([0-9]+(?:\.[0-9]+)?)/i,completeness:/completeness[:\s]*([0-9]+(?:\.[0-9]+)?)/i,overall:/overall[:\s]*([0-9]+(?:\.[0-9]+)?)/i,reasoning:/reasoning[:\s]*(.+?)(?=\n\s*\w+:|\n\s*$|$)/is};for(const[a,c]of Object.entries(s)){const l=e.match(c);if(l)if(a==="reasoning")o.reasoning=l[1].trim();else{const u=parseFloat(l[1]);if(u>=1&&u<=10){const d=Math.round(u);a==="relevance"?o.relevance=d:a==="accuracy"?o.accuracy=d:a==="completeness"?o.completeness=d:a==="overall"&&(o.overall=d)}}}const i={relevance:o.relevance||1,accuracy:o.accuracy||1,completeness:o.completeness||1,overall:o.overall||1,domainAlignment:o.domainAlignment||(t.primaryDomain?5:void 0),terminologyAccuracy:o.terminologyAccuracy||(t.primaryDomain?5:void 0),toolEffectiveness:o.toolEffectiveness||(t.toolUsage?.length?5:void 0)};try{const a=v9.parse(i);let c=o.reasoning||"No detailed reasoning provided";return t.primaryDomain&&(c+=` (Domain: ${t.primaryDomain})`),t.toolUsage?.length&&(c+=` (Tools used: ${t.toolUsage.map(l=>l.toolName).join(", ")})`),t.conversationHistory?.length&&(c+=` (Conversation turns: ${t.conversationHistory.length})`),{...a,reasoning:c}}catch(a){return p.warn(`[${r}] Schema validation failed, using fallback`,{validationError:a,originalData:i}),{relevance:Math.max(1,Math.min(10,o.relevance||1)),accuracy:Math.max(1,Math.min(10,o.accuracy||1)),completeness:Math.max(1,Math.min(10,o.completeness||1)),overall:Math.max(1,Math.min(10,o.overall||1)),reasoning:o.reasoning||"No detailed reasoning provided"}}}catch(n){return p.error(`[${r}] Failed to parse evaluation result`,{error:n}),{relevance:1,accuracy:1,completeness:1,overall:1,reasoning:"Error occurred during evaluation parsing"}}}async function Spt(e){const t="generateEvaluation",r=Date.now();p.debug(`[${t}] Starting evaluation`,{hasUserQuery:!!e.userQuery,hasAiResponse:!!e.aiResponse,domain:e.primaryDomain});try{await Xd.registerAllProviders();const n=process.env.NEUROLINK_EVALUATION_PROVIDER||"google-ai",o=process.env.NEUROLINK_EVALUATION_MODEL||zh.getModelForTier(n,"fast")||"gemini-2.5-flash";p.debug(`[${t}] Using provider: ${n}, model: ${o}`);const s=await Dn.createProvider(n,o);if(!s)return p.debug(`[${t}] No evaluation provider available, returning defaults`),VM("no-provider",Date.now()-r,e);const i=`
|
|
953
953
|
Evaluate this AI response on a scale of 1-10 for each criterion:
|
|
954
954
|
|
|
955
955
|
User Query: ${e.userQuery}
|
|
@@ -1007,7 +1007,7 @@ ${k}`,l++}else Sgt(v,w,_)?u=v.slice(v.charCodeAt(w+6)===cp?w+7:w+6,S)||void 0:h(
|
|
|
1007
1007
|
`,w);let C=-1;if(S!==-1&&_!==-1?C=S<_?S:_:S!==-1?S===v.length-1?C=-1:C=S:_!==-1&&(C=_),C===-1)break;h(v,w,C),w=C+1,v.charCodeAt(w-1)===bgt&&v.charCodeAt(w)===mW&&w++}return v.slice(w)}function h(v,w,S){if(w===S){g();return}const _=v.charCodeAt(w);if(Egt(v,w,_)){const M=v.charCodeAt(w+5)===cp?w+6:w+5,O=v.slice(M,S);c=l===0?O:`${c}
|
|
1008
1008
|
${O}`,l++;return}if(Sgt(v,w,_)){u=v.slice(v.charCodeAt(w+6)===cp?w+7:w+6,S)||void 0;return}if(_===105&&v.charCodeAt(w+1)===100&&v.charCodeAt(w+2)===58){const M=v.slice(v.charCodeAt(w+3)===cp?w+4:w+3,S);a=M.includes("\0")?void 0:M;return}if(_===58){if(o){const M=v.slice(w,S);o(M.slice(v.charCodeAt(w+1)===cp?2:1))}return}const C=v.slice(w,S),k=C.indexOf(":");if(k===-1){f(C,"",C);return}const x=C.slice(0,k),R=C.charCodeAt(k+1)===cp?2:1,I=C.slice(k+R);f(x,I,C)}function f(v,w,S){switch(v){case"event":u=w||void 0;break;case"data":c=l===0?w:`${c}
|
|
1009
1009
|
${w}`,l++;break;case"id":a=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new dW(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:S}));break;default:r(new dW(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:w,line:S}));break}}function g(){l>0&&t({id:a,event:u,data:c}),a=void 0,c="",l=0,u=void 0}function y(v={}){if(v.consume&&s.length>0){const w=s.join("");h(w,0,w.length)}i=!0,a=void 0,c="",l=0,u=void 0,s.length=0}return{feed:d,reset:y}}function Egt(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Sgt(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var dW,mW,bgt,cp,pW=b({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js"(){dW=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},mW=10,bgt=13,cp=32}}),_gt={};te(_gt,{createAnnotatedTool:()=>kgt,filterToolsByAnnotations:()=>Igt,getAnnotationSummary:()=>Rgt,getToolSafetyLevel:()=>xgt,inferAnnotations:()=>Id,isSafeToRetry:()=>fW,mergeAnnotations:()=>hW,requiresConfirmation:()=>Agt,validateAnnotations:()=>Cgt});function Id(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(l,u)=>new RegExp(`\\b${u}\\b`,"i").test(l)?!0:l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(m=>m===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(l=>o(r,l)||o(t,l))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(l=>o(r,l)||o(t,l))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(l=>o(r,l)||o(t,l))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(l=>o(r,l)||o(t,l))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function hW(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Cgt(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function kgt(e){const t=Id(e),r=hW(t,e.annotations);return{...e,annotations:r}}function Agt(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function fW(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function xgt(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function Igt(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function Rgt(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var p_=b({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),gW={};te(gW,{TOOL_COMPATIBILITY:()=>wW,batchConvertToMCP:()=>Dgt,batchConvertToNeuroLink:()=>Ogt,createToolFromFunction:()=>Ngt,mcpProtocolToolToServerTool:()=>Mgt,mcpToolToNeuroLink:()=>vW,neuroLinkToolToMCP:()=>yW,sanitizeToolName:()=>TW,serverToolToMCPProtocol:()=>Pgt,validateToolName:()=>Lgt});function yW(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=t,i=s?`${s}_${e.name}`:e.name,a=r?Id({name:e.name,description:e.description}):{},c={...n,...a};e.tags?.length&&(c.tags=[...new Set([...c.tags??[],...e.tags])]);const l=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:i,description:e.description,inputSchema:l,annotations:c,execute:e.execute,metadata:u}}function vW(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Mgt(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,s=e.annotations??{},i=n?Id({name:e.name,description:e.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function Pgt(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Dgt(e,t={}){return e.map(r=>yW(r,t))}function Ogt(e,t={}){return e.map(r=>vW(r,t))}function Ngt(e,t,r,n){const o=Id({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await _t(r(s,i),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function Lgt(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function TW(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var wW,bP=b({"src/lib/mcp/toolConverter.ts"(){"use strict";p_(),Lr(),wW={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}});function _4r(e){const t=e?.error?.message;if(typeof t=="string"&&t.trim().length>0)return t;if(Array.isArray(t)){const r=t.map(n=>n.msg?.trim()).filter(n=>n!==void 0&&n.length>0);if(r.length>0)return r.join("; ")}return typeof e?.detail=="string"&&e.detail.trim().length>0?e.detail:void 0}var Ca,EW,_P,SW,El,h_,bW,_W,Fgt,CW,kW,$gt,Ugt,AW,xW,Bgt,zgt,j0,Af,qgt,Ggt,Hgt,IW,jgt,RW,MW,f_,PW,Vgt,lp=b({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";pW(),bP(),qm(),di(),is(),Ca=e=>e.replace(/\/+$/,""),EW=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,_P=(e,t)=>{if(e.every(o=>EW.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let s=EW.test(o)?o:TW(o);if(n.has(s)||t?.has(s)){let i=2,a;do{const c=`_${i}`;a=`${s.slice(0,64-c.length)}${c}`,i++}while(n.has(a)||t?.has(a));s=a}r.set(o,s),n.set(s,o)}return{toWire:r,fromWire:n}},SW=(e,t,r)=>{let n=0;for(const o of e){const s=typeof o.content=="string"?o.content:El(o.content);n+=nr(s,r)+wl;const i=o.tool_calls;i&&(n+=nr(El(i),r))}return t&&t.length>0&&(n+=nr(El(t),r)),n},El=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},h_=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},bW=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:El(t.value);case"json":return El(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:El(t.value);case"error-json":return El(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
|
|
1010
|
-
`):"";default:return El(e)}},_W=(e,t)=>{const r=t&&t.includes("/")?t:"image/png";if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:${r};base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:${r};base64,${Buffer.from(e).toString("base64")}`},Fgt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return El(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=_W(o);s&&t.push({type:"image_url",image_url:{url:s}})}else if(n.type==="file"){const o=r;if(o.mediaType?.startsWith("image/")){const s=_W(o.data,o.mediaType);s&&t.push({type:"image_url",image_url:{url:s}})}}}return t.length===1&&t[0].type==="text"?t[0].text:t},CW=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:El(n.content)});break;case"user":r.push({role:"user",content:Fgt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const c of o)if(c&&typeof c=="object"){const l=c;if(l.type==="text")s.push({type:"text",text:c.text??""});else if(l.type==="tool-call"){const u=c,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:h_(u.input)}})}}else typeof c=="string"&&s.push({type:"text",text:c});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:bW(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},kW=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,c=a?lUe(No(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:c}})}return n},$gt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:lUe(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},Ugt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},AW=["properties","patternProperties","$defs","definitions"],xW=["items","prefixItems","anyOf","oneOf","allOf","not","then","else"],Bgt=["allOf","not","if","then","else"],zgt=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([r,n])=>[r,t(n)])),j0=e=>{if(Array.isArray(e))return e.map(j0);if(!e||typeof e!="object")return e;const t={...e};for(const r of AW)r in t&&(t[r]=zgt(t[r],j0));for(const r of xW)r in t&&(t[r]=j0(t[r]));return t.additionalProperties&&typeof t.additionalProperties=="object"?t.additionalProperties=j0(t.additionalProperties):t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1),t},Af=e=>{if(Array.isArray(e))return e.every(Af);if(!e||typeof e!="object")return!0;const t=e;if(Bgt.some(o=>o in t))return!1;if(t.type==="object"){if(t.additionalProperties!==!1)return!1;const o=Object.keys(t.properties??{}),s=Array.isArray(t.required)?t.required:[];if(o.some(i=>!s.includes(i)))return!1}const r=AW.filter(o=>o in t).every(o=>Object.values(t[o]??{}).every(Af)),n=xW.filter(o=>o in t).every(o=>Af(t[o]));return r&&n},qgt=e=>{if(e.type==="text")return{type:"text"};if(!e.schema)return{type:"json_object"};const t=e.schema,r=j0(t),n=Af(t)?t:Af(r)?r:t;return{type:"json_schema",json_schema:{name:e.name??"response",schema:n,...e.description?{description:e.description}:{},strict:Af(n)}}},Ggt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},Hgt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),IW=e=>e.response_format?.type==="json_object"&&!Hgt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,jgt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),RW=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,c={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(c.max_tokens=n.maxTokens);const l=hu("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return l.temperature!==void 0&&(c.temperature=l.temperature),l.topP!==void 0&&(c.top_p=l.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(c.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(c.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(c.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(c.stop=n.stopSequences),o&&(c.tools=o),s!==void 0&&o&&o.length>0&&(c.tool_choice=s),a&&(c.response_format=a),n.extraBody&&Object.assign(c,n.extraBody),c},MW=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=uW({onEvent:l=>{const u=l.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(g){s=g instanceof Error?g:new Error(String(g));return}d.usage&&(n.usage=d.usage),d.id&&!n.id&&(n.id=d.id),d.model&&!n.model&&(n.model=d.model);const m=d.choices?.[0];if(!m)return;const h=m.delta;h?.content&&(n.text+=h.content,t(h.content));const f=h?.reasoning_content||h?.reasoning;if(f&&(n.reasoning+=f,r?.(f)),h?.tool_calls)for(const g of h.tool_calls){let y=n.toolCalls.get(g.index);y?g.id&&(y.id=g.id):(y={id:g.id??`call_${g.index}_${Date.now()}`,name:g.function?.name??"",argsBuffered:""},n.toolCalls.set(g.index,y)),g.function?.name&&(y.name=g.function.name),g.function?.arguments&&(y.argsBuffered+=g.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),c=e.getReader();try{for(;;){const{done:l,value:u}=await c.read();if(l)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{c.releaseLock()}if(s)throw s;return n},f_=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=_4r(o)??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const c=a.toLowerCase();return c==="retry-after"||c.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},PW=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},Vgt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function CP(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function C4r(e,t){let r=CP(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=CP(e.tool_calls)),nr(r,t)+wl}function k4r(e,t){if(e.role!=="tool")return;const r=CP(e.content),n={maxBytes:DW,maxLines:OW};if(!bpt(r,n))return;const{preview:o}=Qa(r,n);return nr(o,t)+wl}function A4r(e,t){return e.map(r=>{const n=C4r(r,t);if(r.role==="tool"){const o=k4r(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function x4r(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,c=A4r(t,o),l=n+c.reduce((g,y)=>g+y.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=vP(c,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(l);return}const m=new Set(d.truncate),h=new Set(d.drop),f=[];for(let g=0;g<t.length;g++){if(h.has(g))continue;const y=t[g];if(m.has(g)&&y.role==="tool"){const{preview:v}=Qa(CP(y.content),{maxBytes:DW,maxLines:OW});f.push({...y,content:v});continue}f.push(y)}if(h.size>0){let g=f.findIndex(y=>y.role==="tool"||y.role==="assistant"&&y.tool_calls);g<0&&(g=Math.min(1,f.length)),f.splice(g,0,{role:"user",content:Wgt})}return p.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:f.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),f}var DW,OW,Wgt,I4r=b({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";is(),yf(),TP(),z(),DW=2048,OW=60,Wgt="[Earlier tool exchanges were removed to fit the context window.]"}});function R4r(e){let t,r;const n=o=>nr(LW(o),e.provider)+wl;return{observeUsage(o){const s=g_(o)?o.inputTokens:void 0,i=g_(s)?s.total:s;r=typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0},guardConversation(o){const s=o.findIndex(S=>S.role==="user"),i=Math.max(1,s+1),a=o.slice(i),c=a.map(Kgt),l=[{kind:"other",tokens:o.slice(0,i).reduce((S,_)=>S+n(_),0)},...a.map((S,_)=>{const C=NW(S.content);return S.role==="assistant"&&C.some(k=>k.type==="tool-call")?{kind:"toolCall",tokens:n(S)}:S.role==="tool"&&C.some(k=>k.type==="tool-result")?{kind:"toolResult",tokens:n(S),previewTokens:n(c[_])}:{kind:"other",tokens:n(S)}})],u=e.getFixedOverheadTokens(),d=r&&t?Math.min(3,Math.max(1,r/t)):1,m=vP(l,{availableInputTokens:e.availableInputTokens,fixedOverheadTokens:u,calibration:d}),h=Math.floor(e.availableInputTokens*e4/(d>0?d:1)),f=u+l.reduce((S,_)=>S+_.tokens,0);if(!m.fire){t=f,f>h?p.warn("[NativeGenerateGuard] Over threshold, nothing reclaimable",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,overThresholdByTokens:f-h,calibration:d}):p.debug("[NativeGenerateGuard] Under threshold",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,headroomToThresholdTokens:h-f,calibration:d});return}const g=new Set(m.drop),y=new Set(m.truncate),v=[...o.slice(0,i)];let w=!1;return a.forEach((S,_)=>{const C=_+1;g.has(C)?(w||v.push({role:"user",content:"[Earlier tool exchanges were removed to fit the context window.]"}),w=!0):v.push(y.has(C)?c[_]:S)}),t=u+v.reduce((S,_)=>S+n(_),0),p.info("[NativeGenerateGuard] Reclaimed context",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedBeforeTokens:f,estimatedAfterTokens:t,truncated:m.truncate.length,dropped:m.drop.length,calibration:d}),v}}}var g_,NW,LW,Kgt,M4r=b({"src/lib/context/nativeGenerateGuard.ts"(){"use strict";is(),z(),TP(),Oo(),yf(),g_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),NW=e=>Array.isArray(e)?e.filter(g_):[],LW=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}},Kgt=e=>({...e,content:NW(e.content).map(t=>{if(t.type!=="tool-result")return t;const r=t.output,n=g_(r)&&["text","json","error-text","error-json"].includes(String(r.type))&&"value"in r,{preview:o,truncated:s}=Qa(LW(n?r.value:r),{maxBytes:2048,maxLines:60});return s?{...t,output:n?{...r,type:String(r.type).startsWith("error")?"error-text":"text",value:o}:o}:t})})}});function FW(e){const t=UW(e);return t?BW.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function P4r(e){const t=UW(e);if(!t)return null;for(const{provider:r,patterns:n}of BW)if(n.some(o=>o.test(t)))return r;return null}function $W(e){const t=UW(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function UW(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var BW,Jgt=b({"src/lib/context/errorDetection.ts"(){"use strict";BW=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),ka,Ygt=b({"src/lib/context/errors.ts"(){"use strict";ka=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),Xgt,zW,Zgt=b({"src/lib/core/streamAnalytics.ts"(){"use strict";cb(),z(),l4(),Mm(),Xgt=class{async collectUsage(e){try{const t=await e.usage;return t?c4(t):(p.debug("No usage data available from stream result"),Q$e())}catch(t){return ru.isInstance(t)?p.debug("No output generated from stream \u2014 returning empty usage"):p.warn("Failed to collect usage from stream result",{error:t}),Q$e()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return ru.isInstance(t)?p.debug("No output generated from stream \u2014 returning default metadata"):p.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,c,l,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return u0(e,t,{usage:s,content:a,response:i,finishReason:c,toolResults:l,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:c})}catch(s){return p.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),u0(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},zW=new Xgt}});function Qgt(e,t){if(!(!e||!t||t.length===0))for(const r of t){const n=r.output??r.result,o=!!r.error||n!=null&&typeof n=="object"&&"isError"in n&&n.isError===!0;let s;if(o){if(r.error)s=r.error;else if(n&&typeof n=="object"){const i=n.content;if(Array.isArray(i)){const a=i.filter(c=>c.type==="text"&&c.text).map(c=>c.text);s=a.length>0?a.join(" "):"Tool returned isError: true"}else s="Tool returned isError: true"}}e.emit("tool:end",O0(r.toolName,{responseTime:0,success:!o,timestamp:Date.now(),result:n,error:s}))}}var eyt=b({"src/lib/utils/toolEndEmitter.ts"(){"use strict";w9()}});async function qW(e,t){const r=[];let n="",o="",s="stop",i,a=0,c=0,l=0,u=0,d=0,m=!1,h=!1,f;const g=!!(e.tools&&e.tools.length>0);for(let y=0;y<e.maxSteps;y++){d=y+1;const v=e.guardConversation?.(e.conversation);v&&e.conversation.splice(0,e.conversation.length,...v);const w=()=>e.runStep(()=>e.doGenerate({prompt:e.conversation,...e.tools&&e.tools.length>0?{tools:e.tools}:{},...m?{toolChoice:{type:"none"}}:e.toolChoice!==void 0?{toolChoice:e.toolChoice}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.maxOutputTokens?{maxOutputTokens:e.maxOutputTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{}}));let S;try{S=await w()}catch(M){if(h&&f){p.warn("toolChoice: none re-ask failed; returning the original result",{error:M instanceof Error?M.message:String(M)}),n=f.text,s=f.finishReason,i=f.rawFinishReason;break}throw M}h=!1,e.observeUsage?.(S.usage);const _=tyt(S.content);n=_.filter(M=>M.type==="text"&&typeof M.text=="string").map(M=>M.text).join(""),o+=_.filter(M=>M.type==="reasoning"&&typeof M.text=="string").map(M=>M.text).join("");const C=S.finishReason;if(typeof C=="string")s=C;else if(typeof C=="object"&&C!==null){const M=C;s=M.unified??s,i=M.raw??i}const k=S.usage;a+=GW(k?.inputTokens),c+=GW(k?.outputTokens);const x=k?.inputTokens;l+=x?.cacheRead??0,u+=x?.cacheWrite??0;const R=_.filter(M=>M.type==="tool-call");if(R.length===0){if(s==="tool-calls"&&n.trim()===""&&g&&!m&&y+1<e.maxSteps){m=!0,h=!0,f={text:n,finishReason:s,rawFinishReason:i},e.conversation.push({role:"assistant",content:_});continue}break}e.conversation.push({role:"assistant",content:_});const I=[];for(const M of R){const O=String(M.toolName??""),U=String(M.toolCallId??""),P=new Date,D=ryt(M.input),F=D.input,$=e.toolsRecord[O];let q,j;const V=D.error??(typeof $?.execute=="function"?nyt($,F):void 0);if(typeof $?.execute!="function")j=`Tool not found: ${O}`,q={error:j};else if(V)j=`Tool ${O}: ${V}`,q={error:j};else try{q=await Ef(O,$.execute,{...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}})(F,{toolCallId:U,messages:[],...e.abortSignal?{abortSignal:e.abortSignal}:{}}),r.push(O)}catch(H){j=H instanceof Error?H.message:String(H),q={error:j}}t.push({toolCallId:U,toolName:O,input:F,...j?{error:j}:{output:q},startTime:P,endTime:new Date}),I.push({type:"tool-result",toolCallId:U,output:q})}e.conversation.push({role:"tool",content:I})}return{text:n,...o?{reasoning:o}:{},finishReason:s,...i?{rawFinishReason:i}:{},inputTokens:a,outputTokens:c,cacheReadTokens:l,cacheWriteTokens:u,toolsUsed:r,steps:d}}var kP,tyt,GW,ryt,nyt,y_,HW=b({"src/lib/core/nativeGenerateLoop.ts"(){"use strict";z(),aP(),kP=e=>typeof e=="object"&&e!==null&&typeof e.doGenerate=="function",tyt=e=>Array.isArray(e)?e:[],GW=e=>typeof e=="object"&&e!==null&&typeof e.total=="number"?e.total:0,ryt=e=>{if(typeof e!="string")return{input:e??{}};if(e.trim()==="")return{input:{}};try{return{input:JSON.parse(e)}}catch{return{input:{},error:"arguments were not valid JSON"}}},nyt=(e,t)=>{const r=e?.inputSchema;if(typeof r?.safeParse!="function")return;const n=r.safeParse(t);return n.success?void 0:`input did not match the tool's schema: ${n.error instanceof Error?n.error.message:"schema mismatch"}`},y_=(e,t)=>{const r=`When you give your final answer, respond with only a single JSON object that conforms to the following JSON Schema. No prose before or after it, and no markdown code fence. JSON Schema: ${JSON.stringify(t)}`,n=e.reduce((i,a,c)=>a.role==="system"?c:i,-1);if(n===-1)return[{role:"system",content:r},...e];const o=e[n],s=typeof o.content=="string"?`${o.content}
|
|
1010
|
+
`):"";default:return El(e)}},_W=(e,t)=>{const r=t&&t.includes("/")?t:"image/png";if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:${r};base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:${r};base64,${Buffer.from(e).toString("base64")}`},Fgt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return El(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=r.mediaType??r.mimeType,i=_W(o,s);i&&t.push({type:"image_url",image_url:{url:i}})}else if(n.type==="file"){const o=r;if(o.mediaType?.startsWith("image/")){const s=_W(o.data,o.mediaType);s&&t.push({type:"image_url",image_url:{url:s}})}}}return t.length===1&&t[0].type==="text"?t[0].text:t},CW=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:El(n.content)});break;case"user":r.push({role:"user",content:Fgt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const c of o)if(c&&typeof c=="object"){const l=c;if(l.type==="text")s.push({type:"text",text:c.text??""});else if(l.type==="tool-call"){const u=c,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:h_(u.input)}})}}else typeof c=="string"&&s.push({type:"text",text:c});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:bW(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},kW=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,c=a?lUe(No(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:c}})}return n},$gt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:lUe(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},Ugt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},AW=["properties","patternProperties","$defs","definitions"],xW=["items","prefixItems","anyOf","oneOf","allOf","not","then","else"],Bgt=["allOf","not","if","then","else"],zgt=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([r,n])=>[r,t(n)])),j0=e=>{if(Array.isArray(e))return e.map(j0);if(!e||typeof e!="object")return e;const t={...e};for(const r of AW)r in t&&(t[r]=zgt(t[r],j0));for(const r of xW)r in t&&(t[r]=j0(t[r]));return t.additionalProperties&&typeof t.additionalProperties=="object"?t.additionalProperties=j0(t.additionalProperties):t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1),t},Af=e=>{if(Array.isArray(e))return e.every(Af);if(!e||typeof e!="object")return!0;const t=e;if(Bgt.some(o=>o in t))return!1;if(t.type==="object"){if(t.additionalProperties!==!1)return!1;const o=Object.keys(t.properties??{}),s=Array.isArray(t.required)?t.required:[];if(o.some(i=>!s.includes(i)))return!1}const r=AW.filter(o=>o in t).every(o=>Object.values(t[o]??{}).every(Af)),n=xW.filter(o=>o in t).every(o=>Af(t[o]));return r&&n},qgt=e=>{if(e.type==="text")return{type:"text"};if(!e.schema)return{type:"json_object"};const t=e.schema,r=j0(t),n=Af(t)?t:Af(r)?r:t;return{type:"json_schema",json_schema:{name:e.name??"response",schema:n,...e.description?{description:e.description}:{},strict:Af(n)}}},Ggt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},Hgt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),IW=e=>e.response_format?.type==="json_object"&&!Hgt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,jgt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),RW=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,c={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(c.max_tokens=n.maxTokens);const l=hu("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return l.temperature!==void 0&&(c.temperature=l.temperature),l.topP!==void 0&&(c.top_p=l.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(c.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(c.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(c.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(c.stop=n.stopSequences),o&&(c.tools=o),s!==void 0&&o&&o.length>0&&(c.tool_choice=s),a&&(c.response_format=a),n.extraBody&&Object.assign(c,n.extraBody),c},MW=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=uW({onEvent:l=>{const u=l.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(g){s=g instanceof Error?g:new Error(String(g));return}d.usage&&(n.usage=d.usage),d.id&&!n.id&&(n.id=d.id),d.model&&!n.model&&(n.model=d.model);const m=d.choices?.[0];if(!m)return;const h=m.delta;h?.content&&(n.text+=h.content,t(h.content));const f=h?.reasoning_content||h?.reasoning;if(f&&(n.reasoning+=f,r?.(f)),h?.tool_calls)for(const g of h.tool_calls){let y=n.toolCalls.get(g.index);y?g.id&&(y.id=g.id):(y={id:g.id??`call_${g.index}_${Date.now()}`,name:g.function?.name??"",argsBuffered:""},n.toolCalls.set(g.index,y)),g.function?.name&&(y.name=g.function.name),g.function?.arguments&&(y.argsBuffered+=g.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),c=e.getReader();try{for(;;){const{done:l,value:u}=await c.read();if(l)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{c.releaseLock()}if(s)throw s;return n},f_=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=_4r(o)??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const c=a.toLowerCase();return c==="retry-after"||c.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},PW=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},Vgt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function CP(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function C4r(e,t){let r=CP(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=CP(e.tool_calls)),nr(r,t)+wl}function k4r(e,t){if(e.role!=="tool")return;const r=CP(e.content),n={maxBytes:DW,maxLines:OW};if(!bpt(r,n))return;const{preview:o}=Qa(r,n);return nr(o,t)+wl}function A4r(e,t){return e.map(r=>{const n=C4r(r,t);if(r.role==="tool"){const o=k4r(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function x4r(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,c=A4r(t,o),l=n+c.reduce((g,y)=>g+y.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=vP(c,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(l);return}const m=new Set(d.truncate),h=new Set(d.drop),f=[];for(let g=0;g<t.length;g++){if(h.has(g))continue;const y=t[g];if(m.has(g)&&y.role==="tool"){const{preview:v}=Qa(CP(y.content),{maxBytes:DW,maxLines:OW});f.push({...y,content:v});continue}f.push(y)}if(h.size>0){let g=f.findIndex(y=>y.role==="tool"||y.role==="assistant"&&y.tool_calls);g<0&&(g=Math.min(1,f.length)),f.splice(g,0,{role:"user",content:Wgt})}return p.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:f.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),f}var DW,OW,Wgt,I4r=b({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";is(),yf(),TP(),z(),DW=2048,OW=60,Wgt="[Earlier tool exchanges were removed to fit the context window.]"}});function R4r(e){let t,r;const n=o=>nr(LW(o),e.provider)+wl;return{observeUsage(o){const s=g_(o)?o.inputTokens:void 0,i=g_(s)?s.total:s;r=typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0},guardConversation(o){const s=o.findIndex(S=>S.role==="user"),i=Math.max(1,s+1),a=o.slice(i),c=a.map(Kgt),l=[{kind:"other",tokens:o.slice(0,i).reduce((S,_)=>S+n(_),0)},...a.map((S,_)=>{const C=NW(S.content);return S.role==="assistant"&&C.some(k=>k.type==="tool-call")?{kind:"toolCall",tokens:n(S)}:S.role==="tool"&&C.some(k=>k.type==="tool-result")?{kind:"toolResult",tokens:n(S),previewTokens:n(c[_])}:{kind:"other",tokens:n(S)}})],u=e.getFixedOverheadTokens(),d=r&&t?Math.min(3,Math.max(1,r/t)):1,m=vP(l,{availableInputTokens:e.availableInputTokens,fixedOverheadTokens:u,calibration:d}),h=Math.floor(e.availableInputTokens*e4/(d>0?d:1)),f=u+l.reduce((S,_)=>S+_.tokens,0);if(!m.fire){t=f,f>h?p.warn("[NativeGenerateGuard] Over threshold, nothing reclaimable",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,overThresholdByTokens:f-h,calibration:d}):p.debug("[NativeGenerateGuard] Under threshold",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,headroomToThresholdTokens:h-f,calibration:d});return}const g=new Set(m.drop),y=new Set(m.truncate),v=[...o.slice(0,i)];let w=!1;return a.forEach((S,_)=>{const C=_+1;g.has(C)?(w||v.push({role:"user",content:"[Earlier tool exchanges were removed to fit the context window.]"}),w=!0):v.push(y.has(C)?c[_]:S)}),t=u+v.reduce((S,_)=>S+n(_),0),p.info("[NativeGenerateGuard] Reclaimed context",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedBeforeTokens:f,estimatedAfterTokens:t,truncated:m.truncate.length,dropped:m.drop.length,calibration:d}),v}}}var g_,NW,LW,Kgt,M4r=b({"src/lib/context/nativeGenerateGuard.ts"(){"use strict";is(),z(),TP(),Oo(),yf(),g_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),NW=e=>Array.isArray(e)?e.filter(g_):[],LW=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}},Kgt=e=>({...e,content:NW(e.content).map(t=>{if(t.type!=="tool-result")return t;const r=t.output,n=g_(r)&&["text","json","error-text","error-json"].includes(String(r.type))&&"value"in r,{preview:o,truncated:s}=Qa(LW(n?r.value:r),{maxBytes:2048,maxLines:60});return s?{...t,output:n?{...r,type:String(r.type).startsWith("error")?"error-text":"text",value:o}:o}:t})})}});function FW(e){const t=UW(e);return t?BW.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function P4r(e){const t=UW(e);if(!t)return null;for(const{provider:r,patterns:n}of BW)if(n.some(o=>o.test(t)))return r;return null}function $W(e){const t=UW(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function UW(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var BW,Jgt=b({"src/lib/context/errorDetection.ts"(){"use strict";BW=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),ka,Ygt=b({"src/lib/context/errors.ts"(){"use strict";ka=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),Xgt,zW,Zgt=b({"src/lib/core/streamAnalytics.ts"(){"use strict";cb(),z(),l4(),Mm(),Xgt=class{async collectUsage(e){try{const t=await e.usage;return t?c4(t):(p.debug("No usage data available from stream result"),Q$e())}catch(t){return ru.isInstance(t)?p.debug("No output generated from stream \u2014 returning empty usage"):p.warn("Failed to collect usage from stream result",{error:t}),Q$e()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return ru.isInstance(t)?p.debug("No output generated from stream \u2014 returning default metadata"):p.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,c,l,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return u0(e,t,{usage:s,content:a,response:i,finishReason:c,toolResults:l,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:c})}catch(s){return p.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),u0(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},zW=new Xgt}});function Qgt(e,t){if(!(!e||!t||t.length===0))for(const r of t){const n=r.output??r.result,o=!!r.error||n!=null&&typeof n=="object"&&"isError"in n&&n.isError===!0;let s;if(o){if(r.error)s=r.error;else if(n&&typeof n=="object"){const i=n.content;if(Array.isArray(i)){const a=i.filter(c=>c.type==="text"&&c.text).map(c=>c.text);s=a.length>0?a.join(" "):"Tool returned isError: true"}else s="Tool returned isError: true"}}e.emit("tool:end",O0(r.toolName,{responseTime:0,success:!o,timestamp:Date.now(),result:n,error:s}))}}var eyt=b({"src/lib/utils/toolEndEmitter.ts"(){"use strict";w9()}});async function qW(e,t){const r=[];let n="",o="",s="stop",i,a=0,c=0,l=0,u=0,d=0,m=!1,h=!1,f;const g=!!(e.tools&&e.tools.length>0);for(let y=0;y<e.maxSteps;y++){d=y+1;const v=e.guardConversation?.(e.conversation);v&&e.conversation.splice(0,e.conversation.length,...v);const w=()=>e.runStep(()=>e.doGenerate({prompt:e.conversation,...e.tools&&e.tools.length>0?{tools:e.tools}:{},...m?{toolChoice:{type:"none"}}:e.toolChoice!==void 0?{toolChoice:e.toolChoice}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.maxOutputTokens?{maxOutputTokens:e.maxOutputTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{}}));let S;try{S=await w()}catch(M){if(h&&f){p.warn("toolChoice: none re-ask failed; returning the original result",{error:M instanceof Error?M.message:String(M)}),n=f.text,s=f.finishReason,i=f.rawFinishReason;break}throw M}h=!1,e.observeUsage?.(S.usage);const _=tyt(S.content);n=_.filter(M=>M.type==="text"&&typeof M.text=="string").map(M=>M.text).join(""),o+=_.filter(M=>M.type==="reasoning"&&typeof M.text=="string").map(M=>M.text).join("");const C=S.finishReason;if(typeof C=="string")s=C;else if(typeof C=="object"&&C!==null){const M=C;s=M.unified??s,i=M.raw??i}const k=S.usage;a+=GW(k?.inputTokens),c+=GW(k?.outputTokens);const x=k?.inputTokens;l+=x?.cacheRead??0,u+=x?.cacheWrite??0;const R=_.filter(M=>M.type==="tool-call");if(R.length===0){if(s==="tool-calls"&&n.trim()===""&&g&&!m&&y+1<e.maxSteps){m=!0,h=!0,f={text:n,finishReason:s,rawFinishReason:i},e.conversation.push({role:"assistant",content:_});continue}break}e.conversation.push({role:"assistant",content:_});const I=[];for(const M of R){const O=String(M.toolName??""),U=String(M.toolCallId??""),P=new Date,D=ryt(M.input),F=D.input,$=e.toolsRecord[O];let q,j;const V=D.error??(typeof $?.execute=="function"?nyt($,F):void 0);if(typeof $?.execute!="function")j=`Tool not found: ${O}`,q={error:j};else if(V)j=`Tool ${O}: ${V}`,q={error:j};else try{q=await Ef(O,$.execute,{...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}})(F,{toolCallId:U,messages:[],...e.abortSignal?{abortSignal:e.abortSignal}:{}}),r.push(O)}catch(H){j=H instanceof Error?H.message:String(H),q={error:j}}t.push({toolCallId:U,toolName:O,input:F,...j?{error:j}:{output:q},startTime:P,endTime:new Date}),I.push({type:"tool-result",toolCallId:U,output:q})}e.conversation.push({role:"tool",content:I})}return{text:n,...o?{reasoning:o}:{},finishReason:s,...i?{rawFinishReason:i}:{},inputTokens:a,outputTokens:c,cacheReadTokens:l,cacheWriteTokens:u,toolsUsed:r,steps:d}}var kP,tyt,GW,ryt,nyt,y_,HW=b({"src/lib/core/nativeGenerateLoop.ts"(){"use strict";z(),aP(),kP=e=>typeof e=="object"&&e!==null&&typeof e.doGenerate=="function",tyt=e=>Array.isArray(e)?e:[],GW=e=>typeof e=="object"&&e!==null&&typeof e.total=="number"?e.total:0,ryt=e=>{if(typeof e!="string")return{input:e??{}};if(e.trim()==="")return{input:{}};try{return{input:JSON.parse(e)}}catch{return{input:{},error:"arguments were not valid JSON"}}},nyt=(e,t)=>{const r=e?.inputSchema;if(typeof r?.safeParse!="function")return;const n=r.safeParse(t);return n.success?void 0:`input did not match the tool's schema: ${n.error instanceof Error?n.error.message:"schema mismatch"}`},y_=(e,t)=>{const r=`When you give your final answer, respond with only a single JSON object that conforms to the following JSON Schema. No prose before or after it, and no markdown code fence. JSON Schema: ${JSON.stringify(t)}`,n=e.reduce((i,a,c)=>a.role==="system"?c:i,-1);if(n===-1)return[{role:"system",content:r},...e];const o=e[n],s=typeof o.content=="string"?`${o.content}
|
|
1011
1011
|
|
|
1012
1012
|
${r}`:r;return e.map((i,a)=>a===n?{...i,content:s}:i)}}}),xf,D4r=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js"(){xf=class extends Error{constructor(e,t){super(`${e} at position ${t}`),this.position=t}}}});function O4r(e){return/^[0-9A-Fa-f]$/.test(e)}function If(e){return e>="0"&&e<="9"}function N4r(e){return e>=" "}function AP(e){return`,:[]/{}()
|
|
1013
1013
|
+`.includes(e)}function oyt(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"}function syt(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"||e>="0"&&e<="9"}function iyt(e){return`,[]/{}
|
|
@@ -163,9 +163,17 @@ export class MessageBuilder {
|
|
|
163
163
|
};
|
|
164
164
|
}
|
|
165
165
|
else if (item.type === "image") {
|
|
166
|
+
// Upstream image builders label the resolved format as
|
|
167
|
+
// either `mediaType` (canonical ImagePart field) or
|
|
168
|
+
// `mimeType` (messageBuilder's convertSimpleImagesToProviderFormat).
|
|
169
|
+
// Dropping it here silently reset every transcoded image
|
|
170
|
+
// back to the provider's hardcoded PNG default even
|
|
171
|
+
// though the transcoded bytes themselves were correct.
|
|
172
|
+
const mediaType = (item.mediaType ?? item.mimeType);
|
|
166
173
|
return {
|
|
167
174
|
type: "image",
|
|
168
175
|
image: item.image || "",
|
|
176
|
+
...(mediaType && { mediaType }),
|
|
169
177
|
...(itemProviderOptions && {
|
|
170
178
|
providerOptions: itemProviderOptions,
|
|
171
179
|
}),
|
|
@@ -287,9 +295,17 @@ export class MessageBuilder {
|
|
|
287
295
|
};
|
|
288
296
|
}
|
|
289
297
|
else if (item.type === "image") {
|
|
298
|
+
// Upstream image builders label the resolved format as
|
|
299
|
+
// either `mediaType` (canonical ImagePart field) or
|
|
300
|
+
// `mimeType` (messageBuilder's convertSimpleImagesToProviderFormat).
|
|
301
|
+
// Dropping it here silently reset every transcoded image
|
|
302
|
+
// back to the provider's hardcoded PNG default even
|
|
303
|
+
// though the transcoded bytes themselves were correct.
|
|
304
|
+
const mediaType = (item.mediaType ?? item.mimeType);
|
|
290
305
|
return {
|
|
291
306
|
type: "image",
|
|
292
307
|
image: item.image || "",
|
|
308
|
+
...(mediaType && { mediaType }),
|
|
293
309
|
...(itemProviderOptions && {
|
|
294
310
|
providerOptions: itemProviderOptions,
|
|
295
311
|
}),
|
|
@@ -193,7 +193,14 @@ export const convertContentForOpenAI = (content) => {
|
|
|
193
193
|
const data = part.image ??
|
|
194
194
|
part.data ??
|
|
195
195
|
part.url;
|
|
196
|
-
|
|
196
|
+
// ImagePart carries the resolved format as `mediaType` (MessageBuilder
|
|
197
|
+
// canonicalizes to it); `mimeType` is accepted for parts that bypass
|
|
198
|
+
// that normalization. Without this, a raw base64 payload (as opposed to
|
|
199
|
+
// an already-labelled data: URI) always fell back to imageDataToURL's
|
|
200
|
+
// hardcoded "image/png" default, mislabeling real JPEG/WebP/etc bytes.
|
|
201
|
+
const mediaType = part.mediaType ??
|
|
202
|
+
part.mimeType;
|
|
203
|
+
const url = imageDataToURL(data, mediaType);
|
|
197
204
|
if (url) {
|
|
198
205
|
out.push({ type: "image_url", image_url: { url } });
|
|
199
206
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.21.
|
|
3
|
+
"version": "12.21.2",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
|
|
6
6
|
"author": {
|