@tsuga/cli 1.23.0 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -5
- package/dist/cli.js +5 -5
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -42,7 +42,7 @@ ${Km.map((o,i)=>_q(o,t===0?0:i/t)).join(`
|
|
|
42
42
|
`)}var EO="/oauth/callback",Uq=5*ca,wq=Vm("Login complete","You can close this tab and return to the terminal."),qp=Vm("Login failed","Return to the terminal for details.");function vq(e){return(0,Jm.platform)()==="darwin"?["open",[e]]:(0,Jm.platform)()==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]]}function Nq(e){let[t,n]=vq(e),o=(0,yO.spawnSync)(t,n,{stdio:"ignore"});return o.error===void 0&&o.status===0}async function Lq(e,t,n){return new Promise((o,i)=>{let a=setTimeout(()=>{i(new Error("Timed out waiting for the browser to complete login (5 minutes)."))},Uq),c=(l,m,f,h)=>{l.writeHead(m,{"Content-Type":"text/html"}),l.end(f),clearTimeout(a),h()};e.on("request",(l,m)=>{let f=new URL(l.url??"/",n);if(f.pathname!==EO){m.writeHead(404,{"Content-Type":"text/html"}),m.end(qp);return}let h=f.searchParams.get("error");if(h){let I=f.searchParams.get("error_description")??"";c(m,400,qp,()=>i(new Error(`Authorization failed: ${h}${I?` (${I})`:""}`)));return}if(f.searchParams.get("state")!==t){c(m,400,qp,()=>i(new Error("State mismatch on OAuth callback; aborting for safety.")));return}let E=f.searchParams.get("code");if(!E){c(m,400,qp,()=>i(new Error("OAuth callback did not include an authorization code.")));return}c(m,200,wq,()=>o(E))})})}async function _O(e){let t=(0,TO.createServer)();t.on("connection",a=>a.unref()),await new Promise((a,c)=>{t.once("error",c),t.listen(0,"127.0.0.1",()=>{t.off("error",c),a()})});let{port:n}=t.address(),o=`http://127.0.0.1:${n}`,i=`${o}${EO}`;try{let a=e.buildAuthorizeUrl(i);return Nq(a)?V("Opening your browser to complete login..."):(V("Visit this URL in your browser to complete login:"),V(` ${a}`)),{code:await Lq(t,e.state,o),redirectUri:i}}finally{t.close()}}var Wt=require("node:fs"),sd=require("node:os"),no=require("node:path");var bO=rn(require("os"),1),Va=rn(require("path"),1),hn=bO.default.homedir(),{env:ro}=process,IO=ro.XDG_DATA_HOME||(hn?Va.default.join(hn,".local","share"):void 0),Fp=ro.XDG_CONFIG_HOME||(hn?Va.default.join(hn,".config"):void 0),lPe=ro.XDG_STATE_HOME||(hn?Va.default.join(hn,".local","state"):void 0),SO=ro.XDG_CACHE_HOME||(hn?Va.default.join(hn,".cache"):void 0),mPe=ro.XDG_RUNTIME_DIR||void 0,kq=(ro.XDG_DATA_DIRS||"/usr/local/share/:/usr/share/").split(":");IO&&kq.unshift(IO);var Mq=(ro.XDG_CONFIG_DIRS||"/etc/xdg").split(":");Fp&&Mq.unshift(Fp);var AO=new Set(["api.tsuga.com","api.tsuga-staging.com"]),Dq=new Set(["localhost","127.0.0.1","[::1]"]);function ed(e){let t=e.replace(/\/+$/,"");if(!URL.canParse(t))throw new Error(`TSUGA_API_URL is not a URL: ${t}`);let n=new URL(t);if(!Dq.has(n.hostname)&&(n.protocol!=="https:"||!AO.has(n.hostname)))throw new Error(`Refusing to send credentials to ${t}. Set TSUGA_API_URL to ${[...AO].map(o=>`https://${o}`).join(", ")}, or a localhost URL.`);return t}var OO=require("node:child_process"),xO=require("node:fs"),Qa="/usr/bin/security",td="tsuga-cli",RO=44,Gq=/^https?:\/\/[^\s"'\\]+$/,Wa="the macOS Keychain";function rd(e){if(process.platform!=="darwin"||!Gq.test(e))return!1;try{return(0,xO.lstatSync)(Qa).isFile()}catch{return!1}}function nd(e,t){try{return{status:0,stdout:(0,OO.execFileSync)(Qa,e,{env:{},input:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),stderr:""}}catch(n){let{status:o,stderr:i}=n;return{status:o??1,stdout:"",stderr:i??""}}}function od(e,{status:t,stderr:n}){let o=n.trim()||`\`security\` exited with ${t}`;console.error(`Warning: could not ${e} ${Wa}: ${o}`)}function CO(e){if(!rd(e))return;let t=nd(["find-generic-password","-s",td,"-a",e,"-w"]);if(t.status!==0){t.status!==RO&&od("read the session from",t);return}try{return JSON.parse(t.stdout.trim())}catch{return}}function PO(e,t){if(!rd(e))return!1;let n=Buffer.from(JSON.stringify(t),"utf-8").toString("hex"),o=nd(["-i"],`add-generic-password -U -s ${td} -a ${e} -X ${n}
|
|
43
43
|
`);return o.status!==0?(od("save the session to",o),!1):!0}function id(e){if(!rd(e))return!0;let t=nd(["delete-generic-password","-s",td,"-a",e]);return t.status!==0&&t.status!==RO?(od("remove the session from",t),!1):!0}var UO=(0,no.join)(Fp??(0,no.join)((0,sd.homedir)(),".config"),"tsuga"),oi=(0,no.join)(UO,"config.json"),wO=(0,no.join)(SO??(0,no.join)((0,sd.homedir)(),".cache"),"tsuga"),ad=(0,no.join)(wO,"update-check.json"),Za=ed("https://api.tsuga.com");function vO(e){return uO(e.credential)}function Hp(){if(!(0,Wt.existsSync)(oi))return{};try{let e=JSON.parse((0,Wt.readFileSync)(oi,"utf-8")),{operationApiKey:t,userAuth:n,...o}=e;return!t&&!n?e:{...o,credentials:{...e.credentials,[Za]:{...t?{operationApiKey:t}:{},...n?{userAuth:n}:{},...e.credentials?.[Za]}}}}catch{throw new Error(`Config file corrupted: ${oi}
|
|
44
44
|
Re-authenticate with \`tsuga auth login\` or \`tsuga auth operation-key <OPERATION_API_KEY>\`.`)}}function Xa(){try{return Hp()}catch{return{}}}function ii(e){(0,Wt.mkdirSync)(UO,{recursive:!0,mode:448}),(0,Wt.writeFileSync)(oi,`${JSON.stringify(e,null,2)}
|
|
45
|
-
`,{mode:384})}function cd(e,t=yn()){let n=e.credentials?.[t]??{},o=CO(t);return o?{...n,userAuth:o}:n}function Bp(e,t,n=yn()){return{...e,credentials:{...e.credentials,[n]:t}}}function yn(){return ed(process.env.TSUGA_API_URL?.trim()||Za)}function ai(e){let t=Hp(),n=yn(),o=cd(t,n),i=pO({overrideKey:
|
|
45
|
+
`,{mode:384})}function cd(e,t=yn()){let n=e.credentials?.[t]??{},o=CO(t);return o?{...n,userAuth:o}:n}function Bp(e,t,n=yn()){return{...e,credentials:{...e.credentials,[n]:t}}}function yn(){return ed(process.env.TSUGA_API_URL?.trim()||Za)}function ai(e){let t=Hp(),n=yn(),o=cd(t,n),i=pO({overrideKey:process.env.TSUGA_OPERATION_API_KEY,operationApiKey:o.operationApiKey,userAuth:o.userAuth}),a=t.defaults??{},c=e.clusterId?.trim()||process.env.TSUGA_CLUSTER_ID?.trim()||a.cluster?.trim()||void 0;return{apiUrl:n,credential:i,clusterId:c,defaults:a}}function Ja(){return cd(Hp()).userAuth}function NO(e,t){let n=Xa(),o=yn(),{operationApiKey:i}=n.credentials?.[o]??{},a=t&&i?{operationApiKey:i}:{};if(PO(o,e))return ii(Bp(n,a,o)),Wa;if(!id(o))throw new Error(`Could not save the session to ${Wa}, nor remove the session already stored there. Remove it with \`${Qa} delete-generic-password -s tsuga-cli -a ${o}\` and log in again.`);return ii(Bp(n,{...a,userAuth:e},o)),oi}function LO(e){return NO(e,!1)}function Kp(e){NO(e,!0)}function kO(e){let t=Xa();ii(Bp(t,{operationApiKey:e}))}function MO(){let e=yn(),t=id(e),n=Xa(),o=cd(n,e);if(ii(Bp(n,o.operationApiKey?{operationApiKey:o.operationApiKey}:{},e)),!t)throw new Error(`The session is still in ${Wa}. Remove it with \`${Qa} delete-generic-password -s tsuga-cli -a ${e}\`.`)}function zp(){return oi}var DO={from:"-30m",to:"now",query:"*","max-results":"100"};function jr(e){return(Hp().defaults??{})[e]??DO[e]}function GO(e,t){let n=Xa();ii({...n,defaults:{...n.defaults,[e]:t}})}function $O(){let{defaults:e,...t}=Xa();ii(t)}function jO(e,t){let n=[`API URL: ${e.apiUrl}`],{credential:o}=e;if(o){let a=o.kind;switch(a){case"operation-api-key":n.push(`Operation API key: ${o.token.slice(0,12)}...${o.token.slice(-4)}`);break;case"user-session":n.push(`User session: ${za(o.userAuth.accessToken)} (expires ${o.userAuth.accessExpiresAt})`);break;default:Je(a)}}else n.push("Not authenticated. Run `tsuga auth login` or `tsuga auth operation-key <OPERATION_API_KEY>`.");n.push(`Config: ${t}`),n.push(""),n.push("Defaults (custom overrides marked with *):");let i={...DO,...e.defaults};for(let[a,c]of Object.entries(i)){let l=a in e.defaults?" *":"";n.push(` ${a}: ${c}${l}`)}return`${n.join(`
|
|
46
46
|
`)}
|
|
47
47
|
`}function qO(){if((0,Wt.existsSync)(ad))try{return JSON.parse((0,Wt.readFileSync)(ad,"utf-8")).lastUpdateCheck}catch{return}}function FO(e){(0,Wt.mkdirSync)(wO,{recursive:!0,mode:448}),(0,Wt.writeFileSync)(ad,`${JSON.stringify({lastUpdateCheck:e})}
|
|
48
48
|
`,{mode:384})}async function $q(){let e=yn(),{verifier:t,challenge:n}=mO(),o=(0,BO.randomBytes)(16).toString("base64url"),{code:i,redirectUri:a}=await _O({state:o,buildAuthorizeUrl:m=>iO(e,{redirectUri:m,challenge:n,state:o})}),c=await sO(e,{code:i,verifier:t,redirectUri:a}),l=LO(Fm(c));V(`Logged in. Session token ${za(c.accessToken)} saved to ${l}`)}async function jq(){let e=yn(),t=Ja();if(!t){let n=e===Za?"":` for ${e}`;process.stderr.write(`No user session${n}. Run \`tsuga auth login\`.
|
|
@@ -136,7 +136,7 @@ complete -c tsuga -f -a '(__tsuga_complete)'
|
|
|
136
136
|
Usage:
|
|
137
137
|
bash: eval "$(tsuga completion bash)" # add to ~/.bashrc
|
|
138
138
|
zsh: eval "$(tsuga completion zsh)" # add to ~/.zshrc
|
|
139
|
-
fish: tsuga completion fish > ~/.config/fish/completions/tsuga.fish`).action(t=>{let{rows:n,valueFlags:o}=tB(e);if(t==="bash")V(rB(kx(n),o));else if(t==="zsh")V(nB(kx(n),o));else if(t==="fish")V(iB(oB(n),o));else throw new Error(`Unsupported shell "${t}". Supported: bash, zsh, fish.`)})}function Gx(e){let t=e.command("config").description("Show or manage configuration");t.action(()=>{let n=e.opts(),o=ai({
|
|
139
|
+
fish: tsuga completion fish > ~/.config/fish/completions/tsuga.fish`).action(t=>{let{rows:n,valueFlags:o}=tB(e);if(t==="bash")V(rB(kx(n),o));else if(t==="zsh")V(nB(kx(n),o));else if(t==="fish")V(iB(oB(n),o));else throw new Error(`Unsupported shell "${t}". Supported: bash, zsh, fish.`)})}function Gx(e){let t=e.command("config").description("Show or manage configuration");t.action(()=>{let n=e.opts(),o=ai({clusterId:n.cluster});V(jO(o,zp()).trimEnd())}),t.command("set").description("Set a configuration value").command("default <FLAG_NAME> <VALUE>").description("Set a custom default value for a command flag").allowUnknownOption(!0).action((n,o)=>{GO(n,o),V(`Default set: ${n} = ${o}`)}),t.command("reset").description("Reset configuration values").command("defaults").description("Clear all custom defaults").action(()=>{$O(),V("Custom defaults cleared")})}var $x=`/${"v1"}/docs`,jx=r.Object({path:r.String({description:"Path identifying the page. Documentation pages use a slug path (e.g. `getting-started/send-your-first-logs`). API-reference pages use `api/<operationId>` (e.g. `api/aggregateScalar`)."}),title:r.String({description:'Title of the page (e.g. "Send your first logs" or "POST /v1/aggregation/multi-query/scalar")'}),content:r.String({description:"Raw markdown content of the page"})},{$id:"DocPage",description:"A documentation or API-reference page with its raw markdown content"}),aB={path:"getting-started/send-your-first-logs",title:"Send your first logs",content:`# Send your first logs
|
|
140
140
|
...`};Object.assign(jx,{examples:[aB]});var qx=r.Object({kind:r.Enum(["doc","api"],{description:"`doc` for documentation pages (guides, references, release notes); `api` for API-reference endpoints indexed from the OpenAPI spec. Use this to decide how to present or follow up on the result."}),path:r.String({description:"Path identifying the result. Documentation pages use a slug path (e.g. `data-collection/guides/how-to-add-resource-attributes`). API-reference results use `api/<operationId>` (e.g. `api/aggregateScalar`)."}),title:r.String({description:'Title of the result (e.g. "How to Add Resource Attributes" or "POST /v1/aggregation/multi-query/scalar")'}),subsection:r.Optional(r.String({description:'For documentation pages: the heading path inside the page that matched (e.g. "Language setup"). For API results: the matched field or parameter breadcrumb (e.g. "Body \u203A queries"). Absent when the match is the page or endpoint intro.'})),tab:r.Optional(r.String({description:'Tab label inside the page that the result matched. Set when the matching content is inside a <Tabs><Tab label="\u2026"> block. Always absent for API results.'})),anchor:r.Optional(r.String({description:"For documentation pages: the slugified heading ID used as the URL fragment (e.g. `language-setup`). For API results: the Scalar deep-link fragment (`tag/<tag>/<METHOD><path>`). The `link` field already has this baked in."})),score:r.Number({description:"Relevance score between 0 and 1 (higher is more relevant)"}),excerpt:r.String({description:"Short snippet of matching content"}),link:r.String({description:"URL to the result in the Tsuga app. Documentation pages include the section anchor and tab query parameter when applicable. API results deep-link into the API reference at `/documentation/api#tag/\u2026`."})},{$id:"DocSearchResult",description:"A documentation page or API-reference endpoint search result"}),sB={kind:"doc",path:"data-collection/guides/how-to-add-resource-attributes",title:"How to Add Resource Attributes",subsection:"Set resource attributes by language",tab:"Python",anchor:"set-resource-attributes-by-language",score:.9,excerpt:"...Python SDK setup should use the default resource detectors...",link:"https://www.app.tsuga.com/documentation/data-collection/guides/how-to-add-resource-attributes?tab=Python#set-resource-attributes-by-language"};Object.assign(qx,{examples:[sB]});var Fx=d({description:"Retrieve the raw markdown content of a documentation or API-reference page by its path. Documentation pages use slug paths (e.g. `getting-started/send-your-first-logs`); API-reference pages use `api/<operationId>` (e.g. `api/aggregateScalar`).",operationId:"getDocPage",tags:["public","docs"],url:$x,method:"GET",query:r.Object({path:u({allowEmpty:!1,description:"Documentation path to fetch. Use page slug paths for docs or `api/<operationId>` for API-reference pages."})},{description:"Documentation page lookup query."}),response:jx}),Bx=d({description:"Searches public documentation pages and API-reference endpoints. Use this to build help search or route users to Tsuga docs and API reference results. Results are ranked by relevance; an empty array means no page or endpoint matched the query.",operationId:"searchDocs",tags:["public","docs"],url:`${$x}/search`,method:"GET",query:r.Object({query:u({allowEmpty:!1,description:"Search text to match against documentation and API-reference content."})},{description:"Documentation search query."}),response:r.Array(qx)});function Hx(e,t){let n=e.command("docs").description("Search and fetch Tsuga documentation and API-reference pages");n.command("get <DOC_PATH>").description("Get a documentation or API-reference page by path (e.g. 'getting-started/send-your-first-logs' or 'api/aggregateScalar')").action(async o=>{let i=await t()(Fx,{query:{path:o}});ee(i)}),n.command("search <SEARCH_TEXT>").description("Search Tsuga documentation and the full API reference, ranked by relevance").action(async o=>{let i=await t()(Bx,{query:{query:o}});ee(i)})}var cB=`/${"v1"}/feedback`,Kx=r.Object({id:r.String({description:"API request ID recorded with the feedback."})},{$id:"Feedback",description:"A recorded piece of feedback"}),pB={id:"request-123-abc"};Object.assign(Kx,{examples:[pB]});var zx=r.Object({content:u({allowEmpty:!1,type:"long",description:"Free-text feedback content, e.g. what went wrong, what was confusing, or a suggestion. Required and must be non-empty."})}),uB={content:"The traces command times out for large services."};Object.assign(zx,{examples:[uB]});var Yx=d({description:"Submit free-text feedback about Tsuga tools or APIs, e.g. a tool that failed, returned unusable output, or was confusing to use. Feedback is recorded for the Tsuga team to review and improve tooling.",operationId:"createFeedback",tags:["public","feedback"],url:cB,method:"POST",body:zx,response:Kx});function Vx(e,t){e.command("feedback <MESSAGE...>").description("Send feedback about Tsuga tools or APIs (e.g. a tool that failed or was confusing)").action(async n=>{let o=await t()(Yx,{body:{content:n.join(" ")}});ee(o)})}var lB="^\\S(.*\\S)?$",mB=128,dB=256,fB=r.Object({key:r.String({description:"Tag key attached to the resource. Consumers can use key/value tags for filtering, ownership context, and policy checks."}),value:r.String({description:"Tag value attached to the resource for this key. Tsuga returns the value exactly as stored."})},{title:"Tag"}),gB=r.Object({key:r.String({maxLength:mB,description:"Tag key to attach to the resource."}),value:r.String({maxLength:dB,pattern:lB,description:"Tag value to attach to the resource. Leading or trailing whitespace is rejected."})},{title:"Tag"}),Ft=r.Array(fB,{title:"Tags",description:"Key/value tags applied to the resource. Use them to organize resources and to satisfy tag policies."}),Bt=r.Array(gB,{title:"Tags",maxItems:50,description:"Key/value tags to apply to the resource. Tag policies may require specific keys or values."}),De=r.Optional(Ft),Xe=r.Optional(Bt);var In="/v0/teams",su=["public","private"],au={NAME:"name",CREATED_AT:"createdAt",MEMBER_COUNT:"memberCount",VISIBILITY:"visibility"},hB=r.Enum([au.NAME,au.CREATED_AT,au.MEMBER_COUNT,au.VISIBILITY],{description:"Team field used for sorting list responses. Use `name`, `createdAt`, `memberCount`, or `visibility`."}),Zx=r.Object({color:r.Enum(Ed,{description:"Color token used by Tsuga when rendering the team avatar."}),mode:r.Enum(_d,{description:"Avatar rendering mode selected for the team."}),iconName:r.Enum(xx,{description:"Icon name rendered inside the team avatar when icon mode is used."})}),Od=r.Object({color:r.Enum(Ed),mode:r.Enum(_d)}),Qx=100,Wx=250,mi=r.Object({id:r.String({description:"Unique identifier of the team. Generated by Tsuga and stable for the team lifetime."}),name:r.String({description:"Human-readable team name displayed throughout Tsuga and used in team search."}),description:r.Optional(r.String({description:"Optional free-text description of the team."})),visibility:r.Enum(su,{description:"`public` makes team-owned resources discoverable according to access controls. `private` restricts discovery to team members and authorized users."}),tags:De,createdAt:A({description:"Timestamp when Tsuga created the team."}),updatedAt:A({description:"Timestamp when Tsuga last updated the team metadata."}),memberCount:r.Optional(r.Number({description:"Number of members currently in the team"})),avatar:r.Optional(Zx)}),cu=r.Object({name:r.String({minLength:1,maxLength:Qx,format:ti,description:`Name to assign to the team. Must be kebab-case (lowercase letters, numbers, and dashes only) and unique in the organization. Maximum length is ${Qx} characters.`}),description:r.Optional(r.String({maxLength:Wx,description:`Optional team description. Maximum length is ${Wx} characters.`})),visibility:r.Enum(su,{description:"`public` makes team-owned resources discoverable according to access controls. `private` restricts discovery to team members and authorized users."}),tags:Xe,avatar:r.Optional(Zx)}),yB=r.Object({id:r.String(),name:r.String(),email:r.String(),role:r.Enum(si),joinedTeamAt:A(),orgRole:r.Enum(KO),avatar:r.Optional(Od)}),Xx=r.Object({searchQuery:r.Optional(u({description:"Substring matched against team names and descriptions."})),visibility:r.Optional(r.Enum(su,{description:"Restrict results to teams with this visibility."})),myTeamsOnly:r.Optional(r.Boolean({description:"If true, return only teams that include the authenticated user."}))}),HNe=d({tags:["teams"],url:In,method:"GET",paginated:!0,response:r.Array(mi),query:r.Object({...fe,includeMemberCount:r.Optional(r.Boolean()),...Xx.properties,sortBy:r.Optional(hB),sortDirection:r.Optional(r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending."}))})}),KNe=d({tags:["teams"],url:`${In}/:id`,method:"GET",params:r.Object({id:u()}),response:mi}),zNe=d({tags:["teams"],url:`${In}/:id/members`,method:"GET",params:r.Object({id:u()}),response:r.Array(yB)}),YNe=d({tags:["teams"],url:`${In}/:id/assets`,method:"GET",params:r.Object({id:u()}),response:r.Object({apiKeyCount:r.Number(),logRouteCount:r.Number(),monitorCount:r.Number(),notificationRuleCount:r.Number(),dashboardCount:r.Number()})}),VNe=d({tags:["teams"],url:In,method:"POST",body:cu,response:mi}),QNe=d({tags:["teams"],url:`${In}/:id`,method:"PUT",params:r.Object({id:u()}),body:cu,response:mi}),TB=C("type",[r.Object({type:r.Literal("ids"),teamIds:r.Array(u({allowEmpty:!1}),{minItems:1,maxItems:100})}),r.Object({type:r.Literal("all"),filters:r.Optional(Xx)})]),WNe=d({tags:["teams"],url:`${In}/bulk-update`,method:"POST",body:r.Object({selection:TB,config:r.Object({visibility:r.Enum(su)})}),response:r.Object({})}),ZNe=d({tags:["teams"],url:`${In}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N});var EB=r.Enum(["agent","cli","mcp-codemode","mcp-server","terraform-provider","web-frontend"],{description:"Tsuga client surface that performed the operation. Use this to distinguish UI, CLI, MCP, and Terraform-originated changes."}),pe=C("type",[r.Object({type:r.Literal("user",{description:"The resource was created or updated by a user."}),id:r.String({description:"Unique identifier of the user actor."}),name:r.String({description:"Display name of the user actor at the time of response."}),avatar:r.Optional(Od)}),r.Object({type:r.Literal("operation-api-key",{description:"The resource was created or updated by an operation API key."}),id:r.String({description:"Unique identifier of the operation API key actor."}),name:r.String({description:"Display name of the operation API key actor."}),source:r.Optional(EB)})],{description:"User or operation API key responsible for creating or updating a resource. Returned by Tsuga for audit context."});var At="/v0/monitors",di=["alert","resolve","keep_last_status","consider_zero"],fi=["alert","resolve","keep_last_status"];var eR=["no_aggregation","all","any","each","proportion"],tR=["greater_than","less_than","equal","not_equal","greater_than_or_equal","less_than_or_equal"];var _B=r.Object({formula:r.String({description:"Formula result to compare against the threshold, usually `q1` or a formula alias."}),operator:r.Enum(tR,{description:"Comparison operator used to evaluate the threshold condition."}),threshold:r.Number({description:"Numeric threshold value used by the comparison. May be negative when the formula result can be below zero."})}),IB=r.Object({formula:u({type:"tsuga-formula",description:"Formula result to compare against the threshold, usually `q1` or a formula alias."}),operator:r.Enum(tR,{description:"Comparison operator used to evaluate the threshold condition."}),threshold:r.Number({description:"Numeric threshold value used by the comparison. May be negative when the formula result can be below zero."})}),bB=5,xd=r.Array(_B,{description:"Threshold conditions evaluated against query and formula results. All listed conditions must match for a non-grouped threshold monitor to alert."}),Rd=r.Array(IB,{minItems:1,maxItems:bB,description:"Threshold conditions evaluated against query and formula results. All listed conditions must match for a non-grouped threshold monitor to alert."}),Cd=r.Object({formula:r.String({description:"Formula result analyzed for anomalous behavior, usually `q1` or a formula alias."}),conditionType:r.Enum(["rate","error","cpu","general","to_be_set"],{description:"Anomaly model type Tsuga uses to classify expected behavior: `rate` flags downward anomalies (e.g. count rates), `error` and `cpu` flag upward anomalies (e.g. error counts/rates, CPU usage), `general` flags both directions, and `to_be_set` is a placeholder Tsuga replaces by inferring the model type from the monitor query when the monitor is created or updated."})},{description:"Anomaly detection condition evaluated by this monitor. The `formula` result is compared against behavior learned from historical query results, and the monitor alerts on deviations in the direction implied by `conditionType`."}),Pd=r.Object({formula:u({type:"tsuga-formula",description:"Formula result analyzed for anomalous behavior, usually `q1` or a formula alias."}),conditionType:r.Enum(["rate","error","cpu","general","to_be_set"],{description:"Anomaly model type used to classify expected behavior: `rate` flags downward anomalies (e.g. count rates), `error` and `cpu` flag upward anomalies (e.g. error counts/rates, CPU usage), and `general` flags both directions. Use `to_be_set` to let Tsuga infer the model type from the monitor query during create or update."})},{description:"Anomaly detection condition evaluated by this monitor. The `formula` result is compared against behavior learned from historical query results, and the monitor alerts on deviations in the direction implied by `conditionType`."}),St=[1,2,3,4,5];var pu={timeframe:r.Number({description:"Lookback window, in minutes, that each query-backed threshold monitor evaluation aggregates over. Always a whole number, at least 1."}),groupByFields:r.Array(r.Object({fields:r.Array(r.String(),{description:"Attribute names the monitor splits results by, evaluating each resulting group independently. Empty means the monitor evaluates a single ungrouped series."}),limit:r.Number({description:"Configured limit for this group by. Currently ignored; monitor evaluation applies a fixed limit of 100 groups per field."}),sortOrder:r.Optional(r.Enum(["asc","desc"],{description:"Sort direction applied to groups: ascending or descending."})),replaceNullWith:r.Optional(r.String({description:"Value used to group documents that have no value for a grouped field."}))}),{description:"Monitor group by configuration. The `limit` setting is currently ignored; evaluation applies a fixed limit of 100 groups per field."}),aggregationAlertLogic:r.Optional(r.Enum(eR,{description:"How grouped results are combined into alert state. Use `no_aggregation` only when `groupByFields` is empty; use `all`, `any`, `each`, or `proportion` with non-empty `groupByFields`. `proportion` also requires `proportionAlertThreshold`."})),proportionAlertThreshold:r.Optional(r.Integer({description:"Percentage threshold used when `aggregationAlertLogic` is `proportion`."}))},uu={timeframe:r.Integer({minimum:1,description:"Lookback window, in minutes, that each query-backed threshold monitor evaluation aggregates over."}),groupByFields:r.Array(r.Object({fields:r.Array(u(),{description:"Attribute names the monitor splits results by, evaluating each resulting group independently. Empty or omitted means the monitor evaluates a single ungrouped series."}),limit:r.Number({description:"Configured limit for this group by. Currently ignored; monitor evaluation applies a fixed limit of 100 groups per field."}),sortOrder:r.Optional(r.Enum(["asc","desc"],{description:"Sort direction applied to groups: ascending or descending."})),replaceNullWith:r.Optional(u({allowEmpty:!1,description:"Value used to group documents that have no value for a grouped field."}))}),{maxItems:1,description:"Monitor group by configuration. The `limit` setting is currently ignored; evaluation applies a fixed limit of 100 groups per field."}),aggregationAlertLogic:r.Optional(r.Enum(eR,{description:"How grouped results are combined into alert state. Use `no_aggregation` only when `groupByFields` is empty; use `all`, `any`, `each`, or `proportion` with non-empty `groupByFields`. `proportion` also requires `proportionAlertThreshold`. On create, omitted query-monitor values default to `no_aggregation`; on update, omitted values keep the existing aggregation logic."})),proportionAlertThreshold:r.Optional(r.Integer({minimum:1,maximum:99,description:"Percentage threshold used when `aggregationAlertLogic` is `proportion`."}))},Ud={...pu,timeframe:r.Number({description:"Lookback window, in minutes, that each anomaly monitor evaluation aggregates over. Always a whole number from 5 through 1440."})},wd={...uu,timeframe:r.Integer({minimum:5,maximum:1440,description:"Lookback window, in minutes, that each anomaly monitor evaluation aggregates over."})},rR=r.Object({type:r.Literal("metric",{description:"Threshold monitor over metric aggregations."}),conditions:xd,noDataBehavior:r.Enum(di,{description:"How the monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, `keep_last_status` preserves the previous state, and `consider_zero` evaluates missing values as zero."}),...pu,queries:qr},{$id:"MonitorConfigurationMetric"}),nR=r.Object({type:r.Literal("metric",{description:"Threshold monitor over metric aggregations."}),conditions:Rd,noDataBehavior:r.Enum(di,{description:"How the monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, `keep_last_status` preserves the previous state, and `consider_zero` evaluates missing values as zero."}),...uu,queries:En},{$id:"InputMonitorConfigurationMetric"}),oR=r.Object({type:r.Literal("log",{description:"Threshold monitor over log aggregations."}),conditions:xd,noDataBehavior:r.Enum(di,{description:"How the monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, `keep_last_status` preserves the previous state, and `consider_zero` evaluates missing values as zero."}),...pu,queries:qr},{$id:"MonitorConfigurationLog"}),iR=r.Object({type:r.Literal("log",{description:"Threshold monitor over log aggregations."}),conditions:Rd,noDataBehavior:r.Enum(di,{description:"How the monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, `keep_last_status` preserves the previous state, and `consider_zero` evaluates missing values as zero."}),...uu,queries:En},{$id:"InputMonitorConfigurationLog"}),aR=r.Object({type:r.Literal("trace",{description:"Threshold monitor over trace aggregations."}),conditions:xd,noDataBehavior:r.Enum(di,{description:"How the monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, `keep_last_status` preserves the previous state, and `consider_zero` evaluates missing values as zero."}),...pu,queries:qr},{$id:"MonitorConfigurationTrace"}),SB=r.Object({type:r.Literal("trace",{description:"Threshold monitor over trace aggregations."}),conditions:Rd,noDataBehavior:r.Enum(di,{description:"How the monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, `keep_last_status` preserves the previous state, and `consider_zero` evaluates missing values as zero."}),...uu,queries:En},{$id:"InputMonitorConfigurationTrace"}),sR=r.Object({type:r.Literal("anomaly-log",{description:"Anomaly monitor over log aggregations."}),condition:Cd,noDataBehavior:r.Enum(fi,{description:"How the anomaly monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, and `keep_last_status` preserves the previous state."}),...Ud,queries:qr},{$id:"MonitorConfigurationAnomalyLog"}),cR=r.Object({type:r.Literal("anomaly-log",{description:"Anomaly monitor over log aggregations."}),condition:Pd,noDataBehavior:r.Enum(fi,{description:"How the anomaly monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, and `keep_last_status` preserves the previous state."}),...wd,queries:En},{$id:"InputMonitorConfigurationAnomalyLog"}),pR=r.Object({type:r.Literal("anomaly-metric",{description:"Anomaly monitor over metric aggregations."}),condition:Cd,noDataBehavior:r.Enum(fi,{description:"How the anomaly monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, and `keep_last_status` preserves the previous state."}),...Ud,queries:qr},{$id:"MonitorConfigurationAnomalyMetric"}),uR=r.Object({type:r.Literal("anomaly-metric",{description:"Anomaly monitor over metric aggregations."}),condition:Pd,noDataBehavior:r.Enum(fi,{description:"How the anomaly monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, and `keep_last_status` preserves the previous state."}),...wd,queries:En},{$id:"InputMonitorConfigurationAnomalyMetric"}),lR=r.Object({type:r.Literal("anomaly-trace",{description:"Anomaly monitor over trace aggregations. Use this configuration when Tsuga should learn historical trace query behavior and alert on unusual movement in trace-derived values."}),condition:Cd,noDataBehavior:r.Enum(fi,{description:"How the anomaly monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, and `keep_last_status` preserves the previous state."}),...Ud,queries:qr},{$id:"MonitorConfigurationAnomalyTrace"}),AB=r.Object({type:r.Literal("anomaly-trace",{description:"Anomaly monitor over trace aggregations. Set this value to create or update an anomaly monitor that learns historical trace query behavior and alerts on unusual movement in trace-derived values."}),condition:Pd,noDataBehavior:r.Enum(fi,{description:"How the anomaly monitor updates state when no data is returned. `alert` enters no-data alert state, `resolve` resolves, and `keep_last_status` preserves the previous state."}),...wd,queries:En},{$id:"InputMonitorConfigurationAnomalyTrace"}),mR=r.Object({type:r.Literal("certificate-expiry",{description:"Monitor that alerts before discovered certificates expire."}),warnBeforeInDays:r.Integer({description:"Number of days before certificate expiry when the monitor should warn."}),cloudAccounts:r.Optional(r.Array(r.String(),{description:"Cloud account IDs whose certificates are checked. Omitted means certificates from all cloud accounts are checked."})),aggregationAlertLogic:r.Literal("each",{description:"Certificate expiry monitors alert independently for each certificate."}),noDataBehavior:r.Literal("resolve",{description:"Certificate expiry monitors resolve when matching certificate data disappears."})},{$id:"MonitorConfigurationCertificateExpiry"}),OB=r.Object({type:r.Literal("certificate-expiry",{description:"Monitor that alerts before discovered certificates expire."}),warnBeforeInDays:r.Integer({minimum:1,maximum:365,description:"Number of days before certificate expiry when the monitor should warn. Valid values are 1 through 365."}),cloudAccounts:r.Optional(r.Array(r.String(),{minItems:1,description:"Cloud account IDs whose certificates are checked. Omit to check certificates from all cloud accounts."})),aggregationAlertLogic:r.Literal("each",{description:"Certificate expiry monitors alert independently for each certificate."}),noDataBehavior:r.Literal("resolve",{description:"Certificate expiry monitors resolve when matching certificate data disappears."})},{$id:"InputMonitorConfigurationCertificateExpiry"}),xB=r.Object({type:r.Literal("log-error-pattern",{description:"Monitor that alerts on newly detected log error patterns for the configured team, environment, and optional service. Recovery notifications are not sent for this monitor type."}),aggregationAlertLogic:r.Literal("each",{description:"Fixed aggregation logic for log error pattern monitors. Each new pattern is evaluated as its own alert group."}),noDataBehavior:r.Literal("keep_last_status",{description:"Fixed no-data behavior for log error pattern monitors. Pattern state is kept until inactive pattern groups expire."}),filter:r.Object({teamIds:r.Array(r.String(),{description:"Team IDs whose logs are searched for new error patterns. Tsuga resolves these team IDs to team names when exporting monitor assets."}),env:r.String({description:"Environment whose logs are searched for new error patterns."}),service:r.Optional(r.String({description:"Optional service name whose logs are searched for new error patterns. If omitted, the monitor searches all services matching the team and environment filter."}))},{description:"Log selection used for new error pattern detection. All configured fields must match for logs to be included."})},{$id:"MonitorConfigurationLogErrorPattern"}),RB=r.Object({type:r.Literal("log-error-pattern",{description:"Monitor that alerts on newly detected log error patterns for the configured team, environment, and optional service. Recovery notifications are not sent for this monitor type."}),aggregationAlertLogic:r.Literal("each",{description:"Fixed aggregation logic for log error pattern monitors. Each new pattern is evaluated as its own alert group."}),noDataBehavior:r.Literal("keep_last_status",{description:"Fixed no-data behavior for log error pattern monitors. Pattern state is kept until inactive pattern groups expire."}),filter:r.Object({teamIds:r.Array(u(),{description:"Team IDs whose logs are searched for new error patterns. Tsuga resolves these team IDs to team names when exporting monitor assets."}),env:u({description:"Environment whose logs are searched for new error patterns."}),service:r.Optional(u({description:"Optional service name whose logs are searched for new error patterns. If omitted, the monitor searches all services matching the team and environment filter."}))},{description:"Log selection used for new error pattern detection. All configured fields must match for logs to be included."})},{$id:"InputMonitorConfigurationLogErrorPattern"}),CB=C("type",[rR,oR,aR,sR,pR,xB,lR,mR],{description:"Monitor evaluation configuration. The `type` discriminator determines which telemetry source, condition shape, and evaluation rules Tsuga uses."}),PB=C("type",[nR,iR,SB,cR,uR,AB,RB,OB],{description:"Monitor evaluation configuration. The `type` discriminator determines which telemetry source, condition shape, and evaluation rules Tsuga uses."});var Br=r.Object({id:r.String({description:"Tsuga-generated monitor ID assigned when the monitor is created."}),name:r.String({description:"Display name of the monitor and alert source."}),owner:r.String({description:"Team ID that owns and manages the monitor."}),message:r.Optional(r.String({description:"Caller-supplied message included in notifications triggered by this monitor. Omitted when the monitor was created or last updated without one."})),tags:De,configuration:CB,priority:r.Enum(St,{description:"Monitor priority from 1 through 5, where 1 is highest priority."}),permissions:Tn,dashboardId:r.Optional(r.String({description:"ID of the dashboard linked to this monitor for context when investigating alerts. Caller-supplied. Omitted when no dashboard is linked."})),pauseUntil:r.Optional(A({description:"Timestamp until which the monitor is snoozed."})),creator:r.Optional(pe),updater:r.Optional(pe),createdAt:A({description:"Timestamp when Tsuga created the monitor."}),updatedAt:A({description:"Timestamp when Tsuga last updated the monitor."}),assetUpdatedAt:A({description:"Timestamp used for asset-change tracking across Tsuga-managed resources."}),clusterIds:r.Array(r.String(),{description:"Cluster IDs where the monitor is deployed. Empty means all eligible clusters."})},{title:"Monitor"}),UB=C("type",[rR,oR,aR,sR,pR,lR,mR]),fLe=r.Object({...Br.properties,configuration:UB},{title:"Monitor"}),gLe=r.Object({...Br.properties,configuration:C("type",[nR,iR,cR,uR])},{title:"Monitor"}),is=r.Object({name:u({description:"Display name of the monitor and alert source."}),message:r.Optional(u({type:"long",description:"Message included in notifications triggered by this monitor. Optional on create. On update, omitting it keeps the existing message."})),tags:Xe,configuration:PB,priority:r.Enum(St,{description:"Monitor priority from 1 through 5, where 1 is highest priority."}),owner:u({allowEmpty:!1,description:"Team ID that owns and manages the monitor."}),dashboardId:r.Optional(r.Union([r.Null(),u({allowEmpty:!1})],{description:"ID of the dashboard to link to this monitor for context when investigating alerts. On create: omit or send `null` to leave the monitor unlinked. On update: omit to skip updating this field, send `null` to clear an existing link."})),pauseUntil:r.Optional(u({allowEmpty:!1,type:"date-time",description:"ISO timestamp until which the monitor should be snoozed."})),permissions:Tn,clusterIds:r.Optional(r.Array(u({allowEmpty:!1}),{description:"Cluster IDs where the monitor should be deployed. Empty or omitted means all eligible clusters for cluster-deployed monitor types."}))}),Jx=["threshold","certificate-expiry","anomaly-detection","log-error-pattern"],bn={PRIORITY:"priority",TYPE:"type",NAME:"name",OWNER:"owner",TAGS:"tags",CLUSTER_IDS:"clusterIds",PAUSE_UNTIL:"pauseUntil",ASSET_UPDATED_AT:"assetUpdatedAt"};var vd=r.Object({owners:_e(u({allowEmpty:!1}),{description:"Restrict results to monitors owned by any of these team IDs",maxItems:50}),searchQuery:r.Object({value:u({allowEmpty:!1,description:"Case-insensitive substring matched against monitor ID, monitor name, query filters, and aggregate fields. Wildcard characters are treated literally."}),exclude:r.Optional(r.Boolean({description:"If true, exclude monitors matching this value instead of including them"}))},{description:"Search query filter for monitors."}),tags:_e(Bt.items,{description:"Restrict results to monitors that have at least one of the listed key/value tags",maxItems:50}),priorities:_e(r.Enum(St),{description:"Restrict results to monitors with one of these priorities",maxItems:St.length}),types:_e(r.Enum(Jx),{description:"Restrict results to monitors with these types",maxItems:Jx.length}),activity:r.Enum(["active","snoozed"],{description:"Restrict results by activity status: active monitors or currently snoozed monitors"}),clusterIds:_e(u({allowEmpty:!1}),{description:"Restrict results to monitors deployed to any of these cluster IDs (monitors with no cluster restriction are always included)",maxItems:50})},{description:"Optional filters applied to narrow the returned monitors"}),Nd=r.Partial(r.Object({...fe,filters:r.Partial(vd),sort:r.Object({by:r.Enum([bn.PRIORITY,bn.TYPE,bn.NAME,bn.OWNER,bn.TAGS,bn.CLUSTER_IDS,bn.PAUSE_UNTIL,bn.ASSET_UPDATED_AT],{description:"Field to sort the returned monitors by. For `priority`, `desc` returns highest-priority monitors first because priority 1 is highest."}),direction:r.Enum(["asc","desc"],{description:"Sort direction. For `priority`, `desc` returns priority 1 first and `asc` returns priority 5 first."})},{description:"Optional sorting applied to the returned monitors. Ties are broken by creation time and monitor ID for stable pagination."})})),hLe=d({tags:["monitors"],url:`${At}/query`,method:"POST",paginated:!0,response:r.Array(Br),body:Nd}),yLe=d({tags:["monitors"],url:`${At}/tags/query`,method:"POST",body:r.Object({filters:r.Optional(r.Partial(r.Omit(vd,["tags"])))}),response:Ft}),TLe=d({tags:["monitors"],url:`${At}/counts/query`,method:"POST",body:r.Object({filters:r.Optional(r.Partial(r.Omit(vd,["activity"])))}),response:r.Object({all:r.Integer({description:"Total number of monitors matching the filters that the user can read."}),active:r.Integer({description:"Number of matching readable monitors that are not currently snoozed."}),snoozed:r.Integer({description:"Number of matching readable monitors that are currently snoozed."})})}),ELe=d({tags:["monitors"],url:`${At}/:id`,method:"GET",params:r.Object({id:u()}),response:Br}),_Le=d({tags:["monitors"],url:At,method:"POST",body:is,response:Br}),ILe=d({tags:["monitors"],url:`${At}/:id`,method:"PUT",params:r.Object({id:u()}),body:is,response:Br}),bLe=d({tags:["monitors"],url:`${At}/bulk-update`,method:"PUT",body:r.Object({monitorIds:r.Array(u({allowEmpty:!1}),{minItems:1}),owner:u({allowEmpty:!1})}),response:r.Object({})}),SLe=d({tags:["monitors"],url:`${At}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),ALe=d({tags:["monitors"],url:`${At}/bulk-delete`,method:"DELETE",body:r.Object({ids:r.Array(u())}),response:r.Object({})}),OLe=d({tags:["monitors"],url:`${At}/:id/snooze`,method:"POST",params:r.Object({id:u()}),body:r.Object({pauseUntil:u({allowEmpty:!1,type:"date-time"})}),response:Br}),xLe=d({tags:["monitors"],url:`${At}/bulk-snooze`,method:"POST",body:r.Object({monitorIds:r.Array(u()),pauseUntil:u({allowEmpty:!1,type:"date-time"})}),response:r.Object({})}),wB=["alert","alert_consider_zero","alert_no_data","keep_last_status_alert"],vB=["ok","ok_consider_zero","ok_no_data","keep_last_status_ok"],NB=[...wB,...vB],po=r.Enum(NB),LB=C("type",[r.Object({type:r.Literal("each"),subStates:r.Record(r.String(),r.Object({stateValue:r.Union([po,r.Null()]),lastChangedAt:A()}))}),r.Object({type:r.Literal("no_aggregation"),stateValue:r.Optional(po)}),r.Object({type:r.Literal("any"),stateValue:r.Optional(po)}),r.Object({type:r.Literal("all"),stateValue:r.Optional(po)}),r.Object({type:r.Literal("proportion"),stateValue:r.Optional(po)})]),kB=r.Object({monitorId:r.String(),currentState:LB,lastChangedAt:r.Optional(A())}),RLe=d({tags:["monitors"],url:`${At}/states/:id`,method:"GET",params:r.Object({id:u()}),response:kB}),CLe=d({tags:["monitors"],url:`${At}/:id/transitions`,method:"GET",params:r.Object({id:u()}),query:r.Object({from:r.Number(),to:r.Number()}),response:r.Array(r.Object({id:r.String(),createdAt:A(),fromState:r.Optional(po),toState:r.Optional(po),dimension:r.Optional(r.String())}))}),MB=["unprocessed","processed","failed-to-process"],PLe=d({tags:["monitors"],url:`${At}/:id/results`,method:"GET",params:r.Object({id:u()}),query:r.Object({from:r.Number(),to:r.Number()}),response:r.Object({isTruncated:r.Boolean(),results:r.Array(r.Object({id:r.String(),evaluationAt:A(),formulaResult:r.Object({groups:r.Array(r.Object({groupKey:r.Record(r.String(),rs),results:r.Array(r.Union([r.Number(),r.Null()])),conditionMet:r.Enum(["true","false","nan-no-data"])}))}),createdAt:A(),status:r.Enum(MB)}))})});var Hr="/v0/slos",DB=[7,30,90],GB=["good","bad"],hR=r.Enum(GB,{description:"How to treat SLO with no data: good (count as meeting the SLO), bad (count as breaching it)"}),$B=["good","bad","ignore"],yR=r.Enum($B,{description:"How to treat time buckets with no data: good (count as meeting the SLO), bad (count as breaching it), or ignore (exclude from the error budget)"}),dR=30,fR=1440,TR=["greater_than","less_than","greater_than_or_equal","less_than_or_equal"],jB=["healthy","breached","no_data"],lu=r.Enum(jB,{description:"SLO status: healthy (meeting the target), breached (breaching it), or no_data (not evaluated yet)"}),gR={sli:r.Optional(r.Number({description:"Service level indicator for the latest evaluation; absent when there is no data"})),errorBudget:r.Optional(r.Number({description:"Remaining error budget at the latest evaluation; negative when exhausted, absent when there is no data"})),status:lu},qB=r.Object({overall:r.Object(gR,{description:"Latest overall evaluation for the cluster"}),perGroup:r.Array(r.Object({groupKey:r.Record(r.String(),rs,{description:"Group-by field values identifying this group, keyed by field name. Present only when the SLO configuration sets `groupByFields`."}),...gR}),{description:"Latest evaluation for each group produced by the SLO configuration's `groupByFields`. Empty when the SLO is not grouped."})},{title:"SloClusterResults"}),ER=r.Record(r.String(),qB,{description:"Latest evaluation results keyed by cluster ID."}),Ld=r.Object({queries:qr,formula:iu},{title:"SloQueryFormula",description:"Aggregation queries combined by a formula to produce the SLO signal. Tsuga evaluates this query formula during SLO evaluation and returns it as part of the saved SLO configuration. Returned queries include Tsuga-derived missing-point fill: event SLO queries use zero fill, and time SLO queries keep missing points null."}),kd=r.Object({queries:Ax,formula:co},{title:"SloQueryFormula",description:"Aggregation queries combined by a formula to produce the SLO signal. Formulas reference queries as q1, q2, and so on. Do not send per-query fill; Tsuga derives the fill behavior from the SLO type."}),FB=r.Object({type:r.Literal("burn-rate",{description:"Alert configuration kind. Set to `burn-rate` for alerts that fire when the SLO consumes error budget faster than the configured multiplier."}),burnRate:r.Number({description:"Burn-rate multiplier that triggers this alert. The short and long evaluation windows are derived from the predefined template with the closest burn rate."})},{title:"BurnRateAlert"}),BB=r.Object({type:r.Literal("burn-rate",{description:"Alert configuration kind. Set to `burn-rate` for alerts that fire when the SLO consumes error budget faster than the configured multiplier."}),burnRate:r.Number({minimum:1,maximum:100,description:"Burn-rate multiplier that triggers this alert. Required for burn-rate alerts; valid input is 1 through 100. Non-template values are accepted; short and long evaluation windows are derived from the predefined template with the closest burn rate."})},{title:"BurnRateAlert"});var HB=r.Object({type:r.Literal("threshold",{description:"Alert configuration kind. Set to `threshold` for alerts that fire when the SLO indicator falls below a percentage threshold."}),threshold:r.Number({description:"SLI percentage threshold for this alert. The alert passes when SLI is at or above this value and fires when SLI is strictly below it."})},{title:"ThresholdAlert"}),KB=r.Object({type:r.Literal("threshold",{description:"Alert configuration kind. Set to `threshold` for alerts that fire when the SLO indicator falls below a percentage threshold."}),threshold:r.Number({exclusiveMinimum:0,exclusiveMaximum:100,description:"SLI percentage threshold for this alert. Required for threshold alerts; valid input is greater than 0 and less than 100. The alert passes when SLI is at or above this value and fires when SLI is strictly below it."})},{title:"ThresholdAlert"}),zB=C("type",[FB,HB],{description:"Alert trigger configuration: burn-rate or threshold"}),_R=C("type",[BB,KB],{description:"Alert trigger configuration: burn-rate or threshold"}),Md=r.Enum(St,{description:"Alert priority (1 is highest, 5 is lowest)"}),Dd=r.Object({id:r.String({description:"Tsuga-generated SLO alert ID assigned when the alert is created."}),sloId:r.String({description:"Parent SLO ID for this alert."}),priority:Md,configuration:zB,createdAt:A({description:"Timestamp when Tsuga created the alert."}),updatedAt:A({description:"Timestamp when Tsuga last updated the alert."}),assetUpdatedAt:A({description:"Timestamp used for asset-change tracking across Tsuga-managed resources."})},{title:"SloAlert"}),YB=r.Object({priority:Md,configuration:_R}),VB=r.Object({id:r.Optional(u({allowEmpty:!1,description:"Identifier of an existing alert to update. Omit to create a new alert on this SLO."})),priority:Md,configuration:_R}),QB=C("type",[r.Object({type:r.Literal("event",{description:"Configuration kind. Set to `event` for SLOs that compute SLI from good and total query formulas over the rolling timeframe."}),dataSource:ir,goodQuery:Ld,totalQuery:Ld,groupByFields:r.Optional(li),noDataBehavior:hR},{title:"EventSloConfiguration"}),r.Object({type:r.Literal("time",{description:"Configuration kind. Set to `time` for SLOs that evaluate a query against a threshold in fixed-size time slices."}),dataSource:ir,query:Ld,sliceSizeMinutes:r.Integer({description:"Length of each time-SLO evaluation slice in minutes. Required for `type: time`."}),threshold:r.Object({operator:r.Enum(TR,{description:"Comparison operator between the query value and the threshold"}),value:r.Number({description:"Threshold value compared against the query signal"})},{description:"Threshold comparison applied to each time-SLO evaluation slice"}),groupByFields:r.Optional(li),noDataBehavior:yR},{title:"TimeSliceSloConfiguration"})],{description:"SLI configuration for this SLO. Use `event` for good/total event-ratio SLOs or `time` for thresholded time-slice SLOs."}),WB=C("type",[r.Object({type:r.Literal("event",{description:"Configuration kind. Set to `event` for SLOs that compute SLI from good and total query formulas over the rolling timeframe."}),dataSource:ir,goodQuery:kd,totalQuery:kd,groupByFields:r.Optional(Fr),noDataBehavior:hR},{title:"EventSloConfiguration"}),r.Object({type:r.Literal("time",{description:"Configuration kind. Set to `time` for SLOs that evaluate a query against a threshold in fixed-size time slices."}),dataSource:ir,query:kd,sliceSizeMinutes:r.Integer({minimum:dR,maximum:fR,description:`Length of each time-SLO evaluation slice in minutes. Required for \`type: time\`. Valid input is ${dR} through ${fR}.`}),threshold:r.Object({operator:r.Enum(TR,{description:"Comparison operator between the query value and the threshold"}),value:r.Number({description:"Threshold value compared against the query signal"})},{description:"Threshold comparison applied to each time-SLO evaluation slice"}),groupByFields:r.Optional(Fr),noDataBehavior:yR},{title:"TimeSliceSloConfiguration"})],{description:"SLI configuration for this SLO. Use `event` for good/total event-ratio SLOs or `time` for thresholded time-slice SLOs."}),ZB=r.Number({exclusiveMinimum:0,exclusiveMaximum:100,description:"Target percentage (0 < target < 100, e.g. 99.9)"}),IR=r.Enum(DB,{type:"integer",description:"Rolling SLO evaluation window in days. Set by the caller on create or update and returned on read and list responses. Allowed values are 7, 30, and 90."}),XB=r.Array(r.String(),{description:"Cluster IDs this SLO is evaluated on. Omit or send an empty array on input to run on all clusters; responses use an empty array to mean all clusters. Non-empty input values must reference existing clusters."}),JB=r.Array(u({allowEmpty:!1}),{description:"Cluster IDs this SLO is evaluated on. Omit or send an empty array on input to run on all clusters; responses use an empty array to mean all clusters. Non-empty input values must reference existing clusters."}),gi=r.Object({id:r.String({description:"Tsuga-generated SLO ID assigned when the SLO is created."}),name:r.String({description:"Display name of the SLO, set by the caller."}),description:r.Optional(r.String({description:"Free-form, caller-provided description of what the SLO measures. Absent when not set."})),tags:De,configuration:QB,target:r.Number({description:"Target percentage (0 < target < 100, e.g. 99.9)"}),timeframeDays:IR,owner:r.String({description:"Team ID that owns the SLO"}),permissions:Tn,clusterIds:XB,creator:r.Optional(pe),updater:r.Optional(pe),alerts:r.Array(Dd,{description:"Alerts attached to this SLO"}),createdAt:A({description:"Timestamp when Tsuga created the SLO."}),updatedAt:A({description:"Timestamp when Tsuga last updated the SLO."}),assetUpdatedAt:A({description:"Timestamp used for asset-change tracking across Tsuga-managed resources."})},{title:"Slo"}),eH=r.Object({...gi.properties,results:ER},{title:"SloWithResults"}),mu=r.Object({name:u({allowEmpty:!1,description:"Display name of the SLO."}),description:r.Optional(u({type:"long",description:"Free-form, caller-provided description of what the SLO measures. Optional."})),tags:Xe,configuration:WB,target:ZB,timeframeDays:IR,owner:u({allowEmpty:!1,description:"Team ID that owns the SLO"}),permissions:Tn,clusterIds:r.Optional(JB),alerts:r.Array(YB,{description:"Alerts to create on this SLO. Send an empty array for none."})}),Gd=r.Object({...r.Omit(mu,["alerts"]).properties,alerts:r.Array(VB,{description:"Alerts attached to this SLO. The SLO owns its alerts: the set is reconciled to exactly this list \u2014 existing alerts are matched by id, alerts without an id are created, and existing alerts absent from the list are deleted. Send an empty array to clear all alerts."})}),bR=r.Object({owners:_e(u({allowEmpty:!1}),{description:"Restrict results to SLOs owned by any of these team IDs",maxItems:50}),searchQuery:r.Object({value:u({allowEmpty:!1,description:"Substring matched case-insensitively against the SLO name or SLO ID."}),exclude:r.Optional(r.Boolean({description:"If true, exclude SLOs matching this value instead of including them"}))},{description:"Text filter for SLO names or IDs. Optional; `exclude: true` removes matching SLOs."}),tags:_e(Bt.items,{description:"Restrict results to SLOs that have at least one of the listed key/value tags",maxItems:50}),clusterIds:_e(u({allowEmpty:!1}),{description:"Restrict results to SLOs that run against any of these cluster IDs (SLOs with no cluster restriction are always included)",maxItems:50}),statuses:_e(lu,{description:"Restrict results to SLOs whose status is one of these values",maxItems:3})},{description:"Optional filters applied to narrow the returned SLOs"}),$d=r.Partial(bR),jd=r.Partial(r.Object({...fe,filters:$d,sort:r.Object({by:r.Enum(["name","owner","tags","updatedAt","sli","errorBudget","status"],{description:"Field to sort by"}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned SLOs"})})),qLe=d({tags:["slos"],url:`${Hr}/query`,method:"POST",paginated:!0,response:r.Array(eH),body:jd}),FLe=d({tags:["slos"],url:`${Hr}/tags/query`,method:"POST",body:r.Object({filters:r.Optional(r.Partial(r.Omit(bR,["tags","statuses"])))}),response:Ft}),BLe=d({tags:["slos"],url:`${Hr}/:id`,method:"GET",params:r.Object({id:u()}),response:gi}),HLe=d({tags:["slos"],url:`${Hr}/:id/results`,method:"GET",params:r.Object({id:u()}),response:ER}),KLe=d({tags:["slos"],url:Hr,method:"POST",body:mu,response:gi}),zLe=d({tags:["slos"],url:`${Hr}/:id`,method:"PUT",params:r.Object({id:u()}),body:Gd,response:gi}),YLe=d({tags:["slos"],url:`${Hr}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),tH=jm($d),VLe=d({tags:["slos"],url:`${Hr}/bulk-delete`,method:"DELETE",body:r.Object({selection:tH}),response:r.Object({})}),rH=jm($d,{maxIds:100}),QLe=d({tags:["slos"],url:`${Hr}/bulk-update`,method:"PUT",body:r.Object({selection:rH,owner:u({allowEmpty:!1})}),response:r.Object({})});var hi="/v0/notifications",Sn=`${hi}/rules`,SR=`${hi}/slack/setup`,as=`${hi}/integrations`,uo=["triggered","resolved","no-data"],nH=["sent","stale","pending","rate-limited","failed","silenced"],oH=r.Optional(r.Object({maxMessages:r.Integer({description:"Maximum number of notifications this target can send during the rate-limiting window."}),minutes:r.Integer({description:"Length of the rate-limiting window, in minutes."})},{description:"Per-target rate limit used when sending notifications. If omitted, Tsuga allows up to 1000 notifications every 10 minutes for this target."})),qd=r.Object({maxMessages:r.Integer({minimum:1,description:"Maximum number of notifications this target can send during the rate-limiting window. The ratio of `maxMessages` to `minutes` cannot exceed 100 notifications per minute."}),minutes:r.Integer({minimum:1,description:"Length of the rate-limiting window, in minutes. The ratio of `maxMessages` to `minutes` cannot exceed 100 notifications per minute."})},{description:"Per-target rate limit used when sending notifications. If omitted, Tsuga allows up to 1000 notifications every 10 minutes for this target."}),iH=r.Optional(qd),Sr=r.Optional(r.Object({mode:r.Literal("each",{description:"Renotification mode. `each` sends repeat notifications for each matching monitor alert that remains in a configured state."}),renotificationStates:r.Array(r.Enum(["alert","alert_no_data"]),{description:"Monitor alert states that trigger repeat notifications while the target remains configured for renotification."}),renotifyIntervalMinutes:r.Integer({description:"Minimum number of minutes to wait after the previous notification."})},{description:"Configuration for repeat monitor notifications on this target. If omitted, Tsuga sends only the original notification for each alert transition."})),Ar=r.Optional(r.Object({mode:r.Literal("each",{description:"Renotification mode. `each` sends repeat notifications for each matching monitor alert that remains in a configured state."}),renotificationStates:r.Array(r.Enum(["alert","alert_no_data"]),{description:"Monitor alert states that trigger repeat notifications while the target remains configured for renotification."}),renotifyIntervalMinutes:r.Integer({minimum:1,description:"Minimum number of minutes to wait after the previous notification."})},{description:"Configuration for repeat monitor notifications on this target. If omitted, Tsuga sends only the original notification for each alert transition."})),ss=r.Object({id:r.String({description:"Identifier of the notification target within this rule, used with the rule ID for per-target delivery state such as rate limiting."}),rateLimit:oH,config:C("type",[r.Object({type:r.Literal("slack",{description:"Slack target backed by a configured Slack integration."}),channel:r.String({description:"Slack channel ID that receives the notification"}),integrationId:r.String({description:"Slack workspace ID that receives the notification"}),integrationName:r.String({description:"Human readable name of the Slack integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigSlack"}),r.Object({type:r.Literal("incident-io",{description:"incident.io target backed by a configured incident.io integration."}),integrationId:r.String({description:"Identifier of the incident.io integration to use"}),integrationName:r.String({description:"Human readable name of the incident.io integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigIncidentIo"}),r.Object({type:r.Literal("email",{description:"Email target that sends directly to the listed addresses and does not require an integration."}),addresses:r.Array(r.String(),{description:"Email addresses that will receive the alert"}),renotifyConfig:Sr},{$id:"RuleTargetConfigEmail"}),r.Object({type:r.Literal("grafana-irm",{description:"Grafana IRM target backed by a configured Grafana IRM integration."}),integrationId:r.String({description:"Identifier of the Grafana IRM integration to use"}),integrationName:r.String({description:"Human readable name of the Grafana IRM integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigGrafanaIrm"}),r.Object({type:r.Literal("pagerduty",{description:"PagerDuty target backed by a configured PagerDuty integration."}),integrationId:r.String({description:"Identifier of the PagerDuty integration to use"}),integrationName:r.String({description:"Human readable name of the PagerDuty integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigPagerDuty"}),r.Object({type:r.Literal("microsoft-teams",{description:"Microsoft Teams target backed by a configured Microsoft Teams integration."}),integrationId:r.String({description:"Identifier of the Microsoft Teams integration to use"}),integrationName:r.String({description:"Human readable name of the Microsoft Teams integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigMicrosoftTeams"}),r.Object({type:r.Literal("webhook",{description:"Webhook target backed by a configured webhook integration."}),integrationId:r.String({description:"Identifier of the webhook integration to use"}),integrationName:r.String({description:"Human readable name of the webhook integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigWebhook"}),r.Object({type:r.Literal("servicenow",{description:"ServiceNow target backed by a configured ServiceNow integration."}),integrationId:r.String({description:"Identifier of the ServiceNow integration to use"}),integrationName:r.String({description:"Human readable name of the ServiceNow integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigServiceNow"}),r.Object({type:r.Literal("google-chat",{description:"Google Chat target backed by a configured Google Chat integration."}),integrationId:r.String({description:"Identifier of the Google Chat integration to use"}),integrationName:r.String({description:"Human readable name of the Google Chat integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigGoogleChat"}),r.Object({type:r.Literal("squadcast",{description:"Squadcast target backed by a configured Squadcast integration."}),integrationId:r.String({description:"Identifier of the Squadcast integration to use"}),integrationName:r.String({description:"Human readable name of the Squadcast integration"}),renotifyConfig:Sr},{$id:"RuleTargetConfigSquadcast"}),r.Object({type:r.Literal("jira",{description:"Jira target backed by a configured Jira integration. Jira targets file one issue per notification and do not support renotification."}),integrationId:r.String({description:"Identifier of the Jira integration to use"}),integrationName:r.String({description:"Human readable name of the Jira integration"}),projectKey:r.String({description:'Key of the Jira project that alert issues are filed into, like "OPS".'}),issueType:r.String({description:'Name of the Jira issue type created for alerts, like "Bug" or "Task".'}),openStatus:r.Optional(r.String({description:"Jira status the alert ticket is moved to right after it is filed for a firing alert. A later transition between two firing states leaves the ticket status alone."})),closedStatus:r.Optional(r.String({description:"Jira status the alert ticket is moved to when the alert resolves. Only takes effect when the rule delivers recovery transitions."}))},{$id:"RuleTargetConfigJira"})],{description:"Destination that received the notification. The `type` field discriminates the variant: `email` sends directly to the listed addresses, and every other type routes through the named integration referenced by `integrationId`."})}),yi=r.Object({id:u({description:"Identifier of the notification target within this rule. Choose a stable ID that is unique among this rule's targets; Tsuga uses it with the rule ID for per-target delivery state such as rate limiting."}),rateLimit:iH,config:C("type",[r.Object({type:r.Literal("slack",{description:"Slack target backed by a configured Slack integration."}),channel:u({allowEmpty:!1,description:"Slack channel ID that receives the notification"}),integrationId:u({allowEmpty:!1,description:"Slack workspace ID that receives the notification"}),renotifyConfig:Ar},{$id:"RuleTargetInputSlack"}),r.Object({type:r.Literal("incident-io",{description:"incident.io target backed by a configured incident.io integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the incident.io integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputIncidentIo"}),r.Object({type:r.Literal("pagerduty",{description:"PagerDuty target backed by a configured PagerDuty integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the PagerDuty integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputPagerDuty"}),r.Object({type:r.Literal("email",{description:"Email target that sends directly to the listed addresses and does not require an integration."}),addresses:r.Array(u({type:"email"}),{minItems:1,maxItems:20,description:"Email addresses that will receive the alert"}),renotifyConfig:Ar},{$id:"RuleTargetInputEmail"}),r.Object({type:r.Literal("grafana-irm",{description:"Grafana IRM target backed by a configured Grafana IRM integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the Grafana IRM integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputGrafanaIrm"}),r.Object({type:r.Literal("microsoft-teams",{description:"Microsoft Teams target backed by a configured Microsoft Teams integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the Microsoft Teams integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputMicrosoftTeams"}),r.Object({type:r.Literal("webhook",{description:"Webhook target backed by a configured webhook integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the webhook integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputWebhook"}),r.Object({type:r.Literal("servicenow",{description:"ServiceNow target backed by a configured ServiceNow integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the ServiceNow integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputServiceNow"}),r.Object({type:r.Literal("google-chat",{description:"Google Chat target backed by a configured Google Chat integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the Google Chat integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputGoogleChat"}),r.Object({type:r.Literal("squadcast",{description:"Squadcast target backed by a configured Squadcast integration."}),integrationId:u({allowEmpty:!1,description:"Identifier of the Squadcast integration to use"}),renotifyConfig:Ar},{$id:"RuleTargetInputSquadcast"}),r.Object({type:r.Literal("jira",{description:"Jira target backed by a configured Jira integration. Jira targets file one issue per notification and do not support renotification."}),integrationId:u({allowEmpty:!1,description:"Identifier of the Jira integration to use"}),projectKey:u({allowEmpty:!1,description:'Key of the Jira project that alert issues are filed into, like "OPS".'}),issueType:u({allowEmpty:!1,description:'Name of the Jira issue type created for alerts, like "Bug" or "Task".'}),openStatus:r.Optional(u({allowEmpty:!1,description:"Jira status the alert ticket is moved to right after it is filed for a firing alert. A later transition between two firing states leaves the ticket status alone."})),closedStatus:r.Optional(u({allowEmpty:!1,description:"Jira status the alert ticket is moved to when the alert resolves. Only takes effect when the rule delivers recovery transitions."}))},{$id:"RuleTargetInputJira"})],{description:"Destination that should receive the notification. The `type` field discriminates the variant: `email` sends directly to the listed addresses and needs no integration; every other type routes through the integration identified by `integrationId`, which must already exist (create it first with the notification integration endpoints)."})}),Fd=C("type",[r.Object({type:r.Literal("specific-teams",{description:"Match alert transitions associated with the listed teams. The caller must be allowed to access every listed team."}),teams:r.Array(r.String(),{description:"Team IDs selected by this filter."})},{title:"SpecificTeams"}),r.Object({type:r.Literal("all-teams",{description:"Match alert transitions for every team in the organization. Public API callers need an API key with `all` scope to create or update this filter."})},{title:"AllTeams"}),r.Object({type:r.Literal("all-public-teams",{description:"Match alert transitions for all public teams. Public API callers need an API key with `all` or `owning-team-and-public` scope to create or update this filter."})},{title:"AllPublicTeams"})],{description:"Team visibility filter used when matching alert transitions. Tsuga validates create and update requests against the caller permissions."}),Bd=C("type",[r.Object({type:r.Literal("specific-teams",{description:"Match alert transitions associated with the listed teams. The caller must be allowed to access every listed team."}),teams:r.Array(u(),{minItems:1,maxItems:100,description:"Team IDs selected by this filter."})},{title:"SpecificTeams"}),r.Object({type:r.Literal("all-teams",{description:"Match alert transitions for every team in the organization. Public API callers need an API key with `all` scope to create or update this filter."})},{title:"AllTeams"}),r.Object({type:r.Literal("all-public-teams",{description:"Match alert transitions for all public teams. Public API callers need an API key with `all` or `owning-team-and-public` scope to create or update this filter."})},{title:"AllPublicTeams"})],{description:"Team visibility filter used when matching alert transitions. Tsuga validates create and update requests against the caller permissions."}),Ti=r.Object({id:r.String({description:"Tsuga-generated notification rule ID assigned when the rule is created."}),name:r.String({description:"Display name of the notification rule."}),queryString:r.Optional(r.String({description:"Optional query that narrows which alert transitions trigger the rule. Matches on the monitor transition group key and the monitor tags, e.g. `env:prod service:api`. Omit or leave empty to match regardless of tags."})),teamsFilter:Fd,prioritiesFilter:r.Array(r.Enum(St),{description:"Monitor priorities that must match for this rule to fire. An empty array matches every priority."}),transitionTypesFilter:r.Array(r.Enum(uo),{description:"Alert state transitions that must match for this rule to fire. An empty array matches every transition type."}),clusterIdsFilter:r.Array(r.String(),{description:"Cluster IDs that must match for this rule to fire. An empty array matches every cluster, as does a transition that has no cluster ID."}),owner:r.String({description:"Team ID that owns and manages the rule."}),createdAt:A({description:"Timestamp when Tsuga created the rule."}),updatedAt:A({description:"Timestamp when Tsuga last updated the rule."}),isActive:r.Boolean({description:"Whether the rule currently sends notifications when its filters match."}),tags:De,targets:r.Array(ss,{description:"Destinations that receive a notification whenever this rule matches an alert transition. Every target in the list is notified independently, subject to its own rate limit and renotification settings."}),creator:r.Optional(pe),updater:r.Optional(pe)}),cs=r.Object({name:u({description:"Display name of the notification rule."}),queryString:r.Optional(u({type:"tags-query",description:"Optional query that narrows which alert transitions trigger the rule. Matches on the monitor transition group key and the monitor tags, e.g. `env:prod service:api`. Omit or leave empty to match regardless of tags."})),teamsFilter:Bd,prioritiesFilter:r.Array(r.Enum(St),{maxItems:St.length,description:"Monitor priorities that must match for this rule to fire. An empty array matches every priority."}),transitionTypesFilter:r.Array(r.Enum(uo),{maxItems:uo.length,description:"Alert state transitions that must match for this rule to fire. An empty array matches every transition type."}),clusterIdsFilter:r.Optional(r.Array(u({allowEmpty:!1}),{description:"Cluster IDs that must match for this rule to fire. Omit it, or leave it empty, to match every cluster."})),owner:u({allowEmpty:!1,description:"Team ID that owns and manages the rule"}),tags:Xe,isActive:r.Boolean({description:"Set to true for the rule to send notifications when its filters match."}),targets:r.Array(yi,{minItems:1,description:"Destinations that receive a notification whenever this rule matches an alert transition. This list replaces the existing targets on update."})}),du=r.Object({id:r.String({description:"Unique identifier of the adaptive notification rule. Generated by Tsuga."}),name:r.String({description:"Display name of the adaptive notification rule."}),owner:r.String({description:"Team ID that owns and manages the rule."}),createdAt:A({description:"Timestamp when Tsuga created the rule."}),updatedAt:A({description:"Timestamp when Tsuga last updated the rule."}),isActive:r.Boolean({description:"Whether the rule currently sends notifications when one of its monitors fires."}),shouldCreateInvestigation:r.Boolean({description:"Whether each page records an investigation holding the sampled traces and the call graph the destination was resolved from, linked from the notification body."}),tags:De,monitorIds:r.Array(r.String(),{description:"Monitors this rule reacts to."}),sloIds:r.Array(r.String(),{description:"SLOs this rule reacts to."}),fallbackTarget:ss,creator:r.Optional(pe),updater:r.Optional(pe)}),AR=r.Object({name:u({description:"Display name of the adaptive notification rule."}),owner:u({allowEmpty:!1,description:"Team ID that owns and manages the rule"}),tags:Xe,isActive:r.Boolean({description:"Set to true for the rule to send notifications when one of its monitors fires."}),shouldCreateInvestigation:r.Optional(r.Boolean({description:"Set to true to record an investigation for each page, holding the sampled traces and the call graph the destination was resolved from, and to link it from the notification body. Defaults to false."})),monitorIds:r.Optional(r.Array(u({allowEmpty:!1}),{maxItems:100,description:"Monitors this rule reacts to. Only trace monitors and metric monitors over OTel span metrics are eligible. Send at least one monitor or SLO."})),sloIds:r.Optional(r.Array(u({allowEmpty:!1}),{maxItems:100,description:"SLOs this rule reacts to. Only SLOs over traces or OTel span metrics are eligible. Omit for a rule that reacts to monitors only; send at least one monitor or SLO."})),fallbackTarget:yi}),oke=d({tags:["notification-rules"],url:Sn,method:"GET",paginated:!0,query:r.Object(fe),response:r.Array(Ti)}),ike=d({tags:["notification-rules"],url:`${Sn}/:id`,params:r.Object({id:u()}),method:"GET",response:Ti}),ake=d({tags:["notification-rules"],url:Sn,method:"POST",body:cs,response:Ti}),ske=d({tags:["notification-rules"],url:`${Sn}/:id`,method:"PUT",params:r.Object({id:u()}),body:cs,response:Ti}),cke=d({tags:["notification-rules"],url:`${Sn}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),pke=d({tags:["notification-rules"],url:`${Sn}/bulk-delete`,method:"DELETE",body:r.Object({ids:r.Array(u())}),response:r.Object({})}),Ei=`${hi}/adaptive-rules`,uke=d({tags:["notification-rules"],url:Ei,method:"GET",paginated:!0,query:r.Object(fe),response:r.Array(du)}),lke=d({tags:["notification-rules"],url:`${Ei}/:id`,params:r.Object({id:u()}),method:"GET",response:du}),mke=d({tags:["notification-rules"],url:Ei,method:"POST",body:AR,response:du}),dke=d({tags:["notification-rules"],url:`${Ei}/:id`,method:"PUT",params:r.Object({id:u()}),body:AR,response:du}),fke=d({tags:["notification-rules"],url:`${Ei}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),gke=d({tags:["notification-rules"],url:`${Ei}/bulk-delete`,method:"DELETE",body:r.Object({ids:r.Array(u())}),response:r.Object({})}),hke=d({tags:["notification-integrations"],url:`${SR}/start`,method:"POST",response:r.Object({redirectUrl:r.String()})}),aH=["google-chat","grafana-irm","incident-io","jira","microsoft-teams","pagerduty","servicenow","slack","squadcast","webhook"],sH=r.Object({id:r.String(),name:r.String(),type:r.Enum(aH),createdAt:A(),ruleCount:r.Number(),creator:r.Optional(pe)}),yke=d({tags:["notification-integrations"],url:`${Sn}/integrations`,method:"GET",paginated:!0,query:r.Object(fe),response:r.Array(sH)}),Tke=d({tags:["notification-integrations"],url:`${SR}/callback`,method:"GET",query:r.Object({code:u()}),response:r.Object({success:r.Boolean()})}),Hd=["POST","PUT"],cH=r.Record(r.String(),r.String()),pH=r.Record(r.String(),r.Unknown()),uH=r.Record(r.String(),r.Union([r.String(),r.Number(),r.Boolean(),r.Null(),r.Array(r.Union([r.String(),r.Number(),r.Boolean()]))])),lH=C("type",[r.Object({type:r.Literal("json"),value:pH}),r.Object({type:r.Literal("form"),value:uH})]),mH=r.Object({ok:r.String(),alert:r.String()}),Kd=r.Object({id:r.String(),name:r.String(),setting:C("type",[r.Object({type:r.Literal("incident-io"),alertSourceConfigId:r.String(),tokenLastChars:r.String()}),r.Object({type:r.Literal("grafana-irm"),urlLastChars:r.String()}),r.Object({type:r.Literal("pagerduty"),integrationKeyLastChars:r.String()}),r.Object({type:r.Literal("microsoft-teams"),webhookUrlLastChars:r.String()}),r.Object({type:r.Literal("webhook"),urlLastChars:r.String(),method:r.Enum(Hd),authentication:C("type",[r.Object({type:r.Literal("bearer"),tokenLastChars:r.String()}),r.Object({type:r.Literal("basic"),username:r.String(),passwordLastChars:r.String()}),r.Object({type:r.Literal("custom-header"),key:r.String(),valueLastChars:r.String()}),r.Object({type:r.Literal("none")})]),customHeaders:r.Optional(cH),payloadTemplate:lH,eventNameMapping:r.Optional(mH)}),r.Object({type:r.Literal("servicenow"),instanceName:r.String(),username:r.String(),passwordLastChars:r.String()}),r.Object({type:r.Literal("google-chat"),webhookUrlLastChars:r.String()}),r.Object({type:r.Literal("squadcast"),webhookUrlLastChars:r.String()}),r.Object({type:r.Literal("jira"),siteUrl:r.String(),email:r.String(),apiTokenLastChars:r.String()})]),tags:De}),dH=r.Object({type:r.Literal("webhook"),url:u({type:"uri"}),method:r.Enum(Hd),authentication:C("type",[r.Object({type:r.Literal("bearer"),token:u({allowEmpty:!1})}),r.Object({type:r.Literal("basic"),username:u({allowEmpty:!1}),password:u({allowEmpty:!1})}),r.Object({type:r.Literal("custom-header"),key:u({allowEmpty:!1}),value:u({allowEmpty:!1})}),r.Object({type:r.Literal("none")})]),customHeaders:r.Record(u({allowEmpty:!1}),u()),payloadTemplate:C("type",[r.Object({type:r.Literal("json"),value:r.Record(u({allowEmpty:!1}),r.Unknown())}),r.Object({type:r.Literal("form"),value:r.Record(u({allowEmpty:!1}),r.Union([r.String(),r.Number(),r.Boolean(),r.Null(),r.Array(r.Union([r.String(),r.Number(),r.Boolean()]))]))})]),eventNameMapping:r.Optional(r.Object({ok:u({allowEmpty:!1}),alert:u({allowEmpty:!1})}))}),OR=r.Object({type:r.Literal("incident-io"),alertSourceConfigId:u(),token:u()}),xR=r.Object({type:r.Literal("grafana-irm"),url:u({type:"uri"})}),RR=r.Object({type:r.Literal("pagerduty"),integrationKey:u()}),CR=r.Object({type:r.Literal("microsoft-teams"),webhookUrl:u({type:"uri"})}),fH=r.Object({type:r.Literal("servicenow"),instanceName:u({allowEmpty:!1,description:'Instance name of the ServiceNow instance. This corresponds to the subdomain part of the instance URL, like "my-instance" in "my-instance.service-now.com"'}),username:u({allowEmpty:!1}),password:u({allowEmpty:!1})}),gH=r.Object({type:r.Literal("google-chat"),webhookUrl:u({type:"uri"})}),hH=r.Object({type:r.Literal("squadcast"),webhookUrl:u({type:"uri"})}),yH=r.Object({type:r.Literal("jira"),siteUrl:u({type:"uri",allowEmpty:!1,description:'Base URL of the Jira Cloud site, like "https://your-company.atlassian.net". Tsuga files issues against this site.'}),email:u({type:"email",allowEmpty:!1,description:"Atlassian account email used together with the API token for Basic authentication."}),apiToken:u({allowEmpty:!1,description:"Atlassian API token minted for the account, used as the Basic auth password."})}),TH=r.Object({name:u(),setting:C("type",[OR,xR,RR,CR,dH,fH,gH,hH,yH]),tags:Xe}),EH=r.Object({type:r.Literal("webhook"),url:r.Optional(u({type:"uri"})),method:r.Optional(r.Enum(Hd)),authentication:r.Optional(C("type",[r.Object({type:r.Literal("bearer"),token:r.Optional(u({allowEmpty:!1}))}),r.Object({type:r.Literal("basic"),username:r.Optional(u({allowEmpty:!1})),password:r.Optional(u({allowEmpty:!1}))}),r.Object({type:r.Literal("custom-header"),key:r.Optional(u({allowEmpty:!1})),value:r.Optional(u({allowEmpty:!1}))}),r.Object({type:r.Literal("none")})])),customHeaders:r.Optional(r.Record(u({allowEmpty:!1}),u())),payloadTemplate:r.Optional(C("type",[r.Object({type:r.Literal("json"),value:r.Record(u({allowEmpty:!1}),r.Unknown())}),r.Object({type:r.Literal("form"),value:r.Record(u({allowEmpty:!1}),r.Union([r.String(),r.Number(),r.Boolean(),r.Null(),r.Array(r.Union([r.String(),r.Number(),r.Boolean()]))]))})])),eventNameMapping:r.Optional(r.Object({ok:r.Optional(u({allowEmpty:!1})),alert:r.Optional(u({allowEmpty:!1}))}))}),_H=r.Object({type:r.Literal("servicenow"),instanceName:r.Optional(u({allowEmpty:!1})),username:r.Optional(u({allowEmpty:!1})),password:r.Optional(u({allowEmpty:!1}))}),IH=r.Object({type:r.Literal("jira"),siteUrl:r.Optional(u({type:"uri",allowEmpty:!1})),email:r.Optional(u({allowEmpty:!1})),apiToken:r.Optional(u({allowEmpty:!1}))}),bH=r.Object({type:r.Literal("google-chat"),webhookUrl:u({type:"uri"})}),SH=r.Object({type:r.Literal("squadcast"),webhookUrl:u({type:"uri"})}),AH=r.Object({name:r.Optional(u()),setting:r.Optional(C("type",[OR,xR,RR,CR,EH,_H,bH,SH,IH]))}),Eke=d({tags:["notification-integrations"],url:as,method:"POST",body:TH,response:Kd}),_ke=d({tags:["notification-integrations"],url:`${as}/:id`,method:"GET",params:r.Object({id:u()}),response:Kd}),Ike=d({tags:["notification-integrations"],url:`${as}/:id`,method:"PUT",params:r.Object({id:u()}),body:AH,response:Kd}),bke=d({tags:["notification-integrations"],url:`${as}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),OH=C("status",[r.Object({status:r.Literal("ok",{description:"Tsuga reached Jira and listed the projects the credentials can file into."}),projects:r.Array(r.Object({key:r.String({description:'Jira project key, like "OPS".'}),name:r.String({description:"Human readable Jira project name."}),issueTypes:r.Array(r.String(),{description:"Issue type names available when creating an issue in this project."}),statuses:r.Optional(r.Array(r.String(),{description:"Status names an issue in this project can be transitioned to. Omitted when Jira refused the status lookup for this project."}))}),{description:"Projects the connected Jira account can file issues into."})},{title:"JiraMetadataOk"}),r.Object({status:r.Literal("error",{description:"Tsuga could not load Jira metadata with the stored credentials."}),message:r.String({description:"Human readable reason the Jira metadata could not be loaded."})},{title:"JiraMetadataError"})],{description:"Result of probing Jira for the projects, issue types and statuses reachable with a stored integration. Returns a typed error instead of failing so the rule editor can fall back to free-text entry."}),Ske=d({tags:["notification-integrations"],url:`${as}/:id/jira-metadata`,method:"GET",params:r.Object({id:u()}),response:OH}),Ake=d({tags:["notification-rules"],url:`${At}/:id/notifications`,method:"GET",params:r.Object({id:u()}),query:r.Optional(r.Object({from:r.Optional(r.Number()),to:r.Optional(r.Number())})),response:r.Object({notifications:r.Array(r.Object({id:r.String(),monitorId:r.String(),monitorResultId:r.String(),ruleId:r.Optional(r.String()),targetId:r.Optional(r.String()),status:r.Enum(nH),tryCount:r.Number(),nextTryAt:A(),createdAt:A(),updatedAt:A(),sentAt:r.Optional(A())})),isTruncated:r.Boolean()})}),xH=["slack","incident-io","pagerduty","email","grafana-irm","microsoft-teams","webhook","servicenow","google-chat","squadcast","jira"],Oke=d({tags:["notification-rules"],url:`${Sn}/test`,method:"POST",body:r.Object({notificationRule:cs,targetIds:r.Optional(r.Array(u({allowEmpty:!1}),{description:"Target IDs to test specific targets",minItems:1,maxItems:10}))}),response:r.Union([r.Object({success:r.Literal(!1),overallMessage:r.String({description:"Message when there is an overall error"})}),r.Object({success:r.Boolean(),results:r.Array(r.Object({targetId:r.String({description:"The ID of the target that was tested"}),targetType:r.Enum(xH,{description:"The type of the target (e.g., slack, webhook)"}),status:r.Enum(["success","failure"],{description:"Whether the test notification was sent successfully"}),message:r.Optional(r.String({description:"Message if the notification failed for this specific target"}))}))})])});var Dt="/v0/service-catalog";var RH=r.Object({team:r.String({description:"Team name observed on telemetry for this service."}),lastSeenAt:A({description:"Most recent time this team was observed for the service."})},{description:"A team name observed on telemetry for this service, with the last time it was seen."}),CH=r.Object({ingestionApiKey:r.String({description:"Ingestion API key name or identifier observed on telemetry for this service."}),lastSeenAt:A({description:"Most recent time this ingestion key was observed for the service."})},{description:"An ingestion API key observed on telemetry for this service, with the last time it was seen."}),PH=r.Object({version:r.String({description:"Service version value observed in telemetry."}),firstSeenAt:A({description:"First time this version was observed for the service."}),lastSeenAt:A({description:"Most recent time this version was observed for the service."}),faulty:r.Optional(r.Boolean({description:"Whether Tsuga detected this version as associated with faulty behavior."})),faultyLatency:r.Optional(r.Boolean({description:"Whether the faulty behavior Tsuga detected for this version is a latency degradation. Only set by faulty deployment detection when it reports on latency; absent when the detection did not evaluate latency."})),detectionTriggered:r.Optional(r.Boolean({description:"Whether faulty deployment detection has already been triggered for this version. Set when the detection job is launched to avoid re-triggering it. Absent on versions predating this field."}))},{description:"A service version observed in telemetry, with first and last seen timestamps and faulty deployment detection results."}),UH=r.Object({language:r.String({description:"Programming language observed for this service."}),lastSeenAt:A({description:"Most recent time this language was observed."})},{description:"A programming language observed for this service, with the last time it was seen."}),wH=r.Object({runtime:r.String({description:"Runtime observed for this service."}),lastSeenAt:A({description:"Most recent time this runtime was observed."})},{description:"A runtime observed for this service, with the last time it was seen."}),PR=r.Object({protocol:r.String({description:"Observed API protocol (e.g. 'http', 'grpc', 'graphql')"}),lastSeenAt:A({description:"Most recent observation timestamp"})},{description:"An API protocol observed for this service, with the last time it was seen."}),vH=r.Object({framework:r.String({description:"Observed application framework (e.g. 'express', 'fastify', 'django', 'rails')"}),lastSeenAt:A({description:"Most recent observation timestamp"})},{description:"An application framework detected from OpenTelemetry instrumentation scope, with the last time it was seen."}),NH=r.Object({platform:r.String({description:"Observed cloud or orchestration platform (e.g. 'aws_eks', 'kubernetes')"}),lastSeenAt:A({description:"Most recent observation timestamp"})},{description:"A cloud or orchestration platform this service runs on, with the last time it was seen."}),LH=r.Object({provider:r.String({description:"Observed cloud provider (e.g. 'aws', 'gcp', 'azure')"}),lastSeenAt:A({description:"Most recent observation timestamp"})},{description:"A cloud provider this service runs on, with the last time it was seen."}),_i=r.Object({id:r.String({description:"Tsuga-generated identifier of this service target, unique across all services. Used with delivery state such as rate limiting and re-notification."}),serviceId:r.String({description:"Identifier of the service catalog entry this target is attached to."}),config:ss.properties.config,rateLimit:ss.properties.rateLimit,createdAt:A({description:"Timestamp when user created this service target."}),updatedAt:A({description:"Timestamp when user last updated this service target."})}),zd=r.Object({config:yi.properties.config,rateLimit:yi.properties.rateLimit}),Yd=r.Object({config:yi.properties.config,rateLimit:r.Union([qd,r.Null()],{description:"Per-target rate limit to apply when sending notifications. Set it to `null` to drop the current limit and fall back to the default of 1000 notifications every 10 minutes."})}),ps=r.Object({id:r.String({description:"Unique identifier of this service. Use it with service detail and graph endpoints."}),serviceName:r.String({description:"OpenTelemetry service name observed in telemetry."}),serviceNamespace:r.Optional(r.String({description:"OpenTelemetry service namespace observed in telemetry."})),env:r.Optional(r.String({description:"Environment value observed for this service."})),teams:r.Array(RH,{description:"Team names observed on telemetry for this service and when each was last seen."}),ingestionApiKeys:r.Array(CH,{description:"Ingestion API keys observed on telemetry for this service and when each was last seen."}),versions:r.Array(PH,{description:"Service version values observed in telemetry, including first and last seen timestamps."}),languages:r.Array(UH,{description:"Programming languages observed for this service."}),runtimes:r.Array(wH,{description:"Runtime values observed for this service."}),serverProtocols:r.Array(PR,{description:"API protocols this service exposes (from server-kind spans)"}),clientProtocols:r.Array(PR,{description:"API protocols this service calls out over (from client-kind spans)"}),frameworks:r.Array(vH,{description:"Application frameworks detected from OTel instrumentation scope"}),cloudPlatforms:r.Array(NH,{description:"Cloud platforms this service is running on"}),cloudProviders:r.Array(LH,{description:"Cloud providers this service is running on"}),lastSeenAt:A({description:"Most recent time Tsuga observed telemetry for this service."}),firstSeenAt:A({description:"First time Tsuga observed telemetry for this service."}),sources:r.Array(r.String(),{description:"Telemetry sources that contributed evidence for this service entry."}),additionalUserFields:r.Optional(r.Unsafe({type:"object",additionalProperties:!0,description:"Additional user-defined service metadata, when configured."})),logsCount24h:r.Number({description:"Number of logs observed for this service in the last 24 hours."}),errorLogsCount24h:r.Number({description:"Number of error logs observed for this service in the last 24 hours."}),tracesCount24h:r.Number({description:"Number of traces observed for this service in the last 24 hours."}),errorTracesCount24h:r.Number({description:"Number of error traces observed for this service in the last 24 hours."}),notificationTargets:r.Array(_i,{description:"Notification targets attached to this service, used by adaptive notification rules to page its owners."}),createdAt:A({description:"Timestamp when Tsuga created this service catalog entry."}),updatedAt:A({description:"Timestamp when Tsuga last updated this service catalog entry."})}),Mke=d({tags:["service-catalog"],query:r.Object({...fe,clusterId:r.Optional(u())}),method:"GET",paginated:!0,url:`${Dt}/services`,response:r.Array(ps)}),kH=r.Object({spanKind:r.Enum(JO),count:r.Number()}),Vd=r.Object({...ps.properties,spanKindCounts:r.Array(kH),envs:r.Object({primaryEnv:r.String(),allEnvs:r.Array(r.String())})}),Dke=d({tags:["service-catalog"],query:r.Object({...fe,clusterId:r.Optional(u()),env:r.Optional(u())}),method:"GET",paginated:!0,url:`${Dt}/v2/services`,response:r.Array(Vd)}),MH=["serviceName","envs","lastDeploy","traceErrorRate","traceRequestRate","logErrorRate","logRequestRate","teams","api","frameworks","languages","pagingDestination"],DH=r.Object({searchQuery:r.Object({value:u({allowEmpty:!1,description:"Substring matched case-insensitively against service names."})},{description:"Text filter for service names."}),teams:_e(u({allowEmpty:!1}),{description:"Restrict results to services observed under any of these team names",maxItems:50}),envs:_e(u({allowEmpty:!1}),{description:"Restrict results to services observed in any of these environments",maxItems:50}),versions:_e(u({allowEmpty:!1}),{description:"Restrict results to services whose latest observed version is one of these",maxItems:50}),languages:_e(u({allowEmpty:!1}),{description:"Restrict results to services written in any of these languages",maxItems:50}),hasRecentData:r.Boolean({description:"When true, only return services that received logs or traces in the last 24 hours"})}),GH=r.Partial(r.Object({...fe,clusterId:u(),filters:r.Partial(DH,{description:"Optional filters applied to narrow the returned services"}),sort:r.Object({by:r.Enum(MH,{description:"Field to sort the returned services by"}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned services"})})),Gke=d({tags:["service-catalog"],url:`${Dt}/v2/services/query`,method:"POST",paginated:!0,body:GH,response:r.Array(Vd)}),$ke=d({tags:["service-catalog"],query:r.Object({serviceName:u({allowEmpty:!1}),serviceNamespace:r.Optional(u({allowEmpty:!1})),env:u({allowEmpty:!1}),clusterId:r.Optional(u())}),method:"GET",url:`${Dt}/v2/service`,response:Vd}),jke=d({tags:["service-catalog"],method:"GET",url:`${Dt}/services/:serviceId`,params:r.Object({serviceId:u()}),response:ps}),qke=d({tags:["service-catalog"],method:"GET",url:`${Dt}/services/:serviceId/targets`,params:r.Object({serviceId:u()}),response:r.Array(_i)}),Fke=d({tags:["service-catalog"],method:"POST",url:`${Dt}/services/:serviceId/targets`,params:r.Object({serviceId:u()}),body:zd,response:_i}),Bke=d({tags:["service-catalog"],method:"PUT",url:`${Dt}/services/:serviceId/targets/:targetId`,params:r.Object({serviceId:u(),targetId:u()}),body:Yd,response:_i}),Hke=d({tags:["service-catalog"],method:"DELETE",url:`${Dt}/services/:serviceId/targets/:targetId`,params:r.Object({serviceId:u(),targetId:u()}),response:N}),$H=["otel_kube","otel_host_kube","otel_host","prometheus","aws_ec2","gcp_compute_engine"];var UR=r.Object({id:r.String(),hostName:r.String(),env:r.Optional(r.String()),cpuUtilizationAverage:r.Number(),hostType:r.Enum($H),teams:r.Array(r.String()),tags:r.Array(r.String()),firstSeenAt:A(),lastSeenAt:A(),clusterId:r.String()}),Kke=d({tags:["service-catalog"],method:"GET",url:`${Dt}/hosts`,response:r.Array(UR)}),zke=d({tags:["service-catalog"],method:"GET",url:`${Dt}/hosts/:hostId`,params:r.Object({hostId:u()}),response:UR}),jH=["http","rpc","messaging","genai","object_store"],wR={name:r.String({description:"Service or inferred dependency name shown in the graph."}),env:r.Optional(r.String({description:"Environment observed from spans."}))},Qd=r.Object({...wR,nodeType:r.Literal("observed",{description:"Discriminator for this node variant. Always `observed` for a graph node matched to a service catalog entry by name and env."}),id:r.Union([r.String(),r.Null()],{description:"Service ID, or null when multiple namespaces match the observed service name."}),namespace:r.Union([r.String(),r.Null()],{description:"Service namespace, or null when multiple namespaces match the observed service name."}),errorRate:r.Optional(r.Number({description:"Ratio of entry requests with at least one error to total entry requests observed on this service. Omitted when no entry requests were observed."})),entryErrorRequestCount:r.Number({description:"Number of entry requests on this service where at least one entry span had error status."}),entryRequestCount:r.Number({description:"Number of entry requests observed on this service, counted as unique trace IDs that have at least one entry span on this service. An entry span is a consumer-kind span, a root span (no parent), or any span whose parent belongs to a different service."})}),vR={...wR,endpoint:r.Optional(r.String({description:"Inferred service endpoint address"})),resourceName:r.Optional(r.String({description:"Inferred resource name, e.g. table or queue name"}))},Wd=r.Object({...vR,nodeType:r.Literal("inferred_db",{description:"Discriminator for this node variant. Always `inferred_db` for a database dependency detected from client-span attributes that could not be matched to a service catalog entry."}),serviceType:r.Literal("db",{description:"Inferred dependency type. Always `db` for this node variant."}),databaseName:r.Optional(r.String({description:"Database name from span_attributes db.namespace (falling back to legacy db.name). Matches the database catalog `name`."})),databaseSystem:r.String({description:"Database system from span_attributes db.system.name (falling back to legacy db.system). Matches the database catalog `databaseSystem`."})}),Zd=r.Object({...vR,nodeType:r.Literal("inferred",{description:"Discriminator for this node variant. Always `inferred` for a non-database dependency detected from client-span attributes (e.g. a queue or external HTTP call) that could not be matched to a service catalog entry. Database dependencies use the `inferred_db` variant."}),serviceType:r.Enum(jH,{description:"Inferred dependency type from span metadata: http, rpc, messaging, genai, or object_store."})}),qH=C("nodeType",[Qd,Wd,Zd]),Xd=r.Object({from:r.Object({env:r.Optional(r.String({description:"Environment of the source node"})),name:r.String({description:"Name of the source node"})},{description:"Reference to the caller node, i.e. the service or dependency that issued the request."}),to:r.Object({env:r.Optional(r.String({description:"Environment of the target node"})),name:r.String({description:"Name of the target node"}),databaseSystem:r.Optional(r.String({description:"Database system of the target when it is an inferred database node (`inferred_db`). Together with `name` and `env` it identifies the target node, distinguishing a database from a same-named service or a same-named database on another system."}))},{description:"Reference to the callee node, i.e. the service or dependency that received the request."}),count:r.Number({description:"Number of cross-service transitions observed on this directed edge in the graph query window."}),errorRate:r.Optional(r.Number({description:"Ratio of errored client spans to total client spans observed on this edge. Omitted when no client spans were observed. For edges to inferred services, the originating span is treated as the client span regardless of its kind."})),errorCount:r.Number({description:"Number of client spans with error status observed on this edge"}),clientSpanCount:r.Number({description:"Number of client spans observed on this edge"})},{description:"Directed dependency edge from a caller node (`from`) to a callee node (`to`) in the service graph, with call-volume and error counts observed over the query window."}),Yke=d({tags:["service-catalog"],url:`${Dt}/services/:serviceId/graph`,method:"GET",params:r.Object({serviceId:u()}),query:r.Object({...at.properties,query:r.Optional(u({type:"tsuga-query"}))}),response:r.Object({clusterId:r.String(),nodes:r.Array(qH),edges:r.Array(Xd)})}),FH=r.Object({monitors:r.Array(r.Object({id:r.String({description:"Identifier of the monitor"}),name:r.String({description:"Display name of the monitor"}),owner:r.String({description:"Team ID that owns the monitor"}),priority:r.Enum(St,{description:"Priority of the monitor"})})),slos:r.Array(r.Object({id:r.String({description:"Identifier of the SLO"}),name:r.String({description:"Display name of the SLO"}),owner:r.String({description:"Team ID that owns the SLO"}),statusCount:r.Partial(r.Record(lu,r.Number()),{description:"Count of SLO statuses for this service: one entry per group matching the service when the SLO groups by service.name, otherwise the overall status"})}))}),Vke=d({tags:["service-catalog"],method:"GET",url:`${Dt}/services/:serviceId/related-resources`,params:r.Object({serviceId:u()}),response:FH}),Qke=d({tags:["service-catalog"],method:"GET",url:`${Dt}/services/by-api-keys`,response:r.Record(r.String(),r.Array(r.Object({serviceName:r.String(),serviceNamespace:r.Optional(r.String())})))});var fu=`/${"v1"}/services`,Jd=r.Pick(ps,["id","serviceName","serviceNamespace","env","teams","versions","languages","runtimes","serverProtocols","clientProtocols","frameworks","cloudPlatforms","cloudProviders","lastSeenAt","firstSeenAt","sources","logsCount24h","errorLogsCount24h","tracesCount24h","errorTracesCount24h"],{$id:"Service",description:"Service inferred from telemetry, with observed metadata, activity counts, and version signals. See [Services](/documentation/categorize/services/index)."}),BH={id:"123-456-abc",serviceName:"api-gateway",serviceNamespace:"platform",env:"production",teams:[{team:"platform",lastSeenAt:"2024-01-15T12:34:56.000Z"}],versions:[{version:"1.2.3",firstSeenAt:"2024-01-01T08:00:00.000Z",lastSeenAt:"2024-01-15T12:34:56.000Z",faulty:!0,faultyLatency:!0}],languages:[{language:"go",lastSeenAt:"2024-01-15T12:34:56.000Z"}],runtimes:[{runtime:"go",lastSeenAt:"2024-01-15T12:34:56.000Z"}],serverProtocols:[{protocol:"http",lastSeenAt:"2024-01-15T12:34:56.000Z"}],clientProtocols:[{protocol:"grpc",lastSeenAt:"2024-01-15T12:34:56.000Z"}],frameworks:[{framework:"gin",lastSeenAt:"2024-01-15T12:34:56.000Z"}],cloudPlatforms:[{platform:"aws_eks",lastSeenAt:"2024-01-15T12:34:56.000Z"},{platform:"kubernetes",lastSeenAt:"2024-01-15T12:34:56.000Z"}],cloudProviders:[{provider:"aws",lastSeenAt:"2024-01-15T12:34:56.000Z"}],lastSeenAt:"2024-01-15T12:34:56.000Z",firstSeenAt:"2024-01-01T08:00:00.000Z",sources:["logs","metrics","traces"],logsCount24h:12e3,errorLogsCount24h:42,tracesCount24h:8500,errorTracesCount24h:17};Object.assign(Jd,{examples:[BH]});var NR=d({description:"Lists services inferred from telemetry. Use this endpoint to inventory service ownership, environments, versions, runtimes, and recent activity. Pagination fields limit the returned page.",operationId:"listServices",tags:["services"],url:fu,method:"GET",paginated:!0,query:r.Object({...Ze,clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Omit to use the first cluster in the organization; this does not query all clusters."}))},{description:"Service list query. Use pagination and optional cluster scope."}),response:r.Array(Jd)}),LR=d({description:"Retrieves one telemetry-inferred service by service ID.",operationId:"getService",tags:["services"],url:`${fu}/:serviceId`,method:"GET",params:r.Object({serviceId:u({allowEmpty:!1,description:"Identifier of the service to retrieve. Use the `id` returned by service list responses."})}),response:Jd}),HH=r.Pick(Qd,["name","env","nodeType","id","namespace","errorRate","entryErrorRequestCount","entryRequestCount"],{$id:"ObservedServiceGraphNode",description:"Service graph node matched to a service catalog entry by name and env. `id`/`namespace` are null when multiple namespaces share the observed service name."}),KH=r.Pick(Zd,["name","env","nodeType","serviceType","endpoint","resourceName"],{$id:"InferredServiceGraphNode",description:"Dependency node detected from client-span attributes (e.g. a queue or external HTTP call) that could not be matched to a service catalog entry. Database dependencies use the `inferred_db` variant."}),zH=r.Pick(Wd,["name","env","nodeType","serviceType","endpoint","resourceName"],{$id:"InferredDbServiceGraphNode",description:"Database dependency node detected from client-span attributes that could not be matched to a service catalog entry."}),YH=C("nodeType",[HH,zH,KH]),VH=r.Pick(Xd,["from","to","count","errorRate","errorCount","clientSpanCount"],{$id:"ServiceGraphEdge",description:"Directed dependency edge from a caller node (`from`) to a callee node (`to`), with call-volume and error counts observed over the query window."}),QH=r.Optional(r.Integer({...at.properties.from,description:"Start of the service graph query window as a Unix timestamp in seconds. Provide both `from` and `to` for a deterministic graph window; otherwise Tsuga uses backend graph defaults."})),WH=r.Optional(r.Integer({...at.properties.to,description:"End of the service graph query window as a Unix timestamp in seconds. Provide both `from` and `to` for a deterministic graph window; otherwise Tsuga uses backend graph defaults."})),ZH=u({type:"tsuga-query",default:"*",description:"Tsuga query used to filter spans considered for the graph. Defaults to `*`, which applies no additional filter beyond the service identity."}),kR=d({description:"Retrieves a dependency graph for one service over an optional time range and query filter. Provide an explicit time range for deterministic results. Use this to inspect observed downstream and upstream service relationships. See [Service page](/documentation/categorize/services/service-page).",operationId:"getServiceGraph",tags:["services"],url:`${fu}/:serviceId/graph`,method:"GET",params:r.Object({serviceId:u({allowEmpty:!1,description:"Identifier of the service to use as the graph root. Use the `id` returned by service list or get responses."})}),query:r.Object({from:QH,to:WH,query:r.Optional(ZH)},{description:"Service graph query. Use time range and optional span query filters."}),response:r.Object({clusterId:r.String({description:"Cluster ID the graph was built from"}),nodes:r.Array(YH,{description:"Observed and inferred nodes included in the service dependency graph."}),edges:r.Array(VH,{description:"Directed dependency edges between graph nodes."})})}),gu=`${fu}/:serviceId/notification-targets`,hu=r.Pick(_i,["id","serviceId","config","rateLimit"],{$id:"ServiceNotificationTarget",description:"Notification target attached to a service, used by adaptive notification rules to page the service owners. See [Rules](/documentation/alert/notifications/rules)."}),ef={rateLimit:{maxMessages:10,minutes:5},config:{type:"email",addresses:["oncall@example.com"],renotifyConfig:{mode:"each",renotificationStates:["alert"],renotifyIntervalMinutes:30}}},XH={id:"789-abc-def",serviceId:"123-456-abc",...ef};Object.assign(hu,{examples:[XH]});var yu=u({allowEmpty:!1,description:"Identifier of the service the notification target belongs to. Use the `id` returned by service list or get responses."}),oMe=d({description:"Lists the notification targets attached to one service. Use this to discover target IDs before updating or deleting a target.",operationId:"listServiceNotificationTargets",tags:["services"],url:gu,method:"GET",params:r.Object({serviceId:yu}),response:r.Array(hu)}),JH=r.Pick(zd,["config","rateLimit"],{description:"Service notification target create request. Provide the delivery destination and an optional per-target rate limit.",examples:[ef]}),e2=r.Pick(Yd,["config","rateLimit"],{description:"Service notification target update request. The submitted destination and rate limit overwrite the stored ones.",examples:[ef]}),iMe=d({description:"Attaches a notification target to a service. Adaptive notification rules matching the service page this target on alert transitions.",operationId:"createServiceNotificationTarget",tags:["services"],url:gu,method:"POST",params:r.Object({serviceId:yu}),body:JH,response:hu}),aMe=d({description:"Updates one notification target attached to a service.",operationId:"updateServiceNotificationTarget",tags:["services"],url:`${gu}/:targetId`,method:"PUT",params:r.Object({serviceId:yu,targetId:u({allowEmpty:!1,description:"Identifier of the notification target to update. Use the `id` returned by service notification target list or create responses."})}),body:e2,response:hu}),sMe=d({description:"Detaches a notification target from a service. Notification rules stop paging this destination for the service.",operationId:"deleteServiceNotificationTarget",tags:["services"],url:`${gu}/:targetId`,method:"DELETE",params:r.Object({serviceId:yu,targetId:u({allowEmpty:!1,description:"Identifier of the notification target to delete. Use the `id` returned by service notification target list or create responses."})}),response:N});var Ge=" (unix seconds, ISO 8601, or relative like -1h/-30m/now)";function MR(e,t){let n=t??jr(e);return n===void 0?void 0:Ic(n)}function tf(e){let t=jr(e);return t===void 0?"":` (default: ${t})`}function DR(e,t){e.command("service-graph").description("Inspect service dependency graphs").command("get <SERVICE_ID>").description("Retrieve the dependency graph for a service").option("--from <TIMESTAMP>",`Start of time range${Ge}${tf("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${tf("to")}`).option("--query <TSUGA_QUERY>",`Tsuga query to filter graph spans${tf("query")}`).action(async(o,i)=>{let a={},c=MR("from",i.from),l=MR("to",i.to);c!==void 0&&(a.from=c),l!==void 0&&(a.to=l),i.query!==void 0&&(a.query=i.query);let m=await t()(kR,{params:{serviceId:o},query:a});ee(m)})}var t2=`/${"v1"}/grok`,r2=25,n2=100,GR=r.Object({rules:r.Array(u({allowEmpty:!1,type:"long",description:"Grok parsing rule to preview against each sample. The rule uses the same Grok syntax as the log route **Grok parser** processor, for example `pod:%{DATA:namespace}/%{DATA:name}`."}),{minItems:1,maxItems:r2,description:"Ordered Grok parsing rules to preview. For each sample, Tsuga tries the rules in order and returns the first successful match, matching route Grok processor semantics."}),samples:r.Array(u({allowEmpty:!1,type:"long",description:"Raw log line to parse with the provided Grok rules. The value is parsed as preview input only; this endpoint does not ingest or store the sample."}),{minItems:1,maxItems:n2,description:"Sample log lines to run against the rules. Results are returned in the same order as this array."})},{description:"Grok rules and sample log lines to preview extraction before saving a route processor. The endpoint uses the same parser as the route builder preview and does not create or update routes."}),o2={rules:['pod:%{DATA:pod_namespace}/%{DATA:pod_name}\\] "%{DATA:request}" HTTP/%{POSINT:status}'],samples:['[conn-id:abc pod:tsuga-events/tsuga-events-searcher-0] "/token" HTTP/200']};Object.assign(GR,{examples:[o2]});var $R=r.Object({results:r.Array(r.Object({sample:r.String({description:"Echo of the submitted log line, so results can be matched to the samples in the request."}),matched:r.Boolean({description:"Whether any submitted rule matched this sample. `true` means `extracted` contains the captured fields; `false` means no rule matched."}),extracted:r.Union([r.Record(r.String(),r.Unknown()),r.Null()],{description:"Fields extracted from the first matching Grok rule when `matched` is `true`; dotted capture names are expanded into nested objects. `null` when no rule matched."})}),{description:"Preview result for each submitted sample, in the same order as the request `samples` array."})},{description:"Grok extraction preview results from applying the ordered rules to each submitted sample."}),i2={results:[{sample:'[conn-id:abc pod:tsuga-events/tsuga-events-searcher-0] "/token" HTTP/200',matched:!0,extracted:{pod_namespace:"tsuga-events",pod_name:"tsuga-events-searcher-0",request:"/token",status:"200"}}]};Object.assign($R,{examples:[i2]});var jR=d({url:`${t2}/parse`,method:"POST",operationId:"parseGrok",tags:["public","grok"],body:GR,response:$R,description:"Parses sample log lines with Grok rules and returns extracted fields, using the same Grok engine as the log route processor. Use this endpoint to author and test route Grok rules before saving them. The operation requires public API read access to log routes. A rule that fails to compile returns a 400 response with error code `GROK_RULE_VALIDATION_ERROR` and structured details in `error.details.ruleErrors`."});var qR=rn(require("node:fs"));function Ii(e){if(e.file){let t=qR.default.readFileSync(e.file==="-"?0:e.file,"utf-8");return JSON.parse(t)}if(e.data)return JSON.parse(e.data);throw new Error("Provide a request body with -f <FILE_PATH> or -d <JSON>. Use --generate-skeleton to get a template.")}function rf(e){return s.HasPropertyKey(e,"~refine")&&s.IsArray(e["~refine"])&&s.Every(e["~refine"],0,t=>s.IsObject(t)&&s.HasPropertyKey(t,"check")&&s.HasPropertyKey(t,"error")&&s.IsFunction(t.check)&&s.IsFunction(t.error))}function ar(e){return s.IsObject(e)&&!s.IsArray(e)}function Tu(e){return s.IsBoolean(e)}function q(e){return ar(e)||Tu(e)}function nf(e){return s.HasPropertyKey(e,"additionalItems")&&q(e.additionalItems)}function Kr(e){return s.HasPropertyKey(e,"additionalProperties")&&q(e.additionalProperties)}function of(e){return s.HasPropertyKey(e,"allOf")&&s.IsArray(e.allOf)&&e.allOf.every(t=>q(t))}function us(e){return s.HasPropertyKey(e,"$anchor")&&s.IsString(e.$anchor)}function af(e){return s.HasPropertyKey(e,"anyOf")&&s.IsArray(e.anyOf)&&e.anyOf.every(t=>q(t))}function sf(e){return s.HasPropertyKey(e,"const")}function lo(e){return s.HasPropertyKey(e,"contains")&&q(e.contains)}function Ht(e){return s.HasPropertyKey(e,"default")}function cf(e){return s.HasPropertyKey(e,"dependencies")&&s.IsObject(e.dependencies)&&Object.values(e.dependencies).every(t=>q(t)||s.IsArray(t)&&t.every(n=>s.IsString(n)))}function pf(e){return s.HasPropertyKey(e,"dependentRequired")&&s.IsObject(e.dependentRequired)&&Object.values(e.dependentRequired).every(t=>s.IsArray(t)&&t.every(n=>s.IsString(n)))}function uf(e){return s.HasPropertyKey(e,"dependentSchemas")&&s.IsObject(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(t=>q(t))}function An(e){return s.HasPropertyKey(e,"$dynamicAnchor")&&s.IsString(e.$dynamicAnchor)}function lf(e){return s.HasPropertyKey(e,"$dynamicRef")&&s.IsString(e.$dynamicRef)}function mf(e){return s.HasPropertyKey(e,"else")&&q(e.else)}function df(e){return s.HasPropertyKey(e,"enum")&&s.IsArray(e.enum)}function ff(e){return s.HasPropertyKey(e,"exclusiveMaximum")&&(s.IsNumber(e.exclusiveMaximum)||s.IsBigInt(e.exclusiveMaximum))}function zr(e){return s.HasPropertyKey(e,"exclusiveMinimum")&&(s.IsNumber(e.exclusiveMinimum)||s.IsBigInt(e.exclusiveMinimum))}function ls(e){return s.HasPropertyKey(e,"format")&&s.IsString(e.format)}function Yr(e){return s.HasPropertyKey(e,"$id")&&s.IsString(e.$id)}function gf(e){return s.HasPropertyKey(e,"if")&&q(e.if)}function bi(e){return s.HasPropertyKey(e,"items")&&(q(e.items)||s.IsArray(e.items)&&e.items.every(t=>q(t)))}function hf(e){return bi(e)&&s.IsArray(e.items)}function yf(e){return s.HasPropertyKey(e,"maximum")&&(s.IsNumber(e.maximum)||s.IsBigInt(e.maximum))}function Tf(e){return s.HasPropertyKey(e,"maxContains")&&s.IsNumber(e.maxContains)}function Eu(e){return s.HasPropertyKey(e,"maxItems")&&s.IsNumber(e.maxItems)}function Ef(e){return s.HasPropertyKey(e,"maxLength")&&s.IsNumber(e.maxLength)}function _f(e){return s.HasPropertyKey(e,"maxProperties")&&s.IsNumber(e.maxProperties)}function Vr(e){return s.HasPropertyKey(e,"minimum")&&(s.IsNumber(e.minimum)||s.IsBigInt(e.minimum))}function mo(e){return s.HasPropertyKey(e,"minContains")&&s.IsNumber(e.minContains)}function Si(e){return s.HasPropertyKey(e,"minItems")&&s.IsNumber(e.minItems)}function ms(e){return s.HasPropertyKey(e,"minLength")&&s.IsNumber(e.minLength)}function ds(e){return s.HasPropertyKey(e,"minProperties")&&s.IsNumber(e.minProperties)}function If(e){return s.HasPropertyKey(e,"multipleOf")&&(s.IsNumber(e.multipleOf)||s.IsBigInt(e.multipleOf))}function bf(e){return s.HasPropertyKey(e,"not")&&q(e.not)}function Sf(e){return s.HasPropertyKey(e,"oneOf")&&s.IsArray(e.oneOf)&&e.oneOf.every(t=>q(t))}function fs(e){return s.HasPropertyKey(e,"pattern")&&(s.IsString(e.pattern)||e.pattern instanceof RegExp)}function gs(e){return s.HasPropertyKey(e,"patternProperties")&&s.IsObject(e.patternProperties)&&Object.values(e.patternProperties).every(t=>q(t))}function Ai(e){return s.HasPropertyKey(e,"prefixItems")&&s.IsArray(e.prefixItems)&&e.prefixItems.every(t=>q(t))}function hs(e){return s.HasPropertyKey(e,"properties")&&s.IsObject(e.properties)&&Object.values(e.properties).every(t=>q(t))}function Af(e){return s.HasPropertyKey(e,"propertyNames")&&(s.IsObject(e.propertyNames)||q(e.propertyNames))}function a2(e){return s.HasPropertyKey(e,"$recursiveAnchor")&&s.IsBoolean(e.$recursiveAnchor)}function _u(e){return a2(e)&&s.IsEqual(e.$recursiveAnchor,!0)}function Of(e){return s.HasPropertyKey(e,"$recursiveRef")&&s.IsString(e.$recursiveRef)}function xf(e){return s.HasPropertyKey(e,"$ref")&&s.IsString(e.$ref)}function fo(e){return s.HasPropertyKey(e,"required")&&s.IsArray(e.required)&&e.required.every(t=>s.IsString(t))}function Rf(e){return s.HasPropertyKey(e,"then")&&q(e.then)}function Cf(e){return s.HasPropertyKey(e,"type")&&(s.IsString(e.type)||s.IsArray(e.type)&&e.type.every(t=>s.IsString(t)))}function Oi(e){return s.HasPropertyKey(e,"uniqueItems")&&s.IsBoolean(e.uniqueItems)}function Iu(e){return s.HasPropertyKey(e,"unevaluatedItems")&&q(e.unevaluatedItems)}function bu(e){return s.HasPropertyKey(e,"unevaluatedProperties")&&q(e.unevaluatedProperties)}var xt=class{constructor(){let t=new Set,n=new Set;this.stack=[{indices:t,keys:n}]}Push(){let t=new Set,n=new Set;return this.stack.push({indices:t,keys:n}),!0}Pop(){return this.stack.pop(),!0}AddIndex(t){return this.GetIndices().add(t),!0}AddKey(t){return this.GetKeys().add(t),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(t){for(let n of t)n.GetIndices().forEach(o=>this.GetIndices().add(o)),n.GetKeys().forEach(o=>this.GetKeys().add(o));return!0}},ys=class extends xt{constructor(t){super(),this.callback=t}AddError(t){return this.callback(t),!1}},st=class extends ys{constructor(){super(t=>this.errors.push(t)),this.errors=[]}AddError(t){return this.errors.push(t),!1}GetErrors(){return this.errors}};function FR(e,t,n,o){return s.Every(n["~refine"],0,(i,a)=>i.check(o))}function BR(e,t,n,o,i,a){return s.EveryAll(i["~refine"],0,(c,l)=>c.check(a)||t.AddError({keyword:"~refine",schemaPath:n,instancePath:o,params:{index:l,message:c.error(a)}}))}function HR(e){return bi(e)&&s.IsArray(e.items)}function KR(e,t,n,o){return HR(n)?s.Every(o,0,(a,c)=>s.IsLessThan(c,n.items.length)||Kt(e,t,n.additionalItems,a)&&t.AddIndex(c)):!0}function zR(e,t,n,o,i,a){return HR(i)?s.Every(a,0,(l,m)=>{let f=`${n}/additionalItems`,h=`${o}/${m}`;return s.IsLessThan(m,i.items.length)||zt(e,t,f,h,i.additionalItems,l)&&t.AddIndex(m)}):!0}function s2(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function YR(e){let t=[];return gs(e)&&t.push(...s.Keys(e.patternProperties)),hs(e)&&t.push(...s.Keys(e.properties).map(s2)),s.IsEqual(t.length,0)?"(?!)":`(${t.join("|")})`}function VR(e,t,n,o){let i=new RegExp(YR(n));return s.Every(s.Keys(o),0,(c,l)=>i.test(c)||Kt(e,t,n.additionalProperties,o[c])&&t.AddKey(c))}function QR(e,t,n,o,i,a){let c=new RegExp(YR(i)),l=[];return s.EveryAll(s.Keys(a),0,(f,h)=>{let E=`${n}/additionalProperties`,I=`${o}/${f}`,g=new st,T=c.test(f)||zt(e,g,E,I,i.additionalProperties,a[f])&&t.AddKey(f);return T||l.push(f),T})||t.AddError({keyword:"additionalProperties",schemaPath:n,instancePath:o,params:{additionalProperties:l}})}function WR(e,t,n,o){let i=n.allOf.reduce((a,c)=>{let l=new xt;return ne(e,l,c,o)?[...a,l]:a},[]);return s.IsEqual(i.length,n.allOf.length)&&t.Merge(i)}function ZR(e,t,n,o,i,a){let c=[],l=i.allOf.reduce((f,h,E)=>{let I=`${n}/allOf/${E}`,g=new st,T=Ie(e,g,I,o,h,a);return T||c.push(g),T?[...f,g]:f},[]),m=s.IsEqual(l.length,i.allOf.length)&&t.Merge(l);return m||c.forEach(f=>f.GetErrors().forEach(h=>t.AddError(h))),m}function XR(e,t,n,o){let i=n.anyOf.reduce((a,c)=>{let l=new xt;return ne(e,l,c,o)?[...a,l]:a},[]);return s.IsGreaterThan(i.length,0)&&t.Merge(i)}function JR(e,t,n,o,i,a){let c=[],l=i.anyOf.reduce((f,h,E)=>{let I=new st,g=`${n}/anyOf/${E}`,T=Ie(e,I,g,o,h,a);return T||c.push(I),T?[...f,I]:f},[]),m=s.IsGreaterThan(l.length,0)&&t.Merge(l);return m||c.forEach(f=>f.GetErrors().forEach(h=>t.AddError(h))),m||t.AddError({keyword:"anyOf",schemaPath:n,instancePath:o,params:{}})}function Uf(e,t,n,o){return n}function eC(e,t,n,o,i,a){return Uf(e,t,i,a)||t.AddError({keyword:"boolean",schemaPath:n,instancePath:o,params:{}})}function wf(e,t,n,o){return s.IsValueLike(n.const)?s.IsEqual(o,n.const):s.IsDeepEqual(o,n.const)}function tC(e,t,n,o,i,a){return wf(e,t,i,a)||t.AddError({keyword:"const",schemaPath:n,instancePath:o,params:{allowedValue:i.const}})}function c2(e){return!(mo(e)&&s.IsEqual(e.minContains,0))}function vf(e,t,n,o){return c2(n)?!s.IsEqual(o.length,0)&&s.SomeAll(o,(i,a)=>ne(e,t,n.contains,i)&&t.AddIndex(a)):!0}function rC(e,t,n,o,i,a){return vf(e,t,i,a)||t.AddError({keyword:"contains",schemaPath:n,instancePath:o,params:{minContains:1}})}function nC(e,t,n,o){let i=s.IsEqual(s.Keys(o).length,0),a=s.Every(s.Entries(n.dependencies),0,([c,l])=>!s.HasPropertyKey(o,c)||(s.IsArray(l)?l.every(m=>s.HasPropertyKey(o,m)):ne(e,t,l,o)));return i||a}function oC(e,t,n,o,i,a){let c=s.IsEqual(s.Keys(a).length,0),l=s.EveryAll(s.Entries(i.dependencies),0,([m,f])=>{let h=`${n}/dependencies/${m}`;return!s.HasPropertyKey(a,m)||(s.IsArray(f)?f.every(E=>s.HasPropertyKey(a,E)||t.AddError({keyword:"dependencies",schemaPath:n,instancePath:o,params:{property:m,dependencies:f}})):Ie(e,t,h,o,f,a))});return c||l}function iC(e,t,n,o){let i=s.IsEqual(s.Keys(o).length,0),a=s.Every(s.Entries(n.dependentRequired),0,([c,l])=>!s.HasPropertyKey(o,c)||l.every(m=>s.HasPropertyKey(o,m)));return i||a}function aC(e,t,n,o,i,a){let c=s.IsEqual(s.Keys(a).length,0),l=s.EveryAll(s.Entries(i.dependentRequired),0,([m,f])=>!s.HasPropertyKey(a,m)||s.EveryAll(f,0,h=>s.HasPropertyKey(a,h)||t.AddError({keyword:"dependentRequired",schemaPath:n,instancePath:o,params:{property:m,dependencies:f}})));return c||l}function sC(e,t,n,o){let i=s.IsEqual(s.Keys(o).length,0),a=s.Every(s.Entries(n.dependentSchemas),0,([c,l])=>!s.HasPropertyKey(o,c)||ne(e,t,l,o));return i||a}function cC(e,t,n,o,i,a){let c=s.IsEqual(s.Keys(a).length,0),l=s.EveryAll(s.Entries(i.dependentSchemas),0,([m,f])=>{let h=`${n}/dependentSchemas/${m}`;return!s.HasPropertyKey(a,m)||Ie(e,t,h,o,f,a)});return c||l}function pC(e,t,n,o){let i=e.DynamicRef(n)??!1;return q(i)&&ne(e,t,i,o)}function uC(e,t,n,o,i,a){let c=e.DynamicRef(i)??!1;return q(c)&&Ie(e,t,"#",o,c,a)}function kf(e,t,n,o){return s.Some(n.enum,i=>s.IsValueLike(i)?s.IsEqual(o,i):s.IsDeepEqual(o,i))}function lC(e,t,n,o,i,a){return kf(e,t,i,a)||t.AddError({keyword:"enum",schemaPath:n,instancePath:o,params:{allowedValues:i.enum}})}function Mf(e,t,n,o){return s.IsLessThan(o,n.exclusiveMaximum)}function mC(e,t,n,o,i,a){return Mf(e,t,i,a)||t.AddError({keyword:"exclusiveMaximum",schemaPath:n,instancePath:o,params:{comparison:"<",limit:i.exclusiveMaximum}})}function Df(e,t,n,o){return s.IsGreaterThan(o,n.exclusiveMinimum)}function dC(e,t,n,o,i,a){return Df(e,t,i,a)||t.AddError({keyword:"exclusiveMinimum",schemaPath:n,instancePath:o,params:{comparison:">",limit:i.exclusiveMinimum}})}var Pi={};Yt(Pi,{Clear:()=>AC,Entries:()=>Y2,Get:()=>W2,Has:()=>Q2,IsDate:()=>Ri,IsDateTime:()=>Su,IsDuration:()=>Au,IsEmail:()=>Ou,IsHostname:()=>Ru,IsIPv4:()=>Uu,IsIPv6:()=>wu,IsIdnEmail:()=>Cu,IsIdnHostname:()=>Pu,IsIri:()=>Nu,IsIriReference:()=>vu,IsJsonPointer:()=>ku,IsJsonPointerUriFragment:()=>Lu,IsRegex:()=>Mu,IsRelativeJsonPointer:()=>Du,IsTime:()=>Ci,IsUri:()=>qu,IsUriReference:()=>Gu,IsUriTemplate:()=>$u,IsUrl:()=>Fu,IsUuid:()=>Bu,Reset:()=>OC,Set:()=>V2,Test:()=>Z2});var p2=[0,31,28,31,30,31,30,31,31,30,31,30,31],u2=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function l2(e){return e%4===0&&(e%100!==0||e%400===0)}function Ri(e){let t=u2.exec(e);if(!t)return!1;let n=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o===2&&l2(n)?29:p2[o])}var m2=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function Ci(e,t=!0){let n=m2.exec(e);if(!n)return!1;let o=+n[1],i=+n[2],a=+n[3],c=n[4]==="-"?-1:1,l=+(n[5]||0),m=+(n[6]||0);if(l>23||m>59||t&&!n[4]&&e.toLowerCase().indexOf("z")===-1)return!1;if(o<=23&&i<=59&&a<60)return!0;let f=i-m*c,h=o-l*c-(f<0?1:0);return(h===23||h===-1)&&(f===59||f===-1)&&a<61}function Su(e,t=!0){let n=e.split(/T/i);return n.length===2&&Ri(n[0])&&Ci(n[1],t)}var d2=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Au(e){return d2.test(e)}var f2=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function Ou(e){return f2.test(e)}var go=36,xu=1,Gf=26,g2=38,h2=700,y2=72,T2=128;function E2(e,t,n){e=n?Math.floor(e/h2):e>>1,e+=Math.floor(e/t);let o=0;for(;e>(go-xu)*Gf>>1;)e=Math.floor(e/(go-xu)),o+=go;return o+Math.floor((go-xu+1)*e/(e+g2))}function fC(e){let t=[],n=T2,o=0,i=y2,a=e.lastIndexOf("-");if(a>0)for(let l=0;l<a;l++){let m=e.charCodeAt(l);if(m>=128)throw new Error("Invalid punycode: non-basic before delimiter");t.push(m)}let c=a<0?0:a+1;for(;c<e.length;){let l=o,m=1,f=go;for(;;){if(c>=e.length)throw new Error("Invalid punycode: unexpected end of input");let E=e.charCodeAt(c++),I;if(E>=97&&E<=122)I=E-97;else if(E>=48&&E<=57)I=E-48+26;else if(E>=65&&E<=90)ge();else throw new Error("Invalid punycode: bad digit character");o+=I*m;let g=f<=i?xu:f>=i+Gf?Gf:f-i;if(I<g)break;m*=go-g,f+=go}let h=t.length+1;i=E2(o-l,h,l===0),n+=Math.floor(o/h),o%=h,t.splice(o,0,n),o++}return globalThis.String.fromCodePoint(...t)}function I2(e){return new RegExp("\\p{Mn}","u").test(String.fromCodePoint(e))}function b2(e){return new RegExp("\\p{Mc}","u").test(String.fromCodePoint(e))}function S2(e){return new RegExp("\\p{Me}","u").test(String.fromCodePoint(e))}function A2(e){return I2(e)||b2(e)||S2(e)}var O2=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),x2=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function R2(e){return new RegExp("\\p{Script=Greek}","u").test(String.fromCodePoint(e))}function C2(e){return new RegExp("\\p{Script=Hebrew}","u").test(String.fromCodePoint(e))}function P2(e){return new RegExp("\\p{Script=Hiragana}","u").test(String.fromCodePoint(e))}function U2(e){return new RegExp("\\p{Script=Katakana}","u").test(String.fromCodePoint(e))}function w2(e){return new RegExp("\\p{Script=Han}","u").test(String.fromCodePoint(e))}function v2(e){return e>=1632&&e<=1641}function N2(e){return e>=1776&&e<=1785}function gC(e){return x2.has(e)}function hC(e){if(e.length===0)return ge();let t=[...e].map(c=>c.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||A2(t[0]))return!1;let o=!1,i=!1,a=!1;for(let c=0;c<n;c++){let l=t[c];if(O2.has(l))return!1;(P2(l)||U2(l)||w2(l))&&(o=!0),v2(l)&&(i=!0),N2(l)&&(a=!0);let m=t[c-1],f=t[c+1];switch(l){case 183:if(m!==108||f!==108)return!1;break;case 885:if(f===void 0||!R2(f))return!1;break;case 1523:case 1524:if(m===void 0||!C2(m))return!1;break;case 8204:if(m===void 0||m<128&&!gC(m))return!1;break;case 8205:if(m===void 0||!gC(m))return!1;break;case 12539:break}}return!(e.includes("\u30FB")&&!o||i&&a)}function L2(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function yC(e){return e.toLowerCase().startsWith("xn--")}function TC(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf("-")===0)return!1;let o=fC(t);return o?hC(o):!1}catch{return!1}}function EC(e){return e.length===0||e.length>63?!1:yC(e)?TC(e):hC(e)}function _C(e){return e.length===0||e.length>63?!1:yC(e)?TC(e):L2(e)}function Ru(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split("."))if(!_C(t))return!1;return!0}var M2=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Cu(e){return M2.test(e)}function Pu(e){if(e.length===0||e.includes(" "))return!1;let t=e.normalize("NFC").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".");if(t.length>253)return!1;for(let n of t.split("."))if(!EC(n))return!1;return!0}function $f(e,t,n){let o=0,i=0,a=0,c=0;for(let l=t;l<n;l++){let m=e.charCodeAt(l);if(m===46){if(a===0||i>255||c===48&&a>1)return!1;o++,i=0,a=0,c=0}else if(m>=48&&m<=57)a===0&&(c=m),i=i*10+(m-48),a++;else return!1}return o===3&&a>0&&i<=255&&!(c===48&&a>1)}function Uu(e){return $f(e,0,e.length)}function D2(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function wu(e){let t=e.length;if(t===0)return!1;let n=0,o=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;o=!0,i=2}for(;i<t;){let a=0,c=i;for(;i<t&&D2(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let l=e.charCodeAt(i);if(l===46){if(!$f(e,c,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(l!==58)return!1;if(i++,e.charCodeAt(i)===58){if(o||e.charCodeAt(i+1)===58)return!1;if(o=!0,i++,i===t)break}}return o?n<=7:n===8}function IC(e){try{return new URL(e,"http://example.com"),!0}catch{return!1}}function vu(e){if(e.includes(" ")||e.includes("\\")||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e==="")return!0;let t=e.indexOf(":");return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?IC(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:IC(e)}function Nu(e){try{return new URL(e),!0}catch{return!1}}var G2=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Lu(e){return G2.test(e)}var $2=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function ku(e){return $2.test(e)}function Mu(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}var j2=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Du(e){return j2.test(e)}var q2=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function Gu(e){return q2.test(e)}var F2=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function $u(e){return F2.test(e)}function bC(e){return e>=97&&e<=122||e>=65&&e<=90}function SC(e){return bC(e)||e>=48&&e<=57}function ju(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function B2(e){return SC(e)||e===43||e===45||e===46}function jf(e){return SC(e)||e===45||e===46||e===95||e===126}function qf(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function H2(e){return jf(e)||qf(e)||e===58||e===64}function qu(e){let t=e.length;if(t===0||!bC(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let o=e.charCodeAt(n);if(o===58)break;if(!B2(o))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let o=n,i=-1;for(let a=n;a<t;a++){let c=e.charCodeAt(a);if(c===64){i=a;break}if(c===47||c===63||c===35)break}if(i!==-1){for(let a=o;a<i;a++){let c=e.charCodeAt(a);if(c===91||c===93)return!1;if(c===37){if(a+2>=i||!ju(e.charCodeAt(a+1))||!ju(e.charCodeAt(a+2)))return!1;a+=2}else if(!jf(c)&&!qf(c)&&c!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let a=e.charCodeAt(n);if(a===47||a===63||a===35||a===58)break;if(a<128&&!jf(a)&&!qf(a))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let a=e.charCodeAt(n);if(a===47||a===63||a===35)break;if(a<48||a>57)return!1;n++}}for(;n<t;){let o=e.charCodeAt(n);if(o===37){if(n+2>=t||!ju(e.charCodeAt(n+1))||!ju(e.charCodeAt(n+2)))return!1;n+=2}else{if(o>127)return!1;if(!(H2(o)||o===47||o===63||o===35))return!1}n++}return!0}var K2=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function Fu(e){return K2.test(e)}var z2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Bu(e){return z2.test(e)}var Oe=new Map;function AC(){Oe.clear()}function Y2(){return[...Oe.entries()]}function V2(e,t){Oe.set(e,t)}function Q2(e){return Oe.has(e)}function W2(e){return Oe.get(e)}function Z2(e,t){return Oe.get(e)?.(t)??!0}function OC(){AC(),Oe.set("date-time",Su),Oe.set("date",Ri),Oe.set("duration",Au),Oe.set("email",Ou),Oe.set("hostname",Ru),Oe.set("idn-email",Cu),Oe.set("idn-hostname",Pu),Oe.set("ipv4",Uu),Oe.set("ipv6",wu),Oe.set("iri-reference",vu),Oe.set("iri",Nu),Oe.set("json-pointer-uri-fragment",Lu),Oe.set("json-pointer",ku),Oe.set("regex",Mu),Oe.set("relative-json-pointer",Du),Oe.set("time",Ci),Oe.set("uri-reference",Gu),Oe.set("uri-template",$u),Oe.set("uri",qu),Oe.set("url",Fu),Oe.set("uuid",Bu)}OC();function Ff(e,t,n,o){return Pi.Test(n.format,o)}function xC(e,t,n,o,i,a){return Ff(e,t,i,a)||t.AddError({keyword:"format",schemaPath:n,instancePath:o,params:{format:i.format}})}function RC(e,t,n,o){let i=Rf(n)?n.then:!0,a=mf(n)?n.else:!0;return ne(e,t,n.if,o)?ne(e,t,i,o):ne(e,t,a,o)}function CC(e,t,n,o,i,a){let c=Rf(i)?i.then:!0,l=mf(i)?i.else:!0,m=new st,f=Ie(e,m,`${n}/if`,o,i.if,a)?Ie(e,m,`${n}/then`,o,c,a)||t.AddError({keyword:"if",schemaPath:n,instancePath:o,params:{failingKeyword:"then"}}):Ie(e,t,`${n}/else`,o,l,a)||t.AddError({keyword:"if",schemaPath:n,instancePath:o,params:{failingKeyword:"else"}});return f&&t.Merge([m]),f}function X2(e,t,n,o){return s.Every(n.items,0,(i,a)=>s.IsLessEqualThan(o.length,a)||Kt(e,t,i,o[a])&&t.AddIndex(a))}function J2(e,t,n,o,i,a){return s.EveryAll(i.items,0,(c,l)=>{let m=`${n}/items/${l}`,f=`${o}/${l}`;return s.IsLessEqualThan(a.length,l)||zt(e,t,m,f,c,a[l])&&t.AddIndex(l)})}function eK(e,t,n,o){let i=Ai(n)?n.prefixItems.length:0;return s.Every(o,i,(a,c)=>Kt(e,t,n.items,a)&&t.AddIndex(c))}function tK(e,t,n,o,i,a){let c=Ai(i)?i.prefixItems.length:0;return s.EveryAll(a,c,(l,m)=>{let f=`${n}/items`,h=`${o}/${m}`;return zt(e,t,f,h,i.items,l)&&t.AddIndex(m)})}function PC(e,t,n,o){return hf(n)?X2(e,t,n,o):eK(e,t,n,o)}function UC(e,t,n,o,i,a){return hf(i)?J2(e,t,n,o,i,a):tK(e,t,n,o,i,a)}function rK(e){return lo(e)}function Bf(e,t,n,o){if(!rK(n))return!0;let i=s.Counted(o,a=>ne(e,t,n.contains,a));return s.IsLessEqualThan(i,n.maxContains)}function wC(e,t,n,o,i,a){let c=mo(i)?i.minContains:1;return Bf(e,t,i,a)||t.AddError({keyword:"contains",schemaPath:n,instancePath:o,params:{minContains:c,maxContains:i.maxContains}})}function Hf(e,t,n,o){return s.IsLessEqualThan(o,n.maximum)}function vC(e,t,n,o,i,a){return Hf(e,t,i,a)||t.AddError({keyword:"maximum",schemaPath:n,instancePath:o,params:{comparison:"<=",limit:i.maximum}})}function Kf(e,t,n,o){return s.IsLessEqualThan(o.length,n.maxItems)}function NC(e,t,n,o,i,a){return Kf(e,t,i,a)||t.AddError({keyword:"maxItems",schemaPath:n,instancePath:o,params:{limit:i.maxItems}})}function zf(e,t,n,o){return s.IsMaxLength(o,n.maxLength)}function LC(e,t,n,o,i,a){return zf(e,t,i,a)||t.AddError({keyword:"maxLength",schemaPath:n,instancePath:o,params:{limit:i.maxLength}})}function Yf(e,t,n,o){return s.IsLessEqualThan(s.Keys(o).length,n.maxProperties)}function kC(e,t,n,o,i,a){return Yf(e,t,i,a)||t.AddError({keyword:"maxProperties",schemaPath:n,instancePath:o,params:{limit:i.maxProperties}})}function nK(e){return lo(e)}function Vf(e,t,n,o){if(!nK(n))return!0;let i=s.Counted(o,(a,c)=>ne(e,t,n.contains,a)&&t.AddIndex(c));return s.IsGreaterEqualThan(i,n.minContains)}function MC(e,t,n,o,i,a){return Vf(e,t,i,a)||t.AddError({keyword:"contains",schemaPath:n,instancePath:o,params:{minContains:i.minContains}})}function Qf(e,t,n,o){return s.IsGreaterEqualThan(o,n.minimum)}function DC(e,t,n,o,i,a){return Qf(e,t,i,a)||t.AddError({keyword:"minimum",schemaPath:n,instancePath:o,params:{comparison:">=",limit:i.minimum}})}function Wf(e,t,n,o){return s.IsGreaterEqualThan(o.length,n.minItems)}function GC(e,t,n,o,i,a){return Wf(e,t,i,a)||t.AddError({keyword:"minItems",schemaPath:n,instancePath:o,params:{limit:i.minItems}})}function Zf(e,t,n,o){return s.IsMinLength(o,n.minLength)}function $C(e,t,n,o,i,a){return Zf(e,t,i,a)||t.AddError({keyword:"minLength",schemaPath:n,instancePath:o,params:{limit:i.minLength}})}function Xf(e,t,n,o){return s.IsGreaterEqualThan(s.Keys(o).length,n.minProperties)}function jC(e,t,n,o,i,a){return Xf(e,t,i,a)||t.AddError({keyword:"minProperties",schemaPath:n,instancePath:o,params:{limit:i.minProperties}})}function Jf(e,t,n,o){return s.IsMultipleOf(o,n.multipleOf)}function qC(e,t,n,o,i,a){return Jf(e,t,i,a)||t.AddError({keyword:"multipleOf",schemaPath:n,instancePath:o,params:{multipleOf:i.multipleOf}})}function eg(e,t,n,o){let i=new xt;return!ne(e,i,n.not,o)&&t.Merge([i])}function FC(e,t,n,o,i,a){return eg(e,t,i,a)||t.AddError({keyword:"not",schemaPath:n,instancePath:o,params:{}})}function BC(e,t,n,o){let i=n.oneOf.reduce((a,c)=>{let l=new xt;return ne(e,l,c,o)?[...a,l]:a},[]);return s.IsEqual(i.length,1)&&t.Merge(i)}function HC(e,t,n,o,i,a){let c=[],l=[],m=i.oneOf.reduce((h,E,I)=>{let g=new st,T=`${n}/oneOf/${I}`,S=Ie(e,g,T,o,E,a);return S&&l.push(I),S||c.push(g),S?[...h,g]:h},[]),f=s.IsEqual(m.length,1)&&t.Merge(m);return!f&&s.IsEqual(l.length,0)&&c.forEach(h=>h.GetErrors().forEach(E=>t.AddError(E))),f||t.AddError({keyword:"oneOf",schemaPath:n,instancePath:o,params:{passingSchemas:l}})}function tg(e,t,n,o){return(s.IsString(n.pattern)?new RegExp(n.pattern,"u"):n.pattern).test(o)}function KC(e,t,n,o,i,a){return tg(e,t,i,a)||t.AddError({keyword:"pattern",schemaPath:n,instancePath:o,params:{pattern:i.pattern}})}function zC(e,t,n,o){return s.Every(s.Entries(n.patternProperties),0,([i,a])=>{let c=new RegExp(i,"u");return s.Every(s.Entries(o),0,([l,m])=>!c.test(l)||Kt(e,t,a,m)&&t.AddKey(l))})}function YC(e,t,n,o,i,a){return s.EveryAll(s.Entries(i.patternProperties),0,([c,l])=>{let m=`${n}/patternProperties/${c}`,f=new RegExp(c,"u");return s.EveryAll(s.Entries(a),0,([h,E])=>{let I=`${o}/${h}`;return!f.test(h)||zt(e,t,m,I,l,E)&&t.AddKey(h)})})}function VC(e,t,n,o){return s.IsEqual(o.length,0)||s.Every(n.prefixItems,0,(i,a)=>s.IsLessEqualThan(o.length,a)||Kt(e,t,i,o[a])&&t.AddIndex(a))}function QC(e,t,n,o,i,a){return s.IsEqual(a.length,0)||s.EveryAll(i.prefixItems,0,(c,l)=>{let m=`${n}/prefixItems/${l}`,f=`${o}/${l}`;return s.IsLessEqualThan(a.length,l)||zt(e,t,m,f,c,a[l])&&t.AddIndex(l)})}function rg(e,t){return e.includes(t)||rt.Get().exactOptionalPropertyTypes}function ng(e,t){return s.IsUndefined(e[t])}function WC(e,t,n,o){let i=fo(n)?n.required:[];return s.Every(s.Entries(n.properties),0,([c,l])=>{let m=!s.HasPropertyKey(o,c)||Kt(e,t,l,o[c])&&t.AddKey(c);return rg(i,c)?m:ng(o,c)||m})}function ZC(e,t,n,o,i,a){let c=fo(i)?i.required:[];return s.EveryAll(s.Entries(i.properties),0,([m,f])=>{let h=`${n}/properties/${m}`,E=`${o}/${m}`,I=()=>!s.HasPropertyKey(a,m)||zt(e,t,h,E,f,a[m])&&t.AddKey(m);return rg(c,m)?I():ng(a,m)||I()})}function XC(e,t,n,o){return s.Every(s.Keys(o),0,(i,a)=>ne(e,t,n.propertyNames,i))}function JC(e,t,n,o,i,a){let c=[];return s.EveryAll(s.Keys(a),0,(m,f)=>{let h=`${o}/${m}`,E=`${n}/propertyNames`,I=new st,g=Ie(e,I,E,h,i.propertyNames,m);return g||c.push(m),g})||t.AddError({keyword:"propertyNames",schemaPath:n,instancePath:o,params:{propertyNames:c}})}function eP(e,t,n,o){let i=e.RecursiveRef(n)??!1;return q(i)&&ne(e,t,i,o)}function tP(e,t,n,o,i,a){let c=e.RecursiveRef(i)??!1;return q(c)&&Ie(e,t,"#",o,c,a)}function rP(e,t,n,o){let i=e.Ref(n)??!1,a=new xt,c=q(i)&&ne(e,a,i,o);return c&&t.Merge([a]),c}function nP(e,t,n,o,i,a){let c=e.Ref(i)??!1,l=new st,m=q(c)&&Ie(e,l,"#",o,c,a);return m&&t.Merge([l]),m||l.GetErrors().forEach(f=>t.AddError(f)),m}function oP(e,t,n,o){return s.Every(n.required,0,i=>s.HasPropertyKey(o,i))}function iP(e,t,n,o,i,a){let c=[];return s.EveryAll(i.required,0,m=>{let f=s.HasPropertyKey(a,m);return f||c.push(m),f})||t.AddError({keyword:"required",schemaPath:n,instancePath:o,params:{requiredProperties:c}})}function og(e,t,n,o,i){return s.IsEqual(n,"object")?s.IsObjectNotArray(i):s.IsEqual(n,"array")?s.IsArray(i):s.IsEqual(n,"boolean")?s.IsBoolean(i):s.IsEqual(n,"integer")?s.IsInteger(i):s.IsEqual(n,"number")?s.IsNumber(i):s.IsEqual(n,"null")?s.IsNull(i):s.IsEqual(n,"string")?s.IsString(i):s.IsEqual(n,"bigint")?s.IsBigInt(i):s.IsEqual(n,"constructor")?s.IsConstructor(i):s.IsEqual(n,"function")?s.IsFunction(i):s.IsEqual(n,"symbol")?s.IsSymbol(i):s.IsEqual(n,"undefined")?s.IsUndefined(i):s.IsEqual(n,"void")?s.IsUndefined(i):!0}function aP(e,t,n,o,i){return s.Some(n,a=>og(e,t,a,o,i))}function sP(e,t,n,o){return s.IsArray(n.type)?aP(e,t,n.type,n,o):og(e,t,n.type,n,o)}function cP(e,t,n,o,i,a){return(s.IsArray(i.type)?aP(e,t,i.type,i,a):og(e,t,i.type,i,a))||t.AddError({keyword:"type",schemaPath:n,instancePath:o,params:{type:i.type}})}function pP(e,t,n,o){let i=t.GetIndices();return s.Every(o,0,(a,c)=>(i.has(c)||ne(e,t,n.unevaluatedItems,a))&&t.AddIndex(c))}function uP(e,t,n,o,i,a){let c=t.GetIndices(),l=[];return s.EveryAll(a,0,(f,h)=>{let E=new st,I=(c.has(h)||Ie(e,E,n,o,i.unevaluatedItems,f))&&t.AddIndex(h);return I||l.push(h),I})||t.AddError({keyword:"unevaluatedItems",schemaPath:n,instancePath:o,params:{unevaluatedItems:l}})}function lP(e,t,n,o){let i=t.GetKeys();return s.Every(s.Entries(o),0,([a,c])=>i.has(a)||ne(e,t,n.unevaluatedProperties,c)&&t.AddKey(a))}function mP(e,t,n,o,i,a){let c=t.GetKeys(),l=[];return s.EveryAll(s.Entries(a),0,([f,h])=>{let E=new st,I=c.has(f)||Ie(e,E,n,o,i.unevaluatedProperties,h)&&t.AddKey(f);return I||l.push(f),I})||t.AddError({keyword:"unevaluatedProperties",schemaPath:n,instancePath:o,params:{unevaluatedProperties:l}})}function dP(e){return!s.IsEqual(e.uniqueItems,!1)}function fP(e,t,n,o){if(!dP(n))return!0;let i=new Set(o.map(Bn.Hash)).size,a=o.length;return s.IsEqual(i,a)}function gP(e,t,n,o,i,a){if(!dP(i))return!0;let c=new Set,l=a.reduce((f,h,E)=>{let I=Bn.Hash(h);return c.has(I)?[...f,E]:(c.add(I),f)},[]);return s.IsEqual(l.length,0)||t.AddError({keyword:"uniqueItems",schemaPath:n,instancePath:o,params:{duplicateItems:l}})}function Kt(e,t,n,o){return t.Push()&&ne(e,t,n,o)&&t.Pop()}function ne(e,t,n,o){e.Push(n);let i=Tu(n)?Uf(e,t,n,o):(!Cf(n)||sP(e,t,n,o))&&(!(s.IsObject(o)&&!s.IsArray(o))||(!fo(n)||oP(e,t,n,o))&&(!Kr(n)||VR(e,t,n,o))&&(!cf(n)||nC(e,t,n,o))&&(!pf(n)||iC(e,t,n,o))&&(!uf(n)||sC(e,t,n,o))&&(!gs(n)||zC(e,t,n,o))&&(!hs(n)||WC(e,t,n,o))&&(!Af(n)||XC(e,t,n,o))&&(!ds(n)||Xf(e,t,n,o))&&(!_f(n)||Yf(e,t,n,o)))&&(!s.IsArray(o)||(!nf(n)||KR(e,t,n,o))&&(!lo(n)||vf(e,t,n,o))&&(!bi(n)||PC(e,t,n,o))&&(!Tf(n)||Bf(e,t,n,o))&&(!Eu(n)||Kf(e,t,n,o))&&(!mo(n)||Vf(e,t,n,o))&&(!Si(n)||Wf(e,t,n,o))&&(!Ai(n)||VC(e,t,n,o))&&(!Oi(n)||fP(e,t,n,o)))&&(!s.IsString(o)||(!Ef(n)||zf(e,t,n,o))&&(!ms(n)||Zf(e,t,n,o))&&(!ls(n)||Ff(e,t,n,o))&&(!fs(n)||tg(e,t,n,o)))&&(!(s.IsNumber(o)||s.IsBigInt(o))||(!ff(n)||Mf(e,t,n,o))&&(!zr(n)||Df(e,t,n,o))&&(!yf(n)||Hf(e,t,n,o))&&(!Vr(n)||Qf(e,t,n,o))&&(!If(n)||Jf(e,t,n,o)))&&(!xf(n)||rP(e,t,n,o))&&(!Of(n)||eP(e,t,n,o))&&(!lf(n)||pC(e,t,n,o))&&(!sf(n)||wf(e,t,n,o))&&(!df(n)||kf(e,t,n,o))&&(!gf(n)||RC(e,t,n,o))&&(!bf(n)||eg(e,t,n,o))&&(!of(n)||WR(e,t,n,o))&&(!af(n)||XR(e,t,n,o))&&(!Sf(n)||BC(e,t,n,o))&&(!Iu(n)||!s.IsArray(o)||pP(e,t,n,o))&&(!bu(n)||!s.IsObject(o)||lP(e,t,n,o))&&(!rf(n)||FR(e,t,n,o));return e.Pop(n),i}function zt(e,t,n,o,i,a){return t.Push()&&Ie(e,t,n,o,i,a)&&t.Pop()}function Ie(e,t,n,o,i,a){e.Push(i);let c=Tu(i)?eC(e,t,n,o,i,a):!!(+(!Cf(i)||cP(e,t,n,o,i,a))&+(!(s.IsObject(a)&&!s.IsArray(a))||!!(+(!fo(i)||iP(e,t,n,o,i,a))&+(!Kr(i)||QR(e,t,n,o,i,a))&+(!cf(i)||oC(e,t,n,o,i,a))&+(!pf(i)||aC(e,t,n,o,i,a))&+(!uf(i)||cC(e,t,n,o,i,a))&+(!gs(i)||YC(e,t,n,o,i,a))&+(!hs(i)||ZC(e,t,n,o,i,a))&+(!Af(i)||JC(e,t,n,o,i,a))&+(!ds(i)||jC(e,t,n,o,i,a))&+(!_f(i)||kC(e,t,n,o,i,a))))&+(!s.IsArray(a)||!!(+(!nf(i)||zR(e,t,n,o,i,a))&+(!lo(i)||rC(e,t,n,o,i,a))&+(!bi(i)||UC(e,t,n,o,i,a))&+(!Tf(i)||wC(e,t,n,o,i,a))&+(!Eu(i)||NC(e,t,n,o,i,a))&+(!mo(i)||MC(e,t,n,o,i,a))&+(!Si(i)||GC(e,t,n,o,i,a))&+(!Ai(i)||QC(e,t,n,o,i,a))&+(!Oi(i)||gP(e,t,n,o,i,a))))&+(!s.IsString(a)||!!(+(!Ef(i)||LC(e,t,n,o,i,a))&+(!ms(i)||$C(e,t,n,o,i,a))&+(!ls(i)||xC(e,t,n,o,i,a))&+(!fs(i)||KC(e,t,n,o,i,a))))&+(!(s.IsNumber(a)||s.IsBigInt(a))||!!(+(!ff(i)||mC(e,t,n,o,i,a))&+(!zr(i)||dC(e,t,n,o,i,a))&+(!yf(i)||vC(e,t,n,o,i,a))&+(!Vr(i)||DC(e,t,n,o,i,a))&+(!If(i)||qC(e,t,n,o,i,a))))&+(!xf(i)||nP(e,t,n,o,i,a))&+(!Of(i)||tP(e,t,n,o,i,a))&+(!lf(i)||uC(e,t,n,o,i,a))&+(!sf(i)||tC(e,t,n,o,i,a))&+(!df(i)||lC(e,t,n,o,i,a))&+(!gf(i)||CC(e,t,n,o,i,a))&+(!bf(i)||FC(e,t,n,o,i,a))&+(!of(i)||ZR(e,t,n,o,i,a))&+(!af(i)||JR(e,t,n,o,i,a))&+(!Sf(i)||HC(e,t,n,o,i,a))&+(!Iu(i)||!s.IsArray(a)||uP(e,t,n,o,i,a))&+(!bu(i)||!s.IsObject(a)||mP(e,t,n,o,i,a)))&&(!rf(i)||BR(e,t,n,o,i,a));return e.Pop(i),c}var On={};Yt(On,{DynamicRef:()=>TK,Ref:()=>ag});var Ui={};Yt(Ui,{Delete:()=>lK,Get:()=>pK,Has:()=>cK,Indices:()=>_s,Set:()=>uK});function hP(e){if(e.length===0)throw Error("Cannot set root")}function yP(e){if(!s.IsObject(e))throw Error("Cannot set value")}function oK(e){if(s.IsUnsafePropertyKey(e))throw Error("Pointer contains unsafe property key")}function TP(e){for(let t of e)oK(t)}function iK(e){return/^(0|[1-9]\d*)$/.test(e)}function EP(e){return[e.slice(0,e.length-1),e.slice(e.length-1)[0]]}function aK(e,t){return s.IsObject(t)&&s.HasPropertyKey(t,e)}function sK(e,t){return s.IsObject(t)&&!s.IsUnsafePropertyKey(e)?t[e]:void 0}function ig(e,t){return e.reduce((n,o)=>sK(o,n),t)}function _s(e){if(s.IsEqual(e.length,0))return[];let t=e.split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~"));return t.length>0&&t[0]===""?t.slice(1):t}function cK(e,t){let n=e;return _s(t).every(o=>aK(o,n)?(n=n[o],!0):!1)}function pK(e,t){let n=_s(t);return ig(n,e)}function uK(e,t,n){let o=_s(t);hP(o),TP(o);let[i,a]=EP(o),c=ig(i,e);return yP(c),c[a]=n,e}function lK(e,t){let n=_s(t);hP(n),TP(n);let[o,i]=EP(n),a=ig(o,e);return yP(a),s.IsArray(a)&&iK(i)?a.splice(+i,1):delete a[i],e}function mK(e,t,n){if(e.$id===n.hash)return e;let o=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(s.IsEqual(o.pathname,i.pathname))return n.hash.startsWith("#")?_P(e,t,n):e}function dK(e,t,n){let o=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return s.IsEqual(o.href,i.href)?e:void 0}function fK(e,t,n){let o=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return s.IsEqual(o.href,i.href)?e:void 0}function _P(e,t,n){if(n.href.endsWith("#"))return e;if(!n.hash.startsWith("#"))return;let o=decodeURIComponent(n.hash.slice(1));if(o.startsWith("/"))return Ui.Get(e,o)}function gK(e,t,n){if(Yr(e)){let o=mK(e,t,n);if(!s.IsUndefined(o))return o}if(us(e)){let o=dK(e,t,n);if(!s.IsUndefined(o))return o}if(An(e)){let o=fK(e,t,n);if(!s.IsUndefined(o))return o}return _P(e,t,n)}function hK(e,t,n){return e.reduce((o,i)=>{let a=sg(i,t,n);return s.IsUndefined(a)?o:a},void 0)}function yK(e,t,n){return s.Keys(e).reduce((o,i)=>{let a=sg(e[i],t,n);return s.IsUndefined(a)?o:a},void 0)}function sg(e,t,n){let o=ar(e)&&Yr(e)?new URL(e.$id,t.href):t;if(ar(e)){let i=gK(e,o,n);if(!s.IsUndefined(i))return i}if(s.IsArray(e))return hK(e,o,n);if(s.IsObject(e))return yK(e,o,n)}function ag(e,t){let n=new URL("http://unknown/"),o=Yr(e)?new URL(e.$id,n.href):n,i=new URL(t,o.href);return sg(e,o,i)}function TK(e,t,n,o){let i=n.$dynamicRef.startsWith("#")?ag(t,n.$dynamicRef):ag(e,n.$dynamicRef);return s.IsUndefined(i)?void 0:!ar(i)||!An(i)||new URL(n.$dynamicRef,"http://unknown/").hash.startsWith("#/")?i:o.find(l=>l.$dynamicAnchor===i.$dynamicAnchor)??i}var wi=function(e,t,n,o){if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},xn,IP,bP,SP,AP,ho=class{constructor(t,n){xn.add(this),this.context=t,this.schema=n,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((t,n)=>new URL(n.$id,t),new URL("http://unknown"))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(t){ar(t)&&(Yr(t)&&(this.ids.push(t),wi(this,xn,"m",IP).call(this,t)),us(t)&&this.anchors.push(t),_u(t)&&this.recursiveAnchors.push(t),An(t)&&this.dynamicAnchors.push(t))}Pop(t){ar(t)&&(Yr(t)&&(this.ids.pop(),wi(this,xn,"m",bP).call(this,t)),us(t)&&this.anchors.pop(),_u(t)&&this.recursiveAnchors.pop(),An(t)&&this.dynamicAnchors.pop())}Ref(t){return wi(this,xn,"m",SP).call(this,t)??wi(this,xn,"m",AP).call(this,t)}RecursiveRef(t){return _u(this.Base())?On.Ref(this.recursiveAnchors[0],t.$recursiveRef):On.Ref(this.Base(),t.$recursiveRef)}DynamicRef(t){let n=this.schema;return On.DynamicRef(n,this.Base(),t,this.dynamicAnchors)}};xn=new WeakSet,IP=function e(t,n=!0){if(!ar(t))return;let o=t;if(!(!n&&Yr(o))){!n&&An(o)&&this.dynamicAnchors.push(o);for(let i of s.Keys(o))wi(this,xn,"m",e).call(this,o[i],!1)}},bP=function e(t,n=!0){if(!ar(t))return;let o=t;if(!(!n&&Yr(o))){!n&&An(o)&&this.dynamicAnchors.pop();for(let i of s.Keys(o))wi(this,xn,"m",e).call(this,o[i],!1)}},SP=function(t){return s.HasPropertyKey(this.context,t.$ref)?this.context[t.$ref]:void 0},AP=function(t){let n=this.schema;return t.$ref.startsWith("#")?On.Ref(this.Base(),t.$ref):On.Ref(n,t.$ref)};function Hu(...e){let[t,n,o]=oe.Match(e,{3:(h,E,I)=>[h,E,I],2:(h,E)=>[{},h,E]}),i=rt.Get(),a=eT(),c=[],l=new ho(t,n),m=new ys(h=>{if(!s.IsGreaterEqualThan(c.length,i.maxErrors))return c.push({...h,message:a(h)})});return[Ie(l,m,"#","",n,o),c]}function pg(...e){let[t,n,o]=oe.Match(e,{3:(c,l,m)=>[c,l,m],2:(c,l)=>[{},c,l]}),i=new ho(t,n),a=new xt;return ne(i,a,n,o)}function he(...e){let[t,n,o]=oe.Match(e,{3:(i,a,c)=>[i,a,c],2:(i,a)=>[{},i,a]});return pg(t,n,o)}function Rn(...e){let[t,n,o]=oe.Match(e,{3:(c,l,m)=>[c,l,m],2:(c,l)=>[{},c,l]}),[i,a]=Hu(t,n,o);return a}var Cn=class extends Error{constructor(t,n,o){super(t),Object.defineProperty(this,"cause",{value:{source:t,errors:o,value:n},writable:!1,configurable:!1,enumerable:!1})}};function OP(e,t,n){return s.IsArray(n)?n.map(o=>ct(e,t.items,o)):n}function xP(e,t,n){return ct({...e,...t.$defs},nt(t.$ref),n)}function IK(e,t){let n=s.HasPropertyKey(t,"unevaluatedProperties")?{additionalProperties:t.unevaluatedProperties}:{},o=Qt(e,t),i=ft(o);return D(i)?Np(i,n):i}function RP(e,t,n){let o=IK(e,t);return ct(e,o,n)}function Ku(e){return s.HasPropertyKey(e,"additionalProperties")?e.additionalProperties:void 0}function CP(e,t,n){if(!s.IsObject(n)||s.IsArray(n))return n;let o=Ku(t);for(let i of s.Keys(n)){if(s.HasPropertyKey(t.properties,i)){n[i]=ct(e,t.properties[i],n[i]);continue}if(s.IsBoolean(o)&&s.IsEqual(o,!0)||Ue(o)&&he(e,o,n[i])){n[i]=ct(e,o,n[i]);continue}delete n[i]}return n}function PP(e,t,n){if(!s.IsObject(n))return n;let o=Ku(t),[i,a]=[new RegExp(it(t)),Se(t)];for(let c of s.Keys(n)){if(i.test(c)){n[c]=ct(e,a,n[c]);continue}if(s.IsBoolean(o)&&s.IsEqual(o,!0)||Ue(o)&&he(e,o,n[c])){n[c]=ct(e,o,n[c]);continue}delete n[c]}return n}function UP(e,t,n){return s.HasPropertyKey(e,t.$ref)?ct(e,e[t.$ref],n):n}function wP(e,t,n){if(!s.IsArray(n))return n;let o=Math.min(n.length,t.items.length);for(let i=0;i<o;i++)n[i]=ct(e,t.items[i],n[i]);return s.IsGreaterThan(n.length,o)?n.slice(0,o):n}function $e(e){return jn(e)}function vP(e,t,n){for(let o of t.anyOf){let i=ct(e,o,$e(n));if(he(e,o,i))return i}return n}function ct(e,t,n){return Z(t)?OP(e,t,n):Te(t)?xP(e,t,n):M(t)?RP(e,t,n):D(t)?CP(e,t,n):de(t)?PP(e,t,n):ce(t)?UP(e,t,n):Y(t)?wP(e,t,n):R(t)?vP(e,t,n):n}function bK(e,t){for(let n of Cc.Keys(e))Cc.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function SK(e){let t={};for(let n of Cc.Keys(e))t[n]=Is(e[n]);return t}function AK(e){return ug(HA(e))}function ug(e){return e.map(t=>Is(t))}function Is(e){let t=Z(e)?Pt(Is(e.items),No(e)):M(e)?ut(ug(e.allOf)):R(e)?F(AK(e.anyOf)):D(e)?k(SK(e.properties)):de(e)?Fo(un(e),Is(Se(e))):Y(e)?ke(ug(e.items)):e;return bK(e,t)}function vi(e){return Is(e)}function Or(...e){let[t,n,o]=oe.Match(e,{3:(a,c,l)=>[a,c,l],2:(a,c)=>[{},a,c]}),i=rt.Get().unionPrioritySort?vi(n):n;return ct(t,i,o)}var ie={};Yt(ie,{Fail:()=>To,IsOk:()=>lg,Ok:()=>L,TryArray:()=>OK,TryBigInt:()=>mg,TryBoolean:()=>DK,TryNull:()=>FK,TryNumber:()=>zK,TryString:()=>YK,TryUndefined:()=>XK});function lg(e){return s.IsObject(e)&&s.HasPropertyKey(e,"value")}function L(e){return{value:e}}function To(){}function OK(e){return s.IsArray(e)?L(e):L([e])}function xK(e){return s.IsEqual(e,!0)?L(BigInt(1)):L(BigInt(0))}var RK=/^-?(0|[1-9]\d*)n$/,CK=/^-?(0|[1-9]\d*)\.\d+$/,PK=/^-?(0|[1-9]\d*)$/;function UK(e){return RK.test(e)}function wK(e){return CK.test(e)}function vK(e){return PK.test(e)}function NK(e){let t=e.toLowerCase();return UK(e)?L(BigInt(e.slice(0,e.length-1))):wK(e)?L(BigInt(e.split(".")[0])):vK(e)?L(BigInt(e)):s.IsEqual(t,"false")?L(BigInt(0)):s.IsEqual(t,"true")?L(BigInt(1)):void 0}function mg(e){return s.IsBigInt(e)?L(e):s.IsBoolean(e)?xK(e):s.IsNumber(e)?L(BigInt(Math.trunc(e))):s.IsNull(e)?L(BigInt(0)):s.IsString(e)?NK(e):s.IsUndefined(e)?L(BigInt(0)):void 0}function LK(e){return s.IsEqual(e,BigInt(0))?L(!1):s.IsEqual(e,BigInt(1))?L(!0):void 0}function kK(e){return s.IsEqual(e,0)?L(!1):s.IsEqual(e,1)?L(!0):void 0}function MK(e){return s.IsEqual(e.toLowerCase(),"false")?L(!1):s.IsEqual(e.toLowerCase(),"true")?L(!0):s.IsEqual(e,"0")?L(!1):s.IsEqual(e,"1")?L(!0):void 0}function DK(e){return s.IsBigInt(e)?LK(e):s.IsBoolean(e)?L(e):s.IsNumber(e)?kK(e):s.IsNull(e)?L(!1):s.IsString(e)?MK(e):s.IsUndefined(e)?L(!1):void 0}function GK(e){return s.IsEqual(e,BigInt(0))?L(null):void 0}function $K(e){return s.IsEqual(e,!1)?L(null):void 0}function jK(e){return s.IsEqual(e,0)?L(null):void 0}function qK(e){let t=e.toLowerCase();return s.IsEqual(t,"undefined")||s.IsEqual(t,"null")||s.IsEqual(e,"")||s.IsEqual(e,"0")?L(null):void 0}function FK(e){return s.IsBigInt(e)?GK(e):s.IsBoolean(e)?$K(e):s.IsNumber(e)?jK(e):s.IsNull(e)?L(null):s.IsString(e)?qK(e):s.IsUndefined(e)?L(null):void 0}var NP=BigInt(Number.MAX_SAFE_INTEGER),LP=BigInt(Number.MIN_SAFE_INTEGER);function BK(e){return e<=NP&&e>=LP?L(Number(e)):void 0}function HK(e){return L(e?1:0)}function KK(e){let t=+e;if(s.IsNumber(t))return L(t);let n=e.toLowerCase();if(s.IsEqual(n,"false"))return L(0);if(s.IsEqual(n,"true"))return L(1);let o=mg(e);return lg(o)?o.value<=NP&&o.value>=LP?L(Number(o.value)):void 0:void 0}function zK(e){return s.IsBigInt(e)?BK(e):s.IsBoolean(e)?HK(e):s.IsNumber(e)?L(e):s.IsNull(e)?L(0):s.IsString(e)?KK(e):s.IsUndefined(e)?L(0):void 0}function YK(e){return s.IsBigInt(e)?L(e.toString()):s.IsBoolean(e)?L(e.toString()):s.IsNumber(e)?L(e.toString()):s.IsNull(e)?L("null"):s.IsString(e)?L(e):s.IsUndefined(e)?L(""):void 0}function VK(e){return s.IsEqual(e,BigInt(0))?L(void 0):void 0}function QK(e){return s.IsEqual(e,!1)?L(void 0):void 0}function WK(e){return s.IsEqual(e,0)?L(void 0):void 0}function ZK(e){let t=e.toLowerCase();return s.IsEqual(t,"undefined")||s.IsEqual(t,"null")||s.IsEqual(e,"")||s.IsEqual(e,"0")?L(void 0):void 0}function XK(e){return s.IsBigInt(e)?VK(e):s.IsBoolean(e)?QK(e):s.IsNumber(e)?WK(e):s.IsNull(e)?L(void 0):s.IsString(e)?ZK(e):s.IsUndefined(e)?L(e):void 0}function kP(e,t,n){return ie.TryArray(n).value.map(i=>je(e,t.items,i))}function MP(e,t,n){let o=ie.TryBigInt(n);return ie.IsOk(o)?o.value:n}function DP(e,t,n){let o=ie.TryBoolean(n);return ie.IsOk(o)?o.value:n}function GP(e,t,n){return je({...e,...t.$defs},nt(t.$ref),n)}function $P(e,t,n){return je(e,ft(t),n)}function jP(e,t,n){let o=ie.TryNumber(n);return ie.IsOk(o)?Math.trunc(o.value):n}function qP(e,t,n){let o=Qt(e,t),i=ft(o);return je(e,i,n)}function JK(e,t,n){let o=ie.TryBigInt(n);return ie.IsOk(o)&&s.IsEqual(t.const,o.value)?o.value:n}function ez(e,t,n){let o=ie.TryBoolean(n);return ie.IsOk(o)&&s.IsEqual(t.const,o.value)?o.value:n}function tz(e,t,n){let o=ie.TryNumber(n);return ie.IsOk(o)&&s.IsEqual(t.const,o.value)?o.value:n}function rz(e,t,n){let o=ie.TryString(n);return ie.IsOk(o)&&s.IsEqual(t.const,o.value)?o.value:n}function FP(e,t,n){return s.IsEqual(t.const,n)?n:pT(t)?JK(e,t,n):uT(t)?ez(e,t,n):Dc(t)?tz(e,t,n):Gc(t)?rz(e,t,n):ge()}function BP(e,t,n){let o=ie.TryNull(n);return ie.IsOk(o)?o.value:n}function HP(e,t,n){let o=ie.TryNumber(n);return ie.IsOk(o)?o.value:n}function zu(e,t,n,o){let i=s.Keys(o);for(let[a,c]of t)for(let l of i)a.test(l)||(o[l]=je(e,n,o[l]));return o}function bs(e,t,n){return et(e)&&s.IsUndefined(n[t])}function nz(e,t,n){let o=s.EntriesRegExp(t.properties),i=s.Keys(n);for(let[a,c]of o)for(let l of i)!a.test(l)||bs(c,l,n)||(n[l]=je(e,c,n[l]));return s.HasPropertyKey(t,"additionalProperties")&&s.IsObject(t.additionalProperties)?zu(e,o,t.additionalProperties,n):n}function KP(e,t,n){return s.IsObjectNotArray(n)?nz(e,t,n):n}function oz(e,t,n){let o=s.EntriesRegExp(t.patternProperties),i=s.Keys(n);for(let[a,c]of o)for(let l of i)a.test(l)&&(n[l]=je(e,c,n[l]));return s.HasPropertyKey(t,"additionalProperties")&&s.IsObject(t.additionalProperties)?zu(e,o,t.additionalProperties,n):n}function zP(e,t,n){return s.IsObjectNotArray(n)?oz(e,t,n):n}function YP(e,t,n){return s.HasPropertyKey(e,t.$ref)?je(e,e[t.$ref],n):n}function VP(e,t,n){let o=ie.TryString(n);return ie.IsOk(o)?o.value:n}function QP(e,t,n){return je(e,ft(t),n)}function WP(e,t,n){if(!s.IsArray(n))return n;for(let o=0;o<Math.min(t.items.length,n.length);o++)n[o]=je(e,t.items[o],n[o]);return n}function ZP(e,t,n){let o=ie.TryUndefined(n);return ie.IsOk(o)?o.value:n}function XP(e,t,n){if(t.anyOf.some(c=>he(e,c,n)))return n;let a=t.anyOf.map(c=>je(e,c,$e(n))).find(c=>he(e,t,c));return s.IsUndefined(a)?n:a}function JP(e,t,n){let o=ie.TryUndefined(n);return ie.IsOk(o)?void 0:n}function je(e,t,n){return Z(t)?kP(e,t,n):vt(t)?MP(e,t,n):_t(t)?DP(e,t,n):Te(t)?GP(e,t,n):ze(t)?$P(e,t,n):ot(t)?jP(e,t,n):M(t)?qP(e,t,n):Q(t)?FP(e,t,n):hr(t)?BP(e,t,n):Ce(t)?HP(e,t,n):D(t)?KP(e,t,n):de(t)?zP(e,t,n):ce(t)?YP(e,t,n):We(t)?VP(e,t,n):Ee(t)?QP(e,t,n):Y(t)?WP(e,t,n):or(t)?ZP(e,t,n):R(t)?XP(e,t,n):kt(t)?JP(e,t,n):n}function Pn(...e){let[t,n,o]=oe.Match(e,{3:(i,a,c)=>[i,a,c],2:(i,a)=>[{},i,a]});return je(t,n,o)}function eU(e,t,n){if(!s.IsArray(n))return n;for(let o=0;o<n.length;o++)n[o]=pt(e,t.items,n[o]);return n}function tU(e,t,n){return pt({...e,...t.$defs},nt(t.$ref),n)}function rU(e,t){return s.IsUndefined(t)?s.IsFunction(e.default)?e.default():$e(e.default):t}function nU(e,t,n){let o=Qt(e,t),i=ft(o);return pt(e,i,n)}function oU(e,t,n){if(!s.IsObject(n))return n;let o=s.Keys(t.properties);for(let i of o){let a=pt(e,t.properties[i],n[i]);s.IsUndefined(a)&&(et(t.properties[i])||!s.HasPropertyKey(t.properties[i],"default"))||(n[i]=a)}if(!Kr(t)||s.IsBoolean(t.additionalProperties))return n;for(let i of s.Keys(n))o.includes(i)||(n[i]=pt(e,t.additionalProperties,n[i]));return n}function iU(e,t,n){if(!s.IsObject(n))return n;let[o,i]=[new RegExp(it(t)),Se(t)];for(let a of s.Keys(n))o.test(a)&&Ht(i)&&(n[a]=pt(e,i,n[a]));if(!Kr(t))return n;for(let a of s.Keys(n))o.test(a)||(n[a]=pt(e,t.additionalProperties,n[a]));return n}function aU(e,t,n){return s.HasPropertyKey(e,t.$ref)?pt(e,e[t.$ref],n):n}function sU(e,t,n){if(!s.IsArray(n))return n;let[o,i]=[t.items,Math.max(t.items.length,n.length)];for(let a=0;a<i;a++)a<o.length&&(n[a]=pt(e,o[a],n[a]));return n}function cU(e,t,n){for(let o of t.anyOf){let i=pt(e,o,$e(n));if(he(e,o,i))return i}return n}function pt(e,t,n){let o=Ht(t)?rU(t,n):n;return Z(t)?eU(e,t,o):Te(t)?tU(e,t,o):M(t)?nU(e,t,o):D(t)?oU(e,t,o):de(t)?iU(e,t,o):ce(t)?aU(e,t,o):Y(t)?sU(e,t,o):R(t)?cU(e,t,o):o}function Eo(...e){let[t,n,o]=oe.Match(e,{3:(i,a,c)=>[i,a,c],2:(i,a)=>[{},i,a]});return pt(t,n,o)}function Ni(e){return(...t)=>{let[n,o,i]=oe.Match(t,{3:(a,c,l)=>[a,c,l],2:(a,c)=>[{},a,c]});return e.reduce((a,c)=>c(n,o,a),i)}}function iz(e,t,n){return t["~codec"].decode(n)}function az(e,t,n){return t["~codec"].encode(n)}function xe(e,t,n,o){return Hn(n)?s.IsEqual(e,"Decode")?iz(t,n,o):az(t,n,o):o}function sz(e,t,n,o){if(!s.IsArray(o))return o;for(let i=0;i<o.length;i++)o[i]=Pe(e,t,n.items,o[i]);return xe(e,t,n,o)}function cz(e,t,n,o){let i=xe(e,t,n,o);if(!s.IsArray(i))return i;for(let a=0;a<i.length;a++)i[a]=Pe(e,t,n.items,i[a]);return i}function pU(e,t,n,o){return s.IsEqual(e,"Decode")?sz(e,t,n,o):cz(e,t,n,o)}function uU(e,t,n,o){return o=Pe(e,{...t,...n.$defs},nt(n.$ref),o),xe(e,t,n,o)}function lU(e){return e.reduce((t,n)=>({...t,...n}),{})}function mU(e,t){for(let n of t)if(!s.IsDeepEqual(e,n))return n;return e}function pz(e,t,n,o){if(s.IsEqual(n.allOf.length,0))return xe(e,t,n,o);let i=n.allOf.map(l=>Pe(e,t,l,Or(l,$e(o)))),c=i.every(l=>s.IsObject(l))?lU(i):mU(o,i);return xe(e,t,n,c)}function uz(e,t,n,o){if(s.IsEqual(n.allOf.length,0))return xe(e,t,n,o);let i=xe(e,t,n,o),a=n.allOf.map(l=>Pe(e,t,l,Or(l,$e(i))));return a.every(l=>s.IsObject(l))?lU(a):mU(i,a)}function dU(e,t,n,o){return s.IsEqual(e,"Decode")?pz(e,t,n,o):uz(e,t,n,o)}function lz(e,t,n,o){if(!s.IsObjectNotArray(o))return o;for(let i of s.Keys(n.properties))!s.HasPropertyKey(o,i)||bs(n.properties[i],i,o)||(o[i]=Pe(e,t,n.properties[i],o[i]));return xe(e,t,n,o)}function mz(e,t,n,o){let i=xe(e,t,n,o);if(!s.IsObjectNotArray(i))return i;for(let a of s.Keys(n.properties))!s.HasPropertyKey(i,a)||bs(n.properties[a],a,i)||(i[a]=Pe(e,t,n.properties[a],i[a]));return i}function fU(e,t,n,o){return s.IsEqual(e,"Decode")?lz(e,t,n,o):mz(e,t,n,o)}function dz(e,t,n,o){if(!s.IsObjectNotArray(o))return o;let i=new RegExp(it(n));for(let a of s.Keys(o))i.test(a)&&(o[a]=Pe(e,t,Se(n),o[a]));return xe(e,t,n,o)}function fz(e,t,n,o){let i=xe(e,t,n,o);if(!s.IsObjectNotArray(i))return i;let a=new RegExp(it(n));for(let c of s.Keys(i))a.test(c)&&(i[c]=Pe(e,t,Se(n),i[c]));return i}function gU(e,t,n,o){return s.IsEqual(e,"Decode")?dz(e,t,n,o):fz(e,t,n,o)}function hU(e,t,n,o){return s.HasPropertyKey(t,n.$ref)?Pe(e,t,t[n.$ref],o):o}function yU(e,t,n,o){return s.IsEqual(e,"Decode")?xe(e,t,n,hU(e,t,n,o)):hU(e,t,n,xe(e,t,n,o))}function gz(e,t,n,o){if(!s.IsArray(o))return o;for(let i=0;i<Math.min(n.items.length,o.length);i++)o[i]=Pe(e,t,n.items[i],o[i]);return xe(e,t,n,o)}function hz(e,t,n,o){let i=xe(e,t,n,o);if(!s.IsArray(i))return o;for(let a=0;a<Math.min(n.items.length,i.length);a++)i[a]=Pe(e,t,n.items[a],i[a]);return i}function TU(e,t,n,o){return s.IsEqual(e,"Decode")?gz(e,t,n,o):hz(e,t,n,o)}function yz(e,t,n,o){for(let i of n.anyOf){if(!he(t,i,o))continue;let a=Pe(e,t,i,o);return xe(e,t,n,a)}return o}function Tz(e,t,n,o){let i=xe(e,t,n,o);for(let a of n.anyOf){let c=Pe(e,t,a,$e(i));if(he(t,a,c))return c}return i}function EU(e,t,n,o){return s.IsEqual(e,"Decode")?yz(e,t,n,o):Tz(e,t,n,o)}function Pe(e,t,n,o){return Z(n)?pU(e,t,n,o):Te(n)?uU(e,t,n,o):M(n)?dU(e,t,n,o):D(n)?fU(e,t,n,o):de(n)?gU(e,t,n,o):ce(n)?yU(e,t,n,o):Y(n)?TU(e,t,n,o):R(n)?EU(e,t,n,o):xe(e,t,n,o)}var dg=class extends Cn{constructor(t,n){super("Decode",t,n)}};function Ez(e,t,n){if(!he(e,t,n))throw new dg(n,Rn(e,t,n));return n}function _z(e,t,n){let o=rt.Get().unionPrioritySort?vi(t):t;return Pe("Decode",e,o,n)}var i9e=Ni([(e,t,n)=>$e(n),(e,t,n)=>Eo(e,t,n),(e,t,n)=>Pn(e,t,n),(e,t,n)=>Or(e,t,n),(e,t,n)=>Ez(e,t,n),(e,t,n)=>_z(e,t,n)]);var fg=class extends Cn{constructor(t,n){super("Encode",t,n)}};function Iz(e,t,n){if(!he(e,t,n))throw new fg(n,Rn(e,t,n));return n}function bz(e,t,n){let o=rt.Get().unionPrioritySort?vi(t):t;return Pe("Encode",e,o,n)}var T9e=Ni([(e,t,n)=>$e(n),(e,t,n)=>bz(e,t,n),(e,t,n)=>Eo(e,t,n),(e,t,n)=>Pn(e,t,n),(e,t,n)=>Or(e,t,n),(e,t,n)=>Iz(e,t,n)]);var Zt=class extends Error{constructor(t,n){super(n),this.type=t}};function _U(e,t){return s.IsFunction(t.default)?t.default(t):s.IsObject(t.default)?$e(t.default):t.default}function IU(e,t){if(Oi(t)&&!Ht(t))throw new Zt(t,"Arrays with uniqueItems constraints must specify a default annotation");let n=Si(t)?t.minItems:0;return Array.from({length:n},()=>qe(e,t.items))}function bU(e,t){return zr(t)?BigInt(t.exclusiveMinimum)+BigInt(1):Vr(t)?BigInt(t.minimum):BigInt(0)}function SU(e,t){return!1}function AU(e,t){let n=qe(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function OU(e,t){return qe({...e,...t.$defs},nt(t.$ref))}function xU(e,t){return qe(e,ft(t))}function RU(e,t){let n=qe(e,t.returnType);return()=>n}function CU(e,t){return zr(t)&&s.IsNumber(t.exclusiveMinimum)?t.exclusiveMinimum+1:Vr(t)?t.minimum:0}function PU(e,t){let n=Qt(e,t),o=ft(n);return qe(e,o)}function UU(e,t){return t.const}function wU(e,t){throw new Zt(t,"Cannot create TNever types")}function vU(e,t){return null}function NU(e,t){return zr(t)&&s.IsNumber(t.exclusiveMinimum)?t.exclusiveMinimum+1:Vr(t)?t.minimum:0}function LU(e,t){return(s.IsUndefined(t.required)?[]:t.required).reduce((o,i)=>({...o,[i]:qe(e,t.properties[i])}),{})}function kU(e,t){if(ds(t)&&!Ht(t))throw new Zt(t,"Record with the minProperties constraint must have a default annotation");return{}}function MU(e,t){return s.HasPropertyKey(e,t.$ref)?qe(e,e[t.$ref]):(()=>{throw new Zt(t,"Unable to deref Ref")})()}function DU(e,t){if((fs(t)||ls(t))&&!Ht(t))throw Error("Strings with format or pattern constraints must specify default");let o=ms(t)?t.minLength:0;return"".padEnd(o)}function GU(e,t){return Symbol()}function $U(e,t){let n=_a(t.pattern);if(We(n))throw new Zt(t,"Unable to create TemplateLiteral due to infinite type expansion");return qe(e,n)}function jU(e,t){return Array.from({length:t.minItems},(n,o)=>qe(e,t.items[o]))}function qU(e,t){if(s.IsEqual(t.anyOf.length,0))throw Error("Unable to create Union with no variants");return qe(e,t.anyOf[0])}function qe(e,t){return Ht(t)?_U(e,t):Z(t)?IU(e,t):vt(t)?bU(e,t):_t(t)?SU(e,t):Be(t)?AU(e,t):Te(t)?OU(e,t):ze(t)?xU(e,t):He(t)?RU(e,t):ot(t)?CU(e,t):M(t)?PU(e,t):Q(t)?UU(e,t):rr(t)?wU(e,t):hr(t)?vU(e,t):Ce(t)?NU(e,t):D(t)?LU(e,t):de(t)?kU(e,t):ce(t)?MU(e,t):We(t)?DU(e,t):yr(t)?GU(e,t):Ee(t)?$U(e,t):Y(t)?jU(e,t):or(t)?void 0:R(t)?qU(e,t):kt(t)?void 0:void 0}function xr(...e){let[t,n]=oe.Match(e,{2:(o,i)=>[o,i],1:o=>[{},o]});return qe(t,n)}var gg=class extends Cn{constructor(t,n){super("Parse",t,n)}};function Sz(e,t,n){if(!he(e,t,n))throw new gg(n,Rn(e,t,n));return n}var $6e=Ni([(e,t,n)=>$e(n),(e,t,n)=>Eo(e,t,n),(e,t,n)=>Pn(e,t,n),(e,t,n)=>Or(e,t,n),(e,t,n)=>Sz(e,t,n)]);var Oz=k({type:z("insert"),path:It(),value:Qe()}),xz=Object({type:z("update"),path:It(),value:Qe()}),Rz=k({type:z("delete"),path:It()}),z6e=F([Oz,xz,Rz]);function Li(e){if(!e.body)throw new Error("This command does not accept a request body");let t=e.body;return t.examples?.length?t.examples[0]:xr(t)}function Zr(e,t,n,o,i){e.command(t).description(n).option("-f, --file <FILE_PATH>","Read body from file (use - for stdin)").option("-d, --data <JSON>","Inline JSON body").option("--generate-skeleton","Print a JSON skeleton for the request body and exit").action(async a=>{if(a.generateSkeleton){ee(Li(o));return}let c=Ii(a),l=await i()(o,{body:c});ee(l)})}function HU(e,t){let n=e.command("grok").description("Test and preview grok parsing rules");Zr(n,"parse","Parse sample log lines with grok rules and return the extracted fields",jR,t)}var KU=require("node:child_process"),zU=require("node:fs"),YU=require("node:os"),Qu=require("node:path");var _o=require("node:fs");function Ss(e,t){let n=`${e}.tmp.${process.pid}`;(0,_o.writeFileSync)(n,t),(0,_o.renameSync)(n,e)}function As(e){try{return(0,_o.readFileSync)(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function Os(e,t){if(t===void 0)return;let n=`${e}.bak.${new Date().toISOString().replaceAll(":","-")}`;return(0,_o.writeFileSync)(n,t),n}function Io(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var hg="tsuga-dev/agent-plugins",Yu="tsuga";function Vu(e,t){V(` $ ${e} ${t.join(" ")}`);try{(0,KU.execFileSync)(e,t,{stdio:["ignore","inherit","inherit"]})}catch(n){let o=n.status??1;throw new Error(`${e} ${t.join(" ")} exited ${o}`,{cause:n})}}function Uz(e,t){V("Claude Code \u2192 installing Tsuga plugin"),Vu("claude",["plugin","marketplace","add",hg]),Vu("claude",["plugin","install",`tsuga@${Yu}`]),t.autoUpdate&&wz(e)}function wz(e){let t=(0,Qu.join)(e,".claude","settings.json");V(`Claude Code \u2192 ${t} (autoUpdate)`),(0,zU.mkdirSync)((0,Qu.dirname)(t),{recursive:!0});let n=As(t),o=JSON.parse(n??"{}");if(!Io(o))throw new Error(`${t} must contain a JSON object`);let i=o.extraKnownMarketplaces??{};if(!Io(i))throw new Error(`${t} "extraKnownMarketplaces" must be a JSON object`);let a=i[Yu],c=Io(a)?a:{};o.extraKnownMarketplaces={...i,[Yu]:{source:{source:"github",repo:hg},...c,autoUpdate:!0}};let l=Os(t,n);Ss(t,`${JSON.stringify(o,null,2)}
|
|
141
141
|
`),V(l===void 0?" created":` patched (backup: ${l})`)}function vz(){V("Codex \u2192 installing Tsuga plugin"),Vu("codex",["plugin","marketplace","add",hg]),Vu("codex",["plugin","add",`tsuga@${Yu}`])}function VU(e){let t=e.command("install").description("Install Tsuga plugins into local LLM CLIs").command("plugin").description("Install the Tsuga plugin into a specific LLM CLI");t.command("claude-code").description("Install the Tsuga plugin into Claude Code (requires the claude CLI in PATH)").option("--no-auto-update","Skip patching ~/.claude/settings.json with autoUpdate=true").action(n=>{Uz((0,YU.homedir)(),n),V("Restart your claude session to load the new plugins.")}),t.command("codex").description("Install the Tsuga plugin into Codex (requires the codex CLI in PATH)").action(()=>{vz(),V("Restart your codex session to load the new plugins.")})}var Nz=10,Lz=r.Object({key:u({allowEmpty:!1,description:"Telemetry attribute key to scope the ranking by: a service, environment, team, route, or other positive equality term in the population you want fields for. Use dot-path keys such as `context.service.name`."}),value:r.Optional(u({allowEmpty:!1,description:"Attribute value the scoped telemetry should match, when the scope is a specific service, environment, team, route, or other known value. When omitted, artifacts that reference the key match this entry at full weight regardless of value."})),valueMustMatch:r.Optional(r.Boolean({description:"When true, this entry is a hard filter rather than a weight: any widget or monitor that does not match it exactly (key = value) contributes no fields at all, instead of contributing at a reduced weight. Other widgets of the same dashboard still contribute if they match. Requires `value`."}))}),yg=r.Object({field:r.String({description:"Field name to use in queries. For `kind: attribute`, this is an attribute dot path. For `kind: metric`, this is either a metric name or a `metricName.context.attribute` path when the metric query used a metric attribute."}),kind:r.Enum(["attribute","metric"],{description:"Whether the field is a telemetry attribute or a metric name. `metric` appears only in the metrics bucket, for fields referenced as the aggregated field of a metrics-source query."}),inferredType:r.Enum(["numeric","categorical","unknown"],{description:"Value type inferred from how the field is used: `numeric` when aggregated with sum/average/percentile, referenced by numeric or range filters, or a metric name; `categorical` when only grouped by or matched with equality/text filters; `unknown` otherwise. Evidence-based \u2014 a numeric field used only in equality filters reads as categorical."}),score:r.Number({description:"Relative relevance score computed by Tsuga from how strongly readable dashboards and monitors use this field for the requested scope, discounted when the field is common across the whole organization. Higher values mean stronger evidence that the field is useful for this scope. Scores are intended for ranking, not for comparison across unrelated scopes."}),artifacts:r.Number({description:"Number of distinct readable dashboards and monitors that reference this field and match the requested scope. Tsuga counts an artifact once per field even if it uses the field in multiple widgets or queries."}),globalArtifacts:r.Number({description:"Number of organization-wide dashboards and monitors that reference this field, regardless of the requested scope or caller permissions. Tsuga uses this anonymous baseline to down-rank fields that are common everywhere."}),usage:r.Object({groupBy:r.Number({description:"Number of distinct readable matching artifacts that use this field as a group-by or split dimension."}),filter:r.Number({description:"Number of distinct readable matching artifacts that filter on this field in widget queries, monitor queries, or dashboard-wide filters."}),measure:r.Number({description:"Number of distinct readable matching artifacts that aggregate this field as `aggregate.field`."}),column:r.Number({description:"Number of distinct readable matching artifacts that pin this field as a list-widget column."})},{description:"Distinct-artifact counts by usage kind, explaining why the field ranked where it did; a dashboard referencing the field the same way in many widgets counts once for that usage kind."})}),Tg=r.Object({logs:r.Array(yg,{description:"Top log fields for the requested scope, ranked by score and mined from readable logs-sourced dashboards and monitors."}),traces:r.Array(yg,{description:"Top trace fields for the requested scope, ranked by score and mined from readable traces-sourced dashboards and monitors."}),metrics:r.Array(yg,{description:"Top metric names and metric-attribute fields for the requested scope, ranked by score and mined from readable metrics-sourced dashboards and monitors."}),dashboardsMatched:r.Number({description:"Number of dashboards that matched the requested scope and that the caller can read. Dashboards the caller cannot read are removed before field rankings are returned."}),monitorsMatched:r.Number({description:"Number of monitors that matched the requested scope and that the caller can read. Monitors the caller cannot read are removed before field rankings are returned."})}),Eg=r.Object({scope:r.Array(Lz,{minItems:1,maxItems:Nz,description:"Scope entries that define the population to rank fields for, drawn from positive equality pairs in a TQL query, such as service and environment. Tsuga matches entries softly by default: an artifact's contribution is weighted by the fraction of entries it matches."})}),H8e=d({tags:["interesting-fields"],url:"/v0/interesting-fields",method:"POST",body:Eg,response:Tg});var kz=`/${"v1"}/interesting-fields`,Mz={scope:[{key:"context.service.name",value:"payments"},{key:"context.env",value:"prod",valueMustMatch:!0}]},Dz=r.Object(Eg.properties,{description:"The scope to rank fields for, as attribute key/value pairs such as a service name and an environment. Entries are matched softly by default: a widget contributes in proportion to how many entries it matches, so a broader scope returns a broader ranking. Set `valueMustMatch` on an entry to make it a hard filter instead: a widget that does not match it exactly contributes nothing, even when other entries match.",examples:[Mz]}),QU=d({url:kz,method:"POST",operationId:"getInterestingFields",tags:["public","interesting-fields"],body:Dz,response:Tg,description:"Ranks the telemetry fields most relevant to a scope, mined from how the org already uses them in dashboards and monitors, bucketed by logs, traces, and metrics. Use this before guessing a field or metric name: a field that many scope-matching dashboards group or filter on is the one an operator would reach for. Ranking is TF-IDF style, so a field used everywhere in the org scores below one that is distinctive to the scope. Dashboards and monitors the caller cannot read never contribute field names, only the anonymous frequency baseline. The operation requires public API read access to dashboards and monitors."});function WU(e,t){let n=e.command("interesting-fields").description("Discover the telemetry fields an org already uses for a scope");Zr(n,"list","Rank the log, trace and metric fields most relevant to a scope, mined from dashboards and monitors",QU,t)}var Xt="/v0/kubernetes-explorer",Gz="^[a-z0-9.-]+$",$z="^[A-Za-z0-9._-]+$",ZU=256,XU=r.Optional(u({allowEmpty:!1,description:"Tsuga cluster ID to target. Tsuga assigns it when a cluster is connected to the organization. Optional for single-cluster organizations and required for organizations with multiple clusters to scope the request to one cluster."}));var sr=e=>r.Optional(r.Array(u({allowEmpty:!1}),{description:e})),_g={clusterId:XU,search:r.Optional(r.String({pattern:Gz,minLength:1,maxLength:ZU,description:"Substring matched against the resource name. Kubernetes names are lowercase RFC 1123, so only lowercase letters, digits, `.` and `-` are accepted; uppercase and other characters are rejected. Wildcard and other query-syntax characters are treated literally."}))},JU={clusterId:XU,search:r.Optional(r.String({pattern:$z,minLength:1,maxLength:ZU,description:"Substring matched against the Kubernetes cluster name. Unlike Kubernetes resource names this is a collector-assigned identifier, so uppercase letters, digits, `.`, `-` and `_` are accepted. Wildcard and other query-syntax characters are treated literally."}))},ew=r.Object(_g),tw=r.Object(JU),xs={..._g,includeInternalNamespaces:r.Optional(r.Boolean({description:"When false or omitted, resources in internal namespaces (kube-system, kube-public, kube-node-lease, local-path-storage, gke-managed-*) are excluded."})),clusters:sr("Restrict results to these Kubernetes cluster names."),namespaces:sr("Restrict results to these namespaces."),teams:sr("Restrict results to these team names."),envs:sr("Restrict results to these environments."),...fe},rw=["Pending","Running","Succeeded","Failed","Unknown","CrashLoopBackOff","Error"],jz={...xs,nodes:sr("Restrict results to pods scheduled on these nodes."),deployments:sr("Restrict results to pods owned by these Deployments."),statefulsets:sr("Restrict results to pods owned by these StatefulSets."),daemonsets:sr("Restrict results to pods owned by these DaemonSets."),podStatus:r.Optional(r.Array(r.Enum(rw),{description:"Restrict results to pods whose resolved status matches any of these values. Includes the five Kubernetes phases plus Tsuga-derived CrashLoopBackOff and Error. Applied after stitching pod phase and container status reason telemetry, because phase is not a filterable metric attribute."}))},bo=r.Enum(["asc","desc"],{description:"Sort direction. Defaults to ascending."}),qz=["deployment","statefulset","daemonset"],nw=r.Object({kind:r.Enum(qz,{description:"Kind of Kubernetes workload associated with the pod. Derived from workload attributes in pod telemetry."}),name:r.String({description:"Name of the workload associated with the pod. Derived from workload attributes in pod telemetry."})},{description:"Kubernetes workload controller that owns the pod. Present when workload attributes are observed in pod telemetry."}),ow=r.Object({podName:r.String({description:"Name of the Kubernetes pod. Set when the pod is created."}),namespace:r.Optional(r.String({description:"Kubernetes namespace that contains the pod. Present when namespace telemetry is observed."})),cluster:r.Optional(r.String({description:"Kubernetes cluster name that reported the pod. Present when cluster telemetry is observed."})),team:r.Optional(r.String({description:"Team metadata associated with the pod. Present when a team label or mapping is observed."})),env:r.Optional(r.String({description:"Environment metadata associated with the pod, such as production or staging. Present when an environment label or mapping is observed."})),node:r.Optional(r.String({description:"Kubernetes node currently or most recently running the pod. Present when node telemetry is observed."})),phase:r.Enum(rw,{description:"Current or most recently observed pod status. From pod status and container state telemetry. Values include the Kubernetes phases Pending, Running, Succeeded, Failed, and Unknown, plus Tsuga-derived CrashLoopBackOff and Error values."}),readyContainers:r.Integer({description:"Number of containers in the pod that are currently ready. From container readiness telemetry. Zero or greater."}),totalContainers:r.Integer({description:"Number of observed containers for the pod based on container readiness telemetry. Zero or greater."}),restarts:r.Integer({description:"Total restart count across containers in the pod. From container restart telemetry. Zero or greater."}),createdAt:r.Optional(A({description:"Timestamp from pod start time telemetry for the selected pod instance. Present when pod start time telemetry is observed."}))}),Ig=r.Object({...ow.properties,workload:r.Optional(nw),cpuUsageMilli:r.Optional(r.Number({description:"Recent pod CPU usage in millicores. Present when CPU usage telemetry is observed."})),cpuLimitMilli:r.Optional(r.Number({description:"Configured pod CPU limit in millicores, summed across observed containers. Present when a CPU limit is configured and observed."})),cpuRequestMilli:r.Optional(r.Number({description:"Configured pod CPU request in millicores, summed across observed containers. Present when a CPU request is configured and observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Recent pod memory usage in bytes. Present when memory usage telemetry is observed."})),memoryLimitBytes:r.Optional(r.Number({description:"Configured pod memory limit in bytes, summed across observed containers. Present when a memory limit is configured and observed."})),memoryRequestBytes:r.Optional(r.Number({description:"Configured pod memory request in bytes, summed across observed containers. Present when a memory request is configured and observed."})),cpuUtilization:r.Optional(r.Number({description:"Recent CPU usage divided by the configured CPU limit. Present when both usage and limit are observed."})),memoryUtilization:r.Optional(r.Number({description:"Recent memory usage divided by the configured memory limit. Present when both usage and limit are observed."})),cpuRequestUtilization:r.Optional(r.Number({description:"Recent CPU usage divided by the configured CPU request. Present when both usage and request are observed."})),memoryRequestUtilization:r.Optional(r.Number({description:"Recent memory usage divided by the configured memory request. Present when both usage and request are observed."}))}),Fz=["podName","namespace","cluster","team","env","node","phase","restarts","cpuUsageMilli","cpuUtilization","cpuRequestUtilization","memoryUsageBytes","memoryUtilization","memoryRequestUtilization","createdAt"],nWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/pods`,query:r.Object({...jz,sortBy:r.Optional(r.Enum(Fz,{description:"Field to sort pods by."})),sortDirection:r.Optional(bo)}),paginated:!0,response:r.Array(Ig)}),bg=r.Object({cluster:r.String({description:"Kubernetes cluster name from cluster telemetry."}),teams:r.Optional(r.Array(r.String(),{description:"Team metadata values observed on pods in non-default Kubernetes namespaces on the cluster. Present when team labels or mappings are observed."})),envs:r.Optional(r.Array(r.String(),{description:"Environment metadata values observed on pods in non-default Kubernetes namespaces on the cluster. Present when environment labels or mappings are observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Aggregate recent CPU usage for observed pods in the cluster, excluding default Kubernetes namespaces, in millicores. Present when CPU usage telemetry is observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Aggregate recent memory usage for observed pods in the cluster, excluding default Kubernetes namespaces, in bytes. Present when memory usage telemetry is observed."})),readyNodes:r.Optional(r.Integer({description:"Number of Kubernetes nodes in the cluster that are ready. Present when node readiness telemetry is observed."})),podPhaseCounts:r.Optional(r.Object({Pending:r.Integer({description:"Number of observed pods currently in the Pending phase."}),Running:r.Integer({description:"Number of observed pods currently in the Running phase."}),Succeeded:r.Integer({description:"Number of observed pods currently in the Succeeded phase."}),Failed:r.Integer({description:"Number of observed pods currently in the Failed phase."}),Unknown:r.Integer({description:"Number of observed pods currently in the Unknown phase."})},{description:"Counts of observed pods by Kubernetes phase, excluding default Kubernetes namespaces. Present when pod phase telemetry is observed."}))}),Bz=["cluster","teams","envs","cpuUsageMilli","memoryUsageBytes","readyNodes"],oWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/clusters`,query:r.Object({...JU,teams:sr("Restrict to clusters that host workloads from these team names."),envs:sr("Restrict to clusters that host workloads in these environments."),sortBy:r.Optional(r.Enum(Bz,{description:"Field to sort clusters by."})),sortDirection:r.Optional(bo),...fe}),paginated:!0,response:r.Array(bg)}),Hz=["Ready","NotReady","Unknown"],Sg=r.Object({node:r.String({description:"Kubernetes node name from node telemetry."}),cluster:r.Optional(r.String({description:"Kubernetes cluster name that contains the node. Present when cluster telemetry is observed."})),status:r.Optional(r.Enum(Hz,{description:"Readiness of the node, derived from its Ready condition. Present when node condition telemetry is observed."})),instanceType:r.Optional(r.String({description:"Cloud instance type backing the node (for example `r7g.2xlarge`). Present when host telemetry is observed."})),pods:r.Optional(r.Integer({description:"Number of observed pods scheduled on the node, including pods in internal namespaces since they occupy node capacity. Present when pod telemetry is observed."})),allocatablePods:r.Optional(r.Integer({description:"Maximum number of pods the node can run. Present when node allocatable telemetry is observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Recent CPU usage for the node, in millicores. Reported by the kubelet, so it is absent on nodes that only report cluster-level telemetry."})),cpuAllocatableMilli:r.Optional(r.Number({description:"CPU available to pods on the node, in millicores. Present when node allocatable telemetry is observed."})),cpuUtilization:r.Optional(r.Number({description:"Node CPU usage divided by allocatable CPU. Present when both usage and allocatable telemetry are observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Recent memory usage for the node, in bytes. Reported by the kubelet, so it is absent on nodes that only report cluster-level telemetry."})),memoryAllocatableBytes:r.Optional(r.Number({description:"Memory available to pods on the node, in bytes. Present when node allocatable telemetry is observed."})),memoryUtilization:r.Optional(r.Number({description:"Node memory usage divided by allocatable memory. Present when both usage and allocatable telemetry are observed."}))}),Kz=["node","cluster","status","instanceType","pods","allocatablePods","cpuUsageMilli","cpuAllocatableMilli","cpuUtilization","memoryUsageBytes","memoryAllocatableBytes","memoryUtilization"],iWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/nodes`,query:r.Object({..._g,clusters:sr("Restrict results to these Kubernetes cluster names."),sortBy:r.Optional(r.Enum(Kz,{description:"Field to sort nodes by."})),sortDirection:r.Optional(bo),...fe}),paginated:!0,response:r.Array(Sg)}),Ag=r.Object({namespace:r.String({description:"Kubernetes namespace name from namespace telemetry. Includes namespaces with no observed pods when namespace telemetry is observed."}),cluster:r.Optional(r.String({description:"Kubernetes cluster name that contains the namespace. Present when cluster telemetry is observed."})),teams:r.Optional(r.Array(r.String(),{description:"Team metadata values observed in workloads in the namespace. Present when team labels or mappings are observed."})),envs:r.Optional(r.Array(r.String(),{description:"Environment metadata values observed in workloads in the namespace. Present when environment labels or mappings are observed."})),pods:r.Optional(r.Integer({description:"Number of observed pods in the namespace. Present when pod telemetry is observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Aggregate recent CPU usage for observed pods in the namespace, in millicores. Present when CPU usage telemetry is observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Aggregate recent memory usage for observed pods in the namespace, in bytes. Present when memory usage telemetry is observed."}))}),zz=["namespace","cluster","teams","envs","pods","cpuUsageMilli","memoryUsageBytes"],aWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/namespaces`,query:r.Object({...xs,sortBy:r.Optional(r.Enum(zz,{description:"Field to sort namespaces by."})),sortDirection:r.Optional(bo)}),paginated:!0,response:r.Array(Ag)}),Og=r.Object({deployment:r.String({description:"Kubernetes Deployment name from workload telemetry."}),namespace:r.Optional(r.String({description:"Kubernetes namespace that contains the Deployment. Present when namespace telemetry is observed."})),cluster:r.Optional(r.String({description:"Kubernetes cluster name that contains the Deployment. Present when cluster telemetry is observed."})),team:r.Optional(r.String({description:"Team metadata associated with the Deployment. Present when a team label or mapping is observed."})),env:r.Optional(r.String({description:"Environment metadata associated with the Deployment. Present when an environment label or mapping is observed."})),pods:r.Optional(r.Integer({description:"Number of observed pods associated with the Deployment. Present when pod telemetry and workload attributes are observed."})),availableReplicas:r.Optional(r.Integer({description:"Number of available Deployment replicas from Deployment status telemetry. Present when deployment status is observed."})),desiredReplicas:r.Optional(r.Integer({description:"Desired replica count configured for the Deployment. Present when Deployment spec telemetry is observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Recent aggregate CPU usage for observed Deployment pods, in millicores. Present when CPU usage telemetry is observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Recent aggregate memory usage for observed Deployment pods, in bytes. Present when memory usage telemetry is observed."}))}),Yz=["deployment","namespace","cluster","team","env","pods","availableReplicas","cpuUsageMilli","memoryUsageBytes"],sWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/deployments`,query:r.Object({...xs,sortBy:r.Optional(r.Enum(Yz,{description:"Field to sort deployments by."})),sortDirection:r.Optional(bo)}),paginated:!0,response:r.Array(Og)}),xg=r.Object({statefulSet:r.String({description:"Kubernetes StatefulSet name from workload telemetry."}),namespace:r.Optional(r.String({description:"Kubernetes namespace that contains the StatefulSet. Present when namespace telemetry is observed."})),cluster:r.Optional(r.String({description:"Kubernetes cluster name that contains the StatefulSet. Present when cluster telemetry is observed."})),team:r.Optional(r.String({description:"Team metadata associated with the StatefulSet. Present when a team label or mapping is observed."})),env:r.Optional(r.String({description:"Environment metadata associated with the StatefulSet. Present when an environment label or mapping is observed."})),pods:r.Optional(r.Integer({description:"Number of observed pods associated with the StatefulSet. Present when pod telemetry and workload attributes are observed."})),readyReplicas:r.Optional(r.Integer({description:"Number of ready StatefulSet replicas from StatefulSet status telemetry. Present when StatefulSet status is observed."})),desiredReplicas:r.Optional(r.Integer({description:"Desired replica count configured for the StatefulSet. Present when StatefulSet spec telemetry is observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Recent aggregate CPU usage for observed StatefulSet pods, in millicores. Present when CPU usage telemetry is observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Recent aggregate memory usage for observed StatefulSet pods, in bytes. Present when memory usage telemetry is observed."}))}),Vz=["statefulSet","namespace","cluster","team","env","pods","cpuUsageMilli","memoryUsageBytes"],cWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/statefulsets`,query:r.Object({...xs,sortBy:r.Optional(r.Enum(Vz,{description:"Field to sort StatefulSets by."})),sortDirection:r.Optional(bo)}),paginated:!0,response:r.Array(xg)}),Rg=r.Object({daemonSet:r.String({description:"Kubernetes DaemonSet name from workload telemetry."}),namespace:r.Optional(r.String({description:"Kubernetes namespace that contains the DaemonSet. Present when namespace telemetry is observed."})),cluster:r.Optional(r.String({description:"Kubernetes cluster name that contains the DaemonSet. Present when cluster telemetry is observed."})),team:r.Optional(r.String({description:"Team metadata associated with the DaemonSet. Present when a team label or mapping is observed."})),env:r.Optional(r.String({description:"Environment metadata associated with the DaemonSet. Present when an environment label or mapping is observed."})),pods:r.Optional(r.Integer({description:"Number of observed pods associated with the DaemonSet. Present when pod telemetry and workload attributes are observed."})),readyNodes:r.Optional(r.Integer({description:"Number of eligible nodes with a ready DaemonSet pod. Present when DaemonSet status telemetry is observed."})),desiredNodes:r.Optional(r.Integer({description:"Number of eligible nodes where the DaemonSet should run a pod. Present when DaemonSet status telemetry is observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Recent aggregate CPU usage for observed DaemonSet pods, in millicores. Present when CPU usage telemetry is observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Recent aggregate memory usage for observed DaemonSet pods, in bytes. Present when memory usage telemetry is observed."}))}),Qz=["daemonSet","namespace","cluster","team","env","pods","readyNodes","cpuUsageMilli","memoryUsageBytes"],pWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/daemonsets`,query:r.Object({...xs,sortBy:r.Optional(r.Enum(Qz,{description:"Field to sort DaemonSets by."})),sortDirection:r.Optional(bo)}),paginated:!0,response:r.Array(Rg)}),Cg=r.Object({overview:r.Object({...ow.properties,workload:r.Optional(nw)},{description:"Pod identity, status, and owning workload, derived from recent pod metrics."}),healthMetrics:r.Object({cpu:r.Object({usage:r.String({description:"Metric name callers can use to query pod CPU usage. This is not the current CPU value."}),limit:r.String({description:"Metric name callers can use to query configured container CPU limits for the pod. This is not the current CPU limit value."}),request:r.String({description:"Metric name callers can use to query configured container CPU requests for the pod. This is not the current CPU request value."})},{description:"Metric names for pod CPU usage and for configured container CPU limits and requests."}),memory:r.Object({usage:r.String({description:"Metric name callers can use to query pod memory usage. This is not the current memory value."}),limit:r.String({description:"Metric name callers can use to query configured container memory limits for the pod. This is not the current memory limit value."}),request:r.String({description:"Metric name callers can use to query configured container memory requests for the pod. This is not the current memory request value."})},{description:"Metric names for pod memory usage and for configured container memory limits and requests."})},{description:"Metric names callers can use to query pod CPU and memory telemetry. These are fixed metric identifiers, not current values."}),searchFilters:r.Object({logs:r.String({description:"TQL log search filter scoped to this pod. Built from cluster, namespace, and pod identifiers."}),traces:r.String({description:"TQL trace search filter scoped to this pod. Built from cluster, namespace, and pod identifiers."})},{description:"TQL filters scoped to this pod, ready to use as the query for log and trace search."})}),iw=r.Object({clusterId:r.Optional(u({allowEmpty:!1})),k8sCluster:u({allowEmpty:!1}),k8sNamespace:u({allowEmpty:!1}),podName:u({allowEmpty:!1})}),uWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/pod-details`,query:iw,response:Cg}),Pg=r.Object({configuration:r.Optional(r.Object({spec:r.Record(r.String(),r.Unknown(),{description:"Kubernetes PodSpec from the latest observed pod manifest. Fields outside `object.spec` are stripped."}),lastObservedAt:A({description:"Timestamp when Tsuga last observed the pod manifest used for configuration."})},{description:"Pod configuration from the latest observed pod manifest. Present when a pod manifest log is found for the pod."})),labels:r.Record(r.String(),r.String(),{description:"Kubernetes labels on the pod from the latest observed pod manifest. Key-value strings."}),annotations:r.Record(r.String(),r.String(),{description:"Kubernetes annotations on the pod from the latest observed pod manifest. Key-value strings."}),deletedAt:r.Optional(A({description:"Timestamp when Tsuga last observed the pod deletion event. Present when the latest observed pod event is deleted."}))}),lWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/pod-manifest`,query:iw,response:Pg}),Ug=r.Object({podName:r.String({description:"Name of a pod instance associated with the workload. Resolved from recent pod usage telemetry and workload attributes."}),podUid:r.Optional(r.String({description:"Kubernetes UID for the pod replica. Present when UID telemetry is observed."})),cpuUsageMilli:r.Optional(r.Number({description:"Recent CPU usage for the pod replica, in millicores. Present when CPU usage telemetry is observed."})),memoryUsageBytes:r.Optional(r.Number({description:"Recent memory usage for the pod replica, in bytes. Present when memory usage telemetry is observed."}))},{description:"A single pod instance with recent CPU or memory telemetry for the workload, resolved from pod usage telemetry and workload attributes."}),wg=r.Object({overview:r.Object({deploymentName:r.String({description:"Kubernetes Deployment name for this detail response."}),namespace:r.Optional(r.String({description:"Kubernetes namespace for this detail response. Present when any deployment signal is found."})),cluster:r.Optional(r.String({description:"Kubernetes cluster name for this detail response. Present when any deployment signal is found."})),team:r.Optional(r.String({description:"Team metadata from the Deployment available-replica metric. Present when the metric includes team metadata."})),env:r.Optional(r.String({description:"Environment metadata from the Deployment available-replica metric. Present when the metric includes environment metadata."})),availableReplicas:r.Optional(r.Integer({description:"Number of available Deployment replicas from Deployment status telemetry. Present when deployment status is observed."})),desiredReplicas:r.Optional(r.Integer({description:"Desired replica count configured for the Deployment. Present when Deployment spec telemetry is observed."})),latestRevisionAt:r.Optional(A({description:"Latest ReplicaSet metadata.creationTimestamp observed for the Deployment. Present when ReplicaSet object telemetry is observed."}))}),podReplicas:r.Array(Ug,{description:"Pod instances with recent CPU or memory telemetry for the Deployment. Tsuga builds this list from pod usage telemetry and workload attributes. Empty when no matching pod usage telemetry is observed."}),revisions:r.Array(r.Object({replicaSetName:r.String({description:"ReplicaSet name for a Deployment revision from workload telemetry."}),revision:r.Integer({description:"Deployment revision number from ReplicaSet annotations. Integer greater than or equal to zero."}),firstSeen:r.Optional(A({description:"ReplicaSet metadata.creationTimestamp from the latest observed ReplicaSet object. Present when creation time is observed."})),observedGeneration:r.Optional(r.Integer({description:"Latest generation observed for the ReplicaSet revision. Present when generation telemetry is observed."})),readyReplicas:r.Optional(r.Integer({description:"Number of ready replicas for the ReplicaSet revision. Present when ReplicaSet status telemetry is observed."})),replicas:r.Optional(r.Integer({description:"Total replica count for the ReplicaSet revision. Present when ReplicaSet status telemetry is observed."})),logsSearchFilter:r.String({description:"TQL log search filter scoped to this ReplicaSet revision. Built from cluster, namespace, and ReplicaSet identifiers."})}),{description:"Deployment rollout revisions from recent ReplicaSet object telemetry. Includes the latest observed event per ReplicaSet, excludes ReplicaSets whose latest observed spec.replicas is 0, and returns up to 8 revisions sorted by revision number descending."})}),mWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/deployment-details`,query:r.Object({clusterId:r.Optional(u({allowEmpty:!1})),k8sCluster:u({allowEmpty:!1}),k8sNamespace:u({allowEmpty:!1}),deploymentName:u({allowEmpty:!1})}),response:wg}),Wz=r.Object({overview:r.Object({statefulSetName:r.String(),namespace:r.Optional(r.String()),cluster:r.Optional(r.String()),team:r.Optional(r.String()),env:r.Optional(r.String()),readyReplicas:r.Optional(r.Integer()),desiredReplicas:r.Optional(r.Integer()),latestRevisionAt:r.Optional(A())}),podReplicas:r.Array(Ug,{description:"Pod instances with recent CPU or memory telemetry for the StatefulSet. Tsuga builds this list from pod usage telemetry and workload attributes. Empty when no matching pod usage telemetry is observed."}),revisions:r.Array(r.Object({revisionName:r.String(),firstSeen:r.Optional(A())}))}),dWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/statefulset-details`,query:r.Object({clusterId:r.Optional(u({allowEmpty:!1})),k8sCluster:u({allowEmpty:!1}),k8sNamespace:u({allowEmpty:!1}),statefulSetName:u({allowEmpty:!1})}),response:Wz}),Zz=r.Object({overview:r.Object({daemonSetName:r.String(),namespace:r.Optional(r.String()),cluster:r.Optional(r.String()),team:r.Optional(r.String()),env:r.Optional(r.String()),readyNodes:r.Optional(r.Integer()),desiredNodes:r.Optional(r.Integer()),latestRevisionAt:r.Optional(A())}),podReplicas:r.Array(Ug,{description:"Pod instances with recent CPU or memory telemetry for the DaemonSet. Tsuga builds this list from pod usage telemetry and workload attributes. Empty when no matching pod usage telemetry is observed."}),revisions:r.Array(r.Object({observedGeneration:r.Integer(),firstSeen:r.Optional(A())}))}),fWe=d({tags:["kubernetes-explorer"],method:"GET",url:`${Xt}/daemonset-details`,query:r.Object({clusterId:r.Optional(u({allowEmpty:!1})),k8sCluster:u({allowEmpty:!1}),k8sNamespace:u({allowEmpty:!1}),daemonSetName:u({allowEmpty:!1})}),response:Zz});var Rr=`/${"v1"}/kubernetes-explorer`,aw=r.Pick(Ig,["podName","namespace","cluster","team","env","node","phase","readyContainers","totalContainers","restarts","createdAt","workload","cpuUsageMilli","cpuLimitMilli","memoryUsageBytes","memoryLimitBytes","cpuUtilization","memoryUtilization"],{description:"A Kubernetes pod with its current phase, owning workload, and resource usage."}),Xz={podName:"api-gateway-7d9f8c6b5-2xk4p",namespace:"production",cluster:"prod-us-east",team:"platform",env:"production",node:"ip-10-0-1-23.ec2.internal",phase:"Running",readyContainers:1,totalContainers:1,restarts:0,createdAt:"2024-01-15T12:34:56.000Z",workload:{kind:"deployment",name:"api-gateway"},cpuUsageMilli:125,cpuLimitMilli:500,memoryUsageBytes:134217728,memoryLimitBytes:536870912,cpuUtilization:.25,memoryUtilization:.25};Object.assign(aw,{examples:[Xz]});var sw=r.Pick(bg,["cluster","teams","envs","cpuUsageMilli","memoryUsageBytes","readyNodes","podPhaseCounts"],{description:"A Kubernetes cluster with aggregate resource usage, node readiness, and pod phase counts."}),Jz={cluster:"prod-us-east",teams:["platform","payments"],envs:["production"],cpuUsageMilli:4200,memoryUsageBytes:8589934592,readyNodes:6,podPhaseCounts:{Pending:1,Running:42,Succeeded:3,Failed:0,Unknown:0}};Object.assign(sw,{examples:[Jz]});var cw=r.Pick(Ag,["namespace","cluster","teams","envs","pods","cpuUsageMilli","memoryUsageBytes"],{description:"A Kubernetes namespace with pod count and aggregate resource usage."}),e4={namespace:"production",cluster:"prod-us-east",teams:["platform"],envs:["production"],pods:24,cpuUsageMilli:1800,memoryUsageBytes:3221225472};Object.assign(cw,{examples:[e4]});var pw=r.Pick(Sg,["node","cluster","status","instanceType","pods","allocatablePods","cpuUsageMilli","cpuAllocatableMilli","cpuUtilization","memoryUsageBytes","memoryAllocatableBytes","memoryUtilization"],{description:"A Kubernetes node with its readiness, instance type, and usage against what it can allocate to pods."}),t4={node:"ip-10-0-1-23.ec2.internal",cluster:"prod-us-east",status:"Ready",instanceType:"r7g.2xlarge",pods:25,allocatablePods:234,cpuUsageMilli:4e3,cpuAllocatableMilli:8e3,cpuUtilization:.5,memoryUsageBytes:4e9,memoryAllocatableBytes:16e9,memoryUtilization:.25};Object.assign(pw,{examples:[t4]});var uw=r.Pick(Og,["deployment","namespace","cluster","team","env","pods","availableReplicas","desiredReplicas","cpuUsageMilli","memoryUsageBytes"],{description:"A Kubernetes deployment with replica counts and aggregate resource usage."}),r4={deployment:"api-gateway",namespace:"production",cluster:"prod-us-east",team:"platform",env:"production",pods:3,availableReplicas:3,desiredReplicas:3,cpuUsageMilli:375,memoryUsageBytes:402653184};Object.assign(uw,{examples:[r4]});var lw=r.Pick(xg,["statefulSet","namespace","cluster","team","env","pods","readyReplicas","desiredReplicas","cpuUsageMilli","memoryUsageBytes"],{description:"A Kubernetes StatefulSet with replica counts and aggregate resource usage."}),n4={statefulSet:"postgres",namespace:"production",cluster:"prod-us-east",team:"platform",env:"production",pods:3,readyReplicas:3,desiredReplicas:3,cpuUsageMilli:900,memoryUsageBytes:2147483648};Object.assign(lw,{examples:[n4]});var mw=r.Pick(Rg,["daemonSet","namespace","cluster","team","env","pods","readyNodes","desiredNodes","cpuUsageMilli","memoryUsageBytes"],{description:"A Kubernetes DaemonSet with eligible-node readiness and aggregate resource usage."}),o4={daemonSet:"otel-collector",namespace:"observability",cluster:"prod-us-east",team:"platform",env:"production",pods:6,readyNodes:6,desiredNodes:6,cpuUsageMilli:300,memoryUsageBytes:805306368};Object.assign(mw,{examples:[o4]});var dw=r.Pick(Cg,["overview","healthMetrics","searchFilters"],{description:"Metrics-derived information for a single Kubernetes pod: status, owning workload, CPU/memory metric identifiers, and log/trace filters."}),i4={overview:{podName:"api-gateway-7d9f8c6b5-2xk4p",namespace:"production",cluster:"prod-us-east",team:"platform",env:"production",node:"ip-10-0-1-23.ec2.internal",phase:"Running",readyContainers:1,totalContainers:1,restarts:0,createdAt:"2024-01-15T12:34:56.000Z",workload:{kind:"deployment",name:"api-gateway"}},healthMetrics:{cpu:{usage:"k8s.pod.cpu.usage",limit:"k8s.container.cpu_limit",request:"k8s.container.cpu_request"},memory:{usage:"k8s.pod.memory.usage",limit:"k8s.container.memory_limit",request:"k8s.container.memory_request"}},searchFilters:{logs:'context.k8s.cluster.name:"prod-us-east" AND context.k8s.namespace.name:"production" AND context.k8s.pod.name:"api-gateway-7d9f8c6b5-2xk4p"',traces:'context.k8s.cluster.name:"prod-us-east" AND context.k8s.namespace.name:"production" AND context.k8s.pod.name:"api-gateway-7d9f8c6b5-2xk4p"'}};Object.assign(dw,{examples:[i4]});var fw=r.Pick(Pg,["configuration","labels","annotations","deletedAt"],{description:"Manifest-derived details for a single Kubernetes pod: the pod manifest spec, labels, and annotations from the pod's most recently observed manifest."}),a4={configuration:{spec:{restartPolicy:"Always",serviceAccountName:"api-gateway"},lastObservedAt:"2024-01-15T12:30:00.000Z"},labels:{app:"api-gateway","pod-template-hash":"7d9f8c6b5"},annotations:{"prometheus.io/scrape":"true"}};Object.assign(fw,{examples:[a4]});var gw=r.Pick(wg,["overview","podReplicas","revisions"],{description:"Detailed information for a single Kubernetes deployment: replica status, backing pods, and rollout revisions."}),s4={overview:{deploymentName:"api-gateway",namespace:"production",cluster:"prod-us-east",team:"platform",env:"production",availableReplicas:3,desiredReplicas:3,latestRevisionAt:"2024-01-15T12:00:00.000Z"},podReplicas:[{podName:"api-gateway-7d9f8c6b5-2xk4p",podUid:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",cpuUsageMilli:125,memoryUsageBytes:134217728}],revisions:[{replicaSetName:"api-gateway-7d9f8c6b5",revision:7,firstSeen:"2024-01-15T12:00:00.000Z",observedGeneration:7,readyReplicas:3,replicas:3,logsSearchFilter:'context.k8s.cluster.name:"prod-us-east" context.k8s.namespace.name:"production" context.k8s.replicaset.name:"api-gateway-7d9f8c6b5"'}]};Object.assign(gw,{examples:[s4]});var hw=r.Object({clusterId:r.Optional(u({allowEmpty:!1,description:"Tsuga cluster ID to target. Tsuga assigns it when a cluster is connected to the organization. Optional for single-cluster organizations and required for organizations with multiple clusters to scope the request to one cluster."}))}),ki=r.Pick(ew,["clusterId","search"]),c4=r.Pick(tw,["clusterId","search"]),yw=d({description:"Lists Kubernetes pods observed across the organization with their current phase, owning workload, and resource usage.",operationId:"listKubernetesPods",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/pods`,query:ki,response:r.Array(aw)}),Tw=d({description:"Lists Kubernetes clusters observed across the organization with aggregate resource usage, node readiness, and pod phase counts.",operationId:"listKubernetesClusters",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/clusters`,query:c4,response:r.Array(sw)}),Ew=d({description:"Lists Kubernetes namespaces observed across the organization with pod counts and aggregate resource usage.",operationId:"listKubernetesNamespaces",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/namespaces`,query:ki,response:r.Array(cw)}),_w=d({description:"Lists Kubernetes nodes observed across the organization with their readiness, instance type, and resource usage against allocatable capacity.",operationId:"listKubernetesNodes",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/nodes`,query:ki,response:r.Array(pw)}),Iw=d({description:"Lists Kubernetes deployments observed across the organization with replica counts and aggregate resource usage.",operationId:"listKubernetesDeployments",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/deployments`,query:ki,response:r.Array(uw)}),bw=d({description:"Lists Kubernetes StatefulSets observed across the organization with replica counts and aggregate resource usage.",operationId:"listKubernetesStatefulSets",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/statefulsets`,query:ki,response:r.Array(lw)}),Sw=d({description:"Lists Kubernetes DaemonSets observed across the organization with eligible-node readiness and aggregate resource usage.",operationId:"listKubernetesDaemonSets",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/daemonsets`,query:ki,response:r.Array(mw)}),Aw=r.Object({...hw.properties,k8sCluster:u({allowEmpty:!1,description:"Kubernetes cluster name that contains the pod. From cluster telemetry. Required to identify the pod because pod names are only unique within a namespace and cluster."}),k8sNamespace:u({allowEmpty:!1,description:"Kubernetes namespace that contains the pod. From pod metadata. Required to identify the pod because pod names are only unique within a namespace and cluster."}),podName:u({allowEmpty:!1,description:"Kubernetes pod name to retrieve. Set when the pod is created. Required to fetch pod details for the selected cluster and namespace."})}),Ow=d({description:"Retrieves metrics-derived information for a single Kubernetes pod: status, owning workload, CPU/memory metric identifiers, and ready-to-use log and trace filters. Manifest configuration, labels, and annotations are served by the pod-manifest endpoint.",operationId:"getKubernetesPodDetails",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/pod-details`,query:Aw,response:dw}),xw=d({description:"Retrieves the manifest-derived details for a single Kubernetes pod: the pod manifest spec, labels, and annotations from the pod's most recently observed manifest.",operationId:"getKubernetesPodManifest",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/pod-manifest`,query:Aw,response:fw}),Rw=d({description:"Retrieves detailed information for a single Kubernetes deployment: replica status, backing pods, and rollout revisions with ready-to-use log filters.",operationId:"getKubernetesDeploymentDetails",tags:["public","kubernetes-explorer"],method:"GET",url:`${Rr}/deployment-details`,query:r.Object({...hw.properties,k8sCluster:u({allowEmpty:!1,description:"Kubernetes cluster name that contains the Deployment. From cluster telemetry. Required to identify the Deployment because names are only unique within a namespace and cluster."}),k8sNamespace:u({allowEmpty:!1,description:"Kubernetes namespace that contains the Deployment. From workload metadata. Required to identify the Deployment because names are only unique within a namespace and cluster."}),deploymentName:u({allowEmpty:!1,description:"Kubernetes Deployment name to retrieve. From workload telemetry. Required to fetch deployment details for the selected cluster and namespace."})}),response:gw});var p4="clusterId";function Cw(e,t,n){let o=t.query.properties??{},i=Object.keys(o).filter(a=>a!==p4);for(let a of i){let c=a.replace(/([A-Z])/g,"-$1").toLowerCase(),l=c.replace(/-/g,"_").toUpperCase(),m=o[a]?.description??"";n?e.requiredOption(`--${c} <${l}>`,m):e.option(`--${c} <${l}>`,m)}return i}function So(e,t,n,o){let i=e.command(t).description(n.description??`List Kubernetes ${t}`),a=Cw(i,n,!1);i.action(async c=>{let l={};for(let m of a)c[m]!==void 0&&(l[m]=c[m]);ee(Object.keys(l).length>0?await o()(n,{query:l}):await o()(n))})}function vg(e,t,n,o){let i=e.command(t).description(n.description??`Get Kubernetes ${t}`),a=Cw(i,n,!0);i.action(async c=>{let l={};for(let m of a)l[m]=c[m];ee(await o()(n,{query:l}))})}function Pw(e,t){let n=e.command("kubernetes").description("Explore Kubernetes resources observed across the organization");So(n,"pods",yw,t),So(n,"clusters",Tw,t),So(n,"namespaces",Ew,t),So(n,"nodes",_w,t),So(n,"deployments",Iw,t),So(n,"statefulsets",bw,t),So(n,"daemonsets",Sw,t),vg(n,"pod-details",Ow,t),vg(n,"pod-manifest",xw,t),vg(n,"deployment-details",Rw,t)}var u4=r.Union([r.Literal("scalar"),r.Literal("timeseries")]),l4="/v0/promql",Wu=r.Object({query:u({type:"long",allowEmpty:!1,description:"PromQL expression to evaluate."}),timeRange:ui,step:u({allowEmpty:!1,description:"Evaluation step interval (e.g. `1m`, `5m`, `1h`). Must be a valid Prometheus duration string."}),returnType:r.Optional(u4),executionOptions:yd,shouldStreamResults:r.Optional(r.Boolean()),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster to target. Defaults to the first cluster created in the organization when omitted."}))}),m4={query:'rate({"otel.trace.span_processor.spans"}[5m])',timeRange:{from:17822015e5,to:17822034e5},step:"1m",executionOptions:{parallelism:1,engine:"q"},clusterId:"cluster-abc"};Object.assign(Wu,{examples:[m4]});var wWe=d({tags:["promql"],url:l4,method:"POST",body:Wu,response:tu});var Uw=`/${"v1"}/aggregation`,ww=r.Object({id:r.String({description:"Result identifier. Query results use `q1`, `q2`, and so on; formula results use `formula`."}),group:r.Record(r.String(),r.Union([r.String(),r.Number()]),{description:"Group-by field values for this result. Empty when no group-by is requested."})}),vw=r.Object({results:r.Array(r.Object({...ww.properties,value:r.Number({description:"Aggregated value for this query or formula and group, over the full time range."})},{title:"ScalarResult"}),{description:"One aggregated value per query or formula and group."})},{$id:"ScalarAggregationResponse",title:"ScalarAggregationResponse",description:"Scalar aggregation response with one value per query or formula and group."}),d4={results:[{id:"q1",group:{host:"server-1"},value:123.45}]};Object.assign(vw,{examples:[d4]});var Zu=r.Object({series:r.Array(r.Object({...ww.properties,points:r.Array(r.Object({timestamp:r.Integer({description:"Unix timestamp in milliseconds for this point, spaced by `aggregationWindow`."}),value:r.Number({description:"Aggregated value at this timestamp."})}),{description:"Ordered data points for this query or formula and group."})},{title:"Series"}),{description:"One time series per query or formula and group."})},{$id:"TimeseriesAggregationResponse",title:"TimeseriesAggregationResponse",description:"Timeseries aggregation response with timestamped points over time."}),f4={series:[{id:"q1",group:{host:"server-1"},points:[{timestamp:16094592e5,value:123.45},{timestamp:160945926e4,value:456.78}]}]};Object.assign(Zu,{examples:[f4]});var g4=r.Omit(os.items,["fill"],{title:"AggregationQuery",description:"Aggregation query. Omit `filter` for an unfiltered query and omit `functions` when no post-processing is needed."}),h4=r.Optional(Fr),Nw={timeRange:bt,queries:r.Array(g4,{maxItems:ns,description:`Aggregations that may be combined together in the same query. Each item is referenced from \`formula\` as q1, q2, and so on, in submission order. Limited to ${ns} items. For dataSource "metrics", each aggregate's \`field\` is the metric name, not an attribute; to count distinct values of an attribute use unique-count with field "<metricName>.context.<attribute>" (e.g. "system.cpu.utilization.context.host.name").`}),groupBy:h4,dataSource:px,formula:r.Optional(co)},Lw=r.Object({clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))}),kw=r.Object(Nw,{description:"Scalar aggregation request. Provide a time range, one or more queries, a telemetry data source, and optional grouping or formula. Omit `groupBy` for ungrouped results. Send `clusterId` as a query parameter, not in the JSON body."}),y4={timeRange:{from:1782201500,to:1782203400},dataSource:"logs",queries:[{aggregate:{type:"count"},filter:"context.service.name:checkout"}],groupBy:[{fields:["level"],limit:5}]};Object.assign(kw,{examples:[y4]});var Mw=d({description:"Runs one or more aggregation queries over logs, metrics, or traces and returns scalar values. Use optional group-by and formula fields to compute grouped or derived results. See [Analytics queries](/documentation/visualize/analytics/queries).",operationId:"aggregateScalar",tags:["public","aggregation"],url:`${Uw}/multi-query/scalar`,method:"POST",body:kw,query:Lw,response:vw}),Dw=r.Object({...Nw,aggregationWindow:u({description:"Time bucket size for timeseries aggregation, such as `10s`, `1m`, or `1h`."})},{description:"Timeseries aggregation request. Provide a time range, bucket size, one or more queries, a telemetry data source, and optional grouping or formula. Omit `groupBy` for ungrouped series. Send `clusterId` as a query parameter, not in the JSON body."}),T4={timeRange:{from:1782201500,to:1782203400},aggregationWindow:"1m",dataSource:"logs",queries:[{aggregate:{type:"count"},filter:"context.service.name:checkout"}],groupBy:[{fields:["level"],limit:5}]};Object.assign(Dw,{examples:[T4]});var Gw=d({description:"Runs one or more aggregation queries over logs, metrics, or traces and returns timestamped series. Use `aggregationWindow` to choose the time bucket size. See [Analytics queries](/documentation/visualize/analytics/queries).",operationId:"aggregateTimeseries",tags:["public","aggregation"],url:`${Uw}/multi-query/timeseries`,method:"POST",body:Dw,query:Lw,response:Zu});var E4=`/${"v1"}/promql`,_4=r.Object({...r.Pick(Wu,["query","step"]).properties,timeRange:bt},{description:"PromQL range-query request. Send clusterId as a query parameter, not in this JSON body.",examples:[{query:'sum by ("context.service.name") (sum_over_time({"traces.span.metrics.calls", "span.kind"="SPAN_KIND_SERVER"}[5m]))',timeRange:{from:1782201500,to:1782203400},step:"1m"}]}),I4=r.Object({clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to query. Set by the client as the clusterId query parameter, not in the JSON body. Required when the organization has multiple clusters; omit only for single-cluster organizations. Unknown cluster IDs return 404."}))}),$w=d({description:"Runs a PromQL range query over Tsuga metric data and returns timeseries results. Authenticate with a bearer operation API key or OAuth access token that can read metrics. Send clusterId as a query parameter; multi-cluster organizations must provide it. See [How to write PromQL queries](/documentation/visualize/guides/how-to-write-promql-queries) for query syntax and examples.",operationId:"queryPromql",tags:["public","promql"],url:E4,method:"POST",body:_4,query:I4,response:Zu});function jw(e,t){let n=e.command("promql").description("Run PromQL queries over metric data");Zr(n,"query","Run a PromQL range query over metric data",$w,t)}var Di="/v0/dashboard-folders",Gi=r.Object({id:r.String({description:"Tsuga-generated dashboard folder ID assigned when the folder is created. Use it as dashboard `folderId` or child-folder `parentFolderId`."}),name:r.String({description:"Display name of the dashboard folder. Set by the caller on create or update."}),owner:r.String({description:"ID of the team that owns the dashboard folder. Set by the caller on create or update and used for folder access control."}),parentFolderId:r.Optional(r.String({description:"ID of the top-level parent folder when this folder is nested. Set by the caller on create or update. Returned only for child folders; omitted for top-level folders."})),tags:De,creator:r.Optional(pe),updater:r.Optional(pe),createdAt:A(),updatedAt:A()},{title:"DashboardFolder"}),Ng=r.Object({...Gi.properties,dashboardCount:r.Number({description:"Number of dashboards directly assigned to this folder that the caller can read. Returned only by folder list responses; callers without dashboard read access see 0."})}),Xu=r.Object({name:u({allowEmpty:!1,description:"Display name of the dashboard folder. Required and non-empty."}),owner:u({allowEmpty:!1,description:"ID of the team that owns the dashboard folder. Required and used for folder access control."}),parentFolderId:r.Optional(r.Union([r.Null(),u({allowEmpty:!1})],{description:"ID of the top-level folder to nest this folder under. Omit on create or pass null to create a top-level folder; omit on update to keep the current parent; pass null on update to move the folder to top level. Non-null values must name a readable top-level folder. Folders can be nested at most two levels deep."})),tags:Xe}),Ju=r.Partial(r.Object({owners:_e(u({allowEmpty:!1}),{description:"Restrict results to dashboard folders owned by any of these team IDs",maxItems:50}),searchQuery:r.Object({value:u({allowEmpty:!1,description:"Substring matched case-insensitively against dashboard folder names or folder IDs. Omit the whole `searchQuery` filter to skip text filtering."}),exclude:r.Optional(r.Boolean({description:"If true, exclude dashboard folders matching this value instead of including them"}))},{description:"Text filter for dashboard folder names or IDs. Optional; `exclude: true` returns folders whose name and ID do not match the substring."}),tags:_e(Bt.items,{description:"Restrict results to dashboard folders that have at least one of the listed key/value tags",maxItems:50}),parentFolderId:r.Union([r.Null(),u({allowEmpty:!1})],{description:"Parent folder filter for dashboard folder query results. Optional; pass a folder ID to return the child folders nested directly under it, or null to return only top-level folders. Omit to return all folders."})},{description:"Optional filters applied to narrow the returned dashboard folders"})),Mi={IS_FAVORITE:"isFavorite",OWNER:"owner",TAGS:"tags",DASHBOARD_COUNT:"dashboardCount",UPDATED_AT:"updatedAt",NAME:"name"},Lg=[Mi.OWNER,Mi.TAGS,Mi.DASHBOARD_COUNT,Mi.UPDATED_AT,Mi.NAME],b4=r.Partial(r.Object({...fe,filters:Ju,sort:r.Object({by:r.Enum([...Lg,Mi.IS_FAVORITE],{description:"Field to sort the returned dashboard folders by"}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned dashboard folders"})})),n7e=d({tags:["dashboard-folders"],url:`${Di}/query`,method:"POST",paginated:!0,body:b4,response:r.Array(Ng)}),o7e=d({tags:["dashboard-folders"],url:`${Di}/:id`,method:"GET",params:r.Object({id:u()}),response:Gi}),i7e=d({tags:["dashboard-folders"],url:Di,method:"POST",body:Xu,response:Gi}),a7e=d({tags:["dashboard-folders"],url:`${Di}/:id`,method:"PUT",params:r.Object({id:u()}),body:Xu,response:Gi}),s7e=d({tags:["dashboard-folders"],url:`${Di}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),c7e=d({tags:["dashboard-folders"],url:`${Di}/tags/query`,method:"POST",body:r.Object({filters:r.Optional(r.Omit(Ju,["tags"]))}),response:Ft});var Rs=`/${"v1"}/dashboard-folders`,el=r.Pick(Gi,["id","name","owner","parentFolderId","tags"],{$id:"DashboardFolder",description:"Folder used to organize dashboards into a two-level hierarchy"}),qw={id:"123-456-abc",name:"Platform",owner:"team-123-abc",tags:[{key:"team",value:"platform"}]};Object.assign(el,{examples:[qw]});var Fw=r.Pick(Ng,["id","name","owner","parentFolderId","tags","dashboardCount"],{$id:"DashboardFolderWithDashboardCount",description:"Folder used to organize dashboards into a two-level hierarchy, including the number of readable dashboards it directly contains."}),S4={...qw,dashboardCount:10};Object.assign(Fw,{examples:[S4]});var kg=r.Pick(Xu,["name","owner","parentFolderId","tags"],{description:"Dashboard folder create or update request. Provide a name, owner team, optional parent folder, and optional tags."}),A4={name:"Platform",owner:"team-123-abc",parentFolderId:null,tags:[{key:"team",value:"platform"}]};Object.assign(kg,{examples:[A4]});var O4=r.Object({by:r.Enum(Lg,{description:"Field to sort the returned dashboard folders by: `owner` sorts by owning team name, `tags` sorts by tag key/value pairs, `dashboardCount` sorts by the number of readable dashboards directly in the folder, `updatedAt` sorts by last-updated timestamp, and `name` sorts alphabetically by folder name."}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned dashboard folders"}),Bw=r.Object({...Ze,filters:r.Optional(r.Pick(Ju,["owners","searchQuery","tags","parentFolderId"])),sort:r.Optional(O4)},{description:"Dashboard folder query request. Use filters, sorting, limit, and offset to page through visible dashboard folders."}),x4={filters:{owners:{values:["team-123-abc"]},searchQuery:{value:"Platform"},tags:{values:[{key:"team",value:"platform"}]}},sort:{by:"name",direction:"asc"},limit:10,offset:0};Object.assign(Bw,{examples:[x4]});var Hw=d({description:"Queries dashboard folders visible to the authenticated operation key. Returns all folders unless the `parentFolderId` filter is set: pass a folder ID to select the children of that folder, or null to return only top-level folders. Results are ordered by most recently updated folder first unless `sort` is set, and include the number of readable dashboards directly assigned to each folder. Use filters to narrow by owning team, name or ID substring, or tags.",operationId:"queryDashboardFolders",tags:["dashboard-folders"],url:`${Rs}/query`,method:"POST",paginated:!0,body:Bw,response:r.Array(Fw)}),Kw=d({description:"Retrieves one dashboard folder by ID.",operationId:"getDashboardFolder",tags:["dashboard-folders"],url:`${Rs}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the dashboard folder to retrieve. Use the `id` returned by folder list, get, create, or update responses."})}),response:el}),zw=d({description:"Creates a dashboard folder owned by the specified team. To create a child folder, set `parentFolderId` to a readable top-level folder.",operationId:"createDashboardFolder",tags:["dashboard-folders"],url:Rs,method:"POST",body:kg,response:el}),Yw=d({description:"Updates an existing dashboard folder by ID. Send the folder name, owner, tags, and parent relationship; omit `parentFolderId` to keep the current parent or send null to move the folder to top level.",operationId:"updateDashboardFolder",tags:["dashboard-folders"],url:`${Rs}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the dashboard folder to update. Use the `id` returned by folder list, get, create, or update responses."})}),body:kg,response:el}),Vw=d({description:"Deletes an empty dashboard folder by ID. The request fails if the folder still contains dashboards or child folders; dashboards and child folders are not moved or deleted automatically.",operationId:"deleteDashboardFolder",tags:["dashboard-folders"],url:`${Rs}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the dashboard folder to delete. Use the `id` returned by folder list, get, create, or update responses."})}),response:N});var Cr="/v0/dashboards",Ww=["white","gray.100","amber.200","lime.200","emerald.200","cyan.200","blue.200","violet.200","fuchsia.200","pink.200","red.200"],R4=["bar","distribution","gauge","heatmap","list","pie","query-value","table","timeseries","top-list"],C7e=[...R4,"note"];var C4=["ns","us","ms","s","m","h","days"];var P4=["B","KB","MB","GB","TB","PB"];var U4=20;var Zw=r.Object({type:r.Literal("cpu",{description:"Normalizes values as CPU usage"})},{$id:"DataNormalizerCpu",title:"CPU"}),Xw=r.Object({type:r.Literal("duration",{description:"Normalizes values as durations using standard time units"}),unit:r.Enum(C4,{description:"Time unit used to present the normalized values"})},{$id:"DataNormalizerDuration",title:"Duration"}),Jw=r.Object({type:r.Literal("data",{description:"Normalizes values as data sizes using byte units"}),unit:r.Enum(P4,{description:"Data size unit used to present the normalized values"})},{$id:"DataNormalizerData",title:"Data"}),ev=r.Object({type:r.Literal("percent",{description:"Formats numeric values as percentages. Use it when the raw value is already on a 0-100 scale, for example `25` to display `25%`."})},{$id:"DataNormalizerPercent",title:"Percent"}),tv=r.Object({type:r.Literal("percent-fraction",{description:"Formats numeric values as percentages. Use it when the raw value is a 0-1 fraction; Tsuga multiplies the value by 100 for display, for example `0.2` to display `20%`."})},{$id:"DataNormalizerPercentFraction",title:"Percent Fraction"}),rv=r.Object({type:r.Literal("date",{description:"Formats values as calendar dates"})},{$id:"DataNormalizerDate",title:"Date"}),nv=r.Object({type:r.Literal("level",{description:"Displays values using their log level name"})},{$id:"DataNormalizerLevel",title:"Level"}),ov=r.Object({type:r.Literal("none",{description:"Displays raw values without a unit. Records an explicit removal of the unit, so it is not re-derived from metric metadata"})},{$id:"DataNormalizerNone",title:"None"}),w4=r.Object({type:r.Literal("custom",{description:"Normalizes values using a custom unit label"}),unit:r.String({description:"Text label describing the custom unit"})},{$id:"DataNormalizerCustom",title:"Custom"}),v4=r.Object({type:r.Literal("custom",{description:"Normalizes values using a custom unit label"}),unit:r.String({description:"Text label describing the custom unit. Must not be empty.",minLength:1,maxLength:U4})},{$id:"InputDataNormalizerCustom",title:"Custom"}),Rt=C("type",[Xw,Jw,ev,tv,rv,nv,Zw,ov,w4],{title:"Normalizer",description:"Display-value formatter for widget values or list/table columns."}),Ct=C("type",[Xw,Jw,ev,tv,rv,nv,Zw,ov,v4],{title:"Normalizer",description:"Display-value formatter for widget values or list/table columns."}),Mg=r.Object({attribute:r.String({description:"Attribute (log field or database row column) displayed as a column in the list"}),normalizer:r.Optional(Rt)},{title:"WidgetListColumn",description:"List column pairing a displayed attribute with the formatting applied to its values."}),Dg=r.Object({attribute:r.String({description:"Attribute (log field or database row column) displayed as a column in the list"}),normalizer:r.Optional(Ct)},{title:"WidgetListColumn",description:"List column pairing a displayed attribute with the formatting applied to its values."}),$i=["background","no-background"],N4=["table","legend-only","no-legend"];var L4=["greater_than","less_than","equal","not_equal","greater_than_or_equal","less_than_or_equal"],iv=["alert","warning","success"],Pr=r.Object({operator:r.Enum(L4,{description:"Comparator used to evaluate the metric value"}),value:r.Number({description:"Threshold value used when evaluating the operator"}),color:r.Enum(iv,{description:"Color applied when the condition is met"})},{title:"ConditionalFormatting",description:"Color rule evaluated against the displayed value. The first matching rule in the array is applied."}),k4=r.Object({value:r.Number({description:"Y-axis value where the threshold marker is placed"}),level:r.Enum(iv,{description:"Level applied to the threshold marker"})},{title:"ThresholdMarker",description:"Marker line drawn across the chart at a fixed value, colored by its level."}),M4=["sec","min","hour","day"],wn=r.Object({time:r.Number({description:"Numeric count of `metric` units in each bucket. Required when `timeBucket` is present."}),metric:r.Enum(M4,{description:"Unit used to measure the bucket width"})},{description:"Time bucket width for time-based chart widgets. Optional; when present, `time` and `metric` together define the bucket width."});var Un=r.Enum(["flex-start","center","flex-end"],{description:"Flex alignment keyword used for widget layout"}),ji=r.Object({formula:r.Optional(r.String({description:"Optional alias for formula (only used for display in the UI)"})),queries:r.Optional(r.Record(r.String(),r.String({description:'Display name for this query series in the legend, keyed by the zero-based query index as a string ("0" = first query, "1" = second, and so on). This differs from `formula`, which references queries as "q1", "q2". Omit to fall back to an auto-generated label like "Count on <filter>".'}),{description:"Display names for individual query series, keyed by the zero-based query index as a string."}))},{description:"Display names used for the formula series and the individual query series instead of auto-generated labels."}),qi=r.Object({formula:r.Optional(u({type:"short",description:"Optional alias for formula (only used for display in the UI)"})),queries:r.Optional(r.Record(r.String(),u({type:"short",description:'Display name for this query series in the legend, keyed by the zero-based query index as a string ("0" = first query, "1" = second, and so on). This differs from `formula`, which references queries as "q1", "q2". Omit to fall back to an auto-generated label like "Count on <filter>".'}),{description:"Display names for individual query series, keyed by the zero-based query index as a string."}))},{description:"Display names used for the formula series and the individual query series instead of auto-generated labels."}),rl={source:ir,queries:Sx,formula:r.Optional(iu),aliases:r.Optional(ji),visibleSeries:r.Optional(r.Array(r.Boolean(),{description:"Flags indicating whether each query or formula series is visible"}))},nl={source:ir,queries:os,formula:r.Optional(co),aliases:r.Optional(qi),visibleSeries:r.Optional(r.Array(r.Boolean(),{description:"Flags indicating whether each query or formula series is visible"}))},Ur=r.Optional(r.Enum(["relative","absolute"],{description:"Whether each group holds its own value or its percentage of the ungrouped total (defaults to absolute)"})),Fi={...rl,groupBy:r.Optional(li)},Bi={...nl,groupBy:r.Optional(Fr)},Fe=r.Enum(N4,{description:"Controls whether and how the widget displays legend or series details (e.g. table, legend-only, or no legend)"}),ye=r.Optional(r.Union([r.Number(),r.Literal("max")],{description:"Display precision for numeric labels, tooltips, tables, and scalar values. Use a number of decimal places to round displayed values, or `max` to display the full submitted precision."})),Jt=r.Optional(r.Array(k4,{description:"Threshold markers displayed on the chart"})),D4=r.Object({name:r.String({description:"Display name of the table column"}),...rl,source:ir,normalizer:r.Optional(Rt),precision:ye},{title:"TableColumn",description:"Table column backed by its own aggregation. `defaultSorting` and `columnSizes` reference it as `col-<index>`, using its zero-based position in `columns`."}),G4=r.Object({name:u({description:"Display name of the table column"}),...nl,source:ir,normalizer:r.Optional(Ct),precision:ye},{title:"TableColumn",description:"Table column backed by its own aggregation. `defaultSorting` and `columnSizes` reference it as `col-<index>`, using its zero-based position in `columns`."}),$4=r.Array(r.Object({id:r.String({description:"ID of the column to sort by"}),desc:r.Boolean({description:"Whether the sort is descending"})},{title:"TableDefaultSorting"}),{description:"Default sorting applied to a table widget. Column IDs are `label` for the grouping column and `col-<index>` for each entry in `columns`. Users can still change sorting by selecting columns in the rendered table."}),j4=r.Array(r.Object({id:u({description:"ID of the column to sort by"}),desc:r.Boolean({description:"Whether the sort is descending"})},{title:"TableDefaultSorting"}),{description:"Default sorting applied to a table widget. Column IDs are `label` for the grouping column and `col-<index>` for each entry in `columns`. Users can still change sorting by selecting columns in the rendered table."}),Gg=r.Array(r.Object({id:r.String({description:"Column attribute used for the default list sort. It matches an attribute in `listColumns` or a built-in list column for the selected list source."}),desc:r.Boolean({description:"Sort direction for the default list sort. `true` sorts descending; `false` sorts ascending."})},{title:"ListDefaultSorting"}),{description:"Default sorting applied to a list widget. Applies to log, span, or connection list widgets. Users can still change sorting by selecting columns in the rendered list."}),$g=r.Array(r.Object({id:u({description:"Column attribute used for the default list sort. Set this to an attribute in `listColumns` or a built-in list column for the selected list source."}),desc:r.Boolean({description:"Sort direction for the default list sort. Set `true` for descending order or `false` for ascending order."})},{title:"ListDefaultSorting"}),{description:"Default sorting applied to a list widget. Optional on create or update for log, span, or connection list widgets. Users can still change sorting by selecting columns in the rendered list."}),av=["horizontal","vertical"],q4=r.Object({type:r.Literal("list",{description:"Displays matching logs in a tabular list"}),query:r.String({description:"Query that selects logs for the list"}),listColumns:r.Optional(r.Array(Mg,{description:"Custom columns to display for each log"})),listColumnsSize:r.Optional(r.Record(r.String(),r.Number({description:"List column width by column id"}),{description:"List column widths in pixels, keyed by the `attribute` of the matching `listColumns` entry. Columns without an entry keep their default width."})),isCellWrapped:r.Optional(r.Boolean({description:"Whether list widget cell text wraps instead of truncating. Applies to list widgets."})),defaultSorting:r.Optional(Gg)},{$id:"GraphVisualizationList",title:"List"}),F4=r.Object({type:r.Literal("list",{description:"Displays matching logs in a tabular list"}),query:u({type:"tsuga-query",description:"Query that selects logs for the list"}),listColumns:r.Optional(r.Array(Dg,{description:"Custom columns to display for each log"})),listColumnsSize:r.Optional(r.Record(r.String(),r.Number({description:"List column width by column id"}),{description:"List column widths in pixels, keyed by the `attribute` of the matching `listColumns` entry. Columns without an entry keep their default width."})),isCellWrapped:r.Optional(r.Boolean({description:"Whether list widget cell text wraps instead of truncating. Applies to list widgets. Optional; omit or set false to use truncated cells."})),defaultSorting:r.Optional($g)},{$id:"InputGraphVisualizationList",title:"List"}),tl=C("type",[r.Object({type:r.Literal("auto",{description:"Automatically choose this axis bound"})}),r.Object({type:r.Literal("number",{description:"Use a fixed numeric axis bound"}),value:r.Number({description:"Fixed numeric axis bound value"})})],{description:"Axis bound mode: automatic or fixed numeric value"}),Hi=r.Object({min:tl,max:tl,scale:C("type",[r.Object({type:r.Literal("pow",{description:"Power scale"}),exponent:r.Number({description:"Exponent used by the power scale"})}),r.Object({type:r.Enum(["linear","log","sqrt"],{description:"Built-in axis scale"})})],{description:"Y-axis scale mode"}),alwaysIncludeZero:r.Boolean({description:"Whether the rendered Y axis should always include zero"})},{description:"Y-axis bounds and scale configuration for chart widgets."}),Ki=r.Object({min:tl,max:tl,scale:C("type",[r.Object({type:r.Literal("pow",{description:"Power scale"}),exponent:r.Number({minimum:0,description:"Exponent used by the power scale"})}),r.Object({type:r.Enum(["linear","log","sqrt"],{description:"Built-in axis scale"})})],{description:"Y-axis scale mode"}),alwaysIncludeZero:r.Boolean({description:"Whether the rendered Y axis should always include zero"})},{description:"Y-axis bounds and scale configuration for chart widgets. Optional on create or update."}),B4=r.Array(r.Integer({description:"Marker value expressed as a percentage between 0 and 100"}),{description:"Percentile markers displayed on top of the distribution chart"}),H4=r.Array(r.Integer({minimum:0,maximum:100,description:"Marker value expressed as a percentage between 0 and 100"}),{description:"Percentile markers displayed on top of the distribution chart"});var K4=r.Object({type:r.Literal("timeseries-connection",{description:"Displays the database rows-based aggregation as a time series chart"}),connectionId:r.String({description:"The ID of the connection to use to query the datastore."}),queries:r.Array(r.String({description:"The read-only SQL query to execute against the connection."})),legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Hi)},{$id:"GraphVisualizationTimeseriesConnection",title:"TimeseriesConnection"}),z4=r.Object({type:r.Literal("timeseries-connection",{description:"Displays the database rows-based aggregation as a time series chart"}),connectionId:u({allowEmpty:!1,description:"The ID of the connection to use to query the datastore."}),queries:r.Array(u({allowEmpty:!1,description:"The read-only SQL query to execute against the connection.",type:"readonly-sql-query"}),{minItems:1}),legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Ki)},{$id:"InputGraphVisualizationTimeseriesConnection",title:"TimeseriesConnection"}),Y4=r.Object({type:r.Literal("list-connection",{description:"Displays database rows as a tabular list"}),connectionId:r.String({description:"The ID of the connection to use to query the datastore."}),query:r.String({description:"The read-only SQL query to execute against the connection."}),listColumns:r.Optional(r.Array(Mg,{description:"Custom columns to display for each database row"})),listColumnsSize:r.Optional(r.Record(r.String(),r.Number({description:"List column width by column id"}),{description:"List column widths in pixels, keyed by the `attribute` of the matching `listColumns` entry. Columns without an entry keep their default width."})),isCellWrapped:r.Optional(r.Boolean({description:"Whether list widget cell text wraps instead of truncating. Applies to connection list widgets."})),defaultSorting:r.Optional(Gg)},{$id:"GraphVisualizationListConnection",title:"ListConnection"}),V4=r.Object({type:r.Literal("list-connection",{description:"Displays database rows as a tabular list"}),connectionId:u({allowEmpty:!1,description:"The ID of the connection to use to query the datastore."}),query:u({allowEmpty:!1,description:"The read-only SQL query to execute against the connection.",type:"readonly-sql-query"}),listColumns:r.Optional(r.Array(Dg,{description:"Custom columns to display for each database row"})),listColumnsSize:r.Optional(r.Record(r.String(),r.Number({description:"List column width by column id"}),{description:"List column widths in pixels, keyed by the `attribute` of the matching `listColumns` entry. Columns without an entry keep their default width."})),isCellWrapped:r.Optional(r.Boolean({description:"Whether list widget cell text wraps instead of truncating. Applies to connection list widgets. Optional; omit or set false to use truncated cells."})),defaultSorting:r.Optional($g)},{$id:"InputGraphVisualizationListConnection",title:"ListConnection"}),Q4=r.Object({type:r.Literal("top-list-connection",{description:"Displays the database rows-based aggregation as a ranked top list"}),connectionId:r.String({description:"The ID of the connection to use to query the datastore."}),queries:r.Array(r.String({description:"The read-only SQL query to execute against the connection."}))},{$id:"GraphVisualizationTopListConnection",title:"TopListConnection"}),W4=r.Object({type:r.Literal("top-list-connection",{description:"Displays the database rows-based aggregation as a ranked top list"}),connectionId:u({allowEmpty:!1,description:"The ID of the connection to use to query the datastore."}),queries:r.Array(u({allowEmpty:!1,description:"The read-only SQL query to execute against the connection.",type:"readonly-sql-query"}),{minItems:1})},{$id:"InputGraphVisualizationTopListConnection",title:"TopListConnection"}),Z4=r.Object({type:r.Literal("pie-connection",{description:"Displays the database rows-based aggregation as a pie chart"}),connectionId:r.String({description:"The ID of the connection to use to query the datastore."}),queries:r.Array(r.String({description:"The read-only SQL query to execute against the connection."})),legendMode:r.Optional(Fe)},{$id:"GraphVisualizationPieConnection",title:"PieConnection"}),X4=r.Object({type:r.Literal("pie-connection",{description:"Displays the database rows-based aggregation as a pie chart"}),connectionId:u({allowEmpty:!1,description:"The ID of the connection to use to query the datastore."}),queries:r.Array(u({allowEmpty:!1,description:"The read-only SQL query to execute against the connection.",type:"readonly-sql-query"}),{minItems:1}),legendMode:r.Optional(Fe)},{$id:"InputGraphVisualizationPieConnection",title:"PieConnection"}),J4=r.Object({type:r.Literal("bar-connection",{description:"Displays the database rows-based aggregation as a bar chart"}),connectionId:r.String({description:"The ID of the connection to use to query the datastore."}),queries:r.Array(r.String({description:"The read-only SQL query to execute against the connection."})),legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Hi)},{$id:"GraphVisualizationBarConnection",title:"BarConnection"}),e3=r.Object({type:r.Literal("bar-connection",{description:"Displays the database rows-based aggregation as a bar chart"}),connectionId:u({allowEmpty:!1,description:"The ID of the connection to use to query the datastore."}),queries:r.Array(u({allowEmpty:!1,description:"The read-only SQL query to execute against the connection.",type:"readonly-sql-query"}),{minItems:1}),legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Ki)},{$id:"InputGraphVisualizationBarConnection",title:"BarConnection"}),t3=r.Object({type:r.Literal("query-value-connection",{description:"Displays a single value computed by a SQL query against a database connection"}),connectionId:r.String({description:"The ID of the connection to use to query the datastore."}),queries:r.Array(r.String({description:"The read-only SQL query to execute against the connection."})),backgroundMode:r.Optional(r.Enum($i,{description:"Controls whether the widget uses a solid or transparent background"})),conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),precision:ye,normalizer:r.Optional(Rt),legendMode:r.Optional(Fe)},{$id:"GraphVisualizationQueryValueConnection",title:"QueryValueConnection"}),r3=r.Object({type:r.Literal("query-value-connection",{description:"Displays a single value computed by a SQL query against a database connection"}),connectionId:u({allowEmpty:!1,description:"The ID of the connection to use to query the datastore."}),queries:r.Array(u({allowEmpty:!1,description:"The read-only SQL query to execute against the connection.",type:"readonly-sql-query"}),{minItems:1}),backgroundMode:r.Optional(r.Enum($i,{description:"Controls whether the widget uses a solid or transparent background"})),conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),precision:ye,normalizer:r.Optional(Ct),legendMode:r.Optional(Fe)},{$id:"InputGraphVisualizationQueryValueConnection",title:"QueryValueConnection"}),n3=r.Object({type:r.Literal("list-log-patterns",{description:"Displays log patterns clustered from logs matching the query"}),query:r.String({description:"Tsuga query that selects logs to cluster into patterns"}),layout:r.Optional(r.Enum(av,{description:"Layout used to render log patterns"}))},{$id:"GraphVisualizationListLogPatterns",title:"ListLogPatterns"}),o3=r.Object({type:r.Literal("list-log-patterns",{description:"Displays log patterns clustered from logs matching the query"}),query:u({type:"tsuga-query",description:"Tsuga query that selects logs to cluster into patterns"}),layout:r.Optional(r.Enum(av,{description:"Layout used to render log patterns"}))},{$id:"InputGraphVisualizationListLogPatterns",title:"ListLogPatterns"}),i3=r.Object({type:r.Literal("list-spans",{description:"Displays matching trace spans in a tabular list"}),query:r.String({description:"Query that selects trace spans for the list"}),listColumns:r.Optional(r.Array(Mg,{description:"Custom columns to display for each span"})),listColumnsSize:r.Optional(r.Record(r.String(),r.Number({description:"List column width by column id"}),{description:"List column widths in pixels, keyed by the `attribute` of the matching `listColumns` entry. Columns without an entry keep their default width."})),isCellWrapped:r.Optional(r.Boolean({description:"Whether list widget cell text wraps instead of truncating. Applies to span list widgets."})),defaultSorting:r.Optional(Gg)},{$id:"GraphVisualizationListSpans",title:"ListSpans"}),a3=r.Object({type:r.Literal("list-spans",{description:"Displays matching trace spans in a tabular list"}),query:u({type:"tsuga-query",description:"Query that selects trace spans for the list"}),listColumns:r.Optional(r.Array(Dg,{description:"Custom columns to display for each span"})),listColumnsSize:r.Optional(r.Record(r.String(),r.Number({description:"List column width by column id"}),{description:"List column widths in pixels, keyed by the `attribute` of the matching `listColumns` entry. Columns without an entry keep their default width."})),isCellWrapped:r.Optional(r.Boolean({description:"Whether list widget cell text wraps instead of truncating. Applies to span list widgets. Optional; omit or set false to use truncated cells."})),defaultSorting:r.Optional($g)},{$id:"InputGraphVisualizationListSpans",title:"ListSpans"}),Cs=r.Array(r.String({description:"Raw PromQL expression for this widget, returned exactly as stored."}),{description:"PromQL expressions configured for this widget. PromQL-backed widgets require at least one query."}),Ps=r.Array(u({allowEmpty:!1,type:"long",description:"Raw PromQL expression for this widget."}),{minItems:1,description:"PromQL expressions configured for this widget."}),s3=r.Object({type:r.Literal("timeseries-promql",{description:"Displays PromQL metrics query-based aggregation as a time series chart"}),queries:Cs,aliases:r.Optional(ji),timeBucket:r.Optional(wn),normalizer:r.Optional(Rt),precision:ye,legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Hi),smoothing:r.Optional(r.Boolean({description:"Whether to apply automatic smoothing to the rendered timeseries"}))},{$id:"GraphVisualizationTimeseriesPromql",title:"TimeseriesPromql"}),c3=r.Object({type:r.Literal("timeseries-promql",{description:"Displays PromQL metrics query-based aggregation as a time series chart"}),queries:Ps,aliases:r.Optional(qi),timeBucket:r.Optional(wn),normalizer:r.Optional(Ct),precision:ye,legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Ki),smoothing:r.Optional(r.Boolean({description:"Whether to apply automatic smoothing to the rendered timeseries"}))},{$id:"InputGraphVisualizationTimeseriesPromql",title:"TimeseriesPromql"}),p3=r.Object({type:r.Literal("query-value-promql",{description:"Configures a PromQL metrics query-based aggregation as a single value"}),queries:Cs,aliases:r.Optional(ji),backgroundMode:r.Optional(r.Enum($i,{description:"Controls whether the widget uses a solid or transparent background"})),conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),precision:ye,normalizer:r.Optional(Rt),legendMode:r.Optional(Fe)},{$id:"GraphVisualizationQueryValuePromql",title:"QueryValuePromql"}),u3=r.Object({type:r.Literal("query-value-promql",{description:"Configures a PromQL metrics query-based aggregation as a single value"}),queries:Ps,aliases:r.Optional(qi),backgroundMode:r.Optional(r.Enum($i,{description:"Controls whether the widget uses a solid or transparent background"})),conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),precision:ye,normalizer:r.Optional(Ct),legendMode:r.Optional(Fe)},{$id:"InputGraphVisualizationQueryValuePromql",title:"QueryValuePromql"}),l3=r.Object({type:r.Literal("top-list-promql",{description:"Displays PromQL metrics query-based aggregation as a ranked top list"}),queries:Cs,aliases:r.Optional(ji),normalizer:r.Optional(Rt),precision:ye,conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"}))},{$id:"GraphVisualizationTopListPromql",title:"TopListPromql"}),m3=r.Object({type:r.Literal("top-list-promql",{description:"Displays PromQL metrics query-based aggregation as a ranked top list"}),queries:Ps,aliases:r.Optional(qi),normalizer:r.Optional(Ct),precision:ye,conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"}))},{$id:"InputGraphVisualizationTopListPromql",title:"TopListPromql"}),d3=r.Object({type:r.Literal("pie-promql",{description:"Displays PromQL metrics query-based aggregation as a pie chart"}),queries:Cs,aliases:r.Optional(ji),normalizer:r.Optional(Rt),precision:ye,legendMode:r.Optional(Fe)},{$id:"GraphVisualizationPiePromql",title:"PiePromql"}),f3=r.Object({type:r.Literal("pie-promql",{description:"Displays PromQL metrics query-based aggregation as a pie chart"}),queries:Ps,aliases:r.Optional(qi),normalizer:r.Optional(Ct),precision:ye,legendMode:r.Optional(Fe)},{$id:"InputGraphVisualizationPiePromql",title:"PiePromql"}),g3=r.Object({type:r.Literal("bar-promql",{description:"Displays PromQL metrics query-based aggregation as a bar chart"}),queries:Cs,aliases:r.Optional(ji),timeBucket:r.Optional(wn),precision:ye,normalizer:r.Optional(Rt),thresholds:Jt,legendMode:r.Optional(Fe),yAxisSettings:r.Optional(Hi)},{$id:"GraphVisualizationBarPromql",title:"BarPromql"}),h3=r.Object({type:r.Literal("bar-promql",{description:"Displays PromQL metrics query-based aggregation as a bar chart"}),queries:Ps,aliases:r.Optional(qi),timeBucket:r.Optional(wn),precision:ye,normalizer:r.Optional(Ct),thresholds:Jt,legendMode:r.Optional(Fe),yAxisSettings:r.Optional(Ki)},{$id:"InputGraphVisualizationBarPromql",title:"BarPromql"}),y3=r.Object({type:r.Literal("timeseries",{description:"Displays the aggregation as a time series chart"}),...Fi,groupByMode:Ur,timeBucket:r.Optional(wn),normalizer:r.Optional(Rt),precision:ye,legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Hi),smoothing:r.Optional(r.Boolean({description:"Whether to apply automatic smoothing to the rendered timeseries"}))},{$id:"GraphVisualizationTimeseries",title:"Timeseries"}),T3=r.Object({type:r.Literal("timeseries",{description:"Displays the aggregation as a time series chart"}),...Bi,groupByMode:Ur,timeBucket:r.Optional(wn),normalizer:r.Optional(Ct),precision:ye,legendMode:r.Optional(Fe),thresholds:Jt,yAxisSettings:r.Optional(Ki),smoothing:r.Optional(r.Boolean({description:"Whether to apply automatic smoothing to the rendered timeseries"}))},{$id:"InputGraphVisualizationTimeseries",title:"Timeseries"}),sv="Requests stacked rendering for a top-list widget. Tsuga renders stacked rows only for one count or sum query with exactly two grouped fields, no formula, non-negative values, and a single-cluster context; otherwise the widget renders as a normal top list.",E3=r.Object({type:r.Literal("top-list",{description:"Displays the aggregation as a ranked list of top results"}),...Fi,groupByMode:Ur,normalizer:r.Optional(Rt),precision:ye,conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),isStacked:r.Optional(r.Boolean({description:sv}))},{$id:"GraphVisualizationTopList",title:"TopList"}),_3=r.Object({type:r.Literal("top-list",{description:"Displays the aggregation as a ranked list of top results"}),...Bi,groupByMode:Ur,normalizer:r.Optional(Ct),precision:ye,conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),isStacked:r.Optional(r.Boolean({description:sv}))},{$id:"InputGraphVisualizationTopList",title:"TopList"}),I3=r.Object({type:r.Literal("pie",{description:"Displays the aggregation as a pie chart"}),...Fi,groupByMode:Ur,normalizer:r.Optional(Rt),precision:ye,legendMode:r.Optional(Fe)},{$id:"GraphVisualizationPie",title:"Pie"}),b3=r.Object({type:r.Literal("pie",{description:"Displays the aggregation as a pie chart"}),...Bi,groupByMode:Ur,normalizer:r.Optional(Ct),precision:ye,legendMode:r.Optional(Fe)},{$id:"InputGraphVisualizationPie",title:"Pie"}),S3=r.Object({type:r.Literal("query-value",{description:"Displays the aggregation as a single value"}),...rl,backgroundMode:r.Optional(r.Enum($i,{description:"Controls whether the widget uses a solid or transparent background"})),conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),precision:ye,normalizer:r.Optional(Rt),legendMode:r.Optional(Fe)},{$id:"GraphVisualizationQueryValue",title:"QueryValue"}),A3=r.Object({type:r.Literal("query-value",{description:"Displays the aggregation as a single value"}),...nl,backgroundMode:r.Optional(r.Enum($i,{description:"Controls whether the widget uses a solid or transparent background"})),conditions:r.Optional(r.Array(Pr,{description:"Conditional formatting rules applied to the displayed value"})),precision:ye,normalizer:r.Optional(Ct),legendMode:r.Optional(Fe)},{$id:"InputGraphVisualizationQueryValue",title:"QueryValue"}),O3=r.Object({type:r.Literal("bar",{description:"Displays the aggregation as a bar chart"}),...Fi,groupByMode:Ur,timeBucket:r.Optional(wn),precision:ye,normalizer:r.Optional(Rt),thresholds:Jt,legendMode:r.Optional(Fe),yAxisSettings:r.Optional(Hi)},{$id:"GraphVisualizationBar",title:"Bar"}),x3=r.Object({type:r.Literal("bar",{description:"Displays the aggregation as a bar chart"}),...Bi,groupByMode:Ur,timeBucket:r.Optional(wn),precision:ye,normalizer:r.Optional(Ct),thresholds:Jt,legendMode:r.Optional(Fe),yAxisSettings:r.Optional(Ki)},{$id:"InputGraphVisualizationBar",title:"Bar"}),cv='Attribute that switches the count to "Groups" mode: records are grouped by this attribute, the aggregation produces one value per group, and the chart buckets those per-group values. When omitted, individual records are bucketed.',pv=r.String({description:cv}),uv=u({description:cv}),R3=r.Object({type:r.Literal("distribution",{description:"Displays the aggregation as a distribution chart"}),...Fi,group:r.Optional(pv),precision:ye,normalizer:r.Optional(Rt),percentileMarkers:r.Optional(B4),boundsScale:r.Optional(ou)},{$id:"GraphVisualizationDistribution",title:"Distribution"}),C3=r.Object({type:r.Literal("distribution",{description:"Displays the aggregation as a distribution chart"}),...Bi,group:r.Optional(uv),precision:ye,normalizer:r.Optional(Ct),percentileMarkers:r.Optional(H4),boundsScale:r.Optional(ou)},{$id:"InputGraphVisualizationDistribution",title:"Distribution"}),lv=["red","pink","violet","blue","cyan","green","yellow","orange"],mv=r.Enum(lv,{description:"Color palette used to render the heatmap intensity gradient"}),P3=r.Object({type:r.Literal("heatmap",{description:"Displays the aggregation as a heatmap chart"}),...Fi,group:r.Optional(pv),precision:ye,normalizer:r.Optional(Rt),palette:r.Optional(mv)},{$id:"GraphVisualizationHeatmap",title:"Heatmap"}),U3=r.Object({type:r.Literal("heatmap",{description:"Displays the aggregation as a heatmap chart"}),...Bi,group:r.Optional(uv),precision:ye,normalizer:r.Optional(Ct),palette:r.Optional(mv)},{$id:"InputGraphVisualizationHeatmap",title:"Heatmap"}),dv=r.Object({from:r.Number({description:"Lower bound of the Gauge color threshold; runs up to the next threshold or the max"}),color:r.Enum(lv,{description:"Color applied to the band starting at this value"})},{title:"GaugeColorThreshold",description:"Color band of the gauge range. Bands are ordered by `from`, so entries may be listed in any order."}),w3=r.Object({type:r.Literal("gauge",{description:"Displays the aggregation as a gauge"}),...rl,max:r.Optional(r.Number({description:"Gauge maximum value"})),colorThresholds:r.Optional(r.Array(dv,{description:"Color thresholds inside the gauge range"})),precision:ye,normalizer:r.Optional(Rt)},{$id:"GraphVisualizationGauge",title:"Gauge"}),v3=r.Object({type:r.Literal("gauge",{description:"Displays the aggregation as a gauge"}),...nl,max:r.Optional(r.Number({description:"Gauge maximum value"})),colorThresholds:r.Optional(r.Array(dv,{description:"Color thresholds inside the gauge range"})),precision:ye,normalizer:r.Optional(Ct)},{$id:"InputGraphVisualizationGauge",title:"Gauge"}),N3=r.Object({type:r.Literal("table",{description:"Displays the aggregation as a table with multi-level grouping"}),columns:r.Array(D4,{description:"Each column defines an independent aggregation displayed as a table column"}),groupBy:r.Optional(li),groupByMode:Ur,defaultSorting:r.Optional($4),columnSizes:r.Optional(r.Record(r.String(),r.Number({description:"Column width by column id"}),{description:"Table column widths in pixels, keyed by column id: `label` for the grouping column and `col-<index>` for each entry in `columns`. Columns without an entry keep their default width."}))},{$id:"GraphVisualizationTable",title:"Table"}),L3=r.Object({type:r.Literal("table",{description:"Displays the aggregation as a table with multi-level grouping"}),columns:r.Array(G4,{minItems:1,description:"Each column defines an independent aggregation displayed as a table column"}),groupBy:r.Optional(Fr),groupByMode:Ur,defaultSorting:r.Optional(j4),columnSizes:r.Optional(r.Record(r.String(),r.Number({description:"Column width by column id"}),{description:"Table column widths in pixels, keyed by column id: `label` for the grouping column and `col-<index>` for each entry in `columns`. Columns without an entry keep their default width."}))},{$id:"InputGraphVisualizationTable",title:"Table"}),k3=r.Object({type:r.Literal("note",{description:"Displays static text on the dashboard"}),note:r.Optional(r.String({description:"Markdown-compatible text shown in the note"})),noteColor:r.Optional(r.Enum(Ww,{description:"Background color used to render the note"})),noteAlign:r.Optional(Un),noteJustifyContent:r.Optional(Un)},{$id:"GraphVisualizationNote",title:"Note"}),M3=r.Object({type:r.Literal("note",{description:"Displays static text on the dashboard"}),note:r.Optional(u({type:"long",description:"Markdown-compatible text shown in the note"})),noteColor:r.Optional(r.Enum(Ww,{description:"Background color used to render the note"})),noteAlign:r.Optional(Un),noteJustifyContent:r.Optional(Un)},{$id:"InputGraphVisualizationNote",title:"Note"}),D3=C("type",[K4,Y4,Q4,Z4,J4,t3,s3,p3,l3,d3,g3,y3,E3,I3,S3,w3,O3,R3,P3,N3,q4,k3,n3,i3],{description:"Widget visualization configuration. The `type` discriminator selects the widget kind and its required fields."}),G3=C("type",[z4,V4,W4,X4,e3,r3,c3,u3,m3,f3,h3,T3,_3,b3,A3,v3,x3,C3,U3,L3,F4,M3,o3,a3],{description:"Widget visualization configuration. The `type` discriminator selects the widget kind and its required fields."}),ol=r.Object({id:r.String({description:"Unique identifier of the graph widget inside the dashboard. Set by the caller when the graph is created; use it to target the graph in later update requests."}),name:r.Optional(r.String({description:"Display name of the graph widget."})),description:r.Optional(r.String({description:"Optional text shown with the graph widget."})),descriptionAlign:r.Optional(Un),descriptionJustifyContent:r.Optional(Un),visualization:D3,layout:r.Optional(r.Object({x:r.Number({description:"Column position of the widget on the 12-column dashboard grid. 0 is the leftmost column; increasing values move right."}),y:r.Number({description:"Row position of the widget on the dashboard grid, in row units of 50 pixels each. 0 is the topmost row; increasing values move down."}),w:r.Number({description:"Width of the widget in grid columns, out of the 12-column grid. Dashboard validation uses this with `h` and the widget type to reject layouts below the widget minimum."}),h:r.Number({description:"Height of the widget in grid rows, where each row is 50 pixels tall. Dashboard validation uses this with `w` and the widget type to reject layouts below the widget minimum."})},{description:`Grid position and size of the widget. Optional; when provided, the size must be at least ${Id}\xD7${bd} (width\xD7height) grid units, except note widgets which can go down to 1\xD71.`}))},{title:"Graph",description:"Single dashboard widget, combining its identity, its visualization configuration, and its position on the dashboard grid."}),il=r.Object({id:u({description:"Unique identifier of the graph widget inside the dashboard. Assign it when the graph is created; use it to target the graph in later update requests."}),name:r.Optional(u({description:"Display name of the graph widget."})),description:r.Optional(r.String({minLength:1,maxLength:800,description:"Text shown with the graph widget."})),descriptionAlign:r.Optional(Un),descriptionJustifyContent:r.Optional(Un),visualization:G3,layout:r.Optional(r.Object({x:r.Number({description:"Column position of the widget on the 12-column dashboard grid. 0 is the leftmost column; increasing values move right."}),y:r.Number({description:"Row position of the widget on the dashboard grid, in row units of 50 pixels each. 0 is the topmost row; increasing values move down."}),w:r.Number({description:"Width of the widget in grid columns, out of the 12-column grid. Dashboard validation uses this with `h` and the widget type to reject layouts below the widget minimum."}),h:r.Number({description:"Height of the widget in grid rows, where each row is 50 pixels tall. Dashboard validation uses this with `w` and the widget type to reject layouts below the widget minimum."})},{description:`Grid position and size of the widget. Optional; when provided, the size must be at least ${Id}\xD7${bd} (width\xD7height) grid units, except note widgets which can go down to 1\xD71.`}))},{title:"Graph",description:"Single dashboard widget, combining its identity, its visualization configuration, and its position on the dashboard grid."}),Qw=10,$3=r.Array(r.Object({key:r.String({description:"Dashboard-wide filter key, usually a telemetry attribute name."}),values:r.Array(r.String({description:"Filter value."}),{description:"Allowed values for this dashboard-wide filter."}),exclude:r.Optional(r.Boolean({description:"If true, widgets exclude telemetry whose value matches this filter instead of including it (is-not)."}))}),{description:"Dashboard-wide filters applied to every widget on the dashboard."}),j3=r.Array(r.Object({key:u({description:"Dashboard-wide filter key, usually a telemetry attribute name."}),values:r.Array(u({description:"Filter value."}),{description:"Allowed values for this dashboard-wide filter."}),exclude:r.Optional(r.Boolean({description:"If true, widgets exclude telemetry whose value matches this filter instead of including it (is-not)."}))}),{maxItems:Qw,description:`Dashboard-wide filters applied to every widget on the dashboard. Up to ${Qw} filters are allowed.`}),zi=r.Object({id:r.String({description:"Tsuga-generated dashboard ID assigned when the dashboard is created."}),name:r.String({description:"Display name of the dashboard. Set by the caller on create or update."}),owner:r.String({description:"ID of the team that owns the dashboard. Set by the caller on create or update and used for dashboard access control."}),graphs:r.Array(ol,{description:"Ordered widgets that compose the dashboard"}),filters:r.Optional($3),createdAt:A({description:"Timestamp when Tsuga created the dashboard."}),updatedAt:A({description:"Timestamp when Tsuga last updated the dashboard."}),creator:r.Optional(pe),updater:r.Optional(pe),tags:De,timePreset:r.Optional(r.Enum(Ul,{description:"Relative time preset used when opening the dashboard."})),folderId:r.Optional(r.String({description:"Folder that contains the dashboard. Set from the dashboard's saved folder relationship. Returned when the dashboard is in a folder; omitted when it is not."}))}),al=r.Object({name:u({description:"Display name of the dashboard."}),owner:u({allowEmpty:!1,description:"ID of the team that owns the dashboard. Required and used for dashboard access control."}),graphs:r.Array(il,{description:"Ordered widgets that compose the dashboard"}),filters:r.Optional(j3),tags:Xe,timePreset:r.Optional(r.Enum(Ul,{description:"Relative time preset used when opening the dashboard. Optional; create defaults to `past-30-minutes` when omitted, and update omission preserves the current value."})),folderId:r.Optional(r.Union([r.Null(),u({allowEmpty:!1})],{description:"Folder that should contain the dashboard. Optional; omit on update to keep the current folder, pass null to clear the folder, or pass a readable dashboard-folder ID to move it."}))}),cr={IS_FAVORITE:"isFavorite",OWNER:"owner",TAGS:"tags",WIDGET_COUNT:"widgetCount",UPDATED_AT:"updatedAt",NAME:"name"},fv=[cr.OWNER,cr.TAGS,cr.WIDGET_COUNT,cr.UPDATED_AT,cr.NAME],Us=r.Partial(r.Object({owners:_e(u({allowEmpty:!1}),{description:"Restrict results to dashboards owned by any of these team IDs",maxItems:50}),searchQuery:r.Object({value:u({allowEmpty:!1,description:"Substring matched case-insensitively against dashboard names or dashboard IDs. Omit the whole `searchQuery` filter to skip text filtering."}),exclude:r.Optional(r.Boolean({description:"If true, exclude dashboards matching this value instead of including them"}))},{description:"Text filter for dashboard names or IDs. Optional; `exclude: true` returns dashboards whose name and ID do not match the substring."}),tags:_e(Bt.items,{description:"Restrict results to dashboards that have at least one of the listed key/value tags",maxItems:50}),folderId:r.Union([r.Null(),u({allowEmpty:!1})],{description:"Folder filter for dashboard query results. Optional; pass a folder ID to return dashboards in that folder, or null to return only dashboards that are not in any folder."})},{description:"Optional filters applied to narrow the returned dashboards"})),q3=r.Partial(r.Object({...fe,filters:Us,sort:r.Object({by:r.Enum([cr.IS_FAVORITE,cr.OWNER,cr.TAGS,cr.WIDGET_COUNT,cr.UPDATED_AT,cr.NAME],{description:"Field to sort the returned dashboards by"}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned dashboards"})})),P7e=d({tags:["dashboards"],url:`${Cr}/query`,method:"POST",paginated:!0,response:r.Array(zi),body:q3}),U7e=d({tags:["dashboards"],url:`${Cr}/tags/query`,method:"POST",body:r.Object({filters:r.Optional(r.Omit(Us,["tags"]))}),response:Ft}),w7e=d({tags:["dashboards"],url:`${Cr}/counts/query`,method:"POST",body:r.Object({filters:r.Optional(r.Partial(Us))}),response:r.Object({all:r.Integer({description:"Total number of dashboards matching the filters that the user can read."})})}),v7e=d({tags:["dashboards"],url:`${Cr}/:id`,method:"GET",params:r.Object({id:u()}),response:zi}),N7e=d({tags:["dashboards"],url:Cr,method:"POST",body:al,response:zi}),L7e=d({tags:["dashboards"],url:`${Cr}/:id`,method:"PUT",params:r.Object({id:u()}),body:r.Partial(al),response:zi}),k7e=d({tags:["dashboards"],url:`${Cr}/bulk-update`,method:"PUT",body:r.Object({dashboardIds:r.Array(u(),{description:"Dashboard IDs to update. At least one dashboard ID is required."}),owner:r.Optional(u({allowEmpty:!1,description:"Owning team ID to apply to every dashboard. Optional when folderId is provided; omit to keep the current owner."})),folderId:r.Optional(r.Union([r.Null(),u({allowEmpty:!1})],{description:"Folder that should contain every dashboard. Optional when owner is provided; omit to keep the current folder, pass null to clear the folder, or pass a dashboard-folder ID to move dashboards."}))}),response:r.Object({})}),M7e=d({tags:["dashboards"],url:`${Cr}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),D7e=d({tags:["dashboards"],url:`${Cr}/:id/graphs/:graphId`,method:"PUT",params:r.Object({id:u({allowEmpty:!1}),graphId:u({allowEmpty:!1})}),body:r.Omit(il,["id"]),response:ol}),G7e=d({tags:["dashboards"],url:`${Cr}/bulk-delete`,method:"DELETE",body:r.Object({ids:r.Array(u())}),response:r.Object({})});var Yi=`/${"v1"}/dashboards`,ws=r.Pick(zi,["id","name","owner","graphs","filters","tags","timePreset","folderId"],{$id:"Dashboard",description:"Saved visualization made of dashboard-wide filters and ordered graphs. Use dashboards to preserve reusable views for a team or workflow. See [Dashboards](/documentation/visualize/dashboards/index)."}),F3={id:"123-456-abc",name:"API Performance Overview",owner:"team-123-abc",graphs:[{id:"789-abc-def",name:"Request Latency P99",visualization:{type:"timeseries",source:"metrics",queries:[{aggregate:{type:"percentile",field:"duration",percentile:99},filter:"service:api-gateway"}]},layout:{x:0,y:0,w:6,h:4}}],filters:[{key:"env",values:["production"]}],tags:[{key:"team",value:"platform"}],timePreset:"past-1-hour"};Object.assign(ws,{examples:[F3]});var B3=r.Object({by:r.Enum([...fv],{description:"Field to sort the returned dashboards by: `owner` sorts by owning team ID, `tags` sorts by tag key/value pairs, `widgetCount` sorts by the number of graphs on the dashboard, `updatedAt` sorts by last-updated timestamp, and `name` sorts alphabetically by dashboard name."}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned dashboards"}),gv=r.Object({...Ze,filters:r.Optional(r.Pick(Us,["owners","searchQuery","tags","folderId"])),sort:r.Optional(B3)},{description:"Dashboard query request. Use filters, sorting, limit, and offset to page through visible dashboards."}),H3={filters:{owners:{values:["team-123-abc"]},searchQuery:{value:"API"},tags:{values:[{key:"service",value:"api-gateway"}]},folderId:"folder-123-abc"},sort:{by:"name",direction:"asc"},limit:10,offset:0};Object.assign(gv,{examples:[H3]});var hv=d({description:"Queries dashboards visible to the authenticated operation key. Use this endpoint to build dashboard inventories or synchronize dashboard metadata. Pagination fields limit the returned page; use the response metadata to request additional pages. See [Dashboards](/documentation/visualize/dashboards/index).",operationId:"queryDashboards",tags:["dashboards"],url:`${Yi}/query`,method:"POST",paginated:!0,body:gv,response:r.Array(ws)}),yv=d({description:"Retrieves one dashboard by ID.",operationId:"getDashboard",tags:["dashboards"],url:`${Yi}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the saved dashboard to retrieve. Use the `id` returned by dashboard query, create, or update responses."})}),response:ws}),jg=r.Pick(al,["name","owner","graphs","filters","tags","timePreset","folderId"],{description:"Dashboard create or update request. Provide the dashboard identity, owner team, widgets, filters, tags, and optional time preset."}),K3={name:"API Performance Overview",owner:"team-123-abc",graphs:[{id:"789-abc-def",name:"Request Latency P99",visualization:{type:"timeseries",source:"metrics",queries:[{aggregate:{type:"percentile",field:"duration",percentile:99},filter:"service:api-gateway"}]},layout:{x:0,y:0,w:6,h:4}}],filters:[{key:"env",values:["production"]}],tags:[{key:"team",value:"platform"}],timePreset:"past-1-hour",folderId:null};Object.assign(jg,{examples:[K3]});var z3=r.Omit(il,["id"],{description:"Dashboard graph update request. The graph identifier is supplied in the `graphId` path parameter; provide the replacement graph definition without an `id` field."}),Tv=d({description:"Creates a dashboard owned by the specified team. Use this to provision dashboards from automation or templates. The response returns the saved dashboard definition.",operationId:"createDashboard",tags:["dashboards"],url:Yi,method:"POST",body:jg,response:ws}),Ev=d({description:"Updates an existing dashboard by ID. Fields are patched from the request body; omitted fields keep their current values.",operationId:"updateDashboard",tags:["dashboards"],url:`${Yi}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the saved dashboard to update. Use the `id` returned by dashboard query, get, or create responses."})}),body:r.Partial(jg),response:ws}),Y3=r.Object({id:u({allowEmpty:!1,description:"Identifier of the saved dashboard to delete. Use the `id` returned by dashboard query, get, create, or update responses."})}),_v=d({description:"Deletes a dashboard by ID. Use only after confirming no users or automation still rely on the dashboard.",operationId:"deleteDashboard",tags:["dashboards"],url:`${Yi}/:id`,method:"DELETE",params:Y3,response:N}),z7e=d({description:"Updates one graph inside a dashboard without replacing the full dashboard. Use this for targeted widget edits when you already know the dashboard ID and graph ID.",operationId:"updateDashboardGraph",tags:["dashboards"],url:`${Yi}/:id/graphs/:graphId`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the dashboard that contains the graph to update. Use the `id` returned by dashboard responses."}),graphId:u({allowEmpty:!1,description:"Identifier of the graph to update within the dashboard. Use graph IDs from the dashboard response."})}),body:z3,response:ol});var Iv=100,bv=3,Vi=r.Object({id:r.String({description:"Tsuga-generated ingestion API key ID assigned when the key is created."}),name:r.String({description:"Human-readable key name. Names must be kebab-case when creating or updating keys."}),keyLastCharacters:r.String({description:"Last visible characters of the secret key. Use this to identify a key without exposing the full secret."}),owner:r.String({description:"Team ID that owns and manages the ingestion API key."}),tags:Ft,teamOverrideFields:r.Optional(r.Array(r.String(),{description:"Telemetry attribute names used to override ownership for data sent with this key."})),updatedAt:A({description:"Timestamp when Tsuga last updated the key metadata."}),createdAt:A({description:"Timestamp when Tsuga created the key."}),creator:r.Optional(pe),updater:r.Optional(pe),assetUpdatedAt:A({description:"Timestamp used for asset-change tracking across Tsuga-managed resources."})}),vs=r.Object({name:r.String({format:ti,minLength:1,maxLength:Iv,description:`Kebab-case name for the ingestion API key. Maximum length is ${Iv} characters.`}),owner:u({allowEmpty:!1,description:"Team ID that will own and manage the ingestion API key."}),tags:Bt,teamOverrideFields:r.Union([r.Array(u({allowEmpty:!1}),{minItems:1,maxItems:bv,description:`Array form. Up to ${bv} fields are allowed.`}),r.Null({description:"Clear any existing team override fields."})],{description:"Telemetry attribute names used to override ownership for data sent with this key. Send null to clear existing override fields."})}),Qi="/v0/ingestion-api-keys",tZe=d({tags:["ingestion-api-keys"],url:Qi,method:"POST",body:vs,response:r.Intersect([Vi,r.Object({key:r.String({description:"Full secret value of the ingestion API key. Generated by Tsuga and returned only in this create response; subsequent get and list responses expose only `keyLastCharacters`. Store it immediately, since it cannot be retrieved again after this response."})})])}),rZe=d({tags:["ingestion-api-keys"],url:Qi,method:"GET",paginated:!0,query:r.Object(fe),response:r.Array(Vi)}),nZe=d({tags:["ingestion-api-keys"],url:`${Qi}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1})}),response:Vi}),oZe=d({tags:["ingestion-api-keys"],url:`${Qi}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1})}),body:vs,response:Vi}),iZe=d({tags:["ingestion-api-keys"],url:`${Qi}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1})}),response:N}),aZe=d({tags:["ingestion-api-keys"],url:`${Qi}/bulk-delete`,method:"DELETE",body:r.Object({ids:r.Array(u({allowEmpty:!1}))}),response:r.Object({})});var Ns=`/${"v1"}/ingestion-api-keys`,Ls=r.Pick(Vi,["id","name","owner","tags","teamOverrideFields","keyLastCharacters"],{$id:"IngestionApiKey",description:"API key used to send telemetry data to Tsuga. The full key secret is returned only when the key is created. See [API keys](/documentation/account-and-settings/api-keys)."}),Sv={id:"123-456-abc",name:"production-logs-ingestion",keyLastCharacters:"x7Qm",owner:"team-123-abc",tags:[{key:"env",value:"production"}],teamOverrideFields:["service"]};Object.assign(Ls,{examples:[Sv]});var Av=r.Pick(vs,["name","owner","tags","teamOverrideFields"],{$id:"CreateIngestionApiKeyRequest",description:"Ingestion API key creation request. Provide a kebab-case name, owner team, required tags, and required team override fields as an array of fields or null."}),Ov=r.Pick(vs,["name","owner","tags","teamOverrideFields"],{$id:"UpdateIngestionApiKeyRequest",description:"Ingestion API key update request. Provide the full metadata definition, including name, owner team, tags, and team override fields."}),xv={name:"production-logs-ingestion",owner:"team-123-abc",tags:[{key:"env",value:"production"}],teamOverrideFields:["service"]};Object.assign(Av,{examples:[xv]});Object.assign(Ov,{examples:[xv]});var V3={...Sv,key:"tsuga_in:v1:abc123xyx7Qm"},Rv=d({description:"Lists ingestion API keys visible to the authenticated operation key. Use this to inventory telemetry intake keys, owners, tags, and team override fields. Pagination fields limit the returned page.",operationId:"listIngestionApiKeys",tags:["ingestion-api-keys"],url:Ns,method:"GET",paginated:!0,query:r.Object(Ze),response:r.Array(Ls)}),fZe=d({description:"Retrieves one ingestion API key by ID. The response never includes the full secret key value; only the last visible characters are returned.",operationId:"getIngestionApiKey",tags:["ingestion-api-keys"],url:`${Ns}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the ingestion API key to retrieve. Use the `id` returned by ingestion API key list or create responses."})}),response:Ls}),Q3=r.Intersect([r.Pick(Ls,["id","name","keyLastCharacters","owner","tags","teamOverrideFields"]),r.Object({key:r.String({description:"Full Tsuga-generated ingestion API key secret. Returned only in the create response; list, get, and update responses expose only `keyLastCharacters`."})})],{title:"IngestionApiKeyCreated",example:V3}),Cv=d({description:"Creates an ingestion API key for telemetry intake. Store the returned `key` immediately because Tsuga returns the full secret only in this response.",operationId:"createIngestionApiKey",tags:["ingestion-api-keys"],url:Ns,method:"POST",body:Av,response:Q3}),Pv=d({description:"Updates ingestion API key metadata by ID, including name, owner, tags, and team override fields. The secret key value is not rotated by this operation.",operationId:"updateIngestionApiKey",tags:["ingestion-api-keys"],url:`${Ns}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the ingestion API key to update. Use the `id` returned by ingestion API key list, get, or create responses."})}),body:Ov,response:Ls}),Uv=d({description:"Deletes an ingestion API key by ID. Telemetry clients using the deleted key can no longer send data with it.",operationId:"deleteIngestionApiKey",tags:["ingestion-api-keys"],url:`${Ns}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the ingestion API key to delete. Use the `id` returned by ingestion API key list, create, or update responses."})}),response:N});var W3={application:{webService:["azure_web_app","gcp_app_engine_service"]},data:{bucket:["aws_s3_bucket","gcp_bucket","azure_blob_storage_container"],messagingService:["aws_kinesis_data_stream","aws_sqs_queue","aws_sns_topic","azure_service_bus_namespace","azure_service_bus_queue","gcp_pubsub_topic","azure_event_grid_topic","azure_event_hub_namespace","azure_event_hub"],fileSystem:["aws_efs","azure_file_share"],contentDeliveryNetwork:["aws_cloudfront_distribution","gcp_cloud_cdn_configuration"],database:["aws_dynamodb_table","aws_elasticache","aws_rds_instance","azure_database_for_mysql_server","azure_database_for_postgres_server","azure_sql_database_server","azure_sql_database","gcp_bigtable_instance","gcp_cloud_sql_instance","gcp_firestore_database","gcp_spanner_instance","azure_cosmos_db_account"],storageAccount:["azure_storage_account"],volume:["aws_ebs_volume","gcp_compute_disk","azure_disk"]},compute:{virtualMachine:["aws_ec2_instance","gcp_compute_instance","azure_compute_virtual_machine"],serverless:["aws_lambda_function","gcp_cloud_run_function","gcp_cloud_run_job","gcp_cloud_run_service","azure_function_app"]},container:{kubernetesCluster:["aws_eks_cluster","gcp_gke_cluster","azure_aks_cluster"],containerRepository:["aws_ecr_repository","gcp_artifact_registry_repository","azure_container_registry"],containerCluster:["aws_ecs_cluster"],containerServiceTask:["aws_ecs_task"],containerService:["aws_ecs_service","azure_container_instance_group"],containerImage:["aws_ecr_image","gcp_artifact_registry_docker_image","azure_container_registry_image"]},network:{virtualNetwork:["aws_vpc","gcp_vpc","azure_virtual_network"],loadBalancer:["aws_elastic_load_balancer","gcp_forwarding_rule","azure_load_balancer","azure_traffic_manager_profile"],targetGroup:["aws_target_group"],certificate:["aws_acm_certificate","gcp_certificate_manager_certificate","azure_app_service_certificate"]}},[TZe,sl,ks]=Z3(W3),EZe=Object.fromEntries(sl.map(e=>[e,e]));function Z3(e){let t=[],n=[],o=[],i=Object.keys(e);for(let a of i){t.push(a);let c=e[a];for(let l in c){n.push(l);let m=c[l];Array.isArray(m)&&o.push(...m)}}return[qg(t),qg(n),qg(o)]}function qg(e){if(e.length===0)throw new Error("Array must have at least one element.");return e}var Fg=r.Enum(["HTTP","HTTPS","TCP","UDP","GENEVE","TLS","TLS_QUIC","TCP_UDP","TCP_QUIC","QUIC"]),X3=r.Object({versioningStatus:r.Optional(r.Enum(["Enabled","Disabled","Suspended","Not configured"]))}),J3=r.Object({domainName:r.Optional(r.String()),origins:r.Optional(r.Array(r.String()))}),eY=r.Object({allocatedStorageGib:r.Optional(r.Number()),encryptedAtRest:r.Optional(r.Boolean()),engine:r.Optional(r.String()),dynamoDbItemCount:r.Optional(r.Number()),dynamoDbActualSizeGib:r.Optional(r.Number())}),tY=r.Object({version:r.Optional(r.String()),virtualNetworkId:r.Optional(r.String()),subnets:r.Optional(r.Array(r.String()))}),rY=r.Object({artifactRegistryFormat:r.Optional(r.Enum(["FORMAT_UNSPECIFIED","DOCKER","MAVEN","NPM","APT","YUM","PYTHON","KFP","GO","GENERIC"])),uri:r.Optional(r.String()),tagMutability:r.Optional(r.Enum(["MUTABLE","IMMUTABLE"])),scanOnPush:r.Optional(r.Boolean()),encryptionType:r.Optional(r.String())}),nY=r.Object({status:r.Optional(r.String()),activeServices:r.Optional(r.Number()),pendingTasks:r.Optional(r.Number()),runningTasks:r.Optional(r.Number()),registeredContainerInstances:r.Optional(r.Number()),capacityProviders:r.Optional(r.Array(r.String()))}),oY=r.Object({status:r.Optional(r.String()),desiredStatus:r.Optional(r.String()),healthStatus:r.Optional(r.String()),availabilityZone:r.Optional(r.String()),startedAt:r.Optional(A())}),iY=r.Object({isEncrypted:r.Optional(r.Boolean()),ownerId:r.Optional(r.String()),state:r.Optional(r.Enum(["creating","available","deleting","deleted","error","updating"]))}),aY=r.Object({type:r.Optional(r.String()),osType:r.Optional(r.String()),subnetIds:r.Optional(r.Array(r.String())),nbContainers:r.Optional(r.Number())}),sY=r.Object({digest:r.String(),imageTags:r.Array(r.String()),imageSizeBytes:r.Optional(r.Number()),imagePushedAt:r.Optional(A()),mediaType:r.Optional(r.String()),repositoryName:r.String(),repositoryId:r.Optional(r.String()),scanStatus:r.Optional(r.String())}),cY=r.Object({url:r.Optional(r.String()),maxMessageSizeBytes:r.Optional(r.Number()),messageRetentionHours:r.Optional(r.Number())}),pY=r.Object({runtime:r.Optional(r.String()),memoryAllocationMib:r.Optional(r.Number()),timeoutMs:r.Optional(r.Number()),codeSha256:r.Optional(r.String())}),uY=r.Object({kind:r.Optional(r.String())}),lY=r.Object({instanceId:r.String(),architecture:r.Optional(r.String()),instanceType:r.Optional(r.String()),operatingSystem:r.Optional(r.String()),memoryMib:r.Optional(r.Number()),vCpus:r.Optional(r.Number()),vpcId:r.Optional(r.String()),k8sClusterId:r.Optional(r.String())}),mY=r.Object({id:r.Optional(r.String()),ipCidrBlocks:r.Array(r.String())}),dY=r.Object({protocol:r.Optional(Fg),port:r.Optional(r.Number()),instanceProtocol:r.Optional(Fg),instancePort:r.Optional(r.Number())}),fY=r.Object({protocol:r.Optional(r.String()),ports:r.Optional(r.Array(r.String())),portRange:r.Optional(r.String()),allPorts:r.Optional(r.Boolean())}),gY=r.Object({name:r.String(),ip:r.Optional(r.String()),type:r.Enum(["public","private"])}),hY=r.Object({type:r.String(),name:r.String()}),yY=r.Object({frontendIp:r.Optional(gY),backendIpPools:r.Array(hY)}),TY=r.Object({targetId:r.String(),targetPort:r.Optional(r.Number()),targetType:r.Optional(r.Enum(["instance","ip","lambda","alb"])),healthState:r.Optional(r.String()),healthReason:r.Optional(r.String()),healthDescription:r.Optional(r.String()),availabilityZone:r.Optional(r.String())}),EY=r.Object({protocol:r.Optional(Fg),port:r.Optional(r.Number()),type:r.Optional(r.Enum(["alb","lambda","instance","ip"])),name:r.Optional(r.String()),targetGroupArn:r.Optional(r.String()),virtualNetworkId:r.Optional(r.String()),healthCheckProtocol:r.Optional(r.String()),healthCheckPort:r.Optional(r.String()),healthCheckPath:r.Optional(r.String()),healthCheckIntervalSeconds:r.Optional(r.Number()),healthCheckTimeoutSeconds:r.Optional(r.Number()),healthyThresholdCount:r.Optional(r.Number()),unhealthyThresholdCount:r.Optional(r.Number()),targets:r.Optional(r.Array(TY)),targetCount:r.Optional(r.Number()),healthyTargetCount:r.Optional(r.Number()),loadBalancerArns:r.Optional(r.Array(r.String()))}),_Y=r.Object({first:r.Optional(r.String()),last:r.Optional(r.String()),scope:r.Optional(r.Number())}),IY=r.Object({type:r.Optional(r.String()),name:r.Optional(r.String()),alwaysServe:r.Optional(r.Boolean()),subnets:r.Optional(r.Array(r.Union([r.Number(),_Y]))),target:r.Optional(r.String()),weight:r.Optional(r.Number()),priority:r.Optional(r.Number()),status:r.Optional(r.String())}),bY=r.Object({instanceId:r.Optional(r.String()),state:r.Optional(r.String()),reasonCode:r.Optional(r.String()),description:r.Optional(r.String())}),SY=r.Object({loadBalancerType:r.Optional(r.String()),dnsName:r.Optional(r.String()),virtualNetworkId:r.Optional(r.String()),subnetIds:r.Array(r.String()),scheme:r.Optional(r.String()),listeners:r.Optional(r.Union([r.Array(dY),r.Array(fY)])),targets:r.Optional(r.Union([r.Array(r.String()),r.Array(bY),r.Array(IY)])),azureLoadBalancingRules:r.Optional(r.Array(yY))}),AY=r.Object({domainName:r.Optional(r.String()),expiresAt:r.Optional(A()),inUseBy:r.Optional(r.Array(r.String())),renewalEligibility:r.Optional(r.String()),revokedAt:r.Optional(A()),status:r.Optional(r.String()),type:r.Optional(r.String())}),OY=r.Object({state:r.Optional(r.Enum(["creating","available","deleting","deleted","error","in-use"])),volumeType:r.Optional(r.Enum(["gp2","gp3","io1","io2","st1","sc1","standard"]))}),xY=r.Object({osType:r.Optional(r.Enum(["Windows","Linux"]))}),RY=r.Object({state:r.Optional(r.String()),volumeType:r.Optional(r.String())}),CY=r.Intersect([r.Object({isEncrypted:r.Optional(r.Boolean()),sizeGib:r.Optional(r.Number())}),r.Union([OY,RY,xY])]),PY=r.Object({instanceCount:r.Optional(r.Number()),hostnames:r.Optional(r.Array(r.String())),runtime:r.Optional(r.String())}),cl=r.Union([r.Object({category:r.Literal("application"),resourceType:r.Literal("webService"),attributes:r.Optional(PY)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("bucket"),attributes:r.Optional(X3)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("messagingService"),attributes:r.Optional(cY)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("fileSystem"),attributes:r.Optional(iY)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("contentDeliveryNetwork"),attributes:r.Optional(J3)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("database"),attributes:r.Optional(eY)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("storageAccount"),attributes:r.Optional(uY)}),r.Object({category:r.Literal("data"),resourceType:r.Literal("volume"),attributes:r.Optional(CY)}),r.Object({category:r.Literal("compute"),resourceType:r.Literal("virtualMachine"),attributes:r.Optional(lY)}),r.Object({category:r.Literal("compute"),resourceType:r.Literal("serverless"),attributes:r.Optional(pY)}),r.Object({category:r.Literal("container"),resourceType:r.Literal("kubernetesCluster"),attributes:r.Optional(tY)}),r.Object({category:r.Literal("container"),resourceType:r.Literal("containerRepository"),attributes:r.Optional(rY)}),r.Object({category:r.Literal("container"),resourceType:r.Literal("containerCluster"),attributes:r.Optional(nY)}),r.Object({category:r.Literal("container"),resourceType:r.Literal("containerServiceTask"),attributes:r.Optional(oY)}),r.Object({category:r.Literal("container"),resourceType:r.Literal("containerService"),attributes:r.Optional(aY)}),r.Object({category:r.Literal("container"),resourceType:r.Literal("containerImage"),attributes:r.Optional(sY)}),r.Object({category:r.Literal("network"),resourceType:r.Literal("virtualNetwork"),attributes:r.Optional(mY)}),r.Object({category:r.Literal("network"),resourceType:r.Literal("loadBalancer"),attributes:SY}),r.Object({category:r.Literal("network"),resourceType:r.Literal("targetGroup"),attributes:r.Optional(EY)}),r.Object({category:r.Literal("network"),resourceType:r.Literal("certificate"),attributes:r.Optional(AY)})],{description:"Normalized public inventory category, resource type, and category-specific attributes. Attribute shape depends on the category and resourceType combination."});var Ao="/v0/inventory",wv=["scan_in_progress","success","failure","partial"],Hg=r.Object({id:r.String({description:"Identifier of the inventory resource. Generated by Tsuga."}),cloudPlatform:r.Enum(_n,{description:"Cloud platform where Tsuga discovered this resource."}),cloudAccount:r.String({description:"Cloud-native account identifier where Tsuga discovered this resource, such as an AWS account ID, GCP project ID, or Azure subscription ID."}),cloudRegion:r.Optional(r.String({description:"Cloud region where Tsuga discovered this resource, when the resource is regional."})),fullyQualifiedResourceId:r.String({description:"Cloud-native unique identifier for this resource, such as an AWS ARN, GCP resource name, or Azure resource ID."}),displayName:r.String({description:"Human-readable resource name shown in Tsuga. Derived from cloud provider metadata when available."}),nativeResourceType:r.String({description:"Cloud-native resource type reported by the inventory integration, for example `aws_ec2_instance` or `gcp_bucket`."}),resourceCreatedAt:r.Optional(A({description:"Timestamp when the resource was created in the cloud, when known."})),resourceUpdatedAt:r.Optional(A({description:"Timestamp when the resource was last updated in the cloud, when known."})),resourceLastSeenAt:A({description:"Timestamp when Tsuga last observed this resource during an inventory scan."}),tags:De,nativeAttributes:r.Optional(r.Unsafe({type:"object",additionalProperties:!0})),covered:r.Optional(r.Boolean({description:"Whether the resource is covered by the configured infrastructure-as-code identifiers"}))}),Wi={DISPLAY_NAME:"displayName",CLOUD_ACCOUNT:"cloudAccount",NATIVE_RESOURCE_TYPE:"nativeResourceType",CLOUD_REGION:"cloudRegion",RESOURCE_TYPE:"resourceType",RESOURCE_CREATED_AT:"resourceCreatedAt"},vv=r.Object({cloudPlatforms:_e(r.Enum(_n),{description:"Restrict results to resources discovered on any of these cloud platforms",maxItems:_n.length}),cloudAccounts:_e(u({allowEmpty:!1}),{description:"Restrict results to resources in any of these cloud accounts",maxItems:500}),cloudRegions:_e(u({allowEmpty:!1}),{description:"Restrict results to resources in any of these cloud regions",maxItems:500}),nativeResourceTypes:_e(r.Enum(ks),{description:"Restrict results to resources of any of these cloud-native resource types",maxItems:ks.length}),resourceTypes:_e(r.Enum(sl),{description:"Restrict results to resources of any of these normalized resource types",maxItems:sl.length}),tags:_e(Bt.items,{description:"Restrict results to resources that have at least one of the listed key/value tags",maxItems:50}),isIacManaged:r.Boolean({description:"Restrict results by infrastructure-as-code coverage. When true, only resources covered by the configured IaC identifiers are returned; when false, only uncovered resources are returned."}),searchQuery:r.Object({value:u({allowEmpty:!1,description:"Case-insensitive substring matched against resource ID, display name, fully-qualified resource ID, cloud account, region, and resource type. Use the `tags` filter to narrow by tag. Wildcard characters are treated literally."}),exclude:r.Optional(r.Boolean({description:"If true, exclude resources matching this value instead of including them"}))},{description:"Search query filter for resources."})},{description:"Optional filters applied to narrow the returned resources"}),Kg=r.Partial(r.Object({...fe,filters:r.Partial(vv,{description:"Filters applied to narrow the returned resources."}),sort:r.Object({by:r.Enum([Wi.DISPLAY_NAME,Wi.CLOUD_ACCOUNT,Wi.NATIVE_RESOURCE_TYPE,Wi.CLOUD_REGION,Wi.RESOURCE_TYPE,Wi.RESOURCE_CREATED_AT],{description:"Field to sort the returned resources by"}),direction:r.Enum(["asc","desc"],{description:"Sort direction: ascending or descending"})},{description:"Optional sorting applied to the returned resources. Ties are broken by resource ID for stable pagination."})})),CZe=d({tags:["inventory"],method:"POST",url:`${Ao}/resources/query`,paginated:!0,body:Kg,response:r.Array(r.Intersect([Hg,cl]))}),UY=["resourceType","cloudAccount","isIacManaged"],PZe=d({tags:["inventory"],method:"POST",url:`${Ao}/resources/counts`,body:r.Object({filters:r.Optional(r.Partial(vv)),groupBy:r.Enum(UY,{description:"Dimension to group the resource counts by."})}),response:r.Array(r.Object({value:r.String({description:'The group value the count belongs to: a resource type, a cloud account id, or "true"/"false" for IaC coverage.'}),count:r.Integer({description:"Number of resources in this group matching the requested filters."})}))}),UZe=d({tags:["inventory"],method:"GET",url:`${Ao}/resources/filter-options`,response:r.Object({cloudRegions:r.Array(r.String(),{description:"Distinct cloud regions present across the tenant's resources."}),nativeResourceTypes:r.Array(r.String(),{description:"Distinct cloud-native resource types present across the tenant's resources."}),tags:Ft})}),wZe=C("type",[r.Object({type:r.Literal("aws",{description:"Discriminator identifying AWS connection settings."}),accountId:r.String({description:"AWS account ID that Tsuga scans."}),externalId:r.String({description:"External ID Tsuga passes when assuming the cross-account IAM role."}),roleArn:r.String({description:"ARN of the IAM role Tsuga assumes to read inventory in the account."})}),r.Object({type:r.Literal("gcp",{description:"Discriminator identifying GCP connection settings."}),projectId:r.String({description:"GCP project ID that Tsuga scans."}),serviceAccountId:r.String({description:"Service account Tsuga impersonates to read inventory."}),workloadIdentityProvider:r.String({description:"Workload identity provider resource name used for federated authentication."})}),r.Object({type:r.Literal("azure",{description:"Discriminator identifying Azure connection settings."}),clientId:r.String({description:"Client ID of the Azure application Tsuga authenticates as."}),subscriptionId:r.String({description:"Azure subscription ID that Tsuga scans."}),tenantId:r.String({description:"Azure tenant ID that owns the subscription."})})]),wY="^[0-9]{12}$",vY="^arn:aws[a-z-]*:iam::[0-9]{12}:role/.+$",NY="^[a-z][a-z0-9-]{4,28}[a-z0-9]$",LY="^[^@\\s]+@[^@\\s]+\\.iam\\.gserviceaccount\\.com$",kY="^//iam\\.googleapis\\.com/projects/[0-9]+/locations/global/workloadIdentityPools/[^/]+/providers/[^/]+$",Bg="^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$",MY=r.Object({type:r.Literal("aws",{description:"Discriminator identifying AWS connection settings."}),accountId:r.String({pattern:wY,description:"AWS account ID that Tsuga scans.",errorMessage:{pattern:"Must be a 12-digit AWS account ID."}}),externalId:u({allowEmpty:!1,description:"External ID Tsuga passes when assuming the cross-account IAM role."}),roleArn:r.String({pattern:vY,minLength:1,maxLength:2048,description:"ARN of the IAM role Tsuga assumes to read inventory in the account.",errorMessage:{pattern:"Must be an IAM role ARN, e.g. arn:aws:iam::123456789012:role/MyRole."}})},{$id:"AwsConnectionSettings"}),DY=r.Object({type:r.Literal("gcp",{description:"Discriminator identifying GCP connection settings."}),projectId:r.String({pattern:NY,minLength:6,maxLength:30,description:"GCP project ID that Tsuga scans.",errorMessage:{pattern:"Must be a GCP project ID (6-30 chars: lowercase letters, digits, hyphens)."}}),serviceAccountId:r.String({pattern:LY,minLength:1,maxLength:128,description:"Service account Tsuga impersonates to read inventory.",errorMessage:{pattern:"Must be a service account email, e.g. name@project.iam.gserviceaccount.com."}}),workloadIdentityProvider:r.String({pattern:kY,minLength:1,maxLength:256,description:"Full resource name of the workload identity provider used for federated authentication, e.g. //iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider.",errorMessage:{pattern:"Must be the full provider resource name: //iam.googleapis.com/projects/<PROJECT_NUMBER>/locations/global/workloadIdentityPools/<POOL_ID>/providers/<PROVIDER_ID>."}})},{$id:"GcpConnectionSettings"}),GY=r.Object({type:r.Literal("azure",{description:"Discriminator identifying Azure connection settings."}),clientId:r.String({pattern:Bg,minLength:1,description:"Client ID of the Azure application Tsuga authenticates as (GUID).",errorMessage:{pattern:"Must be a GUID."}}),subscriptionId:r.String({pattern:Bg,minLength:1,description:"Azure subscription ID that Tsuga scans (GUID).",errorMessage:{pattern:"Must be a GUID."}}),tenantId:r.String({pattern:Bg,minLength:1,description:"Azure tenant ID that owns the subscription (GUID).",errorMessage:{pattern:"Must be a GUID."}})},{$id:"AzureConnectionSettings"}),Nv=C("type",[MY,DY,GY],{description:"Credentials Tsuga uses to scan the account, in the provider-specific shape selected by `type`. Credentials are stored as provided and are not validated at creation time; failures surface through `lastScanStatus`."}),Zi=r.Object({id:r.String({description:"Identifier of the cloud account. Generated by Tsuga."}),cloudType:r.Enum(_n,{description:"Cloud provider of the account."}),cloudAccountId:r.String({description:"Cloud-native account identifier: an AWS account ID, GCP project ID, or Azure subscription ID."}),accountFriendlyName:r.Optional(r.String({description:"Human-readable name for the account shown in Tsuga."})),organizationId:r.Optional(r.String({description:"Cloud organization identifier, when known."})),createdBy:r.Optional(r.String({description:"Identifier of the user who created the account, when created by a user."})),createdAt:A({description:"Timestamp when the account was registered in Tsuga."}),lastScanStartedAt:r.Optional(A({description:"Timestamp when the most recent inventory scan started."})),lastScanFinishedAt:r.Optional(A({description:"Timestamp when the most recent inventory scan finished."})),lastScanStatus:r.Optional(r.Enum(wv,{description:"Status of the most recent inventory scan."}))}),zg=r.Object({cloudType:r.Enum(_n,{description:"Cloud provider of the account."}),cloudAccountId:u({allowEmpty:!1,description:"Cloud-native account identifier: an AWS account ID, GCP project ID, or Azure subscription ID."}),accountFriendlyName:r.Optional(u({description:"Human-readable name for the account shown in Tsuga."})),organizationId:r.Optional(u({description:"Cloud organization identifier, when known."})),connectionSettings:Nv,lastScanStatus:r.Optional(r.Enum(wv,{description:"Status of the most recent inventory scan."}))}),Oo=`${Ao}/cloud-accounts`,vZe=d({tags:["inventory"],url:Oo,method:"GET",response:r.Array(Zi)}),NZe=d({tags:["inventory"],url:`${Oo}/:id`,method:"GET",params:r.Object({id:u()}),response:Zi}),LZe=d({tags:["inventory"],url:Oo,method:"POST",body:zg,response:Zi}),Yg=r.Object({accountFriendlyName:u({description:"Human-readable name for the account shown in Tsuga."})}),kZe=d({tags:["inventory"],url:`${Oo}/:id`,method:"PUT",params:r.Object({id:u()}),body:Yg,response:Zi}),MZe=d({tags:["inventory"],url:`${Oo}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),DZe=d({tags:["inventory"],url:`${Ao}/trigger-scan`,method:"POST",body:r.Object({}),response:r.Object({success:r.Literal(!0)})}),GZe=d({tags:["inventory"],url:`${Oo}/azure/onboarding`,method:"POST",body:r.Object({tenantId:u()}),response:r.Object({subjectId:r.String(),audience:r.String()})}),$Ze=d({tags:["inventory"],method:"POST",url:`${Oo}/validate/:type`,params:r.Object({type:u()}),body:r.Object({data:Nv,id:r.Optional(u())}),response:r.Object({areAccountSettingsValid:r.Boolean(),message:r.Optional(r.String())})}),Lv=`${Ao}/settings`,jZe=d({tags:["inventory"],url:Lv,method:"GET",response:r.Object({settings:r.Optional(r.Object({id:r.String(),infrastructureIdentifiers:r.Array(r.Object({name:r.String(),value:r.Optional(r.String())}))}))})}),$Y=50,qZe=d({tags:["inventory"],url:Lv,method:"POST",body:r.Object({infrastructureIdentifiers:r.Array(r.Object({name:u({allowEmpty:!1}),value:r.Optional(u({allowEmpty:!1}))}),{maxItems:$Y})}),response:r.Object({})}),FZe=d({tags:["inventory"],url:`${Ao}/iac-tags-proposal`,method:"GET",response:r.Array(r.Object({name:r.String(),value:r.Optional(r.String())}))});var kv=`/${"v1"}/inventory`,jY=r.Omit(Hg,["nativeAttributes","covered"],{$id:"InventoryResourceBase",description:"Base fields shared by cloud resources discovered during inventory scans. Public inventory resources omit raw provider-native attributes and infrastructure-as-code coverage fields. See [Cloud resources](/documentation/categorize/cloud-resources)."}),Mv=r.Intersect([jY,cl],{$id:"InventoryResource",description:"Cloud resource discovered by an inventory scan, together with normalized category, resource type, and public category-specific attributes. See [Cloud resources](/documentation/categorize/cloud-resources)."}),qY={id:"123-456-abc",cloudPlatform:"aws",cloudAccount:"123456789012",cloudRegion:"us-east-1",fullyQualifiedResourceId:"arn:aws:s3:::tsuga-example-bucket",displayName:"tsuga-example-bucket",nativeResourceType:"aws_s3_bucket",resourceCreatedAt:"2024-01-01T08:00:00.000Z",resourceLastSeenAt:"2024-01-15T12:34:56.000Z",tags:[{key:"team",value:"platform"}],category:"data",resourceType:"bucket",attributes:{versioningStatus:"Enabled"}};Object.assign(Mv,{examples:[qY]});var Dv=r.Object({...Kg.properties,...Ze},{description:"Inventory resource query request. Use filters, sorting, limit, and offset to page through discovered resources."}),FY={filters:{cloudPlatforms:{values:["aws"]},cloudAccounts:{values:["123456789012"]},cloudRegions:{values:["us-east-1"]},resourceTypes:{values:["bucket"]},nativeResourceTypes:{values:["aws_s3_bucket"]},tags:{values:[{key:"team",value:"platform"}]},isIacManaged:!0,searchQuery:{value:"tsuga-example"}},sort:{by:"displayName",direction:"asc"},limit:10,offset:0};Object.assign(Dv,{examples:[FY]});var Gv=d({description:"Queries cloud resources discovered by inventory scans, with optional filters, sorting, and pagination. Use this endpoint to build infrastructure inventories across connected cloud accounts.",operationId:"queryInventoryResources",tags:["inventory"],url:`${kv}/resources/query`,method:"POST",paginated:!0,body:Dv,response:r.Array(Mv)}),Ms=`${kv}/cloud-accounts`,Ds=r.Pick(Zi,["id","cloudType","cloudAccountId","accountFriendlyName"],{$id:"CloudAccount"}),BY={id:"123-456-abc",cloudType:"aws",cloudAccountId:"123456789012",accountFriendlyName:"Production AWS"};Object.assign(Ds,{examples:[BY]});var $v=r.Pick(zg,["cloudType","cloudAccountId","accountFriendlyName","connectionSettings"]),HY={cloudType:"aws",cloudAccountId:"123456789012",accountFriendlyName:"Production AWS",connectionSettings:{type:"aws",accountId:"123456789012",externalId:"tsuga-external-id",roleArn:"arn:aws:iam::123456789012:role/tsuga-inventory"}};Object.assign($v,{examples:[HY]});var KY=r.Pick(Yg,["accountFriendlyName"]),ZZe=d({description:"Lists cloud accounts connected to Tsuga that the authenticated operation key can read.",operationId:"listCloudAccounts",tags:["inventory"],url:Ms,method:"GET",response:r.Array(Ds)}),XZe=d({description:"Retrieves one cloud account by ID.",operationId:"getCloudAccount",tags:["inventory"],url:`${Ms}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the cloud account to retrieve. Use the `id` returned by the cloud account list or create operations."})}),response:Ds}),JZe=d({description:"Registers a cloud account for inventory scanning. Connection settings are stored as provided and are not validated at creation time; scan failures surface through `lastScanStatus`.",operationId:"createCloudAccount",tags:["inventory"],url:Ms,method:"POST",body:$v,response:Ds}),eXe=d({description:"Updates the friendly name of a cloud account by ID.",operationId:"updateCloudAccount",tags:["inventory"],url:`${Ms}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the cloud account to update. Use the `id` returned by the cloud account list or create operations."})}),body:KY,response:Ds}),tXe=d({description:"Deletes a cloud account by ID. Future inventory scans stop for the account, and the trust relationship on the cloud side can be safely removed afterward.",operationId:"deleteCloudAccount",tags:["inventory"],url:`${Ms}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the cloud account to delete. Use the `id` returned by the cloud account list or create operations."})}),response:N});var Gs="/v0/investigations",zY=["dashboard","monitor","service","slo","log-route","adaptive-notification-rule"],YY=r.Object({type:r.String({description:'Kind of linked asset, e.g. "dashboard"'}),id:r.String({description:"Identifier of the linked asset"})}),VY=r.Object({type:r.Enum(zY,{description:"Kind of linked asset"}),id:u({allowEmpty:!1,description:"Identifier of the linked asset"})}),Xr=r.Object({id:r.String({description:"Identifier of the investigation"}),name:r.String({description:"Human readable name shown for the investigation"}),slug:r.Optional(r.String({description:'Immutable identifier supplied by the creating agent, e.g. "incident-2024-06-payments-5xx". Set once at creation and matched against the agent telemetry to link back to the run that created the investigation.'})),contentMd:r.Optional(r.String({description:"Markdown content capturing the investigation notes and findings"})),tags:De,owner:r.String({description:"Team ID owning the investigation"}),env:r.Optional(r.String({description:'Environment the investigation relates to, e.g. "prod"'})),linkedAssets:r.Array(YY,{description:"Assets (dashboards, monitors, \u2026) referenced by this investigation"}),creator:r.Optional(pe),updater:r.Optional(pe),createdAt:A({description:"Timestamp the investigation was created at."}),updatedAt:A({description:"Timestamp the investigation was last updated at."})},{title:"Investigation"}),pl=r.Object({name:u({allowEmpty:!1,description:"Human readable name shown for the investigation"}),slug:u({type:"kebab-case",allowEmpty:!1,description:'Immutable, unique identifier supplied by the creating agent, used to link the investigation back to the agent run, e.g. "incident-2024-06-payments-5xx". The agent should also emit this value in its telemetry.'}),contentMd:r.Optional(u({type:"long",description:"Markdown content capturing the investigation notes and findings"})),tags:Xe,owner:u({allowEmpty:!1,description:"Team ID owning the investigation"}),env:r.Optional(u({allowEmpty:!0,description:"Environment the investigation relates to"})),linkedAssets:r.Optional(r.Array(VY,{maxItems:100,description:"Assets (dashboards, monitors, \u2026) referenced by this investigation"}))}),Vg=r.Object(r.Omit(pl,["slug"]).properties),pXe=d({tags:["investigations"],url:Gs,method:"GET",paginated:!0,query:r.Object(fe),response:r.Array(Xr)}),uXe=d({tags:["investigations"],url:`${Gs}/:id`,params:r.Object({id:u()}),method:"GET",response:Xr}),lXe=d({tags:["investigations"],url:Gs,method:"POST",body:pl,response:Xr}),mXe=d({tags:["investigations"],url:`${Gs}/:id`,method:"PUT",body:Vg,params:r.Object({id:u()}),response:Xr}),dXe=d({tags:["investigations"],url:`${Gs}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N});var $s=`/${"v1"}/investigations`,jv=d({description:"Retrieve all investigations",tags:["private"],url:$s,method:"GET",paginated:!0,query:r.Object(Ze),response:r.Array(Xr)}),qv=d({description:"Retrieve an investigation by its id",tags:["private"],url:`${$s}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1})}),response:Xr}),Fv=d({description:"Create a new investigation",tags:["private"],url:$s,method:"POST",body:pl,response:Xr}),Bv=d({description:"Update an investigation by its id",tags:["private"],url:`${$s}/:id`,method:"PUT",body:Vg,params:r.Object({id:u({allowEmpty:!1})}),response:Xr}),Hv=d({description:"Delete an investigation by its id",tags:["private"],url:`${$s}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1})}),response:N});var Kv=15,ul={id:r.String({description:"Unique identifier of the processor within the route. Used to preserve processor identity during updates."}),description:r.Optional(r.String({description:"Optional user-provided processor note."})),tags:De,updatedAt:r.Optional(A({description:"Timestamp when Tsuga last updated the processor."}))},ll={id:u({allowEmpty:!1,description:"Unique identifier of the processor within the route. Preserve it across updates for existing processors."}),description:r.Optional(u({type:"long",description:"Optional processor note."})),tags:Xe,updatedAt:r.Optional(A({description:"Backend-maintained timestamp for this processor. Omit this field on create and update requests; Tsuga sets or preserves it based on processor changes."}))},zv={...ul,type:r.Literal("creator",{description:"Create processor. It writes a new attribute from a format string, formula, or category rule."})},Yv={...ll,type:r.Literal("creator",{description:"Create processor. It writes a new attribute from a format string, formula, or category rule."})},QY=C("subtype",[r.Object({targetAttribute:r.String({description:"Attribute that will receive the formatted value"}),formatString:r.String({description:"Template string used to build the target attribute value"}),overrideTarget:r.Optional(r.Boolean({description:"Whether to overwrite the target attribute when it already exists. If omitted, route processing treats this as true."})),subtype:r.Literal("format-string",{description:"Builds a string from literal text and existing attribute values."}),replaceMissingByEmpty:r.Optional(r.Boolean({description:"Whether missing referenced attributes render as empty strings. If omitted, route processing treats this as true."}))},{$id:"ProcessorParamsCreatorFormatString"}),r.Object({targetAttribute:r.String({description:"Attribute that will receive the computed value"}),formula:r.String({description:"Mathematical formula evaluated to populate the target attribute"}),overrideTarget:r.Optional(r.Boolean({description:"Whether to overwrite the target attribute when it already exists. If omitted, route processing treats this as true."})),subtype:r.Literal("math-formula",{description:"Evaluates a mathematical expression and writes the numeric result."}),replaceMissingBy0:r.Optional(r.Boolean({description:"Whether missing referenced attributes evaluate as zero. If omitted, route processing treats this as true."}))},{$id:"ProcessorParamsCreatorMathFormula"}),r.Object({targetAttribute:r.String({description:"Attribute that will receive the category value"}),clauses:r.Array(r.Object({query:r.String({description:"Query that selects logs for this category clause. Clauses are evaluated in order."}),value:r.String({description:"String category value assigned when this clause matches."})}),{description:"Conditions evaluated in order to determine the category value. The first matching clause wins."}),defaultValue:r.Optional(r.String({description:"String category value used when no clause matches. If omitted and no clause matches, no category value is written."})),subtype:r.Literal("category",{description:"Assigns the first matching category value from ordered query clauses, with an optional default."})},{$id:"ProcessorParamsCreatorCategory"})],{description:"Create processor configuration. The `subtype` discriminator selects how the value written to `targetAttribute` is built and which fields are required."}),WY=C("subtype",[r.Object({targetAttribute:u({allowEmpty:!1,description:"Attribute that will receive the formatted value"}),formatString:u({allowEmpty:!1,type:"long",description:"Template string used to build the target attribute value"}),overrideTarget:r.Optional(r.Boolean({description:"Set to true to overwrite an existing target attribute value (defaults to true)"})),subtype:r.Literal("format-string",{description:"Builds a string from literal text and existing attribute values."}),replaceMissingByEmpty:r.Optional(r.Boolean({description:"Set to true for missing referenced attributes to render as empty strings. Defaults to true."}))},{$id:"InputProcessorParamsCreatorFormatString"}),r.Object({targetAttribute:u({allowEmpty:!1,description:"Attribute that will receive the computed value"}),formula:u({allowEmpty:!1,type:"long",description:"Mathematical formula evaluated to populate the target attribute"}),overrideTarget:r.Optional(r.Boolean({description:"Set to true to overwrite an existing target attribute value (defaults to true)"})),subtype:r.Literal("math-formula",{description:"Evaluates a mathematical expression and writes the numeric result."}),replaceMissingBy0:r.Optional(r.Boolean({description:"Set to true for missing referenced attributes to evaluate as zero. Defaults to true."}))},{$id:"InputProcessorParamsCreatorMathFormula"}),r.Object({targetAttribute:u({allowEmpty:!1,description:"Attribute that will receive the category value"}),clauses:r.Array(r.Object({query:u({allowEmpty:!1,type:"tsuga-query",description:"Query that selects logs for this category clause. Clauses are evaluated in order."}),value:u({allowEmpty:!1,description:"String category value assigned when this clause matches."})}),{minItems:1,maxItems:Kv,description:"Conditions evaluated in order to determine the category value. The first matching clause wins."}),defaultValue:r.Optional(u({description:"String category value used when no clause matches. If omitted and no clause matches, no category value is written."})),subtype:r.Literal("category",{description:"Assigns the first matching category value from ordered query clauses, with an optional default."})},{$id:"InputProcessorParamsCreatorCategory"})],{description:"Create processor configuration. The `subtype` discriminator selects how the value written to `targetAttribute` is built and which fields are required."}),ZY=r.Object({...zv,params:QY}),XY=r.Object({...Yv,params:WY}),Vv={...ul,type:r.Literal("mapper",{description:"Map processor. It moves, copies, or normalizes existing log attributes."})},Qv={...ll,type:r.Literal("mapper",{description:"Map processor. It moves, copies, or normalizes existing log attributes."})},JY=C("subtype",[r.Object({attributes:r.Array(r.Object({originAttribute:r.String({description:"Attribute name to map to the target attribute"}),keepOrigin:r.Optional(r.Boolean({description:"Whether the source attribute is preserved after mapping. If omitted, route processing treats this as false."})),overrideTarget:r.Optional(r.Boolean({description:"Whether to overwrite the target attribute when it already exists. If omitted, route processing treats this as true."})),targetAttribute:r.String({description:"Attribute name that will receive the mapped value"})}),{description:"Mappings that map individual attributes to new targets"}),subtype:r.Literal("map-attributes",{description:"Copies or moves one or more source attributes to target attributes."})},{$id:"ProcessorParamsMapperMapAttributes"}),r.Object({attributeName:r.String({description:"Attribute whose value will determine the log level"}),subtype:r.Literal("map-level",{description:"Normalizes a severity or status attribute into Tsuga log levels."})},{$id:"ProcessorParamsMapperMapLevel"}),r.Object({attributeName:r.String({description:"Attribute whose value will determine the log timestamp"}),subtype:r.Literal("map-timestamp",{description:"Uses an event-time attribute as the log timestamp."})},{$id:"ProcessorParamsMapperMapTimestamp"})],{description:"Map processor configuration. The `subtype` discriminator selects whether existing attributes are copied or moved to new names, or used to set the log level or timestamp."}),e9=C("subtype",[r.Object({attributes:r.Array(r.Object({originAttribute:u({allowEmpty:!1,description:"Attribute name to map to the target attribute"}),keepOrigin:r.Optional(r.Boolean({description:"Preserve the source attribute after mapping (defaults to false)"})),overrideTarget:r.Optional(r.Boolean({description:"Overwrite the target attribute when it already exists (defaults to true)"})),targetAttribute:u({allowEmpty:!1,description:"Attribute name that will receive the mapped value"})}),{minItems:1,maxItems:50,description:"Mappings that map individual attributes to new targets"}),subtype:r.Literal("map-attributes",{description:"Copies or moves one or more source attributes to target attributes."})},{$id:"InputProcessorParamsMapperMapAttributes"}),r.Object({attributeName:u({allowEmpty:!1,description:"Attribute whose value will determine the log level"}),subtype:r.Literal("map-level",{description:"Normalizes a severity or status attribute into Tsuga log levels."})},{$id:"InputProcessorParamsMapperMapLevel"}),r.Object({attributeName:u({allowEmpty:!1,description:"Attribute whose value will determine the log timestamp"}),subtype:r.Literal("map-timestamp",{description:"Uses an event-time attribute as the log timestamp."})},{$id:"InputProcessorParamsMapperMapTimestamp"})],{description:"Map processor configuration. The `subtype` discriminator selects whether existing attributes are copied or moved to new names, or used to set the log level or timestamp."}),t9=r.Object({...Qv,params:e9}),r9=r.Object({...Vv,params:JY}),Wv={...ul,type:r.Literal("parse-attribute",{description:"Parse processor. It extracts structured fields from a text attribute."})},Zv={...ll,type:r.Literal("parse-attribute",{description:"Parse processor. It extracts structured fields from a text attribute."})},Xv=5,n9=C("subtype",[r.Object({attributeName:r.String({description:"Attribute whose value will be parsed with Grok rules"}),rules:r.Array(r.String({description:"Grok rule applied to parse text. Route processing sends rules as engine patterns."}),{description:"Ordered Grok rules evaluated until one matches."}),samples:r.Optional(r.Array(r.String(),{description:"Example log lines for validating the Grok rules. Samples are not sent to the ingestion engine."})),subtype:r.Literal("grok",{description:"Extracts fields from unstructured text using ordered Grok rules."})}),r.Object({sourceAttribute:r.String({description:"Attribute containing the URL to parse"}),subtype:r.Literal("url",{description:"Parses a URL attribute and writes URL detail fields."})}),r.Object({sourceAttribute:r.String({description:"Attribute containing the user agent string to parse"}),subtype:r.Literal("user-agent",{description:"Parses a user-agent string and writes browser, operating system, and device details."})}),r.Object({sourceAttribute:r.String({description:"Attribute containing the key/value string segment to parse"}),targetAttribute:r.String({description:"Target map attribute where extracted key/value pairs will be written"}),keyValueSplitter:r.String({description:"Delimiter separating keys from values in the source string"}),pairsSplitter:r.String({description:"Delimiter separating each key/value pair in the source string."}),acceptStandaloneKey:r.Boolean({description:"Whether keys without explicit values are accepted by the parser."}),subtype:r.Literal("key-value",{description:"Parses delimited key/value text into attributes."})})],{description:"Parse processor configuration. The `subtype` discriminator selects which parser reads the source text attribute and which fields it extracts."}),o9=C("subtype",[r.Object({attributeName:u({allowEmpty:!1,description:"Attribute whose value will be parsed with Grok rules"}),rules:r.Array(u({allowEmpty:!1,type:"long",description:"Grok rule applied to parse text. Route processing sends rules as engine patterns."}),{minItems:1,maxItems:5,description:"Ordered Grok rules evaluated until one matches."}),samples:r.Optional(r.Array(u({type:"long"}),{maxItems:Xv,description:"Example log lines for validating the Grok rules. Samples are not sent to the ingestion engine."})),subtype:r.Literal("grok",{description:"Extracts fields from unstructured text using ordered Grok rules."})}),r.Object({sourceAttribute:u({allowEmpty:!1,description:"Attribute containing the URL to parse"}),subtype:r.Literal("url",{description:"Parses a URL attribute and writes URL detail fields."})}),r.Object({sourceAttribute:u({allowEmpty:!1,description:"Attribute containing the user agent string to parse"}),subtype:r.Literal("user-agent",{description:"Parses a user-agent string and writes browser, operating system, and device details."})}),r.Object({sourceAttribute:u({allowEmpty:!1,description:"Attribute containing the key/value string segment to parse"}),targetAttribute:u({description:"Target map attribute where extracted key/value pairs will be written"}),keyValueSplitter:u({allowEmpty:!1,description:"Delimiter separating keys from values in the source string"}),pairsSplitter:u({allowEmpty:!0,description:"Delimiter separating each key/value pair in the source string."}),acceptStandaloneKey:r.Boolean({description:"Set to true to accept keys without explicit values."}),subtype:r.Literal("key-value",{description:"Parses delimited key/value text into attributes."})})],{description:"Parse processor configuration. The `subtype` discriminator selects which parser reads the source text attribute and which fields it extracts."}),i9=r.Object({...Wv,params:n9}),a9=r.Object({...Zv,params:o9}),s9=r.Object({...Yv,params:C("subtype",[r.Object({targetAttribute:u({allowEmpty:!1,description:"Attribute that will receive the formatted value"}),formatString:u({allowEmpty:!1,type:"long",description:"Template string used to build the target attribute value"}),overrideTarget:r.Optional(r.Boolean({description:"Set to true to overwrite an existing target attribute value (defaults to true)"})),subtype:r.Literal("format-string"),replaceMissingByEmpty:r.Optional(r.Boolean({description:"Set to true for missing referenced attributes to render as empty strings. Defaults to true."}))}),r.Object({targetAttribute:u({allowEmpty:!1,description:"Attribute that will receive the category value"}),clauses:r.Array(r.Object({query:u({allowEmpty:!1,type:"tsuga-query",description:"Query that selects logs for this category clause. Clauses are evaluated in order."}),value:u({allowEmpty:!1,description:"String category value assigned when this clause matches."})}),{minItems:1,maxItems:Kv,description:"Conditions evaluated in order to determine the category value. The first matching clause wins."}),defaultValue:r.Optional(u({description:"String category value used when no clause matches."})),subtype:r.Literal("category")})])}),c9=r.Object({...Qv,params:r.Object({attributes:r.Array(r.Object({originAttribute:u({allowEmpty:!1,description:"Attribute name to map to the target attribute"}),keepOrigin:r.Optional(r.Boolean({description:"Preserve the source attribute after mapping (defaults to false)"})),overrideTarget:r.Optional(r.Boolean({description:"Overwrite the target attribute when it already exists (defaults to true)"})),targetAttribute:u({allowEmpty:!1,description:"Attribute name that will receive the mapped value"})}),{minItems:1,maxItems:50,description:"Mappings that map individual attributes to new targets"}),subtype:r.Literal("map-attributes")})}),p9=r.Object({...Zv,params:r.Object({attributeName:u({allowEmpty:!1,description:"Attribute whose value will be parsed with Grok rules"}),rules:r.Array(u({allowEmpty:!1,type:"long",description:"Grok rule applied to parse text. Route processing sends rules as engine patterns."}),{minItems:1,maxItems:5,description:"Ordered Grok rules evaluated until one matches."}),samples:r.Optional(r.Array(u({type:"long"}),{maxItems:Xv,description:"Example log lines for validating the Grok rules."})),subtype:r.Literal("grok")})}),xXe=C("type",[c9,p9,s9]),u9=r.Object({...zv,params:C("subtype",[r.Object({targetAttribute:r.String({description:"Attribute that will receive the formatted value"}),formatString:r.String({description:"Template string used to build the target attribute value"}),overrideTarget:r.Optional(r.Boolean({description:"Whether to overwrite the target attribute when it already exists."})),subtype:r.Literal("format-string"),replaceMissingByEmpty:r.Optional(r.Boolean({description:"Whether missing referenced attributes render as empty strings."}))}),r.Object({targetAttribute:r.String({description:"Attribute that will receive the category value"}),clauses:r.Array(r.Object({query:r.String({description:"Query that selects logs for this category clause."}),value:r.String({description:"String category value assigned when this clause matches."})}),{description:"Conditions evaluated in order to determine the category value."}),defaultValue:r.Optional(r.String({description:"String category value used when no clause matches."})),subtype:r.Literal("category")})])}),l9=r.Object({...Vv,params:r.Object({attributes:r.Array(r.Object({originAttribute:r.String({description:"Attribute name to map to the target attribute"}),keepOrigin:r.Optional(r.Boolean({description:"Whether the source attribute is preserved after mapping."})),overrideTarget:r.Optional(r.Boolean({description:"Whether to overwrite the target attribute when it already exists."})),targetAttribute:r.String({description:"Attribute name that will receive the mapped value"})}),{description:"Mappings that map individual attributes to new targets"}),subtype:r.Literal("map-attributes")})}),m9=r.Object({...Wv,params:r.Object({attributeName:r.String({description:"Attribute whose value will be parsed with Grok rules"}),rules:r.Array(r.String({description:"Grok rule applied to parse text."}),{description:"Ordered Grok rules evaluated until one matches."}),samples:r.Optional(r.Array(r.String(),{description:"Example log lines for validating the Grok rules."})),subtype:r.Literal("grok")})}),RXe=C("type",[l9,m9,u9]),d9=11,Jv=r.Cyclic({OutputProcessor:r.Union([r9,i9,ZY,r.Object({...ul,params:r.Object({items:r.Array(r.Object({query:r.String({description:"Query that determines whether logs enter this branch"}),processors:r.Array(r.Ref("OutputProcessor"),{description:"Processors executed when the branch query matches"})}),{description:"Conditional branches evaluated in order before falling back to the default"})}),type:r.Literal("split",{description:"Split processor. It sends each log through the first matching conditional branch."})})])},"OutputProcessor",{description:"Processing step executed sequentially on route logs"}),eN=r.Cyclic({InputProcessor:r.Union([t9,a9,XY,r.Object({...ll,params:r.Object({items:r.Array(r.Object({query:u({type:"tsuga-query",description:"Query that determines whether logs enter this branch"}),processors:r.Array(r.Ref("InputProcessor"),{maxItems:50,description:"Processors executed when the branch query matches"})}),{minItems:2,maxItems:d9,description:"Conditional branches evaluated in order before falling back to the default"})}),type:r.Literal("split",{description:"Split processor. It sends each log through the first matching conditional branch."})})])},"InputProcessor",{description:"Processing step executed sequentially on route logs"});var f9="/v0/logs",vn=`${f9}/routes`,Nn=r.Object({id:r.String({description:"Tsuga-generated log route ID assigned when the route is created."}),name:r.String({description:"Human-readable route name shown in Tsuga."}),description:r.Optional(r.String({description:"Optional free-text note about the route's purpose, set by the caller. This metadata is not evaluated when matching or processing logs."})),isEnabled:r.Boolean({description:"Whether this route is active for newly ingested logs. Disabled routes remain saved but do not process logs."}),query:r.String({description:"Tsuga query that selects which newly ingested logs enter the route processor chain."}),rank:r.Number({description:"Tsuga-assigned evaluation order, unique across all routes and dense (no gaps). Enabled routes are checked from lower rank to higher rank during ingestion, and every route whose query matches a log applies its processors to it \u2014 matching is not stopped after the first hit. New routes are appended with the highest rank; deleting a route shifts all higher ranks down by one to close the gap. Use `PUT /:id/modify-ranking` to move a route to a different rank, which shifts the routes between its old and new position accordingly."}),tags:De,owner:r.String({description:"ID of the team that owns the route. Determines which team members can view and manage it, and which tag policies apply to it. Only an org admin or an admin of this team may change the `query` field or delete the route."}),processors:r.Array(Jv,{description:"Processors applied in array order to logs that match the route, each transforming the output of the previous one. A `split` processor forks the chain into branches and cannot be followed by another processor at the same level."}),creator:r.Optional(pe),updater:r.Optional(pe),updatedAt:A({description:"Timestamp when Tsuga last updated the route."}),createdAt:A({description:"Timestamp when Tsuga created the route."}),assetUpdatedAt:A({description:"Timestamp when Tsuga last changed route behavior. This can differ from `updatedAt` when only metadata such as `description` or `tags` changed."})},{title:"LogRoute"}),js=r.Object({name:u({allowEmpty:!1,description:"Human-readable log route name shown in Tsuga."}),description:r.Optional(u({type:"long",description:"Optional free-text note about the log route's purpose. This metadata is not evaluated when matching or processing logs."})),isEnabled:r.Boolean({description:"Set to true for the log route to process newly ingested matching logs. Set to false to save it without running it."}),query:u({type:"tsuga-query",description:"Tsuga query that selects which newly ingested logs enter the log route processor chain."}),tags:Xe,owner:u({allowEmpty:!1,description:"ID of the team that will own the log route, determining which team members can view and manage it and which tag policies apply. Only an org admin or an admin of this team may change the `query` field or delete the log route."}),processors:r.Array(eN,{maxItems:50,description:"Processors applied in array order to logs that match the log route, each transforming the output of the previous one. Up to 50 are accepted. A `split` processor forks the chain into branches and cannot be followed by another processor at the same level."})});var MXe=d({tags:["routes"],url:vn,method:"GET",paginated:!0,query:r.Object(fe),response:r.Array(Nn)}),DXe=d({tags:["routes"],url:`${vn}/:id`,params:r.Object({id:u()}),method:"GET",response:Nn}),GXe=d({tags:["routes"],url:vn,method:"POST",body:js,response:Nn}),$Xe=d({tags:["routes"],url:`${vn}/:id`,method:"PUT",body:js,params:r.Object({id:u()}),response:Nn}),jXe=d({tags:["routes"],url:`${vn}/:id/clone`,method:"POST",params:r.Object({id:u()}),body:js,response:Nn}),qXe=d({tags:["routes"],url:`${vn}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),FXe=d({description:"Moves a route to a new rank, shifting the ranks of the routes between its old and new position by one to keep ranks dense and unique. Affects the route's evaluation order for newly ingested logs; does not change any route's processors or other fields.",tags:["routes"],url:`${vn}/:id/modify-ranking`,method:"PUT",params:r.Object({id:u()}),body:r.Object({rank:r.Integer({minimum:1,description:"Target rank for the route, from 1 to the total number of routes. Requests outside that range are rejected."})}),response:r.Object({})}),BXe=d({description:"Sets a route's `isEnabled` state without changing any other field. Disabling a route stops it from processing newly ingested logs while keeping it saved and its rank unchanged.",tags:["routes"],url:`${vn}/:id/enable`,method:"PUT",params:r.Object({id:u()}),body:r.Object({enable:r.Boolean({description:"Set to true to enable the route, or false to disable it."})}),response:Nn});var qs=`/${"v1"}/routes`,tN={name:"Enrich API Gateway Logs",description:"Adds service metadata and normalizes log format",isEnabled:!0,query:"service:api-gateway",tags:[{key:"category",value:"enrichment"}],owner:"team-123-abc",processors:[{id:"parse-gateway-message",type:"parse-attribute",tags:[],params:{subtype:"grok",attributeName:"message",rules:["%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{GREEDYDATA:msg}"]}}]},rN={name:"Normalize Checkout Logs",description:"Maps service fields and extracts key/value details",isEnabled:!0,query:"context.service.name:checkout",tags:[{key:"category",value:"normalization"}],owner:"team-123-abc",processors:[{id:"map-service-name",type:"mapper",tags:[],params:{subtype:"map-attributes",attributes:[{originAttribute:"context.service.name",targetAttribute:"service",keepOrigin:!1,overrideTarget:!0}]}},{id:"parse-logfmt-message",type:"parse-attribute",tags:[],params:{subtype:"key-value",sourceAttribute:"message",targetAttribute:"logfmt",keyValueSplitter:"=",pairsSplitter:" ",acceptStandaloneKey:!1}}]},Fs=r.Pick(Nn,["id","name","description","isEnabled","query","tags","owner","processors"],{$id:"Route",description:"Team-owned log processing definition that selects newly ingested logs and applies ordered processors. See [Routes](/documentation/process/routes/index)."}),g9={id:"123-456-abc",...tN},h9={id:"456-789-def",...rN};Object.assign(Fs,{examples:[g9,h9]});var nN=d({description:"Lists log routes visible to the authenticated operation key. Returned routes are ordered by evaluation order, with earlier routes evaluated first. Use this to inventory ingest-time processing definitions and owners. Pagination fields limit the returned page.",operationId:"listRoutes",tags:["routes"],url:qs,method:"GET",paginated:!0,query:r.Object(Ze),response:r.Array(Fs)}),oN=d({description:"Retrieves one log route by ID.",operationId:"getRoute",tags:["routes"],url:`${qs}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the log route to retrieve. Use the `id` returned by route list or create responses."})}),response:Fs}),Qg=r.Pick(js,["name","description","isEnabled","query","tags","owner","processors"],{description:"Log route create or update request. Provide the route metadata, source query, owner team, enabled state, tags, and ordered processors."});Object.assign(Qg,{examples:[tN,rN]});var iN=d({description:"Creates a log route at the end of the evaluation order. Routes affect only newly ingested logs after the cluster receives the updated configuration.",operationId:"createRoute",tags:["routes"],url:qs,method:"POST",body:Qg,response:Fs}),aN=d({description:"Updates an existing log route by ID without changing its evaluation order. Fields omitted from the request keep their existing values. Routes affect only newly ingested logs after the cluster receives the updated configuration.",operationId:"updateRoute",tags:["routes"],url:`${qs}/:id`,method:"PUT",body:Qg,params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the log route to update. Use the `id` returned by route list, get, or create responses."})}),response:Fs}),sN=d({description:"Deletes a log route by ID and compacts the evaluation order for remaining routes. The route stops processing future logs after the cluster receives the updated configuration.",operationId:"deleteRoute",tags:["routes"],url:`${qs}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the log route to delete. Use the `id` returned by route list, create, or update responses."})}),response:N});var Bs=`/${"v1"}/monitors`,Hs=r.Pick(Br,["id","name","message","tags","configuration","priority","owner","dashboardId","permissions","clusterIds"],{$id:"Monitor",description:"Saved alert definition that evaluates telemetry and creates alert transitions. Notification delivery is configured separately with notification rules. See [Monitors](/documentation/alert/monitors/index)."}),pN={name:"High Error Rate Alert",message:"Error rate exceeded threshold. Check the API gateway logs.",tags:[{key:"severity",value:"critical"}],configuration:{type:"log",timeframe:5,groupByFields:[],aggregationAlertLogic:"no_aggregation",queries:[{aggregate:{type:"count"},filter:"level:ERROR service:api-gateway"}],conditions:[{formula:"q1",operator:"greater_than",threshold:100}],noDataBehavior:"resolve"},priority:1,owner:"team-123-abc",dashboardId:"789-abc-def",permissions:"all",clusterIds:[]},uN={name:"High CPU Utilization By Service",message:"More than half of grouped services are above the CPU threshold.",tags:[{key:"severity",value:"warning"}],configuration:{type:"metric",timeframe:10,groupByFields:[{fields:["context.service.name"],limit:10}],aggregationAlertLogic:"proportion",proportionAlertThreshold:50,queries:[{aggregate:{type:"average",field:"system.cpu.utilization"},filter:"context.service.name:checkout"}],conditions:[{formula:"q1",operator:"greater_than",threshold:.8}],noDataBehavior:"keep_last_status"},priority:2,owner:"team-123-abc",dashboardId:"789-abc-def",permissions:"all",clusterIds:[]},lN={name:"Certificate Expiry Warning",message:"A certificate is approaching expiry.",tags:[{key:"environment",value:"production"}],configuration:{type:"certificate-expiry",warnBeforeInDays:30,cloudAccounts:["aws-prod"],aggregationAlertLogic:"each",noDataBehavior:"resolve"},priority:3,owner:"team-123-abc",dashboardId:"789-abc-def",permissions:"all",clusterIds:[]},mN={name:"New Error Pattern Detector",message:"A new error pattern was detected in the logs.",tags:[{key:"team",value:"platform"}],configuration:{type:"log-error-pattern",aggregationAlertLogic:"each",noDataBehavior:"keep_last_status",filter:{teamIds:["team-123-abc"],env:"production",service:"api-gateway"}},priority:2,owner:"team-123-abc",dashboardId:"789-abc-def",permissions:"all",clusterIds:[]},y9={id:"123-456-abc",...pN},T9={id:"234-567-bcd",...uN},E9={id:"345-678-cde",...lN},_9={id:"456-789-def",...mN};Object.assign(Hs,{examples:[y9,T9,E9,_9]});var cN=r.Pick(Nd,["filters","sort","limit","offset"]),dN=r.Object({...cN.properties,...Ze,filters:cN.properties.filters},{description:"Monitor query request. Use filters, sorting, limit, and offset to page through visible monitors."}),I9={filters:{owners:{values:["team-123-abc"]},searchQuery:{value:"service:api-gateway"},tags:{values:[{key:"paging",value:"true"}]},priorities:{values:[4,5],exclude:!0},types:{values:["threshold"]},activity:"active",clusterIds:{values:["cluster-123-abc"]}},sort:{by:"name",direction:"asc"},limit:10,offset:0};Object.assign(dN,{examples:[I9]});var fN=d({description:"Queries monitors visible to the authenticated operation key. Use this endpoint to inventory monitor definitions, filter by owner, tag, priority, type, activity, or cluster, and page through results. See [Monitors](/documentation/alert/monitors/index).",operationId:"queryMonitors",tags:["monitors"],url:`${Bs}/query`,method:"POST",paginated:!0,body:dN,response:r.Array(Hs)}),gN=d({description:"Retrieves one monitor definition by ID.",operationId:"getMonitor",tags:["monitors"],url:`${Bs}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Monitor ID returned by monitor query, create, or update operations."})}),response:Hs}),hN=["name","message","tags","configuration","priority","owner","dashboardId","permissions","clusterIds"],yN=r.Pick(is,hN,{$id:"CreateMonitorRequest",description:"Monitor creation request. Provide ownership, data access, alert configuration, priority, tags, and optional dashboard or cluster scope."}),TN=r.Pick(is,hN,{$id:"UpdateMonitorRequest",description:"Monitor update request. Required fields and the submitted configuration are overwritten; omitted `message`, `tags`, and `clusterIds` keep their existing values. Omitting `dashboardId` clears the dashboard link."}),EN=pN,_N=uN,IN=lN,bN=mN;Object.assign(yN,{examples:[EN,_N,IN,bN]});Object.assign(TN,{examples:[EN,_N,IN,bN]});var SN=d({description:"Creates a monitor owned by the specified team. The monitor can evaluate logs, metrics, traces, anomaly behavior, certificate expiry, or new error patterns depending on its configuration.",operationId:"createMonitor",tags:["monitors"],url:Bs,method:"POST",body:yN,response:Hs}),AN=d({description:"Updates an existing monitor definition by ID. Required fields and the submitted configuration are overwritten; omitted `message`, `tags`, and `clusterIds` keep their existing values. Omitting `dashboardId` clears the dashboard link, and public updates clear any existing snooze because `pauseUntil` is not part of the public schema.",operationId:"updateMonitor",tags:["monitors"],url:`${Bs}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the saved monitor to update. Use the `id` returned by monitor query or create responses."})}),body:TN,response:Hs}),b9=r.Object({id:u({allowEmpty:!1,description:"Identifier of the saved monitor to delete. Use the `id` returned by monitor query, create, or update responses."})}),ON=d({description:"Deletes a monitor by ID. Deleting a monitor stops future evaluations and alert transitions for that monitor.",operationId:"deleteMonitor",tags:["monitors"],url:`${Bs}/:id`,method:"DELETE",params:b9,response:N});var Ks=`/${"v1"}/notification-rules`,zs=r.Pick(Ti,["id","name","queryString","teamsFilter","prioritiesFilter","transitionTypesFilter","clusterIdsFilter","owner","isActive","tags","targets"],{$id:"Rule",description:"Notification rule that matches alert transitions and routes notifications to one or more targets. See [Rules](/documentation/alert/notifications/rules)."}),xN={name:"Critical Alerts",queryString:"env:prod service:api",teamsFilter:{type:"all-public-teams"},prioritiesFilter:[1,2],transitionTypesFilter:["triggered","resolved"],clusterIdsFilter:[],owner:"team-123-abc",isActive:!0,tags:[{key:"channel",value:"alerts"}],targets:[{id:"789-abc-def",rateLimit:{maxMessages:10,minutes:5},config:{type:"email",addresses:["oncall@example.com"],renotifyConfig:{mode:"each",renotificationStates:["alert"],renotifyIntervalMinutes:30}}}]},S9={id:"123-456-abc",...xN};Object.assign(zs,{examples:[S9]});var RN=d({description:"Lists notification rules visible to the authenticated operation key. Use this endpoint to audit alert delivery routing. Pagination fields limit the returned page.",operationId:"listNotificationRules",tags:["notification-rules"],url:Ks,method:"GET",paginated:!0,query:r.Object(Ze),response:r.Array(zs)}),CN=d({description:"Retrieves one notification rule by ID.",operationId:"getNotificationRule",tags:["notification-rules"],url:`${Ks}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the notification rule to retrieve. Use the `id` returned by notification rule list or create responses."})}),response:zs}),Wg=r.Pick(cs,["name","queryString","teamsFilter","prioritiesFilter","transitionTypesFilter","clusterIdsFilter","owner","tags","isActive","targets"],{description:"Notification rule create or update request. Provide matching filters, owner, tags, active state, and delivery targets."}),A9=xN;Object.assign(Wg,{examples:[A9]});var PN=d({description:"Creates a notification rule that matches alert transitions and sends notifications to configured targets. Monitors keep evaluating separately from notification rules.",operationId:"createNotificationRule",tags:["notification-rules"],url:Ks,method:"POST",body:Wg,response:zs}),UN=d({description:"Updates an existing notification rule by ID. Required fields and the submitted target list are overwritten; omitted optional fields keep their existing values.",operationId:"updateNotificationRule",tags:["notification-rules"],url:`${Ks}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the notification rule to update. Use the `id` returned by notification rule list, get, or create responses."})}),body:Wg,response:zs}),O9=r.Object({id:u({allowEmpty:!1,description:"Identifier of the notification rule to delete. Use the `id` returned by notification rule list, get, create, or update responses."})}),wN=d({description:"Deletes a notification rule by ID. Alerting monitors continue to evaluate, but this rule no longer sends notifications.",operationId:"deleteNotificationRule",tags:["notification-rules"],url:`${Ks}/:id`,method:"DELETE",params:O9,response:N});var Xi=`${hi}/silences`,vN=r.Union([r.Literal("monday"),r.Literal("tuesday"),r.Literal("wednesday"),r.Literal("thursday"),r.Literal("friday"),r.Literal("saturday"),r.Literal("sunday")]),x9=r.Partial(r.Record(vN,r.Array(r.Object({startTime:r.String({format:Gm,description:"Local start time for this recurring silence window on this day, using the schedule time zone."}),endTime:r.String({format:Gm,description:"Local end time for this recurring silence window on this day. It must be after `startTime`, and ranges on the same day cannot overlap."})},{title:"SilenceTimeRange"}),{minItems:1,description:"Silence windows for this day. Each window uses the schedule time zone, and windows on the same day cannot overlap."})),{description:"Recurring silence windows keyed by day of week, evaluated in the schedule `timeZone` or in UTC when it is omitted. At least one day must be listed, and a day with no entry is never silenced. Each window covers `startTime` up to but not including `endTime`."}),R9=r.Partial(r.Record(vN,r.Array(r.Object({startTime:r.String({description:"Local start time for this recurring silence window on this day, using the schedule time zone."}),endTime:r.String({description:"Local end time for this recurring silence window on this day. It must be after `startTime`, and ranges on the same day cannot overlap."})},{title:"SilenceTimeRange"}),{description:"Silence windows for this day. Each window uses the schedule time zone, and windows on the same day cannot overlap."})),{description:"Recurring silence windows keyed by day of week, evaluated in the schedule `timeZone` or in UTC when it is omitted. A day with no entry is never silenced. Each window covers `startTime` up to but not including `endTime`."}),ml='IANA timezone identifier (e.g. "America/New_York"). Defaults to UTC if omitted.',NN="One-time silence schedule with specific start and end times",LN="Recurring weekly silence schedule",C9=C("type",[r.Object({type:r.Literal("one-time",{description:"Silence active once between the configured start and end times."}),startTime:r.String({format:$m,description:"Local start date and time for the one-time silence, interpreted in `timeZone` when provided."}),endTime:r.String({format:$m,description:"Local end date and time for the one-time silence. It must be after `startTime` and in the future."}),timeZone:r.Optional(r.String({format:Dm,description:ml}))},{$id:"InputSilenceScheduleOneTime",description:NN}),r.Object({type:r.Literal("recurring",{description:"Silence active on a recurring weekly schedule."}),weeklySchedule:x9,timeZone:r.Optional(r.String({format:Dm,description:ml}))},{$id:"InputSilenceScheduleRecurring",description:LN})],{description:"Schedule defining when the silence is active. The `type` field discriminates between a `one-time` window and a `recurring` weekly window. Once a one-time schedule's `endTime` passes, or a recurring window closes, the silence stops suppressing notifications but is not deleted; delete it explicitly if it is no longer needed."}),P9=C("type",[r.Object({type:r.Literal("one-time",{description:"Silence active once between the configured start and end times."}),startTime:r.String({description:"Local start date and time for the one-time silence, interpreted in `timeZone` when provided."}),endTime:r.String({description:"Local end date and time for the one-time silence. It must be after `startTime` and in the future when created or updated."}),timeZone:r.Optional(r.String({description:ml}))},{$id:"OutputSilenceScheduleOneTime",description:NN}),r.Object({type:r.Literal("recurring",{description:"Silence active on a recurring weekly schedule."}),weeklySchedule:R9,timeZone:r.Optional(r.String({description:ml}))},{$id:"OutputSilenceScheduleRecurring",description:LN})],{description:"Schedule defining when the silence is active. The `type` field discriminates between a `one-time` window and a `recurring` weekly window. Once a one-time schedule's `endTime` passes, or a recurring window closes, the silence stops suppressing notifications but is not deleted; delete it explicitly if it is no longer needed."}),U9="monitor_id",kN=`Query on the alerting monitor tags and group-by dimensions, e.g. \`env:prod AND service:bridge\`. The monitor itself can be targeted with \`${U9}:<monitor id>\`.`,dl=r.Object({name:u({description:"Display name of the silence"}),reason:u({allowEmpty:!1,type:"long",description:"Free-text explanation of why notifications are being silenced, shown to other operators reviewing active silences."}),owner:u({allowEmpty:!1,description:"Team ID that owns and manages the silence"}),tags:Xe,isActive:r.Boolean({description:"Set to true for the silence to suppress matching notifications while its schedule is active. Set to false to keep the silence without suppressing anything."}),schedule:C9,notificationRuleIds:r.Optional(r.Array(u(),{description:"Notification rule IDs this silence applies to directly, matching any notification produced by one of these rules regardless of priority or transition type. Mutually exclusive with `prioritiesFilter`, `transitionTypesFilter`, and `queryString`: a request combining this field with any of those is rejected."})),queryString:r.Optional(u({type:"tags-query",description:kN})),teamsFilter:Bd,prioritiesFilter:r.Array(r.Enum(St),{maxItems:St.length,description:"Monitor priorities that must match for this silence to apply. An empty array matches every priority."}),transitionTypesFilter:r.Array(r.Enum(uo),{maxItems:uo.length,description:"Alert state transitions that must match for this silence to apply. An empty array matches every transition type."})}),Ji=r.Object({id:r.String({description:"Tsuga-generated notification silence ID assigned when the silence is created."}),name:r.String({description:"Display name of the silence"}),reason:r.String({description:"Free-text explanation of why notifications are being silenced, shown to other operators reviewing active silences."}),owner:r.String({description:"Team ID that owns and manages the silence"}),tags:De,isActive:r.Boolean({description:"Whether the silence suppresses matching notifications while its schedule is active. When false, the silence is kept but never suppresses anything."}),schedule:P9,notificationRuleIds:r.Optional(r.Array(r.String(),{description:"Notification rule IDs this silence applies to directly, matching any notification produced by one of these rules regardless of priority or transition type. Set only when `prioritiesFilter`, `transitionTypesFilter`, and `queryString` are not used to filter alerts."})),queryString:r.Optional(r.String({description:kN})),teamsFilter:Fd,prioritiesFilter:r.Array(r.Enum(St),{description:"Monitor priorities that must match for this silence to apply. An empty array matches every priority."}),transitionTypesFilter:r.Array(r.Enum(uo),{description:"Alert state transitions that must match for this silence to apply. An empty array matches every transition type."}),createdAt:A(),updatedAt:A(),creator:r.Optional(pe),updater:r.Optional(pe)}),IJe=d({tags:["notification-silences"],url:Xi,method:"GET",response:r.Array(Ji)}),bJe=d({tags:["notification-silences"],url:`${Xi}/:id`,params:r.Object({id:u()}),method:"GET",response:Ji}),SJe=d({tags:["notification-silences"],url:Xi,method:"POST",body:dl,response:Ji}),AJe=d({tags:["notification-silences"],url:`${Xi}/:id`,method:"PUT",params:r.Object({id:u()}),body:dl,response:Ji}),OJe=d({tags:["notification-silences"],url:`${Xi}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),xJe=d({tags:["notification-silences"],url:`${Xi}/bulk-delete`,method:"DELETE",body:r.Object({ids:r.Array(u())}),response:r.Object({})});var Ys=`/${"v1"}/notification-silences`,Vs=r.Pick(Ji,["id","name","reason","owner","tags","isActive","schedule","notificationRuleIds","queryString","teamsFilter","prioritiesFilter","transitionTypesFilter"],{$id:"NotificationSilence",description:"Scheduled mute rule that suppresses matching notification delivery while monitors continue evaluating. See [Silences](/documentation/alert/notifications/silences)."}),w9={id:"sil-weekend-maintenance",name:"Weekend maintenance",reason:"Suppress expected alerts during the weekly maintenance window.",owner:"team-123-abc",tags:[{key:"environment",value:"production"}],isActive:!0,schedule:{type:"recurring",weeklySchedule:{saturday:[{startTime:"02:00",endTime:"06:00"}],sunday:[{startTime:"02:00",endTime:"06:00"}]},timeZone:"UTC"},teamsFilter:{type:"specific-teams",teams:["team-123-abc"]},prioritiesFilter:[1,2],transitionTypesFilter:["triggered","resolved"]},v9={id:"sil-critical-routing",name:"Critical routing maintenance",reason:"Temporarily suppress notifications from the critical routing rule.",owner:"team-123-abc",tags:[{key:"change",value:"chg-1234"}],isActive:!0,schedule:{type:"one-time",startTime:"2026-07-04T02:00:00",endTime:"2026-07-04T04:00:00",timeZone:"UTC"},notificationRuleIds:["rule-critical-routing"],teamsFilter:{type:"specific-teams",teams:["team-123-abc"]},prioritiesFilter:[],transitionTypesFilter:[]};Object.assign(Vs,{examples:[w9,v9]});var MN=d({description:"Lists notification silences visible to the authenticated operation key. Use this endpoint to audit maintenance windows and notification muting rules.",operationId:"listNotificationSilences",tags:["notification-silences"],url:Ys,method:"GET",response:r.Array(Vs)}),DN=d({description:"Retrieves one notification silence by ID.",operationId:"getNotificationSilence",tags:["notification-silences"],url:`${Ys}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the notification silence to retrieve. Use the `id` returned by notification silence list or create responses."})}),response:Vs}),Zg=r.Pick(dl,["name","reason","owner","tags","isActive","schedule","notificationRuleIds","queryString","teamsFilter","prioritiesFilter","transitionTypesFilter"],{description:"Notification silence create or update request. Provide the mute reason, owner, schedule, filters, active state, and tags."}),N9={name:"Weekend maintenance",reason:"Suppress expected alerts during the weekly maintenance window.",owner:"team-123-abc",tags:[{key:"environment",value:"production"}],isActive:!0,schedule:{type:"recurring",weeklySchedule:{saturday:[{startTime:"02:00",endTime:"06:00"}],sunday:[{startTime:"02:00",endTime:"06:00"}]},timeZone:"UTC"},teamsFilter:{type:"specific-teams",teams:["team-123-abc"]},prioritiesFilter:[1,2],transitionTypesFilter:["triggered","resolved"]},L9={name:"Critical routing maintenance",reason:"Temporarily suppress notifications from the critical routing rule.",owner:"team-123-abc",tags:[{key:"change",value:"chg-1234"}],isActive:!0,schedule:{type:"one-time",startTime:"2026-07-04T02:00:00",endTime:"2026-07-04T04:00:00",timeZone:"UTC"},notificationRuleIds:["rule-critical-routing"],teamsFilter:{type:"specific-teams",teams:["team-123-abc"]},prioritiesFilter:[],transitionTypesFilter:[]};Object.assign(Zg,{examples:[N9,L9]});var GN=d({description:"Creates a notification silence. Matching notifications that have not yet been sent are suppressed as soon as the schedule becomes active, including ones already queued when the silence is created; monitor evaluation itself is not paused, so alerts still transition and are visible in the UI.",operationId:"createNotificationSilence",tags:["notification-silences"],url:Ys,method:"POST",body:Zg,response:Vs}),$N=d({description:"Updates an existing notification silence by ID. Required fields are overwritten; omitted optional fields keep their existing values.",operationId:"updateNotificationSilence",tags:["notification-silences"],url:`${Ys}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the notification silence to update. Use the `id` returned by notification silence list, get, or create responses."})}),body:Zg,response:Vs}),k9=r.Object({id:u({allowEmpty:!1,description:"Identifier of the notification silence to delete. Use the `id` returned by notification silence list, get, create, or update responses."})}),jN=d({description:"Deletes a notification silence. Any notification not yet sent is re-evaluated against the remaining silences and, if none match, is delivered normally; notifications already marked as silenced are not resent.",operationId:"deleteNotificationSilence",tags:["notification-silences"],url:`${Ys}/:id`,method:"DELETE",params:k9,response:N});var M9={critical:3,important:2,normal:1},se=e=>({label:e,weight:M9[e]}),D9={"unrouted-logs":{key:"unrouted-logs",title:"Logs with no matching route",summary:"Any log that reaches processing without a matched route is flagged.",rationale:"Close gaps by ensuring each event flows through a governed route.",objectType:"route",category:"observability-assets",impact:se("important"),recommendation:"Ensure each team maintains a route that captures all of its logs exactly once."},"no-over-routed-logs":{key:"no-over-routed-logs",title:"No logs matching 3+ routes",summary:"Detects logs that match 3 or more processing routes during the lookback window.",rationale:"A log usually only needs one or two routes. Matching many routes typically means the route queries overlap unintentionally, multiplying the processing and storage cost without adding observability value.",objectType:"route",category:"observability-assets",impact:se("important"),recommendation:"Review the route queries owned by this team for overlap. Tighten the filter on each route so a given log matches the minimum number of routes needed (usually one)."},"team-has-route":{key:"team-has-route",title:"\u22651 route per team",summary:"Each team owns at least one active route that filters on its team name.",rationale:"Provides clear governance boundaries for routing and enrichment.",objectType:"route",category:"observability-assets",impact:se("important"),recommendation:"Ensure every team manages a dedicated route scoped to its context.team value."},"no-team-override-mismatch":{key:"no-team-override-mismatch",title:`${fd} matches ${Qp}`,summary:`Detects logs and spans whose ${fd} resource attribute names a different team than the ${Qp} resolved at ingestion.`,rationale:`${Qp} is reserved and comes from the ingestion API key, so a \`team\` resource attribute never reassigns ownership. A disagreement means the sender expects an ownership Tsuga did not apply.`,objectType:"resource",category:"telemetry-hygiene",impact:se("important"),recommendation:"Drop the `team` resource attribute, or set the ingestion API key team override fields to read ownership from a differently named attribute."},"service-name-present":{key:"service-name-present",title:`${Wp} present`,summary:`Logs and spans must populate ${Wp} with a non-empty value.`,rationale:"Core identifier used to correlate telemetry across services.",objectType:"resource",category:"telemetry-hygiene",impact:se("critical"),recommendation:`Populate ${Wp} in all log and span payloads.`},"no-orphan-spans":{key:"no-orphan-spans",title:"No orphan spans",summary:"Every span with parent_span_id references an existing span in the same trace.",rationale:"Trace integrity depends on preserving parent-child hierarchies.",objectType:"span",category:"telemetry-hygiene",impact:se("normal"),recommendation:"Emit parent spans before their children so references always resolve."},"metric-unit-consistency":{key:"metric-unit-consistency",title:"Name\u2192unit consistency",summary:"All series for a metric name report the same UCUM-compliant unit across the lookback period.",rationale:"Avoid ambiguity when charting and alerting on metrics with shared names.",objectType:"metric",category:"telemetry-hygiene",impact:se("important"),recommendation:"Align exporters so each metric name emits a single consistent unit across services and environments."},"host-name-present":{key:"host-name-present",title:`${es} presence`,summary:`Logs and spans must populate ${es} with a non-empty value.`,rationale:"Core identifier used to correlate telemetry across services.",objectType:"resource",category:"telemetry-hygiene",impact:se("important"),recommendation:`Populate ${es} in all log and span payloads.`},"inconsistent-attribute-naming":{key:"inconsistent-attribute-naming",title:"Consistent attribute naming",summary:"Detects attributes with multiple naming variants (e.g., userId vs user_id).",rationale:"Consistent naming improves queryability.",objectType:"log",category:"telemetry-hygiene",impact:se("normal"),recommendation:"Standardize attribute naming conventions across all log sources."},"no-duplicate-attr-values":{key:"no-duplicate-attr-values",title:"No duplicate attribute values",summary:"Detects when different attributes consistently carry identical values across logs (e.g., err.type and error.type always having the same value).",rationale:"Redundant attributes waste storage and complicate querying. Consolidate to one.",objectType:"log",category:"telemetry-hygiene",impact:se("normal"),recommendation:"Consolidate duplicate attributes at the source to reduce storage costs."},"no-debug-logs-in-prod":{key:"no-debug-logs-in-prod",title:"No DEBUG logs in production",summary:"Detects DEBUG-level logs emitted in production environments.",rationale:"DEBUG logs in production increase costs and risk exposing sensitive data.",objectType:"log",category:"telemetry-hygiene",impact:se("important"),recommendation:"Remove DEBUG-level logging from production environment or adjust log level configuration."},"no-multiline-logs":{key:"no-multiline-logs",title:"No ungrouped multiline logs",summary:"Detects orphaned stack-trace and traceback continuation lines that should have been grouped into a single log entry by the collector.",rationale:"Ungrouped multiline logs fragment errors across many entries, making them harder to read, search, and alert on.",objectType:"log",category:"telemetry-hygiene",impact:se("important"),recommendation:"Configure multiline grouping on the log collector using a line_start_pattern (e.g. a timestamp regex) so stack traces are sent as a single entry."},"no-error-logs-as-info":{key:"no-error-logs-as-info",title:"No error logs mapped as info",summary:"Detects INFO-level logs that carry error fields such as error.*, err.*, exception.*, or a stack trace.",rationale:"A log with error or exception attributes but an INFO severity is never surfaced as an error, so teams miss real failures caused by a misconfigured level mapper or bad logging.",objectType:"log",category:"telemetry-hygiene",impact:se("important"),recommendation:"Map these logs to ERROR in the level mapper, or fix the source logging so errors and exceptions are emitted at the right severity."},"no-empty-dashboards":{key:"no-empty-dashboards",title:"No empty dashboards",summary:"Flags dashboards with 1 or fewer widgets.",rationale:"Empty or near-empty dashboards add clutter and make it harder to find useful dashboards.",objectType:"dashboard",category:"observability-assets",impact:se("normal"),recommendation:"Add meaningful widgets to dashboards or remove empty ones to reduce clutter."},"monitor-has-notification":{key:"monitor-has-notification",title:"No monitors without notification",summary:"Every monitor has at least one active notification destination configured.",rationale:"A monitor without notifications is effectively silent - it detects issues but nobody is alerted.",objectType:"monitor",category:"observability-assets",impact:se("important"),recommendation:"Add a notification destination to every monitor - a monitor without notifications is effectively silent."},"no-future-dated-logs":{key:"no-future-dated-logs",title:"No future-dated logs",summary:"Detects logs with timestamps more than 59 minutes ahead of their intake time.",rationale:"Future-dated logs break dashboards, alerting, and log ordering - they indicate clock skew or incorrect timestamp generation.",objectType:"log",category:"telemetry-hygiene",impact:se("important"),recommendation:"Fix clock synchronization or timestamp generation for services emitting future-dated logs - they break dashboards and alerting."},"metric-usage":{key:"metric-usage",title:"Metric usage",summary:"Percentage of ingested metrics that are referenced by a dashboard or monitor, or were queried in the last 30 days.",rationale:"Metrics that are never visualized, alerted on, or queried add ingestion cost and cardinality without providing value.",objectType:"metric",category:"telemetry-adoption",impact:se("important"),recommendation:"Stop emitting metrics that are never referenced or queried to reduce ingestion cost and cardinality.",scope:"global"},"no-stale-dashboards":{key:"no-stale-dashboards",title:"No stale dashboards",summary:"Flags dashboards that have not been edited in over 180 days.",rationale:"Stale dashboards may contain outdated queries or irrelevant data, making it harder for teams to find useful, up-to-date information.",objectType:"dashboard",category:"observability-assets",impact:se("normal"),recommendation:"Review and update dashboards that haven't been edited in 180+ days, or archive them if no longer relevant."},"no-unused-dashboards":{key:"no-unused-dashboards",title:"No unused dashboards",summary:"Flags dashboards with zero views in the last 60 days.",rationale:"Dashboards that nobody views add clutter and may confuse team members looking for relevant information.",objectType:"dashboard",category:"telemetry-adoption",impact:se("important"),recommendation:"Archive or delete dashboards that nobody has viewed in the last 60 days to reduce noise."},"no-orphan-monitors":{key:"no-orphan-monitors",title:"No monitors without dashboards",summary:"Every monitor should be linked to at least one dashboard.",rationale:"Monitors without a linked dashboard make it harder for teams to investigate alerts \u2014 responders need a dashboard to quickly understand the context and scope of an issue.",objectType:"monitor",category:"observability-assets",impact:se("important"),recommendation:"Link monitors to relevant dashboards so teams can quickly investigate when alerts fire."},"no-flapping-monitors":{key:"no-flapping-monitors",title:"No flappy monitors",summary:"P1/P2 monitors should not have any group (or the monitor itself) trigger 7+ alerts within 7 days.",rationale:"Monitors that constantly flip between alert and OK cause alert fatigue. Teams start ignoring notifications, increasing the risk of missing real incidents.",objectType:"monitor",category:"observability-assets",impact:se("important"),recommendation:"Tune thresholds, add hysteresis, or adjust evaluation windows to reduce flapping."},"no-noisy-group-monitors":{key:"no-noisy-group-monitors",title:"No noisy group-by monitors",summary:"P1/P2 group-by monitors should not have 5+ groups triggering alerts simultaneously on 2+ occasions within 7 days.",rationale:"When a group-by monitor triggers alerts for many groups at once repeatedly, the signal gets lost in noise. Responders cannot prioritize and the monitor effectively becomes useless.",objectType:"monitor",category:"observability-assets",impact:se("important"),recommendation:"Narrow the group-by scope, raise thresholds, or split into more targeted monitors."},"no-long-alert-monitors":{key:"no-long-alert-monitors",title:"No monitors stuck in alert",summary:"P1/P2 monitors should not remain in alert state for more than 15 days.",rationale:"A high-priority monitor stuck in alert for weeks signals an unresolved issue or a misconfigured threshold. Either way, the alert loses meaning and contributes to alert fatigue.",objectType:"monitor",category:"observability-assets",impact:se("important"),recommendation:"Investigate and resolve the underlying issue, adjust the threshold, or acknowledge and close the alert."},"no-redundant-monitors":{key:"no-redundant-monitors",title:"No redundant monitors",summary:"P1/P2 monitors should not always trigger at the same time as another monitor (3+ co-triggers within 7 days).",rationale:"A monitor that always fires alongside another monitor is redundant. It adds noise without providing additional signal, making it harder for responders to identify the root cause.",objectType:"monitor",category:"observability-assets",impact:se("important"),recommendation:"Investigate whether the redundant monitor can be removed or consolidated with the one it always co-triggers with."},"no-absent-log-fields":{key:"no-absent-log-fields",title:"No absent log fields",summary:"Dashboards and monitors should reference log fields that still appear in recent logs (last 24 hours).",rationale:"References to log fields that no longer exist silently break dashboards and monitors, eroding trust in observability.",objectType:"dashboard",category:"observability-assets",impact:se("important"),recommendation:"Remove, rename, or backfill log fields that are referenced by dashboards or monitors but have not been seen in the last 24 hours.",scope:"global"},"k8s-recommended-attributes":{key:"k8s-recommended-attributes",title:"Kubernetes recommended resource attributes",summary:"Kubernetes logs and spans should populate core identity attributes and at least one workload-ownership attribute.",rationale:"These attributes let Tsuga correlate telemetry with the Kubernetes objects that produced it, which is required for faulty-deployment detection and rollback suggestions.",objectType:"resource",category:"collection-coverage",impact:se("important"),recommendation:"Make sure every Kubernetes workload emits k8s.cluster.name, k8s.namespace.name, k8s.pod.name, k8s.pod.uid, k8s.container.name, k8s.node.name and one workload-ownership attribute (for example via the OpenTelemetry Collector k8s_attributes processor)."},"k8s-recommended-metrics":{key:"k8s-recommended-metrics",title:"Kubernetes recommended cluster metrics",summary:"All recommended Kubernetes cluster metrics are collected.",rationale:"These metrics are the primary signals for faulty-deployment detection; without k8s.container.status.reason and the usage/limit pairs, container crash loops and resource starvation cannot be diagnosed.",objectType:"metric",category:"collection-coverage",impact:se("important"),recommendation:"Enable the OpenTelemetry Collector k8s_cluster receiver (for example via the Tsuga Helm chart) so the required Kubernetes metrics are emitted.",scope:"global"},"k8s-recommended-change-events":{key:"k8s-recommended-change-events",title:"Kubernetes recommended change events",summary:"Change events are collected for the Kubernetes object kinds recommended for rollback suggestions.",rationale:"Faulty-deployment detection needs the history of ReplicaSet, Deployment, Pod and Node changes to identify failing revisions and propose rollbacks.",objectType:"log",category:"collection-coverage",impact:se("important"),recommendation:"Configure the Kubernetes change-event collector (for example the OpenTelemetry k8sobjects receiver) so change events for Pod, Deployment, ReplicaSet, StatefulSet, DaemonSet, Namespace and Node are ingested."},"otel-collector-self-metrics":{key:"otel-collector-self-metrics",title:"OpenTelemetry Collector self-metrics",summary:"A cluster collecting Kubernetes metrics through an OpenTelemetry Collector also emits the collector self-metrics (otelcol_*).",rationale:"The Kubernetes receivers feed the Kubernetes explorer. Without the collector self-metrics there is no way to tell a healthy pipeline from one that drops data or fails to export, so a stale or missing Kubernetes view cannot be explained.",objectType:"metric",category:"collection-coverage",impact:se("important"),recommendation:"Enable the collector's internal telemetry (service.telemetry.metrics) and export it to Tsuga so otelcol_* metrics are available.",scope:"global"},"use-standard-attributes":{key:"use-standard-attributes",title:"Standard attribute usage",summary:"Detects log attributes that should be remapped to Tsuga standard attributes.",rationale:"Standard attributes enable consistent querying, out-of-the-box dashboards, and cross-team correlation.",objectType:"log",category:"telemetry-hygiene",impact:se("important"),recommendation:"Use the attribute remapper in your routes to rename attributes to their standard equivalents."},"no-unused-operation-api-keys":{key:"no-unused-operation-api-keys",title:"No unused operation API keys",summary:"Flags operation API keys with no activity in the last 180 days.",rationale:"Long-idle operation credentials add risk if leaked and clutter the inventory. Tracking last-used activity makes it easy to rotate or delete the unused ones.",objectType:"api-key",category:"observability-assets",impact:se("important"),recommendation:"Rotate or delete operation API keys that have not been used in the last 180 days."},"no-unused-ingestion-api-keys":{key:"no-unused-ingestion-api-keys",title:"No unused ingestion API keys",summary:"Flags ingestion API keys with no telemetry in the last 30 days across any cluster.",rationale:"Dormant ingestion credentials add risk if leaked and clutter the inventory. Tracking key activity makes it easy to rotate or delete the unused ones.",objectType:"api-key",category:"observability-assets",impact:se("important"),recommendation:"Rotate or delete ingestion API keys that have sent no data in the last 30 days."},"db-logs-trace-correlation":{key:"db-logs-trace-correlation",title:"Database logs correlated with traces",summary:`Database logs should carry ${XO} so they can be tied back to the trace that issued the query.`,rationale:"Linking database server logs to client traces lets users jump from a slow request to the exact query log. Without a trace id, database logs cannot be joined to the request that produced them.",objectType:"log",category:"telemetry-hygiene",impact:se("normal"),recommendation:"Enable trace correlation on the database log pipeline (for example via SQLcommenter, which embeds the traceparent in each statement) so query logs carry a trace id.",scope:"team"}},qN={"postgresql-server-metrics-collected":{label:"PostgreSQL",systemValues:["postgresql"],metricPrefixes:["postgresql.","pg_"],receiver:"postgresqlreceiver"},"mysql-server-metrics-collected":{label:"MySQL",systemValues:["mysql","mariadb"],metricPrefixes:["mysql.","mysql_"],receiver:"mysqlreceiver"},"mongodb-server-metrics-collected":{label:"MongoDB",systemValues:["mongodb"],metricPrefixes:["mongodb.","mongodbatlas.","mongodb_"],receiver:"mongodbreceiver"},"redis-server-metrics-collected":{label:"Redis",systemValues:["redis"],metricPrefixes:["redis.","redis_"],receiver:"redisreceiver"},"memcached-server-metrics-collected":{label:"Memcached",systemValues:["memcached"],metricPrefixes:["memcached.","memcached_"],receiver:"memcachedreceiver"},"couchdb-server-metrics-collected":{label:"CouchDB",systemValues:["couchdb"],metricPrefixes:["couchdb.","couchdb_"],receiver:"couchdbreceiver"},"elasticsearch-server-metrics-collected":{label:"Elasticsearch",systemValues:["elasticsearch"],metricPrefixes:["elasticsearch.","elasticsearch_"],receiver:"elasticsearchreceiver"},"oracledb-server-metrics-collected":{label:"Oracle DB",systemValues:["oracle.db","oracle"],metricPrefixes:["oracledb.","oracledb_"],receiver:"oracledbreceiver"},"sqlserver-server-metrics-collected":{label:"Microsoft SQL Server",systemValues:["microsoft.sql_server","mssql"],metricPrefixes:["sqlserver.","mssql_"],receiver:"sqlserverreceiver"},"saphana-server-metrics-collected":{label:"SAP HANA",systemValues:["sap.hana","hanadb"],metricPrefixes:["saphana."],receiver:"saphanareceiver"},"cassandra-server-metrics-collected":{label:"Cassandra",systemValues:["cassandra"],metricPrefixes:["cassandra.","cassandra_"]},"clickhouse-server-metrics-collected":{label:"ClickHouse",systemValues:["clickhouse"],metricPrefixes:["ClickHouse"]},"couchbase-server-metrics-collected":{label:"Couchbase",systemValues:["couchbase"],metricPrefixes:["couchbase_"]},"neo4j-server-metrics-collected":{label:"Neo4j",systemValues:["neo4j"],metricPrefixes:["neo4j_"]},"opensearch-server-metrics-collected":{label:"OpenSearch",systemValues:["opensearch"],metricPrefixes:["opensearch_"]},"db2-server-metrics-collected":{label:"IBM Db2",systemValues:["ibm.db2","db2"],metricPrefixes:["ibm_db2_"]}},G9=Object.fromEntries(Object.keys(qN).map(e=>{let{label:t,receiver:n}=qN[e];return[e,{key:e,title:`${t} server metrics collected`,summary:`${t} seen in client spans should have its server metrics collected.`,rationale:"Server metrics (connections, throughput, replication, contention) are needed to investigate database slowness beyond what client spans show. A detected database with no server metrics has a gap in its monitoring setup.",objectType:"metric",category:"collection-coverage",impact:se("important"),recommendation:n?`Configure the ${n} OpenTelemetry receiver so ${t} server metrics are collected.`:`Collect ${t} server metrics, for example via its Prometheus exporter.`,scope:"global"}]})),$9=new Set(["azure_container_registry","azure_container_registry_image","azure_app_service_certificate","azure_virtual_network"]),j9=ks.filter(e=>e.startsWith("azure_")&&!$9.has(e)),FN={"aws-sqs-metrics-collected":{label:"Amazon SQS",source:"AWS/SQS",nativeResourceTypes:["aws_sqs_queue"],metricPrefixes:["aws_sqs_"]},"aws-sns-metrics-collected":{label:"Amazon SNS",source:"AWS/SNS",nativeResourceTypes:["aws_sns_topic"],metricPrefixes:["aws_sns_"]},"aws-kinesis-metrics-collected":{label:"Amazon Kinesis Data Streams",source:"AWS/Kinesis",nativeResourceTypes:["aws_kinesis_data_stream"],metricPrefixes:["aws_kinesis_"]},"aws-dynamodb-metrics-collected":{label:"Amazon DynamoDB",source:"AWS/DynamoDB",nativeResourceTypes:["aws_dynamodb_table"],metricPrefixes:["aws_dynamodb_"]},"aws-rds-metrics-collected":{label:"Amazon RDS",source:"AWS/RDS",nativeResourceTypes:["aws_rds_instance"],metricPrefixes:["aws_rds_"]},"aws-elasticache-metrics-collected":{label:"Amazon ElastiCache",source:"AWS/ElastiCache",nativeResourceTypes:["aws_elasticache"],metricPrefixes:["aws_elasticache_"]},"aws-s3-metrics-collected":{label:"Amazon S3",source:"AWS/S3",nativeResourceTypes:["aws_s3_bucket"],metricPrefixes:["aws_s3_"]},"aws-ebs-metrics-collected":{label:"Amazon EBS",source:"AWS/EBS",nativeResourceTypes:["aws_ebs_volume"],metricPrefixes:["aws_ebs_"]},"aws-efs-metrics-collected":{label:"Amazon EFS",source:"AWS/EFS",nativeResourceTypes:["aws_efs"],metricPrefixes:["aws_efs_"]},"aws-ec2-metrics-collected":{label:"Amazon EC2",source:"AWS/EC2",nativeResourceTypes:["aws_ec2_instance"],metricPrefixes:["aws_ec2_"]},"aws-lambda-metrics-collected":{label:"AWS Lambda",source:"AWS/Lambda",nativeResourceTypes:["aws_lambda_function"],metricPrefixes:["aws_lambda_"]},"aws-ecs-metrics-collected":{label:"Amazon ECS",source:"AWS/ECS",nativeResourceTypes:["aws_ecs_cluster","aws_ecs_service","aws_ecs_task"],metricPrefixes:["aws_ecs_"]},"aws-ecr-metrics-collected":{label:"Amazon ECR",source:"AWS/ECR",nativeResourceTypes:["aws_ecr_repository"],metricPrefixes:["aws_ecr_"]},"aws-elb-metrics-collected":{label:"Elastic Load Balancing",source:"AWS/ApplicationELB, AWS/NetworkELB",nativeResourceTypes:["aws_elastic_load_balancer"],metricPrefixes:["aws_applicationelb_","aws_networkelb_","aws_gatewayelb_","aws_elb_"]},"aws-cloudfront-metrics-collected":{label:"Amazon CloudFront",source:"AWS/CloudFront",nativeResourceTypes:["aws_cloudfront_distribution"],metricPrefixes:["aws_cloudfront_"]},"aws-acm-metrics-collected":{label:"AWS Certificate Manager",source:"AWS/CertificateManager",nativeResourceTypes:["aws_acm_certificate"],metricPrefixes:["aws_certificatemanager_"]},"gcp-pubsub-metrics-collected":{label:"Google Cloud Pub/Sub",source:"pubsub.googleapis.com",nativeResourceTypes:["gcp_pubsub_topic"],metricPrefixes:["pubsub.googleapis.com/"]},"gcp-storage-metrics-collected":{label:"Google Cloud Storage",source:"storage.googleapis.com",nativeResourceTypes:["gcp_bucket"],metricPrefixes:["storage.googleapis.com/"]},"gcp-compute-metrics-collected":{label:"Google Compute Engine",source:"compute.googleapis.com",nativeResourceTypes:["gcp_compute_instance","gcp_compute_disk"],metricPrefixes:["compute.googleapis.com/"]},"gcp-cloud-sql-metrics-collected":{label:"Google Cloud SQL",source:"cloudsql.googleapis.com",nativeResourceTypes:["gcp_cloud_sql_instance"],metricPrefixes:["cloudsql.googleapis.com/"]},"gcp-gke-metrics-collected":{label:"Google Kubernetes Engine",source:"kubernetes.io, container.googleapis.com",nativeResourceTypes:["gcp_gke_cluster"],metricPrefixes:["kubernetes.io/","container.googleapis.com/"]},"gcp-cloud-run-metrics-collected":{label:"Google Cloud Run",source:"run.googleapis.com",nativeResourceTypes:["gcp_cloud_run_service","gcp_cloud_run_job","gcp_cloud_run_function"],metricPrefixes:["run.googleapis.com/"]},"gcp-artifact-registry-metrics-collected":{label:"Google Artifact Registry",source:"artifactregistry.googleapis.com",nativeResourceTypes:["gcp_artifact_registry_repository"],metricPrefixes:["artifactregistry.googleapis.com/"]},"gcp-load-balancing-metrics-collected":{label:"Google Cloud Load Balancing",source:"loadbalancing.googleapis.com",nativeResourceTypes:["gcp_forwarding_rule"],metricPrefixes:["loadbalancing.googleapis.com/"]},"gcp-bigtable-metrics-collected":{label:"Google Cloud Bigtable",source:"bigtable.googleapis.com",nativeResourceTypes:["gcp_bigtable_instance"],metricPrefixes:["bigtable.googleapis.com/"]},"gcp-spanner-metrics-collected":{label:"Google Cloud Spanner",source:"spanner.googleapis.com",nativeResourceTypes:["gcp_spanner_instance"],metricPrefixes:["spanner.googleapis.com/"]},"gcp-firestore-metrics-collected":{label:"Google Cloud Firestore",source:"firestore.googleapis.com",nativeResourceTypes:["gcp_firestore_database"],metricPrefixes:["firestore.googleapis.com/"]},"gcp-app-engine-metrics-collected":{label:"Google App Engine",source:"appengine.googleapis.com",nativeResourceTypes:["gcp_app_engine_service"],metricPrefixes:["appengine.googleapis.com/"]},"azure-metrics-collected":{label:"Azure",source:"Azure Monitor",nativeResourceTypes:j9,metricPrefixes:["azure_"]}},q9=Object.fromEntries(Object.keys(FN).map(e=>{let{label:t,source:n}=FN[e];return[e,{key:e,title:`${t} metrics collected`,summary:`${t} resources found in inventory should have their metrics collected.`,rationale:"A resource that appears in inventory but whose metrics are not collected leaves its dashboards and resource-explorer views empty and impossible to alert on.",objectType:"metric",category:"collection-coverage",impact:se("important"),recommendation:`Enable the ${n} metrics integration so ${t} metrics are ingested.`,scope:"global"}]})),F9={...D9,...G9,...q9},BN=Object.values(F9);var HN=["passed","failed","ignored"],B9=10,H9=r.Enum(HN,{description:"Evaluation outcome for this rule row. Allowed values are passed, failed, and ignored; ignored means the rule was not applicable to the available data."}),K9=["aws-sqs-metrics-collected","aws-sns-metrics-collected","aws-kinesis-metrics-collected","aws-dynamodb-metrics-collected","aws-rds-metrics-collected","aws-elasticache-metrics-collected","aws-s3-metrics-collected","aws-ebs-metrics-collected","aws-efs-metrics-collected","aws-ec2-metrics-collected","aws-lambda-metrics-collected","aws-ecs-metrics-collected","aws-ecr-metrics-collected","aws-elb-metrics-collected","aws-cloudfront-metrics-collected","aws-acm-metrics-collected","gcp-pubsub-metrics-collected","gcp-storage-metrics-collected","gcp-compute-metrics-collected","gcp-cloud-sql-metrics-collected","gcp-gke-metrics-collected","gcp-cloud-run-metrics-collected","gcp-artifact-registry-metrics-collected","gcp-load-balancing-metrics-collected","gcp-bigtable-metrics-collected","gcp-spanner-metrics-collected","gcp-firestore-metrics-collected","gcp-app-engine-metrics-collected","azure-metrics-collected"],z9=["postgresql-server-metrics-collected","mysql-server-metrics-collected","mongodb-server-metrics-collected","redis-server-metrics-collected","memcached-server-metrics-collected","couchdb-server-metrics-collected","elasticsearch-server-metrics-collected","oracledb-server-metrics-collected","sqlserver-server-metrics-collected","saphana-server-metrics-collected","cassandra-server-metrics-collected","clickhouse-server-metrics-collected","couchbase-server-metrics-collected","neo4j-server-metrics-collected","opensearch-server-metrics-collected","db2-server-metrics-collected"],Jg=["unrouted-logs","no-over-routed-logs","team-has-route","no-team-override-mismatch","service-name-present","no-orphan-spans","metric-unit-consistency","host-name-present","inconsistent-attribute-naming","no-duplicate-attr-values","no-debug-logs-in-prod","no-multiline-logs","no-error-logs-as-info","no-empty-dashboards","monitor-has-notification","no-future-dated-logs","metric-usage","no-stale-dashboards","no-unused-dashboards","no-orphan-monitors","no-flapping-monitors","no-noisy-group-monitors","no-long-alert-monitors","no-redundant-monitors","no-absent-log-fields","k8s-recommended-attributes","k8s-recommended-metrics","k8s-recommended-change-events","otel-collector-self-metrics","use-standard-attributes","no-unused-operation-api-keys","no-unused-ingestion-api-keys","db-logs-trace-correlation",...z9,...K9],Y9=r.Enum(Jg),V9=["log","metric","resource","span","api-key","dashboard","monitor","route"],Q9=["collection-coverage","telemetry-hygiene","observability-assets","telemetry-adoption"],W9=["critical","important","normal"],Z9=["team","global"],eh=r.Object({key:r.Enum(Jg),title:r.String(),summary:r.String(),rationale:r.String(),objectType:r.Enum(V9),category:r.Enum(Q9),impact:r.Object({label:r.Enum(W9),weight:r.Number()}),recommendation:r.String(),scope:r.Optional(r.Enum(Z9))}),Qs=r.Object({type:r.String({description:"Tsuga asset or telemetry kind referenced by this example. Set by the rule evaluator from the failing object, record, or lookup result; examples include `monitor`, `dashboard`, `metric`, `log`, and `api-key`."}),label:r.String({description:"Human-readable summary of the example. Set by the rule evaluator from the asset name, telemetry identifier, or lookup result so clients can display the example without following the link."}),link:r.Object({to:r.String({description:"In-app route that opens the example in Tsuga. Set by the rule evaluator when the example has a product surface for inspection."}),search:r.Optional(r.Unknown({description:"Route search payload for the in-app link. Set when the destination needs query-string state such as a search query, time range, or table filter."})),params:r.Optional(r.Unknown({description:"Route params for the in-app link. Set when the destination route needs path parameters such as an asset identifier."}))},{description:"In-app deep link for inspecting the example. Returned when Tsuga can route from the quality-report row to a relevant product page."})}),Xg=r.Intersect([eh,r.Object({id:r.Optional(r.String()),status:H9,normalizedScore:r.Number(),details:r.Optional(r.Record(r.String(),r.Unknown())),recommendation:r.Optional(r.String()),examples:r.Optional(r.Array(Qs)),exampleCount:r.Optional(r.Integer())})]),X9=r.Object({generatedAt:r.String(),overallScore:r.Optional(r.Number()),rules:r.Array(eh),teamResults:r.Array(r.Object({teamId:r.String(),teamName:r.String(),teamWeight:r.Number(),score:r.Number(),weightedScore:r.Number(),totalWeight:r.Number(),ruleResults:r.Array(Xg)})),globalResults:r.Optional(r.Object({score:r.Optional(r.Number()),ruleResults:r.Array(Xg)}))}),th=r.Object({id:r.String({description:"Identifier of this persisted quality-report row. Generated by Tsuga when report rows are stored. Returned on every row. Treat it as an opaque ID."}),reportId:r.String({description:"Identifier shared by rows from the same report generation for the same team or global cluster-wide scope. Generated by Tsuga when the report is stored. Returned on every row."}),ruleId:r.Enum(Jg,{description:"Stable key for the telemetry-quality rule evaluated by this row. Set by Tsuga from the quality-rule catalog. Returned on every row. The enum may grow as Tsuga adds rules; clients should display unknown future values as opaque rule keys if they do not have local labels."}),owner:r.Optional(r.String({description:"Team identifier this row applies to. Set to the owning team ID for team-scoped rules. Returned for team rows; omitted for global cluster-wide rows."})),status:r.Enum(HN,{description:"Evaluation outcome for this rule row. Set by the rule evaluator when the report is generated. Returned on every row. Allowed values are passed, failed, and ignored; ignored means the rule was not applicable to the available data."}),score:r.Number({description:"Normalized score for this rule row. Set by the rule evaluator when the report is generated. Returned on every row. Values are between 0 and 1."}),weight:r.Number({description:"Impact weight of this rule, captured at report-generation time. Set by Tsuga from the rule's impact label: 1 for normal, 2 for important, 3 for critical. Used with score to compute reportOverallScore."}),reportOverallScore:r.Number({description:"Aggregate score for this row's report group. Calculated by Tsuga from non-ignored rows in the same team or global cluster-wide report. Returned on every row in that group with the same value."}),reportTotalWeight:r.Number({description:"Sum of non-ignored rule weights for this row's report group. Calculated by Tsuga when the report is generated. Returned on every row in that group with the same value."}),recommendation:r.Optional(r.String({description:"Recommendation stored with this row. Set by the rule evaluator when the report is generated. Returned when a recommendation was persisted; omitted otherwise. The latest-report endpoint does not recompute or default it at read time."})),examples:r.Optional(r.Array(Qs,{description:`Assets, logs, metrics, or links supporting this rule result. Set by the rule evaluator when the report is generated. Returned when examples were persisted and visible to the caller; global row examples are returned only to admin users. Truncated to the first ${B9}; compare against exampleCount to detect truncation.`})),exampleCount:r.Optional(r.Integer({description:"Total number of examples persisted for this row, before the preview truncation applied to examples. Returned whenever examples are visible to the caller."})),createdAt:r.String({description:"ISO timestamp the row was generated at"})}),FJe=d({tags:["quality-reports"],url:"/v0/quality-reports",method:"POST",response:X9}),rh=r.Optional(u({allowEmpty:!1,description:"Identifier of the cluster whose latest quality-report rows are returned. Use the id from the clusters API. Required when the organization has multiple clusters; omit only in single-cluster organizations. Unknown cluster IDs return RESOURCE_NOT_FOUND."})),BJe=d({tags:["quality-reports"],url:"/v0/quality-reports/latest",method:"GET",query:r.Object({clusterId:rh,team:r.Optional(u({allowEmpty:!1}))}),response:r.Array(th,{description:"Latest persisted rule evaluation rows for the cluster"})}),HJe=d({tags:["quality-reports"],url:"/v0/quality-reports/:id/examples",method:"GET",params:r.Object({id:u({allowEmpty:!1})}),response:r.Object({examples:r.Array(Qs)})}),KJe=d({tags:["quality-reports"],url:"/v0/quality-reports/preview",method:"POST",body:r.Object({ruleKey:Y9,teamId:r.Optional(u({allowEmpty:!1})),lookbackMinutes:r.Optional(r.Integer({minimum:1,maximum:60})),clusterId:r.Optional(u({allowEmpty:!1}))}),response:r.Object({rule:eh,result:Xg,teamId:r.Optional(r.String()),teamName:r.Optional(r.String())})}),zJe=new Map(BN.map(e=>[e.key,e]));var KN=`/${"v1"}/quality-reports`,zN=r.Pick(th,["id","reportId","ruleId","owner","status","score","weight","reportOverallScore","reportTotalWeight","recommendation","examples","exampleCount","createdAt"],{$id:"QualityReportRow",description:"Persisted evaluation of one telemetry-quality rule for a team or cluster-wide scope. See [Quality reports](/documentation/account-and-settings/quality-reports)."}),J9={id:"01j9x3z4vyabcdfghjkmnpqrst",reportId:"01j9x3z4vyabcdfghjkmnpqrsu",ruleId:"team-has-route",owner:"01j9x3z4vyabcdfghjkmnpqrr",status:"passed",score:1,weight:2,reportOverallScore:.85,reportTotalWeight:2,createdAt:"2026-02-26T12:00:00.000Z"};Object.assign(zN,{examples:[J9]});var eV=r.Object({clusterId:rh,team:r.Optional(u({allowEmpty:!1,description:"Team name used to scope the report. Matched against Tsuga team names. Optional; when set, returns only rows for that team and omits global rows. Unknown team names return RESOURCE_NOT_FOUND; teams the caller cannot access return an empty result."}))},{description:"Latest quality report lookup query."}),YN=d({description:"Retrieves the latest persisted quality-report rows for a cluster, optionally scoped to one team. Use this to audit telemetry hygiene and routing recommendations.",operationId:"getLatestQualityReport",tags:["quality-reports"],url:`${KN}/latest`,method:"GET",query:eV,response:r.Array(zN)}),JJe=d({description:"Retrieves every example stored for one quality-report row. The latest-report endpoint returns only a preview of each row's examples, so use this to page past that preview when exampleCount exceeds the number of examples returned there.",operationId:"getQualityReportExamples",tags:["quality-reports"],url:`${KN}/:id/examples`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the quality-report row whose examples are returned. Use the id from the latest-report endpoint. Unknown ids, rows the caller cannot access, and cluster-wide rows requested by a non-admin all return RESOURCE_NOT_FOUND."})}),response:r.Object({examples:r.Array(Qs,{description:"Every example stored for this row, untruncated. Empty when the rule evaluation produced none."})},{description:"All examples stored for one quality-report row."})});var Ws="/v0/admin-center";var wr=`${Ws}/retention-policies`,VN=3650,tV=r.Integer({description:"Number of days Tsuga retains matching telemetry."}),QN=r.Integer({minimum:1,maximum:VN,description:`Number of days Tsuga should retain matching telemetry. Valid values are 1 through ${VN}.`}),Jr=r.Object({id:r.String({description:"Unique identifier of the retention policy. Generated by Tsuga."}),env:r.Optional(r.String({description:"Environment tag value this policy applies to. Omitted policies apply across environments unless a more specific policy exists."})),teamId:r.Optional(r.String({description:"Team ID this policy applies to. Omitted policies apply globally unless a team-specific policy exists."})),dataSource:r.Enum(br,{description:"Telemetry signal retained by this policy: logs, metrics, traces or rum."}),durationDays:tV,isEnabled:r.Boolean({description:"Whether this policy participates in retention resolution."}),createdAt:A({description:"Timestamp when Tsuga created the retention policy."}),updatedAt:A({description:"Timestamp when Tsuga last updated the retention policy."})}),fl=r.Object({env:r.Optional(u({description:"Environment tag value this policy applies to. Omit for a policy that is not environment-specific."})),teamId:r.Optional(u({description:"Team ID this policy applies to. Omit for a policy that is not team-specific."})),dataSource:r.Enum(br,{description:"Telemetry signal retained by this policy: logs, metrics, traces or rum."}),durationDays:QN,isEnabled:r.Boolean({description:"Set to true for the policy to participate in retention resolution."})}),WN=r.Array(r.Object({env:u(),dataSource:r.Enum(br),durationDays:r.Union([QN,r.Null()]),isEnabled:r.Boolean()})),ZN=r.Object({inserted:r.Array(Jr),updated:r.Array(Jr),deleted:r.Array(Jr)}),cet=d({tags:["retention-policies"],url:wr,method:"POST",body:fl,response:Jr}),pet=d({tags:["retention-policies"],url:wr,method:"GET",response:r.Array(Jr)}),uet=d({tags:["retention-policies"],url:`${wr}/:id`,method:"GET",params:r.Object({id:u()}),response:Jr}),met=d({tags:["retention-policies"],url:`${wr}/:id`,method:"PUT",params:r.Object({id:u()}),body:fl,response:Jr}),det=d({tags:["retention-policies"],url:`${wr}/bulk-update`,method:"POST",body:WN,response:ZN}),fet=d({tags:["retention-policies"],url:`${wr}/bulk-update-for-team`,method:"POST",body:r.Object({teamId:u(),policies:WN}),response:ZN}),get=d({tags:["retention-policies"],url:`${wr}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),Zs=["past-24-hours","past-7-days","past-30-days"],het=d({tags:["retention-policies"],url:`${wr}/requested-history-percentile/:teamId`,method:"POST",params:r.Object({teamId:u()}),body:r.Object({percentile:r.Number({minimum:0,maximum:1}),observationWindow:r.Enum(Zs),dataSource:r.Enum(br)}),response:r.Object({percentile:r.Number(),observationWindow:r.Enum(Zs),dataSource:r.Enum(br),teamId:r.String(),requestedHistoryDays:r.Number()})}),rV=["1-day","3-days","7-days","1-month","6-months","more-than-6-months"];var nV=r.Array(r.Object({bucket:r.Enum(rV),count:r.Number()})),yet=d({tags:["retention-policies"],url:`${wr}/requested-history-histogram/:teamId`,method:"POST",params:r.Object({teamId:u()}),body:r.Object({observationWindow:r.Enum(Zs),dataSource:r.Enum(br)}),response:r.Object({observationWindow:r.Enum(Zs),dataSource:r.Enum(br),teamId:r.String(),histogram:nV})}),Tet=d({tags:["retention-policies"],url:`${wr}/top-teams-with-retention-surplus`,method:"POST",body:r.Object({dataSource:r.Enum(br),observationWindow:r.Enum(Zs),percentile:r.Number({minimum:0,maximum:1}),topN:r.Optional(r.Number({minimum:1,maximum:20}))}),response:r.Array(r.Object({teamId:r.String(),retentionSurplusDays:r.Number()}))});var Xs=`/${"v1"}/retention-policies`,Js=r.Pick(Jr,["id","env","teamId","dataSource","durationDays","isEnabled"],{$id:"RetentionPolicy",description:"Retention rule for logs, metrics, or traces. Policies can apply globally, to an environment, or to a team depending on which scope fields are present. See [Retention](/documentation/account-and-settings/retention)."}),oV={id:"123-456-abc",env:"production",teamId:"team-123-abc",dataSource:"logs",durationDays:30,isEnabled:!0};Object.assign(Js,{examples:[oV]});var XN=d({description:"Lists retention policy rows visible to the authenticated operation key. Use this to audit retention duration by signal, environment, and team.",operationId:"listRetentionPolicies",tags:["retention-policies"],url:Xs,method:"GET",response:r.Array(Js)}),JN=d({description:"Retrieves one retention policy by ID.",operationId:"getRetentionPolicy",tags:["retention-policies"],url:`${Xs}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the retention policy to retrieve. Use the `id` returned by retention policy list or create responses."})}),response:Js}),nh=r.Pick(fl,["env","teamId","dataSource","durationDays","isEnabled"],{description:"Retention policy create or update request. Provide the telemetry signal, retention duration, enabled state, and optional environment or team scope."}),iV={env:"production",teamId:"team-123-abc",dataSource:"logs",durationDays:30,isEnabled:!0};Object.assign(nh,{examples:[iV]});var eL=d({description:"Creates a retention policy row for a telemetry signal, optionally scoped to an environment or team. Only one policy may exist per combination of data source, environment, and team; creating a duplicate combination fails.",operationId:"createRetentionPolicy",tags:["retention-policies"],url:Xs,method:"POST",body:nh,response:Js}),tL=d({description:"Replaces an existing retention policy by ID, including signal, scope fields, duration, and enabled state.",operationId:"updateRetentionPolicy",tags:["retention-policies"],url:`${Xs}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the retention policy to update. Use the `id` returned by retention policy list, get, or create responses."})}),body:nh,response:Js}),rL=d({description:"Deletes a retention policy by ID. Retention resolution falls back to the next broader matching policy when one exists.",operationId:"deleteRetentionPolicy",tags:["retention-policies"],url:`${Xs}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the retention policy to delete. Use the `id` returned by retention policy list, create, or update responses."})}),response:N});var ec=`/${"v1"}/slos`,aV=r.Pick(Dd,["id","sloId","priority","configuration"],{$id:"SloAlert",description:"Alert attached to an SLO, triggered on a burn-rate multiplier or an SLO target threshold"}),tc=r.Object({...r.Pick(gi,["id","name","description","tags","configuration","target","timeframeDays","owner","permissions","clusterIds"]).properties,alerts:r.Array(aV,{description:"Alerts attached to this SLO"})},{$id:"Slo",description:"Service Level Objective definition: its SLI configuration, target percentage, rolling timeframe, cluster scope, and attached alerts"}),sV={id:"123-456-abc",name:"API availability 99.9%",description:"Overall API gateway availability over the last 30 days",tags:[{key:"team",value:"platform"}],configuration:{type:"event",dataSource:"logs",goodQuery:{queries:[{filter:"status:ok",aggregate:{type:"count"}}],formula:"q1"},totalQuery:{queries:[{filter:"*",aggregate:{type:"count"}}],formula:"q1"},noDataBehavior:"good"},target:99.9,timeframeDays:30,owner:"team-123-abc",permissions:"all",clusterIds:[],alerts:[{id:"alert-123-abc",sloId:"123-456-abc",priority:1,configuration:{type:"burn-rate",burnRate:14.4}}]};Object.assign(tc,{examples:[sV]});var nL=r.Pick(jd,["filters","sort","limit","offset"]),oL=r.Object({...nL.properties,...Ze,filters:nL.properties.filters},{description:"SLO query request. Use filters, sorting, limit, and offset to page through visible SLOs."}),cV={filters:{owners:{values:["team-123-abc"]},searchQuery:{value:"availability"},tags:{values:[{key:"team",value:"platform"}]},statuses:{values:["breached"]},clusterIds:{values:["cluster-123-abc"]}},sort:{by:"name",direction:"asc"},limit:10,offset:0};Object.assign(oL,{examples:[cV]});var iL=d({description:"Queries SLOs visible to the authenticated operation key. Use this endpoint to inventory SLO definitions, filter by owner, tag, status, or cluster, and page through results.",operationId:"querySlos",tags:["slos"],url:`${ec}/query`,method:"POST",paginated:!0,body:oL,response:r.Array(tc)}),aL=d({description:"Retrieves one SLO definition by ID.",operationId:"getSlo",tags:["slos"],url:`${ec}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"SLO ID returned by SLO query, create, or update operations."})}),response:tc}),sL=["name","description","tags","configuration","target","timeframeDays","owner","permissions","clusterIds","alerts"],cL=r.Pick(mu,sL,{$id:"CreateSloRequest",description:"SLO creation request. Provide ownership, data access, SLI configuration, target, timeframe, optional cluster scope, and the alerts to create."}),pL=r.Pick(Gd,sL,{$id:"UpdateSloRequest",description:"SLO update request. Send all required SLO fields and the full alert list. Alerts are reconciled to exactly the provided list: alerts with a known id are updated, alerts without an id are created, and existing alerts absent from the list are deleted. Omit `clusterIds` to preserve the current cluster scope; send an empty array to run on all clusters."}),uL={name:"API availability 99.9%",description:"Overall API gateway availability over the last 30 days",tags:[{key:"team",value:"platform"}],configuration:{type:"event",dataSource:"logs",goodQuery:{queries:[{filter:"status:ok",aggregate:{type:"count"}}],formula:"q1"},totalQuery:{queries:[{filter:"*",aggregate:{type:"count"}}],formula:"q1"},noDataBehavior:"good"},target:99.9,timeframeDays:30,owner:"team-123-abc",permissions:"all",clusterIds:[],alerts:[{priority:1,configuration:{type:"burn-rate",burnRate:14.4}}]};Object.assign(cL,{examples:[uL]});Object.assign(pL,{examples:[uL]});var lL=d({description:"Creates an SLO owned by the specified team. The SLO can be event-based (good/total queries) or time-based (a thresholded query over evaluation slices) depending on its configuration.",operationId:"createSlo",tags:["slos"],url:ec,method:"POST",body:cL,response:tc}),mL=d({description:"Replaces an existing SLO definition by ID. Send the full SLO input shape, including configuration, ownership, permissions, cluster scope, and the reconciled alert list. Changing configuration, target, timeframe, permissions, or cluster scope resets evaluated SLO state, so returned status and error budget are based on data evaluated after the update.",operationId:"updateSlo",tags:["slos"],url:`${ec}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the SLO to update. Use the `id` returned by SLO query or create."})}),body:pL,response:tc}),dL=d({description:"Deletes an SLO by ID. Deleting an SLO stops future evaluations and removes its attached alerts.",operationId:"deleteSlo",tags:["slos"],url:`${ec}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the SLO to delete. Use the `id` returned by SLO query or create."})}),response:N});var xo=`${Ws}/tag-policies`;var pV=["logs","metrics","traces"],oh=r.Array(r.Enum(pV,{description:"Telemetry signal covered by a data tag policy."}),{description:"Telemetry signals covered by the policy. An empty array means logs, metrics, and traces."}),uV=r.Union([Mp,oh]),lV=r.Object({teamIds:r.Array(r.String(),{description:"Team IDs used by this policy scope."}),mode:r.Enum(["include","exclude"],{description:"`include` applies the policy only to listed teams. `exclude` applies it to all teams except the listed teams."})},{description:"Team scope that limits where this policy applies. Omitted means the policy applies to all teams."}),mV=C("type",[r.Object({type:r.Literal("telemetry",{description:"Policy applies to telemetry data points during ingestion or evaluation."}),assetTypes:oh,shouldInsertWarning:r.Boolean({description:"When true, Tsuga annotates non-compliant telemetry with tag policy warnings instead of only measuring violations."}),dropSample:r.Optional(r.Number({description:"Percentage of non-compliant telemetry datapoints to drop. Omitted means no sampling drop is configured."}))},{title:"TelemetryTagPolicy"}),r.Object({type:r.Literal("tsuga_asset",{description:"Policy applies to Tsuga-managed resources such as dashboards, routes, and keys."}),assetTypes:Mp},{title:"TsugaAssetTagPolicy"})]),dV=C("type",[r.Object({type:r.Literal("telemetry",{description:"Policy applies to telemetry data points during ingestion or evaluation."}),assetTypes:oh,shouldInsertWarning:r.Boolean({description:"When true, Tsuga annotates non-compliant telemetry with tag policy warnings instead of only measuring violations."}),dropSample:r.Optional(r.Number({minimum:0,maximum:100,description:"Percentage of non-compliant telemetry datapoints to drop. Valid values are 0 through 100."}))},{title:"TelemetryTagPolicy"}),r.Object({type:r.Literal("tsuga_asset",{description:"Policy applies to Tsuga-managed resources such as dashboards, routes, and keys."}),assetTypes:Mp},{title:"TsugaAssetTagPolicy"})]),fL="Policy surface and enforcement behavior. Use `telemetry` for telemetry data or `tsuga_asset` for Tsuga-managed resources.",fV=r.Unsafe({...mV,description:fL}),gV=r.Unsafe({...dV,description:fL}),ea=r.Object({id:r.String({description:"Tsuga-generated tag policy ID assigned when the policy is created."}),name:r.String({description:"Human-readable tag policy name."}),description:r.Optional(r.String({description:"Optional user-provided policy description."})),isActive:r.Boolean({description:"Whether Tsuga currently evaluates this policy. Reserved policies (for example the built-in `env` policy on ingestion API keys) cannot be set to false."}),tagKey:r.String({description:"Tag key enforced by this policy."}),allowedTagValues:r.Array(r.String(),{description:"Allowed values for `tagKey`. An empty array means any value is accepted when the tag exists."}),isRequired:r.Boolean({description:"Whether the tag must be present. If false, `allowedTagValues` is still enforced when the tag exists. Reserved policies cannot be set to false."}),teamScope:r.Optional(lV),configuration:fV,creator:r.Optional(pe),updater:r.Optional(pe),owner:r.Optional(r.String({description:"Team ID that owns and manages the policy."})),createdAt:A({description:"Timestamp when Tsuga created the tag policy."}),updatedAt:A({description:"Timestamp when Tsuga last updated the tag policy."}),assetUpdatedAt:A({description:"Timestamp used for asset-change tracking across Tsuga-managed resources."})});var rc=r.Object({name:u({description:"Human-readable tag policy name."}),description:r.Optional(u({description:"Optional policy description."})),isActive:r.Boolean({description:"Set to true for Tsuga to evaluate this policy. Reserved policies (for example the built-in `env` policy on ingestion API keys) reject a false value."}),tagKey:u({allowEmpty:!1,description:"Tag key enforced by this policy. Tsuga trims surrounding whitespace before storing the policy."}),allowedTagValues:r.Array(u({allowEmpty:!1}),{maxItems:1e3,description:"Allowed values for `tagKey`. Leave empty to allow any value when the tag exists. Tsuga trims each submitted value before storing the policy."}),isRequired:r.Boolean({description:"Set to true to require the tag. If false, allowed values still apply when the tag exists. Reserved policies reject a false value."}),teamScope:r.Optional(r.Object({teamIds:r.Array(u(),{minItems:1,maxItems:100,description:"Team IDs used by this policy scope."}),mode:r.Enum(["include","exclude"],{description:"`include` applies the policy only to listed teams. `exclude` applies it to all teams except the listed teams."})},{description:"Team scope to store for this policy. Omit this field to apply the policy to all teams."})),configuration:gV,owner:u({allowEmpty:!1,description:"Team ID that will own and manage the policy."})}),Fet=d({tags:["tag-policies"],url:xo,method:"GET",query:r.Object({teamIds:r.Optional(r.Array(u(),{maxItems:100})),assetTypes:r.Optional(uV),searchQuery:r.Optional(u())}),response:r.Array(ea)}),Bet=d({tags:["tag-policies"],url:`${xo}/:id`,method:"GET",params:r.Object({id:u()}),response:ea}),Het=d({tags:["tag-policies"],url:xo,method:"POST",body:rc,response:ea}),Ket=d({tags:["tag-policies"],url:`${xo}/:id`,method:"PUT",params:r.Object({id:u()}),body:rc,response:ea}),zet=d({tags:["tag-policies"],url:`${xo}/:id`,method:"DELETE",params:r.Object({id:u()}),response:N}),Yet=d({tags:["tag-policies"],url:`${Ws}/applicable-tag-rules`,method:"GET",query:r.Object({assetType:r.Enum(Ha),teamId:u()}),response:r.Array(r.Object({tagKey:r.String(),allowedTagValues:r.Array(r.String()),isRequired:r.Boolean(),tagPolicyId:r.String()}))}),gL=r.Object({total:r.Number(),totalNonCompliant:r.Number(),idsNonCompliant:r.Array(r.String())}),hL=r.Union([r.Literal("ingestion-api-key"),r.Literal("operation-api-key"),r.Literal("rum-public-token"),r.Literal("dashboard"),r.Literal("log-route"),r.Literal("metric-route"),r.Literal("monitor"),r.Literal("notification-rule"),r.Literal("notification-silence"),r.Literal("slo")]),hV=r.Object({total:r.Number(),totalNonCompliant:r.Number(),byAssetType:r.Record(hL,gL)}),yV=r.Omit(gL,["total"]),TV=r.Object({totalNonCompliant:r.Number(),byAssetType:r.Record(hL,yV)}),yL=r.Object({totals:hV,byTeam:r.Record(r.String(),TV)}),Vet=d({tags:["tag-policies"],url:`${xo}/:id/stats`,method:"GET",params:r.Object({id:u()}),response:yL}),Qet=d({tags:["tag-policies"],url:`${xo}/new-policy-stats`,method:"POST",body:rc,response:yL});var nc=`/${"v1"}/tag-policies`,TL={name:"Required Environment Tag",description:"Requires dashboards and monitors to declare an environment.",isActive:!0,tagKey:"environment",allowedTagValues:["production","staging"],isRequired:!0,teamScope:{teamIds:["team-123-abc"],mode:"include"},configuration:{type:"tsuga_asset",assetTypes:["dashboard","monitor"]},owner:"team-123-abc"},EL={name:"Telemetry Environment Policy",description:"Warns when telemetry is missing a known deployment environment.",isActive:!0,tagKey:"deployment.environment.name",allowedTagValues:["production","staging","development"],isRequired:!0,configuration:{type:"telemetry",assetTypes:[],shouldInsertWarning:!0,dropSample:25},owner:"team-123-abc"},EV={id:"123-456-abc",...TL},_V={id:"456-789-def",...EL},oc=r.Pick(ea,["id","name","description","isActive","tagKey","allowedTagValues","isRequired","teamScope","configuration","owner"],{$id:"TagPolicy",description:"Policy that enforces tag requirements on Tsuga-managed assets or telemetry data. See [Tag policies](/documentation/account-and-settings/tag-policies)."}),IV=EV,bV=_V;Object.assign(oc,{examples:[IV,bV]});var ih=r.Pick(rc,["name","description","isActive","tagKey","allowedTagValues","isRequired","teamScope","configuration","owner"],{description:"Tag policy create or update request. Provide policy identity, owner, enforced tag key, allowed values, team scope, active state, and asset or telemetry configuration."}),SV=TL,AV=EL;Object.assign(ih,{examples:[SV,AV]});var _L=d({description:"Lists tag policies visible to the authenticated operation key. Use this to audit required tags, allowed values, team scope, and whether each policy applies to assets or telemetry.",operationId:"listTagPolicies",tags:["tag-policies"],url:nc,method:"GET",response:r.Array(oc)}),IL=d({description:"Retrieves one tag policy by ID.",operationId:"getTagPolicy",tags:["tag-policies"],url:`${nc}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the tag policy to retrieve. Use the `id` returned by tag policy list or create responses."})}),response:oc}),bL=d({description:"Creates a tag policy for Tsuga-managed assets or telemetry data. Use the configuration type to choose the policy surface.",operationId:"createTagPolicy",tags:["tag-policies"],url:nc,method:"POST",body:ih,response:oc}),SL=d({description:"Replaces an existing tag policy by ID, including scope, requiredness, allowed values, owner, active state, and configuration. Reserved policies (for example the built-in `env` policy on ingestion API keys) reject changes to `tagKey` and reject `isActive: false` or `isRequired: false`.",operationId:"updateTagPolicy",tags:["tag-policies"],url:`${nc}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the tag policy to update. Use the `id` returned by tag policy list, get, or create responses."})}),body:ih,response:oc}),AL=d({description:"Deletes a tag policy by ID. Tsuga stops evaluating the policy after deletion. Reserved policies (for example the built-in `env` policy on ingestion API keys) cannot be deleted.",operationId:"deleteTagPolicy",tags:["tag-policies"],url:`${nc}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the tag policy to delete. Use the `id` returned by tag policy list, create, or update responses."})}),response:N});var ic=`/${"v1"}/teams`,ac=r.Pick(mi,["id","name","description","visibility","tags"],{$id:"Team",description:"Collection of users used to manage ownership, visibility, and access to team-owned Tsuga resources. See [Teams](/documentation/account-and-settings/teams)."}),OV={id:"team-123-abc",name:"platform-engineering",visibility:"public",tags:[{key:"department",value:"engineering"}]};Object.assign(ac,{examples:[OV]});var OL=d({description:"Lists teams visible to the authenticated operation key. Use this endpoint to inventory owners for resources, dashboards, monitors, routes, and policies. Pagination fields limit the returned page.",operationId:"listTeams",tags:["teams"],url:ic,method:"GET",paginated:!0,query:r.Object(Ze),response:r.Array(ac)}),xL=d({description:"Retrieves one team by ID.",operationId:"getTeam",tags:["teams"],url:`${ic}/:id`,method:"GET",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the team to retrieve. Use the `id` returned by team list or create responses."})}),response:ac}),ah=r.Pick(cu,["name","description","visibility","tags"],{description:"Team create or update request. Provide the team name, optional description, visibility, and tags."}),xV={name:"platform-engineering",visibility:"public",tags:[{key:"department",value:"engineering"}]};Object.assign(ah,{examples:[xV]});var RL=d({description:"Creates a team for ownership and access control. Use this before assigning resources to a new owner team. A new team sits outside every existing team, so the operation key must be scoped to all teams: a key scoped to its owning team cannot create teams, even with write access to teams.",operationId:"createTeam",tags:["teams"],url:ic,method:"POST",body:ah,response:ac}),CL=d({description:"Replaces a team definition by ID, including name, description, visibility, and tags.",operationId:"updateTeam",tags:["teams"],url:`${ic}/:id`,method:"PUT",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the team to update. Use the `id` returned by team list, get, or create responses."})}),body:ah,response:ac}),PL=d({description:"Deletes a team. Fails while the team still owns resources (dashboards, monitors, routes, API keys, etc.); reassign or delete those first. Team memberships are removed automatically as part of the deletion.",operationId:"deleteTeam",tags:["teams"],url:`${ic}/:id`,method:"DELETE",params:r.Object({id:u({allowEmpty:!1,description:"Identifier of the team to delete. Use the `id` returned by team list, create, or update responses."})}),response:N});function RV(e){return/^[aeiou]/i.test(e)||e==="SLO"?"an":"a"}function UL(e,t){let n=Number(t);if(Number.isNaN(n))throw new Error(`--${e} must be a number (got: ${t})`);return n}function wL(e){let t={};return e.limit!==void 0&&(t.limit=UL("limit",e.limit)),e.offset!==void 0&&(t.offset=UL("offset",e.offset)),t}function sh(e){let t=e.params;if(t?.properties){let n=Object.keys(t.properties);if(n.length===1&&n[0])return n[0]}return"id"}function vL(e,t,n){let o=e.command(t.commandName).description(t.description),i=t.singularOverride??Cx(t.commandName).replace(/-/g," "),a=t.pluralOverride??t.commandName.replace(/-/g," "),c=RV(i),l=o.command("list").description(t.listDescription??`List all ${a}`);if(t.listOptions)for(let m of t.listOptions)l.option(m.flag,m.description);if(t.endpoints.list.paginated===!0&&l.option("--limit <n>",`Maximum number of items to return, up to ${ni} (default: ${kp})`).option("--offset <n>","Number of items to skip, to request a later page"),t.enableListBody?l.option("-d, --data <JSON>","Inline JSON body").option("--generate-skeleton","Print a JSON skeleton for the request body and exit").action(async m=>{if(m.generateSkeleton){ee(Li(t.endpoints.list));return}let f=m.data?Ii({data:m.data}):{},h=await n()(t.endpoints.list,{body:{...f,...wL(m)}});ee(h)}):l.action(async m=>{let f=wL(m);if(t.listOptions)for(let E of t.listOptions){let I=m[E.queryParam];I!==void 0&&(f[E.queryParam]=I)}let h=await n()(t.endpoints.list,Object.keys(f).length>0?{query:f}:void 0);ee(h)}),t.endpoints.get){let m=t.endpoints.get,f=sh(m);o.command("get <ID>").description(`Get ${c} ${i} by ID`).action(async h=>{let E=await n()(m,{params:{[f]:h}});ee(E)})}if(t.endpoints.create){let m=t.endpoints.create;o.command("create").description(`Create a new ${i}`).option("-f, --file <FILE_PATH>","Read body from file (use - for stdin)").option("-d, --data <JSON>","Inline JSON body").option("--generate-skeleton","Print a JSON skeleton for the request body and exit").action(async f=>{if(f.generateSkeleton){ee(Li(m));return}let h=Ii(f),E=await n()(m,{body:h});ee(E)})}if(t.endpoints.update){let m=t.endpoints.update,f=sh(m);o.command("update <ID>").description(`Update ${c} ${i} by ID`).option("-f, --file <FILE_PATH>","Read body from file (use - for stdin)").option("-d, --data <JSON>","Inline JSON body").option("--generate-skeleton","Print a JSON skeleton for the request body and exit").action(async(h,E)=>{if(E.generateSkeleton){ee(Li(m));return}let I=Ii(E),g=await n()(m,{params:{[f]:h},body:I});ee(g)})}if(t.endpoints.delete){let m=t.endpoints.delete,f=sh(m);o.command("delete <ID>").description(`Delete ${c} ${i} by ID`).action(async h=>{let E=await n()(m,{params:{[f]:h}});ee(E)})}}var CV=[{commandName:"cloud-resources",description:"List cloud resources discovered by inventory scans",endpoints:{list:Gv},enableListBody:!0},{commandName:"dashboard-folders",description:"Manage dashboard folders",endpoints:{list:Hw,get:Kw,create:zw,update:Yw,delete:Vw},enableListBody:!0},{commandName:"dashboards",description:"Manage dashboards",endpoints:{list:hv,get:yv,create:Tv,update:Ev,delete:_v},enableListBody:!0},{commandName:"ingestion-api-keys",description:"Manage ingestion API keys",singularOverride:"ingestion API key",pluralOverride:"ingestion API keys",endpoints:{list:Rv,create:Cv,update:Pv,delete:Uv}},{commandName:"investigations",description:"Manage investigations (beta)",endpoints:{list:jv,get:qv,create:Fv,update:Bv,delete:Hv}},{commandName:"monitors",description:"Manage monitors",endpoints:{list:fN,get:gN,create:SN,update:AN,delete:ON},enableListBody:!0},{commandName:"notification-rules",description:"Manage notification rules",endpoints:{list:RN,get:CN,create:PN,update:UN,delete:wN}},{commandName:"notification-silences",description:"Manage notification silences",endpoints:{list:MN,get:DN,create:GN,update:$N,delete:jN}},{commandName:"quality-reports",description:"Get the latest quality report rows for a cluster",listDescription:"Get the latest quality report rows for a cluster (pass --cluster <CLUSTER_ID> when the org has more than one cluster)",endpoints:{list:YN},listOptions:[{flag:"--team <TEAM_NAME>",description:"Only return rows for this team by name (omits cluster-wide global rows)",queryParam:"team"}]},{commandName:"retention-policies",description:"Manage retention policies",endpoints:{list:XN,get:JN,create:eL,update:tL,delete:rL}},{commandName:"log-routes",description:"Manage log routes",endpoints:{list:nN,get:oN,create:iN,update:aN,delete:sN}},{commandName:"services",description:"List and inspect services (read-only; services are inferred from telemetry)",endpoints:{list:NR,get:LR}},{commandName:"slos",description:"Manage SLOs",singularOverride:"SLO",pluralOverride:"SLOs",endpoints:{list:iL,get:aL,create:lL,update:mL,delete:dL},enableListBody:!0},{commandName:"tag-policies",description:"Manage tag policies",endpoints:{list:_L,get:IL,create:bL,update:SL,delete:AL}},{commandName:"teams",description:"Manage teams",endpoints:{list:OL,get:xL,create:RL,update:CL,delete:PL}}];function NL(e,t){for(let n of CV)vL(e,n,t)}var LL=require("node:child_process");var gl="@tsuga/cli@latest";function PV(){V(`Updating ${gl}`),V(` $ npm install -g ${gl}`);try{(0,LL.execFileSync)("npm",["install","-g",gl],{stdio:["ignore","inherit","inherit"]})}catch(e){let t=e.status??1;throw new Error(`npm install -g ${gl} exited ${t}`,{cause:e})}V("Updated. Run `tsuga --version` to confirm the new version.")}function kL(e){e.command("self-update").description("Update the Tsuga CLI to the latest version via npm").action(()=>{PV()})}var fh=require("node:fs"),dh=require("node:os"),ra=require("node:path");var UV=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,sc=class e extends Date{#t=!1;#r=!1;#e=null;constructor(t){let n=!0,o=!0,i="Z";if(typeof t=="string"){let a=t.match(UV);a?(a[1]||(n=!1,t=`0000-01-01T${t}`),o=!!a[2],o&&t[10]===" "&&(t=t.replace(" ","T")),a[2]&&+a[2]>23?t="":(i=a[3]||null,t=t.toUpperCase(),!i&&o&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=n,this.#r=o,this.#e=i)}isDateTime(){return this.#t&&this.#r}isLocal(){return!this.#t||!this.#r||!this.#e}isDate(){return this.#t&&!this.#r}isTime(){return this.#r&&!this.#t}isValid(){return this.#t||this.#r}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#e===null)return t.slice(0,-1);if(this.#e==="Z")return t;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(t,n="Z"){let o=new e(t);return o.#e=n,o}static wrapAsLocalDateTime(t){let n=new e(t);return n.#e=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#r=!1,n.#e=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#t=!1,n.#e=null,n}};function wV(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function vV(e,t,n){let o=e.split(/\r\n|\n|\r/g),i="",a=(Math.log10(t+1)|0)+1;for(let c=t-1;c<=t+1;c++){let l=o[c-1];l&&(i+=c.toString().padEnd(a," "),i+=": ",i+=l,i+=`
|
|
142
142
|
`,c===t&&(i+=" ".repeat(a+n+2),i+=`^
|
|
@@ -169,10 +169,10 @@ ${c}`:a||c}function mh(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(pc(e)!=="ob
|
|
|
169
169
|
`?o+`
|
|
170
170
|
`:o}var FV={CLAUDE_CODE_ENABLE_TELEMETRY:"1",CLAUDE_CODE_ENHANCED_TELEMETRY_BETA:"1",OTEL_METRICS_EXPORTER:"otlp",OTEL_LOGS_EXPORTER:"otlp",OTEL_TRACES_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"delta"};function BV(e,t,n,o){let i=(0,ra.join)(e,".claude","settings.json");V(`Claude Code \u2192 ${i}`),(0,fh.mkdirSync)((0,ra.dirname)(i),{recursive:!0});let a=As(i),c;try{c=JSON.parse(a??"{}")}catch{throw new Error(`${i} is not valid JSON. Fix or remove it before re-running.`)}if(!Io(c))throw new Error(`${i} must contain a JSON object at the top level.`);let l=c.env??{};if(!Io(l))throw new Error(`${i} "env" must be a JSON object.`);let m=o?"1":"0";c.env={...l,...FV,OTEL_EXPORTER_OTLP_ENDPOINT:t,OTEL_LOG_USER_PROMPTS:m,OTEL_LOG_TOOL_DETAILS:m,OTEL_LOG_TOOL_CONTENT:m,OTEL_EXPORTER_OTLP_HEADERS:`Authorization=Bearer ${n}`};let f=Os(i,a);Ss(i,`${JSON.stringify(c,null,2)}
|
|
171
171
|
`),V(f===void 0?" created":` patched (backup: ${f})`)}function HV(e,t,n){return{environment:"dev",log_user_prompt:n,exporter:{"otlp-http":{endpoint:`${e}/v1/logs`,protocol:"binary",headers:{Authorization:`Bearer ${t}`}}},trace_exporter:{"otlp-http":{endpoint:`${e}/v1/traces`,protocol:"binary",headers:{Authorization:`Bearer ${t}`}}}}}function KV(e,t,n,o){let i=(0,ra.join)(e,".codex"),a=(0,ra.join)(i,"config.toml");V(`Codex \u2192 ${a}`),(0,fh.mkdirSync)(i,{recursive:!0});let c=As(a),l=c===void 0?{}:ch(c),m="otel"in l;delete l.otel,l.otel=HV(t,n,o);let f=Os(a,c);Ss(a,mh(l)),V(f===void 0?" created":m?` replaced existing [otel] tables (backup: ${f})`:` appended (backup: ${f})`)}function FL(){return new Mr("--endpoint <OTLP_ENDPOINT>","OTLP base URL").env("TSUGA_OTLP_ENDPOINT").makeOptionMandatory()}function BL(){return new Mr("--ingestion-api-key <INGESTION_API_KEY>","Tsuga ingestion API key").env("TSUGA_INGESTION_API_KEY").makeOptionMandatory()}var HL="Restart your claude / codex session to load the new config.";function KL(e){let t=e.command("setup").description("Configure local LLM CLIs to ship OTEL telemetry to Tsuga");t.command("claude-code").description("Patch ~/.claude/settings.json with Tsuga OTEL env").addOption(FL()).addOption(BL()).option("--no-include-prompts","Strip user prompts + tool content from telemetry (default: include)").action(n=>{BV((0,dh.homedir)(),n.endpoint.replace(/\/+$/,""),n.ingestionApiKey,n.includePrompts),V(HL)}),t.command("codex").description("Patch ~/.codex/config.toml with Tsuga OTEL settings (replaces any existing [otel] table)").addOption(FL()).addOption(BL()).option("--no-include-prompts","Strip user prompts from telemetry (default: include)").action(n=>{KV((0,dh.homedir)(),n.endpoint.replace(/\/+$/,""),n.ingestionApiKey,n.includePrompts),V(HL)})}var Ro="/v0/logs";var gh=["CRITICAL","ERROR","WARN","NOTICE","INFO","DEBUG","TRACE"];var uc=0,hh=r.Object({__tsuga_metadata__:r.Object({id:r.String(),source:r.Optional(r.String())},{additionalProperties:!0}),context:r.Optional(r.Object({team:r.Optional(r.String({description:"Team name associated with this log."})),tag_policy_warnings:r.Optional(r.Record(r.String(),r.String()))},{additionalProperties:!0,description:"Context attributes attached to the log after ingestion and route processing. `team` comes from telemetry or route-enriched context when present."})),message:r.Optional(r.Unknown({description:"Log message after ingestion and route processing. It can be any JSON value because processors may map arbitrary data into `message`."})),timestamp:r.Number({description:"Log timestamp as a Unix timestamp in milliseconds."}),level:r.Enum(gh,{description:"Log severity, normalized from the source severity into one of the fixed Tsuga levels (ordered `CRITICAL` to `TRACE`)."}),[ex]:r.Optional(r.String({description:"ID of the cluster this log was read from. Only set when the request spanned several clusters."}))},{additionalProperties:!0}),zL=100,zV="timestamp",YV=r.Union([r.Literal(zV)]),Ln=r.Partial(r.Object({...at.properties,query:u({type:"tsuga-query",description:"Tsuga query used to filter logs in the selected time range."}),maxResults:r.Integer({minimum:1,maximum:1e3,description:"Maximum number of logs to return. Valid values are 1 through 1000."}),shouldRecommendAttributes:r.Boolean({description:"Whether Tsuga should return suggested attributes to highlight in results."}),triggeredBy:r.Literal("refresh",{description:"Indicates the query was triggered by a refresh action."}),startOffset:r.Number({minimum:uc,description:"Result offset used when fetching additional log rows."}),startOffsets:r.Array(r.Number({minimum:uc}),{description:`Result offsets used when fetching additional log rows, one per entry of \`clusterIds\` and in the same order. Echo back each cluster's \`nextStartOffset\` from the previous response. Must have the same length as \`clusterIds\`. Defaults to ${uc} for every cluster.`}),clusterId:u({allowEmpty:!1,description:"ID of the cluster to target. Omit to use the default cluster."}),clusterIds:ts,sortBy:YV,sortDirection:r.Union([r.Literal("asc"),r.Literal("desc")],{description:"Timestamp sort direction for log results."})})),_rt=d({tags:["logs"],url:`${Ro}/count`,method:"GET",query:r.Pick(Ln,["from","to","query","clusterId","clusterIds"]),response:r.Object({count:r.Number(),clusterResponses:r.Optional(pi())})}),lc=r.Object({value:r.String(),priority:r.Number()}),Irt=d({tags:["logs"],url:`${Ro}/search`,method:"GET",query:Ln,response:r.Object({logs:r.Optional(r.Array(hh)),attributesToHighlight:r.Optional(r.Array(lc)),clusterResponses:r.Optional(pi(r.Object({nextStartOffset:r.Number({description:"Number of logs consumed on this cluster so far. Echo it back at this cluster's position in `startOffsets` to fetch the next page."})})))},{additionalProperties:!0})}),VV=r.Cyclic({TokenOutput:r.Union([r.Object({type:r.Literal("top"),values:r.Array(r.String())}),r.Object({type:r.Literal("ip"),value:r.String()}),r.Object({type:r.Literal("range"),min:r.Number(),max:r.Number()}),r.Object({type:r.Literal("variable"),value:r.String()}),r.Object({type:r.Literal("text"),value:r.String()}),r.Object({type:r.Literal("date"),value:r.String()}),r.Object({type:r.Literal("url"),value:r.String()}),r.Object({type:r.Literal("structure"),key:r.Array(r.String()),value:r.Array(r.Ref("TokenOutput"))})])},"TokenOutput",{description:"A token identified as part of the pattern"}),QV=r.Object({id:r.String(),pattern:r.Array(VV),size:r.Integer({description:"Number of logs that matched the pattern"}),examples:r.Array(r.Object({id:r.String(),timestampUnix:r.Number()})),timeDistribution:r.Array(r.Number()),staticFeatures:r.Array(r.Object({key:r.String(),value:r.String()},{description:"Fixed groups present in all logs matching the pattern"}))}),brt=d({tags:["logs"],url:`${Ro}/patterns`,method:"GET",query:r.Object({...at.properties,query:u({type:"tsuga-query"}),clusteringThreshold:r.Optional(r.Number()),clusterId:r.Optional(u({allowEmpty:!1}))}),response:r.Object({patterns:r.Array(QV),sampleSize:r.Number()})}),Srt=d({tags:["logs"],url:`${Ro}/attributes`,method:"GET",query:r.Object({...at.properties,clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"})),clusterIds:r.Optional(ts)}),response:r.Object({attributes:r.Array(r.String()),clusterResponses:r.Optional(pi())})});var WV=["pending","running","completed","incomplete","failed"],YL=r.Object({id:r.String({description:"ID of the export."}),status:r.Enum(WV,{description:"Lifecycle of the export. `pending` until the download is claimed, `running` while the CSV streams, then `completed`, `incomplete` when the file is usable but some matched logs could not be reached, or `failed` if the export was interrupted."}),rowsWritten:r.Number({description:"Logs written to the CSV so far. Updated periodically while the download streams, so it lags slightly behind the bytes on the wire."}),totalRows:r.Number({description:"Logs this export will write, already clamped to the export maximum. Use it as the denominator for progress."}),isTruncated:r.Boolean({description:"Whether the query matched more logs than the export maximum, so the CSV holds only the first logs in the requested sort order."}),errorMessage:r.Optional(r.String({description:"Why the export is incomplete or failed."}))}),Art=d({tags:["logs"],url:`${Ro}/exports`,method:"POST",body:r.Object({...r.Pick(Ln,["from","to","query","clusterId","clusterIds","sortBy","sortDirection"]).properties,columns:r.Array(u({allowEmpty:!1}),{minItems:1,description:"Log attributes to write as CSV columns, in order. Each becomes one column, resolved against the log with dotted-path lookup."})}),response:r.Object({...YL.properties,downloadUrl:r.String({description:"Relative URL to fetch the CSV from. It carries a single-use token that expires shortly after creation, so the caller must start the download immediately."})})}),Ort=d({tags:["logs"],url:`${Ro}/exports/:exportId`,method:"GET",params:r.Object({exportId:r.String()}),response:YL}),xrt=d({tags:["logs"],url:`${Ro}/exports/:exportId/download`,method:"GET",params:r.Object({exportId:r.String()}),query:r.Object({token:u({allowEmpty:!1,description:"Single-use token minted when the export was created."})}),response:r.String({description:"CSV file, streamed as it is produced."})});var mc=`/${"v1"}/logs`,yh=r.Object({context:r.Optional(r.Object({team:r.Optional(r.String({description:"Team name associated with this log."}))},{additionalProperties:!0,$id:"LogContext",description:"Context attributes attached to the log after ingestion and route processing. `team` comes from telemetry or route-enriched context when present."})),...r.Pick(hh,["message","timestamp","level"]).properties},{additionalProperties:!0,$id:"LogEvent",description:"Log event including message, timestamp, severity level, and optional enriched context attributes."}),ZV={context:{team:"platform"},message:"Request completed successfully",timestamp:17040672e5,level:"INFO"};Object.assign(yh,{examples:[ZV]});var VL=r.Object({query:r.Optional(u({type:"tsuga-query",default:"*",description:"Tsuga query selecting logs to return. Omit to search all logs with `*`."})),maxResults:r.Optional(r.Integer({minimum:1,maximum:1e3,default:zL,description:"Maximum number of logs to return. Defaults to 100. Valid values are 1 through 1000."})),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."})),...bt.properties},{description:"Log search query. Provide a time range, optional Tsuga query, and optional limit."}),XV={query:"level:ERROR",maxResults:100,from:1704067200,to:1704070800};Object.assign(VL,{examples:[XV]});var QL=d({description:"Searches logs in a required time range using Tsuga query syntax. Use this endpoint to retrieve raw log events for investigations or automation. See [Logs](/documentation/explore/logs) and [Query syntax](/documentation/explore/query-syntax).",operationId:"searchLogs",tags:["public","logs"],url:`${mc}/search`,method:"GET",query:VL,response:r.Object({logs:r.Array(yh,{description:"Log events matching the query and time range."})})}),JV=r.Object({pattern:r.String({description:"Clustered log pattern formatted as a readable string."}),size:r.Integer({description:"Number of logs that matched the pattern"}),groups:r.Array(r.Object({key:r.String({description:"Attribute dot-path shared by all logs in the pattern."}),value:r.String({description:"Value of the attribute identified by `key`, common to all logs in the pattern."})},{description:"Attribute key-value pair that is constant across every log matching this pattern, e.g. a shared `level` or `context.team`."}))}),WL=r.Object({patterns:r.Array(JV,{description:"Log patterns clustered from logs matching the query."}),sampleSize:r.Number({description:"Number of logs sampled while computing patterns."})},{}),e6={patterns:[{pattern:"Resolved segment SegmentId([0:1]) from cache",size:37004,groups:[{key:"level",value:"DEBUG"},{key:"context.team",value:"infra"}]}],sampleSize:100};Object.assign(WL,{examples:[e6]});var ZL=d({description:"Clusters matching logs into readable patterns for the requested time range. Use this to summarize common log shapes before drilling into raw events. See [Logs](/documentation/explore/logs).",operationId:"getLogPatterns",tags:["public","logs"],url:`${mc}/patterns`,method:"GET",query:r.Object({...bt.properties,query:u({type:"tsuga-query",description:"Tsuga query selecting logs to cluster into patterns."}),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))}),response:WL}),t6=r.Object({exampleLog:r.Optional(yh),team:r.String({description:"Team associated with the new error pattern."}),env:r.String({description:"Environment associated with the new error pattern."}),service:r.String({description:"Service associated with the new error pattern."}),firstSeen:r.Number({description:"Unix timestamp in seconds when this pattern was first seen."}),lastSeen:r.Number({description:"Unix timestamp in seconds when this pattern was last seen."})}),XL=r.Object({newErrorPatterns:r.Array(t6,{description:"Error patterns first seen in the requested time range."})},{}),r6={newErrorPatterns:[{team:"platform",env:"production",service:"api-gateway",firstSeen:1704067200,lastSeen:1704153600,exampleLog:{message:"ConnectionError: Failed to connect to database",timestamp:17041536e5,level:"ERROR"}}]};Object.assign(XL,{examples:[r6]});var JL=d({description:"Finds error patterns first seen in the requested time range, optionally filtered by team, environment, or service. Use this to detect newly appearing failures. See [Logs](/documentation/explore/logs).",operationId:"getNewErrorPatterns",tags:["public","logs"],url:`${mc}/patterns/new`,method:"GET",query:r.Object({...bt.properties,team:r.Optional(u({description:"Team name to restrict pattern detection to."})),env:r.Optional(u({description:"Environment to restrict pattern detection to."})),service:r.Optional(u({description:"Service name to restrict pattern detection to."})),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))}),response:XL}),n6=r.Object({team:r.String({description:"Team associated with the error pattern."}),env:r.String({description:"Environment associated with the error pattern."}),pattern:r.String({description:"Error pattern formatted as a readable string."}),increaseTimestamps:r.Array(r.Number({description:"Unix timestamp in milliseconds of a detected spike in occurrence of this pattern. One entry per spike detected in the requested time range."}))}),ek=r.Object({errorPatternIncreases:r.Array(n6,{description:"Error patterns with increased occurrence in the requested time range."})},{}),o6={errorPatternIncreases:[{team:"platform",env:"production",pattern:"Non-resolved segment SegmentId(*) from cache",increaseTimestamps:[17041536e5,17042392e5]}]};Object.assign(ek,{examples:[o6]});var tk=d({description:"Finds error patterns whose occurrence increased for a team in the requested time range. Use this to identify growing failure modes. See [Logs](/documentation/explore/logs).",operationId:"getErrorPatternIncrease",tags:["public","logs"],url:`${mc}/patterns/increase`,method:"GET",query:r.Object({...bt.properties,team:u({description:"Team name to analyze for pattern increases."}),env:r.Optional(u({description:"Environment to restrict the analysis to."})),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))}),response:ek}),rk=r.Object({attributes:r.Array(r.String(),{description:"Log attribute dot-paths observed in the time range"})},{}),i6={attributes:["context.env","context.k8s.pod.name","context.service.name","context.team","level","message","timestamp"]};Object.assign(rk,{examples:[i6]});var a6=r.Object({...bt.properties,clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))},{description:"Log attribute discovery query. Provide a time range and optional cluster ID."}),nk=d({description:"Lists log attribute dot-paths observed in the requested time range. This endpoint requires a public API credential that can read all relevant teams because attribute discovery is not team-filtered. Use this to discover fields for Tsuga queries, filters, and grouping. See [Logs](/documentation/explore/logs).",operationId:"getLogAttributes",tags:["public","logs"],url:`${mc}/attributes`,method:"GET",query:a6,response:rk});var en="/v0/metrics",s6=r.Object({__tsuga_metadata__:r.Object({},{additionalProperties:!0}),context:r.Optional(r.Object({},{additionalProperties:!0})),message:r.Optional(r.String()),timestamp:r.Number(),level:r.Enum(gh)},{additionalProperties:!0}),jrt=d({tags:["metrics"],url:`${en}/count`,method:"GET",query:r.Pick(Ln,["from","to","query","clusterId"]),response:r.Object({count:r.Number()})}),qrt=d({tags:["metrics"],url:`${en}/search`,method:"GET",query:Ln,response:r.Object({logs:r.Optional(r.Array(s6)),totalHits:r.Optional(r.Number()),attributesToHighlight:r.Optional(r.Array(lc))},{additionalProperties:!0})}),El=r.Enum(["counter","gauge","histogram","summary","composite_histogram"],{description:"Metric instrument type, set by the reporting instrumentation. `counter` accumulates a monotonically increasing total (aggregate with `sum` or `increase`); `gauge` reports a point-in-time value that can go up or down (aggregate with `average`, `max`, `min`, or `last`); `histogram`, `composite_histogram`, and `summary` report a distribution of values, from which percentiles can be computed. Tsuga displays `composite_histogram` metrics as Histogram in the app."}),Th=r.Enum(["delta","cumulative","none"],{description:"Metric temporality. `delta` reports changes per collection interval, `cumulative` reports running totals, and `none` means temporality is not applicable or unknown."}),ok=r.Number({description:"Timestamp of the most recent data point recorded for this metric, in milliseconds since the Unix epoch. Omitted when Tsuga has no record of it. Computed from a periodically refreshed metadata snapshot, so it can lag ingestion by a few minutes and should not be used to detect sub-minute gaps."}),c6=r.Object({capabilities:r.Optional(r.Array(r.String(),{description:"Aggregate function types (such as `max`, `min`, `sum`) supported when querying or graphing this metric. If this field is omitted or empty, all aggregate types are supported."})),description:r.Optional(r.String({description:"Human-readable description of the metric"})),tags:r.Optional(r.Array(r.String(),{description:"Attribute names available as dimensions for filtering or grouping this metric. Exposed publicly as `attributes`."})),temporality:r.Optional(Th),type:r.Optional(El),unit:r.Optional(r.String({description:"Metric unit reported by instrumentation or inferred metadata."})),lastSeen:r.Optional(ok)}),Frt=d({url:`${en}/metadata`,method:"GET",query:r.Object({...at.properties,metricName:u({allowEmpty:!1}),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:c6}),Brt=d({tags:["metrics"],url:en,method:"GET",query:r.Object({...at.properties,clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:r.Array(r.String())}),_l=r.Array(r.Object({name:r.String({description:"Metric name observed by Tsuga."}),type:El,lastSeen:r.Optional(ok)}),{description:"Metrics observed in the requested time range, with the instrument type each was reported as."}),p6=[{name:"http.server.request.duration",type:"histogram"},{name:"http.server.active_requests",type:"gauge"},{name:"http.server.request.count",type:"counter"}];Object.assign(_l,{examples:[p6]});var Hrt=d({tags:["metrics"],url:`${en}/names-and-types`,method:"GET",query:r.Object({...at.properties,clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:_l}),dc=r.Array(r.String(),{description:"Attribute names available as dimensions for filtering or grouping the requested metric(s)."}),u6=["service","env","host","method","status_code"];Object.assign(dc,{examples:[u6]});var Krt=d({tags:["metrics"],url:`${en}/attributes`,method:"GET",query:r.Object({...at.properties,metricName:u({allowEmpty:!1}),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:dc}),zrt=d({tags:["metrics"],url:`${en}/attributes/batch`,method:"GET",query:r.Object({...at.properties,metricNames:r.Array(u({allowEmpty:!1}),{minItems:1,description:"Metric names to fetch attributes for"}),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:dc}),Eh=r.Object({assets:r.Array(r.Object({type:r.Enum(["dashboard","monitor"],{description:"Kind of asset referencing the metric."}),id:r.String({description:"Dashboard or monitor ID for the asset that queries this metric."}),name:r.String({description:"Display name of the referencing dashboard or monitor."}),owner:r.String({description:"Team ID that owns the referencing dashboard or monitor."})},{description:"A dashboard or monitor that queries this metric."}),{description:"Dashboards and monitors that currently query this metric."})}),Yrt=d({tags:["metrics"],url:`${en}/assets-usage`,method:"GET",query:r.Object({metricName:u({allowEmpty:!1})}),response:Eh}),Vrt=d({url:`${en}/per-attribute`,method:"GET",query:r.Object({from:r.Optional(r.Number()),to:r.Optional(r.Number()),attribute:u(),clusterId:r.Optional(u({allowEmpty:!1}))}),response:r.Array(r.String())});var _h=`/${"v1"}/metrics`,l6=[{name:"http.server.request.duration",type:"histogram"},{name:"http.server.active_requests",type:"gauge"},{name:"http.server.request.count",type:"counter"}];Object.assign(_l,{examples:[l6]});var Ih=r.Object({name:r.String({description:"Metric name observed by Tsuga. Use this value in metric queries and aggregations."}),type:El,description:r.Optional(r.String({description:"Human-readable description of what the metric measures, set by the reporting instrumentation. Omitted when the instrumentation did not provide one."})),unit:r.Optional(r.String({description:"Metric unit reported by instrumentation or inferred metadata."})),temporality:r.Optional(Th),capabilities:r.Optional(r.Array(r.String(),{description:"Aggregate function types (such as `max`, `min`, `sum`) supported when querying or graphing this metric. An empty or omitted array means all aggregate types are supported."})),attributes:r.Optional(r.Array(r.String(),{description:"Metric attribute names available as dimensions for filtering or grouping."}))}),m6={name:"http.server.request.duration",type:"histogram",description:"Duration of HTTP server requests",unit:"ms",temporality:"delta",capabilities:["max","min","sum"],attributes:["context.team","context.environment","context.region"]};Object.assign(Ih,{examples:[m6]});var ik=r.Object({...bt.properties,clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))},{description:"Metric metadata query. Provide the time range to inspect and optionally a cluster ID."}),ak=d({description:"Lists metrics observed in the requested time range with metadata such as type, unit, temporality, capabilities, and attributes. Use this to discover metric names before querying or graphing them. See [Metrics](/documentation/explore/metrics/index).",operationId:"listMetrics",tags:["public","metrics"],url:_h,method:"GET",query:ik,response:r.Array(Ih)}),sk=d({description:"Retrieves metadata for one metric name in the requested time range. Use this to inspect available dimensions and supported query behavior for a metric. See [Metric details](/documentation/explore/metrics/metric-details).",operationId:"getMetric",tags:["public","metrics"],url:`${_h}/:name`,method:"GET",params:r.Object({name:u({allowEmpty:!1,description:"Metric name to retrieve, for example `http.server.request.duration`."})}),query:ik,response:Ih}),d6=["service","env","host","method","status_code"];Object.assign(dc,{examples:[d6]});var ck=r.Pick(Eh,["assets"]),f6={assets:[{type:"dashboard",id:"dash-123-abc",name:"API Performance Overview",owner:"team-123-abc"},{type:"monitor",id:"mon-789-ghi",name:"High Latency Alert",owner:"team-123-abc"}]};Object.assign(ck,{examples:[f6]});var pk=d({description:"Retrieve dashboards and monitors that use a specific metric",operationId:"getMetricAssetsUsage",tags:["private"],url:`${_h}/assets-usage`,method:"GET",query:r.Object({metricName:u({allowEmpty:!1,description:"The name of the metric to find usage for"})}),response:ck});var na="/v0/traces",cnt=d({tags:["traces"],url:`${na}/count`,method:"GET",query:r.Pick(Ln,["from","to","query","clusterId"]),response:r.Object({count:r.Number()})}),g6=["unset","ok","error"],h6=r.Enum(g6),y6=["unspecified","internal","server","client","producer","consumer"],T6=r.Enum(y6),lk=r.Object({__tsuga_metadata__:r.Optional(r.Object({},{additionalProperties:!0})),context:r.Optional(r.Object({telemetry:r.Optional(r.Object({sdk:r.Optional(r.Object({language:r.Optional(r.String())},{additionalProperties:!0}))},{additionalProperties:!0})),tag_policy_warnings:r.Optional(r.Record(r.String(),r.String())),service:r.Optional(r.Object({name:r.Optional(r.String()),version:r.Optional(r.String())},{additionalProperties:!0})),env:r.Optional(r.String())},{additionalProperties:!0})),parent_span_id:r.Optional(r.String()),resource_attributes:r.Object({},{additionalProperties:!0}),span_attributes:r.Object({},{additionalProperties:!0}),duration:r.Number({description:"In milliseconds."}),duration_ns:r.String({description:"In nanoseconds. Transmitted as a string to avoid losing precision, as BigInt is not JSON-compatible."}),start_time:r.String({description:"In nanoseconds. Transmitted as a string to avoid losing precision, as BigInt is not JSON-compatible."}),end_time:r.String({description:"In nanoseconds. Transmitted as a string to avoid losing precision, as BigInt is not JSON-compatible."}),error:r.Optional(r.Object({message:r.String()})),events:r.Optional(r.Array(r.Object({event_attributes:r.Object({},{additionalProperties:!0}),event_name:r.String(),event_timestamp_nanos:r.String({description:"In nanoseconds. Transmitted as a string to avoid losing precision, as BigInt is not JSON-compatible."})}))),links:r.Optional(r.Array(r.Object({},{additionalProperties:!0}))),span_id:r.String(),span:r.Object({kind:T6,name:r.String()}),status_code:r.Optional(h6),trace_id:r.String()}),mk=100,E6="start_time",_6="duration_ns",I6=r.Union([r.Literal(E6),r.Literal(_6)]),b6={...at.properties,query:r.Optional(u({type:"tsuga-query"})),maxResults:r.Optional(r.Integer({minimum:1,maximum:1e4})),shouldRecommendAttributes:r.Optional(r.Boolean()),startOffset:r.Optional(r.Number({minimum:uc})),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"})),sortBy:r.Optional(I6),sortDirection:r.Optional(r.Union([r.Literal("asc"),r.Literal("desc")]))},pnt=d({tags:["traces"],url:`${na}/search`,method:"GET",query:r.Object(b6),response:r.Object({spans:r.Optional(r.Array(lk)),attributesToHighlight:r.Optional(r.Array(lc))})});var S6=r.Object({groupByAttributes:r.Array(u({allowEmpty:!1}),{description:'Glob patterns of span_attributes keys to use as additional grouping dimensions (e.g. "db.*"). Matches against flattened dotted keys of span_attributes only.'}),minLeafSpansToAggregate:r.Integer({minimum:2,description:"Minimum leaf-group size before aggregation occurs. Default 5."}),maxParentDepth:r.Integer({minimum:-1,description:"Max depth of recursive parent aggregation. 0 = leaves only, -1 = unlimited (default)."}),aggregationHistogramBucketsSeconds:r.Array(r.Number({minimum:0}),{description:"Upper bounds for the latency histogram in seconds. Empty array disables the histogram attributes."}),sortSpans:r.Boolean({description:"Whether to sort the returned spans by start_time (span_id tie-breaker). Set false when the caller reconstructs the trace tree and does not need ordering. Default true."})}),A6=r.Object({...at.properties,traceId:u({allowEmpty:!1,description:"Trace ID to summarize"}),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"})),...r.Partial(S6).properties}),unt=d({tags:["traces"],url:`${na}/summarize`,method:"GET",query:A6,response:r.Object({spans:r.Array(lk)})}),lnt=d({tags:["traces"],url:`${na}/attributes`,method:"GET",query:r.Object({...at.properties,clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:r.Object({attributes:r.Array(r.String())})}),O6=r.Object({key:r.String({description:"Opaque stable key identifying this contributing service within the response. Tsuga assigns it while building the summary; `ranges[].contributions[].serviceKey` and `serviceTotals[].serviceKey` reference this value."}),name:r.String({description:"Observed service name that contributed leaf-span time to the trace. Comes from trace service context and is returned for every contributing service."}),env:r.Optional(r.String({description:"Observed service environment for this contributing service. Comes from trace service context and is absent when the spans do not carry an environment."})),id:r.Optional(r.String({description:"Service catalog ID for this contributing service. Tsuga sets it when exactly one catalog entry matches the observed service and environment; absent when the service is not cataloged or matches ambiguously."})),namespace:r.Optional(r.String({description:"Service namespace from the matched service catalog entry. Returned only when Tsuga can resolve the contributing service to one catalog entry with a namespace."}))}),x6=r.Object({fromNs:r.String({description:"Range start time in nanoseconds since Unix epoch. Tsuga sets it from the trace timeline split where active leaf spans change. Transmitted as a string to avoid losing precision."}),toNs:r.String({description:"Range end time in nanoseconds since Unix epoch. Tsuga sets it from the trace timeline split where active leaf spans change. Transmitted as a string to avoid losing precision."}),durationNs:r.String({description:"Range duration in nanoseconds, computed as `toNs - fromNs`. Transmitted as a string to avoid losing precision."}),contributions:r.Array(r.Object({serviceKey:r.String({description:"Contributing service key for this range. References `services[].key` in the same response."}),weight:r.Number({description:"Share of this range attributed to the service, from `0` through `1`. Tsuga computes the weight from active leaf spans in the range; weights inside one range sum to `1`."}),durationNs:r.String({description:"Estimated duration attributed to this service in the range, computed as `weight` times the range's own `durationNs` and rounded to whole nanoseconds. Use `serviceTotals` as authoritative when rounded range values do not add up exactly."})}),{description:"Services contributing active leaf-span time to this range, with weighted shares for the range duration."}),spanIds:r.Array(r.String(),{description:"Leaf span IDs that produced this range. Tsuga returns IDs from the leaf-only attribution set, including merged sub-ranges after short-range collapsing."})}),R6=r.Object({serviceKey:r.String({description:"Contributing service key for this aggregate total. References `services[].key` in the same response."}),durationNs:r.String({description:"Total wall-clock contribution of this service across the trace, in nanoseconds. Sum of `weight * durationNs` over every range the service contributes to; authoritative when it disagrees with rounded per-range values. Transmitted as a string to avoid losing precision."}),share:r.Number({description:"Share of total trace duration attributed to this service, from `0` through `1`. Computed as `durationNs / totalDurationNs`; multiply by 100 for a percentage."})}),bh=r.Optional(r.Number({minimum:0,description:"Minimum range duration in milliseconds. Shorter ranges are collapsed (absorbed into a neighbor or blended with adjacent shorts) to keep the timeline readable. When omitted, the default depends on the trace: max(1ms, 1% of the total trace duration), so e.g. a 10s trace collapses ranges shorter than 100ms. Pass 0 to disable collapsing."})),Sh=r.Optional(r.Boolean({default:!0,description:"When false, omits the per-range timeline (returns `ranges: []`) and returns only `services` and `serviceTotals`. Cuts payload size for callers that only need the headline. Defaults to true."})),Il=r.Object({traceId:r.String({description:"Trace ID summarized by the response. Echoes the required `traceId` query parameter."}),startTimeNs:r.String({description:"Earliest `start_time` across fetched spans, in nanoseconds since Unix epoch. If the request window does not cover the full trace, this reflects the fetched subset, not necessarily the trace's true start. Transmitted as a string to avoid losing precision."}),endTimeNs:r.String({description:"Latest `end_time` across fetched spans, in nanoseconds since Unix epoch. If the request window does not cover the full trace, this reflects the fetched subset, not necessarily the trace's true end. Transmitted as a string to avoid losing precision."}),totalDurationNs:r.String({description:"Total fetched trace duration in nanoseconds, computed as `endTimeNs - startTimeNs`. Transmitted as a string to avoid losing precision."}),truncated:r.Boolean({description:"Whether the underlying span fetch hit its result cap. When true, the latency summary may be incomplete because not every span in the trace was available."}),services:r.Array(O6,{description:"Unique services that contributed leaf-span time to the trace, enriched with catalog IDs when Tsuga can resolve them. Referenced by `serviceKey` from `ranges` and `serviceTotals`."}),ranges:r.Array(x6,{description:"Sequential trace timeline split into ranges wherever the active leaf-span set changes. Empty when the request sets `includeRanges` to false."}),serviceTotals:r.Array(R6,{description:"Aggregated wall-clock contribution per service across the fetched trace. Use this for service-level latency ownership without processing the per-range timeline."})}),C6={traceId:"78c99c5bb1e4a30297fa134b9dbec64f",startTimeNs:"1704067200000000000",endTimeNs:"1704067202400000000",totalDurationNs:"2400000000",truncated:!1,services:[{key:"checkout|prod",name:"checkout",env:"prod",id:"123-456-abc",namespace:"default"},{key:"payments|prod",name:"payments",env:"prod",id:"456-789-def",namespace:"default"}],ranges:[{fromNs:"1704067200000000000",toNs:"1704067201200000000",durationNs:"1200000000",contributions:[{serviceKey:"checkout|prod",weight:1,durationNs:"1200000000"}],spanIds:["3df8cc3449378f66"]},{fromNs:"1704067201200000000",toNs:"1704067202400000000",durationNs:"1200000000",contributions:[{serviceKey:"checkout|prod",weight:.5,durationNs:"600000000"},{serviceKey:"payments|prod",weight:.5,durationNs:"600000000"}],spanIds:["187a47da1b2560f8","3df8cc3449378f66"]}],serviceTotals:[{serviceKey:"checkout|prod",durationNs:"1800000000",share:.75},{serviceKey:"payments|prod",durationNs:"600000000",share:.25}]};Object.assign(Il,{examples:[C6]});var mnt=d({tags:["traces"],url:`${na}/latency-summary`,method:"GET",query:r.Object({...at.properties,traceId:u({allowEmpty:!1,description:"Trace ID to summarize"}),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"})),minRangeDurationMs:bh,includeRanges:Sh}),response:Il}),uk=r.Object({filter:u({type:"tsuga-query",description:"TQL filter defining the group"}),timeRange:ui}),P6=r.Object({value:r.String(),supportA:r.Number(),supportB:r.Number()}),U6=r.Object({value:r.String(),supportA:r.Number(),supportB:r.Number(),lift:r.Union([r.Number(),r.Null()]),pValue:r.Number()}),w6=r.Object({attr:r.String(),values:r.Array(U6),otherValues:r.Array(P6)}),dnt=d({tags:["traces"],url:`${na}/contrast-sets`,method:"POST",body:r.Object({groupA:uk,groupB:uk,candidateAttrs:r.Optional(r.Array(u({allowEmpty:!1}))),topK:r.Optional(r.Integer({minimum:1,maximum:100})),minLift:r.Optional(r.Number({minimum:1})),minSupport:r.Optional(r.Number({minimum:0,maximum:100})),clusterId:r.Optional(u({allowEmpty:!1,description:"Cluster ID"}))}),response:r.Object({contrastSets:r.Array(w6),groupACount:r.Number(),groupBCount:r.Number()})});var Ah=`/${"v1"}/traces`,Oh=r.Object({context:r.Optional(r.Object({service:r.Optional(r.Object({name:r.Optional(r.String({description:"Service name associated with the span."})),version:r.Optional(r.String({description:"Service version associated with the span."}))},{additionalProperties:!0,description:"Service identity associated with the span, from OpenTelemetry service resource attributes."}))},{additionalProperties:!0,description:"OpenTelemetry resource context resolved for the span, holding the identity of the emitting service."})),parentSpanId:r.Optional(r.String({description:"`spanId` of this span's parent within the same trace. Absent for the root span."})),resourceAttributes:r.Object({},{additionalProperties:!0,description:"OpenTelemetry resource attributes describing the process/host that emitted the span (e.g. `host.name`, `k8s.pod.name`), as a flat key-value map set by the instrumented service or its SDK."}),spanAttributes:r.Object({},{additionalProperties:!0,description:"OpenTelemetry span attributes describing this operation (e.g. HTTP method, DB statement), as a flat key-value map set by the instrumented code or auto-instrumentation."}),duration:r.Number({description:"Span duration in milliseconds, derived from the nanosecond `startTime` and `endTime` values."}),startTime:r.String({description:"Span start time as a Unix epoch timestamp in nanoseconds, encoded as a string to preserve precision."}),endTime:r.String({description:"Span end time as a Unix epoch timestamp in nanoseconds, encoded as a string to preserve precision."}),error:r.Optional(r.Object({message:r.String({description:"Error message associated with the span."})},{description:"Error details associated with the span, separate from the OpenTelemetry `statusCode` field."})),events:r.Optional(r.Array(r.Object({event_attributes:r.Object({},{additionalProperties:!0,description:"Key-value attributes recorded with this event, set by the instrumented code when the event was added to the span (e.g. exception details)."}),event_name:r.String({description:"Name of the span event."}),event_timestamp_nanos:r.String({description:"Event timestamp in nanoseconds, transmitted as a string for precision."})},{description:"A single timestamped event recorded on the span, with its name and attributes."}),{description:"Events recorded on the span."})),spanId:r.String({description:"Unique span ID within the trace."}),span:r.Object({kind:r.String({description:"OpenTelemetry span kind describing the relationship to remote calls: `unspecified`, `internal`, `server`, `client`, `producer`, or `consumer`."}),name:r.String({description:"Operation name recorded on the span."})},{description:"Operation identity for the span, combining the recorded operation name and the OpenTelemetry span kind."}),statusCode:r.Optional(r.String({description:"OpenTelemetry span status set by the instrumented code: `unset` (default, no explicit status), `ok`, or `error`. Absent if the source span never set a status."})),traceId:r.String({description:"Trace ID shared by all spans in the trace."})},{additionalProperties:!0,$id:"SpanEvent",description:"Distributed tracing span including timing, identifiers, OpenTelemetry attributes, events, and status metadata."}),v6={context:{service:{name:"my-service",version:"1.0.0"}},parentSpanId:"187a47da1b2560f8",resourceAttributes:{},spanAttributes:{busyNs:374640,code:{file:{path:"src/queue/sqs.rs"},line:{number:162},module:{name:"queue::sqs"}},idleNs:23621445,maxMessages:"1",target:"queue::sqs",thread:{id:2,name:"tokio-runtime-worker"}},duration:23,startTime:"1770923469995353600",endTime:"1770923470019349500",spanId:"3df8cc3449378f66",span:{kind:"internal",name:"receive_messages"},statusCode:"ok",traceId:"78c99c5bb1e4a30297fa134b9dbec64f"};Object.assign(Oh,{examples:[v6]});var N6={from:1704067200,to:1704070800,query:"context.service.name:my-service",maxResults:100},dk=r.Object({...bt.properties,query:r.Optional(u({type:"tsuga-query",default:"*",description:"Tsuga query selecting spans to return. Omit to search all spans in the range with `*`."})),maxResults:r.Optional(r.Integer({minimum:1,maximum:1e4,default:mk,description:"Maximum number of spans to return. Defaults to 100. Valid values are 1 through 10000."})),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."}))},{description:"Span search query. Provide a time range, optional Tsuga query, and optional limit."});Object.assign(dk,{examples:[N6]});var fk=d({description:"Searches spans in a required time range using Tsuga query syntax. Use this endpoint to retrieve trace spans for investigations or automation. See [Traces](/documentation/explore/traces) and [Query syntax](/documentation/explore/query-syntax).",operationId:"searchSpans",tags:["public","traces"],url:`${Ah}/search`,method:"GET",query:dk,response:r.Object({spans:r.Array(Oh,{description:"Spans matching the query and time range."})})}),L6={from:1704067200,to:1704070800,traceId:"78c99c5bb1e4a30297fa134b9dbec64f"},gk=r.Object({...bt.properties,traceId:u({allowEmpty:!1,description:"Trace ID to summarize. Use the `traceId` returned by span search, the trace details page, or your tracing instrumentation. Required; the requested time range must include the trace."}),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."})),groupByAttributes:r.Optional(r.Array(u({allowEmpty:!1}),{description:"Glob patterns of span attribute keys to use as additional grouping dimensions. Use this when spans should be summarized separately for matching attributes, such as `db.*`. Matches flattened dotted span attribute keys; omitted by default."})),minLeafSpansToAggregate:r.Optional(r.Integer({minimum:2,default:5,description:"Minimum number of similar leaf spans in a group before Tsuga replaces them with one synthetic summary span. Use higher values for less aggressive summarization. Optional; defaults to 5 and must be at least 2."})),maxParentDepth:r.Optional(r.Integer({minimum:-1,default:-1,description:"Maximum depth of recursive parent aggregation after leaf spans are summarized. Use this to limit parent-level aggregation. Use `0` to aggregate leaf spans only or `-1` for unlimited depth; defaults to `-1`."})),aggregationHistogramBucketsSeconds:r.Optional(r.Array(r.Number({minimum:0}),{description:"Upper-bound bucket values, in seconds, for the latency histogram recorded on synthetic summary spans. Provide custom buckets when the default latency buckets are not suitable. Pass an empty array to omit histogram attributes; omitted values use Tsuga defaults from 5 ms through 10 s."})),sortSpans:r.Optional(r.Boolean({default:!0,description:"Whether Tsuga sorts returned spans by start time, using span ID as the tie-breaker for identical start times. Defaults to `true`; set to `false` only when reconstructing the trace tree yourself, in which case summary spans are appended after surviving spans."}))},{description:"Trace summarization query. Provide a trace ID, a time range covering the trace, and optional aggregation tuning."});Object.assign(gk,{examples:[L6]});var hk=d({description:"Summarizes a trace by aggregating groups of similar spans into synthetic summary spans, producing a compact view of large traces. Summary spans are marked with `spanAttributes.aggregation.is_summary` and carry span counts, duration statistics, and an optional latency histogram. See [Traces](/documentation/explore/traces).",operationId:"summarizeTrace",tags:["public","traces"],url:`${Ah}/summarize`,method:"GET",query:gk,response:r.Object({spans:r.Array(Oh,{description:"Summarized trace spans, sorted by start time unless `sortSpans` is false. Aggregated groups are replaced by synthetic summary spans marked with `spanAttributes.aggregation.is_summary`."})})}),k6={from:1704067200,to:1704070800,traceId:"78c99c5bb1e4a30297fa134b9dbec64f"},yk=r.Object({...bt.properties,traceId:u({allowEmpty:!1,description:"Trace ID to summarize. Use the `traceId` returned by span search, the trace details page, or your tracing instrumentation. Required; the requested time range must include the trace."}),clusterId:r.Optional(u({allowEmpty:!1,description:"Telemetry cluster to target. Required when the organization has multiple clusters; omit only for single-cluster organizations."})),minRangeDurationMs:bh,includeRanges:Sh},{description:"Trace latency summary query. Provide a trace ID, a time range covering the trace, and optional timeline tuning."});Object.assign(yk,{examples:[k6]});var Tk=d({description:"Summarizes where wall-clock time is spent in a trace, attributing each slice of the trace timeline to the services with active leaf spans. Returns per-service totals and an optional sequential range timeline. See [Traces](/documentation/explore/traces).",operationId:"getTraceLatencySummary",tags:["public","traces"],url:`${Ah}/latency-summary`,method:"GET",query:yk,response:Il});var Ik=["timestamp","level","message"],bk=["count","ratio","team","level","pattern"];function gt(e,t){let n=t??jr(e);if(!n)throw new Error(`--${e} is required`);return Ic(n)}function Ek(e){let t={from:gt("from",e.from),to:gt("to",e.to)},n=e.query??jr("query");n!==void 0&&(t.query=n);let o=e.maxResults??jr("max-results");if(o!==void 0){let i=Number(o);if(Number.isNaN(i))throw new Error(`--max-results must be a number (got: ${o})`);t.maxResults=i}return t}function Ne(e){let t=jr(e);return t===void 0?"":` (default: ${t})`}function M6(e){let t=Qm(e.output),n=e.fields===void 0?void 0:Wm(e.fields);return t==="json"?{format:t,fields:n}:{format:t,fields:n??Ik}}function D6(e){let t=Qm(e.output),n=e.fields===void 0?void 0:Wm(e.fields);return t==="json"?{format:t,fields:n}:{format:t,fields:n??bk}}function _k(e,t){let n={count:e.size,ratio:t>0?e.size/t:0,pattern:e.pattern};for(let{key:o,value:i}of e.groups)o==="context.team"?n.team=i:n[o]=i;return n}function G6(e,t){if(t.format==="json"){if(t.fields===void 0){ee(e);return}let{fields:i}=t;ee({patterns:e.patterns.map(a=>_k(a,e.sampleSize)).map(a=>Zm(a,i)),sampleSize:e.sampleSize});return}let n=e.patterns.map(i=>_k(i,e.sampleSize)),o=Xm(t.format,n,t.fields);o.length>0&&V(o)}function $6(e,t){if(t.format==="json"){if(t.fields===void 0){ee(e);return}let{fields:o}=t;ee({logs:e.logs.map(i=>Zm(i,o))});return}let n=Xm(t.format,e.logs,t.fields);n.length>0&&V(n)}function Sk(e,t){let n=e.command("logs").description("Search and analyze logs");n.command("search").description("Search logs").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).option("--query <TSUGA_QUERY>",`Tsuga query to filter logs${Ne("query")}`).option("--max-results <COUNT>",`Maximum number of results, 1-1000${Ne("max-results")}`).option("--fields <FIELDS>",`Comma-separated dot-paths to project from each log (default for --output=tsv|csv: ${Ik.join(",")})`).option("-o, --output <FORMAT>","Output format: json | tsv | csv","json").action(async c=>{let l=M6(c),m=await t()(QL,{query:Ek(c)});$6(m,l)}),n.command("attributes").description("List log attribute dot-paths observed in the time range").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).action(async c=>{let l=await t()(nk,{query:{from:gt("from",c.from),to:gt("to",c.to)}});ee(l)}),n.command("patterns").description("List log patterns").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).option("--query <TSUGA_QUERY>",`Tsuga query to filter logs before clustering into patterns${Ne("query")}`).option("--fields <FIELDS>",`Comma-separated dot-paths to project from each pattern (default for --output=tsv|csv: ${bk.join(",")})`).option("-o, --output <FORMAT>","Output format: json | tsv | csv","json").action(async c=>{let l=D6(c),m={from:gt("from",c.from),to:gt("to",c.to)},f=c.query??jr("query");f!==void 0&&(m.query=f);let h=await t()(ZL,{query:m});G6(h,l)}),n.command("new-error-patterns").description("List error patterns first seen in this time range").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).option("--team <TEAM_NAME>","Filter by team").option("--env <ENV_NAME>","Filter by environment").option("--service <SERVICE_NAME>","Filter by service").action(async c=>{let l={from:gt("from",c.from),to:gt("to",c.to)};c.team!==void 0&&(l.team=c.team),c.env!==void 0&&(l.env=c.env),c.service!==void 0&&(l.service=c.service);let m=await t()(JL,{query:l});ee(m)}),n.command("error-pattern-increases").description("List error pattern increases for a given team").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).requiredOption("--team <TEAM_NAME>","Team to query").option("--env <ENV_NAME>","Filter by environment").action(async c=>{let l={from:gt("from",c.from),to:gt("to",c.to),team:c.team};c.env!==void 0&&(l.env=c.env);let m=await t()(tk,{query:l});ee(m)});let o=e.command("metrics").description("List and inspect metrics");o.command("list").description("List all metrics with their metadata").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).action(async c=>{let l=await t()(ak,{query:{from:gt("from",c.from),to:gt("to",c.to)}});ee(l)}),o.command("get <METRIC_NAME>").description("Retrieve a metric by name with its metadata").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).action(async(c,l)=>{let m=await t()(sk,{params:{name:c},query:{from:gt("from",l.from),to:gt("to",l.to)}});ee(m)}),o.command("assets-usage <METRIC_NAME>").description("List dashboards and monitors that use a specific metric").action(async c=>{let l=await t()(pk,{query:{metricName:c}});ee(l)});let i=e.command("traces").description("Search and summarize traces");i.command("search").description("Search spans").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).option("--query <TSUGA_QUERY>",`Tsuga query to filter spans${Ne("query")}`).option("--max-results <COUNT>",`Maximum number of results, 1-10000${Ne("max-results")}`).action(async c=>{let l=await t()(fk,{query:Ek(c)});ee(l)}),i.command("summarize").description("Summarize a trace by aggregating groups of similar spans into summary spans").requiredOption("--trace-id <TRACE_ID>","Trace ID to summarize").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).action(async c=>{let l=await t()(hk,{query:{traceId:c.traceId,from:gt("from",c.from),to:gt("to",c.to)}});ee(l)}),i.command("latency-summary").description("Summarize where wall-clock time is spent in a trace, attributed per service").requiredOption("--trace-id <TRACE_ID>","Trace ID to summarize").option("--from <TIMESTAMP>",`Start of time range${Ge}${Ne("from")}`).option("--to <TIMESTAMP>",`End of time range${Ge}${Ne("to")}`).option("--min-range-duration-ms <MILLISECONDS>","Collapse timeline ranges shorter than this (default: max(1ms, 1% of trace duration); 0 disables collapsing)").option("--no-ranges","Omit the per-range timeline; return only services and serviceTotals").action(async c=>{let l={traceId:c.traceId,from:gt("from",c.from),to:gt("to",c.to)};if(c.minRangeDurationMs!==void 0){let f=Number(c.minRangeDurationMs);if(Number.isNaN(f))throw new Error(`--min-range-duration-ms must be a number (got: ${c.minRangeDurationMs})`);l.minRangeDurationMs=f}c.ranges||(l.includeRanges=!1);let m=await t()(Tk,{query:l});ee(m)});let a=e.command("aggregation").description("Run aggregation queries");Zr(a,"scalar","Run aggregation queries and return scalar results",Mw,t),Zr(a,"timeseries","Run aggregation queries and return timeseries results",Gw,t)}var j6="x-tsuga-session-id",xh="x-tsuga-source",Rh="x-tsuga-source-version",Ch="x-tsuga-source-commit",Ph="x-tsuga-source-date",Uh="x-tsuga-rationale",q6="x-tsuga-dashboard-id",F6="x-tsuga-widget-id",B6="x-request-id",vnt={[j6]:"Session identifier for request correlation",[xh]:"SDK or client source identifier (e.g., web-frontend, terraform-provider)",[Rh]:"SDK version",[Ch]:"SDK commit hash",[Ph]:"SDK commit date",[Uh]:"Optional caller-supplied rationale for this request, recorded for telemetry",[q6]:"ID of the dashboard a query is issued from, when the request originates from a dashboard widget",[F6]:"ID of the dashboard widget (graph) a query is issued from, when the request originates from a dashboard widget",[B6]:"Unique identifier for this API request, useful for debugging and support"};var kn=class e extends Error{constructor(n,o,i,a,c){super(n);this.statusCode=o;this.code=i;this.requestId=a;this.details=c;this.name="CliError"}static fromErrorResponse(n,o){return new e(n.message,n.statusCode,n.code,o,n.details)}};function Ak(e){if(e instanceof kn){let t=[`Error: ${e.message}`];return e.code&&t.push(`Code: ${e.code}`),e.statusCode&&t.push(`Status: ${e.statusCode}`),e.requestId&&t.push(`Request ID: ${e.requestId}`),e.details&&t.push(`Details: ${JSON.stringify(e.details,null,2)}`),t.join(`
|
|
172
|
-
`)}return e instanceof Error?`Error: ${e.message}`:String(e)}function H6(e){return e.replace(/\s+/g," ").replace(/[^\x20-\x7e\x80-\xff]/g,"").trim()}function Ok(e,t,n,o){return async function(a,c={}){let{body:l,params:m,query:f}=c,h;if(a.url!==void 0)h=a.url;else if(a.buildUrl){if(!m)throw new kn("Internal error: params required for this endpoint");h=a.buildUrl(m)}else throw new kn("Internal error: endpoint has neither url nor buildUrl");let E=n===void 0?f:{clusterId:n,...f},I=rO(`${e}${h}`,E),g={Accept:"application/json",Authorization:`Bearer ${t}`,[xh]:"cli",[Rh]:"1.
|
|
172
|
+
`)}return e instanceof Error?`Error: ${e.message}`:String(e)}function H6(e){return e.replace(/\s+/g," ").replace(/[^\x20-\x7e\x80-\xff]/g,"").trim()}function Ok(e,t,n,o){return async function(a,c={}){let{body:l,params:m,query:f}=c,h;if(a.url!==void 0)h=a.url;else if(a.buildUrl){if(!m)throw new kn("Internal error: params required for this endpoint");h=a.buildUrl(m)}else throw new kn("Internal error: endpoint has neither url nor buildUrl");let E=n===void 0?f:{clusterId:n,...f},I=rO(`${e}${h}`,E),g={Accept:"application/json",Authorization:`Bearer ${t}`,[xh]:"cli",[Rh]:"1.24.0",[Ch]:"eb66f96d6",[Ph]:"2026-08-28T17:04:16.448Z"};l&&(g["Content-Type"]="application/json");let T=o?.(),S=T?H6(T):"";S&&(g[Uh]=S);let b=await fetch(I,{method:a.method,headers:g,body:l?JSON.stringify(l):null}),x;try{x=await b.json()}catch{throw new kn(b.status===504?"The server timed out (504). Try a smaller time range.":`Server returned a non-JSON response (HTTP ${b.status}).`,b.status)}if(x.error)throw kn.fromErrorResponse(x.error,x.requestId);return z6(x,K6(c)),x.data}}function K6({body:e,query:t}){let n=t?.offset??e?.offset;return typeof n=="number"?n:0}function z6(e,t){let n=e.metadata?.pagination;if(n===void 0||!Array.isArray(e.data))return;let o=t+e.data.length;o>=n.totalCount||fO(`Showing ${e.data.length} of ${n.totalCount} (offset ${t}). Use --limit (max ${ni}) and --offset ${o} for the next page.`)}function wh(e,t=n=>{process.exit(n)}){e.on("error",n=>{if(n.code==="EPIPE"){t(process.exitCode);return}throw n})}var Y6=3e3,V6="https://registry.npmjs.org/@tsuga/cli/latest";function Q6(e,t){let n=e.split(".").map(Number),o=t.split(".").map(Number);for(let i=0;i<Math.max(n.length,o.length);i++){let a=n[i]??0,c=o[i]??0;if(a>c)return!0;if(a<c)return!1}return!1}async function xk(e){try{let t=qO();if(t&&Date.now()-new Date(t).getTime()<_c)return;let n=await fetch(V6,{signal:AbortSignal.timeout(Y6)});if(!n.ok)return;let i=(await n.json()).version;Q6(i,e)&&(process.stderr.write(`
|
|
173
173
|
Update available: ${e} \u2192 ${i}
|
|
174
|
-
`),process.stderr.write("Run `tsuga self-update` to update\n")),FO(new Date().toISOString())}catch{}}wh(process.stdout);wh(process.stderr);var Re=new Co().name("tsuga").description("Manage Tsuga resources, telemetry, and configuration from the command line").version("1.
|
|
175
|
-
`).configureHelp({sortSubcommands:!0}).helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").option("--
|
|
174
|
+
`),process.stderr.write("Run `tsuga self-update` to update\n")),FO(new Date().toISOString())}catch{}}wh(process.stdout);wh(process.stderr);var Re=new Co().name("tsuga").description("Manage Tsuga resources, telemetry, and configuration from the command line").version("1.24.0").addHelpText("before",()=>`${lO()}
|
|
175
|
+
`).configureHelp({sortSubcommands:!0}).helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").option("--cluster <CLUSTER_ID>","Target cluster (overrides config and TSUGA_CLUSTER_ID)"),oa,Rk;function Nr(){if(oa)return oa;let e=Re.opts(),t=ai({clusterId:e.cluster}),n=vO(t);n||(console.error("Error: no credentials. Authenticate with one of:"),console.error(" tsuga auth login # log in as a user (OAuth)"),console.error(" tsuga auth operation-key <OPERATION_API_KEY> # save an operation API key"),console.error(" export TSUGA_OPERATION_API_KEY=<OPERATION_API_KEY>"),process.exit(1));let o=l=>Ok(t.apiUrl,l,t.clusterId,()=>Rk),{credential:i}=t;if(i?.kind!=="user-session")return oa=o(n),oa;let a=i.userAuth,c=o(a.accessToken);return oa=async(l,m)=>{let f=await jp({userAuth:a,now:new Date,reload:Ja,refresh:h=>$p(t.apiUrl,h),persist:Kp});return f!==a&&(a=f,c=o(a.accessToken)),c(l,m)},oa}var Ck="Setup & config:",Pk="Documentation, help & feedback:";Re.commandsGroup(Ck);HO(Re);Gx(Re);var W6=new Set(Re.commands);Re.commandsGroup("Resources:");NL(Re,Nr);Re.commandsGroup("Query & explore:");Sk(Re,Nr);DR(Re,Nr);HU(Re,Nr);WU(Re,Nr);Pw(Re,Nr);jw(Re,Nr);Re.commandsGroup(Pk);Hx(Re,Nr);Vx(Re,Nr);Re.commandsGroup(Ck);Lx(Re,Nr);KL(Re);VU(Re);kL(Re);Dx(Re);Re.commandsGroup(Pk).helpCommand("help [command]");function Uk(e){if(e.commands.length===0){e.option("--rationale <RATIONALE>",'Why you are making this call, e.g. "confirming the deploy caused the error spike". Recorded to explain intent; does not affect the result.');return}for(let t of e.commands)Uk(t)}var Z6=new Set(["completion","self-update","install","setup","feedback"]);for(let e of Re.commands)!W6.has(e)&&!Z6.has(e.name())&&Uk(e);Re.hook("preAction",(e,t)=>{let{rationale:n}=t.opts();Rk=n});Re.parseAsync().then(()=>xk("1.24.0")).catch(e=>{console.error(Ak(e)),process.exitCode=1});
|
|
176
176
|
/**
|
|
177
177
|
* The following is a list of HTTP status codes and their meanings.
|
|
178
178
|
*
|