@github/copilot 1.0.15-2 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk/index.js CHANGED
@@ -397,7 +397,45 @@ Use shell commands or **grep** tool to check if the paths exist or not if not su
397
397
  Create files require parent directories to exist already and the file itself to not exist.
398
398
  Editing files require the file path to already exist. Be sure before making edits.
399
399
  If the tool call fails due to invalid paths, correct and try again and remember for future edits.
400
- </file_paths_for_edit_view_create>`});var d$,a9t,I9t,oNe,c9t=g(()=>{"use strict";d$='<tool_use_guidelines>\n- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)\n- If a tool exists for an action, prefer to use the tool instead of shell commands (e.g view over cat). Strictly avoid raw `cmd`/terminal when a dedicated tool exists. Default to solver tools: `rg` (search), `view`, `glob`, `apply_patch`. Use `cmd`/`run_terminal_cmd` only when no listed tool can perform the action.\n- When multiple tool calls can be parallelized (e.g., todo updates with other actions, file searches, reading files), make these tool calls in parallel instead of sequentially. Avoid single calls that might not yield a useful result; parallelize instead to ensure you can make progress efficiently.\n- Code chunks that you receive (via tool calls or from user) may include inline line numbers in the form "Lxxx:LINE_CONTENT", e.g. "L123:LINE_CONTENT". Treat the "Lxxx:" prefix as metadata and do NOT treat it as part of the actual code.\n- Default expectation: deliver working code, not just a plan. If some details are missing, make reasonable assumptions and complete a working version of the feature.\n</tool_use_guidelines>\n\n<editing_constraints>\n- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.\n- Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.\n- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).\n- You may be in a dirty git worktree.\n * NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.\n * If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn\'t make in those files, don\'t revert those changes.\n * If the changes are in files you\'ve touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.\n * If the changes are in unrelated files, just ignore them and don\'t revert them.\n- Do not amend a commit unless explicitly requested to do so.\n- While you are working, you might notice unexpected changes that you didn\'t make. If this happens, STOP IMMEDIATELY and ask the user how they would like to proceed.\n- **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested or approved by the user.\n</editing_constraints>\n\n<exploration_and_reading_files>\n- **Think first.** Before any tool call, decide ALL files/resources you will need.\n- **Batch everything.** If you need multiple files (even from different places), read them together.\n- **multi_tool_use.parallel** Use `multi_tool_use.parallel` to parallelize tool calls and only this.\n- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**\n- **Workflow:** (a) plan all needed reads \u2192 (b) issue one parallel batch \u2192 (c) analyze results \u2192 (d) repeat if new, unpredictable reads arise.\n\n**Additional notes**:\n* Always maximize parallelism. Never read files one-by-one unless logically unavoidable.\n* This concerns every read/list/search operations including, but not only, `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`, ...\n* Do not try to parallelize using scripting or anything else than `multi_tool_use.parallel`.\n</exploration_and_reading_files>\n\n<autonomy_and_persistence>\n- You are autonomous senior engineer: once the user gives a direction, proactively gather context, plan, implement, test, and refine without waiting for additional prompts at each step.\n- Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.\n- Bias to action: default to implementing with reasonable assumptions; do not end your turn with clarifications unless truly blocked.\n- Avoid excessive looping or repetition; if you find yourself re-reading or re-editing the same files without clear progress, stop and end the turn with a concise summary and any clarifying questions needed.\n</autonomy_and_persistence>\n',a9t=`<preamble_messages>
400
+ </file_paths_for_edit_view_create>`});var d$,a9t,I9t,oNe,c9t=g(()=>{"use strict";d$=`<tool_use_guidelines>
401
+ - Use built-in tools such as \`rg\`, \`glob\`, \`view\`, and \`apply_patch\` whenever possible, as they are optimized for performance and reliability. Only fall back to shell commands when these tools cannot meet your needs.
402
+ - Parallelize tool calls whenever possible - especially file reads. You should always maximize parallelism in order to be efficient. Never read files one-by-one unless logically unavoidable.
403
+ - Use \`multi_tool_use.parallel\` to parallelize tool calls and only this. Do not try to parallelize using scripting.
404
+ - Code chunks that you receive (via tool calls or from user) may include inline line numbers in the form "Lxxx:LINE_CONTENT", e.g. "L123:LINE_CONTENT". Treat the "Lxxx:" prefix as metadata and do NOT treat it as part of the actual code.
405
+ </tool_use_guidelines>
406
+
407
+ <editing_constraints>
408
+ - Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
409
+ - Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.
410
+ - Always use apply_patch for manual code edits. Do not use cat or any other commands when creating or editing files. Formatting commands or bulk edits don't need to be done with apply_patch.
411
+ - Do not use Python to read/write files when the view tool or apply_patch would suffice.
412
+ - You may be in a dirty git worktree.
413
+ * NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
414
+ * If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
415
+ * If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
416
+ * If the changes are in unrelated files, just ignore them and don't revert them.
417
+ - Do not amend a commit unless explicitly requested to do so.
418
+ - While you are working, you might notice unexpected changes that you didn't make. It's likely the user intentionally made them, or they were autogenerated. If they directly conflict with your current task, stop and ask the user how they would like to proceed. Otherwise, focus on the task at hand.
419
+ - **NEVER** use destructive commands like \`git reset --hard\` or \`git checkout --\` unless specifically requested or approved by the user.
420
+ - You struggle using the git interactive console. **ALWAYS** prefer using non-interactive git commands.
421
+ </editing_constraints>
422
+
423
+ <exploration_and_reading_files>
424
+ You build context by examining the codebase first without making assumptions or jumping to conclusions. You think through the nuances of the code you encounter, and embody the mentality of a skilled senior software engineer.
425
+
426
+ - **Think first.** Before any tool call, decide ALL files/resources you will need.
427
+ - **Batch everything.** If you need multiple files (even from different places), read them together.
428
+ - **Only make sequential calls if you truly cannot know the next file without seeing a result first.**
429
+ - **Workflow:** (a) plan all needed reads \u2192 (b) issue one parallel batch \u2192 (c) analyze results \u2192 (d) repeat if new, unpredictable reads arise.
430
+ </exploration_and_reading_files>
431
+
432
+ <autonomy_and_persistence>
433
+ - Bias to action. Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.
434
+ - Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
435
+ - Your default expectation is to deliver working code. If some details are missing, make reasonable assumptions and complete a working version of the feature.
436
+ - Avoid excessive looping or repetition; if you find yourself re-reading or re-editing the same files without clear progress, stop and end the turn with a concise summary and any clarifying questions needed.
437
+ </autonomy_and_persistence>
438
+ `,a9t=`<preamble_messages>
401
439
  As you work, occasionally send a brief preamble to the user explaining where you're at.
402
440
 
403
441
  - Prioritize sharing information that helps the user follow your progress and understand your next steps.
@@ -4037,7 +4075,7 @@ ${a}`}}}let n=await t.workspace.listCheckpoints();if(n.length===0)return{kind:"a
4037
4075
  ${"\u2500".repeat(40)}
4038
4076
  ${n}`}}:{kind:"add-timeline-entry",entry:{type:"info",text:"No plan exists for this session."}}}if(r==="rename"){if(!t.workspace)return{kind:"add-timeline-entry",entry:{type:"info",text:"Workspace features are not enabled for this session."}};let n=e.slice(1).join(" ").trim();if(n)return n.length>100?{kind:"add-timeline-entry",entry:{type:"error",text:"Session name must be 100 characters or less."}}:(await t.workspace.renameSession(n),{kind:"add-timeline-entry",entry:{type:"info",text:`Session renamed to: ${n}`}});let s=t.session.instance,l=s.getAuthInfo(),o=t.models;if(!l||!o?.length)return{kind:"add-timeline-entry",entry:{type:"error",text:"Unable to generate a session name (auth or models unavailable). Provide a name with /rename <name>"}};let a=s.getEvents(),I=[];for(let u of a)u.type==="user.message"&&!("source"in u.data&&u.data.source)&&u.data.content&&I.push(u.data.content);if(I.length===0)return{kind:"add-timeline-entry",entry:{type:"error",text:"No conversation history to generate a name from. Provide a name with /rename <name>"}};let c=I.slice(-20).join(`
4039
4077
 
4040
- `),d;try{d=await DMr({userMessage:c,availableModels:o,authInfo:l,sessionId:t.session.getSessionId(),featureFlagService:t.featureFlagService})}catch{return{kind:"add-timeline-entry",entry:{type:"error",text:"Failed to generate a session name. Provide a name with /rename <name>"}}}return d?(await t.workspace.renameSession(d),{kind:"add-timeline-entry",entry:{type:"info",text:`Session renamed to: ${d}`}}):{kind:"add-timeline-entry",entry:{type:"error",text:"Failed to generate a session name. Provide a name with /rename <name>"}}}return r==="prune"?t.featureFlags.SESSION_CLEANUP?kUs(t,e.slice(1)):Q2t(e[0],t.featureFlags.SESSION_CLEANUP):r==="cleanup"&&t.featureFlags.SESSION_CLEANUP?LUs(t,e.slice(1)):Q2t(e[0],t.featureFlags.SESSION_CLEANUP)};KMr={name:i5e,aliases:[okr],args:"[info|checkpoints [n]|files|plan|rename [name]]",help:"View and manage sessions. Use subcommands for details.",allowDuringAgentExecution:!0,execute:async(t,e)=>jMr(t,e)},qMr={name:n5e,args:"[name]",help:"Rename the current session, or auto-generate a name from conversation",allowDuringAgentExecution:!0,execute:async(t,e)=>jMr(t,["rename",...e])}});var ezr=g(()=>{"use strict"});function xUs(t){return typeof t=="object"&&t!==null&&"ok"in t&&t.ok===!1}async function s5(t,e){let r=e?{authorization:`token ${e}`}:{};try{let n=await t(r);return e&&xUs(n)?(te.info("Retrying without auth token"),await t({})):n}catch(n){if(!e)throw n;return te.info("Retrying without auth token"),await t({})}}var v2t=g(()=>{"use strict";ns()});var nzr={};Fo(nzr,{MAX_RECENT_RELEASES:()=>BUs,fetchLatestRelease:()=>l5,fetchReleaseByTag:()=>OUs,getUpdateChannel:()=>m9,getVersion:()=>XY,getVersionWithoutUpdateCheck:()=>JUs,isPrerelease:()=>tzr,showVersionWithUpdateCheck:()=>SUs});function XY(){return process.env.COPILOT_CLI_VERSION||"1.0.15-2"}function tzr(){try{let t=(0,A4e.parse)("1.0.15-2");return t!==null&&t.prerelease.length>0}catch{return!1}}function m9(t,e){return t||(e||tzr()?"prerelease":"stable")}function JUs(){return`GitHub Copilot CLI ${F1().version}.
4078
+ `),d;try{d=await DMr({userMessage:c,availableModels:o,authInfo:l,sessionId:t.session.getSessionId(),featureFlagService:t.featureFlagService})}catch{return{kind:"add-timeline-entry",entry:{type:"error",text:"Failed to generate a session name. Provide a name with /rename <name>"}}}return d?(await t.workspace.renameSession(d),{kind:"add-timeline-entry",entry:{type:"info",text:`Session renamed to: ${d}`}}):{kind:"add-timeline-entry",entry:{type:"error",text:"Failed to generate a session name. Provide a name with /rename <name>"}}}return r==="prune"?t.featureFlags.SESSION_CLEANUP?kUs(t,e.slice(1)):Q2t(e[0],t.featureFlags.SESSION_CLEANUP):r==="cleanup"&&t.featureFlags.SESSION_CLEANUP?LUs(t,e.slice(1)):Q2t(e[0],t.featureFlags.SESSION_CLEANUP)};KMr={name:i5e,aliases:[okr],args:"[info|checkpoints [n]|files|plan|rename [name]]",help:"View and manage sessions. Use subcommands for details.",allowDuringAgentExecution:!0,execute:async(t,e)=>jMr(t,e)},qMr={name:n5e,args:"[name]",help:"Rename the current session, or auto-generate a name from conversation",allowDuringAgentExecution:!0,execute:async(t,e)=>jMr(t,["rename",...e])}});var ezr=g(()=>{"use strict"});function xUs(t){return typeof t=="object"&&t!==null&&"ok"in t&&t.ok===!1}async function s5(t,e){let r=e?{authorization:`token ${e}`}:{};try{let n=await t(r);return e&&xUs(n)?(te.info("Retrying without auth token"),await t({})):n}catch(n){if(!e)throw n;return te.info("Retrying without auth token"),await t({})}}var v2t=g(()=>{"use strict";ns()});var nzr={};Fo(nzr,{MAX_RECENT_RELEASES:()=>BUs,fetchLatestRelease:()=>l5,fetchReleaseByTag:()=>OUs,getUpdateChannel:()=>m9,getVersion:()=>XY,getVersionWithoutUpdateCheck:()=>JUs,isPrerelease:()=>tzr,showVersionWithUpdateCheck:()=>SUs});function XY(){return process.env.COPILOT_CLI_VERSION||"1.0.15"}function tzr(){try{let t=(0,A4e.parse)("1.0.15");return t!==null&&t.prerelease.length>0}catch{return!1}}function m9(t,e){return t||(e||tzr()?"prerelease":"stable")}function JUs(){return`GitHub Copilot CLI ${F1().version}.
4041
4079
  Run 'copilot update' to check for updates.`}async function SUs(t,e){let r=F1();if(process.stdout.write(`GitHub Copilot CLI ${r.version}
4042
4080
  `),CG())return;let n=m9(t.autoUpdatesChannel,t.staff),s=await l5(n,e);if("error"in s){process.stderr.write(`
4043
4081
  Unable to check for updates: ${String(s.error)}
@@ -4574,7 +4612,7 @@ eof_line: "*** End of File" LF
4574
4612
  %import common.LF`},safeForTelemetry:!0,callback:async r=>{let n;if(typeof r=="string")n=r;else if(typeof r=="object"&&r!==null){let s=r;if(typeof s.input=="string")n=s.input;else if(typeof s.patch=="string")n=s.patch;else return f9("apply_patch received invalid input format. Expected a string (the patch content) or an object with an 'input' or 'patch' string property.")}else return f9("apply_patch requires a string input (the patch content). Received invalid input type.");return!n||n.trim()===""?f9("apply_patch requires a non-empty string input (the patch content)."):await RDs(n,t.location,t.permissions)}}}var Fqr=g(()=>{"use strict";bi();Vt();tG();cqr();Wqr();fqr()});function Ift(t){return Array.isArray(t)?t.join(", "):String(t)}function VDs(t){let e=Object.entries(t);return e.length===1?Ift(e[0][1]):e.map(([r,n])=>`${r}=${Ift(n)}`).join(", ")}function fDs(t){return Object.entries(t).map(([e,r])=>`${e}: ${Ift(r)}`).join(`
4575
4613
  `)}function wDs(t){let e=new Set;for(let r of Object.values(t.properties)){let n=r;n.type==="array"?e.add("multi-enum"):n.type==="string"&&(n.enum||n.oneOf)?e.add("enum"):e.add(n.type)}return[...e].sort()}function Cqr(t,e){let r=Object.keys(t.requestedSchema.properties).length,n=wDs(t.requestedSchema);return{properties:{elicitation_action:e,elicitation_field_types:JSON.stringify(n)},metrics:{elicitation_field_count:r}}}function Qqr(t){return{name:sh,title:"Asking user",description:["Ask the user a question and wait for their response.","Use this tool when you need to ask the user questions during execution. This allows you to:","1. Gather user preferences or requirements","2. Clarify ambiguous instructions","3. Get decisions on implementation choices as you work","4. Collect multiple related pieces of information in a single interaction"].join(`
4576
4614
  `),input_schema:Er(aft),callback:Xn(aft,async(e,r)=>{try{let n=await t({message:e.message,requestedSchema:{type:"object",...e.requestedSchema},toolCallId:r?.toolCallId}),s=Cqr(e,n.action);switch(n.action){case"accept":{let l=n.content;if(!l||Object.keys(l).length===0)return{textResultForLlm:"User accepted but provided no values.",resultType:"success",toolTelemetry:s};let o=VDs(l),a=fDs(l);return{textResultForLlm:`User responded: ${o}`,sessionLog:`User responded:
4577
- ${a}`,resultType:"success",toolTelemetry:s}}case"decline":return{textResultForLlm:YTt,resultType:"success",toolTelemetry:s};case"cancel":return{textResultForLlm:"User cancelled the request.",resultType:"success",toolTelemetry:s};default:return{textResultForLlm:`Unknown user action: ${String(n.action)}`,resultType:"failure",error:`Unknown action: ${String(n.action)}`,toolTelemetry:s}}}catch(n){let s=D(n);return{textResultForLlm:`Error asking user: ${s}`,resultType:"failure",error:s,toolTelemetry:Cqr(e,"error")}}}),safeForTelemetry:!0,summariseIntention:ou(aft,e=>e.message.length>60?e.message.slice(0,57)+"...":e.message,"Waiting for response"),instructions:[`Use the ${sh} tool to ask the user clarifying questions when needed.`,"","**IMPORTANT: Never ask questions via plain text output.** When you need input from the user, use this tool instead of asking in your response text. The tool provides a better UX and ensures the user's answer is captured properly.","","This tool presents a structured form to the user. You provide a `message` describing what you need, and a `requestedSchema` defining the form fields. The schema follows JSON Schema conventions \u2014 the input_schema for this tool already describes the exact shape.","","**When to use this tool:**","- You need the user to make a decision before you can proceed (e.g., choosing between implementation approaches)","- Requirements are ambiguous and you need specific, structured input to resolve them","- You want to collect several related preferences at once rather than asking one at a time","- The user should confirm or override defaults before you act on them","","**Choosing field types:**","- **Enum** \u2014 when you know the valid options and the user must pick one (e.g., database engine, auth strategy, log level)",'- **Boolean** \u2014 for yes/no decisions (e.g., "enable caching?", "run migrations?")',"- **Multi-select array** \u2014 when the user should pick one or more from a known set (e.g., which features to include, which platforms to target)","- **Number/integer** \u2014 for numeric configuration the user may want to tune (e.g., port, timeout, retry count)","- **String** \u2014 only when the answer is truly open-ended and can't be predicted (e.g., project name, custom path). Use `format` to hint at structure when applicable (email, URI, date).","","**Guidelines:**","- Keep forms focused on one topic \u2014 don't mix unrelated questions in a single form","- Provide clear `title` and `description` on each field so the user understands what they're choosing","- Set sensible `default` values when a reasonable default exists \u2014 if you recommend a specific option, make it the default","- A single-field form is perfectly fine for a simple yes/no or single choice","","**Example \u2014 simple single-choice question:**","```json","{",' "message": "What database should I use?",',' "requestedSchema": {',' "properties": {',' "database": {',' "type": "string",',' "title": "Database engine",',' "enum": ["PostgreSQL", "MySQL", "SQLite"],',' "default": "PostgreSQL"'," }"," },",' "required": ["database"]'," }","}","```","","**User actions:**","- The user may **accept** the form (you receive their field values)","- The user may **decline** (they chose not to answer \u2014 respect this and proceed with reasonable defaults)","- The user may **cancel** (they want to abort the current interaction)","","**When to STOP and ask (do not assume):**","- Design decisions that significantly affect implementation approach",'- Behavioral questions (e.g., "should this be unlimited or capped?")',"- Scope ambiguity (e.g., which features to include/exclude)","- Edge cases where multiple reasonable approaches exist"].join(`
4615
+ ${a}`,resultType:"success",toolTelemetry:s}}case"decline":return{textResultForLlm:YTt,resultType:"success",toolTelemetry:s};case"cancel":return{textResultForLlm:"User cancelled the request.",resultType:"success",toolTelemetry:s};default:return{textResultForLlm:`Unknown user action: ${String(n.action)}`,resultType:"failure",error:`Unknown action: ${String(n.action)}`,toolTelemetry:s}}}catch(n){let s=D(n);return{textResultForLlm:`Error asking user: ${s}`,resultType:"failure",error:s,toolTelemetry:Cqr(e,"error")}}}),safeForTelemetry:!0,summariseIntention:ou(aft,e=>e.message.length>60?e.message.slice(0,57)+"...":e.message,"Waiting for response"),instructions:[`Use the ${sh} tool to ask the user clarifying questions when needed.`,"","**IMPORTANT: Never ask questions via plain text output.** When you need input from the user, use this tool instead of asking in your response text. The tool provides a better UX and ensures the user's answer is captured properly.","","This tool presents a structured form to the user. You provide a `message` describing what you need, and a `requestedSchema` defining the form fields. The schema follows JSON Schema conventions \u2014 the input_schema for this tool already describes the exact shape.","","**When to use this tool:**","- You need the user to make a decision before you can proceed (e.g., choosing between implementation approaches)","- Requirements are ambiguous and you need specific, structured input to resolve them","- You want to collect several related preferences at once rather than asking one at a time","- The user should confirm or override defaults before you act on them","","**Choosing field types:**","- **Enum** \u2014 when you know the valid options and the user must pick one (e.g., database engine, auth strategy, log level)",'- **Boolean** \u2014 for yes/no decisions (e.g., "enable caching?", "run migrations?")',"- **Multi-select array** \u2014 when the user should pick one or more from a known set (e.g., which features to include, which platforms to target)","- **Number/integer** \u2014 for numeric configuration the user may want to tune (e.g., port, timeout, retry count)","- **String** \u2014 only when the answer is truly open-ended and can't be predicted (e.g., project name, custom path). Use `format` to hint at structure when applicable (email, URI, date).","","**Guidelines:**","- Keep forms focused on one topic \u2014 don't mix unrelated questions in a single form","- Provide clear `title` and `description` on each field so the user understands what they're choosing","- Set sensible `default` values when a reasonable default exists \u2014 if you recommend a specific option, make it the default","- A single-field form is perfectly fine for a simple yes/no or single choice","- Order `properties` keys in the same sequence you discuss the topics in `message` \u2014 the form renders fields in property order, so matching the description avoids forcing the user to jump around","","**Example \u2014 simple single-choice question:**","```json","{",' "message": "What database should I use?",',' "requestedSchema": {',' "properties": {',' "database": {',' "type": "string",',' "title": "Database engine",',' "enum": ["PostgreSQL", "MySQL", "SQLite"],',' "default": "PostgreSQL"'," }"," },",' "required": ["database"]'," }","}","```","","**User actions:**","- The user may **accept** the form (you receive their field values)","- The user may **decline** (they chose not to answer \u2014 respect this and proceed with reasonable defaults)","- The user may **cancel** (they want to abort the current interaction)","","**When to STOP and ask (do not assume):**","- Design decisions that significantly affect implementation approach",'- Behavioral questions (e.g., "should this be unlimited or capped?")',"- Scope ambiguity (e.g., which features to include/exclude)","- Edge cases where multiple reasonable approaches exist"].join(`
4578
4616
  `)}}var YDs,aft,vqr=g(()=>{"use strict";$t();Vt();FNe();fl();KRt();YDs=k.object({properties:k.record(k.string(),i4e),required:k.array(k.string()).optional()}),aft=k.object({message:k.string().describe("A message describing what information you need from the user. Be clear and specific."),requestedSchema:YDs.describe("A JSON Schema object defining the form fields to present to the user.")})});import*as cft from"path";function Hqr(){if(process.env.USE_BUILTIN_RIPGREP==="false")return"rg";let t=process.platform==="win32"?".exe":"",e=`ripgrep/bin/${process.platform}-${process.arch}/rg${t}`,r=cft.join(import.meta.dirname,e),n=cft.join(import.meta.dirname,"..","..","dist-cli",e);return import.meta.url.endsWith(".ts")?n:r}var Xqr=g(()=>{"use strict"});var kqr,dft,gq,uft=g(()=>{"use strict";rL();ns();JRt();Vt();oze();kqr=500,dft=128,gq=class{constructor(e,r,n){this.threshold=e;this.ignoreContentBefore=r;this.ignoreContentAfter=n.ignoreContentAfter,this.onTempFileCreated=n.onTempFileCreated,this.sessionFs=n.sessionFs}memoryBuffer="";tempFilePath;totalBytes=0;preview="";isUsingFile=!1;closed=!1;fileQueue;bytesWrittenToFile=0;markerPrefix="";ignoreContentAfter;onTempFileCreated;sessionFs;get stats(){return this.fileQueue?.stats??{writeCount:0,pendingLength:0,drainScheduled:!1}}get length(){return this.memoryBuffer.length}append(e){if(this.closed)return;let r=Buffer.byteLength(e,"utf8");this.totalBytes+=r,this.isUsingFile?(this.queueFileWrite(e),this.updateTailBuffer(e)):(this.memoryBuffer+=e,this.totalBytes>this.threshold&&this.switchToFileMode()),this.capturePreview()}set(e){this.closed||(this.memoryBuffer=e,this.totalBytes=Buffer.byteLength(e,"utf8"),this.preview="",this.isUsingFile=!1,this.bytesWrittenToFile=0,this.markerPrefix="",this.tempFilePath=void 0,this.fileQueue?.reset(),this.fileQueue=void 0,this.capturePreview())}async readOutput(){return await this.fileQueue?.flush(),this.getOutputSnapshot()}getOutputSnapshot(){return this.isUsingFile&&this.tempFilePath?{isLargeOutput:!0,filePath:this.tempFilePath,totalBytes:this.totalBytes,preview:this.preview}:{isLargeOutput:!1,output:this.getOutputBuffer()}}async waitForPendingWrites(){await this.fileQueue?.flush()}getOutputBuffer(){return this.isUsingFile?this.getTailContent():this.extractOutputAfterMarker(this.memoryBuffer)??""}lastIndexOf(e){let r=this.isUsingFile?this.markerPrefix+this.memoryBuffer:this.memoryBuffer,n=this.extractOutputAfterMarker(r,{stripEndMarker:!1});return n===void 0?-1:n.lastIndexOf(e)}substring(e,r){return this.isUsingFile?this.getTailContent().substring(e,r):this.extractOutputAfterMarker(this.memoryBuffer)?.substring(e,r)??""}match(e){let r=this.isUsingFile?this.markerPrefix+this.memoryBuffer:this.memoryBuffer;return this.extractOutputAfterMarker(r,{stripEndMarker:!1})?.match(e)??null}getRawContent(){return this.isUsingFile?this.markerPrefix+this.memoryBuffer:this.memoryBuffer}close(){this.closed=!0}capturePreview(){if(this.preview.length>=kqr)return;let e=this.isUsingFile?this.markerPrefix+this.memoryBuffer:this.memoryBuffer,r=this.extractOutputAfterMarker(e,{stripEndMarker:!1});r!==void 0&&(this.preview=r.slice(0,kqr))}switchToFileMode(){let e=Date.now(),r=Math.random().toString(36).substring(2,8),n=`copilot-tool-output-${e}-${r}.txt`,s=this.sessionFs??nh.default;this.tempFilePath=s.join(s.tmpdir,n),te.debug(`StreamingOutputBuffer switching to file mode: ${this.totalBytes} bytes exceeded ${this.threshold} byte threshold, writing to ${this.tempFilePath}`);let l=this.findLastRealMarkerIndex(this.memoryBuffer);if(l!==-1){let I=l+this.ignoreContentBefore.length;this.markerPrefix=this.memoryBuffer.slice(0,I+this.markerTrailingSkip(this.memoryBuffer,I))}let o=this.extractOutputAfterMarker(this.memoryBuffer)??"";this.capturePreview();let a=this.tempFilePath;this.fileQueue=new CK(async I=>{await s.appendFile(a,I),this.bytesWrittenToFile+=Buffer.byteLength(I,"utf8")},I=>{te.debug(`Failed to write to temp file ${this.tempFilePath}: ${D(I)}`)}),this.fileQueue.enqueue(async()=>{await s.mkdir(s.tmpdir,{recursive:!0}),await s.writeFile(a,o),this.bytesWrittenToFile=Buffer.byteLength(o,"utf8"),this.onTempFileCreated?.(this.tempFilePath)}),this.memoryBuffer=this.memoryBuffer.slice(-dft),this.isUsingFile=!0}queueFileWrite(e){this.fileQueue?.append(e)}updateTailBuffer(e){if(this.memoryBuffer+=e,this.ignoreContentBefore){let r=this.findLastRealMarkerIndex(this.memoryBuffer);if(r!==-1){let n=r+this.ignoreContentBefore.length;this.markerPrefix=this.memoryBuffer.slice(0,n+this.markerTrailingSkip(this.memoryBuffer,n)),this.preview="",this.capturePreview()}}this.memoryBuffer.length>dft&&(this.memoryBuffer=this.memoryBuffer.slice(-dft))}getTailContent(){let e=this.memoryBuffer;if(this.ignoreContentAfter){let r=e.indexOf(this.ignoreContentAfter);r!==-1&&(e=e.slice(0,r))}return e}findLastRealMarkerIndex(e){let r=this.ignoreContentBefore;if(r.endsWith(`
4579
4617
  `))return e.lastIndexOf(r);let n=e.length;for(;n>0;){let s=e.lastIndexOf(r,n-1);if(s===-1)return-1;let l=s+r.length,o=e.indexOf(`
4580
4618
  `,l),a=o!==-1?o:e.length;if(e.substring(l,a).trim()==="")return s;n=s}return-1}markerTrailingSkip(e,r){if(this.ignoreContentBefore.endsWith(`
@@ -4789,7 +4827,7 @@ ${d$}`}}},T8r={...Ua,supports:{tool_choice:!0,parallel_tool_calls:!0,vision:!0},
4789
4827
  <preToolPreamble>
4790
4828
  Before invoking tools, briefly explain the next action and why it is the best next step. Explain with the tool call. Do not use "I will" statements like "I will run" or "I will install", instead use statements without self reference, e.g. "Running" or "Installing".
4791
4829
  </preToolPreamble>`}}},"gpt-4.1":{...Ua,cli:{...Ua.cli,systemMessage:{additionalInstructions:`${sNe}`}}},"oswe-magpie":{...T8r},"oswe-rook":{...T8r}}};Ajs="OPUS_MEDIUM_EFFORT_DEFAULT"});function vK(){return process.env.COPILOT_ENABLE_ALT_PROVIDERS==="true"}async function bhe(t){if(!(await t?.isGptDefaultModelEnabled()??!1))return u9;let r=n=>n.startsWith("gpt-");return[...u9].sort((n,s)=>Number(r(s))-Number(r(n)))}function PRt(t){let e=Lft(t);return e!==void 0&&e.length>0}async function jRt(t,e,r,n){let s=Lft(t);if(!s||s.length===0)return;if(!e)return xft(t,r,n);let l=s.find(o=>o===e);return l||xft(t,r,n)}function S2t(t,e){let r=" ".repeat(e);return t.map(n=>{let s=typeof n=="string"?n:n.id;return`${r}- "${s}"`}).join(`
4792
- `)}function R_r(t){return u9.filter(e=>!t.find(r=>r.id===e))}function m4e(t){return t.policy!==void 0&&t.policy.state!=="enabled"}function HK(t,e=!1){return u9.includes(t)||vK()||e}function W0(t,e,r=!1){return r||!e?!0:!!e.find(s=>s.id===t)}async function B2t(t,e,r){if(e?.staff){let l=await r?.isOpus1mDefaultModelEnabled()??!1?"claude-opus-4.6-1m":"claude-opus-4.6";if(W0(l,t))return l}return(await bhe(r)).find(s=>W0(s,t)&&h4e(s,t)<=1)}function h4e(t,e){if(e&&e.length>0){let n=e.find(s=>s.id===t);if(n?.billing?.multiplier!==void 0)return n.billing.multiplier}return{"claude-sonnet-4.6":1,"claude-sonnet-4":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33,"gpt-5.4":1,"gpt-5.4-mini":.33,"gpt-5.3-codex":1,"gpt-5.2-codex":1,"gpt-5.1-codex":1,"gpt-5.1-codex-mini":.33,"gpt-5.1-codex-max":1,"gpt-5.2":1,"gpt-5.1":1,goldeneye:1,"gpt-5-mini":0,"gpt-4.1":0,"claude-opus-4.5":3,"claude-opus-4.6":3,"claude-opus-4.6-1m":6,"claude-opus-4.6-fast":30}[t]??1}function o2t(t,e,r){return r?0:t?h4e(t,e):1}async function i2t(t,e,r,n){let s=vK()&&process.env.COPILOT_AGENT_MODEL?process.env.COPILOT_AGENT_MODEL:`capi:${t}`;if(PRt(t)){let l=r;if(!l)try{l=(await Ys.load(e)||{}).effortLevel}catch{}let o=await jRt(t,l,e,n);if(o)return`${s}:defaultReasoningEffort=${o}`}return s}async function a2t(t,e,r,n,s=!1,l,o){let a=vK(),I=e?await e?.getSelectedModel?.():void 0,c=process.env.COPILOT_MODEL,d,u,m;try{d=await Ys.load(l)||{},u=typeof d.model=="string"&&d.model?d.model:void 0,m=d.effortLevel}catch{}let h=s?void 0:await B2t(r,d,o),b=d?.staff===!0,p=e?.getReasoningEffort?.(),G={cliModel:t,sessionModel:I??void 0,envModel:c??void 0,configModel:u,defaultModel:h,hasCustomProvider:s,isAltProviders:a,isStaff:b,availableModelCount:r?.length??0,reasoningEffort:p??void 0,configReasoningEffort:m};if(a&&process.env.COPILOT_AGENT_MODEL){let{model:Z}=bd(process.env.COPILOT_AGENT_MODEL);if(Z)return{info:{...G,resolvedModel:Z,source:"alt_provider"}}}if(t){if(W0(t,r,s))return{info:{...G,resolvedModel:t,source:"cli"}};n?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(I){if(W0(I,r,s))return{info:{...G,resolvedModel:I,source:"session"}};n?.warning(`Model '${I}' from session is not available. Falling back to next option.`)}if(c&&HK(c,s)){if(W0(c,r,s))return{info:{...G,resolvedModel:c,source:"env"}};n?.warning(`Model '${c}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}if(!s&&u&&HK(u,s)){if(W0(u,r,s))return{info:{...G,resolvedModel:u,source:"config"}};n?.warning(`Model '${u}' from config file is not available. Falling back to default.`)}return s?(n?.error("Custom provider requires an explicit model. Use --model flag or COPILOT_MODEL env var."),{info:{...G,resolvedModel:void 0,source:"none"}}):(h&&n?.info(`Using default model: ${h}`),{info:{...G,resolvedModel:h,source:h?"default":"none"}})}var u9,Sot,R2i,QXe,wE=g(()=>{"use strict";VX();s0();zp();u9=["claude-sonnet-4.6","claude-sonnet-4.5","claude-haiku-4.5","claude-opus-4.6","claude-opus-4.6-fast","claude-opus-4.6-1m","claude-opus-4.5","claude-sonnet-4","goldeneye","gpt-5.4","gpt-5.3-codex","gpt-5.2-codex","gpt-5.2","gpt-5.1-codex-max","gpt-5.1-codex","gpt-5.1","gpt-5.4-mini","gpt-5.1-codex-mini","gpt-5-mini","gpt-4.1"],Sot=new Set(["claude-opus-4.6-1m","goldeneye"]),R2i=u9.filter(t=>!Sot.has(t));QXe="gpt-5.4"});var O8r=g(()=>{"use strict";EB();Vt()});var M8r=w((w2i,U8r)=>{function Vjs(t){try{return P(t+"/keytar.node")}catch{}}function fjs(){var t="prebuilds/"+process.platform+"-"+process.arch,e=["../build/Release","../"+t,"./"+t];for(var r of e){var n=Vjs(r);if(n)return n}throw new Error("Failed to load keytar native addon, checked "+JSON.stringify(e)+" on "+t)}var Phe=fjs();function cF(t,e){if(!t||t.length<=0)throw new Error(e+" is required.")}U8r.exports={getPassword:function(t,e){return cF(t,"Service"),cF(e,"Account"),Phe.getPassword(t,e)},setPassword:function(t,e,r){return cF(t,"Service"),cF(e,"Account"),cF(r,"Password"),Phe.setPassword(t,e,r)},deletePassword:function(t,e){return cF(t,"Service"),cF(e,"Account"),Phe.deletePassword(t,e)},findPassword:function(t){return cF(t,"Service"),Phe.findPassword(t)},findCredentials:function(t){return cF(t,"Service"),Phe.findCredentials(t)}}});async function jhe(){if(process.env.COPILOT_DISABLE_KEYTAR)throw new Error("Keytar disabled: system keychain unreachable");if(tJe)return tJe;let t=await Promise.resolve().then(()=>fr(M8r(),1));return tJe=t.default||t,tJe}async function Khe(t){return QN(t,wjs,new Error("Keytar operation timed out"),"reject")}var wjs,tJe,z8r=g(()=>{"use strict";HR();wjs=5e3});import{existsSync as _8r}from"fs";var rJe,qhe,Fjs,Jft,D8r=g(()=>{"use strict";zp();z8r();rJe="copilot-cli",qhe=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},Fjs=()=>{let t=new Map,e=async(I,c,d)=>{let u=qhe(I,c);if(u)if(_8r(Ys.path("",d)))try{let b=(await Ys.load(d))?.copilot_tokens?.[u];t.set(u,b&&b.trim()!==""?b:void 0)}catch{t.set(u,void 0)}else t.set(u,void 0)},r=async I=>{if(_8r(Ys.path("",I)))try{let d=(await Ys.load(I))?.copilot_tokens;if(d){let u=Object.values(d).filter(m=>m&&m.trim()!=="");if(u.length>0)return u[0]}}catch{return}},n=async(I,c,d)=>{let u=qhe(I,c);if(!u)return;if(t.has(u))return t.get(u);if((await Ys.load(d))?.storeTokenPlaintext)return await e(I,c,d),t.get(u);try{let h=await jhe(),b=await Khe(h.getPassword(rJe,u));b?t.set(u,b):await e(I,c,d)}catch{await e(I,c,d)}return t.get(u)},s=async I=>{if(t.size>0)return t.values().next().value;if((await Ys.load(I))?.storeTokenPlaintext)return await r(I);let d;try{let u=await jhe();d=await Khe(u.findPassword(rJe))}catch{}return d||(d=await r(I)),d},l=async(I,c,d)=>{let u=qhe(I,c);if(u){t.delete(u);try{let m=await jhe();return await Khe(m.deletePassword(rJe,u))}catch{let b=(await Ys.load(d))?.copilot_tokens??{};return delete b[u],await Ys.writeKey("copilot_tokens",b,"",d),Promise.resolve(!0)}}},o=async(I,c,d,u)=>{if(!I)throw new Error("No token provided to store");let m=qhe(c,d);if(!m)return;if(t.set(m,I),(await Ys.load(u))?.storeTokenPlaintext)return await a(c,d,u),!0;try{let b=await jhe();return await Khe(b.setPassword(rJe,m,I)),!0}catch{return!1}},a=async(I,c,d)=>{let u=qhe(I,c);if(!u)return;let m=t.get(u);if(!m)return;let b=(await Ys.load(d))?.copilot_tokens??{};b[u]=m,await Ys.writeKey("copilot_tokens",b,"",d)};return{getToken:n,getAnyToken:s,removeToken:l,storeToken:o,storeCurrentTokenInConfig:a}},Jft=Fjs()});function uD(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);case"token":return e.onTokenAuthInfo(t);case"copilot-api-token":return e.onCopilotApiTokenAuthInfo(t);default:{let r=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function pd(t){return await uD(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Jft.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{},onTokenAuthInfo:async e=>e.token,onCopilotApiTokenAuthInfo:async()=>{}})}async function b9(t){if(t)try{let e=await t.getCurrentAuthInfo();return e?await uD(e,{onHMACAuthInfo:async()=>{},onApiKeyAuthInfo:async()=>{},onCopilotApiTokenAuthInfo:async()=>{},onEnvAuthInfo:async r=>RB(r.host)?r.token:void 0,onUserAuthInfo:async r=>RB(r.host)&&await Jft.getToken(r.host,r.login)||void 0,onGhCliAuthInfo:async r=>RB(r.host)?r.token:void 0,onTokenAuthInfo:async r=>RB(r.host)?r.token:void 0}):void 0}catch{return}}function O2t(t,e){return!t||t.type==="hmac"||t.type==="copilot-api-token"?`${yB}/${e}`:`${t.host}/${e}`}function E_r(t){return t.host.endsWith(".ghe.com")?{supported:!1,kind:"gheCloud",reason:"Gists are not available for GitHub Enterprise Cloud with data residency (*.ghe.com)."}:RB(t.host)&&"login"in t&&t.login?.includes("_")?{supported:!1,kind:"emuUser",reason:"Gists are not available for Enterprise Managed Users."}:{supported:!0}}var YZ=g(()=>{"use strict";ns();mV();I7();EB();wE();Rw();O8r();D8r();Vt();hv();qfe()});import{readdir as Cjs,readFile as Qjs,stat as vjs}from"node:fs/promises";import Hjs from"node:os";import Xjs,{join as P8r}from"node:path";function j8r(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push(n));return r}async function K8r(t,e,r,n){let s=[],l=[],o=[],a=await q8r(t.userDir,"user",n);if(s.push(...a.agents),l.push(...a.warnings),o.push(...a.errors),e!==null&&r!==null){let I=await mGe(e.path,r,[{kind:"directory",convention:t.projectComponent,componentType:"agents"}]),c=hGe(I);for(let d=0;d<c.length;d++){let u=d===0?"project":"inherited",m=await q8r(c[d],u,n);s.push(...m.agents),l.push(...m.warnings),o.push(...m.errors)}}return{agents:s,warnings:l,errors:o}}async function b4e(t,e,r,n,s,l=!1,o,a,I){let c=s!==null?await KQt(s.path,Pa):null,d=await K8r({userDir:n,projectComponent:".github"},s,c,I),u=await K8r({userDir:Xjs.join(Hjs.homedir(),".claude","agents"),projectComponent:".claude"},s,c,I),m=await kjs(t,o,a),h=j8r([...d.agents,...u.agents,...m.agents]),b=[...d.warnings,...u.warnings,...m.warnings],p=[...d.errors,...u.errors,...m.errors];if(s===null||s.kind!=="git")return{agents:h,warnings:b,errors:p};if(!s.repo)return{agents:h,warnings:[...b,"could not load remote agents, no GitHub remote found"],errors:p};if(l)return{agents:h,warnings:b,errors:p};if(!r)return{agents:h,warnings:[...b,fq(s.repo,"no authentication available")],errors:p};let G=await Ljs(t,e,r,s.repo);return{agents:j8r([...h,...G.agents]),warnings:[...b,...G.warnings],errors:[...p,...G.errors]}}async function kjs(t,e,r){let n=[];try{n=(await Ys.load(r)).installed_plugins||[]}catch(o){t.debug(`Failed to load config for plugin agents: ${String(o)}`)}if(e&&e.length>0&&(n=[...n,...e]),n.length===0)return{agents:[],warnings:[],errors:[]};let s=await kHt(n,r);return{agents:s.agents.map(o=>({id:o.id,name:o.id,displayName:o.displayName,description:o.description,tools:o.tools,prompt:o.prompt,mcpServers:o.mcpServers,disableModelInvocation:o.disableModelInvocation,userInvocable:o.userInvocable,source:"plugin"})),warnings:s.warnings,errors:[]}}function fq(t,e){return`could not load remote agents for ${t.owner}/${t.name}: ${e}`}async function Ljs(t,e,r,n,s=!1){let{host:l}=new URL(r.host);if(l!==n.host)return{agents:[],warnings:[fq(n,`auth info targets ${l} but repo is on ${n.host}`)],errors:[]};let o=await pd(r);if(!o)return{agents:[],warnings:[fq(n,"no usable token for accessing repo contents found")],errors:[]};let a=FA(r);if(!a)return{agents:[],warnings:[fq(n,"Copilot API URL not available")],errors:[]};let I=`${a}/agents/swe/custom-agents/${n.owner}/${n.name}?exclude_invalid_config=true${s?"":"&include_sources=org,enterprise"}`,c={Authorization:`Bearer ${o}`},d=await Mp(I,{method:"GET",headers:c},t);if(!d.ok)return t.warning(`Failed to load custom agents for ${n.owner}/${n.name}: ${await d.text()}`),{agents:[],warnings:[fq(n,`server returned ${d.status}: ${d.statusText}`)],errors:[]};let u=await d.json(),h=me.object({agents:me.array(t7r)}).safeParse(u);return h.success?{agents:h.data.agents.map(b=>({id:b.name,name:b.name,displayName:b.display_name,description:b.description,tools:b.tools,prompt:async()=>{let p=await Bjs({logger:t,integrationId:e,sweAgentsEndpoint:`${a}/agents/swe`,token:o,repoOwner:b.repo_owner,repoName:b.repo_name,customAgentName:b.name});if(!p)throw new Error(`Failed to load prompt for agent ${b.name}`);return p.prompt},mcpServers:ppe(b),disableModelInvocation:b.disable_model_invocation,userInvocable:b.user_invocable??!0,source:"remote",github:b.github??void 0})),warnings:[],errors:[]}:{agents:[],warnings:[fq(n,aT("parsing http response into schema",h.error))],errors:[]}}async function q8r(t,e,r){let n=await Cjs(t,{withFileTypes:!0}).then(I=>({kind:"success",dirEntries:I})).catch(I=>I.code==="ENOENT"?{kind:"success",dirEntries:[]}:{kind:"error",message:aT(t,I)});if(n.kind==="error")return{agents:[],warnings:[],errors:[]};let s=new Map;for(let I of n.dirEntries){if(!I.name.endsWith(".md"))continue;let c=I.isFile();if(I.isSymbolicLink())try{let d=P8r(t,I.name);c=(await vjs(d)).isFile()}catch{continue}if(c){let d=I.name.endsWith(".agent.md"),u=I.name.replace(/(\.agent)?\.md$/,""),m=s.get(u);(!m||d&&!m.isAgentMd)&&s.set(u,{fileName:I.name,isAgentMd:d})}}let l=[],o=[],a=[];for(let[I,{fileName:c}]of s.entries()){let d=P8r(t,c),u=await $8r(d);if(u.kind==="error"){a.push(u.message);continue}u.warnings&&o.push(...u.warnings);let m=u.agent.model;m&&r&&r.length>0&&(r.some(h=>h.id===m)||o.push(`${oV(d)}: model "${m}" is not available; will use current model instead`)),l.push({id:I,name:u.agent.name||I,displayName:u.agent.name||I,description:u.agent.description,tools:u.agent.tools||["*"],prompt:async()=>{let h=await $8r(d);if(h.kind==="error")throw new Error(h.message);return await h.agent.prompt()},mcpServers:u.agent.mcpServers,disableModelInvocation:u.agent.disableModelInvocation,userInvocable:u.agent.userInvocable,source:e,model:u.agent.model})}return{agents:l,warnings:o,errors:a}}async function $8r(t){let e=oV(t),r=await xjs(()=>Qjs(t,"utf-8"),l=>aT(e,l));if(r.kind==="error")return{kind:"error",message:r.message};let n=kGe(r.value);if(n.kind==="error")return{kind:"error",message:`${e}: ${n.message}`};let s=n.warnings?.map(l=>`${e}: ${l}`);return{kind:"success",agent:n.agent,warnings:s}}function kGe(t){let e=me.preprocess(o=>typeof o=="string"?o.split(",").map(a=>a.trim()).filter(Boolean):o,me.array(me.string()).optional()),r=me.object({name:me.string().optional(),description:me.string(),tools:e,"mcp-servers":e7r,infer:me.boolean().optional(),"disable-model-invocation":me.boolean().optional(),"user-invocable":me.boolean().optional(),model:me.string().optional(),github:me.object({toolsets:me.array(me.string()).optional(),permissions:me.record(me.string(),me.string()).optional()}).optional()}),n=nV(t,{schema:r});if(n.kind==="error")return{kind:"error",message:`custom agent markdown frontmatter is malformed: ${n.message}`};let s=[...n.warnings??[]],l=n.value.frontmatter;return{kind:"success",agent:{name:l.name??"",displayName:l.name??"",description:l.description,tools:l.tools||["*"],prompt:()=>Promise.resolve(n.value.body),mcpServers:ppe({mcp_servers:l["mcp-servers"],github:l.github}),disableModelInvocation:l["disable-model-invocation"]??(l.infer!==void 0?!l.infer:!1),userInvocable:l["user-invocable"]??!0,model:l.model,github:l.github},warnings:s.length>0?s:void 0}}async function xjs(t,e){try{return{kind:"success",value:await t()}}catch(r){return{kind:"error",message:e(r)}}}async function Bjs(t){t.logger.info(`Reading custom agent "${t.customAgentName}" from ${t.repoOwner}/${t.repoName}`);try{let e={"Copilot-Integration-Id":t.integrationId,Authorization:`Bearer ${t.token}`,"X-GitHub-Job-Nonce":t.jobNonce??""},r=await Mp(`${t.sweAgentsEndpoint}/custom-agents/${t.repoOwner}/${t.repoName}/${t.customAgentName}`,{method:"GET",headers:e},t.logger,"get custom agent config");if(!r.ok){if(r.status===404)return null;throw new Error(`Failed to get custom agent config: ${r.status} ${r.statusText}`)}let n=await r.json();return Tjs.parse(n)}catch(e){let r=e,n=r?.requestId||"unknown";throw t.logger.error(`Failed to get custom agent config (request ID: ${n}): ${r}`),r}}var Jjs,Sjs,e7r,t7r,Tjs,LGe=g(()=>{"use strict";$t();I8();Vt();AT();ak();$9e();Bs();LHt();YZ();Rw();L0();zp();Jjs=me.object({command:me.string(),args:me.array(me.string()),cwd:me.string().optional(),env:me.record(me.string(),me.string()).optional(),tools:me.array(me.string()),type:me.enum(["local","stdio"]).optional()}),Sjs=me.object({url:me.string(),headers:me.record(me.string(),me.string()).optional(),tools:me.array(me.string()),type:me.enum(["http","sse"])}),e7r=me.record(me.string(),me.union([Jjs,Sjs])).optional().nullable(),t7r=me.object({name:me.string(),repo_owner:me.string(),repo_name:me.string(),display_name:me.string(),description:me.string(),tools:me.array(me.string()),version:me.string(),mcp_servers:e7r,disable_model_invocation:me.boolean(),user_invocable:me.boolean().optional(),github:me.object({toolsets:me.array(me.string()).optional(),permissions:me.record(me.string(),me.string()).optional()}).optional().nullable()}),Tjs=t7r.extend({prompt:me.string()})});import Ojs from"node:path";async function FEi(t,e,r,n,s,l){r??=QK,n??=new Dp;let o=await n4e(e),{agents:a}=await b4e(n,r,t,Ojs.join(Ao(s,"config"),"agents"),o,!1,l,s);return a.map(I=>({name:I.id,displayName:I.displayName,description:I.description,tools:I.tools,prompt:I.prompt,mcpServers:I.mcpServers||{},disableModelInvocation:I.disableModelInvocation}))}var r7r=g(()=>{"use strict";LGe();BRt();Bs();t4e();t5()});var Tp,n7r=g(()=>{"use strict";o4e();mk();Tp=Evt(hUr.parse,"session")});import{readdir as Ujs,stat as Mjs}from"fs/promises";import{join as zjs}from"path";async function $he(t){try{let e=await Ujs(t,{withFileTypes:!0});return(await Promise.all(e.map(async n=>{try{let s=zjs(t,n.name);if(n.isDirectory())return $he(s);if(n.isFile())return(await Mjs(s)).size}catch{}return 0}))).reduce((n,s)=>n+s,0)}catch{return 0}}var s7r=g(()=>{"use strict"});import*as y5 from"node:fs/promises";import _js from"node:path";function Kjs(t,e){return _js.join(t,`${Djs}${e}${Pjs}`)}function qjs(t){try{return process.kill(t,0),!0}catch(e){return!(e&&typeof e=="object"&&"code"in e&&e.code==="ESRCH")}}async function $js(t){let e;try{e=await y5.readdir(t)}catch{return[]}let r=[];for(let n of e){let s=jjs.exec(n);s&&r.push({file:n,pid:Number(s[1])})}return r}async function l7r(t){let e=Kjs(t,process.pid);try{await y5.mkdir(t,{recursive:!0}),await y5.writeFile(e,`${process.pid}
4830
+ `)}function R_r(t){return u9.filter(e=>!t.find(r=>r.id===e))}function m4e(t){return t.policy!==void 0&&t.policy.state!=="enabled"}function HK(t,e=!1){return u9.includes(t)||vK()||e}function W0(t,e,r=!1){return r||!e?!0:!!e.find(s=>s.id===t)}async function B2t(t,e,r){if(e?.staff){let l=await r?.isOpus1mDefaultModelEnabled()??!1?"claude-opus-4.6-1m":"claude-opus-4.6";if(W0(l,t))return l}return(await bhe(r)).find(s=>W0(s,t)&&h4e(s,t)<=1)}function h4e(t,e){if(e&&e.length>0){let n=e.find(s=>s.id===t);if(n?.billing?.multiplier!==void 0)return n.billing.multiplier}return{"claude-sonnet-4.6":1,"claude-sonnet-4":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33,"gpt-5.4":1,"gpt-5.4-mini":.33,"gpt-5.3-codex":1,"gpt-5.2-codex":1,"gpt-5.2":1,"gpt-5.1":1,goldeneye:1,"gpt-5-mini":0,"gpt-4.1":0,"claude-opus-4.5":3,"claude-opus-4.6":3,"claude-opus-4.6-1m":6,"claude-opus-4.6-fast":30}[t]??1}function o2t(t,e,r){return r?0:t?h4e(t,e):1}async function i2t(t,e,r,n){let s=vK()&&process.env.COPILOT_AGENT_MODEL?process.env.COPILOT_AGENT_MODEL:`capi:${t}`;if(PRt(t)){let l=r;if(!l)try{l=(await Ys.load(e)||{}).effortLevel}catch{}let o=await jRt(t,l,e,n);if(o)return`${s}:defaultReasoningEffort=${o}`}return s}async function a2t(t,e,r,n,s=!1,l,o){let a=vK(),I=e?await e?.getSelectedModel?.():void 0,c=process.env.COPILOT_MODEL,d,u,m;try{d=await Ys.load(l)||{},u=typeof d.model=="string"&&d.model?d.model:void 0,m=d.effortLevel}catch{}let h=s?void 0:await B2t(r,d,o),b=d?.staff===!0,p=e?.getReasoningEffort?.(),G={cliModel:t,sessionModel:I??void 0,envModel:c??void 0,configModel:u,defaultModel:h,hasCustomProvider:s,isAltProviders:a,isStaff:b,availableModelCount:r?.length??0,reasoningEffort:p??void 0,configReasoningEffort:m};if(a&&process.env.COPILOT_AGENT_MODEL){let{model:Z}=bd(process.env.COPILOT_AGENT_MODEL);if(Z)return{info:{...G,resolvedModel:Z,source:"alt_provider"}}}if(t){if(W0(t,r,s))return{info:{...G,resolvedModel:t,source:"cli"}};n?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(I){if(W0(I,r,s))return{info:{...G,resolvedModel:I,source:"session"}};n?.warning(`Model '${I}' from session is not available. Falling back to next option.`)}if(c&&HK(c,s)){if(W0(c,r,s))return{info:{...G,resolvedModel:c,source:"env"}};n?.warning(`Model '${c}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}if(!s&&u&&HK(u,s)){if(W0(u,r,s))return{info:{...G,resolvedModel:u,source:"config"}};n?.warning(`Model '${u}' from config file is not available. Falling back to default.`)}return s?(n?.error("Custom provider requires an explicit model. Use --model flag or COPILOT_MODEL env var."),{info:{...G,resolvedModel:void 0,source:"none"}}):(h&&n?.info(`Using default model: ${h}`),{info:{...G,resolvedModel:h,source:h?"default":"none"}})}var u9,Sot,R2i,QXe,wE=g(()=>{"use strict";VX();s0();zp();u9=["claude-sonnet-4.6","claude-sonnet-4.5","claude-haiku-4.5","claude-opus-4.6","claude-opus-4.6-fast","claude-opus-4.6-1m","claude-opus-4.5","claude-sonnet-4","goldeneye","gpt-5.4","gpt-5.3-codex","gpt-5.2-codex","gpt-5.2","gpt-5.1","gpt-5.4-mini","gpt-5-mini","gpt-4.1"],Sot=new Set(["claude-opus-4.6-1m","goldeneye"]),R2i=u9.filter(t=>!Sot.has(t));QXe="gpt-5.4"});var O8r=g(()=>{"use strict";EB();Vt()});var M8r=w((w2i,U8r)=>{function Vjs(t){try{return P(t+"/keytar.node")}catch{}}function fjs(){var t="prebuilds/"+process.platform+"-"+process.arch,e=["../build/Release","../"+t,"./"+t];for(var r of e){var n=Vjs(r);if(n)return n}throw new Error("Failed to load keytar native addon, checked "+JSON.stringify(e)+" on "+t)}var Phe=fjs();function cF(t,e){if(!t||t.length<=0)throw new Error(e+" is required.")}U8r.exports={getPassword:function(t,e){return cF(t,"Service"),cF(e,"Account"),Phe.getPassword(t,e)},setPassword:function(t,e,r){return cF(t,"Service"),cF(e,"Account"),cF(r,"Password"),Phe.setPassword(t,e,r)},deletePassword:function(t,e){return cF(t,"Service"),cF(e,"Account"),Phe.deletePassword(t,e)},findPassword:function(t){return cF(t,"Service"),Phe.findPassword(t)},findCredentials:function(t){return cF(t,"Service"),Phe.findCredentials(t)}}});async function jhe(){if(process.env.COPILOT_DISABLE_KEYTAR)throw new Error("Keytar disabled: system keychain unreachable");if(tJe)return tJe;let t=await Promise.resolve().then(()=>fr(M8r(),1));return tJe=t.default||t,tJe}async function Khe(t){return QN(t,wjs,new Error("Keytar operation timed out"),"reject")}var wjs,tJe,z8r=g(()=>{"use strict";HR();wjs=5e3});import{existsSync as _8r}from"fs";var rJe,qhe,Fjs,Jft,D8r=g(()=>{"use strict";zp();z8r();rJe="copilot-cli",qhe=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},Fjs=()=>{let t=new Map,e=async(I,c,d)=>{let u=qhe(I,c);if(u)if(_8r(Ys.path("",d)))try{let b=(await Ys.load(d))?.copilot_tokens?.[u];t.set(u,b&&b.trim()!==""?b:void 0)}catch{t.set(u,void 0)}else t.set(u,void 0)},r=async I=>{if(_8r(Ys.path("",I)))try{let d=(await Ys.load(I))?.copilot_tokens;if(d){let u=Object.values(d).filter(m=>m&&m.trim()!=="");if(u.length>0)return u[0]}}catch{return}},n=async(I,c,d)=>{let u=qhe(I,c);if(!u)return;if(t.has(u))return t.get(u);if((await Ys.load(d))?.storeTokenPlaintext)return await e(I,c,d),t.get(u);try{let h=await jhe(),b=await Khe(h.getPassword(rJe,u));b?t.set(u,b):await e(I,c,d)}catch{await e(I,c,d)}return t.get(u)},s=async I=>{if(t.size>0)return t.values().next().value;if((await Ys.load(I))?.storeTokenPlaintext)return await r(I);let d;try{let u=await jhe();d=await Khe(u.findPassword(rJe))}catch{}return d||(d=await r(I)),d},l=async(I,c,d)=>{let u=qhe(I,c);if(u){t.delete(u);try{let m=await jhe();return await Khe(m.deletePassword(rJe,u))}catch{let b=(await Ys.load(d))?.copilot_tokens??{};return delete b[u],await Ys.writeKey("copilot_tokens",b,"",d),Promise.resolve(!0)}}},o=async(I,c,d,u)=>{if(!I)throw new Error("No token provided to store");let m=qhe(c,d);if(!m)return;if(t.set(m,I),(await Ys.load(u))?.storeTokenPlaintext)return await a(c,d,u),!0;try{let b=await jhe();return await Khe(b.setPassword(rJe,m,I)),!0}catch{return!1}},a=async(I,c,d)=>{let u=qhe(I,c);if(!u)return;let m=t.get(u);if(!m)return;let b=(await Ys.load(d))?.copilot_tokens??{};b[u]=m,await Ys.writeKey("copilot_tokens",b,"",d)};return{getToken:n,getAnyToken:s,removeToken:l,storeToken:o,storeCurrentTokenInConfig:a}},Jft=Fjs()});function uD(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);case"token":return e.onTokenAuthInfo(t);case"copilot-api-token":return e.onCopilotApiTokenAuthInfo(t);default:{let r=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function pd(t){return await uD(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Jft.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{},onTokenAuthInfo:async e=>e.token,onCopilotApiTokenAuthInfo:async()=>{}})}async function b9(t){if(t)try{let e=await t.getCurrentAuthInfo();return e?await uD(e,{onHMACAuthInfo:async()=>{},onApiKeyAuthInfo:async()=>{},onCopilotApiTokenAuthInfo:async()=>{},onEnvAuthInfo:async r=>RB(r.host)?r.token:void 0,onUserAuthInfo:async r=>RB(r.host)&&await Jft.getToken(r.host,r.login)||void 0,onGhCliAuthInfo:async r=>RB(r.host)?r.token:void 0,onTokenAuthInfo:async r=>RB(r.host)?r.token:void 0}):void 0}catch{return}}function O2t(t,e){return!t||t.type==="hmac"||t.type==="copilot-api-token"?`${yB}/${e}`:`${t.host}/${e}`}function E_r(t){return t.host.endsWith(".ghe.com")?{supported:!1,kind:"gheCloud",reason:"Gists are not available for GitHub Enterprise Cloud with data residency (*.ghe.com)."}:RB(t.host)&&"login"in t&&t.login?.includes("_")?{supported:!1,kind:"emuUser",reason:"Gists are not available for Enterprise Managed Users."}:{supported:!0}}var YZ=g(()=>{"use strict";ns();mV();I7();EB();wE();Rw();O8r();D8r();Vt();hv();qfe()});import{readdir as Cjs,readFile as Qjs,stat as vjs}from"node:fs/promises";import Hjs from"node:os";import Xjs,{join as P8r}from"node:path";function j8r(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push(n));return r}async function K8r(t,e,r,n){let s=[],l=[],o=[],a=await q8r(t.userDir,"user",n);if(s.push(...a.agents),l.push(...a.warnings),o.push(...a.errors),e!==null&&r!==null){let I=await mGe(e.path,r,[{kind:"directory",convention:t.projectComponent,componentType:"agents"}]),c=hGe(I);for(let d=0;d<c.length;d++){let u=d===0?"project":"inherited",m=await q8r(c[d],u,n);s.push(...m.agents),l.push(...m.warnings),o.push(...m.errors)}}return{agents:s,warnings:l,errors:o}}async function b4e(t,e,r,n,s,l=!1,o,a,I){let c=s!==null?await KQt(s.path,Pa):null,d=await K8r({userDir:n,projectComponent:".github"},s,c,I),u=await K8r({userDir:Xjs.join(Hjs.homedir(),".claude","agents"),projectComponent:".claude"},s,c,I),m=await kjs(t,o,a),h=j8r([...d.agents,...u.agents,...m.agents]),b=[...d.warnings,...u.warnings,...m.warnings],p=[...d.errors,...u.errors,...m.errors];if(s===null||s.kind!=="git")return{agents:h,warnings:b,errors:p};if(!s.repo)return{agents:h,warnings:[...b,"could not load remote agents, no GitHub remote found"],errors:p};if(l)return{agents:h,warnings:b,errors:p};if(!r)return{agents:h,warnings:[...b,fq(s.repo,"no authentication available")],errors:p};let G=await Ljs(t,e,r,s.repo);return{agents:j8r([...h,...G.agents]),warnings:[...b,...G.warnings],errors:[...p,...G.errors]}}async function kjs(t,e,r){let n=[];try{n=(await Ys.load(r)).installed_plugins||[]}catch(o){t.debug(`Failed to load config for plugin agents: ${String(o)}`)}if(e&&e.length>0&&(n=[...n,...e]),n.length===0)return{agents:[],warnings:[],errors:[]};let s=await kHt(n,r);return{agents:s.agents.map(o=>({id:o.id,name:o.id,displayName:o.displayName,description:o.description,tools:o.tools,prompt:o.prompt,mcpServers:o.mcpServers,disableModelInvocation:o.disableModelInvocation,userInvocable:o.userInvocable,source:"plugin"})),warnings:s.warnings,errors:[]}}function fq(t,e){return`could not load remote agents for ${t.owner}/${t.name}: ${e}`}async function Ljs(t,e,r,n,s=!1){let{host:l}=new URL(r.host);if(l!==n.host)return{agents:[],warnings:[fq(n,`auth info targets ${l} but repo is on ${n.host}`)],errors:[]};let o=await pd(r);if(!o)return{agents:[],warnings:[fq(n,"no usable token for accessing repo contents found")],errors:[]};let a=FA(r);if(!a)return{agents:[],warnings:[fq(n,"Copilot API URL not available")],errors:[]};let I=`${a}/agents/swe/custom-agents/${n.owner}/${n.name}?exclude_invalid_config=true${s?"":"&include_sources=org,enterprise"}`,c={Authorization:`Bearer ${o}`},d=await Mp(I,{method:"GET",headers:c},t);if(!d.ok)return t.warning(`Failed to load custom agents for ${n.owner}/${n.name}: ${await d.text()}`),{agents:[],warnings:[fq(n,`server returned ${d.status}: ${d.statusText}`)],errors:[]};let u=await d.json(),h=me.object({agents:me.array(t7r)}).safeParse(u);return h.success?{agents:h.data.agents.map(b=>({id:b.name,name:b.name,displayName:b.display_name,description:b.description,tools:b.tools,prompt:async()=>{let p=await Bjs({logger:t,integrationId:e,sweAgentsEndpoint:`${a}/agents/swe`,token:o,repoOwner:b.repo_owner,repoName:b.repo_name,customAgentName:b.name});if(!p)throw new Error(`Failed to load prompt for agent ${b.name}`);return p.prompt},mcpServers:ppe(b),disableModelInvocation:b.disable_model_invocation,userInvocable:b.user_invocable??!0,source:"remote",github:b.github??void 0})),warnings:[],errors:[]}:{agents:[],warnings:[fq(n,aT("parsing http response into schema",h.error))],errors:[]}}async function q8r(t,e,r){let n=await Cjs(t,{withFileTypes:!0}).then(I=>({kind:"success",dirEntries:I})).catch(I=>I.code==="ENOENT"?{kind:"success",dirEntries:[]}:{kind:"error",message:aT(t,I)});if(n.kind==="error")return{agents:[],warnings:[],errors:[]};let s=new Map;for(let I of n.dirEntries){if(!I.name.endsWith(".md"))continue;let c=I.isFile();if(I.isSymbolicLink())try{let d=P8r(t,I.name);c=(await vjs(d)).isFile()}catch{continue}if(c){let d=I.name.endsWith(".agent.md"),u=I.name.replace(/(\.agent)?\.md$/,""),m=s.get(u);(!m||d&&!m.isAgentMd)&&s.set(u,{fileName:I.name,isAgentMd:d})}}let l=[],o=[],a=[];for(let[I,{fileName:c}]of s.entries()){let d=P8r(t,c),u=await $8r(d);if(u.kind==="error"){a.push(u.message);continue}u.warnings&&o.push(...u.warnings);let m=u.agent.model;m&&r&&r.length>0&&(r.some(h=>h.id===m)||o.push(`${oV(d)}: model "${m}" is not available; will use current model instead`)),l.push({id:I,name:u.agent.name||I,displayName:u.agent.name||I,description:u.agent.description,tools:u.agent.tools||["*"],prompt:async()=>{let h=await $8r(d);if(h.kind==="error")throw new Error(h.message);return await h.agent.prompt()},mcpServers:u.agent.mcpServers,disableModelInvocation:u.agent.disableModelInvocation,userInvocable:u.agent.userInvocable,source:e,model:u.agent.model})}return{agents:l,warnings:o,errors:a}}async function $8r(t){let e=oV(t),r=await xjs(()=>Qjs(t,"utf-8"),l=>aT(e,l));if(r.kind==="error")return{kind:"error",message:r.message};let n=kGe(r.value);if(n.kind==="error")return{kind:"error",message:`${e}: ${n.message}`};let s=n.warnings?.map(l=>`${e}: ${l}`);return{kind:"success",agent:n.agent,warnings:s}}function kGe(t){let e=me.preprocess(o=>typeof o=="string"?o.split(",").map(a=>a.trim()).filter(Boolean):o,me.array(me.string()).optional()),r=me.object({name:me.string().optional(),description:me.string(),tools:e,"mcp-servers":e7r,infer:me.boolean().optional(),"disable-model-invocation":me.boolean().optional(),"user-invocable":me.boolean().optional(),model:me.string().optional(),github:me.object({toolsets:me.array(me.string()).optional(),permissions:me.record(me.string(),me.string()).optional()}).optional()}),n=nV(t,{schema:r});if(n.kind==="error")return{kind:"error",message:`custom agent markdown frontmatter is malformed: ${n.message}`};let s=[...n.warnings??[]],l=n.value.frontmatter;return{kind:"success",agent:{name:l.name??"",displayName:l.name??"",description:l.description,tools:l.tools||["*"],prompt:()=>Promise.resolve(n.value.body),mcpServers:ppe({mcp_servers:l["mcp-servers"],github:l.github}),disableModelInvocation:l["disable-model-invocation"]??(l.infer!==void 0?!l.infer:!1),userInvocable:l["user-invocable"]??!0,model:l.model,github:l.github},warnings:s.length>0?s:void 0}}async function xjs(t,e){try{return{kind:"success",value:await t()}}catch(r){return{kind:"error",message:e(r)}}}async function Bjs(t){t.logger.info(`Reading custom agent "${t.customAgentName}" from ${t.repoOwner}/${t.repoName}`);try{let e={"Copilot-Integration-Id":t.integrationId,Authorization:`Bearer ${t.token}`,"X-GitHub-Job-Nonce":t.jobNonce??""},r=await Mp(`${t.sweAgentsEndpoint}/custom-agents/${t.repoOwner}/${t.repoName}/${t.customAgentName}`,{method:"GET",headers:e},t.logger,"get custom agent config");if(!r.ok){if(r.status===404)return null;throw new Error(`Failed to get custom agent config: ${r.status} ${r.statusText}`)}let n=await r.json();return Tjs.parse(n)}catch(e){let r=e,n=r?.requestId||"unknown";throw t.logger.error(`Failed to get custom agent config (request ID: ${n}): ${r}`),r}}var Jjs,Sjs,e7r,t7r,Tjs,LGe=g(()=>{"use strict";$t();I8();Vt();AT();ak();$9e();Bs();LHt();YZ();Rw();L0();zp();Jjs=me.object({command:me.string(),args:me.array(me.string()),cwd:me.string().optional(),env:me.record(me.string(),me.string()).optional(),tools:me.array(me.string()),type:me.enum(["local","stdio"]).optional()}),Sjs=me.object({url:me.string(),headers:me.record(me.string(),me.string()).optional(),tools:me.array(me.string()),type:me.enum(["http","sse"])}),e7r=me.record(me.string(),me.union([Jjs,Sjs])).optional().nullable(),t7r=me.object({name:me.string(),repo_owner:me.string(),repo_name:me.string(),display_name:me.string(),description:me.string(),tools:me.array(me.string()),version:me.string(),mcp_servers:e7r,disable_model_invocation:me.boolean(),user_invocable:me.boolean().optional(),github:me.object({toolsets:me.array(me.string()).optional(),permissions:me.record(me.string(),me.string()).optional()}).optional().nullable()}),Tjs=t7r.extend({prompt:me.string()})});import Ojs from"node:path";async function FEi(t,e,r,n,s,l){r??=QK,n??=new Dp;let o=await n4e(e),{agents:a}=await b4e(n,r,t,Ojs.join(Ao(s,"config"),"agents"),o,!1,l,s);return a.map(I=>({name:I.id,displayName:I.displayName,description:I.description,tools:I.tools,prompt:I.prompt,mcpServers:I.mcpServers||{},disableModelInvocation:I.disableModelInvocation}))}var r7r=g(()=>{"use strict";LGe();BRt();Bs();t4e();t5()});var Tp,n7r=g(()=>{"use strict";o4e();mk();Tp=Evt(hUr.parse,"session")});import{readdir as Ujs,stat as Mjs}from"fs/promises";import{join as zjs}from"path";async function $he(t){try{let e=await Ujs(t,{withFileTypes:!0});return(await Promise.all(e.map(async n=>{try{let s=zjs(t,n.name);if(n.isDirectory())return $he(s);if(n.isFile())return(await Mjs(s)).size}catch{}return 0}))).reduce((n,s)=>n+s,0)}catch{return 0}}var s7r=g(()=>{"use strict"});import*as y5 from"node:fs/promises";import _js from"node:path";function Kjs(t,e){return _js.join(t,`${Djs}${e}${Pjs}`)}function qjs(t){try{return process.kill(t,0),!0}catch(e){return!(e&&typeof e=="object"&&"code"in e&&e.code==="ESRCH")}}async function $js(t){let e;try{e=await y5.readdir(t)}catch{return[]}let r=[];for(let n of e){let s=jjs.exec(n);s&&r.push({file:n,pid:Number(s[1])})}return r}async function l7r(t){let e=Kjs(t,process.pid);try{await y5.mkdir(t,{recursive:!0}),await y5.writeFile(e,`${process.pid}
4793
4831
  `,"utf8")}catch(r){return te.info(`Failed to create in-use lock file ${e}: ${D(r)}`),{dispose:async()=>{}}}return{dispose:async()=>{try{await y5.rm(e,{force:!0})}catch(r){te.info(`Failed to remove in-use lock file ${e}: ${D(r)}`)}}}}async function o7r(t){return(await $js(t)).some(({pid:r})=>qjs(r))}var Djs,Pjs,jjs,i7r=g(()=>{"use strict";ns();Vt();Djs="inuse.",Pjs=".lock",jjs=/^inuse\.(\d+)\.lock$/});function a7r(){let t=process.env.COPILOT_OTEL_ENABLED?.toLowerCase()==="true",e=!!process.env.OTEL_EXPORTER_OTLP_ENDPOINT,r=!!process.env.COPILOT_OTEL_FILE_EXPORTER_PATH;if(!t&&!e&&!r)return null;let n=process.env.COPILOT_OTEL_EXPORTER_TYPE?.toLowerCase(),s="otlp-http";return n==="file"&&(s=n),r&&!n&&(s="file"),{enabled:!0,captureContent:process.env[t6s]?.toLowerCase()==="true",exporterType:s,filePath:process.env.COPILOT_OTEL_FILE_EXPORTER_PATH,sourceName:process.env.COPILOT_OTEL_SOURCE_NAME??e6s}}var e6s,t6s,I7r=g(()=>{"use strict";e6s="github.copilot",t6s="OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"});var c7r,d7r=g(()=>{c7r=typeof globalThis=="object"?globalThis:global});var u7r=g(()=>{d7r()});var m7r=g(()=>{u7r()});var dF,Sft=g(()=>{dF="1.9.0"});function r6s(t){var e=new Set([t]),r=new Set,n=t.match(h7r);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(I){return I===t};function l(a){return r.add(a),!1}function o(a){return e.add(a),!0}return function(I){if(e.has(I))return!0;if(r.has(I))return!1;var c=I.match(h7r);if(!c)return l(I);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||s.major!==d.major?l(I):s.major===0?s.minor===d.minor&&s.patch<=d.patch?o(I):l(I):s.minor<=d.minor?o(I):l(I)}}var h7r,b7r,p7r=g(()=>{Sft();h7r=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;b7r=r6s(dF)});function JY(t,e,r,n){var s;n===void 0&&(n=!1);var l=tbe[ebe]=(s=tbe[ebe])!==null&&s!==void 0?s:{version:dF};if(!n&&l[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(l.version!==dF){var o=new Error("@opentelemetry/api: Registration of version v"+l.version+" for "+t+" does not match previously registered API v"+dF);return r.error(o.stack||o.message),!1}return l[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+dF+"."),!0}function lN(t){var e,r,n=(e=tbe[ebe])===null||e===void 0?void 0:e.version;if(!(!n||!b7r(n)))return(r=tbe[ebe])===null||r===void 0?void 0:r[t]}function SY(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+dF+".");var r=tbe[ebe];r&&delete r[t]}var n6s,ebe,tbe,X9=g(()=>{m7r();Sft();p7r();n6s=dF.split(".")[0],ebe=Symbol.for("opentelemetry.js.api."+n6s),tbe=c7r});function rbe(t,e,r){var n=lN("diag");if(n)return r.unshift(e),n[t].apply(n,l6s([],s6s(r),!1))}var s6s,l6s,G7r,g7r=g(()=>{X9();s6s=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,l=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)l.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return l},l6s=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,l;n<s;n++)(l||!(n in e))&&(l||(l=Array.prototype.slice.call(e,0,n)),l[n]=e[n]);return t.concat(l||Array.prototype.slice.call(e))},G7r=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return rbe("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return rbe("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return rbe("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return rbe("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return rbe("verbose",this._namespace,e)},t})()});var Mm,nJe=g(()=>{(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Mm||(Mm={}))});function Z7r(t,e){t<Mm.NONE?t=Mm.NONE:t>Mm.ALL&&(t=Mm.ALL),e=e||{};function r(n,s){var l=e[n];return typeof l=="function"&&t>=s?l.bind(e):function(){}}return{error:r("error",Mm.ERROR),warn:r("warn",Mm.WARN),info:r("info",Mm.INFO),debug:r("debug",Mm.DEBUG),verbose:r("verbose",Mm.VERBOSE)}}var N7r=g(()=>{nJe()});var o6s,i6s,a6s,ob,k9=g(()=>{g7r();N7r();nJe();X9();o6s=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,l=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)l.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return l},i6s=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,l;n<s;n++)(l||!(n in e))&&(l||(l=Array.prototype.slice.call(e,0,n)),l[n]=e[n]);return t.concat(l||Array.prototype.slice.call(e))},a6s="diag",ob=(function(){function t(){function e(s){return function(){for(var l=[],o=0;o<arguments.length;o++)l[o]=arguments[o];var a=lN("diag");if(a)return a[s].apply(a,i6s([],o6s(l),!1))}}var r=this,n=function(s,l){var o,a,I;if(l===void 0&&(l={logLevel:Mm.INFO}),s===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof l=="number"&&(l={logLevel:l});var d=lN("diag"),u=Z7r((a=l.logLevel)!==null&&a!==void 0?a:Mm.INFO,s);if(d&&!l.suppressOverrideMessage){var m=(I=new Error().stack)!==null&&I!==void 0?I:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+m),u.warn("Current logger will overwrite one already registered from "+m)}return JY("diag",u,r,!0)};r.setLogger=n,r.disable=function(){SY(a6s,r)},r.createComponentLogger=function(s){return new G7r(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})()});var I6s,c6s,A7r,W7r=g(()=>{I6s=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,l=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)l.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return l},c6s=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A7r=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=I6s(e,2),n=r[0],s=r[1];return[n,s]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var l=new t(this._entries);try{for(var o=c6s(n),a=o.next();!a.done;a=o.next()){var I=a.value;l._entries.delete(I)}}catch(c){e={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return l},t.prototype.clear=function(){return new t},t})()});var y7r,R7r=g(()=>{y7r=Symbol("BaggageEntryMetadata")});function E7r(t){return t===void 0&&(t={}),new A7r(new Map(Object.entries(t)))}function sJe(t){return typeof t!="string"&&(d6s.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:y7r,toString:function(){return t}}}var d6s,Tft=g(()=>{k9();W7r();R7r();d6s=ob.instance()});function R5(t){return Symbol.for(t)}var u6s,E5,nbe=g(()=>{u6s=(function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var l=new t(r._currentContext);return l._currentContext.set(n,s),l},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t})(),E5=new u6s});var Bft,Y7r,V7r=g(()=>{Bft=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],Y7r=(function(){function t(){function e(n){return function(){for(var s=[],l=0;l<arguments.length;l++)s[l]=arguments[l];if(console){var o=console[n];if(typeof o!="function"&&(o=console.log),typeof o=="function")return o.apply(console,s)}}}for(var r=0;r<Bft.length;r++)this[Bft[r].n]=e(Bft[r].c)}return t})()});function wq(){return Uft}var L9,m6s,lJe,h6s,b6s,p6s,G6s,Oft,g6s,Z6s,N6s,Uft,A6s,W6s,y6s,R6s,E6s,Y6s,V6s,Mft=g(()=>{L9=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var l in s)Object.prototype.hasOwnProperty.call(s,l)&&(n[l]=s[l])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),m6s=(function(){function t(){}return t.prototype.createGauge=function(e,r){return W6s},t.prototype.createHistogram=function(e,r){return y6s},t.prototype.createCounter=function(e,r){return A6s},t.prototype.createUpDownCounter=function(e,r){return R6s},t.prototype.createObservableGauge=function(e,r){return Y6s},t.prototype.createObservableCounter=function(e,r){return E6s},t.prototype.createObservableUpDownCounter=function(e,r){return V6s},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t})(),lJe=(function(){function t(){}return t})(),h6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(lJe),b6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(lJe),p6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(lJe),G6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(lJe),Oft=(function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t})(),g6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Oft),Z6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Oft),N6s=(function(t){L9(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Oft),Uft=new m6s,A6s=new h6s,W6s=new p6s,y6s=new G6s,R6s=new b6s,E6s=new g6s,Y6s=new Z6s,V6s=new N6s});var yg,f7r=g(()=>{(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(yg||(yg={}))});var oJe,iJe,zft=g(()=>{oJe={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},iJe={set:function(t,e,r){t!=null&&(t[e]=r)}}});var f6s,w6s,w7r,F7r=g(()=>{nbe();f6s=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,l=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)l.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return l},w6s=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,l;n<s;n++)(l||!(n in e))&&(l||(l=Array.prototype.slice.call(e,0,n)),l[n]=e[n]);return t.concat(l||Array.prototype.slice.call(e))},w7r=(function(){function t(){}return t.prototype.active=function(){return E5},t.prototype.with=function(e,r,n){for(var s=[],l=3;l<arguments.length;l++)s[l-3]=arguments[l];return r.call.apply(r,w6s([n],f6s(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})()});var F6s,C6s,_ft,Q6s,Y5,sbe=g(()=>{F7r();X9();k9();F6s=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,l=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)l.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return l},C6s=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,l;n<s;n++)(l||!(n in e))&&(l||(l=Array.prototype.slice.call(e,0,n)),l[n]=e[n]);return t.concat(l||Array.prototype.slice.call(e))},_ft="context",Q6s=new w7r,Y5=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return JY(_ft,e,ob.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,l=[],o=3;o<arguments.length;o++)l[o-3]=arguments[o];return(s=this._getContextManager()).with.apply(s,C6s([e,r,n],F6s(l),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return lN(_ft)||Q6s},t.prototype.disable=function(){this._getContextManager().disable(),SY(_ft,ob.instance())},t})()});var ju,Dft=g(()=>{(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(ju||(ju={}))});var lbe,obe,Fq,aJe=g(()=>{Dft();lbe="0000000000000000",obe="00000000000000000000000000000000",Fq={traceId:obe,spanId:lbe,traceFlags:ju.NONE}});var V5,IJe=g(()=>{aJe();V5=(function(){function t(e){e===void 0&&(e=Fq),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t})()});function cJe(t){return t.getValue(Pft)||void 0}function C7r(){return cJe(Y5.getInstance().active())}function ibe(t,e){return t.setValue(Pft,e)}function Q7r(t){return t.deleteValue(Pft)}function v7r(t,e){return ibe(t,new V5(e))}function dJe(t){var e;return(e=cJe(t))===null||e===void 0?void 0:e.spanContext()}var Pft,jft=g(()=>{nbe();IJe();sbe();Pft=R5("OpenTelemetry Context Key SPAN")});function abe(t){return v6s.test(t)&&t!==obe}function Kft(t){return H6s.test(t)&&t!==lbe}function TY(t){return abe(t.traceId)&&Kft(t.spanId)}function H7r(t){return new V5(t)}var v6s,H6s,uJe=g(()=>{aJe();IJe();v6s=/^([0-9a-f]{32})$/i,H6s=/^[0-9a-f]{16}$/i});function X6s(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var qft,mJe,$ft=g(()=>{sbe();jft();IJe();uJe();qft=Y5.getInstance(),mJe=(function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=qft.active());var s=!!r?.root;if(s)return new V5;var l=n&&dJe(n);return X6s(l)&&TY(l)?new V5(l):new V5},t.prototype.startActiveSpan=function(e,r,n,s){var l,o,a;if(!(arguments.length<2)){arguments.length===2?a=r:arguments.length===3?(l=r,a=n):(l=r,o=n,a=s);var I=o??qft.active(),c=this.startSpan(e,l,I),d=ibe(I,c);return qft.with(d,a,void 0,c)}},t})()});var k6s,hJe,ewt=g(()=>{$ft();k6s=new mJe,hJe=(function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var l=this._getTracer();return Reflect.apply(l.startActiveSpan,l,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):k6s},t})()});var X7r,k7r=g(()=>{$ft();X7r=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new mJe},t})()});var L6s,Ibe,twt=g(()=>{ewt();k7r();L6s=new X7r,Ibe=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new hJe(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:L6s},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t})()});var x9,L7r=g(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(x9||(x9={}))});var Rg,x7r=g(()=>{(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(Rg||(Rg={}))});var f5,J7r=g(()=>{(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(f5||(f5={}))});function S7r(t){return S6s.test(t)}function T7r(t){return T6s.test(t)&&!B6s.test(t)}var rwt,x6s,J6s,S6s,T6s,B6s,B7r=g(()=>{rwt="[_0-9a-z-*/]",x6s="[a-z]"+rwt+"{0,255}",J6s="[a-z0-9]"+rwt+"{0,240}@[a-z]"+rwt+"{0,13}",S6s=new RegExp("^(?:"+x6s+"|"+J6s+")$"),T6s=/^[ -~]{0,255}[!-~]$/,B6s=/,|=/});var O7r,O6s,U7r,M7r,z7r,_7r=g(()=>{B7r();O7r=32,O6s=512,U7r=",",M7r="=",z7r=(function(){function t(e){this._internalState=new Map,e&&this._parse(e)}return t.prototype.set=function(e,r){var n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n},t.prototype.unset=function(e){var r=this._clone();return r._internalState.delete(e),r},t.prototype.get=function(e){return this._internalState.get(e)},t.prototype.serialize=function(){var e=this;return this._keys().reduce(function(r,n){return r.push(n+M7r+e.get(n)),r},[]).join(U7r)},t.prototype._parse=function(e){e.length>O6s||(this._internalState=e.split(U7r).reverse().reduce(function(r,n){var s=n.trim(),l=s.indexOf(M7r);if(l!==-1){var o=s.slice(0,l),a=s.slice(l+1,n.length);S7r(o)&&T7r(a)&&r.set(o,a)}return r},new Map),this._internalState.size>O7r&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,O7r))))},t.prototype._keys=function(){return Array.from(this._internalState.keys()).reverse()},t.prototype._clone=function(){var e=new t;return e._internalState=new Map(this._internalState),e},t})()});function D7r(t){return new z7r(t)}var P7r=g(()=>{_7r()});var di,j7r=g(()=>{sbe();di=Y5.getInstance()});var kt,K7r=g(()=>{k9();kt=ob.instance()});var U6s,q7r,$7r=g(()=>{Mft();U6s=(function(){function t(){}return t.prototype.getMeter=function(e,r,n){return Uft},t})(),q7r=new U6s});var nwt,e$r,t$r=g(()=>{$7r();X9();k9();nwt="metrics",e$r=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return JY(nwt,e,ob.instance())},t.prototype.getMeterProvider=function(){return lN(nwt)||q7r},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){SY(nwt,ob.instance())},t})()});var J9,r$r=g(()=>{t$r();J9=e$r.getInstance()});var n$r,s$r=g(()=>{n$r=(function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t})()});function lwt(t){return t.getValue(swt)||void 0}function l$r(){return lwt(Y5.getInstance().active())}function o$r(t,e){return t.setValue(swt,e)}function i$r(t){return t.deleteValue(swt)}var swt,a$r=g(()=>{sbe();nbe();swt=R5("OpenTelemetry Baggage Key")});var owt,M6s,I$r,c$r=g(()=>{X9();s$r();zft();a$r();Tft();k9();owt="propagation",M6s=new n$r,I$r=(function(){function t(){this.createBaggage=E7r,this.getBaggage=lwt,this.getActiveBaggage=l$r,this.setBaggage=o$r,this.deleteBaggage=i$r}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return JY(owt,e,ob.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=iJe),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=oJe),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){SY(owt,ob.instance())},t.prototype._getGlobalPropagator=function(){return lN(owt)||M6s},t})()});var w5,d$r=g(()=>{c$r();w5=I$r.getInstance()});var iwt,u$r,m$r=g(()=>{X9();twt();uJe();jft();k9();iwt="trace",u$r=(function(){function t(){this._proxyTracerProvider=new Ibe,this.wrapSpanContext=H7r,this.isSpanContextValid=TY,this.deleteSpan=Q7r,this.getSpan=cJe,this.getActiveSpan=C7r,this.getSpanContext=dJe,this.setSpan=ibe,this.setSpanContext=v7r}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=JY(iwt,this._proxyTracerProvider,ob.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return lN(iwt)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){SY(iwt,ob.instance()),this._proxyTracerProvider=new Ibe},t})()});var ta,h$r=g(()=>{m$r();ta=u$r.getInstance()});var F5={};Fo(F5,{DiagConsoleLogger:()=>Y7r,DiagLogLevel:()=>Mm,INVALID_SPANID:()=>lbe,INVALID_SPAN_CONTEXT:()=>Fq,INVALID_TRACEID:()=>obe,ProxyTracer:()=>hJe,ProxyTracerProvider:()=>Ibe,ROOT_CONTEXT:()=>E5,SamplingDecision:()=>x9,SpanKind:()=>Rg,SpanStatusCode:()=>f5,TraceFlags:()=>ju,ValueType:()=>yg,baggageEntryMetadataFromString:()=>sJe,context:()=>di,createContextKey:()=>R5,createNoopMeter:()=>wq,createTraceState:()=>D7r,default:()=>z6s,defaultTextMapGetter:()=>oJe,defaultTextMapSetter:()=>iJe,diag:()=>kt,isSpanContextValid:()=>TY,isValidSpanId:()=>Kft,isValidTraceId:()=>abe,metrics:()=>J9,propagation:()=>w5,trace:()=>ta});var z6s,Rl=g(()=>{Tft();nbe();V7r();nJe();Mft();f7r();zft();ewt();twt();L7r();x7r();J7r();Dft();P7r();uJe();aJe();j7r();K7r();r$r();d$r();h$r();z6s={context:di,diag:kt,metrics:J9,propagation:w5,trace:ta}});var bJe,Cq,pJe,Qq,GJe,gJe,ZJe,b$r,cbe,p$r,dbe,ube,awt=g(()=>{bJe="error.type",Cq="exception.message",pJe="exception.stacktrace",Qq="exception.type",GJe="server.address",gJe="server.port",ZJe="service.name",b$r="service.version",cbe="telemetry.sdk.language",p$r="nodejs",dbe="telemetry.sdk.name",ube="telemetry.sdk.version"});var Iwt=g(()=>{});var cwt=g(()=>{});var G$r,g$r,dwt,Z$r,uwt,NJe,vq,mbe,hbe,AJe,bbe,N$r,pbe,mwt,hwt,A$r,W$r,WJe,y$r,R$r,yJe,E$r,Y$r,V$r,f$r,w$r,F$r=g(()=>{G$r="gen_ai.agent.description",g$r="gen_ai.agent.id",dwt="gen_ai.agent.name",Z$r="gen_ai.agent.version",uwt="gen_ai.conversation.id",NJe="gen_ai.input.messages",vq="gen_ai.operation.name",mbe="gen_ai.output.messages",hbe="gen_ai.provider.name",AJe="gen_ai.request.model",bbe="gen_ai.response.finish_reasons",N$r="gen_ai.response.id",pbe="gen_ai.response.model",mwt="gen_ai.system_instructions",hwt="gen_ai.token.type",A$r="gen_ai.tool.call.arguments",W$r="gen_ai.tool.call.id",WJe="gen_ai.tool.call.result",y$r="gen_ai.tool.definitions",R$r="gen_ai.tool.description",yJe="gen_ai.tool.name",E$r="gen_ai.tool.type",Y$r="gen_ai.usage.cache_creation.input_tokens",V$r="gen_ai.usage.cache_read.input_tokens",f$r="gen_ai.usage.input_tokens",w$r="gen_ai.usage.output_tokens"});var C$r,Q$r,v$r=g(()=>{C$r="gen_ai.client.operation.duration",Q$r="gen_ai.client.token.usage"});var H$r=g(()=>{});var bwt=g(()=>{awt();Iwt();cwt();F$r();v$r();H$r()});var k$r=g(()=>{});var L$r=g(()=>{k$r()});var x$r=g(()=>{});var J$r=g(()=>{x$r()});var Hq=g(()=>{L$r();J$r();awt();Iwt();cwt()});function gwt(t,e){if(!t)return E5;let r={traceparent:t};return e&&(r.tracestate=e),w5.extract(E5,r)}function z$r(t){let e=ta.setSpan(E5,t),r={};if(w5.inject(e,r),!!r.traceparent)return{traceparent:r.traceparent,tracestate:r.tracestate}}function YJe(t,e,r){let n={[vq]:t,[hbe]:e.providerName};return e.requestModel&&(n[AJe]=e.requestModel),r&&(n[pbe]=r),e.serverAddress&&(n[GJe]=e.serverAddress,e.serverPort!=null&&(n[gJe]=e.serverPort)),n}function VJe(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function C5(t,e){if(!t||t.length===0)return;let r=[];for(let n of t){if(n.parts.length===0)continue;let s=[];for(let a of n.parts){let I={type:a.type};switch(a.type){case"server_tool_call":a.id!=null&&(I.id=a.id),a.name!=null&&(I.name=a.name),I.server_tool_call={type:"mcp",...a.mcpServerName!=null&&{server_name:a.mcpServerName},...a.arguments!=null&&{arguments:a.arguments}};break;case"server_tool_call_response":a.id!=null&&(I.id=a.id),I.server_tool_call_response={type:"mcp",...a.mcpServerName!=null&&{server_name:a.mcpServerName},...a.response!=null&&{response:a.response}};break;default:a.content!=null&&(I.content=a.content),a.id!=null&&(I.id=a.id),a.name!=null&&(I.name=a.name),a.arguments!=null&&(I.arguments=a.arguments),a.response!=null&&(I.response=a.response);break}s.push(I)}let l={role:n.role,parts:s},o=n.finishReason??e;o&&(l.finish_reason=o),r.push(l)}return r.length>0?JSON.stringify(r):void 0}var D6s,pwt,T$r,B$r,Gwt,O$r,U$r,M$r,sr,uF,BY,S$r,P6s,j6s,K6s,q6s,$6s,eKs,RJe,tKs,EJe,rKs,w0,_$r=g(()=>{"use strict";Rl();Hq();bwt();D6s="github",pwt="github.copilot.cost",T$r="github.copilot.server_duration",B$r="github.copilot.initiator",Gwt="github.copilot.aiu",O$r="github.copilot.turn_id",U$r="github.copilot.interaction_id",M$r="github.copilot.turn_count",sr={USER_MESSAGE:"github.copilot.user.message",USER_MESSAGE_SOURCE:"github.copilot.user.message.source",USER_MESSAGE_AGENT_MODE:"github.copilot.user.message.agent_mode",USER_MESSAGE_INTERACTION_ID:"github.copilot.user.message.interaction_id",SYSTEM_NOTIFICATION:"github.copilot.system.notification",SYSTEM_NOTIFICATION_TYPE:"github.copilot.system.notification.type",SYSTEM_NOTIFICATION_AGENT_ID:"github.copilot.system.notification.agent_id",SYSTEM_NOTIFICATION_AGENT_TYPE:"github.copilot.system.notification.agent_type",SYSTEM_NOTIFICATION_STATUS:"github.copilot.system.notification.status",SYSTEM_NOTIFICATION_SHELL_ID:"github.copilot.system.notification.shell_id",SYSTEM_NOTIFICATION_EXIT_CODE:"github.copilot.system.notification.exit_code",SESSION_TRUNCATION:"github.copilot.session.truncation",SESSION_COMPACTION_START:"github.copilot.session.compaction_start",SESSION_COMPACTION_COMPLETE:"github.copilot.session.compaction_complete",SESSION_SHUTDOWN:"github.copilot.session.shutdown",SESSION_ABORT:"github.copilot.session.abort",SKILL_INVOKED:"github.copilot.skill.invoked",MESSAGE:"github.copilot.message",TOKEN_LIMIT:"github.copilot.token_limit",PRE_TOKENS:"github.copilot.pre_tokens",POST_TOKENS:"github.copilot.post_tokens",PRE_MESSAGES:"github.copilot.pre_messages",POST_MESSAGES:"github.copilot.post_messages",TOKENS_REMOVED:"github.copilot.tokens_removed",MESSAGES_REMOVED:"github.copilot.messages_removed",PERFORMED_BY:"github.copilot.performed_by",SUCCESS:"github.copilot.success",SKILL_NAME:"github.copilot.skill.name",SKILL_PATH:"github.copilot.skill.path",SKILL_CONTENT:"github.copilot.skill.content",SKILL_PLUGIN_NAME:"github.copilot.skill.plugin_name",SKILL_PLUGIN_VERSION:"github.copilot.skill.plugin_version",SHUTDOWN_TYPE:"github.copilot.shutdown_type",ERROR_REASON:"github.copilot.error_reason",TOTAL_PREMIUM_REQUESTS:"github.copilot.total_premium_requests",TOTAL_API_DURATION_MS:"github.copilot.total_api_duration_ms",LINES_ADDED:"github.copilot.lines_added",LINES_REMOVED:"github.copilot.lines_removed",FILES_MODIFIED_COUNT:"github.copilot.files_modified_count",ABORT_REASON:"github.copilot.abort_reason",ERROR_TYPE_NAME:"github.copilot.error_type",ERROR_STATUS_CODE:"github.copilot.error_status_code",ERROR_PROVIDER_CALL_ID:"github.copilot.error_provider_call_id",HOOK_START:"github.copilot.hook.start",HOOK_END:"github.copilot.hook.end",HOOK_ERROR:"github.copilot.hook.error",HOOK_TYPE:"github.copilot.hook.type",HOOK_INVOCATION_ID:"github.copilot.hook.invocation_id",HOOK_ERROR_MESSAGE:"github.copilot.hook.error_message",PERMISSION_KIND:"github.copilot.permission.kind",PERMISSION_TOOL_NAME:"github.copilot.permission.tool_name",PERMISSION_RESULT:"github.copilot.permission.result",ELICITATION_MESSAGE:"github.copilot.elicitation.message",EXTERNAL_TOOL_NAME:"github.copilot.external_tool.name",EXTERNAL_TOOL_CALL_ID:"github.copilot.external_tool.call_id",SESSION_SNAPSHOT_REWIND:"github.copilot.session.snapshot_rewind",EVENTS_REMOVED:"github.copilot.events_removed",UP_TO_EVENT_ID:"github.copilot.up_to_event_id",SESSION_CONTEXT_CHANGED:"github.copilot.session.context_changed",CWD:"github.copilot.cwd",GIT_ROOT:"github.copilot.git_root",REPOSITORY:"github.copilot.repository",BRANCH:"github.copilot.branch",SESSION_USAGE_INFO:"github.copilot.session.usage_info",CURRENT_TOKENS:"github.copilot.current_tokens",MESSAGES_LENGTH:"github.copilot.messages_length"},uF="invoke_agent",BY="chat",S$r="execute_tool",P6s="gen_ai.client.operation.exception",j6s="gen_ai.client.operation.time_to_first_chunk",K6s="gen_ai.client.operation.time_per_output_chunk",q6s="github.copilot.tool.call.count",$6s="github.copilot.tool.call.duration",eKs="github.copilot.agent.turn.count",RJe="s",tKs="{token}",EJe=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],rKs=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],w0=class{tracer;meter;operationDurationHistogram;tokenUsageHistogram;timeToFirstChunkHistogram;timePerOutputChunkHistogram;toolCallCounter;toolCallDurationHistogram;agentTurnCountHistogram;captureContent;constructor(e){this.captureContent=e.captureContent,this.tracer=ta.getTracer(e.sourceName,e.serviceVersion),this.meter=J9.getMeter(e.sourceName,e.serviceVersion),this.operationDurationHistogram=this.meter.createHistogram(C$r,{unit:RJe,description:"GenAI operation duration.",advice:{explicitBucketBoundaries:EJe}}),this.tokenUsageHistogram=this.meter.createHistogram(Q$r,{unit:tKs,description:"Number of input and output tokens used.",advice:{explicitBucketBoundaries:rKs}}),this.timeToFirstChunkHistogram=this.meter.createHistogram(j6s,{unit:RJe,description:"Time to receive the first chunk from a streaming response.",advice:{explicitBucketBoundaries:EJe}}),this.timePerOutputChunkHistogram=this.meter.createHistogram(K6s,{unit:RJe,description:"Time elapsed between streamed output chunks after the first chunk.",advice:{explicitBucketBoundaries:EJe}}),this.toolCallCounter=this.meter.createCounter(q6s,{unit:"{call}",description:"Number of tool invocations by tool name and outcome."}),this.toolCallDurationHistogram=this.meter.createHistogram($6s,{unit:RJe,description:"Tool execution latency.",advice:{explicitBucketBoundaries:EJe}}),this.agentTurnCountHistogram=this.meter.createHistogram(eKs,{unit:"{turn}",description:"Number of LLM round-trips per agent invocation."})}startInvokeAgentSpan(e,r,n,s,l,o){let a=n?`${uF} ${n}`:uF,I={[vq]:uF,[hbe]:r.providerName,[g$r]:e,[uwt]:e};return r.requestModel&&(I[AJe]=r.requestModel),n&&(I[dwt]=n),s&&(I[G$r]=s),l&&(I[Z$r]=l),r.serverAddress&&(I[GJe]=r.serverAddress,r.serverPort!=null&&(I[gJe]=r.serverPort)),this.tracer.startSpan(a,{kind:Rg.CLIENT,attributes:I},o)}startChatSpan(e,r,n){let s=e.requestModel?`${BY} ${e.requestModel}`:BY,l={[vq]:BY,[hbe]:e.providerName};return e.requestModel&&(l[AJe]=e.requestModel),n&&(l[uwt]=n),e.serverAddress&&(l[GJe]=e.serverAddress,e.serverPort!=null&&(l[gJe]=e.serverPort)),this.tracer.startSpan(s,{kind:Rg.CLIENT,attributes:l},r)}startExecuteToolSpan(e,r,n,s,l,o){let a=`${S$r} ${e}`,I={[vq]:S$r,[yJe]:e,[W$r]:r,[E$r]:"function"};return l&&(I[hbe]=l),n&&(I[R$r]=n),this.captureContent&&s!=null&&(I[A$r]=VJe(s)),this.tracer.startSpan(a,{kind:Rg.INTERNAL,attributes:I},o??di.active())}setExecuteToolResult(e,r){!this.captureContent||r==null||e.setAttribute(WJe,VJe(r))}recordTokenUsageMetrics(e,r,n,s,l,o=uF){let a=YJe(o,n,s);l&&(a[bJe]=l.name||l.constructor.name),e!=null&&this.tokenUsageHistogram.record(e,{...a,[hwt]:"input"}),r!=null&&this.tokenUsageHistogram.record(r,{...a,[hwt]:"output"})}recordOperationDuration(e,r,n,s,l=uF){let o=YJe(l,r,n);s&&(o[bJe]=s.name||s.constructor.name),this.operationDurationHistogram.record(e,o)}recordTimeToFirstChunk(e,r,n){this.timeToFirstChunkHistogram.record(e,YJe(BY,r,n))}recordTimePerOutputChunk(e,r,n){this.timePerOutputChunkHistogram.record(e,YJe(BY,r,n))}recordToolCall(e,r){this.toolCallCounter.add(1,{[yJe]:e,success:r})}recordToolCallDuration(e,r){this.toolCallDurationHistogram.record(e,{[yJe]:r})}recordAgentTurnCount(e,r){let n={[vq]:uF};r&&(n[dwt]=r),this.agentTurnCountHistogram.record(e,n)}static recordError(e,r){let n=r,s=n.errorClassification||r.name||r.constructor.name;e.setAttribute(bJe,s),e.setStatus({code:f5.ERROR,message:r.message});let l={...n.otelAttributes,[Qq]:r.name||r.constructor.name};r.message&&(l[Cq]=r.message),r.stack&&(l[pJe]=r.stack),e.addEvent(P6s,l)}static normalizeProviderName(e){if(!e)return D6s;switch(e.trim().toLowerCase()){case"azure":return"azure.ai.openai";default:return e.toLocaleLowerCase()}}static parseServerAddress(e){if(!e)return{address:void 0,port:void 0};try{let r=new URL(e);if(!r.hostname)return{address:void 0,port:void 0};let n;return r.port?n=parseInt(r.port,10):r.protocol==="https:"?n=443:r.protocol==="http:"&&(n=80),{address:r.hostname,port:n}}catch{return{address:void 0,port:void 0}}}}});function Zwt(){return{responseModel:void 0,responseId:void 0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function fJe(t,e){e.responseModel&&t.setAttribute(pbe,e.responseModel),e.responseId&&t.setAttribute(N$r,e.responseId),e.inputTokens>0&&t.setAttribute(f$r,e.inputTokens),e.outputTokens>0&&t.setAttribute(w$r,e.outputTokens),e.cacheReadTokens>0&&t.setAttribute(V$r,e.cacheReadTokens),e.cacheCreationTokens>0&&t.setAttribute(Y$r,e.cacheCreationTokens)}function D$r(t,e){e.model&&(t.responseModel=e.model),e.apiCallId?t.responseId=e.apiCallId:e.providerCallId&&(t.responseId=e.providerCallId),e.inputTokens!=null&&(t.inputTokens+=e.inputTokens),e.outputTokens!=null&&(t.outputTokens+=e.outputTokens),e.cacheReadTokens!=null&&(t.cacheReadTokens+=e.cacheReadTokens),e.cacheWriteTokens!=null&&(t.cacheCreationTokens+=e.cacheWriteTokens)}function nKs(t){switch(t.type){case"assistant.usage":case"assistant.message":case"assistant.message_delta":case"tool.execution_start":case"tool.execution_complete":return t.data.parentToolCallId??void 0;default:return}}var Nwt,Gbe,wJe,P$r=g(()=>{"use strict";Rl();Vt();ns();bwt();_$r();Nwt=class extends Error{constructor(e){super(e),this.name="SessionDestroyedError"}},Gbe=class extends Error{otelAttributes;errorClassification;constructor(e,r){super(e),this.name="SessionTurnError",this.otelAttributes=r?.otelAttributes,this.errorClassification=r?.errorClassification}};wJe=class{otel;sessionId;unsubscribe;unsubscribeTools;agentVersion;metricCtx;isStreaming=!1;systemInstructions;toolDefinitions;agent;turn;parentTraceContext;pendingInputMessages;activeSubagents;activeToolSpans;toolStartTimes;toolNames;pendingToolParents;mcpToolCallIds;activePermissionSpans;activeElicitationSpans;activeExternalToolSpans;constructor(e,r,n){this.otel=new w0(e),this.sessionId=r.sessionId,this.agentVersion=n?.agentVersion,this.isStreaming=n?.streaming??!1;let s=w0.parseServerAddress(n?.providerBaseUrl);this.metricCtx={requestModel:n?.model,providerName:w0.normalizeProviderName(n?.providerType),serverAddress:s.address,serverPort:s.port},n?.traceparent&&(this.parentTraceContext=gwt(n.traceparent,n.tracestate)),this.unsubscribe=r.on("*",l=>this.processEvent(l)),e.captureContent&&r.onToolsUpdate&&(this.unsubscribeTools=r.onToolsUpdate(l=>{this.toolDefinitions=l.map(o=>({type:"function",name:o.name,description:o.description,parameters:o.input_schema}))}))}dispose(){if(this.unsubscribe(),this.unsubscribeTools?.(),this.endOrphanedPairedSpans(),this.agent){let e=new Nwt("Session destroyed while agent turn was in progress");this.completeChatTurn(e),this.completeAgentTurn(e)}}updateParentTraceContext(e,r){e?this.parentTraceContext=gwt(e,r):this.parentTraceContext=void 0}getToolCallTraceContext(e){let r=this.activeToolSpans?.get(e);if(r)return z$r(r)}processEvent(e){try{this.processEventCore(e)}catch(r){te.warning(`OTel event processing error on ${e.type}: ${D(r)}`)}}processEventCore(e){if(e.type==="user.message"){let n=e.data?.content;this.ensureAgentSpan();let s=e.data?.source??"user",l=this.turn?.span??this.agent?.span;if(l){let o={[sr.USER_MESSAGE_SOURCE]:s};e.data?.agentMode&&(o[sr.USER_MESSAGE_AGENT_MODE]=e.data.agentMode),e.data?.interactionId&&(o[sr.USER_MESSAGE_INTERACTION_ID]=e.data.interactionId),l.addEvent(sr.USER_MESSAGE,o)}n&&this.appendInputMessage({role:"user",parts:[{type:"text",content:n}]});return}if(e.type==="system.message"&&this.otel.captureContent){let n=e.data;n.content&&(this.systemInstructions??=[]).push({type:"text",content:n.content});return}if(e.type==="system.notification"){let n=e.data;this.ensureAgentSpan(),n.content&&this.appendInputMessage({role:"user",parts:[{type:"text",content:n.content}]});let s=this.turn?.span??this.agent?.span;if(s){let l=n.kind,o={[sr.SYSTEM_NOTIFICATION_TYPE]:String(l.type)};typeof l.agentId=="string"&&(o[sr.SYSTEM_NOTIFICATION_AGENT_ID]=l.agentId),typeof l.agentType=="string"&&(o[sr.SYSTEM_NOTIFICATION_AGENT_TYPE]=l.agentType),typeof l.status=="string"&&(o[sr.SYSTEM_NOTIFICATION_STATUS]=l.status),typeof l.shellId=="string"&&(o[sr.SYSTEM_NOTIFICATION_SHELL_ID]=l.shellId),typeof l.exitCode=="number"&&(o[sr.SYSTEM_NOTIFICATION_EXIT_CODE]=l.exitCode),this.otel.captureContent&&n.content&&(o[sr.MESSAGE]=n.content),s.addEvent(sr.SYSTEM_NOTIFICATION,o)}return}let r=nKs(e);if(r){let n=this.activeSubagents?.get(r);if(n){this.processSubagentEvent(n,e);return}}switch(e.type){case"subagent.started":this.beginSubagent(e);return;case"subagent.completed":{let n=e.data;this.completeSubagent(n.toolCallId);return}case"subagent.failed":{let n=e.data,s=new Gbe("Subagent '"+n.agentName+"' failed: "+n.error);this.completeSubagent(n.toolCallId,s);return}}if(e.type==="hook.start"){let n=e.data,s=this.turn?.span??this.agent?.span;s&&s.addEvent(sr.HOOK_START,{[sr.HOOK_TYPE]:n.hookType,[sr.HOOK_INVOCATION_ID]:n.hookInvocationId});return}if(e.type==="hook.end"){let n=e.data,s=this.turn?.span??this.agent?.span;s&&(n.success?s.addEvent(sr.HOOK_END,{[sr.HOOK_TYPE]:n.hookType,[sr.HOOK_INVOCATION_ID]:n.hookInvocationId}):s.addEvent(sr.HOOK_ERROR,{[sr.HOOK_TYPE]:n.hookType,[sr.HOOK_INVOCATION_ID]:n.hookInvocationId,[sr.HOOK_ERROR_MESSAGE]:n.error?.message??"Hook failed"}));return}if(e.type==="permission.requested"){let n=e.data,s=n.permissionRequest,l=typeof s?.toolCallId=="string"?s.toolCallId:void 0,o=(l?this.pendingToolParents?.get(l):void 0)??(this.turn?.span?ta.setSpan(di.active(),this.turn.span):void 0)??this.agent?.spanContext??di.active(),a=this.otel.tracer.startSpan("permission",{kind:Rg.INTERNAL},o),I=n.permissionRequest?.kind;I&&a.setAttribute(sr.PERMISSION_KIND,I);let c=s?.toolName;typeof c=="string"&&a.setAttribute(sr.PERMISSION_TOOL_NAME,c),this.activePermissionSpans??=new Map,this.activePermissionSpans.set(n.requestId,a);return}if(e.type==="permission.completed"){let n=e.data,s=this.activePermissionSpans?.get(n.requestId);s&&(this.activePermissionSpans.delete(n.requestId),n.result?.kind&&s.setAttribute(sr.PERMISSION_RESULT,n.result.kind),s.end());return}if(e.type==="elicitation.requested"){let n=e.data,s=this.turn?.span?ta.setSpan(di.active(),this.turn.span):this.agent?.spanContext??di.active(),l=this.otel.tracer.startSpan("elicitation",{kind:Rg.INTERNAL},s);this.otel.captureContent&&n.message&&l.setAttribute(sr.ELICITATION_MESSAGE,n.message),this.activeElicitationSpans??=new Map,this.activeElicitationSpans.set(n.requestId,l);return}if(e.type==="elicitation.completed"){let n=e.data,s=this.activeElicitationSpans?.get(n.requestId);s&&(this.activeElicitationSpans.delete(n.requestId),s.end());return}if(e.type==="external_tool.requested"){let n=e.data,s=this.pendingToolParents?.get(n.toolCallId)??(this.turn?.span?ta.setSpan(di.active(),this.turn.span):void 0)??this.agent?.spanContext??di.active(),l=this.otel.tracer.startSpan(`external_tool ${n.toolName}`,{kind:Rg.INTERNAL},s);l.setAttribute(sr.EXTERNAL_TOOL_NAME,n.toolName),l.setAttribute(sr.EXTERNAL_TOOL_CALL_ID,n.toolCallId),this.activeExternalToolSpans??=new Map,this.activeExternalToolSpans.set(n.requestId,l);return}if(e.type==="external_tool.completed"){let n=e.data,s=this.activeExternalToolSpans?.get(n.requestId);s&&(this.activeExternalToolSpans.delete(n.requestId),s.end());return}if(e.type==="session.model_change"){let n=e.data;this.metricCtx.requestModel=n.newModel,this.turn&&(this.turn.usage.responseModel=n.newModel);return}if(this.recordOutputChunkMetric(),this.turn)switch(e.type){case"assistant.message":{let n=e.data,s=[];n.reasoningText&&s.push({type:"reasoning",content:n.reasoningText}),n.content&&s.push({type:"text",content:n.content}),s.length>0&&this.turn.outputMessages.push({role:"assistant",parts:s});break}case"assistant.usage":{let n=e.data;D$r(this.turn.usage,n),n.cost!=null&&(this.turn.cost=(this.turn.cost??0)+n.cost),n.duration!=null&&(this.turn.serverDuration=(this.turn.serverDuration??0)+n.duration),n.initiator&&(this.turn.initiator=n.initiator),n.copilotUsage&&(this.turn.aiu=(this.turn.aiu??0)+n.copilotUsage.totalNanoAiu);break}case"tool.execution_start":this.handleToolStart(e.data,this.agent?.spanContext??di.active(),this.turn.outputMessages);break;case"tool.execution_complete":this.handleToolComplete(e.data,this.turn.inputMessages);break}{let n=this.turn?.span??this.agent?.span;if(n)switch(e.type){case"session.truncation":{let s=e.data,l={};s.tokenLimit!==0&&(l[sr.TOKEN_LIMIT]=s.tokenLimit),s.preTruncationTokensInMessages!==0&&(l[sr.PRE_TOKENS]=s.preTruncationTokensInMessages),s.postTruncationTokensInMessages!==0&&(l[sr.POST_TOKENS]=s.postTruncationTokensInMessages),s.preTruncationMessagesLength!==0&&(l[sr.PRE_MESSAGES]=s.preTruncationMessagesLength),s.postTruncationMessagesLength!==0&&(l[sr.POST_MESSAGES]=s.postTruncationMessagesLength),s.tokensRemovedDuringTruncation!==0&&(l[sr.TOKENS_REMOVED]=s.tokensRemovedDuringTruncation),s.messagesRemovedDuringTruncation!==0&&(l[sr.MESSAGES_REMOVED]=s.messagesRemovedDuringTruncation),s.performedBy!=null&&(l[sr.PERFORMED_BY]=s.performedBy),n.addEvent(sr.SESSION_TRUNCATION,l);break}case"session.compaction_start":n.addEvent(sr.SESSION_COMPACTION_START);break;case"session.compaction_complete":{let s=e.data,l={[sr.SUCCESS]:s.success};this.otel.captureContent&&s.error!=null&&(l[sr.MESSAGE]=s.error),s.preCompactionTokens!=null&&(l[sr.PRE_TOKENS]=s.preCompactionTokens),s.postCompactionTokens!=null&&(l[sr.POST_TOKENS]=s.postCompactionTokens),s.tokensRemoved!=null&&(l[sr.TOKENS_REMOVED]=s.tokensRemoved),s.messagesRemoved!=null&&(l[sr.MESSAGES_REMOVED]=s.messagesRemoved),n.addEvent(sr.SESSION_COMPACTION_COMPLETE,l);break}case"skill.invoked":{let s=e.data,l={[sr.SKILL_NAME]:s.name,[sr.SKILL_PATH]:s.path};s.pluginName!=null&&(l[sr.SKILL_PLUGIN_NAME]=s.pluginName),s.pluginVersion!=null&&(l[sr.SKILL_PLUGIN_VERSION]=s.pluginVersion),this.otel.captureContent&&(l[sr.SKILL_CONTENT]=s.content),n.addEvent(sr.SKILL_INVOKED,l);break}case"session.snapshot_rewind":{let s=e.data,l={[sr.EVENTS_REMOVED]:s.eventsRemoved,[sr.UP_TO_EVENT_ID]:s.upToEventId};n.addEvent(sr.SESSION_SNAPSHOT_REWIND,l);break}case"session.context_changed":{let s=e.data,l={};s.cwd&&(l[sr.CWD]=s.cwd),s.gitRoot&&(l[sr.GIT_ROOT]=s.gitRoot),s.repository&&(l[sr.REPOSITORY]=s.repository),s.branch&&(l[sr.BRANCH]=s.branch),n.addEvent(sr.SESSION_CONTEXT_CHANGED,l);break}case"session.usage_info":{let s=e.data,l={[sr.TOKEN_LIMIT]:s.tokenLimit,[sr.CURRENT_TOKENS]:s.currentTokens,[sr.MESSAGES_LENGTH]:s.messagesLength};n.addEvent(sr.SESSION_USAGE_INFO,l);break}}}switch(e.type){case"assistant.turn_start":{this.beginChatTurn();let n=e.data;this.turn&&(this.turn.turnId=n.turnId,this.turn.interactionId=n.interactionId);break}case"assistant.turn_end":this.completeChatTurn();break;case"session.idle":this.completeChatTurn(),this.completeAgentTurn();break;case"session.error":{let n=e.data,s={};n.errorType&&(s[sr.ERROR_TYPE_NAME]=n.errorType),n.statusCode!=null&&(s[sr.ERROR_STATUS_CODE]=n.statusCode),n.providerCallId&&(s[sr.ERROR_PROVIDER_CALL_ID]=n.providerCallId),n.message&&(s[sr.MESSAGE]=n.message);let l=new Gbe("Session error: "+(n.message??"unknown error"),{otelAttributes:Object.keys(s).length>0?s:void 0,errorClassification:n.errorType});n.stack&&(l.stack=n.stack),this.completeChatTurn(l),this.completeAgentTurn(l);break}case"abort":{let n=e.data,s=this.turn?.span??this.agent?.span;if(s){let l={};n.reason&&(l[sr.ABORT_REASON]=n.reason),s.addEvent(sr.SESSION_ABORT,l)}this.completeChatTurn(),this.completeAgentTurn();break}case"session.shutdown":{let n=e.data,s=this.turn?.span??this.agent?.span;if(s){let l={[sr.SHUTDOWN_TYPE]:n.shutdownType,[sr.TOTAL_PREMIUM_REQUESTS]:n.totalPremiumRequests,[sr.TOTAL_API_DURATION_MS]:n.totalApiDurationMs};n.errorReason&&(l[sr.ERROR_REASON]=n.errorReason),n.codeChanges&&(l[sr.LINES_ADDED]=n.codeChanges.linesAdded,l[sr.LINES_REMOVED]=n.codeChanges.linesRemoved,l[sr.FILES_MODIFIED_COUNT]=n.codeChanges.filesModified?.length??0),s.addEvent(sr.SESSION_SHUTDOWN,l)}break}}}ensureAgentSpan(){if(!this.agent){let e=this.otel.startInvokeAgentSpan(this.sessionId,this.metricCtx,void 0,void 0,this.agentVersion,this.parentTraceContext);this.agent={span:e,spanContext:ta.setSpan(di.active(),e),startTime:performance.now(),inputMessages:[],outputMessages:void 0,usage:Zwt(),totalCost:0,totalAiu:0,turnCount:0}}}beginChatTurn(){this.completeChatTurn(),this.ensureAgentSpan();let e=this.agent;e.turnCount++;let r=e.spanContext??di.active();this.turn={span:this.otel.startChatSpan(this.metricCtx,r,this.sessionId),startTime:performance.now(),usage:Zwt(),inputMessages:this.pendingInputMessages??[],outputMessages:[],firstOutputChunkRecorded:!1,lastOutputChunkTime:0,cost:void 0,serverDuration:void 0,initiator:void 0,aiu:void 0,turnId:void 0,interactionId:void 0},this.pendingInputMessages=void 0}completeChatTurn(e){let r=this.turn;if(!r)return;this.turn=void 0,e&&w0.recordError(r.span,e);let n=e?"error":"stop";if(r.span.setAttribute(bbe,[n]),r.outputMessages.length>0&&this.agent&&(this.agent.outputMessages=r.outputMessages.map(l=>({...l,finishReason:n}))),this.agent){let l=this.agent.usage;r.usage.responseModel&&(l.responseModel=r.usage.responseModel),r.usage.responseId&&(l.responseId=r.usage.responseId),l.inputTokens+=r.usage.inputTokens,l.outputTokens+=r.usage.outputTokens,l.cacheReadTokens+=r.usage.cacheReadTokens,l.cacheCreationTokens+=r.usage.cacheCreationTokens,r.cost!=null&&(this.agent.totalCost+=r.cost),r.aiu!=null&&(this.agent.totalAiu+=r.aiu)}if(fJe(r.span,r.usage),r.cost!=null&&r.span.setAttribute(pwt,r.cost),r.serverDuration!=null&&r.span.setAttribute(T$r,r.serverDuration),r.initiator!=null&&r.span.setAttribute(B$r,r.initiator),r.aiu!=null&&r.span.setAttribute(Gwt,r.aiu),r.turnId!=null&&r.span.setAttribute(O$r,r.turnId),r.interactionId!=null&&r.span.setAttribute(U$r,r.interactionId),this.otel.captureContent){let l=C5(r.inputMessages);l&&r.span.setAttribute(NJe,l);let o=C5(r.outputMessages,n);o&&r.span.setAttribute(mbe,o),this.systemInstructions&&this.systemInstructions.length>0&&r.span.setAttribute(mwt,JSON.stringify(this.systemInstructions))}this.otel.recordTokenUsageMetrics(r.usage.inputTokens>0?r.usage.inputTokens:void 0,r.usage.outputTokens>0?r.usage.outputTokens:void 0,this.metricCtx,r.usage.responseModel,e,BY);let s=(performance.now()-r.startTime)/1e3;this.otel.recordOperationDuration(s,this.metricCtx,r.usage.responseModel,e,BY),r.span.end()}completeAgentTurn(e){let r=this.agent;if(!r)return;if(this.agent=void 0,this.activeSubagents&&this.activeSubagents.size>0)for(let l of[...this.activeSubagents.keys()])this.completeSubagent(l,e);if(this.activeSubagents=void 0,this.pendingToolParents=void 0,this.mcpToolCallIds=void 0,this.pendingInputMessages=void 0,this.activeToolSpans){for(let[,l]of this.activeToolSpans)e&&w0.recordError(l,e),l.end();this.activeToolSpans=void 0}this.toolStartTimes=void 0,this.toolNames=void 0,this.endOrphanedPairedSpans(),e&&w0.recordError(r.span,e);let n=e?"error":"stop";if(r.span.setAttribute(bbe,[n]),fJe(r.span,r.usage),r.totalCost>0&&r.span.setAttribute(pwt,r.totalCost),r.totalAiu>0&&r.span.setAttribute(Gwt,r.totalAiu),r.turnCount>0&&r.span.setAttribute(M$r,r.turnCount),this.otel.captureContent){let l=C5(r.inputMessages);l&&r.span.setAttribute(NJe,l);let o=C5(r.outputMessages);o&&r.span.setAttribute(mbe,o),this.systemInstructions&&this.systemInstructions.length>0&&r.span.setAttribute(mwt,JSON.stringify(this.systemInstructions)),this.toolDefinitions&&this.toolDefinitions.length>0&&r.span.setAttribute(y$r,JSON.stringify(this.toolDefinitions))}let s=(performance.now()-r.startTime)/1e3;this.otel.recordOperationDuration(s,this.metricCtx,r.usage.responseModel,e,uF),r.turnCount>0&&this.otel.recordAgentTurnCount(r.turnCount),r.span.end()}recordOutputChunkMetric(){if(!this.isStreaming||!this.turn)return;let e=performance.now(),r=e-this.turn.startTime;if(!this.turn.firstOutputChunkRecorded){this.turn.firstOutputChunkRecorded=!0,this.turn.lastOutputChunkTime=e,this.otel.recordTimeToFirstChunk(r/1e3,this.metricCtx);return}let n=(e-this.turn.lastOutputChunkTime)/1e3;this.turn.lastOutputChunkTime=e,this.otel.recordTimePerOutputChunk(n,this.metricCtx)}appendInputMessage(e){this.agent?.inputMessages.push(e),this.turn?this.turn.inputMessages.push(e):(this.pendingInputMessages??=[]).push(e)}handleToolStart(e,r,n){let s=!!e.mcpServerName;s&&e.toolCallId&&(this.mcpToolCallIds??=new Map,this.mcpToolCallIds.set(e.toolCallId,e.mcpServerName)),n.push({role:"assistant",parts:[{type:s?"server_tool_call":"tool_call",id:e.toolCallId,name:e.toolName,arguments:e.arguments,mcpServerName:e.mcpServerName}]});let l=this.toolDefinitions?.find(a=>a.name===e.toolName)?.description,o=this.otel.startExecuteToolSpan(e.toolName,e.toolCallId,l,e.arguments,this.metricCtx.providerName,r);this.activeToolSpans??=new Map,this.activeToolSpans.set(e.toolCallId,o),this.toolStartTimes??=new Map,this.toolStartTimes.set(e.toolCallId,performance.now()),this.toolNames??=new Map,this.toolNames.set(e.toolCallId,e.toolName),e.toolCallId&&(this.pendingToolParents??=new Map,this.pendingToolParents.set(e.toolCallId,ta.setSpan(di.active(),o)))}handleToolComplete(e,r){let n=e.result?.content??e.error?.message,s,l=this.mcpToolCallIds?.has(e.toolCallId)??!1;l&&(s=this.mcpToolCallIds.get(e.toolCallId),this.mcpToolCallIds.delete(e.toolCallId)),r.push({role:"tool",parts:[{type:l?"server_tool_call_response":"tool_call_response",id:e.toolCallId,response:n,mcpServerName:s}]});let o=this.activeToolSpans?.get(e.toolCallId);if(o){if(this.activeToolSpans.delete(e.toolCallId),this.pendingToolParents?.delete(e.toolCallId),this.otel.captureContent&&e.result?.content!=null&&o.setAttribute(WJe,VJe(e.result.content)),e.error){let I=new Error(e.error.message);I.name=e.error.code??"ToolError",w0.recordError(o,I)}o.end()}let a=this.toolNames?.get(e.toolCallId);if(a){this.toolNames.delete(e.toolCallId),this.otel.recordToolCall(a,!e.error);let I=this.toolStartTimes?.get(e.toolCallId);I!=null&&(this.toolStartTimes.delete(e.toolCallId),this.otel.recordToolCallDuration((performance.now()-I)/1e3,a))}}beginSubagent(e){let r=e.data;if(!r)return;this.activeSubagents?.has(r.toolCallId)&&this.completeSubagent(r.toolCallId,new Gbe("Duplicate subagent.started"));let n=this.pendingToolParents?.get(r.toolCallId)??this.agent?.spanContext??di.active(),s=this.otel.startInvokeAgentSpan(this.sessionId,this.metricCtx,r.agentName,r.agentDescription,void 0,n),l=ta.setSpan(di.active(),s),o=this.otel.startChatSpan(this.metricCtx,l,this.sessionId),a={invokeAgentSpan:s,invokeAgentContext:l,invokeAgentStartTime:performance.now(),chatSpan:o,chatStartTime:performance.now(),agentName:r.agentName,usage:Zwt(),inputMessages:[],outputMessages:[]};this.activeSubagents??=new Map,this.activeSubagents.set(r.toolCallId,a)}processSubagentEvent(e,r){switch(r.type){case"assistant.usage":D$r(e.usage,r.data),r.data.model&&e.chatSpan?.setAttribute(pbe,r.data.model);break;case"assistant.message":{let n=r.data,s=[];n.reasoningText&&s.push({type:"reasoning",content:n.reasoningText}),n.content&&s.push({type:"text",content:n.content}),s.length>0&&e.outputMessages.push({role:"assistant",parts:s});break}case"tool.execution_start":this.handleToolStart(r.data,e.invokeAgentContext,e.outputMessages);break;case"tool.execution_complete":this.handleToolComplete(r.data,e.inputMessages);break}}completeSubagent(e,r){if(!this.activeSubagents)return;let n=this.activeSubagents.get(e);if(!n)return;this.activeSubagents.delete(e);let s=r?"error":"stop",l=n.chatSpan;if(l){if(r&&w0.recordError(l,r),l.setAttribute(bbe,[s]),fJe(l,n.usage),this.otel.captureContent){if(n.inputMessages.length>0){let c=C5(n.inputMessages);c&&l.setAttribute(NJe,c)}if(n.outputMessages.length>0){let c=C5(n.outputMessages,s);c&&l.setAttribute(mbe,c)}}this.otel.recordTokenUsageMetrics(n.usage.inputTokens>0?n.usage.inputTokens:void 0,n.usage.outputTokens>0?n.usage.outputTokens:void 0,this.metricCtx,n.usage.responseModel,r,BY);let I=(performance.now()-n.chatStartTime)/1e3;this.otel.recordOperationDuration(I,this.metricCtx,n.usage.responseModel,r,BY),l.end()}let o=n.invokeAgentSpan;if(r&&w0.recordError(o,r),o.setAttribute(bbe,[s]),fJe(o,n.usage),this.otel.captureContent&&n.outputMessages.length>0){let I=C5(n.outputMessages.map(c=>({...c,finishReason:s})));I&&o.setAttribute(mbe,I)}let a=(performance.now()-n.invokeAgentStartTime)/1e3;this.otel.recordOperationDuration(a,this.metricCtx,n.usage.responseModel,r,uF),o.end()}endOrphanedPairedSpans(){let e=r=>{if(r){for(let[,n]of r)n.end();r.clear()}};e(this.activePermissionSpans),e(this.activeElicitationSpans),e(this.activeExternalToolSpans)}}});function gbe(t){return t.setValue(j$r,!0)}function Zbe(t){return t.getValue(j$r)===!0}var j$r,FJe=g(()=>{Rl();j$r=R5("OpenTelemetry SDK Context Key SUPPRESS_TRACING")});function sKs(t){if(!t)return;let e=t.indexOf(";"),r=e===-1?t:t.substring(0,e),n=r.indexOf("=");if(n<=0)return;let s=r.substring(0,n).trim(),l=r.substring(n+1).trim();if(!s||!l)return;let o,a;try{o=decodeURIComponent(s),a=decodeURIComponent(l)}catch{return}let I;if(e!==-1&&e<t.length-1){let c=t.substring(e+1);I=sJe(c)}return{key:o,value:a,metadata:I}}function Xq(t){let e={};return typeof t=="string"&&t.length>0&&t.split(",").forEach(r=>{let n=sKs(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}var K$r=g(()=>{Rl()});function S9(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!lKs(r)){kt.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!CJe(n)){kt.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}function lKs(t){return typeof t=="string"&&t!==""}function CJe(t){return t==null?!0:Array.isArray(t)?oKs(t):q$r(typeof t)}function oKs(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(q$r(n)){e=n;continue}return!1}return!1}}return!0}function q$r(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}var $$r=g(()=>{Rl()});function een(){return t=>{kt.error(iKs(t))}}function iKs(t){return typeof t=="string"?t:JSON.stringify(aKs(t))}function aKs(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let s=r[n];s&&(e[n]=String(s))}),r=Object.getPrototypeOf(r);return e}var ten=g(()=>{Rl()});function oN(t){try{IKs(t)}catch{}}var IKs,ren=g(()=>{ten();IKs=een()});import{inspect as cKs}from"util";function _a(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){kt.warn(`Unknown value ${cKs(e)} for ${t}, expected a number, using defaults`);return}return r}function ib(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}var nen=g(()=>{Rl()});var sen,len=g(()=>{sen="2.6.0"});var oen,ien=g(()=>{oen="process.runtime.name"});var T9,aen=g(()=>{len();Hq();ien();T9={[dbe]:"opentelemetry",[oen]:"node",[cbe]:p$r,[ube]:sen}});var OY,den=g(()=>{nen();aen();OY=performance});var Awt=g(()=>{den()});function Eg(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*hKs);return[r,n]}function Wwt(t){let e=Eg(OY.timeOrigin),r=Eg(typeof t=="number"?t:OY.now());return XJe(e,r)}function ywt(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=QJe),[r,n]}function Rwt(t){return t[0]*QJe+t[1]}function kq(t){return t[0]*1e6+t[1]/1e3}function vJe(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}function HJe(t){return vJe(t)||typeof t=="number"||t instanceof Date}function XJe(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=QJe&&(r[1]-=QJe,r[0]+=1),r}var uKs,mKs,hKs,QJe,uen=g(()=>{Awt();uKs=9,mKs=6,hKs=Math.pow(10,mKs),QJe=Math.pow(10,uKs)});var ac,men=g(()=>{(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(ac||(ac={}))});function hen(t){return GKs.test(t)}function ben(t){return gKs.test(t)&&!ZKs.test(t)}var Ewt,bKs,pKs,GKs,gKs,ZKs,pen=g(()=>{Ewt="[_0-9a-z-*/]",bKs=`[a-z]${Ewt}{0,255}`,pKs=`[a-z0-9]${Ewt}{0,240}@[a-z]${Ewt}{0,13}`,GKs=new RegExp(`^(?:${bKs}|${pKs})$`),gKs=/^[ -~]{0,255}[!-~]$/,ZKs=/,|=/});var Gen,NKs,gen,Zen,kJe,Nen=g(()=>{pen();Gen=32,NKs=512,gen=",",Zen="=",kJe=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+Zen+this.get(r)),e),[]).join(gen)}_parse(e){e.length>NKs||(this._internalState=e.split(gen).reverse().reduce((r,n)=>{let s=n.trim(),l=s.indexOf(Zen);if(l!==-1){let o=s.slice(0,l),a=s.slice(l+1,n.length);hen(o)&&ben(a)&&r.set(o,a)}return r},new Map),this._internalState.size>Gen&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Gen))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}}});function Aen(t){let e=YKs.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}var LJe,xJe,AKs,WKs,yKs,RKs,EKs,YKs,Nbe,Wen=g(()=>{Rl();FJe();Nen();LJe="traceparent",xJe="tracestate",AKs="00",WKs="(?!ff)[\\da-f]{2}",yKs="(?![0]{32})[\\da-f]{32}",RKs="(?![0]{16})[\\da-f]{16}",EKs="[\\da-f]{2}",YKs=new RegExp(`^\\s?(${WKs})-(${yKs})-(${RKs})-(${EKs})(-.*)?\\s?$`);Nbe=class{inject(e,r,n){let s=ta.getSpanContext(e);if(!s||Zbe(e)||!TY(s))return;let l=`${AKs}-${s.traceId}-${s.spanId}-0${Number(s.traceFlags||ju.NONE).toString(16)}`;n.set(r,LJe,l),s.traceState&&n.set(r,xJe,s.traceState.serialize())}extract(e,r,n){let s=n.get(r,LJe);if(!s)return e;let l=Array.isArray(s)?s[0]:s;if(typeof l!="string")return e;let o=Aen(l);if(!o)return e;o.isRemote=!0;let a=n.get(r,xJe);if(a){let I=Array.isArray(a)?a.join(","):a;o.traceState=new kJe(typeof I=="string"?I:void 0)}return ta.setSpanContext(e,o)}fields(){return[LJe,xJe]}}});function Ywt(t){if(!vKs(t)||HKs(t)!==VKs)return!1;let e=QKs(t);if(e===null)return!0;let r=Een.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&yen.call(r)===CKs}function vKs(t){return t!=null&&typeof t=="object"}function HKs(t){return t==null?t===void 0?wKs:fKs:B9&&B9 in Object(t)?XKs(t):kKs(t)}function XKs(t){let e=Een.call(t,B9),r=t[B9],n=!1;try{t[B9]=void 0,n=!0}catch{}let s=Yen.call(t);return n&&(e?t[B9]=r:delete t[B9]),s}function kKs(t){return Yen.call(t)}var VKs,fKs,wKs,FKs,yen,CKs,QKs,Ren,Een,B9,Yen,Ven=g(()=>{VKs="[object Object]",fKs="[object Null]",wKs="[object Undefined]",FKs=Function.prototype,yen=FKs.toString,CKs=yen.call(Object),QKs=Object.getPrototypeOf,Ren=Object.prototype,Een=Ren.hasOwnProperty,B9=Symbol?Symbol.toStringTag:void 0,Yen=Ren.toString});function fwt(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=wen(e,t.shift(),0,r);return e}function Vwt(t){return SJe(t)?t.slice():t}function wen(t,e,r=0,n){let s;if(!(r>LKs)){if(r++,JJe(t)||JJe(e)||Fen(e))s=Vwt(e);else if(SJe(t)){if(s=t.slice(),SJe(e))for(let l=0,o=e.length;l<o;l++)s.push(Vwt(e[l]));else if(Abe(e)){let l=Object.keys(e);for(let o=0,a=l.length;o<a;o++){let I=l[o];s[I]=Vwt(e[I])}}}else if(Abe(t))if(Abe(e)){if(!xKs(t,e))return e;s=Object.assign({},t);let l=Object.keys(e);for(let o=0,a=l.length;o<a;o++){let I=l[o],c=e[I];if(JJe(c))typeof c>"u"?delete s[I]:s[I]=c;else{let d=s[I],u=c;if(fen(t,I,n)||fen(e,I,n))delete s[I];else{if(Abe(d)&&Abe(u)){let m=n.get(d)||[],h=n.get(u)||[];m.push({obj:t,key:I}),h.push({obj:e,key:I}),n.set(d,m),n.set(u,h)}s[I]=wen(s[I],c,r,n)}}}}else s=e;return s}}function fen(t,e,r){let n=r.get(t[e])||[];for(let s=0,l=n.length;s<l;s++){let o=n[s];if(o.key===e&&o.obj===t)return!0}return!1}function SJe(t){return Array.isArray(t)}function Fen(t){return typeof t=="function"}function Abe(t){return!JJe(t)&&!SJe(t)&&!Fen(t)&&typeof t=="object"}function JJe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function xKs(t,e){return!(!Ywt(t)||!Ywt(e))}var LKs,Cen=g(()=>{Ven();LKs=20});var TJe,Qen=g(()=>{TJe=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}});var O9,ven=g(()=>{Qen();O9=class{_isCalled=!1;_deferred=new TJe;_callback;_that;constructor(e,r){this._callback=e,this._that=r}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}}});function Hen(t,e){return new Promise(r=>{di.with(gbe(di.active()),()=>{t.export(e,r)})})}var Xen=g(()=>{Rl();FJe()});var BJe,Tc=g(()=>{$$r();ren();uen();men();K$r();Awt();Wen();FJe();Cen();ven();Xen();BJe={_export:Hen}});function ken(){if(OJe===void 0)try{let t=globalThis.process.argv0;OJe=t?`unknown_service:${t}`:"unknown_service"}catch{OJe="unknown_service"}return OJe}var OJe,Len=g(()=>{});var Lq,xen=g(()=>{Lq=t=>t!==null&&typeof t=="object"&&typeof t.then=="function"});function UJe(t,e){return wwt.FromAttributeList(Object.entries(t),e)}function Wbe(){return UJe({[ZJe]:ken(),[cbe]:T9[cbe],[dbe]:T9[dbe],[ube]:T9[ube]})}function Jen(t){return t.map(([e,r])=>Lq(r)?[e,r.catch(n=>{kt.debug("promise rejection for resource attribute: %s - %s",e,n)})]:[e,r])}function JKs(t){if(typeof t=="string"||t===void 0)return t;kt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t)}function SKs(t,e){let r=t?.schemaUrl,n=e?.schemaUrl,s=r===void 0||r==="",l=n===void 0||n==="";if(s)return n;if(l||r===n)return r;kt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}var wwt,Sen=g(()=>{Rl();Tc();Hq();Len();xen();wwt=class t{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,r){let n=new t({},r);return n._rawAttributes=Jen(e),n._asyncAttributesPending=e.filter(([s,l])=>Lq(l)).length>0,n}constructor(e,r){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([s,l])=>(Lq(l)&&(this._asyncAttributesPending=!0),[s,l])),this._rawAttributes=Jen(this._rawAttributes),this._schemaUrl=JKs(r?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[r,n]=this._rawAttributes[e];this._rawAttributes[e]=[r,Lq(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&kt.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[r,n]of this._rawAttributes){if(Lq(n)){kt.debug(`Unsettled resource attribute ${r} skipped`);continue}n!=null&&(e[r]??=n)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(e){if(e==null)return this;let r=SKs(this,e),n=r?{schemaUrl:r}:void 0;return t.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],n)}}});var MJe=g(()=>{Sen()});var Ten,Ben=g(()=>{Ten="exception"});var zJe,Oen=g(()=>{Rl();Tc();Hq();Ben();zJe=class{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:f5.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){let r=Date.now();this._spanContext=e.spanContext,this._performanceStartTime=OY.now(),this._performanceOffset=r-(this._performanceStartTime+OY.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,this.links=e.links||[],this.startTime=this._getTime(e.startTime??r),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,r){if(r==null||this._isSpanEnded())return this;if(e.length===0)return kt.warn(`Invalid attribute key: ${e}`),this;if(!CJe(r))return kt.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:n}=this._spanLimits,s=!Object.prototype.hasOwnProperty.call(this.attributes,e);return n!==void 0&&this._attributesCount>=n&&s?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(r),s&&this._attributesCount++,this)}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}addEvent(e,r,n){if(this._isSpanEnded())return this;let{eventCountLimit:s}=this._spanLimits;if(s===0)return kt.warn("No events allowed."),this._droppedEventsCount++,this;s!==void 0&&this.events.length>=s&&(this._droppedEventsCount===0&&kt.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),HJe(r)&&(HJe(n)||(n=r),r=void 0);let l=S9(r);return this.events.push({name:e,attributes:l,time:this._getTime(n),droppedAttributesCount:0}),this}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}setStatus(e){return this._isSpanEnded()?this:(this.status={...e},this.status.message!=null&&typeof e.message!="string"&&(kt.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`),delete this.status.message),this)}updateName(e){return this._isSpanEnded()?this:(this.name=e,this)}end(e){if(this._isSpanEnded()){kt.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(e),this._duration=ywt(this.startTime,this.endTime),this._duration[0]<0&&(kt.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&kt.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e=="number"&&e<=OY.now())return Wwt(e+this._performanceOffset);if(typeof e=="number")return Eg(e);if(e instanceof Date)return Eg(e.getTime());if(vJe(e))return e;if(this._startTimeProvided)return Eg(Date.now());let r=OY.now()-this._performanceStartTime;return XJe(this.startTime,Eg(r))}isRecording(){return this._ended===!1}recordException(e,r){let n={};typeof e=="string"?n[Cq]=e:e&&(e.code?n[Qq]=e.code.toString():e.name&&(n[Qq]=e.name),e.message&&(n[Cq]=e.message),e.stack&&(n[pJe]=e.stack)),n[Qq]||n[Cq]?this.addEvent(Ten,n,r):kt.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);kt.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,r){return e.length<=r?e:e.substring(0,r)}_truncateToSize(e){let r=this._attributeValueLengthLimit;return r<=0?(kt.warn(`Attribute value limit must be positive, got ${r}`),e):typeof e=="string"?this._truncateToLimitUtil(e,r):Array.isArray(e)?e.map(n=>typeof n=="string"?this._truncateToLimitUtil(n,r):n):e}}});var Yg,ybe=g(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(Yg||(Yg={}))});var Q5,Fwt=g(()=>{ybe();Q5=class{shouldSample(){return{decision:Yg.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}});var UY,Cwt=g(()=>{ybe();UY=class{shouldSample(){return{decision:Yg.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}});var U9,Uen=g(()=>{Rl();Tc();Fwt();Cwt();U9=class{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(oN(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new UY),this._remoteParentSampled=e.remoteParentSampled??new UY,this._remoteParentNotSampled=e.remoteParentNotSampled??new Q5,this._localParentSampled=e.localParentSampled??new UY,this._localParentNotSampled=e.localParentNotSampled??new Q5}shouldSample(e,r,n,s,l,o){let a=ta.getSpanContext(e);return!a||!TY(a)?this._root.shouldSample(e,r,n,s,l,o):a.isRemote?a.traceFlags&ju.SAMPLED?this._remoteParentSampled.shouldSample(e,r,n,s,l,o):this._remoteParentNotSampled.shouldSample(e,r,n,s,l,o):a.traceFlags&ju.SAMPLED?this._localParentSampled.shouldSample(e,r,n,s,l,o):this._localParentNotSampled.shouldSample(e,r,n,s,l,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}});var Rbe,Men=g(()=>{Rl();ybe();Rbe=class{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,r){return{decision:abe(r)&&this._accumulate(r)<this._upperBound?Yg.RECORD_AND_SAMPLED:Yg.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!="number"||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let r=0;for(let n=0;n<e.length/8;n++){let s=n*8,l=parseInt(e.slice(s,s+8),16);r=(r^l)>>>0}return r}}});function DJe(){return{sampler:Qwt(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:_a("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:_a("OTEL_ATTRIBUTE_COUNT_LIMIT")??128},spanLimits:{attributeValueLengthLimit:_a("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:_a("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??128,linkCountLimit:_a("OTEL_SPAN_LINK_COUNT_LIMIT")??128,eventCountLimit:_a("OTEL_SPAN_EVENT_COUNT_LIMIT")??128,attributePerEventCountLimit:_a("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT")??128,attributePerLinkCountLimit:_a("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT")??128}}}function Qwt(){let t=ib("OTEL_TRACES_SAMPLER")??MY.ParentBasedAlwaysOn;switch(t){case MY.AlwaysOn:return new UY;case MY.AlwaysOff:return new Q5;case MY.ParentBasedAlwaysOn:return new U9({root:new UY});case MY.ParentBasedAlwaysOff:return new U9({root:new Q5});case MY.TraceIdRatio:return new Rbe(zen());case MY.ParentBasedTraceIdRatio:return new U9({root:new Rbe(zen())});default:return kt.error(`OTEL_TRACES_SAMPLER value "${t}" invalid, defaulting to "${MY.ParentBasedAlwaysOn}".`),new U9({root:new UY})}}function zen(){let t=_a("OTEL_TRACES_SAMPLER_ARG");return t==null?(kt.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${_Je}.`),_Je):t<0||t>1?(kt.error(`OTEL_TRACES_SAMPLER_ARG=${t} was given, but it is out of range ([0..1]), defaulting to ${_Je}.`),_Je):t}var MY,_Je,vwt=g(()=>{Rl();Tc();Fwt();Cwt();Uen();Men();(function(t){t.AlwaysOff="always_off",t.AlwaysOn="always_on",t.ParentBasedAlwaysOff="parentbased_always_off",t.ParentBasedAlwaysOn="parentbased_always_on",t.ParentBasedTraceIdRatio="parentbased_traceidratio",t.TraceIdRatio="traceidratio"})(MY||(MY={}));_Je=1});function _en(t){let e={sampler:Qwt()},r=DJe(),n=Object.assign({},r,e,t);return n.generalLimits=Object.assign({},r.generalLimits,t.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,t.spanLimits||{}),n}function Den(t){let e=Object.assign({},t.spanLimits);return e.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??_a("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??_a("OTEL_ATTRIBUTE_COUNT_LIMIT")??TKs,e.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??_a("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??_a("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??BKs,Object.assign({},t,{spanLimits:e})}var TKs,BKs,Hwt=g(()=>{vwt();Tc();TKs=128,BKs=1/0});var PJe,Pen=g(()=>{Rl();Tc();PJe=class{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,r){this._exporter=e,this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:_a("OTEL_BSP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:_a("OTEL_BSP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:_a("OTEL_BSP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:_a("OTEL_BSP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new O9(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(kt.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,r){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&ju.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&kt.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(kt.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,r)=>{let n=[],s=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let l=0,o=s;l<o;l++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(r)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("Timeout"))},this._exportTimeoutMillis);di.with(gbe(di.active()),()=>{let s;this._finishedSpans.length<=this._maxExportBatchSize?(s=this._finishedSpans,this._finishedSpans=[]):s=this._finishedSpans.splice(0,this._maxExportBatchSize);let l=()=>this._exporter.export(s,a=>{clearTimeout(n),a.code===ac.SUCCESS?e():r(a.error??new Error("BatchSpanProcessor: span export failed"))}),o=null;for(let a=0,I=s.length;a<I;a++){let c=s[a];c.resource.asyncAttributesPending&&c.resource.waitForAsyncAttributes&&(o??=[],o.push(c.resource.waitForAsyncAttributes()))}o===null?l():Promise.all(o).then(l,a=>{oN(a),r(a)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(r=>{this._isExporting=!1,oN(r)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!="number"&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}}});var M9,jen=g(()=>{Pen();M9=class extends PJe{onShutdown(){}}});function Ken(t){return function(){for(let r=0;r<t/4;r++)jJe.writeUInt32BE(Math.random()*2**32>>>0,r*4);for(let r=0;r<t&&!(jJe[r]>0);r++)r===t-1&&(jJe[t-1]=1);return jJe.toString("hex",0,t)}}var z9,jJe,qen=g(()=>{z9=class{generateTraceId=Ken(16);generateSpanId=Ken(8)},jJe=Buffer.allocUnsafe(16)});var $en=g(()=>{jen();qen()});var Xwt=g(()=>{$en()});var etn,kwt,ttn,rtn,ntn=g(()=>{etn="otel.span.parent.origin",kwt="otel.span.sampling_result",ttn="otel.sdk.span.live",rtn="otel.sdk.span.started"});function OKs(t){return t?t.isRemote?"remote":"local":"none"}function UKs(t){switch(t){case Yg.RECORD_AND_SAMPLED:return"RECORD_AND_SAMPLE";case Yg.RECORD:return"RECORD_ONLY";case Yg.NOT_RECORD:return"DROP"}}var KJe,stn=g(()=>{ybe();ntn();KJe=class{startedSpans;liveSpans;constructor(e){this.startedSpans=e.createCounter(rtn,{unit:"{span}",description:"The number of created spans."}),this.liveSpans=e.createUpDownCounter(ttn,{unit:"{span}",description:"The number of currently live spans."})}startSpan(e,r){let n=UKs(r);if(this.startedSpans.add(1,{[etn]:OKs(e),[kwt]:n}),r===Yg.NOT_RECORD)return()=>{};let s={[kwt]:n};return this.liveSpans.add(1,s),()=>{this.liveSpans.add(-1,s)}}}});var ltn,otn=g(()=>{ltn="2.6.0"});var qJe,itn=g(()=>{Rl();Tc();Oen();Hwt();Xwt();stn();otn();qJe=class{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,r,n,s){let l=_en(r);this._sampler=l.sampler,this._generalLimits=l.generalLimits,this._spanLimits=l.spanLimits,this._idGenerator=r.idGenerator||new z9,this._resource=n,this._spanProcessor=s,this.instrumentationScope=e;let o=l.meterProvider?l.meterProvider.getMeter("@opentelemetry/sdk-trace",ltn):wq();this._tracerMetrics=new KJe(o)}startSpan(e,r={},n=di.active()){r.root&&(n=ta.deleteSpan(n));let s=ta.getSpan(n);if(Zbe(n))return kt.debug("Instrumentation suppressed, returning Noop Span"),ta.wrapSpanContext(Fq);let l=s?.spanContext(),o=this._idGenerator.generateSpanId(),a,I,c;!l||!ta.isSpanContextValid(l)?I=this._idGenerator.generateTraceId():(I=l.traceId,c=l.traceState,a=l);let d=r.kind??Rg.INTERNAL,u=(r.links??[]).map(A=>({context:A.context,attributes:S9(A.attributes)})),m=S9(r.attributes),h=this._sampler.shouldSample(n,I,e,d,m,u),b=this._tracerMetrics.startSpan(l,h.decision);c=h.traceState??c;let p=h.decision===x9.RECORD_AND_SAMPLED?ju.SAMPLED:ju.NONE,G={traceId:I,spanId:o,traceFlags:p,traceState:c};if(h.decision===x9.NOT_RECORD)return kt.debug("Recording is off, propagating context in a non-recording span"),ta.wrapSpanContext(G);let Z=S9(Object.assign(m,h.attributes));return new zJe({resource:this._resource,scope:this.instrumentationScope,context:n,spanContext:G,name:e,kind:d,links:u,parentSpanContext:a,attributes:Z,startTime:r.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:b})}startActiveSpan(e,r,n,s){let l,o,a;if(arguments.length<2)return;arguments.length===2?a=r:arguments.length===3?(l=r,a=n):(l=r,o=n,a=s);let I=o??di.active(),c=this.startSpan(e,l,I),d=ta.setSpan(I,c);return di.with(d,a,void 0,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}});var $Je,atn=g(()=>{Tc();$Je=class{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let r of this._spanProcessors)e.push(r.forceFlush());return new Promise(r=>{Promise.all(e).then(()=>{r()}).catch(n=>{oN(n||new Error("MultiSpanProcessor: forceFlush failed")),r()})})}onStart(e,r){for(let n of this._spanProcessors)n.onStart(e,r)}onEnding(e){for(let r of this._spanProcessors)r.onEnding&&r.onEnding(e)}onEnd(e){for(let r of this._spanProcessors)r.onEnd(e)}shutdown(){let e=[];for(let r of this._spanProcessors)e.push(r.shutdown());return new Promise((r,n)=>{Promise.all(e).then(()=>{r()},n)})}}});var _9,Ebe,Itn=g(()=>{Tc();MJe();itn();vwt();atn();Hwt();(function(t){t[t.resolved=0]="resolved",t[t.timeout=1]="timeout",t[t.error=2]="error",t[t.unresolved=3]="unresolved"})(_9||(_9={}));Ebe=class{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){let r=fwt({},DJe(),Den(e));this._resource=r.resource??Wbe(),this._config=Object.assign({},r,{resource:this._resource});let n=[];e.spanProcessors?.length&&n.push(...e.spanProcessors),this._activeSpanProcessor=new $Je(n)}getTracer(e,r,n){let s=`${e}@${r||""}:${n?.schemaUrl||""}`;return this._tracers.has(s)||this._tracers.set(s,new qJe({name:e,version:r,schemaUrl:n?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(s)}forceFlush(){let e=this._config.forceFlushTimeoutMillis,r=this._activeSpanProcessor._spanProcessors.map(n=>new Promise(s=>{let l,o=setTimeout(()=>{s(new Error(`Span processor did not completed within timeout period of ${e} ms`)),l=_9.timeout},e);n.forceFlush().then(()=>{clearTimeout(o),l!==_9.timeout&&(l=_9.resolved,s(l))}).catch(a=>{clearTimeout(o),l=_9.error,s(a)})}));return new Promise((n,s)=>{Promise.all(r).then(l=>{let o=l.filter(a=>a!==_9.resolved);o.length>0?s(o):n()}).catch(l=>s([l]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}});var Ybe,ctn=g(()=>{Rl();Tc();Ybe=class{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new O9(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,r){}onEnd(e){if(this._shutdownOnce.isCalled||(e.spanContext().traceFlags&ju.SAMPLED)===0)return;let r=this._doExport(e).catch(n=>oN(n));this._pendingExports.add(r),r.finally(()=>this._pendingExports.delete(r))}async _doExport(e){e.resource.asyncAttributesPending&&await e.resource.waitForAsyncAttributes?.();let r=await BJe._export(this._exporter,[e]);if(r.code!==ac.SUCCESS)throw r.error??new Error(`SimpleSpanProcessor: span export failed (status ${r})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}});var dtn=g(()=>{Itn();Xwt();ctn()});var Ku,eSe=g(()=>{(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Ku||(Ku={}))});var Kn,ab,v5=g(()=>{(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(Kn||(Kn={}));(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(ab||(ab={}))});function tSe(t){let e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(r=>[r,t[r]])))}function utn(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}function H5(t,e){let r,n=new Promise(function(l,o){r=setTimeout(function(){o(new Vbe("Operation timed out."))},e)});return Promise.race([t,n]).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s})}function mtn(t,e){if(t.size!==e.size)return!1;for(let r of t)if(!e.has(r))return!1;return!0}function htn(t,e){let r=0,n=t.length-1,s=t.length;for(;n>=r;){let l=r+Math.trunc((n-r)/2);t[l]<e?r=l+1:(s=l,n=l-1)}return s}function btn(t,e){return t.toLowerCase()===e.toLowerCase()}var Vbe,mF=g(()=>{Vbe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var F0,xq=g(()=>{(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(F0||(F0={}))});var fbe,ptn=g(()=>{xq();fbe=class{kind=F0.DROP;createAccumulation(){}merge(e,r){}diff(e,r){}toMetricData(e,r,n,s){}}});function MKs(t){let e=t.map(()=>0);return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Jq,Sq,Gtn=g(()=>{xq();v5();mF();Jq=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,r,n=!0,s=MKs(r)){this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=s}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let r=htn(this._boundaries,e);this._current.buckets.counts[r]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Sq=class{kind=F0.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,r){this._boundaries=e,this._recordMinMax=r}createAccumulation(e){return new Jq(e,this._boundaries,this._recordMinMax)}merge(e,r){let n=e.toPointValue(),s=r.toPointValue(),l=n.buckets.counts,o=s.buckets.counts,a=new Array(l.length);for(let d=0;d<l.length;d++)a[d]=l[d]+o[d];let I=1/0,c=-1/0;return this._recordMinMax&&(n.hasMinMax&&s.hasMinMax?(I=Math.min(n.min,s.min),c=Math.max(n.max,s.max)):n.hasMinMax?(I=n.min,c=n.max):s.hasMinMax&&(I=s.min,c=s.max)),new Jq(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:a},count:n.count+s.count,sum:n.sum+s.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||s.hasMinMax),min:I,max:c})}diff(e,r){let n=e.toPointValue(),s=r.toPointValue(),l=n.buckets.counts,o=s.buckets.counts,a=new Array(l.length);for(let I=0;I<l.length;I++)a[I]=o[I]-l[I];return new Jq(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:a},count:s.count-n.count,sum:s.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,r,n,s){return{descriptor:e,aggregationTemporality:r,dataPointType:ab.HISTOGRAM,dataPoints:n.map(([l,o])=>{let a=o.toPointValue(),I=e.type===Kn.GAUGE||e.type===Kn.UP_DOWN_COUNTER||e.type===Kn.OBSERVABLE_GAUGE||e.type===Kn.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:o.startTime,endTime:s,value:{min:a.hasMinMax?a.min:void 0,max:a.hasMinMax?a.max:void 0,sum:I?void 0:a.sum,buckets:a.buckets,count:a.count}}})}}}});var wbe,Lwt,gtn=g(()=>{wbe=class t{backing;indexBase;indexStart;indexEnd;constructor(e=new Lwt,r=0,n=0,s=0){this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=s}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,r)=>this.at(r))}at(e){let r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)}incrementBucket(e,r){this.backing.increment(e,r)}decrementBucket(e,r){this.backing.decrement(e,r)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let r=1+this.indexEnd-this.indexStart,n=1<<e,s=0,l=0;for(let o=this.indexStart;o<=this.indexEnd;){let a=o%n;a<0&&(a+=n);for(let I=a;I<n&&s<r;I++)this._relocateBucket(l,s),s++,o++;l++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))}},Lwt=class t{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,r,n){let s=new Array(e).fill(0);s.splice(n,this._counts.length-r,...this._counts.slice(r)),s.splice(0,r,...this._counts.slice(0,r)),this._counts=s}reverse(e,r){let n=Math.floor((e+r)/2)-e;for(let s=0;s<n;s++){let l=this._counts[e+s];this._counts[e+s]=this._counts[r-s-1],this._counts[r-s-1]=l}}emptyBucket(e){let r=this._counts[e];return this._counts[e]=0,r}increment(e,r){this._counts[e]+=r}decrement(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0}clone(){return new t([...this._counts])}}});function rSe(t){let e=new DataView(new ArrayBuffer(8));return e.setFloat64(0,t),((e.getUint32(0)&2146435072)>>20)-1023}function nSe(t){let e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);let r=e.getUint32(0),n=e.getUint32(4);return(r&1048575)*Math.pow(2,32)+n}var Fbe,xwt=g(()=>{Fbe=Math.pow(2,-1022)});function Cbe(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function Ntn(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var sSe=g(()=>{});var zY,lSe=g(()=>{zY=class extends Error{}});var oSe,Wtn=g(()=>{xwt();sSe();lSe();oSe=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e<Fbe)return this._minNormalLowerBoundaryIndex();let r=rSe(e),n=this._rightShift(nSe(e)-1,52);return r+n>>this._shift}lowerBoundary(e){let r=this._minNormalLowerBoundaryIndex();if(e<r)throw new zY(`underflow: ${e} is < minimum lower boundary: ${r}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new zY(`overflow: ${e} is > maximum lower boundary: ${n}`);return Cbe(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=-1022>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return 1023>>this._shift}_rightShift(e,r){return Math.floor(e*Math.pow(2,-r))}}});var iSe,ytn=g(()=>{xwt();sSe();lSe();iSe=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=Cbe(Math.LOG2E,e),this._inverseFactor=Cbe(Math.LN2,-e)}mapToIndex(e){if(e<=Fbe)return this._minNormalLowerBoundaryIndex()-1;if(nSe(e)===0)return(rSe(e)<<this._scale)-1;let r=Math.floor(Math.log(e)*this._scaleFactor),n=this._maxNormalLowerBoundaryIndex();return r>=n?n:r}lowerBoundary(e){let r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new zY(`overflow: ${e} is > maximum lower boundary: ${r}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Fbe;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new zY(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return-1022<<this._scale}_maxNormalLowerBoundaryIndex(){return(1024<<this._scale)-1}}});function Twt(t){if(t>Etn||t<Rtn)throw new zY(`expected scale >= ${Rtn} && <= ${Etn}, got: ${t}`);return _Ks[t+10]}var Rtn,Etn,_Ks,Ytn=g(()=>{Wtn();ytn();lSe();Rtn=-10,Etn=20,_Ks=Array.from({length:31},(t,e)=>e>10?new iSe(e-10):new oSe(e-10))});var Tq,DKs,PKs,Bwt,aSe,Qbe,Vtn=g(()=>{xq();v5();Rl();gtn();Ytn();sSe();Tq=class t{static combine(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))}low;high;constructor(e,r){this.low=e,this.high=r}},DKs=20,PKs=160,Bwt=2,aSe=class t{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,r=PKs,n=!0,s=0,l=0,o=0,a=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,c=new wbe,d=new wbe,u=Twt(DKs)){this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=s,this._count=l,this._zeroCount=o,this._min=a,this._max=I,this._positive=c,this._negative=d,this._mapping=u,this._maxSize<Bwt&&(kt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${Bwt}`),this._maxSize=Bwt)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}}merge(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;let r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;let r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)}clone(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,r,n){let s=this._mapping.mapToIndex(r),l=!1,o=0,a=0;if(e.length===0?(e.indexStart=s,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):s<e.indexStart&&e.indexEnd-s>=this._maxSize?(l=!0,a=s,o=e.indexEnd):s>e.indexEnd&&s-e.indexStart>=this._maxSize&&(l=!0,a=e.indexStart,o=s),l){let I=this._changeScale(o,a);this._downscale(I),s=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,s,n)}_incrementIndexBy(e,r,n){if(n===0)return;if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){let l=e.indexEnd-r;l>=e.backing.length&&this._grow(e,l+1),e.indexStart=r}else if(r>e.indexEnd){let l=r-e.indexStart;l>=e.backing.length&&this._grow(e,l+1),e.indexEnd=r}let s=r-e.indexBase;s<0&&(s+=e.backing.length),e.incrementBucket(s,n)}_grow(e,r){let n=e.backing.length,s=e.indexBase-e.indexStart,l=n-s,o=Ntn(r);o>this._maxSize&&(o=this._maxSize);let a=o-s;e.backing.growTo(o,l,a)}_changeScale(e,r){let n=0;for(;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n}_downscale(e){if(e===0)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);let r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Twt(r)}_minScale(e){let r=Math.min(this.scale,e.scale),n=Tq.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),s=Tq.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(s.high,s.low))}_highLowAtScale(e,r,n){if(e.length===0)return new Tq(0,-1);let s=r-n;return new Tq(e.indexStart>>s,e.indexEnd>>s)}_mergeBuckets(e,r,n,s){let l=n.offset,o=r.scale-s;for(let a=0;a<n.length;a++)this._incrementIndexBy(e,l+a>>o,n.at(a))}_diffBuckets(e,r,n,s){let l=n.offset,o=r.scale-s;for(let a=0;a<n.length;a++){let c=(l+a>>o)-e.indexBase;c<0&&(c+=e.backing.length),e.decrementBucket(c,n.at(a))}e.trim()}},Qbe=class{kind=F0.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,r){this._maxSize=e,this._recordMinMax=r}createAccumulation(e){return new aSe(e,this._maxSize,this._recordMinMax)}merge(e,r){let n=r.clone();return n.merge(e),n}diff(e,r){let n=r.clone();return n.diff(e),n}toMetricData(e,r,n,s){return{descriptor:e,aggregationTemporality:r,dataPointType:ab.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([l,o])=>{let a=o.toPointValue(),I=e.type===Kn.GAUGE||e.type===Kn.UP_DOWN_COUNTER||e.type===Kn.OBSERVABLE_GAUGE||e.type===Kn.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:o.startTime,endTime:s,value:{min:a.hasMinMax?a.min:void 0,max:a.hasMinMax?a.max:void 0,sum:I?void 0:a.sum,positive:{offset:a.positive.offset,bucketCounts:a.positive.bucketCounts},negative:{offset:a.negative.offset,bucketCounts:a.negative.bucketCounts},count:a.count,scale:a.scale,zeroCount:a.zeroCount}}})}}}});var Bq,vbe,ftn=g(()=>{xq();Tc();v5();Bq=class{startTime;_current;sampleTime;constructor(e,r=0,n=[0,0]){this.startTime=e,this._current=r,this.sampleTime=n}record(e){this._current=e,this.sampleTime=Eg(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},vbe=class{kind=F0.LAST_VALUE;createAccumulation(e){return new Bq(e)}merge(e,r){let n=kq(r.sampleTime)>=kq(e.sampleTime)?r:e;return new Bq(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,r){let n=kq(r.sampleTime)>=kq(e.sampleTime)?r:e;return new Bq(r.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,r,n,s){return{descriptor:e,aggregationTemporality:r,dataPointType:ab.GAUGE,dataPoints:n.map(([l,o])=>({attributes:l,startTime:o.startTime,endTime:s,value:o.toPointValue()}))}}}});var X5,Oq,wtn=g(()=>{xq();v5();X5=class{startTime;monotonic;_current;reset;constructor(e,r,n=0,s=!1){this.startTime=e,this.monotonic=r,this._current=n,this.reset=s}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Oq=class{kind=F0.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new X5(e,this.monotonic)}merge(e,r){let n=e.toPointValue(),s=r.toPointValue();return r.reset?new X5(r.startTime,this.monotonic,s,r.reset):new X5(e.startTime,this.monotonic,n+s)}diff(e,r){let n=e.toPointValue(),s=r.toPointValue();return this.monotonic&&n>s?new X5(r.startTime,this.monotonic,s,!0):new X5(r.startTime,this.monotonic,s-n)}toMetricData(e,r,n,s){return{descriptor:e,aggregationTemporality:r,dataPointType:ab.SUM,dataPoints:n.map(([l,o])=>({attributes:l,startTime:o.startTime,endTime:s,value:o.toPointValue()})),isMonotonic:this.monotonic}}}});var Ftn=g(()=>{ptn();Gtn();Vtn();ftn();wtn()});var Owt,Uwt,Mwt,zwt,Hbe,Xbe,_wt,Dwt,Pwt,jwt,Kwt,lCi,Ctn,Qtn=g(()=>{Rl();Ftn();v5();Owt=class t{static DEFAULT_INSTANCE=new fbe;createAggregator(e){return t.DEFAULT_INSTANCE}},Uwt=class t{static MONOTONIC_INSTANCE=new Oq(!0);static NON_MONOTONIC_INSTANCE=new Oq(!1);createAggregator(e){switch(e.type){case Kn.COUNTER:case Kn.OBSERVABLE_COUNTER:case Kn.HISTOGRAM:return t.MONOTONIC_INSTANCE;default:return t.NON_MONOTONIC_INSTANCE}}},Mwt=class t{static DEFAULT_INSTANCE=new vbe;createAggregator(e){return t.DEFAULT_INSTANCE}},zwt=class t{static DEFAULT_INSTANCE=new Sq([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return t.DEFAULT_INSTANCE}},Hbe=class{_boundaries;_recordMinMax;constructor(e,r=!0){if(e==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=e.concat(),e=e.sort((l,o)=>l-o);let n=e.lastIndexOf(-1/0),s=e.indexOf(1/0);s===-1&&(s=void 0),this._boundaries=e.slice(n+1,s),this._recordMinMax=r}createAggregator(e){return new Sq(this._boundaries,this._recordMinMax)}},Xbe=class{_maxSize;_recordMinMax;constructor(e=160,r=!0){this._maxSize=e,this._recordMinMax=r}createAggregator(e){return new Qbe(this._maxSize,this._recordMinMax)}},_wt=class{_resolve(e){switch(e.type){case Kn.COUNTER:case Kn.UP_DOWN_COUNTER:case Kn.OBSERVABLE_COUNTER:case Kn.OBSERVABLE_UP_DOWN_COUNTER:return Pwt;case Kn.GAUGE:case Kn.OBSERVABLE_GAUGE:return jwt;case Kn.HISTOGRAM:return e.advice.explicitBucketBoundaries?new Hbe(e.advice.explicitBucketBoundaries):Kwt}return kt.warn(`Unable to recognize instrument type: ${e.type}`),Dwt}createAggregator(e){return this._resolve(e).createAggregator(e)}},Dwt=new Owt,Pwt=new Uwt,jwt=new Mwt,Kwt=new zwt,lCi=new Xbe,Ctn=new _wt});function ISe(t){switch(t.type){case Bp.DEFAULT:return Ctn;case Bp.DROP:return Dwt;case Bp.SUM:return Pwt;case Bp.LAST_VALUE:return jwt;case Bp.EXPONENTIAL_HISTOGRAM:{let e=t;return new Xbe(e.options?.maxSize,e.options?.recordMinMax)}case Bp.EXPLICIT_BUCKET_HISTOGRAM:{let e=t;return e.options==null?Kwt:new Hbe(e.options?.boundaries,e.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}var Bp,kbe=g(()=>{Qtn();(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.DROP=1]="DROP",t[t.SUM=2]="SUM",t[t.LAST_VALUE=3]="LAST_VALUE",t[t.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"})(Bp||(Bp={}))});var vtn,Htn,Xtn=g(()=>{eSe();kbe();vtn=t=>({type:Bp.DEFAULT}),Htn=t=>Ku.CUMULATIVE});var cSe,ktn=g(()=>{Rl();mF();Xtn();cSe=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??vtn,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??Htn,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");let[r,...n]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(a=>a.collect({timeoutMillis:e?.timeoutMillis}))]),s=r.errors.concat(n.flatMap(a=>a.errors)),l=r.resourceMetrics.resource,o=r.resourceMetrics.scopeMetrics.concat(n.flatMap(a=>a.resourceMetrics.scopeMetrics));return{resourceMetrics:{resource:l,scopeMetrics:o},errors:s}}async shutdown(e){if(this._shutdown){kt.error("Cannot call shutdown twice.");return}e?.timeoutMillis==null?await this.onShutdown():await H5(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){kt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await H5(this.onForceFlush(),e.timeoutMillis)}}});var Lbe,Ltn=g(()=>{Rl();Tc();ktn();mF();Lbe=class extends cSe{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){let{exporter:r,exportIntervalMillis:n=6e4,metricProducers:s}=e,{exportTimeoutMillis:l=3e4}=e;if(super({aggregationSelector:r.selectAggregation?.bind(r),aggregationTemporalitySelector:r.selectAggregationTemporality?.bind(r),metricProducers:s}),n<=0)throw Error("exportIntervalMillis must be greater than 0");if(l<=0)throw Error("exportTimeoutMillis must be greater than 0");if(n<l){if("exportIntervalMillis"in e&&"exportTimeoutMillis"in e)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");kt.info(`Timeout of ${l} exceeds the interval of ${n}. Clamping timeout to interval duration.`),l=n}this._exportInterval=n,this._exportTimeout=l,this._exporter=r}async _runOnce(){try{await H5(this._doRun(),this._exportTimeout)}catch(e){if(e instanceof Vbe){kt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}oN(e)}}async _doRun(){let{resourceMetrics:e,errors:r}=await this.collect({timeoutMillis:this._exportTimeout});if(r.length>0&&kt.error("PeriodicExportingMetricReader: metrics collection errors",...r),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(s){kt.debug("Error while resolving async portion of resource: ",s),oN(s)}if(e.scopeMetrics.length===0)return;let n=await BJe._export(this._exporter,e);if(n.code!==ac.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${n.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),typeof this._interval!="number"&&this._interval.unref()}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}});var dSe,xtn=g(()=>{dSe=class{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,r){return this._registeredViews.filter(s=>this._matchInstrument(s.instrumentSelector,e)&&this._matchMeter(s.meterSelector,r))}_matchInstrument(e,r){return(e.getType()===void 0||r.type===e.getType())&&e.getNameFilter().match(r.name)&&e.getUnitFilter().match(r.unit)}_matchMeter(e,r){return e.getNameFilter().match(r.name)&&(r.version===void 0||e.getVersionFilter().match(r.version))&&(r.schemaUrl===void 0||e.getSchemaUrlFilter().match(r.schemaUrl))}}});function _Y(t,e,r){return KKs(t)||kt.warn(`Invalid metric name: "${t}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:t,type:e,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??yg.DOUBLE,advice:r?.advice??{}}}function Jtn(t,e){return{name:t.name??e.name,description:t.description??e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function Stn(t,e){return btn(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}function KKs(t){return jKs.test(t)}var jKs,xbe=g(()=>{Rl();mF();jKs=/^[a-z][a-z0-9_.\-/]{0,254}$/i});function Jbe(t){return t instanceof Mq}var Uq,uSe,mSe,hSe,bSe,Mq,pSe,GSe,gSe,ZSe=g(()=>{Rl();Tc();Uq=class{_writableMetricStorage;_descriptor;constructor(e,r){this._writableMetricStorage=e,this._descriptor=r}_record(e,r={},n=di.active()){if(typeof e!="number"){kt.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===yg.INT&&!Number.isInteger(e)&&(kt.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,r,n,Eg(Date.now()))}},uSe=class extends Uq{add(e,r,n){this._record(e,r,n)}},mSe=class extends Uq{add(e,r,n){if(e<0){kt.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,r,n)}},hSe=class extends Uq{record(e,r,n){this._record(e,r,n)}},bSe=class extends Uq{record(e,r,n){if(e<0){kt.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,r,n)}},Mq=class{_metricStorages;_descriptor;_observableRegistry;constructor(e,r,n){this._descriptor=e,this._metricStorages=r,this._observableRegistry=n}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}},pSe=class extends Mq{},GSe=class extends Mq{},gSe=class extends Mq{}});var NSe,Ttn=g(()=>{xbe();ZSe();v5();NSe=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,r){let n=_Y(e,Kn.GAUGE,r),s=this._meterSharedState.registerMetricStorage(n);return new hSe(s,n)}createHistogram(e,r){let n=_Y(e,Kn.HISTOGRAM,r),s=this._meterSharedState.registerMetricStorage(n);return new bSe(s,n)}createCounter(e,r){let n=_Y(e,Kn.COUNTER,r),s=this._meterSharedState.registerMetricStorage(n);return new mSe(s,n)}createUpDownCounter(e,r){let n=_Y(e,Kn.UP_DOWN_COUNTER,r),s=this._meterSharedState.registerMetricStorage(n);return new uSe(s,n)}createObservableGauge(e,r){let n=_Y(e,Kn.OBSERVABLE_GAUGE,r),s=this._meterSharedState.registerAsyncMetricStorage(n);return new GSe(n,s,this._meterSharedState.observableRegistry)}createObservableCounter(e,r){let n=_Y(e,Kn.OBSERVABLE_COUNTER,r),s=this._meterSharedState.registerAsyncMetricStorage(n);return new pSe(n,s,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,r){let n=_Y(e,Kn.OBSERVABLE_UP_DOWN_COUNTER,r),s=this._meterSharedState.registerAsyncMetricStorage(n);return new gSe(n,s,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,r){this._meterSharedState.observableRegistry.addBatchCallback(e,r)}removeBatchObservableCallback(e,r){this._meterSharedState.observableRegistry.removeBatchCallback(e,r)}}});var zq,qwt=g(()=>{xbe();zq=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=_Y(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}});var $wt,iN,Sbe=g(()=>{mF();$wt=class{_valueMap=new Map;_keyMap=new Map;_hash;constructor(e){this._hash=e}get(e,r){return r??=this._hash(e),this._valueMap.get(r)}getOrDefault(e,r){let n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);let s=r();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,s),s}set(e,r,n){n??=this._hash(e),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r)}has(e,r){return r??=this._hash(e),this._valueMap.has(r)}*keys(){let e=this._keyMap.entries(),r=e.next();for(;r.done!==!0;)yield[r.value[1],r.value[0]],r=e.next()}*entries(){let e=this._valueMap.entries(),r=e.next();for(;r.done!==!0;)yield[this._keyMap.get(r.value[0]),r.value[1],r.value[0]],r=e.next()}get size(){return this._valueMap.size}},iN=class extends $wt{constructor(){super(tSe)}}});var _q,e1t=g(()=>{mF();Sbe();_q=class{_activeCollectionStorage=new iN;_cumulativeMemoStorage=new iN;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,r){this._aggregator=e,this._cardinalityLimit=(r??2e3)-1,this._overflowHashCode=tSe(this._overflowAttributes)}record(e,r,n,s){let l=this._activeCollectionStorage.get(r);if(!l){if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(s))?.record(e);return}l=this._aggregator.createAccumulation(s),this._activeCollectionStorage.set(r,l)}l?.record(e)}batchCumulate(e,r){Array.from(e.entries()).forEach(([n,s,l])=>{let o=this._aggregator.createAccumulation(r);o?.record(s);let a=o;if(this._cumulativeMemoStorage.has(n,l)){let I=this._cumulativeMemoStorage.get(n,l);a=this._aggregator.diff(I,o)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(n=this._overflowAttributes,l=this._overflowHashCode,this._cumulativeMemoStorage.has(n,l))){let I=this._cumulativeMemoStorage.get(n,l);a=this._aggregator.diff(I,o)}if(this._activeCollectionStorage.has(n,l)){let I=this._activeCollectionStorage.get(n,l);a=this._aggregator.merge(I,a)}this._cumulativeMemoStorage.set(n,o,l),this._activeCollectionStorage.set(n,a,l)})}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new iN,e}}});function qKs(t){return Array.from(t.entries())}var Dq,t1t=g(()=>{eSe();Sbe();Dq=class t{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,r){this._aggregator=e,r.forEach(n=>{this._unreportedAccumulations.set(n,[])})}buildMetrics(e,r,n,s){this._stashAccumulations(n);let l=this._getMergedUnreportedAccumulations(e),o=l,a;if(this._reportHistory.has(e)){let c=this._reportHistory.get(e),d=c.collectionTime;a=c.aggregationTemporality,a===Ku.CUMULATIVE?o=t.merge(c.accumulations,l,this._aggregator):o=t.calibrateStartTime(c.accumulations,l,d)}else a=e.selectAggregationTemporality(r.type);this._reportHistory.set(e,{accumulations:o,collectionTime:s,aggregationTemporality:a});let I=qKs(o);if(I.length!==0)return this._aggregator.toMetricData(r,a,I,s)}_stashAccumulations(e){let r=this._unreportedAccumulations.keys();for(let n of r){let s=this._unreportedAccumulations.get(n);s===void 0&&(s=[],this._unreportedAccumulations.set(n,s)),s.push(e)}}_getMergedUnreportedAccumulations(e){let r=new iN,n=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),n===void 0)return r;for(let s of n)r=t.merge(r,s,this._aggregator);return r}static merge(e,r,n){let s=e,l=r.entries(),o=l.next();for(;o.done!==!0;){let[a,I,c]=o.value;if(e.has(a,c)){let d=e.get(a,c),u=n.merge(d,I);s.set(a,u,c)}else s.set(a,I,c);o=l.next()}return s}static calibrateStartTime(e,r,n){for(let[s,l]of e.keys())r.get(s,l)?.setStartTime(n);return r}}});var ASe,Btn=g(()=>{qwt();e1t();t1t();Sbe();ASe=class extends zq{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,r,n,s,l){super(e),this._aggregationCardinalityLimit=l,this._deltaMetricStorage=new _q(r,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Dq(r,s),this._attributesProcessor=n}record(e,r){let n=new iN;Array.from(e.entries()).forEach(([s,l])=>{n.set(this._attributesProcessor.process(s),l)}),this._deltaMetricStorage.batchCumulate(n,r)}collect(e,r){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,r)}}});function r1t(t,e){let r="";return t.unit!==e.unit&&(r+=` - Unit '${t.unit}' does not match '${e.unit}'
4794
4832
  `),t.type!==e.type&&(r+=` - Type '${t.type}' does not match '${e.type}'
4795
4833
  `),t.valueType!==e.valueType&&(r+=` - Value Type '${t.valueType}' does not match '${e.valueType}'